carlos / platform Public

console: a policy write lands only on the app it found; rename refuses over policy state (#328, #329)

Final review finding 2: a first grant that had found its app could
publish after the app was purged and its name created again. The app's
policy lock now lives on the store (Store.AppPolicyLock) and every path
that frees a name or moves an app onto one holds it and counts the
change: PurgeAppRow, MoveApp, and the rename door around RenameAppIn and
UndoRenameAppIn. The PUT door reads the app's incarnation (created_at
and the name's freed count) when it finds the app and checks it again
under the lock right before it audits, signs, records and publishes; a
stale write is refused with 409 and writes nothing. Create's lock-free
absent path (Task 11b) is unchanged.

Final review finding 3: the rename door refuses when either name has
policy state (an object at its key or a revision row), checked before
the confirm card and again under both names' policy locks.

New strings are in the plan 1 copy deck (IP1-45 to IP1-48, IP1-L8).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9670a95c908043bd7dfe63a243fad2eaa88324bd parent efccf36
8 files changed, +766 −41
  • docs/superpowers/notes/copy-instance-policy-plan1.md +14 −0
  • internal/console/apipolicy.go +52 −28
  • internal/console/apppolicy_names.go +141 −0
  • internal/console/apppolicy_names_test.go +450 −0
  • internal/console/appsettings.go +50 −0
  • internal/console/claim_app_enroll.go +7 −4
  • internal/console/server.go +6 −5
  • internal/console/store.go +46 −4
diff --git a/docs/superpowers/notes/copy-instance-policy-plan1.md b/docs/superpowers/notes/copy-instance-policy-plan1.md
index 071097dc8..8f256014f 100644
--- a/docs/superpowers/notes/copy-instance-policy-plan1.md
+++ b/docs/superpowers/notes/copy-instance-policy-plan1.md
@@ -94,6 +94,7 @@ would only see them if the CLI and console disagreed.
| IP1-28 | internal/console/apipolicy.go:72 `policyUnpublishedMsg` | the change is recorded but not yet published. Run the command again to publish it now | 502 on `apps set` / `instances set` | 0 |
| IP1-29 | internal/console/apipolicy.go:73 `policyReadFailedMsg` | could not read the policy. Try again | 502 or 503 on `apps show`, `apps set`, `instances set` | 0 |
| IP1-30 | internal/console/apipolicy.go:74 `policyInvalidHostMsg` | invalid host | 400 on `instances set --size` with a malformed host | 15 (shared wording across ten files; this is its own literal, so a rewrite here changes only this door) |
+| IP1-45 | internal/console/apipolicy.go:74 `policyAppReplacedMsg` (new, final review finding 2) | the app was deleted, renamed or moved while the change was being made, so it was not made | 409 on `apps set` / `instances set` when the app the request found was trashed, purged, renamed or moved (and perhaps created again) before the write | 0 |
Reused unchanged, not new copy: `doorKeyNoBucketMsg`
(`internal/console/apidoorkeys.go:44`, "no deployment bucket on this host.
@@ -128,6 +129,18 @@ size -> large (cli)`.
The lease refusals (IP1-15 to IP1-19) also answer a create:
`apicli.go:487`, `apitemporary.go:223`, and the flash at `server.go:4562`.
+## 4a. App rename (final review finding 3, `internal/console/appsettings.go`)
+
+A rename is refused when either name has had a policy: an object at its
+key, or a revision row in the console's table. The row outlives a cleared
+policy, so these refusals do not tell the person to clear anything.
+
+| id | where | text | seen | base |
+|---|---|---|---|---|
+| IP1-46 | internal/console/appsettings.go:919 `renamePolicyFromMsg` | This app has had an instance policy set by an operator, so it cannot be renamed. Create a new app instead. | the rename form's flash (app settings, General) | 0 |
+| IP1-47 | internal/console/appsettings.go:920 `renamePolicyToMsg` | The name %s has had an instance policy set by an operator, so no app can be renamed to it. Choose another name. | the same flash; `%s` is the new name | 0 |
+| IP1-48 | internal/console/appsettings.go:921 `renamePolicyCheckMsg` | Could not check the instance policies, so nothing was renamed. Try again. | the same flash, when the bucket or the table cannot be read | 0 |
+
## 5. The CLI (Task 12)
| id | where | text | seen | base |
@@ -200,6 +213,7 @@ diagnostics and are left out.
| IP1-L5 | internal/provision/apppolicy_reconcile.go:186 | provision: %s/%s: policy %s: %v (`%s` is `unreadable`, `unverifiable` or `expired`) | box log, once per app per pass | 0 |
| IP1-L6 | internal/provision/apppolicy_reconcile.go:175 | provision: %s/%s: policy read failed: %v | box log | 0 |
| IP1-L7 | internal/provision/apppolicy_cache.go:253 | provision: app policies: listing failed, retried next pass: %v | box log | 0 |
+| IP1-L8 | internal/console/apipolicy.go:381 | console: app policy %s/%s: the app was deleted, renamed or moved during the request; nothing written | console log, with IP1-45 | 0 |
Status words, set by plan 1 for plan 2's report and not yet shown to anyone:
`policy unreadable`, `policy unverifiable`, `policy expired`
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go
index 9eb2c6f6d..8d9ca35af 100644
--- a/internal/console/apipolicy.go
+++ b/internal/console/apipolicy.go
@@ -71,6 +71,7 @@ const (
policyAuditFailedMsg = "the change could not be audited, so it was not made. Try again"
policyUnpublishedMsg = "the change is recorded but not yet published. Run the command again to publish it now"
policyReadFailedMsg = "could not read the policy. Try again"
+ policyAppReplacedMsg = "the app was deleted, renamed or moved while the change was being made, so it was not made"
policyInvalidHostMsg = "invalid host"
policyAuditAction = "app-policy"
policyBodyLimit = 8 << 10
@@ -100,22 +101,13 @@ type policyReply struct {
Stale []string `json:"stale_overrides,omitempty"`
}
-// policyLock is the app's policy mutex, created on first use as
-// doorPublishLock is. The door holds it from before its base read until its
-// reply; the re-sign pass shares it.
-func (s *Server) policyLock(sqid, app string) *sync.Mutex {
- s.policyLocksMu.Lock()
- defer s.policyLocksMu.Unlock()
- if s.policyLocks == nil {
- s.policyLocks = map[string]*sync.Mutex{}
- }
- k := sqid + "/" + app
- mu := s.policyLocks[k]
- if mu == nil {
- mu = &sync.Mutex{}
- s.policyLocks[k] = mu
- }
- return mu
+// policyLock is the app's policy mutex, the store's (Store.AppPolicyLock), so
+// every path that frees the name or moves an app onto it takes the same one
+// (apppolicy_names.go). The door holds it from before its base read until its
+// reply; the re-sign pass and a create that clears an earlier app's policy
+// share it.
+func (s *Server) policyLock(accountID int64, app string) *sync.Mutex {
+ return s.store.AppPolicyLock(accountID, app)
}
// policyTouched reports whether holding n already chose a base for key.
@@ -342,30 +334,55 @@ func samePolicyPayload(a, b []byte) bool {
}
// policyAccountApp resolves the path's account and app for an operator: a
-// missing account or app is the same bare 404 as the operator gate's.
-func (s *Server) policyAccountApp(w http.ResponseWriter, r *http.Request) (*Account, string, bool) {
+// missing account or app is the same bare 404 as the operator gate's. inc is
+// the live app the request found, which a write checks again under the
+// app's policy lock before it writes anything (policyStillTheApp).
+func (s *Server) policyAccountApp(w http.ResponseWriter, r *http.Request) (*Account, string, AppIncarnation, bool) {
acct, err := s.store.AccountBySqid(r.PathValue("account"))
if err != nil {
s.policyLogf("console: app policy: account: %v", err)
jsonError(w, http.StatusServiceUnavailable, policyReadFailedMsg)
- return nil, "", false
+ return nil, "", AppIncarnation{}, false
}
if acct == nil {
http.NotFound(w, r)
- return nil, "", false
+ return nil, "", AppIncarnation{}, false
}
app := r.PathValue("app")
- ok, err := s.store.HasAppIn(acct.ID, app)
+ inc, ok, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app)
if err != nil {
s.policyLogf("console: app policy %s/%s: app: %v", acct.Sqid, app, err)
jsonError(w, http.StatusServiceUnavailable, policyReadFailedMsg)
- return nil, "", false
+ return nil, "", AppIncarnation{}, false
}
if !ok {
http.NotFound(w, r)
- return nil, "", false
+ return nil, "", AppIncarnation{}, false
}
- return acct, app, true
+ return acct, app, inc, true
+}
+
+// policyStillTheApp is the write's check, under the app's policy lock and
+// right before it audits, signs, records and publishes, that the name still
+// names the live app the request found at its start (final review finding
+// 2). A purge, move or rename that freed the name since (and a create that
+// took it again) changes the answer; none can run while the lock is held,
+// so the write lands on the app it was asked for or not at all. A trashed
+// app is refused too: the request was for a live one.
+func (s *Server) policyStillTheApp(ctx context.Context, acct *Account, app string, inc AppIncarnation) *doorRefusal {
+ // A local read, outside the publish budget: a write whose budget ran
+ // out is answered by its holding check in writePolicy, not here.
+ now, ok, err := s.store.AppIncarnationContext(context.WithoutCancel(ctx), acct.ID, app)
+ switch {
+ case err != nil:
+ s.policyLogf("console: app policy %s/%s: recheck the app: %v", acct.Sqid, app, err)
+ return &doorRefusal{http.StatusServiceUnavailable, policyReadFailedMsg}
+ case !ok || now != inc:
+ s.policyLogf("console: app policy %s/%s: the app was deleted, renamed or moved during the request; nothing written",
+ acct.Sqid, app)
+ return &doorRefusal{http.StatusConflict, policyAppReplacedMsg}
+ }
+ return nil
}
func (s *Server) policyRefuse(w http.ResponseWriter, acct *Account, app string, err error) {
@@ -387,7 +404,7 @@ func (s *Server) handleAPIPolicyGet(w http.ResponseWriter, r *http.Request) {
if _, _, ok := s.apiSystemRoller(w, r); !ok {
return
}
- acct, app, ok := s.policyAccountApp(w, r)
+ acct, app, _, ok := s.policyAccountApp(w, r)
if !ok {
return
}
@@ -429,7 +446,7 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- acct, app, ok := s.policyAccountApp(w, r)
+ acct, app, inc, ok := s.policyAccountApp(w, r)
if !ok {
return
}
@@ -459,7 +476,10 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
// client that hangs up must not cut its publication short.
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), doorKeyPublishBudget)
defer cancel()
- mu := s.policyLock(acct.Sqid, app)
+ if s.policyBeforeLock != nil {
+ s.policyBeforeLock(acct.Sqid, app)
+ }
+ mu := s.policyLock(acct.ID, app)
mu.Lock()
defer mu.Unlock()
hold, ref := s.policyWriter(ctx)
@@ -499,6 +519,10 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
}
}
detail := policyAuditDetail(old, pol, req)
+ if ref := s.policyStillTheApp(ctx, acct, app, inc); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
var (
refusal *doorRefusal
@@ -836,7 +860,7 @@ func policyKeyApp(key string) (sqid, app string, ok bool) {
// app mutation, within doorKeyPublishBudget, bound to hold. A lost holding is
// errPolicyResignLost; any other failure is this app's alone.
func (s *Server) resignAppPolicy(ctx context.Context, acct *Account, app string, hold policyHolding) error {
- mu := s.policyLock(acct.Sqid, app)
+ mu := s.policyLock(acct.ID, app)
mu.Lock()
defer mu.Unlock()
// Nothing of a later app is read once the holding is gone.
diff --git a/internal/console/apppolicy_names.go b/internal/console/apppolicy_names.go
new file mode 100644
index 000000000..9f6551dad
--- /dev/null
+++ b/internal/console/apppolicy_names.go
@@ -0,0 +1,141 @@
+package console
+
+import (
+ "cmp"
+ "context"
+ "database/sql"
+ "errors"
+ "slices"
+ "sync"
+ "sync/atomic"
+)
+
+// appNameLocks is, per app name, the app's policy lock and a count of the
+// times the name stopped naming the app it named (#328, #329; final review
+// finding 2). One set per database, shared by every view of the Store.
+//
+// The policy door, the re-sign pass and a create that clears an earlier
+// app's policy hold the name's lock (Server.policyLock). Every path that
+// frees a name or moves an app onto one holds it too: PurgeAppRow, MoveApp,
+// and the rename door around RenameAppIn and UndoRenameAppIn. Each of them
+// counts the change (appNameFreed) before it unlocks. So a policy write that
+// read the app's incarnation at its start (AppIncarnationContext) and reads
+// the same one again under the lock knows no purge, move or rename freed the
+// name in between, and none can until it unlocks.
+//
+// The count lives in memory: a restart ends every request that read one.
+// Claim-mode purges (PurgeClaimAppRow) are fenced by the incarnation's
+// app_id and the claim mutation instead, and take no lock here.
+type appNameLocks struct {
+ mu sync.Mutex
+ names map[appNameKey]*appNameLock
+ // waiting is a TEST SEAM (nil in production), set under mu:
+ // lockAppNames calls it with each name right before it waits for that
+ // name's lock.
+ waiting func(accountID int64, app string)
+}
+
+type appNameKey struct {
+ accountID int64
+ app string
+}
+
+type appNameLock struct {
+ mu sync.Mutex
+ freed atomic.Uint64
+}
+
+func (s *Store) appName(accountID int64, app string) *appNameLock {
+ s.names.mu.Lock()
+ defer s.names.mu.Unlock()
+ if s.names.names == nil {
+ s.names.names = map[appNameKey]*appNameLock{}
+ }
+ k := appNameKey{accountID, app}
+ l := s.names.names[k]
+ if l == nil {
+ l = &appNameLock{}
+ s.names.names[k] = l
+ }
+ return l
+}
+
+// AppPolicyLock is the app's policy lock (see appNameLocks).
+func (s *Store) AppPolicyLock(accountID int64, app string) *sync.Mutex {
+ return &s.appName(accountID, app).mu
+}
+
+// setAppNameWaiting installs the TEST SEAM on appNameLocks.waiting.
+func (s *Store) setAppNameWaiting(f func(accountID int64, app string)) {
+ s.names.mu.Lock()
+ defer s.names.mu.Unlock()
+ s.names.waiting = f
+}
+
+// lockAppNames takes the policy locks of every name, in one order (account,
+// then name) so two callers never wait on each other, and returns the
+// unlock. A name listed twice is locked once.
+func (s *Store) lockAppNames(names ...appNameKey) (unlock func()) {
+ names = slices.Clone(names)
+ slices.SortFunc(names, func(a, b appNameKey) int {
+ return cmp.Or(cmp.Compare(a.accountID, b.accountID), cmp.Compare(a.app, b.app))
+ })
+ names = slices.Compact(names)
+ s.names.mu.Lock()
+ waiting := s.names.waiting
+ s.names.mu.Unlock()
+ locked := make([]*sync.Mutex, 0, len(names))
+ for _, n := range names {
+ if waiting != nil {
+ waiting(n.accountID, n.app)
+ }
+ mu := s.AppPolicyLock(n.accountID, n.app)
+ mu.Lock()
+ locked = append(locked, mu)
+ }
+ return func() {
+ for i := len(locked) - 1; i >= 0; i-- {
+ locked[i].Unlock()
+ }
+ }
+}
+
+// appNameFreed counts that the name stopped naming its app. The caller holds
+// the name's lock and has committed the change.
+func (s *Store) appNameFreed(accountID int64, app string) {
+ s.appName(accountID, app).freed.Add(1)
+}
+
+// AppIncarnation identifies one live app under its name: the row's
+// created_at and the name's freed count read before it. Two reads are equal
+// only if no purge, move or rename freed the name between them.
+type AppIncarnation struct {
+ createdAt int64
+ freed uint64
+}
+
+// AppIncarnationContext is the live app under the name now; ok is false when
+// the account holds no live app of that name (none, or only a trashed one).
+// The freed count is read first, so a change between the two reads makes the
+// answer differ from any later one.
+func (s *Store) AppIncarnationContext(ctx context.Context, accountID int64, app string) (inc AppIncarnation, ok bool, err error) {
+ inc.freed = s.appName(accountID, app).freed.Load()
+ err = s.db.QueryRowContext(ctx, `SELECT created_at FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
+ accountID, app).Scan(&inc.createdAt)
+ if errors.Is(err, sql.ErrNoRows) {
+ return AppIncarnation{}, false, nil
+ }
+ if err != nil {
+ return AppIncarnation{}, false, err
+ }
+ return inc, true, nil
+}
+
+// HasAppPolicyRevisionContext reports whether the table holds a revision row
+// for the name: some app of that name has had a policy recorded here.
+func (s *Store) HasAppPolicyRevisionContext(ctx context.Context, accountID int64, app string) (bool, error) {
+ var n int
+ err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM app_policy_revisions WHERE account_id = ? AND app = ?`,
+ accountID, app).Scan(&n)
+ return n > 0, err
+}
diff --git a/internal/console/apppolicy_names_test.go b/internal/console/apppolicy_names_test.go
new file mode 100644
index 000000000..d22e45638
--- /dev/null
+++ b/internal/console/apppolicy_names_test.go
@@ -0,0 +1,450 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "html"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apppolicy"
+)
+
+// ---- final review finding 2: a policy write lands on the app it was for ----
+
+// nameWaits is closed the first time a name-freeing path is about to wait
+// for the policy lock of (accountID, app) (the appNameLocks TEST SEAM).
+func nameWaits(st *Store, accountID int64, app string) <-chan struct{} {
+ ch := make(chan struct{})
+ var once sync.Once
+ st.setAppNameWaiting(func(a int64, n string) {
+ if a == accountID && n == app {
+ once.Do(func() { close(ch) })
+ }
+ })
+ return ch
+}
+
+// pausePoint is a one-shot pause: the first caller of hit signals paused and
+// waits for resume.
+type pausePoint struct {
+ once sync.Once
+ paused chan struct{}
+ resume chan struct{}
+}
+
+func newPausePoint() *pausePoint {
+ return &pausePoint{paused: make(chan struct{}), resume: make(chan struct{})}
+}
+
+func (p *pausePoint) hit() {
+ p.once.Do(func() {
+ close(p.paused)
+ <-p.resume
+ })
+}
+
+// putResult is a PUT run in the background.
+type putResult struct {
+ status int
+ out string
+}
+
+func (fx *policyFx) putAsync(t *testing.T, app, body string, hdr map[string]string) <-chan putResult {
+ ch := make(chan putResult, 1)
+ go func() {
+ st, _, out := policyReq(t, fx.consoleFixture, http.MethodPut, app, fx.owner, body, hdr)
+ ch <- putResult{st, out}
+ }()
+ return ch
+}
+
+// purgeAndRecreate is a person's "Delete now" on the Trash page, through the
+// real purge door, then a create of the same name through the CLI door.
+// trashKass must have run. Safe off the test goroutine: failures are
+// reported with t.Errorf.
+func purgeAndRecreate(t *testing.T, fx *policyFx, c *http.Client, csrf string) {
+ if st, _, body := postGated(t, fx.consoleFixture, c, fx.u("/trash/delete"),
+ url.Values{"csrf": {csrf}, "app": {"kass"}, "confirm": {"kass"}}); st != http.StatusSeeOther {
+ t.Errorf("delete now = %d:\n%s", st, body)
+ return
+ }
+ if st, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]string{"name": "kass"}, fx.owner); st != http.StatusOK {
+ t.Errorf("recreate = %d %v", st, out)
+ }
+}
+
+// wantCleanSuccessor checks the recreated kass carries nothing of its
+// predecessor's grant: no object at the key, and a GET that shows nothing.
+func wantCleanSuccessor(t *testing.T, fx *policyFx) {
+ t.Helper()
+ if !fx.hasApp(t, "kass") {
+ t.Fatal("kass was not recreated")
+ }
+ fx.noObject(t, "kass")
+ if g := fx.get(t, "kass"); len(g.Policy.EgressAllow) != 0 || g.Policy.DefaultSize != "" || g.ETag != "" {
+ t.Fatalf("the recreated app's policy = %+v etag %q, want empty", g.Policy, g.ETag)
+ }
+}
+
+const firstGrant = `{"egress_allow":["10.0.5.20"],"default_size":"xlarge"}`
+
+// The reviewer's interleaving: a first grant has found the app, and before
+// it takes the policy lock the app is trashed, purged and its name created
+// again. The write is refused and writes nothing; the new app starts empty.
+// Fails without policyStillTheApp.
+func TestPolicyGrantAdmittedBeforeAPurgeAndRecreateIsRefused(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-stale-before-lock")
+ fx.leased()
+ c := newBrowser(t)
+ signUp(t, fx.consoleFixture, c, "code-policy-stale-before-lock-web")
+ csrf := sessionToken(t, fx.consoleFixture, c)
+ p := newPausePoint()
+ fx.srv.policyBeforeLock = func(_, app string) {
+ if app == "kass" {
+ p.hit()
+ }
+ }
+
+ res := fx.putAsync(t, "kass", firstGrant, policyCreate)
+ <-p.paused
+ trashKass(t, fx.consoleFixture, "paul@keymail.dev", time.Now())
+ purgeAndRecreate(t, fx, c, csrf)
+ close(p.resume)
+ r := <-res
+ if r.status != http.StatusConflict || errorOf(t, r.out) != policyAppReplacedMsg {
+ t.Fatalf("PUT = %d %s, want 409 %q", r.status, r.out, policyAppReplacedMsg)
+ }
+ wantCleanSuccessor(t, fx)
+ if row := fx.row(t, "kass"); row.Revision != 0 {
+ t.Fatalf("the refused write recorded %+v", row)
+ }
+ if evs := fx.policyEvents(t, "kass"); len(evs) != 0 {
+ t.Fatalf("the refused write was audited: %+v", evs)
+ }
+}
+
+// The controlled interleaving through policyAfterBase: a first grant holds
+// the lock having read an absent base; the app is trashed, and its purge and
+// a recreate are started. The purge waits for the lock; the grant, checking
+// the app again under the lock, finds it trashed and writes nothing; then
+// the purge and the recreate finish and the new app starts empty. Fails
+// without policyStillTheApp (200, a recorded revision) and, with it gone as
+// well as PurgeAppRow's lock (HEAD 540690f4), the new app inherits the grant.
+func TestPolicyGrantPausedAfterItsBaseReadOutlivesNoPurge(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-stale-after-base")
+ fx.leased()
+ c := newBrowser(t)
+ signUp(t, fx.consoleFixture, c, "code-policy-stale-after-base-web")
+ csrf := sessionToken(t, fx.consoleFixture, c)
+ p := newPausePoint()
+ fx.srv.policyAfterBase = func(_, app string) {
+ if app == "kass" {
+ p.hit()
+ }
+ }
+ waiting := nameWaits(fx.st, OpsAccountID, "kass")
+
+ res := fx.putAsync(t, "kass", firstGrant, policyCreate)
+ <-p.paused
+ trashKass(t, fx.consoleFixture, "paul@keymail.dev", time.Now())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ purgeAndRecreate(t, fx, c, csrf)
+ }()
+ select {
+ case <-waiting: // the purge waits for the grant's lock
+ case <-done: // a purge that takes no lock
+ }
+ close(p.resume)
+ r := <-res
+ <-done
+ if r.status != http.StatusConflict || errorOf(t, r.out) != policyAppReplacedMsg {
+ t.Fatalf("PUT = %d %s, want 409 %q", r.status, r.out, policyAppReplacedMsg)
+ }
+ wantCleanSuccessor(t, fx)
+ if row := fx.row(t, "kass"); row.Revision != 0 {
+ t.Fatalf("the refused write recorded %+v", row)
+ }
+}
+
+// A purge waits for a publication in flight: the grant has passed its check
+// and is writing the object when the app is trashed and its purge and a
+// recreate start. The write lands on the app it was for; the purge then
+// frees the name and the recreate clears what the write left, so the new
+// app starts empty. Fails if PurgeAppRow takes no lock: the recreate lands
+// before the write, which then lands on the new app.
+func TestAPurgeWaitsForAPolicyPublicationInFlight(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-purge-waits")
+ fx.leased()
+ c := newBrowser(t)
+ signUp(t, fx.consoleFixture, c, "code-policy-purge-waits-web")
+ csrf := sessionToken(t, fx.consoleFixture, c)
+ hs := &appPolicyHookStore{Store: fx.rel, key: apppolicy.Key(fx.sqid, "kass")}
+ fx.srv.cfg.Releases = hs
+ p := newPausePoint()
+ hs.hook = func(context.Context, int, []byte, string) (bool, string, error) {
+ p.hit()
+ return false, "", nil
+ }
+ waiting := nameWaits(fx.st, OpsAccountID, "kass")
+
+ res := fx.putAsync(t, "kass", firstGrant, policyCreate)
+ <-p.paused
+ trashKass(t, fx.consoleFixture, "paul@keymail.dev", time.Now())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ purgeAndRecreate(t, fx, c, csrf)
+ }()
+ select {
+ case <-waiting:
+ case <-done:
+ }
+ close(p.resume)
+ r := <-res
+ <-done
+ if r.status != http.StatusOK {
+ t.Fatalf("PUT = %d %s, want 200: the write was for the app it found", r.status, r.out)
+ }
+ wantCleanSuccessor(t, fx)
+}
+
+// Every path that frees a name or moves an app onto one waits for the
+// name's policy lock and counts the change.
+func TestNameFreeingPathsWaitForThePolicyLock(t *testing.T) {
+ t.Parallel()
+ type world struct {
+ fx *consoleFixture
+ run func() // the name-freeing operation
+ // lockOn is the name the test holds; changed reports whether the
+ // operation has happened.
+ lockOn appNameKey
+ changed func(t *testing.T) bool
+ }
+ for _, tc := range []struct {
+ name string
+ setup func(t *testing.T) world
+ }{
+ {"purge", func(t *testing.T) world {
+ fx := newConsoleFixture(t)
+ if err := fx.st.TrashAppRow(OpsAccountID, "kass", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return world{fx: fx, lockOn: appNameKey{OpsAccountID, "kass"},
+ run: func() {
+ if err := fx.st.PurgeAppRow(OpsAccountID, "kass"); err != nil {
+ t.Errorf("purge: %v", err)
+ }
+ },
+ changed: func(t *testing.T) bool {
+ live, trashed, err := fx.st.AppNameState(OpsAccountID, "kass")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return !live && !trashed
+ }}
+ }},
+ {"move, the destination's name", func(t *testing.T) world {
+ fx := newConsoleFixture(t)
+ if err := fx.st.CreateAccount(42, "zzz", "Shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return world{fx: fx, lockOn: appNameKey{42, "kass"},
+ run: func() {
+ if err := fx.st.MoveApp("kass", OpsAccountID, 42); err != nil {
+ t.Errorf("move: %v", err)
+ }
+ },
+ changed: func(t *testing.T) bool {
+ has, err := fx.st.HasAppIn(42, "kass")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return has
+ }}
+ }},
+ {"rename door, the new name", func(t *testing.T) world {
+ fx := newConsoleFixture(t)
+ freshApp(t, fx, "sprout")
+ c := signInPaul(t, fx)
+ form := url.Values{"csrf": {sessionToken(t, fx, c)}, "to": {"sapling"}, "confirmed": {"1"}}
+ return world{fx: fx, lockOn: appNameKey{OpsAccountID, "sapling"},
+ run: func() {
+ if st, loc, body := postForm(t, c, fx.u("/apps/sprout/rename"), form); st != http.StatusSeeOther ||
+ loc != fx.path("/apps/sapling/settings") {
+ t.Errorf("rename = %d -> %q:\n%s", st, loc, body)
+ }
+ },
+ changed: func(t *testing.T) bool {
+ has, err := fx.st.HasAppIn(OpsAccountID, "sapling")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return has
+ }}
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ w := tc.setup(t)
+ before := w.fx.st.appName(w.lockOn.accountID, w.lockOn.app).freed.Load()
+ waiting := nameWaits(w.fx.st, w.lockOn.accountID, w.lockOn.app)
+ mu := w.fx.st.AppPolicyLock(w.lockOn.accountID, w.lockOn.app)
+ mu.Lock()
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ w.run()
+ }()
+ select {
+ case <-waiting:
+ case <-done:
+ mu.Unlock()
+ t.Fatal("the operation finished while the name's policy lock was held")
+ }
+ if w.changed(t) {
+ mu.Unlock()
+ t.Fatal("the operation changed the name while the policy lock was held")
+ }
+ mu.Unlock()
+ <-done
+ if !w.changed(t) {
+ t.Fatal("the operation did not happen after the lock was released")
+ }
+ if after := w.fx.st.appName(w.lockOn.accountID, w.lockOn.app).freed.Load(); after == before {
+ t.Fatal("the operation did not count the name as changed")
+ }
+ })
+ }
+}
+
+// ---- final review finding 3: rename refuses over policy state ------------
+
+// renameSprout posts a confirmed rename of sprout to sapling through the real
+// door and returns where it redirected and the page shown there.
+func renameSprout(t *testing.T, fx *consoleFixture, c *http.Client) (string, string) {
+ t.Helper()
+ st, loc, body := postForm(t, c, fx.u("/apps/sprout/rename"),
+ url.Values{"csrf": {sessionToken(t, fx, c)}, "to": {"sapling"}, "confirmed": {"1"}})
+ if st != http.StatusSeeOther {
+ t.Fatalf("rename = %d:\n%s", st, body)
+ }
+ notACard(t, body)
+ _, _, page := get(t, c, fx.ts.URL+loc)
+ return loc, page
+}
+
+// Final review finding 3, through the real rename door: a rename is refused
+// when either name has policy state, a policy object at its key or a
+// revision row, and nothing moves. Fails without renamePolicyRefusal: the
+// app's policy stays at the old name for the next app to take it.
+func TestRenameRefusedWhileEitherNameHasAnAppPolicy(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ toMsg := strings.Replace(renamePolicyToMsg, "%s", "sapling", 1)
+ for _, tc := range []struct {
+ name string
+ seed func(t *testing.T, fx *policyFx)
+ want string // the flash; "" for a rename that goes ahead
+ }{
+ {"the app has a policy", func(t *testing.T, fx *policyFx) {
+ fx.mustPut(t, "sprout", firstGrant, policyCreate)
+ }, renamePolicyFromMsg},
+ {"the app has a revision row only", func(t *testing.T, fx *policyFx) {
+ wire := signPolicy(t, fx.consoleFixture, apppolicy.Policy{V: 1, Account: fx.sqid, App: "sprout", Revision: 1,
+ SignedAt: time.Now().UTC(), DefaultSize: "large"})
+ if err := fx.st.RecordAppPolicyContext(ctx, OpsAccountID, "sprout", 1, wire); err != nil {
+ t.Fatal(err)
+ }
+ }, renamePolicyFromMsg},
+ {"the new name has an earlier app's policy object", func(t *testing.T, fx *policyFx) {
+ seedPredecessorPolicy(t, fx.consoleFixture, "sapling")
+ }, toMsg},
+ {"the new name has a revision row only", func(t *testing.T, fx *policyFx) {
+ wire := signPolicy(t, fx.consoleFixture, apppolicy.Policy{V: 1, Account: fx.sqid, App: "sapling", Revision: 3,
+ SignedAt: time.Now().UTC(), DefaultSize: "large"})
+ if err := fx.st.RecordAppPolicyContext(ctx, OpsAccountID, "sapling", 3, wire); err != nil {
+ t.Fatal(err)
+ }
+ }, toMsg},
+ {"control: neither name has one", func(*testing.T, *policyFx) {}, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-rename-policy-"+claimSafeName(tc.name))
+ freshApp(t, fx.consoleFixture, "sprout")
+ tc.seed(t, fx)
+ sproutObj := policyObject(t, fx.consoleFixture, "sprout")
+ saplingObj := policyObject(t, fx.consoleFixture, "sapling")
+ c := signInPaul(t, fx.consoleFixture)
+ loc, page := renameSprout(t, fx.consoleFixture, c)
+ if tc.want == "" {
+ if loc != fx.path("/apps/sapling/settings") || !fx.hasApp(t, "sapling") || fx.hasApp(t, "sprout") {
+ t.Fatalf("rename -> %q; want it done:\n%s", loc, page)
+ }
+ return
+ }
+ if loc != fx.path("/apps/sprout/settings") || !strings.Contains(html.UnescapeString(page), tc.want) {
+ t.Fatalf("rename -> %q, want the flash %q:\n%s", loc, tc.want, page)
+ }
+ if !fx.hasApp(t, "sprout") || fx.hasApp(t, "sapling") {
+ t.Fatal("the refused rename moved the app")
+ }
+ if got := policyObject(t, fx.consoleFixture, "sprout"); !bytes.Equal(got, sproutObj) {
+ t.Fatalf("sprout's policy object changed: %s", got)
+ }
+ if got := policyObject(t, fx.consoleFixture, "sapling"); !bytes.Equal(got, saplingObj) {
+ t.Fatalf("sapling's policy object changed: %s", got)
+ }
+ })
+ }
+}
+
+// A grant that lands after the rename's first check, while the rename waits
+// for the names' policy locks, still refuses the rename: the check runs
+// again under the locks. Fails without the second renamePolicyRefusal.
+func TestRenameRechecksThePolicyUnderTheLocks(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-rename-policy-recheck")
+ freshApp(t, fx.consoleFixture, "sprout")
+ var once sync.Once
+ fx.st.setAppNameWaiting(func(_ int64, app string) {
+ if app == "sapling" || app == "sprout" {
+ once.Do(func() {
+ st, _, out := policyReq(t, fx.consoleFixture, http.MethodPut, "sprout", fx.owner, firstGrant, policyCreate)
+ if st != http.StatusOK {
+ t.Errorf("grant during the rename = %d %s", st, out)
+ }
+ })
+ }
+ })
+ c := signInPaul(t, fx.consoleFixture)
+ loc, page := renameSprout(t, fx.consoleFixture, c)
+ if loc != fx.path("/apps/sprout/settings") || !strings.Contains(html.UnescapeString(page), renamePolicyFromMsg) {
+ t.Fatalf("rename -> %q, want the flash %q:\n%s", loc, renamePolicyFromMsg, page)
+ }
+ if !fx.hasApp(t, "sprout") || fx.hasApp(t, "sapling") {
+ t.Fatal("the rename went ahead over the grant")
+ }
+ if _, _, etag := fx.stored(t, "sprout"); etag == "" {
+ t.Fatal("the grant is gone from sprout's key")
+ }
+}
+
+func (fx *policyFx) hasApp(t *testing.T, app string) bool {
+ t.Helper()
+ has, err := fx.st.HasAppIn(OpsAccountID, app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return has
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 3a0f37384..aa3ac57c1 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -31,6 +31,7 @@ import (
"context"
"crypto/subtle"
"errors"
+ "fmt"
"log"
"net/http"
"net/url"
@@ -843,6 +844,12 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
back("err", "Cannot rename to "+to+": "+apexHeldSentence(s.apexHost(acct.Sqid, to), hold)+".")
return
}
+ // Neither name may carry an app policy (#328, #329), checked here as
+ // advice and again under both names' policy locks below.
+ if msg := s.renamePolicyRefusal(ctx, acct, app, to); msg != "" {
+ back("err", msg)
+ return
+ }
if !confirmed(r) {
cv := &ConfirmView{
Title: "Rename " + app + " to " + to + "?",
@@ -860,6 +867,15 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
s.renderConfirm(w, r, addr, raw, acct, role, app, cv)
return
}
+ // Both names' policy locks, held through the rename and any undo: no
+ // policy write lands on either name between the check and the rename,
+ // and the rename counts both names as changed for a write already in
+ // flight (apppolicy_names.go, policyStillTheApp).
+ defer s.store.lockAppNames(appNameKey{acct.ID, app}, appNameKey{acct.ID, to})()
+ if msg := s.renamePolicyRefusal(ctx, acct, app, to); msg != "" {
+ back("err", msg)
+ return
+ }
if err := s.store.RenameAppIn(acct.ID, app, to); err != nil {
log.Printf("console: rename %s/%s -> %s: %v", acct.Sqid, app, to, err)
back("err", renameAdvice(err, to))
@@ -898,6 +914,40 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, appSettingsURL(acct.Sqid, to, "general"), http.StatusSeeOther)
}
+// Rename refusals over an app policy (#328, #329; final review finding 3).
+const (
+ renamePolicyFromMsg = "This app has had an instance policy set by an operator, so it cannot be renamed. Create a new app instead."
+ renamePolicyToMsg = "The name %s has had an instance policy set by an operator, so no app can be renamed to it. Choose another name."
+ renamePolicyCheckMsg = "Could not check the instance policies, so nothing was renamed. Try again."
+)
+
+// renamePolicyRefusal is the rename's refusal when either name has policy
+// state: a policy object at its key, or a revision row in this console's
+// table. A policy lives at its name's key, signed for that name, and its
+// revisions are recorded under the name, so a rename would leave both
+// behind: the renamed app would lose its settings, and the next app to take
+// the old name by a rename (which, unlike a create, clears nothing) would
+// inherit them. Moving a policy to another name is out of scope; an operator
+// handles it. A failed check refuses ("" means the rename may go ahead).
+func (s *Server) renamePolicyRefusal(ctx context.Context, acct *Account, from, to string) string {
+ for _, name := range []string{from, to} {
+ present, err := s.appPolicyPresent(ctx, acct, name)
+ if err == nil && !present {
+ present, err = s.store.HasAppPolicyRevisionContext(ctx, acct.ID, name)
+ }
+ switch {
+ case err != nil:
+ log.Printf("console: rename %s/%s -> %s: policy state of %s: %v", acct.Sqid, from, to, name, err)
+ return renamePolicyCheckMsg
+ case present && name == from:
+ return renamePolicyFromMsg
+ case present:
+ return fmt.Sprintf(renamePolicyToMsg, to)
+ }
+ }
+ return ""
+}
+
// renameAdvice maps RenameAppIn's refusals onto the sentence a person can
// act on, without leaking storage details they cannot.
func renameAdvice(err error, to string) string {
diff --git a/internal/console/claim_app_enroll.go b/internal/console/claim_app_enroll.go
index 7e15941a0..e365ab6c1 100644
--- a/internal/console/claim_app_enroll.go
+++ b/internal/console/claim_app_enroll.go
@@ -32,9 +32,12 @@ func (e policyWriterRefused) Error() string {
// as it did before the clear existed: a lost policy lease (a crashed console,
// or a release denied by the region-host s3:DeleteObject Deny) never blocks
// the create of a name without a policy. Nothing can write a policy for the
-// name between that read and the insert, because the policy door only writes
-// for an app whose row exists, and a concurrent create of the name still
-// loses at the unique insert.
+// name between that read and the insert: the policy door writes only for the
+// live app it found at its start, checked again under the app's policy lock
+// right before it writes (policyStillTheApp), and every path that frees a
+// name holds that lock and counts the change (apppolicy_names.go), so a write
+// admitted for an earlier app of the name is refused rather than landing on
+// this one. A concurrent create of the name still loses at the unique insert.
//
// A present object is cleared inside policy publication's exclusion: the
// app's policyLock, held until the insert has returned, and a live writer
@@ -52,7 +55,7 @@ func (s *Server) createClaimAppRow(ctx context.Context, acct *Account, app strin
if !present {
return s.insertClaimAppRow(ctx, acct, app, insert, nil)
}
- mu := s.policyLock(acct.Sqid, app)
+ mu := s.policyLock(acct.ID, app)
mu.Lock()
defer mu.Unlock()
hold, ref := s.policyWriter(ctx)
diff --git a/internal/console/server.go b/internal/console/server.go
index 222fccd7d..6958e14cd 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -996,24 +996,25 @@ type Server struct {
policyStopping bool
policyLog func(format string, args ...any)
policyAttemptEnding func()
- // The app policy door (apipolicy.go). policyLocks is each app's policy
- // mutex, keyed "<sqid>/<app>" and built lazily under policyLocksMu as
- // doorPublish is; the door and the re-sign pass share it. policySynced
+ // The app policy door (apipolicy.go). Each app's policy mutex is the
+ // store's (Store.AppPolicyLock, apppolicy_names.go), so the paths that
+ // free a name share it with the door and the re-sign pass. policySynced
// is, per app, the number of the last writer holding that chose a base
// for it, under policySyncedMu: an app not yet touched in the current
// holding builds on the bucket's record when another console may have
// written it (ruling 10). policyAfterBase is a TEST SEAM (nil in
// production), called right after policyBase returns in a write or a
// re-sign, so a test can pause a writer that has read its base.
+ // policyBeforeLock is a TEST SEAM too (nil in production), called by
+ // the PUT door after it found the app and before it takes the lock.
// policyListedN, under policyStateMu, is the holding the re-sign pass
// last listed control/app-policy/ in (0: not holding, never counted);
// policyDiscovered, also under policyStateMu, is every listed
// {sqid, app} with no row that no pass has processed yet.
- policyLocksMu sync.Mutex
- policyLocks map[string]*sync.Mutex
policySyncedMu sync.Mutex
policySynced map[string]uint64
policyAfterBase func(sqid, app string)
+ policyBeforeLock func(sqid, app string)
policyListedN uint64
policyDiscovered map[[2]string]bool
// sendApp is how the alert watcher (alertwatch.go) delivers keymail:
diff --git a/internal/console/store.go b/internal/console/store.go
index 9ea01e066..658cf0810 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -72,6 +72,10 @@ type Store struct {
// codeEpoch is a random per-process label stored in front of each
// code_mac, so a code minted by an earlier process is recognised as such.
codeEpoch string
+
+ // names is each app name's policy lock and freed count
+ // (apppolicy_names.go). A pointer, so a Store view shares it.
+ names *appNameLocks
}
func newStore(db *sql.DB) *Store {
@@ -81,7 +85,7 @@ func newStore(db *sql.DB) *Store {
_, _ = rand.Read(key)
ep := make([]byte, 8)
_, _ = rand.Read(ep)
- return &Store{codeEpoch: hex.EncodeToString(ep), db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64), codeKey: key}
+ return &Store{codeEpoch: hex.EncodeToString(ep), db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64), codeKey: key, names: &appNameLocks{}}
}
// Open opens (creating if needed) the console DB at path.
@@ -1769,7 +1773,12 @@ WHERE account_id = ? AND app = ?`, accountID, app)
// the row back while a marker delete failed elsewhere, or raced it) and the
// auto-purge pass this feeds must never be the thing that frees a serving
// app's name out from under it.
+//
+// It holds the name's policy lock (apppolicy_names.go), so it waits for a
+// policy write in flight for the app and counts the freed name before any
+// later write can start (#328, #329).
func (s *Store) PurgeAppRow(accountID int64, app string) error {
+ defer s.lockAppNames(appNameKey{accountID, app})()
ctx := context.Background()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
@@ -1780,7 +1789,8 @@ func (s *Store) PurgeAppRow(accountID int64, app string) error {
if err != nil {
return err
}
- if n, _ := res.RowsAffected(); n > 0 {
+ n, _ := res.RowsAffected()
+ if n > 0 {
// The name is free from here, so nothing keyed by it may outlive the
// row (mailevents.go): a later app of the same name starts clean.
var sqid string
@@ -1807,7 +1817,13 @@ func (s *Store) PurgeAppRow(accountID int64, app string) error {
return err
}
}
- return tx.Commit()
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ if n > 0 {
+ s.appNameFreed(accountID, app)
+ }
+ return nil
}
// TrashedApp is one app in an account's Trash: past-tense on purpose, since a
@@ -1950,7 +1966,21 @@ func (s *Store) AppAccounts(app string) ([]int64, error) {
// do, so an operator who is unsure whether the move landed can simply run it
// again. Moving onto a name the destination already claims is REFUSED rather
// than merged — those are two different apps, and one of them would vanish.
+//
+// It holds the policy locks of the name in both accounts
+// (apppolicy_names.go) and counts both as freed: the source's name no longer
+// names the app, and the destination's names a different one (#328, #329).
func (s *Store) MoveApp(app string, from, to int64) error {
+ defer s.lockAppNames(appNameKey{from, app}, appNameKey{to, app})()
+ if err := s.moveApp(app, from, to); err != nil {
+ return err
+ }
+ s.appNameFreed(from, app)
+ s.appNameFreed(to, app)
+ return nil
+}
+
+func (s *Store) moveApp(app string, from, to int64) error {
tx, err := s.db.Begin()
if err != nil {
return err
@@ -2089,6 +2119,11 @@ LIMIT 1`, cliKindService, to, cliKindService, from, app).Scan(&collidingName)
// tokens (both kinds), which are bound (account, name) and would otherwise
// 404 the running app while retaining authority over the freed name. The
// rename itself is the caller's audit line.
+//
+// The caller also holds both names' policy locks (Store.lockAppNames) and
+// has refused a name with policy state (#328, #329; handleAppRename): a
+// policy stays at its name's key, so a rename would leave it behind for the
+// next app to take the name.
func (s *Store) RenameAppIn(accountID int64, from, to string) error {
return s.renameAppIn(accountID, from, to, false)
}
@@ -2163,7 +2198,14 @@ func (s *Store) renameAppIn(accountID int64, from, to string, undo bool) error {
if err := carryMailApp(context.Background(), tx, sqid, from, sqid, to, createdAt); err != nil {
return err
}
- return tx.Commit()
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ // Both names changed what they name (apppolicy_names.go); the rename
+ // door holds both names' policy locks around this call.
+ s.appNameFreed(accountID, from)
+ s.appNameFreed(accountID, to)
+ return nil
}
// HasApp reports whether an app name is claimed in the apps table.