mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
P14 S2 fix²: close-safe delivery, catch-up ordering, pointer-form bypass
Addresses five architect findings across two review rounds, all on
the authority package introduced in 5c663b8. The core S2 boundary
(Publisher is the sole minter, identity keyed by (VolumeID,
ReplicaID), Directive is the only policy seam) stays unchanged;
this commit tightens correctness of delivery and the strength of
the non-forgeability proof.
1. Close-safe delivery (High). apply()'s fan-out ran outside
pub.mu and could race with cancel()/Run-exit closing the same
channel. The former deliverLatest free function was not
close-aware — a concurrent close would produce send-on-closed
panics, and its drain-retry loop on a closed channel (where
receive is permanently ready with zero value) would spin
forever.
Fix: subscription now owns a sync.Mutex + closed flag. New
methods subscription.deliver() and subscription.close() both
acquire s.mu; deliver() returns early if closed, and close()
is idempotent. The deliverLatest free function is gone;
apply() calls s.deliver(next). cancelSubscription and
closeAllSubscriptions call target.close() instead of closing
target.ch directly.
Regression: TestPublisher_CancelDuringDeliveryDoesNotPanic
stress-runs 50 concurrent subscribe/cancel goroutines against
200 concurrent Refresh asks on the same (vid, rid). Asserts no
panic and no hang within 5 s.
2. Catch-up ordering race (High). Subscribe() registered the new
subscriber in p.subs under pub.mu, then released the lock and
did a blocking sub.ch <- st.info. A concurrent apply() could
deliver a newer fact first; the delayed catch-up would then
enqueue the older fact, producing stale/out-of-order delivery
on a route that must converge to current authority truth.
Fix: the catch-up send now happens INSIDE the pub.mu critical
section, immediately after the subs-map insert. Because sub.ch
is cap=1 and the fresh subscription is invisible to any other
goroutine until pub.mu is released, the catch-up send is
guaranteed non-blocking. Any later apply() either runs before
us (catch-up state IS current) or sees us in the subs map and
drains our stale catch-up via deliver(). Strict ordering.
Regression:
TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish
runs 200 iterations of (concurrent Reassign + fresh Subscribe +
drain); asserts drained epoch <= current authoritative epoch
every iteration.
3. AST non-forgeability proof gap — deferred-mutation bypass
(Medium). The earlier AST walker explicitly skipped short
declarations (x := adapter.AssignmentInfo{}), so the pattern
x := adapter.AssignmentInfo{}
x.Epoch = userInput
bypassed both checks: the literal is zero-valued so check (a)
did not trigger, and the short-decl path was ignored in (b).
Fix: auditNonForgeability now handles the AssignStmt branch
with Tok == token.DEFINE; any RHS that is a composite literal
of AssignmentInfo type is flagged as the deferred-mutation
bypass shape, regardless of field values. Also added the
long-decl-with-value case: var x = adapter.AssignmentInfo{}.
Regression (two synthetic-source tests that exercise the audit
function directly):
- TestNonForgeability_CatchesShortDeclBypass
- TestNonForgeability_CatchesVarDeclBypass
4. AST non-forgeability proof gap — pointer form (Medium,
subsequent round). After the short-decl fix, the architect
noted the same bypass in pointer form was still outside the
proof:
x := &adapter.AssignmentInfo{}
x.Epoch = userInput
The AST walker only recognized a bare *ast.CompositeLit on the
RHS, missing the UnaryExpr(&, CompositeLit) wrapper.
Fix: new helper unwrapAddrOfCompositeLit recognizes both
X{...} and &X{...}. Both GenDecl-with-value and AssignStmt
branches use it.
Regression:
- TestNonForgeability_CatchesPointerShortDeclBypass
- TestNonForgeability_CatchesPointerVarDeclBypass
5. Doc drift (Low). Two doc blocks still described the pre-fix²
state: docs/p14-s2-design.md said "simple 'forbidden
constructor' grep" and docs/p14-s2-closure.md listed
Unsubscribe as a Publisher method. Both updated to reflect the
AST-based whole-repo walker (covering value and pointer
forms) and the per-subscription cancel API with no key-wide
unsubscribe verb. Test count in closure.md bumped to 26 and
pointer-form test names added to the verification list.
No changes to engine, adapter, transport, ops, storage, or
sparrow. Authority tests: 26 pass. Full module: 12 packages pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
3d53563ca9
commit
63ea717a75
4 files changed
+440
-67
No files matched your search
@@ -39,10 +39,57 @@ type assignmentState struct {
|
||||
// between the subscriber's last read and the next may be skipped
|
||||
// — for authority truth that is correct (the engine cares about
|
||||
// current identity, not history).
|
||||
//
|
||||
// Delivery and close are guarded by a per-subscription mutex so
|
||||
// the publisher never sends on a closed channel (panic) or loops
|
||||
// on a closed channel's zero-receives (hang). A cancellation that
|
||||
// races with an in-flight delivery sees one of two outcomes:
|
||||
// - delivery wins: it drain+sends under the lock, then close
|
||||
// runs next and closes the channel.
|
||||
// - close wins: close sets closed=true and closes the channel,
|
||||
// then delivery sees closed and returns without touching ch.
|
||||
type subscription struct {
|
||||
id uint64
|
||||
key subKey
|
||||
ch chan adapter.AssignmentInfo
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
// deliver performs an overwrite-latest send to this subscription.
|
||||
// Called by Publisher.apply outside pub.mu. Safe to call
|
||||
// concurrently with close(): if the subscription is already
|
||||
// closed, deliver is a no-op and never touches ch.
|
||||
func (s *subscription) deliver(info adapter.AssignmentInfo) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
// Drain any stale pending value (non-blocking: either the
|
||||
// buffer has one item, or it's empty). Then send the latest.
|
||||
// Cap=1 + known-empty-after-drain means the send is also
|
||||
// non-blocking. Consumer-side receives never need the lock.
|
||||
select {
|
||||
case <-s.ch:
|
||||
default:
|
||||
}
|
||||
s.ch <- info
|
||||
}
|
||||
|
||||
// close closes the subscription's delivery channel exactly once.
|
||||
// Idempotent. Concurrent deliver() calls observe closed=true and
|
||||
// return without touching ch — so a cancel during in-flight
|
||||
// delivery never produces a send-on-closed panic.
|
||||
func (s *subscription) close() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
close(s.ch)
|
||||
}
|
||||
|
||||
// Publisher is the system-owned authority for assignment truth.
|
||||
@@ -80,7 +127,12 @@ func NewPublisher(dir Directive) *Publisher {
|
||||
//
|
||||
// If the publisher has already authored an AssignmentInfo for the
|
||||
// key, the new subscriber receives it immediately as late-
|
||||
// subscriber catch-up.
|
||||
// subscriber catch-up — and the catch-up value is guaranteed to
|
||||
// be the current authoritative state at the moment the subscriber
|
||||
// becomes visible, because the catch-up send and the subs-map
|
||||
// insert happen together under pub.mu. An apply() that authors a
|
||||
// newer fact after the subscriber is visible will drain the stale
|
||||
// catch-up value and replace it with the new fact via deliver().
|
||||
//
|
||||
// cancel is idempotent and safe to call from any goroutine.
|
||||
func (p *Publisher) Subscribe(volumeID, replicaID string) (<-chan adapter.AssignmentInfo, func()) {
|
||||
@@ -89,21 +141,24 @@ func (p *Publisher) Subscribe(volumeID, replicaID string) (<-chan adapter.Assign
|
||||
id: id,
|
||||
key: subKey{volumeID: volumeID, replicaID: replicaID},
|
||||
// Capacity 1 with overwrite-latest semantics on full. See
|
||||
// deliver() for the rationale.
|
||||
// subscription.deliver() for the rationale.
|
||||
ch: make(chan adapter.AssignmentInfo, 1),
|
||||
}
|
||||
|
||||
// Subs-map insert and catch-up send happen atomically under
|
||||
// pub.mu. This closes the "catch-up arrives after a newer
|
||||
// apply()" race: any apply() contending for pub.mu must either
|
||||
// run before us (so the state we read IS the current authoritative
|
||||
// state), or after us (so it sees us in the subs map and will
|
||||
// drain our catch-up via deliver()). The catch-up send to
|
||||
// sub.ch is non-blocking because sub is fresh and only we can
|
||||
// see it — no other goroutine can have filled its cap=1 buffer.
|
||||
p.mu.Lock()
|
||||
p.subs[sub.key] = append(p.subs[sub.key], sub)
|
||||
st, hasState := p.state[sub.key]
|
||||
p.mu.Unlock()
|
||||
|
||||
// Late-subscriber catch-up: deliver the last authored fact
|
||||
// immediately so a subscriber that attaches after authoring
|
||||
// does not miss identity.
|
||||
if hasState && st.present {
|
||||
sub.ch <- st.info // cap=1, fresh channel, always succeeds
|
||||
if st, ok := p.state[sub.key]; ok && st.present {
|
||||
sub.ch <- st.info
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
var once sync.Once
|
||||
cancel := func() {
|
||||
@@ -138,7 +193,7 @@ func (p *Publisher) cancelSubscription(target *subscription) {
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if found {
|
||||
close(target.ch)
|
||||
target.close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,7 +246,7 @@ func (p *Publisher) closeAllSubscriptions() {
|
||||
p.subs = make(map[subKey][]*subscription)
|
||||
p.mu.Unlock()
|
||||
for _, s := range all {
|
||||
close(s.ch)
|
||||
s.close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,41 +325,11 @@ func (p *Publisher) apply(ask AssignmentAsk) error {
|
||||
p.mu.Unlock()
|
||||
|
||||
for _, s := range subs {
|
||||
deliverLatest(s.ch, next)
|
||||
s.deliver(next)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deliverLatest performs a lossless-for-current-fact send onto a
|
||||
// capacity-1 channel. If the channel is empty, the send succeeds
|
||||
// directly. If the channel already holds a pending value (because
|
||||
// the subscriber hasn't drained yet), the stale pending value is
|
||||
// dropped and replaced with the latest one.
|
||||
//
|
||||
// The subscriber therefore always reads the LATEST authoritative
|
||||
// state next, never a stale one, and never silently loses the
|
||||
// current fact. For authority truth that is the correct semantic:
|
||||
// the engine cares about current identity, not interstitial
|
||||
// history between two publications.
|
||||
//
|
||||
// This replaces the earlier "drop on full with only a log line"
|
||||
// behavior, which could leave a subscriber on stale truth until
|
||||
// an unrelated future ask happened.
|
||||
func deliverLatest(ch chan adapter.AssignmentInfo, info adapter.AssignmentInfo) {
|
||||
for {
|
||||
select {
|
||||
case ch <- info:
|
||||
return
|
||||
case <-ch:
|
||||
// Drained a stale pending value. Retry send. Because
|
||||
// only the publisher produces and the publisher's
|
||||
// authoring loop is sequential per (vid, rid), the
|
||||
// next iteration's send will either succeed or find
|
||||
// a concurrent consumer read — both cases converge.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AssignmentConsumer is the narrow interface the Bridge calls back
|
||||
// into on delivery. adapter.VolumeReplicaAdapter satisfies it via
|
||||
// OnAssignment. Declared here so tests can provide their own fake
|
||||
|
||||
@@ -380,6 +380,128 @@ func TestPublisher_DeliveryConvergesToLatestOnSlowConsumer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublisher_CancelDuringDeliveryDoesNotPanic — regression for
|
||||
// the architect finding that apply()'s fan-out (outside pub.mu)
|
||||
// could race with cancel() and end up sending on a closed channel
|
||||
// (panic) or receiving zero values from a closed channel in a tight
|
||||
// loop (hang).
|
||||
//
|
||||
// The per-subscription mutex + closed flag closes that race: a
|
||||
// cancel that wins the per-sub lock closes the channel; any
|
||||
// in-flight deliver sees closed=true and returns; any late-arriving
|
||||
// deliver also sees closed=true and returns. No send-on-closed and
|
||||
// no infinite spin.
|
||||
func TestPublisher_CancelDuringDeliveryDoesNotPanic(t *testing.T) {
|
||||
// Stress test: many concurrent publishes and cancels on the same
|
||||
// key. Runs under the default test timeout; any panic trips the
|
||||
// test runner's recovery. Any hang shows up as a timeout.
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
|
||||
// Prime state so all subsequent Refresh asks are valid.
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
|
||||
const subscribers = 50
|
||||
const publishes = 200
|
||||
|
||||
var wg sync.WaitGroup
|
||||
// Consumers: subscribe, drain a few, cancel.
|
||||
for i := 0; i < subscribers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
ch, cancel := pub.Subscribe("v1", "r1")
|
||||
for j := 0; j < 3; j++ {
|
||||
select {
|
||||
case _, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
}()
|
||||
}
|
||||
|
||||
// Publisher: push many Refresh/Reassign asks in parallel.
|
||||
for i := 0; i < publishes; i++ {
|
||||
ask := AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: fmt.Sprintf("d%d", i), CtrlAddr: fmt.Sprintf("c%d", i),
|
||||
Intent: IntentRefreshEndpoint,
|
||||
}
|
||||
_ = pub.apply(ask)
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
// If we get here, no panic and no hang.
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("stress test hung — possible panic recovery or channel hang")
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish
|
||||
// is the regression for the architect finding that Subscribe()'s
|
||||
// catch-up send happened OUTSIDE pub.mu, so a concurrent apply()
|
||||
// could author a newer fact and deliver it to the new subscriber
|
||||
// before the delayed catch-up send landed — producing stale/out-of-
|
||||
// order delivery.
|
||||
//
|
||||
// With catch-up under pub.mu, the subscriber is guaranteed to
|
||||
// eventually drain a value at least as fresh as the state at the
|
||||
// moment of subscription.
|
||||
func TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish(t *testing.T) {
|
||||
pub := NewPublisher(NewStaticDirective(nil))
|
||||
if err := pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d1", CtrlAddr: "c1",
|
||||
Intent: IntentBind,
|
||||
}); err != nil {
|
||||
t.Fatalf("Bind: %v", err)
|
||||
}
|
||||
|
||||
const iterations = 200
|
||||
for i := 0; i < iterations; i++ {
|
||||
// Kick off a Reassign that races with Subscribe.
|
||||
go func() {
|
||||
_ = pub.apply(AssignmentAsk{
|
||||
VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "d", CtrlAddr: "c",
|
||||
Intent: IntentReassign,
|
||||
})
|
||||
}()
|
||||
|
||||
ch, cancel := pub.Subscribe("v1", "r1")
|
||||
var got adapter.AssignmentInfo
|
||||
select {
|
||||
case got = <-ch:
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
cancel()
|
||||
t.Fatalf("iter %d: no delivery on fresh subscribe", i)
|
||||
}
|
||||
// After all drains, the publisher's current state must be
|
||||
// >= got. If the catch-up raced and enqueued a stale value
|
||||
// after a newer deliver ran, the consumer could observe
|
||||
// monotonicity violation across multiple drains.
|
||||
latest, _ := pub.LastPublished("v1", "r1")
|
||||
if got.Epoch > latest.Epoch {
|
||||
cancel()
|
||||
t.Fatalf("iter %d: delivered epoch=%d > current epoch=%d (stale delivery)",
|
||||
i, got.Epoch, latest.Epoch)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublisher_RunClosesLiveSubscriptionsOnExit — when Run exits
|
||||
// (ctx cancelled, directive errored), every still-live subscription
|
||||
// channel must close so Bridges observe end-of-stream and exit
|
||||
@@ -722,6 +844,153 @@ func TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonForgeability_CatchesShortDeclBypass exercises the audit
|
||||
// function directly on synthetic source to prove it catches the
|
||||
// `x := adapter.AssignmentInfo{}; x.Epoch = userInput` deferred-
|
||||
// mutation bypass. Without the short-decl rule added to check (b),
|
||||
// this shape would pass both checks silently.
|
||||
func TestNonForgeability_CatchesShortDeclBypass(t *testing.T) {
|
||||
src := `package bypass
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
|
||||
func Forge(userInput uint64) {
|
||||
x := adapter.AssignmentInfo{}
|
||||
x.Epoch = userInput
|
||||
_ = x
|
||||
}
|
||||
`
|
||||
tmp, err := os.CreateTemp("", "authority-bypass-*.go")
|
||||
if err != nil {
|
||||
t.Fatalf("tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.WriteString(src); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
tmp.Close()
|
||||
|
||||
findings, err := auditNonForgeability(tmp.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("audit: %v", err)
|
||||
}
|
||||
if len(findings) == 0 {
|
||||
t.Fatal("expected audit to flag `x := adapter.AssignmentInfo{}` short-decl bypass, got none")
|
||||
}
|
||||
joined := strings.Join(findings, " | ")
|
||||
if !strings.Contains(joined, "short decl") && !strings.Contains(joined, "deferred-mutation") {
|
||||
t.Fatalf("expected bypass-specific finding, got: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonForgeability_CatchesVarDeclBypass confirms the long-form
|
||||
// `var x adapter.AssignmentInfo` bypass is also flagged.
|
||||
func TestNonForgeability_CatchesVarDeclBypass(t *testing.T) {
|
||||
src := `package bypass
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
|
||||
func Forge(userInput uint64) {
|
||||
var x adapter.AssignmentInfo
|
||||
x.Epoch = userInput
|
||||
_ = x
|
||||
}
|
||||
`
|
||||
tmp, err := os.CreateTemp("", "authority-bypass-*.go")
|
||||
if err != nil {
|
||||
t.Fatalf("tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.WriteString(src); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
tmp.Close()
|
||||
|
||||
findings, err := auditNonForgeability(tmp.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("audit: %v", err)
|
||||
}
|
||||
if len(findings) == 0 {
|
||||
t.Fatal("expected audit to flag `var x adapter.AssignmentInfo`, got none")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonForgeability_CatchesPointerShortDeclBypass exercises the
|
||||
// pointer-form short-decl bypass:
|
||||
//
|
||||
// x := &adapter.AssignmentInfo{}
|
||||
// x.Epoch = userInput
|
||||
//
|
||||
// A prior version of the AST walker only recognized a bare
|
||||
// *ast.CompositeLit on the RHS, missing the UnaryExpr(&, ...)
|
||||
// wrapper. The fix added unwrapAddrOfCompositeLit; this test
|
||||
// guards it.
|
||||
func TestNonForgeability_CatchesPointerShortDeclBypass(t *testing.T) {
|
||||
src := `package bypass
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
|
||||
func Forge(userInput uint64) {
|
||||
x := &adapter.AssignmentInfo{}
|
||||
x.Epoch = userInput
|
||||
_ = x
|
||||
}
|
||||
`
|
||||
tmp, err := os.CreateTemp("", "authority-bypass-*.go")
|
||||
if err != nil {
|
||||
t.Fatalf("tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.WriteString(src); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
tmp.Close()
|
||||
|
||||
findings, err := auditNonForgeability(tmp.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("audit: %v", err)
|
||||
}
|
||||
if len(findings) == 0 {
|
||||
t.Fatal("expected audit to flag `x := &adapter.AssignmentInfo{}` pointer-form bypass, got none")
|
||||
}
|
||||
joined := strings.Join(findings, " | ")
|
||||
if !strings.Contains(joined, "short decl") && !strings.Contains(joined, "deferred-mutation") {
|
||||
t.Fatalf("expected bypass-specific finding, got: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonForgeability_CatchesPointerVarDeclBypass exercises the
|
||||
// pointer-form long-decl bypass: `var x = &adapter.AssignmentInfo{}`.
|
||||
func TestNonForgeability_CatchesPointerVarDeclBypass(t *testing.T) {
|
||||
src := `package bypass
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
|
||||
func Forge(userInput uint64) {
|
||||
var x = &adapter.AssignmentInfo{}
|
||||
x.Epoch = userInput
|
||||
_ = x
|
||||
}
|
||||
`
|
||||
tmp, err := os.CreateTemp("", "authority-bypass-*.go")
|
||||
if err != nil {
|
||||
t.Fatalf("tempfile: %v", err)
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.WriteString(src); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
tmp.Close()
|
||||
|
||||
findings, err := auditNonForgeability(tmp.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("audit: %v", err)
|
||||
}
|
||||
if len(findings) == 0 {
|
||||
t.Fatal("expected audit to flag `var x = &adapter.AssignmentInfo{}`, got none")
|
||||
}
|
||||
}
|
||||
|
||||
// auditNonForgeability parses a Go source file and returns a list
|
||||
// of human-readable findings describing any disallowed use of
|
||||
// adapter.AssignmentInfo. It catches:
|
||||
@@ -800,7 +1069,20 @@ func auditNonForgeability(path string) ([]string, error) {
|
||||
|
||||
// (b) Local variable declarations of type AssignmentInfo.
|
||||
// Scope: inside function bodies only. Package-level declarations,
|
||||
// parameter declarations, and struct field types are excluded.
|
||||
// function parameters, and struct field types are excluded —
|
||||
// they do not create a mutation point for later `.Epoch = x`
|
||||
// assignment.
|
||||
//
|
||||
// Three declaration shapes are flagged:
|
||||
// - `var x adapter.AssignmentInfo` (DeclStmt / GenDecl)
|
||||
// - `var x = adapter.AssignmentInfo{}` (DeclStmt / GenDecl with value)
|
||||
// - `x := adapter.AssignmentInfo{}` (short AssignStmt)
|
||||
//
|
||||
// The short-decl shape is the deferred-mutation bypass the
|
||||
// architect called out: a zero-valued composite literal passes
|
||||
// the (a) check (no non-zero fields set), then a later
|
||||
// `x.Epoch = userInput` assignment forges authority truth.
|
||||
// Flagging the short decl itself closes the hole.
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
fn, ok := n.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
@@ -815,24 +1097,53 @@ func auditNonForgeability(path string) ([]string, error) {
|
||||
}
|
||||
for _, spec := range gd.Specs {
|
||||
vs, ok := spec.(*ast.ValueSpec)
|
||||
if !ok || vs.Type == nil {
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if isAssignmentInfoType(vs.Type) {
|
||||
// `var x adapter.AssignmentInfo`
|
||||
if vs.Type != nil && isAssignmentInfoType(vs.Type) {
|
||||
pos := fset.Position(vs.Pos())
|
||||
findings = append(findings, fmtFinding(pos.Line, "local variable declared of type AssignmentInfo"))
|
||||
continue
|
||||
}
|
||||
// `var x = adapter.AssignmentInfo{...}` or
|
||||
// `var x = &adapter.AssignmentInfo{...}` — type
|
||||
// comes from the RHS composite literal. Both
|
||||
// value and pointer forms are deferred-mutation
|
||||
// bypass shapes: the pointer form lets a later
|
||||
// `x.Epoch = userInput` forge authority truth
|
||||
// just as easily as the value form.
|
||||
for _, val := range vs.Values {
|
||||
if cl := unwrapAddrOfCompositeLit(val); cl != nil && cl.Type != nil && isAssignmentInfoType(cl.Type) {
|
||||
pos := fset.Position(vs.Pos())
|
||||
findings = append(findings, fmtFinding(pos.Line, "local variable inferred type AssignmentInfo (value or pointer)"))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
case *ast.AssignStmt:
|
||||
// `var x adapter.AssignmentInfo` uses GenDecl above.
|
||||
// `x := adapter.AssignmentInfo{}` is a short decl; if
|
||||
// RHS is a composite literal, the type check in (a)
|
||||
// already handles non-zero Epoch/EV. We do NOT flag
|
||||
// short decls of zero-value AssignmentInfo from a
|
||||
// function call return (legitimate when the callee is
|
||||
// a consumer API returning a zero value, e.g.
|
||||
// Publisher.LastPublished), because that would be
|
||||
// over-broad.
|
||||
// Short decl: `x := adapter.AssignmentInfo{...}` or
|
||||
// `x := &adapter.AssignmentInfo{...}` has
|
||||
// Tok == token.DEFINE. Only flag if the RHS directly
|
||||
// constructs AssignmentInfo via composite literal
|
||||
// (optionally wrapped in &). Flagging every
|
||||
// `x, _ := someFn()` whose return happens to be
|
||||
// AssignmentInfo would over-reach (legitimate
|
||||
// consumer reads like LastPublished).
|
||||
if v.Tok != token.DEFINE {
|
||||
return true
|
||||
}
|
||||
for _, rhs := range v.Rhs {
|
||||
cl := unwrapAddrOfCompositeLit(rhs)
|
||||
if cl == nil || cl.Type == nil {
|
||||
continue
|
||||
}
|
||||
if isAssignmentInfoType(cl.Type) {
|
||||
pos := fset.Position(v.Pos())
|
||||
findings = append(findings, fmtFinding(pos.Line, "short decl `x := [&]adapter.AssignmentInfo{...}` — deferred-mutation bypass shape"))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
@@ -846,6 +1157,24 @@ func fmtFinding(line int, msg string, args ...any) string {
|
||||
return fmt.Sprintf("line %d: %s", line, fmt.Sprintf(msg, args...))
|
||||
}
|
||||
|
||||
// unwrapAddrOfCompositeLit returns the composite literal at the
|
||||
// core of an expression that is either a plain `X{...}` or an
|
||||
// address-of `&X{...}`. Returns nil if the expression is neither.
|
||||
//
|
||||
// Added to close the architect-identified gap where `x :=
|
||||
// &adapter.AssignmentInfo{}` and `var x = &adapter.AssignmentInfo{}`
|
||||
// slipped past the inferred-type bypass check because the walker
|
||||
// only recognized a bare *ast.CompositeLit on the RHS.
|
||||
func unwrapAddrOfCompositeLit(e ast.Expr) *ast.CompositeLit {
|
||||
if u, ok := e.(*ast.UnaryExpr); ok && u.Op == token.AND {
|
||||
e = u.X
|
||||
}
|
||||
if cl, ok := e.(*ast.CompositeLit); ok {
|
||||
return cl
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func litIsZero(e ast.Expr) bool {
|
||||
if lit, ok := e.(*ast.BasicLit); ok {
|
||||
return lit.Kind == token.INT && lit.Value == "0"
|
||||
|
||||
@@ -126,15 +126,22 @@ Added:
|
||||
|
||||
- `core/authority/directive.go` — `AskIntent`, `AssignmentAsk`,
|
||||
`Directive`, `StaticDirective`, validation errors.
|
||||
- `core/authority/authority.go` — `Publisher`, `Subscribe`,
|
||||
`Unsubscribe`, `LastPublished`, `Run`, `Bridge`,
|
||||
`AssignmentConsumer`.
|
||||
- `core/authority/authority_test.go` — 20 tests covering intent
|
||||
- `core/authority/authority.go` — `Publisher`, `Subscribe` (returns
|
||||
per-subscription cancel func), `LastPublished`, `Run`, `Bridge`,
|
||||
`AssignmentConsumer`. No key-wide unsubscribe verb — per-
|
||||
subscription cancel is the only teardown path.
|
||||
- `core/authority/authority_test.go` — 26 tests covering intent
|
||||
semantics, fan-out keyed by `(VolumeID, ReplicaID)`,
|
||||
**independent-unsubscribe**, **lossless-for-current-fact
|
||||
delivery**, late-subscriber catch-up, `Run` loop,
|
||||
delivery**, **cancel-vs-delivery race (stress test)**,
|
||||
**late-subscriber-under-concurrent-publish ordering**,
|
||||
late-subscriber catch-up, `Run` loop,
|
||||
`RunClosesLiveSubscriptionsOnExit`, `Bridge`, closure target,
|
||||
AST-based non-forgeability.
|
||||
AST-based non-forgeability including direct bypass-coverage
|
||||
tests for `var x AssignmentInfo`,
|
||||
`x := adapter.AssignmentInfo{}`, and the pointer-form variants
|
||||
`var x = &adapter.AssignmentInfo{}` and
|
||||
`x := &adapter.AssignmentInfo{}`.
|
||||
- `docs/p14-s2-audit.md`, `docs/p14-s2-design.md`, this file.
|
||||
|
||||
Changed:
|
||||
@@ -171,12 +178,18 @@ Specifically:
|
||||
- `TestPublisher_LateSubscriber_ReceivesLastPublished`
|
||||
- `TestPublisher_Cancel_ClosesOnlyThisSubscription`
|
||||
- `TestPublisher_DeliveryConvergesToLatestOnSlowConsumer`
|
||||
- `TestPublisher_CancelDuringDeliveryDoesNotPanic`
|
||||
- `TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish`
|
||||
- `TestPublisher_RunClosesLiveSubscriptionsOnExit`
|
||||
- `TestPublisher_Run_DrivesDirectiveUntilCtxCancel`
|
||||
- `TestPublisher_Run_LogsAndContinuesOnRejectedAsk`
|
||||
- `TestBridge_ForwardsToConsumer`
|
||||
- `TestClosureTarget_SparrowReachesHealthyViaAuthorityRoute`
|
||||
- `TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority`
|
||||
- `TestNonForgeability_CatchesShortDeclBypass`
|
||||
- `TestNonForgeability_CatchesVarDeclBypass`
|
||||
- `TestNonForgeability_CatchesPointerShortDeclBypass`
|
||||
- `TestNonForgeability_CatchesPointerVarDeclBypass`
|
||||
|
||||
If the non-forgeability test starts failing because some new
|
||||
production package wants to construct `AssignmentInfo{Epoch: ...}`,
|
||||
|
||||
@@ -122,12 +122,18 @@ Only `core/authority/` may construct an `AssignmentInfo` with
|
||||
1. `AssignmentInfo` stays in `core/adapter` as it is today (it is
|
||||
the adapter's ingress shape). The authority package is the only
|
||||
production package that constructs one.
|
||||
2. A package-level test in `core/authority/` audits production
|
||||
imports with a simple "forbidden constructor" grep: any
|
||||
non-test `.go` file outside `core/authority/` that literal-typed
|
||||
`adapter.AssignmentInfo{` with a non-zero `Epoch` field fails the
|
||||
test. Test helpers (`_test.go` files) are exempt — calibration
|
||||
and conformance retain their right to forge test facts.
|
||||
2. A package-level test in `core/authority/` audits every
|
||||
production `.go` file in the whole repo (not just `core/`)
|
||||
using `go/ast`. It fails if a file outside the allowlist either
|
||||
(a) constructs `adapter.AssignmentInfo` via composite literal
|
||||
with a non-zero `Epoch` or `EndpointVersion`, or (b) declares a
|
||||
local variable — `var x`, `var x = X{...}`, or `x := X{...}`,
|
||||
including pointer forms (`&X{...}`) — whose declared or
|
||||
inferred type is `AssignmentInfo`. Case (b) closes the
|
||||
deferred-mutation bypass (`var x AssignmentInfo; x.Epoch = v`).
|
||||
Test helpers (`_test.go` files) are exempt, and the
|
||||
test-infrastructure packages `core/calibration/`,
|
||||
`core/conformance/`, `core/schema/` are explicitly allowlisted.
|
||||
|
||||
## Publication API — no public write verb
|
||||
|
||||
|
||||
Reference in new issue
Block a user