carlos / platform Public

Task 6b fix round 1: the guard names Sealer field uses and sealWith outside their owners, and the background walks fail the job on any seal key error but an absent key

The guard collects every use of appconfig.Sealer's fields, by identity, and
allows it only in NewSealer and Sealer's own methods, so a second
constructor that fills a zero Sealer field by field is named; sealWith is
guarded, allowed only in SealBound and SealUnbound. Two fixtures: a
field-assignment constructor and an exported sealWith helper. NewSealer's
literal must be seen exactly once.

sealKeyAbsent (a keyless fleet, no deployment key, no live row) is the only
case the relay reconcile and plan storage skip quietly; a store or registry
read error or errFleetNotOwned fails the job again, as before fleet keys.
relaySealKey wraps only the absent states in errRelaySealKey.

Account lock entry points: unchanged from the Task 6b commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4abe5168f45a1fd11f5b1b5e2de5eedf239c5382 parent 72fde1a
7 files changed, +281 −28
  • internal/console/fleetsecrets_relay_test.go +131 −0
  • internal/console/planstorage.go +12 −5
  • internal/console/relayops.go +17 −10
  • internal/console/sealkey.go +14 −0
  • internal/console/sealkey_guard_test.go +81 −13
  • internal/console/testdata/sealguard/ctor/fieldassign.go +12 −0
  • internal/console/testdata/sealguard/ctor/sealwith.go +14 −0

Intent

Human

<task-notification> <task-id>afde850d773aca226</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/afde850d773aca226.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6b: relay, plan storage, guard" 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>Status: DONE_WITH_CONCERNS Commit: 72fde1a9 (BASE bdb89206), one commit. Tests: the 10 new tests and the guard pass; 9 of them failed at BASE first. The plan storage test already passed at BASE because 6a wired the skip; mutation M9 shows it does real work. The guard catches the planted `appconfig.SealBound` in apimail.go and 11 other mutations were each caught. The Relay/Store/Mail/Scan/Plan/Team set, a wider console run (477 s), the copy gate, build, vet, gofmt and the darwin/windows/arm64 builds all pass. Two old relay tests that enabled the relay for apps with no live row were changed to create the app first. Relay reconcile: at BASE it did not re-seal a stale envelope. I added a `sealed_to` check, with a missing `sealed_to` read as the deployment key, so platform apps' existing envelopes are left alone. A fleet app's relay credential now heals by itself once its fleet has a key, so FSK-C47 and FSK-C60 need no relay step. Concerns (full list in the report): 1. Plan storage skips a keyless-fleet app as the brief says, so its storage deny is never applied or lifted until the fleet registers a key. Requiring a key only when the regrant would mint, as the scan doors now do, would close this. Your call. 2. On a keyless fleet, a released team environment's relay identity stays in the aggregate until a key is registered. Low risk: nobody but platform boxes could ever open it. 3. The reconcile now skips trashed apps with a log line each pass. 4. Repeating an enable on a keyless fleet is now refused. Rotate no longer refuses up front when the console has no deployment key. 5. Guard deviations: empty `Sealer{}` literals are allowed anywhere; the allowlist is per function and per guarded call; types are checked on linux files only, with a text check for the rest; fixtures are overlays on the real packages. Scan enforce skips the key in both directions, not only off. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6b-report.md</result> <usage><subagent_tokens>333622</subagent_tokens><tool_uses>127</tool_uses><duration_ms>2738103</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a882ab414e6435b4f</task-id> <tool-use-id>toolu_019HVZ11ZHck3c1qRL2SH19q</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/a882ab414e6435b4f.output</output-file> <status>completed</status> <summary>Agent "Review Task 6b (spec + quality)" 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:** ❌ Issues found, one item. The rule that the guard must catch "a second constructor" (I1) is only met for the `Sealer{...}` literal form. Everything else in 6b's scope matches the brief or the ledger rulings. **Task quality:** Needs fixes. **Important:** 1. **The guard can be bypassed from inside appconfig** (`sealkey_guard_test.go:67`, `:212-223`). A new constructor can fill a zero `Sealer` by field assignment, or a new exported helper can call the unexported `sealWith` (`crypto.go:206`). Either gives console code a sealer for any key, and the guard names nothing. Fix: add `sealWith` to the guarded functions, allowed only in `SealBound` and `SealUnbound`; flag every use of `Sealer`'s fields outside `NewSealer` and `Sealer`'s own methods; add a fixture for each. 2. **The background walks now hide real failures** (`relayops.go:516-528`, `:1597-1603`, `planstorage.go:98-101`). The relay reconcile and plan storage treat every `sealKeyFor` failure as "skip, log, no `jobFailed`". That includes store and registry read errors and `errFleetNotOwned`, which is a tenancy anomaly. Before 6b, plan storage called `jobFailed` on these. Fix: skip quietly only for the keyless fleet, no deployment key and unknown app cases; keep `jobFailed` for the rest. **Your five named risks:** - **(a) Guard bypass:** yes, the one in Important 1. A narrower Minor one: a package whose every file is excluded on linux never appears in `go list ./...`, so the guard cannot see it. I confirmed that on a scratch module, since removed. The other cases hold: method values, function variables holding `SealBound`, non-linux files in a listed package, and new packages outside internal/console are all caught. - **(b) Zero `Sealer{}`:** cannot seal. A binding other than `{}` hits `ErrSealerBinding`. For `{}`, the empty account and app are refused before the nil key is touched, and a subtest pins both. - **(c) Stale re-seal:** cannot go the wrong way. The key always comes from `sealKeyFor`, so a re-seal only ever goes to the app's own key. Reading a missing sealed_to as the deployment key matches what the relay sealed to before this feature. - **(d) Per-app selection:** correct. Each app's key is chosen before its first write, a failing app is skipped without stopping the others, and the single aggregate publish is unaffected. - **(e) Lock order:** no inversion found, from a grep of every lock site and every caller. The order is always account lock first, then the relay or app lock. I ran no tests, per the review rules; there are five Minor items in the file. Review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-6b-review.md</result> <usage><subagent_tokens>158097</subagent_tokens><tool_uses>32</tool_uses><duration_ms>359488</duration_ms></usage> </task-notification>

Attributed to this commit: 74.7 g CO₂e (4,690,726 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-secrets-key, 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/console/fleetsecrets_relay_test.go b/internal/console/fleetsecrets_relay_test.go
index 20d6426b0..e46149a2d 100644
--- a/internal/console/fleetsecrets_relay_test.go
+++ b/internal/console/fleetsecrets_relay_test.go
@@ -15,6 +15,7 @@ import (
"context"
"fmt"
"net/http"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -469,3 +470,133 @@ func TestTeamEnvironmentRelayOnFleetDoesNotDeadlock(t *testing.T) {
})
}
}
+
+// fsrRunJob runs pass as a job named name and returns its recorded status:
+// what the job page, and so monitoring, sees of the pass.
+func fsrRunJob(t *testing.T, fx *consoleFixture, name string, pass func(context.Context) error) JobStatus {
+ t.Helper()
+ _ = fx.srv.jobs.Run(context.Background(), name, pass)
+ st, ok := jobStatusOf(fx.srv, name)
+ if !ok {
+ t.Fatalf("no status recorded for %s", name)
+ }
+ return st
+}
+
+// fsrSealKeyBreaks are the ways a background walk can fail to choose shop's
+// key, other than the expected states: a registry it cannot open (a read
+// error) and a placement naming a fleet that is not the account's
+// (errFleetNotOwned, a tenancy anomaly). Each runs on a world whose shop is
+// placed on home, keyed.
+var fsrSealKeyBreaks = []struct {
+ name string
+ breakIt func(t *testing.T, w *fcmWorld)
+}{
+ {"registry read error", func(t *testing.T, w *fcmWorld) {
+ w.fx.srv.cfg.Registry = filepath.Join(t.TempDir(), "missing", "registry.db")
+ }},
+ {"fleet not owned", func(t *testing.T, w *fcmWorld) { fsrPlaceByColumn(t, w, "nowhere") }},
+}
+
+// TestPlanStorageReportsSealKeyFailures: the storage stage skips quietly
+// only for an app whose key is absent by design (here a keyless fleet); a
+// read error or a placement on a fleet not the account's fails the job, as
+// it did before fleet keys, and still writes nothing for the app.
+func TestPlanStorageReportsSealKeyFailures(t *testing.T) {
+ run := func(t *testing.T, w *fcmWorld) JobStatus {
+ t.Helper()
+ w.fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := w.fx.account(t)
+ st := storageRow(acct, 2_000_000_000, 1_500_000_000, planNow.Add(-10*24*time.Hour))
+ st.NoticeAt = planNow.Add(-9 * 24 * time.Hour)
+ return fsrRunJob(t, w.fx, "plan-storage-test", func(ctx context.Context) error {
+ return w.fx.srv.convergeStorageDeny(ctx, acct, st, true, planNow)
+ })
+ }
+ t.Run("keyless fleet is skipped quietly", func(t *testing.T) {
+ w, _ := fsrLegacyShop(t, "code-fsr-plan-quiet", false)
+ fsrPlaceByColumn(t, w, "home")
+ if st := run(t, w); st.State == JobFailed {
+ t.Fatalf("a keyless fleet failed the job: %+v", st)
+ }
+ })
+ for _, b := range fsrSealKeyBreaks {
+ t.Run(b.name, func(t *testing.T) {
+ w, _ := fsrLegacyShop(t, "code-fsr-plan-"+strings.ReplaceAll(b.name, " ", "-"), true)
+ fsrPlaceByColumn(t, w, "home")
+ b.breakIt(t, w)
+ st := run(t, w)
+ if st.State != JobFailed || !strings.Contains(st.Err, "shop") {
+ t.Fatalf("job after %s = %+v, want Failed naming shop", b.name, st)
+ }
+ if rec := storedRecord(t, w.fx, "shop"); rec.WritesDenied != nil {
+ t.Fatalf("shop was converged without a key: %+v", rec)
+ }
+ })
+ }
+}
+
+// fsrRelayPlatformShop is bab with home (keyless unless withKey), the
+// deployment key and the relay armed, and shop's relay enabled while shop
+// was placed nowhere. The caller then places shop by the column.
+func fsrRelayPlatformShop(t *testing.T, code string, withKey bool) *fcmWorld {
+ t.Helper()
+ fx, token, _ := fskFixture(t, code)
+ dep := skNewKey(t)
+ fx.srv.cfg.SecretsPub = dep.pub
+ k := skNewKey(t)
+ if withKey {
+ skRegister(t, fx, token, "home", k)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ appconfig.SetBoundSealing(false)
+ t.Cleanup(func() { appconfig.SetBoundSealing(false) })
+ fx.srv.cfg.RelayRegions = []string{"eu-west-1"}
+ fx.srv.cfg.PlatformDomain = "oncarlos.com"
+ t.Setenv(relayMastersEnv("eu-west-1"), "k1:"+relayTestMaster(1))
+ if err := fx.srv.relayAcquire(context.Background()); err != nil {
+ t.Fatalf("acquire the writer lease: %v", err)
+ }
+ w := &fcmWorld{fx: fx, token: token, fleet: k, depPriv: dep.priv}
+ fsrEnableRelay(t, w, "shop")
+ return w
+}
+
+// TestRelayReconcileReportsSealKeyFailures: the reconcile skips quietly only
+// for an app whose key is absent by design (a keyless fleet: nothing
+// written, the job OK); a read error or a placement on a fleet not the
+// account's fails the job, and the app's envelope is left as it was.
+func TestRelayReconcileReportsSealKeyFailures(t *testing.T) {
+ reconcile := func(t *testing.T, w *fcmWorld) JobStatus {
+ t.Helper()
+ return fsrRunJob(t, w.fx, "relay-reconcile-test", w.fx.srv.relayReconcile)
+ }
+ t.Run("keyless fleet is skipped quietly", func(t *testing.T) {
+ w := fsrRelayPlatformShop(t, "code-fsr-relay-quiet", false)
+ before := appVars(t, w.fx, "shop")[relayVar]
+ fsrPlaceByColumn(t, w, "home")
+ if st := reconcile(t, w); st.State == JobFailed {
+ t.Fatalf("a keyless fleet failed the reconcile: %+v", st)
+ }
+ if v := appVars(t, w.fx, "shop")[relayVar]; v.Envelope != before.Envelope {
+ t.Fatal("the reconcile rewrote a keyless fleet app's relay config")
+ }
+ })
+ for _, b := range fsrSealKeyBreaks {
+ t.Run(b.name, func(t *testing.T) {
+ w := fsrRelayPlatformShop(t, "code-fsr-relay-"+strings.ReplaceAll(b.name, " ", "-"), true)
+ before := appVars(t, w.fx, "shop")[relayVar]
+ fsrPlaceByColumn(t, w, "home")
+ b.breakIt(t, w)
+ st := reconcile(t, w)
+ if st.State != JobFailed || !strings.Contains(st.Err, "shop") {
+ t.Fatalf("reconcile after %s = %+v, want Failed naming shop", b.name, st)
+ }
+ if v := appVars(t, w.fx, "shop")[relayVar]; v.Envelope != before.Envelope {
+ t.Fatal("the reconcile rewrote shop's relay config without a key")
+ }
+ })
+ }
+}
diff --git a/internal/console/planstorage.go b/internal/console/planstorage.go
index 4b2b788cb..10b506b1c 100644
--- a/internal/console/planstorage.go
+++ b/internal/console/planstorage.go
@@ -91,15 +91,22 @@ func (s *Server) convergeStoreDeny(ctx context.Context, acct *Account, app, env
return nil
}
// The app's own key (sealKeyFor), chosen before the first write, under
- // the account lock convergeStores holds. An app whose key cannot be
- // chosen, such as one on a keyless fleet, is skipped with a log line:
- // nothing is written, so WritesDenyApplied still disagrees and the next
- // pass tries again. That is the app's state, not a failure of the pass.
+ // the account lock convergeStores holds. Nothing is written for an app
+ // whose key cannot be chosen, so WritesDenyApplied still disagrees and
+ // the next pass tries again. A key absent by design (sealKeyAbsent: a
+ // keyless fleet, say) is the app's state and is skipped with a log line;
+ // anything else (a read that failed, a placement naming a fleet not the
+ // account's) also fails the job.
sealer, err := s.sealKeyFor(ctx, acct.Sqid, app)
- if err != nil {
+ if err != nil && sealKeyAbsent(err) {
log.Printf("console: plan storage %s/%s: skipped, no key to seal a store credential to; the next pass tries again: %v", acct.Sqid, app, err)
return nil
}
+ if err != nil {
+ log.Printf("console: plan storage %s/%s: no key could be chosen, store policy left as it is: %v", acct.Sqid, app, err)
+ jobFailed(ctx, fmt.Errorf("plan storage %s/%s: no key could be chosen, store policy left as it is: %w", acct.Sqid, app, err))
+ return nil
+ }
action, detail := "store.writes_allowed", fmt.Sprintf("plan storage: %d of %d bytes; new uploads allowed again", st.Used, st.Limit)
if want {
action, detail = "store.writes_denied", fmt.Sprintf("plan storage: %d of %d bytes; new uploads refused, downloads and deletes still work", st.Used, st.Limit)
diff --git a/internal/console/relayops.go b/internal/console/relayops.go
index 903426758..d39481e7d 100644
--- a/internal/console/relayops.go
+++ b/internal/console/relayops.go
@@ -494,10 +494,11 @@ func (e errRelayKeylessFleet) Error() string {
return fmt.Sprintf("%s has no secrets key, so the console cannot deliver a relay key to %s and will not issue one. run carlos fleets secrets-key %s <pubkey>", e.Fleet, e.App, e.Fleet)
}
-// errRelaySealKey is any refusal of relaySealKey: no key could be chosen for
-// the app, so nothing was sealed or written for it. The reconcile reads it
-// as "skip this app until its key is right", not as a failed pass. It says
-// what the error it carries says.
+// errRelaySealKey is relaySealKey's refusal for an app whose key is absent
+// by design (sealKeyAbsent): nothing was sealed or written for it. The
+// reconcile reads it as "skip this app until its key is right", not as a
+// failed pass. Any other failure to choose the key comes back unwrapped and
+// fails the pass. It says what the error it carries says.
type errRelaySealKey struct{ err error }
func (e errRelaySealKey) Error() string { return e.err.Error() }
@@ -507,8 +508,9 @@ func (e errRelaySealKey) Unwrap() error { return e.err }
// credentials, the app's and every owned environment's. sealKeyFor's two
// configuration refusals become the relay's own answers: errRelayNoSealKey
// for an app placed nowhere on a console with no CARLOS_SECRETS_PUBKEY, and
-// errRelayKeylessFleet for an app on a fleet with no key. Every refusal comes
-// back as errRelaySealKey.
+// errRelayKeylessFleet for an app on a fleet with no key. Those, and an app
+// with no live row, come back as errRelaySealKey; every other error (a read
+// that failed, a placement naming a fleet not the account's) as it is.
//
// It takes no lock (sealKeyFor's rule). Its callers hold the account lock
// from here through their write: relayEnable, relayReissue and
@@ -518,6 +520,9 @@ func (s *Server) relaySealKey(ctx context.Context, acct, app string) (appconfig.
if err == nil {
return sealer, nil
}
+ if !sealKeyAbsent(err) {
+ return appconfig.Sealer{}, err
+ }
var keyless errFleetNoSecretsKey
switch {
case errors.Is(err, errNoDeploymentKey):
@@ -1596,9 +1601,10 @@ func (s *Server) relayReconcile(ctx context.Context) error {
etag, changed, err := s.relayConverge(ctx, r)
var noKey errRelaySealKey
if errors.As(err, &noKey) {
- // No key could be chosen for this app (a keyless fleet, say):
+ // The app's key is absent by design (a keyless fleet, say):
// nothing was written for it, and the next pass tries again.
- // The app's state, not a failure of the pass.
+ // The app's state, not a failure of the pass. Any other
+ // failure to choose the key falls through to the failure path.
log.Printf("console: relay reconcile %s/%s: skipped, no key to seal to: %v", r.Account, r.App, err)
continue
}
@@ -1663,8 +1669,9 @@ func (s *Server) relayConvergeWalk(ctx context.Context, r relayAppRecord) (strin
}
if rec.Enabled {
// The app's own key, chosen before anything is written for it. An
- // app with none (errRelaySealKey) is skipped by the reconcile and
- // tried again on the next pass.
+ // app whose key is absent by design (errRelaySealKey) is skipped by
+ // the reconcile and tried again on the next pass; any other failure
+ // fails the pass.
sealer, err := s.relaySealKey(ctx, r.Account, r.App)
if err != nil {
return "", false, err
diff --git a/internal/console/sealkey.go b/internal/console/sealkey.go
index e8d113f3a..ae6f322dc 100644
--- a/internal/console/sealkey.go
+++ b/internal/console/sealkey.go
@@ -70,6 +70,20 @@ func (e errFleetNotOwned) Error() string {
return fmt.Sprintf("console: seal key: placement fleet/%s is not a fleet of this account", e.Fleet)
}
+// sealKeyAbsent reports whether err is one of sealKeyFor's refusals that
+// describe the app, not a fault: its fleet has no key (errFleetNoSecretsKey),
+// it is placed nowhere on a console with no deployment key
+// (errNoDeploymentKey), or it has no live row, such as an app in the Trash
+// (errUnknownApp). A background walk skips such an app quietly and tries
+// again next pass. Anything else (a store or registry read that failed, a
+// placement naming a fleet that is not the account's) is a failure the walk
+// reports.
+func sealKeyAbsent(err error) bool {
+ var keyless errFleetNoSecretsKey
+ var unknown errUnknownApp
+ return errors.As(err, &keyless) || errors.Is(err, errNoDeploymentKey) || errors.As(err, &unknown)
+}
+
// sealChoice is sealKeyFor's reading of where an app's secrets go, before a
// sealer is built from it: the key, whether its envelopes are bound, and the
// fleet ("" for the deployment key).
diff --git a/internal/console/sealkey_guard_test.go b/internal/console/sealkey_guard_test.go
index e8ee0b230..9e0559d12 100644
--- a/internal/console/sealkey_guard_test.go
+++ b/internal/console/sealkey_guard_test.go
@@ -10,7 +10,8 @@ package console
// count), every use of:
//
// - appconfig.Seal, appconfig.SealBound, appconfig.SealUnbound and
-// appconfig.NewSealer, which seal to whatever key they are handed;
+// appconfig.NewSealer, which seal to whatever key they are handed, and
+// sealWith, the unexported core the two envelope writers share;
// - archive.Seal (internal/moves/archive), which does the same for a move;
// - console's chooseSealKey, sealKeyFor without the sealer: whoever reads
// its key could build one.
@@ -18,9 +19,12 @@ package console
// Each is allowed only inside the functions sealGuardAllowed names for it.
// (appconfig.Sealer).Seal is allowed anywhere: a Sealer comes only from
// NewSealer, so it seals only to a key an allowed caller chose. That rests on
-// two more checks: a composite literal of appconfig.Sealer with any field set
-// appears only in NewSealer (an empty one is the zero Sealer, which refuses
-// every binding and seals nothing), and the struct has no exported field.
+// three more checks: a composite literal of appconfig.Sealer with any field
+// set appears only in NewSealer, exactly once (an empty one is the zero
+// Sealer, which refuses every binding and seals nothing); every read or write
+// of one of Sealer's fields, found by identity, is inside NewSealer or one of
+// Sealer's own methods, so no second constructor can fill a zero Sealer field
+// by field; and the struct has no exported field.
//
// Negative fixtures (testdata/sealguard) are laid over the real packages with
// go list's overlay, so each resolves exactly as real code would, and each
@@ -59,19 +63,22 @@ const (
sgSealBound = sgAppconfig + ".SealBound"
sgSealUnbound = sgAppconfig + ".SealUnbound"
sgNewSealer = sgAppconfig + ".NewSealer"
+ sgSealWith = sgAppconfig + ".sealWith"
sgArchiveSeal = sgArchive + ".Seal"
sgChooseSealKey = "(*" + sgConsole + ".Server).chooseSealKey"
)
// sgTargets is every guarded function, by types.Func.FullName.
-var sgTargets = []string{sgSeal, sgSealBound, sgSealUnbound, sgNewSealer, sgArchiveSeal, sgChooseSealKey}
+var sgTargets = []string{sgSeal, sgSealBound, sgSealUnbound, sgNewSealer, sgSealWith, sgArchiveSeal, sgChooseSealKey}
// sealGuardAllowed is the allowlist: an enclosing function (FullName) and
// the guarded functions it may use. Nothing else may use any of them.
var sealGuardAllowed = map[string][]string{
- // The envelope's own two writers.
+ // The envelope's own two writers, and the core they share.
"(" + sgAppconfig + ".Sealer).Seal": {sgSealBound, sgSealUnbound},
sgSeal: {sgSealBound, sgSealUnbound},
+ sgSealBound: {sgSealWith},
+ sgSealUnbound: {sgSealWith},
// The one choice of key (sealkey.go).
"(*" + sgConsole + ".Server).sealKeyFor": {sgNewSealer, sgChooseSealKey},
// The config PUT's check of what a client sealed: it reads the choice
@@ -177,6 +184,39 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
}
var out []sgFinding
seen := map[string]int{}
+ // Sealer's fields, by identity: reading or writing one is building or
+ // taking apart a sealer, which only NewSealer and Sealer's own methods
+ // may do. A keyed literal's keys are uses of the fields too.
+ fields := map[*types.Var]bool{}
+ for _, pkg := range pkgs {
+ if pkg.PkgPath != sgAppconfig {
+ continue
+ }
+ if obj := pkg.Types.Scope().Lookup("Sealer"); obj != nil {
+ if st, ok := obj.Type().Underlying().(*types.Struct); ok {
+ for i := range st.NumFields() {
+ fields[st.Field(i)] = true
+ }
+ }
+ }
+ }
+ fieldsAllowed := func(fn *types.Func) bool {
+ if fn == nil {
+ return false
+ }
+ if fn.FullName() == sgNewSealer {
+ return true
+ }
+ recv := fn.Signature().Recv()
+ if recv == nil {
+ return false
+ }
+ t := recv.Type()
+ if p, ok := t.(*types.Pointer); ok {
+ t = p.Elem()
+ }
+ return sgIsSealer(t)
+ }
rel := func(p token.Position) token.Position {
if r, err := filepath.Rel(root, p.Filename); err == nil {
p.Filename = r
@@ -188,14 +228,24 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
for _, file := range pkg.Syntax {
for _, decl := range file.Decls {
in := ""
+ var encl *types.Func
if fd, ok := decl.(*ast.FuncDecl); ok {
if fn, ok := info.Defs[fd.Name].(*types.Func); ok {
- in = fn.FullName()
+ in, encl = fn.FullName(), fn
}
}
ast.Inspect(decl, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.Ident:
+ if v, ok := info.Uses[n].(*types.Var); ok && fields[v] {
+ what := "appconfig.Sealer." + v.Name()
+ if fieldsAllowed(encl) {
+ seen[in+" -> "+what]++
+ return true
+ }
+ out = append(out, sgFinding{rel(pkg.Fset.Position(n.Pos())), what, in})
+ return true
+ }
fn, ok := info.Uses[n].(*types.Func)
if !ok {
return true
@@ -236,7 +286,7 @@ func sgScan(root string, pkgs []*packages.Package) ([]sgFinding, map[string]int)
// the guard needs a load under that file's GOOS or tags.
func sgIgnoredFiles(t *testing.T, root string, pkgs []*packages.Package) []string {
t.Helper()
- names := []string{"chooseSealKey", "NewSealer", "SealBound", "SealUnbound", "Seal(", "Sealer{"}
+ names := []string{"chooseSealKey", "NewSealer", "SealBound", "SealUnbound", "sealWith", "Seal(", "Sealer{"}
var out []string
for _, pkg := range pkgs {
for _, path := range pkg.IgnoredFiles {
@@ -336,6 +386,9 @@ func TestOnlySealKeyForBuildsSealers(t *testing.T) {
}
// The scan resolves identities at all: sealKeyFor's own sealer is
// found where it is allowed.
+ if n := seen[sgNewSealer+" -> appconfig.Sealer{...}"]; n != 1 {
+ t.Errorf("NewSealer builds %d Sealer literal(s); the guard allows exactly one, there", n)
+ }
if seen["(*"+sgConsole+".Server).sealKeyFor -> "+sgNewSealer] == 0 {
t.Errorf("the scan did not see sealKeyFor's NewSealer; it is not resolving uses (seen: %v)", seen)
}
@@ -403,7 +456,12 @@ func TestOnlySealKeyForBuildsSealers(t *testing.T) {
// package-level function value;
// - sealkey: a second NewSealer in sealkey.go, outside sealKeyFor, built
// from chooseSealKey (the fixture is appended to the real file);
-// - ctor: a second constructor inside appconfig, returning Sealer{...};
+// - ctor: a second constructor inside appconfig, returning Sealer{...}
+// (named as a literal and by each keyed field);
+// - fieldassign: a second constructor that fills a zero Sealer field by
+// field, with no literal;
+// - sealwith: an exported appconfig helper sealing to any key through
+// the unexported core, sealWith;
// - choose: chooseSealKey called from a console function that is neither
// sealKeyFor nor the config PUT's check.
func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
@@ -420,10 +478,12 @@ func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
consoleDir := filepath.Join(root, "internal", "console")
appconfigDir := filepath.Join(root, "internal", "appconfig")
overlay := map[string][]byte{
- filepath.Join(consoleDir, "zz_sealguard_arbitrary.go"): read("arbitrary/arbitrary.go"),
- filepath.Join(consoleDir, "zz_sealguard_aliased.go"): read("aliased/aliased.go"),
- filepath.Join(consoleDir, "zz_sealguard_choose.go"): read("choose/choose.go"),
- filepath.Join(appconfigDir, "zz_sealguard_ctor.go"): read("ctor/ctor.go"),
+ filepath.Join(consoleDir, "zz_sealguard_arbitrary.go"): read("arbitrary/arbitrary.go"),
+ filepath.Join(consoleDir, "zz_sealguard_aliased.go"): read("aliased/aliased.go"),
+ filepath.Join(consoleDir, "zz_sealguard_choose.go"): read("choose/choose.go"),
+ filepath.Join(appconfigDir, "zz_sealguard_ctor.go"): read("ctor/ctor.go"),
+ filepath.Join(appconfigDir, "zz_sealguard_fields.go"): read("ctor/fieldassign.go"),
+ filepath.Join(appconfigDir, "zz_sealguard_sealwith.go"): read("ctor/sealwith.go"),
}
// The sealkey fixture's declarations go at the end of the real
// sealkey.go, whose imports they share.
@@ -451,6 +511,14 @@ func sgFixtures(t *testing.T, root string) (map[string][]byte, []string) {
sgNewSealer + " in " + server + ".sealKeyForOtherApp",
sgChooseSealKey + " in " + server + ".sealKeyForOtherApp",
"appconfig.Sealer{...} in " + sgAppconfig + ".sealGuardSealer",
+ "appconfig.Sealer.pub in " + sgAppconfig + ".sealGuardSealer",
+ "appconfig.Sealer.binding in " + sgAppconfig + ".sealGuardSealer",
+ "appconfig.Sealer.bound in " + sgAppconfig + ".sealGuardSealer",
+ "appconfig.Sealer.pub in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.fp in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.binding in " + sgAppconfig + ".SealGuardFieldSealer",
+ "appconfig.Sealer.bound in " + sgAppconfig + ".SealGuardFieldSealer",
+ sgAppconfig + ".sealWith in " + sgAppconfig + ".SealGuardAny",
sgChooseSealKey + " in " + server + ".sealGuardChoose",
}
}
diff --git a/internal/console/testdata/sealguard/ctor/fieldassign.go b/internal/console/testdata/sealguard/ctor/fieldassign.go
new file mode 100644
index 000000000..1c340cfb4
--- /dev/null
+++ b/internal/console/testdata/sealguard/ctor/fieldassign.go
@@ -0,0 +1,12 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/appconfig: a second constructor that fills a zero Sealer field by
+// field, with no literal, and exports it.
+package appconfig
+
+import "crypto/ecdh"
+
+func SealGuardFieldSealer(pub *ecdh.PublicKey, b Binding) Sealer {
+ var s Sealer
+ s.pub, s.fp, s.binding, s.bound = pub, KeyFingerprint(pub), b, true
+ return s
+}
diff --git a/internal/console/testdata/sealguard/ctor/sealwith.go b/internal/console/testdata/sealguard/ctor/sealwith.go
new file mode 100644
index 000000000..8a2e1348f
--- /dev/null
+++ b/internal/console/testdata/sealguard/ctor/sealwith.go
@@ -0,0 +1,14 @@
+// A negative fixture of TestOnlySealKeyForBuildsSealers, laid over
+// internal/appconfig: an exported helper that seals to any key through the
+// unexported core, sealWith.
+package appconfig
+
+import "crypto/ecdh"
+
+func SealGuardAny(pub *ecdh.PublicKey, plaintext []byte) (string, error) {
+ eph, nonce, err := freshEphemeral()
+ if err != nil {
+ return "", err
+ }
+ return sealWith(eph, nonce, pub, "", hkdfInfo, nil, plaintext)
+}