carlos / platform Public

durability 3a: guard each staging operation through the classifier

Check every staging call through typed dispatch and module-wide alias
assignments. Require dominating classification or refusal, and reject
mixed callable aliases, forwarded skips and unsafe platform items.

Overlay nine fixtures on the real module, including interface dispatch,
reassignment and control-flow bypasses. Pin the files-relative to
inventory-relative host/path mapping without a call-site exemption.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 984fadb73fb28c6fa856d9427b1be0c73a1de8ec parent 3c67bc6
10 files changed, +1,249 −0
  • internal/layout/pubclass/publication_guard_test.go +902 −0
  • internal/layout/pubclass/testdata/publication_guard/clean.go +99 −0
  • internal/layout/pubclass/testdata/publication_guard/iface.go +21 −0
  • internal/layout/pubclass/testdata/publication_guard/ignored.go +20 −0
  • internal/layout/pubclass/testdata/publication_guard/mixedalias.go +40 −0
  • internal/layout/pubclass/testdata/publication_guard/nilvar.go +34 −0
  • internal/layout/pubclass/testdata/publication_guard/prepared.go +17 −0
  • internal/layout/pubclass/testdata/publication_guard/reassign.go +48 −0
  • internal/layout/pubclass/testdata/publication_guard/unclassified.go +57 −0
  • internal/layout/pubclass/testdata/publication_guard/wrapper.go +11 −0

Intent

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/1164902.sock" from-name="platform-60" from-mode="bypass"> From platform-60, on Paul's ask (2026-10-31: "are we doing something particularly slow?"): a verification budget for subagent-built work, to use from now on. 1. Mutation checks only on refusal, security, termination and lifecycle paths: at most about 10 per task, each with targeted -run tests. Plan 6 Tasks 10 and 11 ran 47 and 56 against the console package (1-2 min a run), so Task 10 took about 4 h. 2. Run tests locally once (-count=1), with -race once. Repeat counts like -count=20 only for a test with a known or suspected flake. 3. CI runs the full suite; locally run only the touched packages, targeted (as before). 4. Smoke-test on a real dev box as soon as a feature works end to end, not at the end of the plan. If you have implementer briefs or SDD common.md files in flight, please add this. No reply needed. </cross-session-message>

Human

Status?

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/1164902.sock" from-name="platform-60" from-mode="bypass"> platform-60: on Paul's go, I'm merging rootfs apps Plan 6 (interactive sessions; carlos run on rootfs and fleet boxes) once its CI is green, then cutting v0.33.1 to dev only from main at that merge. If you have anything about to merge that should ride along, or a reason to hold, reply within about 20 minutes; otherwise I'll go ahead. Your HA hosts hapair-a1 and hacheck-ha1 won't be touched beyond the normal box update. </cross-session-message>

Human

<task-notification> <task-id>afd81f86431eaa878</task-id> <tool-use-id>toolu_01TjnGNE5AznFwjs1mpvi37p</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/953e7524-2e06-4308-b9ce-fd1b38579971/tasks/afd81f86431eaa878.output</output-file> <status>failed</status> <summary>Agent "Review Task 6 (spec + quality)" failed: Agent terminated early due to an API error: You've hit your weekly limit · resets Nov 6, 1am (Europe/Dublin) (error type rate_limit, HTTP 429, request id req_011Cgbp1aRcWvcujVcgCNpU2, model sent to the API: claude-opus-5-5)</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once. This agent's work so far is saved. The limit resets Nov 6, 1am (Europe/Dublin). Once its requests are accepted again, send the agent a message (SendMessage) to let it continue from where it stopped instead of starting a new agent.</note> </task-notification>

Human

<task-notification> <task-id>ace361f17e369e6e2</task-id> <tool-use-id>toolu_01SXEGjuCLRMLYRyQ4B1fwDr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/aab63774-dfe6-44a4-9cd9-230e6f4c3d13/tasks/ace361f17e369e6e2.output</output-file> <status>completed</status> <summary>Agent "Review durability 3a Task 6" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ The create door takes `lockAccount(acct.Sqid)` unconditionally (`internal/console/apiinstances.go:2257`). It replaces `planLock`, so the lock order with plans on is unchanged. Checked for re-entry: every other `lockAccount`/`planLock` site in console (37 sites) is a separate handler or entry point (`restoreApp`, `placeAppTarget`, `runFrom`'s async store step, relay ops and so on). None is reached synchronously from the door, so nothing deadlocks with plans off. - ✅ The seed and import record writes really do run under the door's lock. `createSeedRecord` is called from `beginFrom` (`apiinstanceseed.go:369`) and `beginImport` (`apiinstanceimport.go:184`). Both are the synchronous halves. `go s.runFrom` starts only after the reservation record is written. - ✅ Recovery takes `lockAccount(a.Account)` around each pending-allocation `withAppHost` (`lifetimes_recovery.go:82-87`), in the order account, then app, then hostname. `recoverLifetimes` runs only from `s.jobs.Run` (`:44`), with no lock held. The recovery witness proves `a.Account` is the same key the door locks (sqid). - ✅ `fleetHasInstances` matches the brief's signature and meaning (`fleetsecretskey.go:189-207`). A malformed body counts as an instance (conservative), and a list or Get error propagates and answers 502 (`:140-145`). A first key is unaffected. The same-key no-op is unaffected. - ✅ The 409 text matches the brief word for word and has no em or en dashes (`fleetsecretskey.go:147`). - ✅ `fleetKeyHook` is an `atomic.Pointer[func(string)]`, called with `"after-membership-check"` under the lock and before any write (`:151-153`). - ✅ The race witnesses (`fleetsecrets_race_test.go`) run with `PlanCatalog == nil`. Each calls `waitForWaiter` on `acctLocks` before release and checks the key fingerprint at the actual record write. The replace-blocks-create and replace-blocks-recovery witnesses also check that no record exists while the replacement is parked. - ✅ `TestPurgeRecoveryWritesNoRecord` covers both the "slot" and "record" pending steps and counts record Puts (`fleetsecrets_race_test.go:230-262`). - ✅ `TestEveryInstanceRecordCreatorIsUnderTheAccountLock` loads the whole module (`./...`, non-test). It resolves functions by identity, including aliases and function values, and pins caller counts. It has negative overlay fixtures. It also found the sidecar `finishClaimCreate` caller (`recordcreators_guard_test.go:819-820`), which the brief's table missed. - ❌ `TestABoxThatChangesKeyResealsItsEscrow` (activator) was not written. The brief's Step 1 lists it, and its Step 5 includes `git add internal/activator`. The controller's `task-6-extra.txt` scoped the task to console only. No ruling in `progress.md` records where this witness went, and no equivalent test exists in `internal/activator` or `internal/hostfiles`. See Important 2. - ⚠️ Cannot verify from the diff: - Record writers outside the brief's grep set. One example is `provision.WriteRecord` (`record_sequence.go:125`) with an empty etag. Moves and adopt paths could also write a first record for a host in a fleet-placed app without the account lock. The guard pins only the named creators. - Whether a first key on a fleet whose instances already escrowed under the deployment key behaves as the brief's "box that changes key" paragraph says. The plan accepts this (a first key is unaffected), and nothing witnesses it. - Whether deleting an instance, which the 409 text recommends, removes or invalidates its old-key escrow. If the escrow stays under `&lt;host&gt;/files/0/`, a later create on the same hostname under key B would meet an escrow it cannot open and fail closed. That is outside Task 6's diff, but the 409 text sends users down this path. - The full-package result. The implementer's sweep went green only after a re-sharded rerun. `TestSweepPassIsBoundedByATimeout` is intermittent, and its paths are untouched by this diff. ### Strengths - The lock change is minimal and correct. With plans on, the door already took this exact lock, so the change only extends existing behaviour to plans-off deployments. - The witnesses are production-wired. They use real HTTP doors, the real `recoverLifetimes`, a real `hostfiles` sealed publication opened with `ReadSealed`, and an ordering proof through `waitForWaiter` rather than sleeps. Refusal tests check that the row is unchanged, the owner record bytes are unchanged, and there were zero owner-record writes. - The fail-closed split is right: unreadable record means 409, store error means 502, and nothing is written in either case. - The guard's negative fixtures prove the guard can fail, rather than only listing today's callers. - The audit allowlist entry in `lifetimes_audit_test.go` is narrow and gives its reason. - New files are small (207 and 143 lines). ### Issues **Important** 1. **A trashed app slips past the gate, and its old-key escrows come back when it is restored** (plan-mandated). Location: `fleetsecretskey.go:190` → `fleetPlacedApps` (`:353-354`) → `Store.AppsIn`, which filters `deleted_at = 0`. - What: an app in the trash is not counted. `restoreApp` (`restore.go:55-110`, under the same account lock) brings the app's objects back, records included. So this sequence passes every check: trash app → replace key A with B → restore app. The restored instances then carry escrows sealed to A on a fleet whose boxes hold B. Task 4's rules make restore and mint fail closed, so those instances cannot launch on a box without local files. The operator cannot fix this from the console, because key A is no longer registered. - Why it matters: this is exactly the stranded-escrow state Task 6 exists to prevent, reached through ordinary console doors. The implementer confirmed it from source (report concern 1). - Fix: count trashed, unpurged apps placed on the fleet in `fleetHasInstances`, for example with a store query that includes `deleted_at != 0` rows with a placement. Add a witness: trash, then replace, gets a 409. Alternatively, `restoreApp` could refuse when the fleet's key changed after the trash. The first fix is simpler and keeps one gate. `fleetHasSealedValues` has the same hole from before this task, so the same fix could cover both. 2. **The brief's activator witness was dropped, and the drop is not tracked.** Location: brief Step 1, `TestABoxThatChangesKeyResealsItsEscrow`. - What: no test pins the brief's claim that a box with its local files reseals under the new key on its next sweep. Nothing equivalent exists at 3c67bc64. - Why it matters: the claim is the brief's whole answer for a box whose key changes outside the console. As built, it is an unwitnessed behavioural claim. - Fix: write the witness in a follow-up activator task, or record a controller ruling in `progress.md` that names where it lands. The witness: escrow under A, `EscrowKey` B, one sweep, then `ReadSealed` opens with B. **Minor** 3. **The check reads every record body when listing the keys would do.** Location: `fleetsecretskey.go:199`. - What: `ListRecordsStrict(..., math.MaxInt)` GETs every record of every app on the fleet while holding the account lock, inside the door's 30 s budget. "Any record or unreadable" is the same as "any key under the records prefix", so one LIST per app would answer it with no GETs. - Why it matters: on a large fleet the GETs can run past 30 s. The user then gets a misleading 502 ("run ... again") instead of the true 409, and every retry fails the same way. It also holds up creates for the whole time. - Fix: list keys only, and stop at the first key for each app. 4. **The hostname-lock witness no longer tests the hostname lock.** Location: `lifetimes_create_test.go:745-751`. - What: `TestTwoAppsCreatingOneHostnameSerialise` now passes because both apps share the `bab` account lock. It no longer shows that the hostname lock serialises creates. - Why it matters: if that guarantee is still needed across accounts, nothing tests it now. - Fix: put the second app in a different account so the original hostname-wait assertion still applies, or point to another cross-account witness. 5. **The guard pins direct callers but not the next level up.** Location: `recordcreators_guard_test.go:794-826`. - What: the guard pins `createSeedRecord`'s use of the creators, but not who calls `createSeedRecord`, `beginFrom` or `beginImport`. A new non-door caller of `createSeedRecord` would pass the guard without the lock. - Fix: add `createSeedRecord` → {`beginFrom`: 1, `beginImport`: 1} and the next level up to the table. 6. **The purge witness skips the real purge entry.** Location: `fleetsecrets_race_test.go:248-250`. - What: `TestPurgeRecoveryWritesNoRecord` calls `purgeHostLocked` directly instead of going through a real purge door (`ownership.go:601` or the expiry pass). - Why it matters: it is acceptable as a unit pin, but it is weaker than the repo's production-wired standard. ### Assessment **Task quality:** Needs fixes. The lock change, the membership refusal and the witnesses are correct and well built. Lock order holds and no re-entry or deadlock was found. However, the gate skips trashed apps, and restore brings their old-key escrows back (plan-mandated). The brief's activator reseal witness was dropped with no recorded ruling. The report is also saved to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/durability-3a/.superpowers/sdd/2026-10-30-durability-step3-escrow-fence-restore/task-6-review-opus.md`.</result> <usage><subagent_tokens>107440</subagent_tokens><tool_uses>23</tool_uses><duration_ms>295016</duration_ms></usage> </task-notification>

Attributed to this commit: 5.07 g CO₂e (565,311 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on durability-3a-escrow, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/layout/pubclass/publication_guard_test.go b/internal/layout/pubclass/publication_guard_test.go
new file mode 100644
index 000000000..d40512a62
--- /dev/null
+++ b/internal/layout/pubclass/publication_guard_test.go
@@ -0,0 +1,902 @@
+package pubclass
+
+import (
+ "fmt"
+ "go/ast"
+ "go/constant"
+ "go/token"
+ "go/types"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "golang.org/x/tools/go/cfg"
+ "golang.org/x/tools/go/packages"
+)
+
+const publicationModule = "github.com/carlosframework/platform"
+const publicationHostfiles = publicationModule + "/internal/hostfiles"
+const publicationClassifier = publicationModule + "/internal/layout/pubclass"
+const publicationFixturePrefix = "zz_publication_guard_fixture_"
+
+type publicationUnit struct {
+ pkg *packages.Package
+ name string
+ node ast.Node
+ body *ast.BlockStmt
+ graph *cfg.CFG
+}
+
+type publicationBinding struct {
+ unit *publicationUnit
+ node ast.Node
+ expr ast.Expr
+ definition bool
+}
+
+type publicationTarget struct {
+ identity string
+ kind string
+ offset int
+}
+
+type publicationProblem struct {
+ file, function, rule string
+ line int
+}
+
+func (p publicationProblem) String() string {
+ return fmt.Sprintf("%s:%d: %s: %s", p.file, p.line, p.function, p.rule)
+}
+
+type publicationGuard struct {
+ units []*publicationUnit
+ writes map[types.Object][]publicationBinding
+ parameters map[types.Object]bool
+ locals map[types.Object]*publicationUnit
+ aliases map[types.Object]map[publicationTarget]bool
+ publishers []*types.Pointer
+ bound map[ast.Expr]bool
+ fieldWrites map[types.Object]bool
+ problems []publicationProblem
+}
+
+func publicationObject(info *types.Info, e ast.Expr) types.Object {
+ switch e := ast.Unparen(e).(type) {
+ case *ast.Ident:
+ return info.ObjectOf(e)
+ case *ast.SelectorExpr:
+ return info.ObjectOf(e.Sel)
+ }
+ return nil
+}
+
+func publicationNamed(t types.Type, pkg, name string) bool {
+ if p, ok := t.(*types.Pointer); ok {
+ t = p.Elem()
+ }
+ n, ok := types.Unalias(t).(*types.Named)
+ return ok && n.Obj().Pkg() != nil && n.Obj().Pkg().Path() == pkg && n.Obj().Name() == name
+}
+
+func publicationFunction(info *types.Info, e ast.Expr, pkg, name string) bool {
+ fn, ok := publicationObject(info, e).(*types.Func)
+ return ok && fn.Pkg() != nil && fn.Pkg().Path() == pkg && fn.Name() == name
+}
+
+func publicationFunctionType(t types.Type) bool {
+ if t == nil {
+ return false
+ }
+ _, ok := t.Underlying().(*types.Signature)
+ return ok
+}
+
+func (g *publicationGuard) direct(u *publicationUnit, e ast.Expr) (publicationTarget, bool) {
+ info := u.pkg.TypesInfo
+ fn, ok := publicationObject(info, e).(*types.Func)
+ if !ok || fn.Pkg() == nil {
+ return publicationTarget{}, false
+ }
+ sig := fn.Type().(*types.Signature)
+ name := fn.Name()
+ identity := ""
+ if sig.Recv() == nil {
+ if fn.Pkg().Path() != publicationHostfiles {
+ return publicationTarget{}, false
+ }
+ switch name {
+ case "SyncDir", "SyncDirAt", "Seed", "Publish", "Run":
+ identity = name
+ default:
+ return publicationTarget{}, false
+ }
+ } else {
+ switch name {
+ case "Stage", "StagePlatform", "StageSealed":
+ default:
+ return publicationTarget{}, false
+ }
+ recv := sig.Recv().Type()
+ if publicationNamed(recv, publicationHostfiles, "Publisher") {
+ identity = "Publisher." + name
+ } else if publicationNamed(recv, publicationHostfiles, "Prepared") && name != "StageSealed" {
+ identity = "Prepared." + name
+ } else {
+ iface, ok := recv.Underlying().(*types.Interface)
+ if !ok {
+ return publicationTarget{}, false
+ }
+ for _, p := range g.publishers {
+ if types.Implements(p, iface) {
+ n := p.Elem().(*types.Named)
+ identity = n.Obj().Name() + "." + name
+ break
+ }
+ }
+ if identity == "" {
+ return publicationTarget{}, false
+ }
+ }
+ }
+ offset := 0
+ if sel, ok := ast.Unparen(e).(*ast.SelectorExpr); ok {
+ if selection := info.Selections[sel]; selection != nil && selection.Kind() == types.MethodExpr {
+ offset = 1
+ }
+ }
+ return publicationTarget{identity: identity, kind: name, offset: offset}, true
+}
+
+func (g *publicationGuard) targets(u *publicationUnit, e ast.Expr) map[publicationTarget]bool {
+ if p, ok := g.direct(u, e); ok {
+ return map[publicationTarget]bool{p: true}
+ }
+ return g.aliases[publicationObject(u.pkg.TypesInfo, e)]
+}
+
+func (g *publicationGuard) write(u *publicationUnit, n ast.Node, lhs, rhs ast.Expr, definition bool) {
+ obj := publicationObject(u.pkg.TypesInfo, lhs)
+ if obj == nil || obj.Name() == "_" {
+ return
+ }
+ if _, ok := obj.(*types.Var); !ok {
+ return
+ }
+ g.writes[obj] = append(g.writes[obj], publicationBinding{u, n, rhs, definition})
+ if publicationFunctionType(obj.Type()) {
+ g.bound[lhs] = true
+ if rhs != nil {
+ g.bound[rhs] = true
+ }
+ }
+ if definition && u.body != nil {
+ g.locals[obj] = u
+ }
+}
+
+func (g *publicationGuard) parameter(u *publicationUnit, fields *ast.FieldList) {
+ if fields == nil {
+ return
+ }
+ for _, field := range fields.List {
+ for _, id := range field.Names {
+ g.write(u, id, id, nil, true)
+ g.parameters[u.pkg.TypesInfo.ObjectOf(id)] = true
+ }
+ }
+}
+
+func publicationStruct(t types.Type) *types.Struct {
+ if t == nil {
+ return nil
+ }
+ if p, ok := t.(*types.Pointer); ok {
+ t = p.Elem()
+ }
+ s, _ := t.Underlying().(*types.Struct)
+ return s
+}
+
+func (g *publicationGuard) composite(u *publicationUnit, c *ast.CompositeLit) {
+ s := publicationStruct(u.pkg.TypesInfo.TypeOf(c))
+ if s == nil {
+ return
+ }
+ fields := map[types.Object]ast.Expr{}
+ for i, e := range c.Elts {
+ if kv, ok := e.(*ast.KeyValueExpr); ok {
+ fields[publicationObject(u.pkg.TypesInfo, kv.Key)] = kv.Value
+ } else if i < s.NumFields() {
+ fields[s.Field(i)] = e
+ }
+ }
+ for i := 0; i < s.NumFields(); i++ {
+ field := s.Field(i)
+ if publicationFunctionType(field.Type()) {
+ g.writes[field] = append(g.writes[field], publicationBinding{unit: u, node: c, expr: fields[field]})
+ if fields[field] != nil {
+ g.bound[fields[field]] = true
+ }
+ }
+ }
+ if publicationNamed(u.pkg.TypesInfo.TypeOf(c), publicationHostfiles, "PlatformRelay") {
+ for i := 0; i < s.NumFields(); i++ {
+ if s.Field(i).Name() == "Name" && !publicationPlatformName(u.pkg.TypesInfo, fields[s.Field(i)]) {
+ g.problem(u, c, "StagePlatform: PlatformRelay.Name is not WakeItem or AdoptionItem")
+ }
+ }
+ }
+}
+
+func (g *publicationGuard) zeroFields(u *publicationUnit, n ast.Node, t types.Type) {
+ if _, ok := t.(*types.Pointer); ok {
+ return
+ }
+ if publicationNamed(t, publicationHostfiles, "PlatformRelay") {
+ g.problem(u, n, "StagePlatform: zero PlatformRelay has no approved Name")
+ }
+ s := publicationStruct(t)
+ if s == nil {
+ return
+ }
+ for i := 0; i < s.NumFields(); i++ {
+ field := s.Field(i)
+ if publicationFunctionType(field.Type()) {
+ g.writes[field] = append(g.writes[field], publicationBinding{unit: u, node: n})
+ }
+ }
+}
+
+func (g *publicationGuard) collect(u *publicationUnit) {
+ info := u.pkg.TypesInfo
+ ast.Inspect(u.node, func(n ast.Node) bool {
+ if n == nil {
+ return false
+ }
+ if lit, ok := n.(*ast.FuncLit); ok {
+ child := &publicationUnit{pkg: u.pkg, name: u.name, node: lit.Body, body: lit.Body}
+ g.units = append(g.units, child)
+ g.parameter(child, lit.Type.Params)
+ g.parameter(child, lit.Type.Results)
+ g.collect(child)
+ return false
+ }
+ switch n := n.(type) {
+ case *ast.AssignStmt:
+ for i, lhs := range n.Lhs {
+ if sel, ok := lhs.(*ast.SelectorExpr); ok {
+ g.fieldWrites[publicationObject(info, sel.X)] = true
+ }
+ var rhs ast.Expr
+ if len(n.Rhs) == len(n.Lhs) {
+ rhs = n.Rhs[i]
+ }
+ id, _ := lhs.(*ast.Ident)
+ g.write(u, n, lhs, rhs, id != nil && info.Defs[id] != nil)
+ if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "Name" && publicationNamed(info.TypeOf(sel.X), publicationHostfiles, "PlatformRelay") && !publicationPlatformName(info, rhs) {
+ g.problem(u, n, "StagePlatform: PlatformRelay.Name is not WakeItem or AdoptionItem")
+ }
+ }
+ case *ast.ValueSpec:
+ for i, id := range n.Names {
+ var rhs ast.Expr
+ if len(n.Values) == len(n.Names) {
+ rhs = n.Values[i]
+ }
+ g.write(u, n, id, rhs, true)
+ if rhs == nil {
+ g.zeroFields(u, n, info.TypeOf(id))
+ }
+ }
+ case *ast.RangeStmt:
+ for _, e := range []ast.Expr{n.Key, n.Value} {
+ if e != nil {
+ id, _ := e.(*ast.Ident)
+ g.write(u, n, e, nil, id != nil && info.Defs[id] != nil)
+ }
+ }
+ case *ast.IncDecStmt:
+ g.write(u, n, n.X, nil, false)
+ case *ast.UnaryExpr:
+ if n.Op == token.AND {
+ g.write(u, n, n.X, nil, false)
+ if sel, ok := n.X.(*ast.SelectorExpr); ok && sel.Sel.Name == "Name" && publicationNamed(info.TypeOf(sel.X), publicationHostfiles, "PlatformRelay") {
+ g.problem(u, n, "StagePlatform: PlatformRelay.Name escapes by address")
+ }
+ }
+ case *ast.CompositeLit:
+ g.composite(u, n)
+ case *ast.CallExpr:
+ if id, ok := n.Fun.(*ast.Ident); ok {
+ if builtin, ok := info.Uses[id].(*types.Builtin); ok && builtin.Name() == "new" && len(n.Args) == 1 {
+ g.zeroFields(u, n, info.TypeOf(n.Args[0]))
+ }
+ }
+ sig, _ := info.TypeOf(n.Fun).Underlying().(*types.Signature)
+ if sig == nil {
+ break
+ }
+ for i, arg := range n.Args {
+ if i >= sig.Params().Len() {
+ break
+ }
+ param := sig.Params().At(i)
+ if publicationFunctionType(param.Type()) {
+ g.parameters[param] = true
+ g.writes[param] = append(g.writes[param], publicationBinding{unit: u, node: n, expr: arg})
+ g.bound[arg] = true
+ }
+ }
+ }
+ return true
+ })
+}
+
+func (g *publicationGuard) problem(u *publicationUnit, n ast.Node, rule string) {
+ if u.pkg.PkgPath == publicationHostfiles {
+ return
+ }
+ pos := u.pkg.Fset.Position(n.Pos())
+ g.problems = append(g.problems, publicationProblem{pos.Filename, u.pkg.Name + "." + u.name, rule, pos.Line})
+}
+
+func (g *publicationGuard) resolveAliases() {
+ for changed := true; changed; {
+ changed = false
+ for obj, writes := range g.writes {
+ if !publicationFunctionType(obj.Type()) {
+ continue
+ }
+ for _, w := range writes {
+ if w.expr == nil {
+ continue
+ }
+ for target := range g.targets(w.unit, w.expr) {
+ if g.aliases[obj] == nil {
+ g.aliases[obj] = map[publicationTarget]bool{}
+ }
+ if !g.aliases[obj][target] {
+ g.aliases[obj][target] = true
+ changed = true
+ }
+ }
+ }
+ }
+ }
+ for obj, targets := range g.aliases {
+ writes := g.writes[obj]
+ mixed := len(targets) != 1
+ for _, w := range writes {
+ if w.expr == nil || len(g.targets(w.unit, w.expr)) != 1 {
+ mixed = true
+ }
+ }
+ if mixed || g.parameters[obj] {
+ for _, w := range writes {
+ reason := "mixed callable alias "
+ if g.parameters[obj] {
+ reason = "unknown callable parameter "
+ }
+ g.problem(w.unit, w.node, reason+obj.Name())
+ }
+ }
+ }
+}
+
+func publicationPlatformName(info *types.Info, e ast.Expr) bool {
+ if e == nil {
+ return false
+ }
+ obj, ok := publicationObject(info, e).(*types.Const)
+ if !ok || obj.Pkg() == nil {
+ return false
+ }
+ return (obj.Pkg().Path() == publicationHostfiles && obj.Name() == "WakeItem") ||
+ (obj.Pkg().Path() == publicationModule+"/internal/instancekey" && obj.Name() == "AdoptionItem")
+}
+
+func (g *publicationGuard) skip(u *publicationUnit, e ast.Expr) bool {
+ if e == nil {
+ return false
+ }
+ if c, ok := ast.Unparen(e).(*ast.CallExpr); ok {
+ return publicationFunction(u.pkg.TypesInfo, c.Fun, publicationClassifier, "FilesDirSkip")
+ }
+ obj := publicationObject(u.pkg.TypesInfo, e)
+ if obj == nil || g.parameters[obj] || len(g.writes[obj]) == 0 {
+ return false
+ }
+ for _, w := range g.writes[obj] {
+ if w.expr == nil {
+ return false
+ }
+ c, ok := ast.Unparen(w.expr).(*ast.CallExpr)
+ if !ok || !publicationFunction(w.unit.pkg.TypesInfo, c.Fun, publicationClassifier, "FilesDirSkip") {
+ return false
+ }
+ }
+ return true
+}
+
+func publicationContains(n ast.Node, target ast.Node) bool {
+ found := false
+ ast.Inspect(n, func(n ast.Node) bool {
+ if n == target {
+ found = true
+ }
+ if _, ok := n.(*ast.FuncLit); ok {
+ return false
+ }
+ return !found
+ })
+ return found
+}
+
+func publicationBlock(graph *cfg.CFG, n ast.Node) *cfg.Block {
+ for _, b := range graph.Blocks {
+ for _, node := range b.Nodes {
+ if publicationContains(node, n) {
+ return b
+ }
+ }
+ }
+ return nil
+}
+
+func publicationReach(from, to, without *cfg.Block) bool {
+ seen := map[*cfg.Block]bool{}
+ var visit func(*cfg.Block) bool
+ visit = func(b *cfg.Block) bool {
+ if b == nil || b == without || seen[b] {
+ return false
+ }
+ if b == to {
+ return true
+ }
+ seen[b] = true
+ for _, next := range b.Succs {
+ if visit(next) {
+ return true
+ }
+ }
+ return false
+ }
+ return visit(from)
+}
+
+func (g *publicationGuard) dominates(u *publicationUnit, ifs *ast.IfStmt, site ast.Node) bool {
+ // Require a preceding guard in the same or an enclosing block, then
+ // check the graph for goto, break and continue edges around that guard.
+ if ifs.End() >= site.Pos() {
+ return false
+ }
+ enclosing := false
+ ast.Inspect(u.body, func(n ast.Node) bool {
+ if _, ok := n.(*ast.FuncLit); ok {
+ return false
+ }
+ if b, ok := n.(*ast.BlockStmt); ok {
+ for _, st := range b.List {
+ if st == ifs && publicationContains(b, site) {
+ enclosing = true
+ }
+ }
+ }
+ return true
+ })
+ if !enclosing {
+ return false
+ }
+ if u.graph == nil {
+ u.graph = cfg.New(u.body, func(*ast.CallExpr) bool { return true })
+ }
+ check, call := publicationBlock(u.graph, ifs.Cond), publicationBlock(u.graph, site)
+ if check == nil || call == nil || len(check.Succs) != 2 {
+ return false
+ }
+ if publicationReach(u.graph.Blocks[0], call, check) {
+ return false
+ }
+ // Successor zero is the mismatch (then) branch. It must not get to
+ // the operation without evaluating this guard again.
+ return !publicationReach(check.Succs[0], call, check)
+}
+
+func publicationExits(b *ast.BlockStmt) bool {
+ if b == nil || len(b.List) == 0 {
+ return false
+ }
+ switch st := b.List[len(b.List)-1].(type) {
+ case *ast.ReturnStmt:
+ return true
+ case *ast.BranchStmt:
+ return st.Tok == token.CONTINUE || st.Tok == token.BREAK
+ }
+ return false
+}
+
+func (g *publicationGuard) singleLocal(u *publicationUnit, e ast.Expr, before token.Pos) types.Object {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ if !ok {
+ return nil
+ }
+ obj := u.pkg.TypesInfo.ObjectOf(id)
+ writes := g.writes[obj]
+ if g.locals[obj] != u || len(writes) != 1 || !writes[0].definition || writes[0].node.Pos() >= before {
+ return nil
+ }
+ return obj
+}
+
+func (g *publicationGuard) checkedCall(u *publicationUnit, e ast.Expr, before token.Pos, pkg, name string) *ast.CallExpr {
+ if e == nil {
+ return nil
+ }
+ if c, ok := ast.Unparen(e).(*ast.CallExpr); ok && publicationFunction(u.pkg.TypesInfo, c.Fun, pkg, name) {
+ return c
+ }
+ obj := g.singleLocal(u, e, before)
+ if obj == nil {
+ return nil
+ }
+ w := g.writes[obj][0]
+ if w.expr == nil {
+ return nil
+ }
+ c, ok := ast.Unparen(w.expr).(*ast.CallExpr)
+ if !ok || !publicationFunction(w.unit.pkg.TypesInfo, c.Fun, pkg, name) {
+ return nil
+ }
+ return c
+}
+
+func publicationMismatch(info *types.Info, ifs *ast.IfStmt, pkg, name string) ast.Expr {
+ c, ok := ast.Unparen(ifs.Cond).(*ast.BinaryExpr)
+ if !ok || c.Op != token.NEQ || !publicationExits(ifs.Body) {
+ return nil
+ }
+ isExpected := func(e ast.Expr) bool {
+ obj := publicationObject(info, e)
+ if pkg == "" {
+ _, ok := obj.(*types.Nil)
+ return ok
+ }
+ v, ok := obj.(*types.Const)
+ return ok && v.Pkg() != nil && v.Pkg().Path() == pkg && v.Name() == name
+ }
+ if isExpected(c.Y) {
+ return c.X
+ }
+ if isExpected(c.X) {
+ return c.Y
+ }
+ return nil
+}
+
+// Files publishers stage files-relative names; Of also accepts their
+// inventory-relative form, host+"/"+x. Only that exact, stable mapping is
+// recognized, never a substring occurrence of x in another expression.
+func (g *publicationGuard) classifiedPath(u *publicationUnit, c *ast.CallExpr, obj types.Object) bool {
+ info := u.pkg.TypesInfo
+ if publicationObject(info, c.Args[2]) == obj {
+ return true
+ }
+ suffix, ok := ast.Unparen(c.Args[2]).(*ast.BinaryExpr)
+ if !ok || suffix.Op != token.ADD || publicationObject(info, suffix.Y) != obj {
+ return false
+ }
+ prefix, ok := ast.Unparen(suffix.X).(*ast.BinaryExpr)
+ if !ok || prefix.Op != token.ADD {
+ return false
+ }
+ sep := info.Types[prefix.Y].Value
+ if sep == nil || sep.Kind() != constant.String || constant.StringVal(sep) != "/" {
+ return false
+ }
+ host := publicationObject(info, c.Args[1])
+ writes := g.writes[host]
+ return host != nil && publicationObject(info, prefix.X) == host && len(writes) == 1 && writes[0].definition && writes[0].node.Pos() < c.Pos()
+}
+
+func (g *publicationGuard) classified(u *publicationUnit, site ast.Node, path ast.Expr) bool {
+ if u.body == nil {
+ return false
+ }
+ obj := g.singleLocal(u, path, site.Pos())
+ if obj == nil {
+ return false
+ }
+ good := false
+ ast.Inspect(u.body, func(n ast.Node) bool {
+ if _, ok := n.(*ast.FuncLit); ok {
+ return false
+ }
+ ifs, ok := n.(*ast.IfStmt)
+ if !ok {
+ return true
+ }
+ expr := publicationMismatch(u.pkg.TypesInfo, ifs, publicationClassifier, "App")
+ c := g.checkedCall(u, expr, ifs.Cond.Pos(), publicationClassifier, "Of")
+ if c != nil && len(c.Args) == 4 && g.classifiedPath(u, c, obj) &&
+ g.writes[obj][0].node.Pos() < c.Pos() && g.dominates(u, ifs, site) {
+ good = true
+ }
+ return true
+ })
+ return good
+}
+
+func (g *publicationGuard) refused(u *publicationUnit, site ast.Node, root ast.Expr) bool {
+ if u.body == nil {
+ return false
+ }
+ obj := publicationObject(u.pkg.TypesInfo, root)
+ if _, ok := ast.Unparen(root).(*ast.Ident); !ok || obj == nil || g.locals[obj] != u {
+ return false
+ }
+ good := false
+ ast.Inspect(u.body, func(n ast.Node) bool {
+ if _, ok := n.(*ast.FuncLit); ok {
+ return false
+ }
+ ifs, ok := n.(*ast.IfStmt)
+ if !ok {
+ return true
+ }
+ expr := publicationMismatch(u.pkg.TypesInfo, ifs, "", "")
+ c := g.checkedCall(u, expr, ifs.Cond.Pos(), publicationHostfiles, "RefuseSecretsAt")
+ if c != nil && len(c.Args) == 4 && publicationObject(u.pkg.TypesInfo, c.Args[1]) == obj &&
+ g.unchanged(obj, c.Pos(), site.End()) && g.dominates(u, ifs, site) {
+ good = true
+ }
+ return true
+ })
+ return good
+}
+
+func (g *publicationGuard) unchanged(obj types.Object, from, to token.Pos) bool {
+ for _, w := range g.writes[obj] {
+ if w.node.Pos() >= from && w.node.Pos() < to {
+ return false
+ }
+ }
+ return true
+}
+
+func (g *publicationGuard) runSkip(u *publicationUnit, e ast.Expr) bool {
+ c, ok := ast.Unparen(e).(*ast.CompositeLit)
+ if !ok {
+ obj := publicationObject(u.pkg.TypesInfo, e)
+ if obj == nil || g.parameters[obj] || g.fieldWrites[obj] || len(g.writes[obj]) == 0 {
+ return false
+ }
+ for _, w := range g.writes[obj] {
+ if w.expr == nil {
+ return false
+ }
+ c, ok := ast.Unparen(w.expr).(*ast.CompositeLit)
+ if !ok || !g.runSkip(w.unit, c) {
+ return false
+ }
+ }
+ return true
+ }
+ for _, e := range c.Elts {
+ if kv, ok := e.(*ast.KeyValueExpr); ok {
+ if id, ok := kv.Key.(*ast.Ident); ok && id.Name == "Skip" {
+ return g.skip(u, kv.Value)
+ }
+ }
+ }
+ return false
+}
+
+func (g *publicationGuard) check(u *publicationUnit, c *ast.CallExpr, target publicationTarget) {
+ args := c.Args
+ if target.offset > len(args) {
+ g.problem(u, c, "unknown staging arguments")
+ return
+ }
+ args = args[target.offset:]
+ switch target.kind {
+ case "Stage":
+ if len(args) < 2 || !g.classified(u, c, args[1]) {
+ g.problem(u, c, "Stage: path has no dominating, single-assignment App classification")
+ }
+ case "StagePlatform":
+ if len(args) < 2 || !publicationPlatformName(u.pkg.TypesInfo, args[1]) {
+ g.problem(u, c, "StagePlatform: name is not WakeItem or AdoptionItem")
+ }
+ case "StageSealed":
+ if len(args) < 2 || !publicationNamed(u.pkg.TypesInfo.TypeOf(args[1]), publicationClassifier, "SealedRel") {
+ g.problem(u, c, "StageSealed: argument is not SealedRel")
+ }
+ default:
+ rootIndex, skipIndex := 2, 3
+ if target.kind == "Seed" {
+ skipIndex = 4
+ }
+ if target.kind == "Publish" {
+ rootIndex, skipIndex = 3, 4
+ }
+ valid := false
+ if len(args) > skipIndex {
+ if target.kind == "Run" {
+ valid = g.runSkip(u, args[skipIndex])
+ } else {
+ valid = g.skip(u, args[skipIndex])
+ }
+ }
+ if !valid && len(args) > rootIndex {
+ valid = g.refused(u, c, args[rootIndex])
+ }
+ if !valid {
+ g.problem(u, c, target.kind+": skip is not FilesDirSkip and root has no dominating refusal")
+ }
+ }
+}
+
+func publicationProblems(pkgs []*packages.Package) []publicationProblem {
+ g := &publicationGuard{writes: map[types.Object][]publicationBinding{}, parameters: map[types.Object]bool{}, locals: map[types.Object]*publicationUnit{}, aliases: map[types.Object]map[publicationTarget]bool{}, bound: map[ast.Expr]bool{}, fieldWrites: map[types.Object]bool{}}
+ for _, pkg := range pkgs {
+ if pkg.PkgPath == publicationHostfiles {
+ for _, name := range []string{"Publisher", "Prepared"} {
+ if obj := pkg.Types.Scope().Lookup(name); obj != nil {
+ g.publishers = append(g.publishers, types.NewPointer(obj.Type()))
+ }
+ }
+ }
+ }
+ for _, pkg := range pkgs {
+ for _, file := range pkg.Syntax {
+ for _, decl := range file.Decls {
+ switch d := decl.(type) {
+ case *ast.FuncDecl:
+ if d.Body == nil {
+ continue
+ }
+ u := &publicationUnit{pkg: pkg, name: d.Name.Name, node: d.Body, body: d.Body}
+ g.units = append(g.units, u)
+ g.parameter(u, d.Recv)
+ g.parameter(u, d.Type.Params)
+ g.parameter(u, d.Type.Results)
+ g.collect(u)
+ case *ast.GenDecl:
+ for _, spec := range d.Specs {
+ v, ok := spec.(*ast.ValueSpec)
+ if !ok {
+ continue
+ }
+ u := &publicationUnit{pkg: pkg, name: "var " + v.Names[0].Name, node: v}
+ g.units = append(g.units, u)
+ g.collect(u)
+ }
+ }
+ }
+ }
+ }
+ g.resolveAliases()
+ for _, u := range g.units {
+ if u.pkg.PkgPath == publicationHostfiles {
+ continue
+ }
+ var stack []ast.Node
+ ast.Inspect(u.node, func(n ast.Node) bool {
+ if n == nil {
+ stack = stack[:len(stack)-1]
+ return false
+ }
+ if _, ok := n.(*ast.FuncLit); ok {
+ return false
+ }
+ var parent ast.Node
+ if len(stack) > 0 {
+ parent = stack[len(stack)-1]
+ }
+ stack = append(stack, n)
+ if c, ok := n.(*ast.CallExpr); ok {
+ for target := range g.targets(u, c.Fun) {
+ g.check(u, c, target)
+ }
+ }
+ e, ok := n.(ast.Expr)
+ if !ok || len(g.targets(u, e)) == 0 {
+ return true
+ }
+ if sel, ok := parent.(*ast.SelectorExpr); ok && sel.Sel == e {
+ return true
+ }
+ if _, ok := parent.(*ast.ParenExpr); ok {
+ return true
+ }
+ if call, ok := parent.(*ast.CallExpr); ok && call.Fun == e {
+ return true
+ }
+ if !g.bound[e] {
+ g.problem(u, e, "unknown callable escape")
+ }
+ return true
+ })
+ }
+ slices.SortFunc(g.problems, func(a, b publicationProblem) int { return strings.Compare(a.String(), b.String()) })
+ return slices.Compact(g.problems)
+}
+
+func TestEveryStagingOperationIsClassified(t *testing.T) {
+ dir, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ root := filepath.Clean(filepath.Join(dir, "../../.."))
+ fixtures, err := filepath.Glob(filepath.Join(dir, "testdata/publication_guard/*.go"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ overlay := map[string][]byte{}
+ for _, file := range fixtures {
+ body, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ overlay[filepath.Join(root, "internal/host", publicationFixturePrefix+filepath.Base(file))] = body
+ }
+ env := slices.DeleteFunc(os.Environ(), func(s string) bool {
+ return strings.HasPrefix(s, "GOOS=") || strings.HasPrefix(s, "GOARCH=") || strings.HasPrefix(s, "CGO_ENABLED=")
+ })
+ env = append(env, "GOOS=linux", "GOARCH=amd64", "CGO_ENABLED=0")
+ pkgs, err := packages.Load(&packages.Config{Dir: root, Env: env, Overlay: overlay, Tests: false,
+ Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports}, publicationModule+"/...")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if packages.PrintErrors(pkgs) > 0 {
+ t.Fatal("publication guard could not type-check the module and fixtures")
+ }
+ problems := publicationProblems(pkgs)
+ byFixture := map[string][]publicationProblem{}
+ for _, p := range problems {
+ base := filepath.Base(p.file)
+ if strings.HasPrefix(base, publicationFixturePrefix) {
+ byFixture[strings.TrimPrefix(base, publicationFixturePrefix)] = append(byFixture[strings.TrimPrefix(base, publicationFixturePrefix)], p)
+ } else {
+ t.Error(p.String())
+ }
+ }
+ want := map[string][]string{
+ "clean.go": nil,
+ "unclassified.go": {"zzUnclassified:Stage:", "zzNondominating:Stage:", "zzBypass:Stage:", "zzWrongBreak:Stage:", "zzWrongInventoryPath:Stage:"},
+ "ignored.go": {"zzIgnored:Stage:", "zzSwallowed:Stage:"},
+ "nilvar.go": {"zzNilVar:SyncDirAt:", "zzMixedSkip:SyncDirAt:", "zzUncheckedRefusal:SyncDirAt:", "zzWrongRoot:SyncDirAt:", "zzNilRun:Run:"},
+ "prepared.go": {"zzPrepared:Stage:", "zzPrepared:StagePlatform:", "zzRelay:StagePlatform:", "zzRelayAssign:StagePlatform:", "zzRelayZero:StagePlatform:"},
+ "reassign.go": {"zzReassign:Stage:", "zzReassignClass:Stage:", "zzReassignRoot:SyncDirAt:", "zzReassignHost:Stage:", "zzReassignOptions:Run:"},
+ "mixedalias.go": {"zzMixedAlias:mixed callable alias", "zzMixedAliasCall:SyncDirAt:", "zzMethodAlias:StagePlatform:", "zzFieldAlias:StagePlatform:", "zzPassAlias:unknown callable parameter", "zzReturnAlias:unknown callable escape", "zzSliceAlias:unknown callable escape"},
+ "wrapper.go": {"zzWrapper:SyncDirAt:"},
+ "iface.go": {"zzIface:StagePlatform:", "zzIface:StagePlatform:", "zzIfacePrepared:Stage:"},
+ }
+ if len(fixtures) != len(want) {
+ t.Fatalf("loaded %d fixtures, want %d", len(fixtures), len(want))
+ }
+ for fixture, names := range want {
+ t.Run(fixture, func(t *testing.T) {
+ got := byFixture[fixture]
+ if len(names) == 0 && len(got) != 0 {
+ t.Fatalf("clean fixture reported: %v", got)
+ }
+ remaining := slices.Clone(got)
+ for _, want := range names {
+ function, rule, _ := strings.Cut(want, ":")
+ i := slices.IndexFunc(remaining, func(p publicationProblem) bool {
+ return p.function == "host."+function && strings.HasPrefix(p.rule, rule)
+ })
+ if i < 0 {
+ t.Errorf("guard did not report %s; got %v", want, got)
+ } else {
+ remaining = slices.Delete(remaining, i, i+1)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/clean.go b/internal/layout/pubclass/testdata/publication_guard/clean.go
new file mode 100644
index 000000000..6132606c4
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/clean.go
@@ -0,0 +1,99 @@
+package host
+
+import (
+ "context"
+ "os"
+
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancekey"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+)
+
+func zzClean(ctx context.Context, p *hostfiles.Publisher, q *hostfiles.Prepared, root *os.File, host, path string) error {
+ x := path
+ if c := pubclass.Of(pubclass.Nested, host, x, false); c != pubclass.App {
+ return nil
+ }
+ if err := p.Stage(ctx, x, nil, 0600, false); err != nil {
+ return err
+ }
+ if err := q.Stage(ctx, x, nil, 0600); err != nil {
+ return err
+ }
+ stage := p.Stage
+ if err := stage(ctx, x, nil, 0600, false); err != nil {
+ return err
+ }
+ if err := q.StagePlatform(ctx, hostfiles.WakeItem, nil); err != nil {
+ return err
+ }
+ var stager hostfiles.PlatformStager = p
+ if err := stager.StagePlatform(ctx, instancekey.AdoptionItem, nil); err != nil {
+ return err
+ }
+ _ = &hostfiles.PlatformRelay{Name: instancekey.AdoptionItem, Stage: p}
+ if r, ok := pubclass.SealedPath(pubclass.Nested, host, host+".env"); ok {
+ if err := p.StageSealed(ctx, r, nil, nil); err != nil {
+ return err
+ }
+ }
+ skip := pubclass.FilesDirSkip(pubclass.Nested, host)
+ _, err := hostfiles.SyncDirAt(ctx, p, root, skip)
+ return err
+}
+
+func zzCleanRefusal(ctx context.Context, p *hostfiles.Publisher, root *os.File, host string) error {
+ if err := hostfiles.RefuseSecretsAt(ctx, root, pubclass.Nested, host); err != nil {
+ return err
+ }
+ _, err := hostfiles.Seed(ctx, p, root, hostfiles.WakeState{}, nil)
+ return err
+}
+
+func zzCleanLoop(ctx context.Context, p *hostfiles.Publisher, host string, paths []string) error {
+ for _, x := range paths {
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ continue
+ }
+ if err := p.Stage(ctx, x, nil, 0600, false); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func zzCleanRun(ctx context.Context, p *hostfiles.Publisher, host, dir string) error {
+ return hostfiles.Run(ctx, p, dir, hostfiles.Options{Skip: pubclass.FilesDirSkip(pubclass.Nested, host)})
+}
+
+func zzCleanOtherCalls(ctx context.Context, p *hostfiles.Publisher, root *os.File, host, dir string) error {
+ skip := pubclass.FilesDirSkip(pubclass.Nested, host)
+ if _, err := hostfiles.SyncDir(ctx, p, dir, skip); err != nil {
+ return err
+ }
+ if _, _, err := hostfiles.Publish(ctx, nil, "files/0/", dir, skip); err != nil {
+ return err
+ }
+ stage := (*hostfiles.Publisher).StagePlatform
+ return stage(p, ctx, hostfiles.WakeItem, nil)
+}
+
+func zzCleanBreak(ctx context.Context, p *hostfiles.Publisher, host string, paths []string) error {
+ for _, x := range paths {
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ break
+ }
+ if err := p.Stage(ctx, x, nil, 0600, false); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func zzCleanInventoryPath(ctx context.Context, p *hostfiles.Prepared, host, path string) error {
+ x := path
+ if pubclass.Of(pubclass.Nested, host, host+"/"+x, false) != pubclass.App {
+ return nil
+ }
+ return p.Stage(ctx, x, nil, 0600)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/iface.go b/internal/layout/pubclass/testdata/publication_guard/iface.go
new file mode 100644
index 000000000..4992e99a7
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/iface.go
@@ -0,0 +1,21 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+)
+
+func zzIface(ctx context.Context, p *hostfiles.Publisher) {
+ var local interface {
+ StagePlatform(context.Context, string, []byte) error
+ } = p
+ local.StagePlatform(ctx, hostfiles.EnvItem, nil)
+ var named hostfiles.PlatformStager = p
+ named.StagePlatform(ctx, hostfiles.EnvItem, nil)
+}
+func zzIfacePrepared(ctx context.Context, p *hostfiles.Prepared, path string) {
+ var local interface {
+ Stage(context.Context, string, []byte, uint32) error
+ } = p
+ local.Stage(ctx, path, nil, 0600)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/ignored.go b/internal/layout/pubclass/testdata/publication_guard/ignored.go
new file mode 100644
index 000000000..612ad9285
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/ignored.go
@@ -0,0 +1,20 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+)
+
+func zzIgnored(ctx context.Context, p *hostfiles.Publisher, host, path string) error {
+ x := path
+ pubclass.Of(pubclass.Nested, host, x, false)
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+func zzSwallowed(ctx context.Context, p *hostfiles.Publisher, host, path string) error {
+ x := path
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ _ = x
+ }
+ return p.Stage(ctx, x, nil, 0600, false)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/mixedalias.go b/internal/layout/pubclass/testdata/publication_guard/mixedalias.go
new file mode 100644
index 000000000..024082b8a
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/mixedalias.go
@@ -0,0 +1,40 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "os"
+)
+
+var zzStage = hostfiles.SyncDirAt
+
+func zzMySync(context.Context, *hostfiles.Publisher, *os.File, func(string, bool) bool) (hostfiles.SyncStats, error) {
+ return hostfiles.SyncStats{}, nil
+}
+func zzMixedAlias() { zzStage = zzMySync }
+func zzMixedAliasCall(ctx context.Context, p *hostfiles.Publisher, root *os.File) {
+ zzStage(ctx, p, root, nil)
+}
+
+type zzAliasHolder struct {
+ stage func(context.Context, string, []byte) error
+}
+
+func zzMethodAlias(ctx context.Context, p *hostfiles.Publisher) {
+ f := p.StagePlatform
+ f(ctx, hostfiles.EnvItem, nil)
+}
+func zzFieldAlias(ctx context.Context, p *hostfiles.Publisher) {
+ h := zzAliasHolder{stage: p.StagePlatform}
+ h.stage(ctx, hostfiles.EnvItem, nil)
+}
+func zzUnknownAlias(f func(context.Context, string, []byte) error) {}
+func zzPassAlias(p *hostfiles.Publisher) { zzUnknownAlias(p.StagePlatform) }
+
+func zzReturnAlias(p *hostfiles.Publisher) func(context.Context, string, []byte) error {
+ return p.StagePlatform
+}
+func zzSliceAlias(ctx context.Context, p *hostfiles.Publisher) {
+ f := []func(context.Context, string, []byte) error{p.StagePlatform}
+ f[0](ctx, hostfiles.EnvItem, nil)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/nilvar.go b/internal/layout/pubclass/testdata/publication_guard/nilvar.go
new file mode 100644
index 000000000..822d33c47
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/nilvar.go
@@ -0,0 +1,34 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+ "os"
+)
+
+func zzNilVar(ctx context.Context, p *hostfiles.Publisher, root *os.File) {
+ var skip func(string, bool) bool
+ hostfiles.SyncDirAt(ctx, p, root, skip)
+}
+func zzMixedSkip(ctx context.Context, p *hostfiles.Publisher, root *os.File, host string, bad bool) {
+ skip := pubclass.FilesDirSkip(pubclass.Nested, host)
+ if bad {
+ skip = nil
+ }
+ hostfiles.SyncDirAt(ctx, p, root, skip)
+}
+func zzUncheckedRefusal(ctx context.Context, p *hostfiles.Publisher, root *os.File, host string) {
+ hostfiles.RefuseSecretsAt(ctx, root, pubclass.Nested, host)
+ hostfiles.SyncDirAt(ctx, p, root, nil)
+}
+func zzWrongRoot(ctx context.Context, p *hostfiles.Publisher, root, other *os.File, host string) error {
+ if err := hostfiles.RefuseSecretsAt(ctx, other, pubclass.Nested, host); err != nil {
+ return err
+ }
+ _, err := hostfiles.SyncDirAt(ctx, p, root, nil)
+ return err
+}
+func zzNilRun(ctx context.Context, p *hostfiles.Publisher, dir string) error {
+ return hostfiles.Run(ctx, p, dir, hostfiles.Options{})
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/prepared.go b/internal/layout/pubclass/testdata/publication_guard/prepared.go
new file mode 100644
index 000000000..ffa3c459f
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/prepared.go
@@ -0,0 +1,17 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+)
+
+func zzPrepared(ctx context.Context, p *hostfiles.Prepared, path string) {
+ p.Stage(ctx, path, nil, 0600)
+ p.StagePlatform(ctx, hostfiles.EnvItem, nil)
+}
+func zzRelay(p *hostfiles.Publisher) {
+ _ = &hostfiles.PlatformRelay{Name: hostfiles.EnvItem, Stage: p}
+}
+func zzRelayAssign(r *hostfiles.PlatformRelay) { r.Name = hostfiles.EnvItem }
+
+func zzRelayZero() { _ = new(hostfiles.PlatformRelay) }
diff --git a/internal/layout/pubclass/testdata/publication_guard/reassign.go b/internal/layout/pubclass/testdata/publication_guard/reassign.go
new file mode 100644
index 000000000..688317678
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/reassign.go
@@ -0,0 +1,48 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+ "os"
+)
+
+func zzReassign(ctx context.Context, p *hostfiles.Publisher, host, path string) error {
+ x := path
+ if c := pubclass.Of(pubclass.Nested, host, x, false); c != pubclass.App {
+ return nil
+ }
+ x = host + ".env"
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+func zzReassignClass(ctx context.Context, p *hostfiles.Publisher, host, path string) error {
+ x := path
+ c := pubclass.Of(pubclass.Nested, host, x, false)
+ c = pubclass.App
+ if c != pubclass.App {
+ return nil
+ }
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+func zzReassignRoot(ctx context.Context, p *hostfiles.Publisher, root, other *os.File, host string) error {
+ if err := hostfiles.RefuseSecretsAt(ctx, root, pubclass.Nested, host); err != nil {
+ return err
+ }
+ root = other
+ _, err := hostfiles.SyncDirAt(ctx, p, root, nil)
+ return err
+}
+
+func zzReassignHost(ctx context.Context, p *hostfiles.Prepared, host, path string) error {
+ x := path
+ if pubclass.Of(pubclass.Nested, host, host+"/"+x, false) != pubclass.App {
+ return nil
+ }
+ host = "other.example.com"
+ return p.Stage(ctx, x, nil, 0600)
+}
+func zzReassignOptions(ctx context.Context, p *hostfiles.Publisher, host, dir string) error {
+ o := hostfiles.Options{Skip: pubclass.FilesDirSkip(pubclass.Nested, host)}
+ o.Skip = nil
+ return hostfiles.Run(ctx, p, dir, o)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/unclassified.go b/internal/layout/pubclass/testdata/publication_guard/unclassified.go
new file mode 100644
index 000000000..149b91cbe
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/unclassified.go
@@ -0,0 +1,57 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/layout/pubclass"
+)
+
+func zzUnclassified(ctx context.Context, p *hostfiles.Publisher, host, path, other string) error {
+ x := path
+ if c := pubclass.Of(pubclass.Nested, host, x, false); c != pubclass.App {
+ return nil
+ }
+ if err := p.Stage(ctx, x, nil, 0600, false); err != nil {
+ return err
+ }
+ y := other
+ return p.Stage(ctx, y, nil, 0600, false)
+}
+func zzNondominating(ctx context.Context, p *hostfiles.Publisher, host, path string, check bool) error {
+ x := path
+ if check {
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ return nil
+ }
+ }
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+func zzBypass(ctx context.Context, p *hostfiles.Publisher, host, path string, bypass bool) error {
+ x := path
+ if bypass {
+ goto stage
+ }
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ return nil
+ }
+stage:
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+func zzWrongBreak(ctx context.Context, p *hostfiles.Publisher, host, path string) error {
+ x := path
+ for {
+ if pubclass.Of(pubclass.Nested, host, x, false) != pubclass.App {
+ break
+ }
+ break
+ }
+ return p.Stage(ctx, x, nil, 0600, false)
+}
+
+func zzWrongInventoryPath(ctx context.Context, p *hostfiles.Prepared, host, path string) error {
+ x := path
+ if pubclass.Of(pubclass.Nested, host, "unrelated/"+x, false) != pubclass.App {
+ return nil
+ }
+ return p.Stage(ctx, x, nil, 0600)
+}
diff --git a/internal/layout/pubclass/testdata/publication_guard/wrapper.go b/internal/layout/pubclass/testdata/publication_guard/wrapper.go
new file mode 100644
index 000000000..873673802
--- /dev/null
+++ b/internal/layout/pubclass/testdata/publication_guard/wrapper.go
@@ -0,0 +1,11 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "os"
+)
+
+func zzWrapper(ctx context.Context, p *hostfiles.Publisher, root *os.File, skip func(string, bool) bool) {
+ hostfiles.SyncDirAt(ctx, p, root, skip)
+}