diff --git a/seaweed-block/core/host/master/placement_admission_guard_test.go b/seaweed-block/core/host/master/placement_admission_guard_test.go new file mode 100644 index 0000000000..972c18c12e --- /dev/null +++ b/seaweed-block/core/host/master/placement_admission_guard_test.go @@ -0,0 +1,202 @@ +package master + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// INV-AUTH-DYNAMIC-NEEDS-LOOP-001: the pure guard must not reject a recorded +// retry or run after a new write. The restart RPC test supplies the behavioral +// control; this census pins the two receiving boundaries and their ordering. +func TestAssignmentProducerGuardSitesAndOrder(t *testing.T) { + sources := map[string][]byte{} + paths, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + sources[path], err = os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + } + if err := assignmentProducerGuardSites(sources); err != nil { + t.Fatal(err) + } + + // Mutate source in memory: neither production code nor its assertions are + // edited to demonstrate that missing/extra sites and reordered guards fail. + for name, mutate := range map[string]func(map[string][]byte){ + "missing site": func(s map[string][]byte) { + s["services.go"] = []byte(strings.Replace(string(s["services.go"]), "s.host.requireAssignmentProducer(spec.VolumeID)", "s.host.otherGuard(spec.VolumeID)", 1)) + }, + "new site": func(s map[string][]byte) { + s["new.go"] = []byte("package master; func newDoor() { h.requireAssignmentProducer(v) }") + }, + "guard before record lookup": func(s map[string][]byte) { + s["services.go"] = []byte(`package master +func (s *services) CreateVolume() { + if err := s.host.requireAssignmentProducer(spec.VolumeID); err != nil { return } + if existing, ok := stores.Volumes.GetVolume(spec.VolumeID); ok { use(existing) } + s.host.createLifecycleVolume(ctx, spec) +}`) + }, + "create before guard": func(s map[string][]byte) { + s["services.go"] = []byte(`package master +func (s *services) CreateVolume() { + s.host.createLifecycleVolume(ctx, spec) + if existing, ok := stores.Volumes.GetVolume(spec.VolumeID); ok { use(existing) } else if err := s.host.requireAssignmentProducer(spec.VolumeID); err != nil { return } +}`) + }, + "guard before recorded placement": func(s map[string][]byte) { + s["workspace_binding.go"] = []byte(`package master +func (s *services) PlaceWorkspace() { + s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error { + if err := s.host.requireAssignmentProducer(q.GetVolumeId()); err != nil { return err } + if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok { if identical(p) { return nil }; return conflict } + s.host.lifecycle.Placements.ApplyPlan(plan) + return nil + }) +}`) + }, + "placement before guard": func(s map[string][]byte) { + s["workspace_binding.go"] = []byte(`package master +func (s *services) PlaceWorkspace() { + s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error { + if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok { if identical(p) { return nil }; return conflict } + s.host.lifecycle.Placements.ApplyPlan(plan) + if err := s.host.requireAssignmentProducer(q.GetVolumeId()); err != nil { return err } + return nil + }) +}`) + }, + } { + t.Run(name, func(t *testing.T) { + changed := make(map[string][]byte, len(sources)) + for path, raw := range sources { + changed[path] = raw + } + mutate(changed) + if err := assignmentProducerGuardSites(changed); err == nil { + t.Fatal("unsafe guard mutation escaped the census") + } + }) + } +} + +func assignmentProducerGuardSites(sources map[string][]byte) error { + sites := map[string]int{} + functions := map[string]*ast.FuncDecl{} + for path, raw := range sources { + file, err := parser.ParseFile(token.NewFileSet(), path, raw, 0) + if err != nil { + return err + } + for _, decl := range file.Decls { + owner := "" + if fn, ok := decl.(*ast.FuncDecl); ok { + owner = fn.Name.Name + functions[path+" "+owner] = fn + } + ast.Inspect(decl, func(n ast.Node) bool { + // Count method references too: saving a method value must not + // hide a new caller from the enumeration. + if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == "requireAssignmentProducer" { + sites[path+" "+owner]++ + } + return true + }) + } + } + want := map[string]int{"services.go CreateVolume": 1, "workspace_binding.go PlaceWorkspace": 1} + if !reflect.DeepEqual(sites, want) { + return fmt.Errorf("assignment producer guard sites changed: got %v, want %v", sites, want) + } + create := functions["services.go CreateVolume"] + write := guardCalls(create.Body, "createLifecycleVolume") + if len(write) != 1 { + return fmt.Errorf("CreateVolume first write boundary changed") + } + valid := false + for _, stmt := range create.Body.List { + lookup, ok := stmt.(*ast.IfStmt) + if !ok || !guardInitCalls(lookup, "GetVolume") { + continue + } + guard, ok := lookup.Else.(*ast.IfStmt) + if ok && guardInitCalls(guard, "requireAssignmentProducer") && guard.End() < write[0].Pos() { + valid = true + } + } + if !valid { + return fmt.Errorf("CreateVolume guard must be the absent-record else branch, before createLifecycleVolume") + } + place := functions["workspace_binding.go PlaceWorkspace"] + publication := guardCalls(place.Body, "RecordWorkspacePlacement") + if len(publication) != 1 || len(publication[0].Args) != 3 { + return fmt.Errorf("PlaceWorkspace publisher boundary changed") + } + callback, ok := publication[0].Args[2].(*ast.FuncLit) + if !ok { + return fmt.Errorf("PlaceWorkspace persist callback must be inspected") + } + writes := guardCalls(callback.Body, "ApplyPlan") + guards := guardCalls(callback.Body, "requireAssignmentProducer") + if len(writes) != 1 || len(guards) != 1 { + return fmt.Errorf("PlaceWorkspace guard/write must remain inside the publisher callback") + } + valid = false + for _, stmt := range callback.Body.List { + lookup, ok := stmt.(*ast.IfStmt) + if !ok || !guardInitCalls(lookup, "GetPlacement") || lookup.End() >= guards[0].Pos() || guards[0].End() >= writes[0].Pos() { + continue + } + // A recorded intent must answer both identical and conflicting calls + // before reaching the new-write guard. + if len(lookup.Body.List) != 2 { + continue + } + identical, ok := lookup.Body.List[0].(*ast.IfStmt) + if ok && guardEndsInReturn(identical.Body) && guardEndsInReturn(lookup.Body) { + valid = true + } + } + if !valid { + return fmt.Errorf("PlaceWorkspace guard must follow recorded-intent returns and precede ApplyPlan") + } + return nil +} + +func guardCalls(node ast.Node, name string) (calls []*ast.CallExpr) { + ast.Inspect(node, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == name { + calls = append(calls, call) + } + } + return true + }) + return calls +} + +func guardInitCalls(stmt *ast.IfStmt, name string) bool { + return stmt.Init != nil && len(guardCalls(stmt.Init, name)) == 1 +} + +func guardEndsInReturn(body *ast.BlockStmt) bool { + if len(body.List) == 0 { + return false + } + _, ok := body.List[len(body.List)-1].(*ast.ReturnStmt) + return ok +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9e22954558..dcca85e56e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -731,7 +731,7 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-AUTH-DYNAMIC-NEEDS-LOOP-001` | With the loop off, new dynamic records and first placements fail without writes (FailedPrecondition names the cure); exact static RF1 membership is exempt. Recorded retries keep identity/conflict rules after restart. | M2 none → Bound admission | `core/host/master/placement_admission.go` `requireAssignmentProducer`; `services.go` `CreateVolume`; `workspace_binding.go` `PlaceWorkspace` (under workspaceMu) | `TestCreateVolumeRequiresAnAssignmentProducerBeforeAnyWrite`, `TestPlaceWorkspaceRequiresAnAssignmentProducerBeforePlacement`, `TestRecordedDynamicIntentRetriesAfterRestartWithTheLoopOff` (`core/host/master/create_placement_loop_test.go`) | — (immutable configuration admission; no kernel transition) | ACTIVE | +| `INV-AUTH-DYNAMIC-NEEDS-LOOP-001` | With the loop off, new dynamic records and first placements fail without writes (FailedPrecondition names the cure); exact static RF1 membership is exempt. Recorded retries keep identity/conflict rules after restart. | M2 none → Bound admission | `core/host/master/placement_admission.go` `requireAssignmentProducer`; `services.go` `CreateVolume`; `workspace_binding.go` `PlaceWorkspace` (under workspaceMu) | `TestCreateVolumeRequiresAnAssignmentProducerBeforeAnyWrite`, `TestPlaceWorkspaceRequiresAnAssignmentProducerBeforePlacement`, `TestRecordedDynamicIntentRetriesAfterRestartWithTheLoopOff` (`core/host/master/create_placement_loop_test.go`); `TestAssignmentProducerGuardSitesAndOrder` (`core/host/master/placement_admission_guard_test.go`) | — (immutable configuration admission; no kernel transition) | ACTIVE | | `INV-AUTH-HOLDER-IDENTITY-001` | A primary holder is the pair (server id, replica id): every site that decides holdership (adopting a fact, lease first grant, renew, re-grant, HEAD claim, superseded exit) compares both; a missing server id is refused, never guessed. | AUTHORITY: PRIMARY holdership (supporting replicas are not holders) | `core/host/volume/host.go` `applyFact`, `IsSuperseded`, `recordOtherLine`; `assignment_holder.go` `assignmentNamesSelf`, `observeForeignHolder`, `refusePrimaryAssignment`; `host.go` `IsSuperseded`; `core/host/master/services.go` `SubscribeAssignments`; `workspace_service.go` `holderMatches`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`; `cmd/blockvolume/chunk_remote.go` `chunkHolder`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim`; superseded exit covered by #409; `core/host/master/workspace_binding.go` `workspaceLineOwner`, `workspaceSourceHost`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/server_host_identity.go` `refuseServerIDFromOtherHost` (from `ReportHeartbeat`), `refuseWorkspaceHolderHost` (from `holderMatches` and, for a workspace volume, `SubscribeAssignments`), `holderSlotFact` (from `QueryVolumeStatus` and `observationVolume`/`observationReplicas`); `core/csi/master_backend.go` `primaryOwnedFrontends` (a CSI target only from a usable primary frontend); `core/authority/snapshot_builder.go` `expectOwnerForLine` (a moved line's replica facts and endpoint refreshes only from its owner, #425) | `TestAssignmentHolderIdentityRestartedOldProcess`, `TestAssignmentHolderIdentityMatchingServerStillAdopts`, `TestAssignmentHolderIdentityFencesPreviouslyHealthySameReplica`, `TestAssignmentHolderIdentityAdoptsAndWarnsCarriedEndpointMismatch`, `TestAssignmentHolderIdentityForeignStreamOrdering`, `TestAssignmentHolderIdentityForcedMoveRefusesEveryDeliveredVersion`, `TestAssignmentHolderIdentitySameEpochCannotChangeServer` (`core/host/volume/assignment_holder_test.go`); `TestWorkspaceLeaseGuardCarriesHolderServerIdentity` (`core/host/volume/workspace_holder_identity_test.go`); `TestWorkspaceLeaseRequiresHolderServerForGrantRenewAndRegrant`, `TestWorkspaceRevocationACKRequiresHolderServer` (`core/host/master/workspace_holder_identity_test.go`); `TestWorkspaceRPCCleanMovePreservesReplicaIdentity` (`core/host/master/workspace_service_test.go`); HEAD claim: `TestChunkHolderIsServerAndReplica` (`cmd/blockvolume/chunk_remote_test.go`), `TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced` (`core/frontend/durable/provider_chunk_holder_test.go`); superseded exit: covered by #409 (server-id/replica-id pair, never replica alone); supporting replicas are not holders; descriptor identity not in this row; `TestWorkspaceLineOwnerIssuedAndHistorical` (`core/host/master/workspace_line_owner_test.go`), `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestAssignmentFactKeepsCapturedMoveOwnerWithoutReadableJournal` (`core/host/master/assignment_fact_owner_test.go`), `TestAssignmentOwnerReservedAndIssuedCapture` (`core/authority/assignment_owner_test.go`), `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestServerIDRefusedFromAHostOtherThanItsRegisteredOne`, `TestWorkspaceHolderRefusedFromAnotherHostAtRenewAckAndStream`, `TestPortalAndPrimaryComeFromTheLineServerNotTheFreshestHeartbeat`, `TestDisplayedPrimaryIsTheIssuedHolderNotThePlacementSlot`, `TestStatusListsNoFrontendWhenThePrimaryEvidenceIsMissing`, `TestCSIPublishesNoTargetWhenThePrimaryFrontendIsMissingOrRejected`, `TestDeletionReservedWorkspaceVolumeKeepsTheStreamHostCheck` (`core/host/master/server_host_identity_test.go`); `TestPublishTargetIsPrimaryOwned` (`core/csi/primary_owned_frontend_test.go`). Host scope: registered advertised-host consistency, not process uniqueness; a workspace holder's server id must be registered (no first-seen binding: host addresses change); non-workspace heartbeats from an unregistered id are not checked. Limits: with mutual TLS on, a node may act only for the server id bound to its certificate (`TERM-CALLER-001`; `auth.RequireNode` in `ReportHeartbeat`, `SubscribeAssignments`, `RenewWorkspaceLease`, `AckWorkspaceRevoked`, `QueryVolumeStatus`; `TestNodeActsOnlyForItsOwnServerID`, `core/host/master/auth_red_test.go`), and the registered-host check stays beside it (no NAT or proxy between volume and master in OSS); in development mode (plaintext on loopback, no role file) there is no authentication; `TestBuildSnapshotTakesTheMovedLinesReplicaFromItsOwner` (`core/authority/line_owner_snapshot_test.go`); `TestProcedureForcedMoveWithTheOldHostReturning` (`cmd/blockvolume/procedure_gate_integration_test.go`, tags subprocess chunkstore_integration: every forced-epoch line carries the new owner's endpoints) | `WorkspaceRegrant` `NoForeignAdoption`, `TargetNotFencedByOwnLine` (round 4 pinned simulations only; exhaustive combo10 pending) | ACTIVE | | `INV-AUTH-CALLER-ROLE-001` | With mutual TLS on, every blockmaster gRPC call (unary, and before every stream send) is decided by the caller's certificate and the current role file: an unknown caller is refused UNAUTHENTICATED, a role its method's rule does not admit PERMISSION_DENIED, a method without a rule always. | AUTHORITY: control API callers (people, tools, nodes) | `core/auth/identity.go` `Authenticator.PeerIdentity`, `Authenticator.Reload`; `core/auth/authorize.go` `Rule.Allows`, `UnaryInterceptor`, `StreamInterceptor`, `RequireNode`, `RequireRole`; `core/host/master/authz.go` `masterRules`, `serverAuth`; `core/rpc/link/tls.go` `ServerCredentials`, `ClientCredentials`; `cmd/blockmaster/auth.go` `authFlags.validate`, `authFlags.build` | `TestPeerIdentity`, `TestRoleFileReload` (`core/auth/identity_test.go`); `TestRuleAllows`, `TestRequireNodeAndRole`, `TestUnaryInterceptor`, `TestStreamEndsAtTheReloadThatRevokesItsCaller` (`core/auth/authorize_test.go`); `TestMasterAuthorizationTableCoversEveryMethod` (`core/host/master/authz_test.go`); `TestForcedMoveNeedsAnAdmin`, `TestNodeActsOnlyForItsOwnServerID` (`core/host/master/auth_red_test.go`); `TestMasterLinkMutualTLS` (`core/rpc/link/tls_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`); `TestMasterTLSFlags` (`cmd/blockvolume/master_tls_test.go`). Also: a mutating operator or admin method writes its audit attempt before it runs or is refused as audit unavailable (`Rule.Strict`; `TestMasterOperatorMethodsAreStrict` (inverted: a new operator or admin method fails unless strict or named with its reason), `core/host/master/authz_test.go`; `TestStrictCallsNeedTheirAttemptLine`, `core/auth/strict_audit_test.go`), node calls never wait on the audit log; a reload that removes a caller, or changes its role so the method's rule no longer admits it, ends its open streams at the reload; a forced move needs an admin; plaintext listens only on loopback without a role file (development mode). Limits: the audit log records outcomes and decides nothing; the volume process's own HTTP routes stay loopback-only and unauthenticated. | `AuthLease` (exhaustive run pending) | ACTIVE | | `INV-AUTH-ONE-REPLICATED-FACTOR-001` | CreateVolume admits a replicated volume only if the master can decide it: its replication factor equals the master's one slot count (--expected-slots-per-volume) and the lifecycle product loop runs (only that loop binds, mints and promotes it). | M2 none → Bound (a created replicated volume's first line) | `core/host/master/services.go` `CreateVolume`; `core/host/master/host.go` `Config.LifecycleProductLoop`; `core/authority/controller.go` `ExpectedSlotsPerVolume`, `validateVolumeTopology` | `TestAnRF2CreateOnAnRF3MasterIsRefusedAndFailoverContinues`, `TestAReplicatedCreateWithTheProductLoopOffIsRefused` (`core/host/master/create_rf_mismatch_test.go`) | — (an admission check). Limits: single-replica volumes are admitted at any slot count (they never reach the check); a static --topology file with a mismatched volume is not checked at start (a cluster spec is: `INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001`) | ACTIVE |