app-region-set: Astra round 2 fixes
The browser door resolves the app's incarnation before it reads the form body. The operator's any-account branch needs ?exact=sqid, so a name never loses to another account's sqid. The write also requires the app to be unplaced, so a fleet placement made meanwhile stops it. Round 2 findings and the round 3 brief committed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+267
−66
docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md+65 −0docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md+11 −11docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md+37 −38internal/console/appregionset.go+38 −14internal/console/appregionset_test.go+109 −0internal/console/store.go+6 −2internal/provision/testdata/plan14-root-reads-app-region-set.tsv+1 −1
CI passed — run details
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md| new file mode 100644 |
| index 000000000..855017976 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md |
| @@ -0,0 +1,65 @@ |
| +- **Round 1 P1, closed-door count — resolved.** The inventory and assertion both require 66. |
| +- **Round 1 P1, write identity — partly resolved; P1 remains.** API and store checks are fixed, but the browser still captures identity after its initial app lookup. |
| +- **Round 1 P2, operator paths — resolved under the Round 2 ruling.** Member operators retain authority; non-member operators use the CLI. |
| +- **Round 1 P2, pooled display — resolved.** CLI output now distinguishes the stored region from pooled placement. |
| +- **Round 1 P2, unnamed home — resolved.** Writes are refused before region validation when the home is unnamed. |
| + |
| +Reviewed `6f8d3b5c114bcb376d9e84d49855feb150ff83ec` against `origin/main` at `b1d00ca7d84dd2c158151469f9fd40283707e33b`. No files changed. |
| + |
| +1. **P1 — Write identity: the browser can still change a replacement app.** |
| + |
| + [handleAppRegionSet:405](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:405) first calls `accountApp`, whose [existence check:3701](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:3701) captures no incarnation. It then calls `FormValue("csrf")`, parsing the request body, before capturing identity at [appregionset.go:427](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:427). |
| + |
| + **Failure scenario:** the handler finds `shop`; form-body reading pauses; another request renames `shop` away and creates a replacement; form reading resumes. The handler captures the replacement’s incarnation. Both later comparisons succeed, and it changes and audits the replacement. |
| + |
| + The [replacement test:488](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:488) supplies an already-captured incarnation directly to `setAppRegion`. It cannot catch this handler-level window. |
| + |
| + **Fix:** establish one app-resolution boundary that returns the incarnation with the existence result, and preserve that identity through the mutation. Add a browser-handler test that pauses body reading while the name is replaced. |
| + |
| + **Fault family:** a mutation must affect the app incarnation the request originally resolved. This is the unresolved Round 1 invariant. |
| + |
| +2. **P1 — Account resolution: an operator’s name-based API request can mutate another account.** |
| + |
| + [appRegionCaller:124](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:124) tries a global `AccountBySqid` lookup and immediately returns its result. It does this even without `?exact=sqid`, before considering the caller’s account-name matches. |
| + |
| + **Failure scenario:** an operator belongs to account A, named `cdef`, while account B has sqid `cdef`. Both contain `shop`. A direct `PUT /api/cli/apps/cdef/shop/region` intended to address A by name changes B instead. Creating B can therefore change what an existing name-based request targets. |
| + |
| + The shared resolver explicitly rejects this precedence because it silently changes the target account: [apicli.go:172](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/apicli.go:172). The new [operator-name test:465](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:465) uses a non-colliding name. The CLI canonicalizes its reference, so this finding concerns direct API requests. |
| + |
| + **Fix:** preserve collision detection for non-exact requests. Refuse a membership-name/global-sqid collision and require `?exact=sqid`; retain operators’ approved access to non-member accounts by explicit sqid. |
| + |
| + **Fault family:** account references must not silently select a different tenant when another matching identifier exists. |
| + |
| +3. **P2 — Concurrent placement: the fleet refusal can become stale before the write.** |
| + |
| + Fleet placement is checked at [appregionset.go:298](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:298), before `lockApp`. The placement writer at [fleets.go:657](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/fleets.go:657) does not share that lock. Neither incarnation comparison includes placement, and the [UPDATE predicate:1716](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1716) checks only identity, live state and the previous region. |
| + |
| + **Failure scenario:** region validation observes an unplaced app; a concurrent placement commits `fleet/racks`; the region write then succeeds and reports that new instances start in the selected region, although the fleet now governs them. I executed the exact UPDATE against in-memory SQLite after that placement transition: it affected one row. |
| + |
| + **Fix:** make the validated placement part of the atomic write condition, or serialize placement validation and mutation with the placement writer. Add a controlled concurrent-placement test. |
| + |
| + **Fault family:** the placement prerequisite for changing the default must remain valid when the write commits. |
| + |
| +No P3 findings. |
| + |
| +Stopping rule 2 applies to the repeated write-identity finding. Before another patch, choose between refusing the case up front, removing the browser write, or enforcing the incarnation invariant at one shared boundary with a controlled race test. I recommend the shared boundary. |
| + |
| +The remaining reader paths do not move or rewrite existing instances. Seeded creates pass through the same defaulting checks; deploy and canary compare the stored region; `changed` is accepted as display metadata. The migration adds and preserves `region_set_at`, and main’s already-rebuilt schema path remains structurally compatible. GET and the added page control introduce no bucket reads or polling. |
| + |
| +The targeted Go tests could not start because the read-only sandbox prevented creation of Go’s work directory. This is a validation limitation, not a failing test result. The inspected new Go files are formatted. `git diff --check` reports trailing spaces in the committed Round 1 findings Markdown. |
| + |
| +Census verdicts for this tip: |
| + |
| +| Unit or envelope | Verdict and evidence | |
| +|---|---| |
| +| `NewServer` | **Approve.** [server.go:1738](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:1738): route registration only; existing read basis unchanged. | |
| +| `Store.NonHomeAppRegions` | **Approve.** [store.go:1735](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1735): same console-owned query, with the later discrepancy cutoff. | |
| +| `Store.migrate` | **Approve.** [store.go:574](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:574): additive column through existing execution sites. | |
| +| `Store.migrateAppsKey` | **Approve.** [store.go:715](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:715), [store.go:734](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:734): preserves the column in the existing transactional rebuild. | |
| +| Template `external` unit | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): embedded form and CSRF field; no new read authority. | |
| +| `.` envelope | **Approve.** [apps.go:159](/home/paulca/amadan.net/carlos/platform-app-region/apps.go:159), [apps_region_cmd.go:55](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:55): dispatch, authenticated API calls and formatting; no new root execution or filesystem authority. | |
| +| `internal/console` envelope | **Approve.** [appregionset.go:118](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:118), [appregionset.go:251](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:251), [store.go:1710](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1710), [server.go:4440](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:4440): configured stores and console-owned SQLite; host-claim writes remain refused. The findings above do not expand root-read targets or weaken the recorded root-read basis. | |
| +| `internal/console/templates` envelope | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): unchanged embedded-template boundary. | |
| +| `internal/regionlabel` envelope | **Approve.** [regionlabel.go:81](/home/paulca/amadan.net/carlos/platform-app-region/internal/regionlabel/regionlabel.go:81): sorts existing in-memory keys; no I/O. | |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md| index ce4c87e02..b8336c461 100644 |
| --- a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md |
| @@ -1,40 +1,40 @@ |
| Reviewed round 1 of 3 at `f686d3d5e26efd000f144e10a94318f96a7f65e5` against `origin/main` (`b1d00ca7d84dd2c158151469f9fd40283707e33b`). No files changed. |
| -1. **P1 — Tests: the closed-route test necessarily fails.** |
| - The two additions at [svcroutes_test.go:260](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:260) increase `closedDoors` from 64 to 66. [Line 1103](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:1103) still requires `seen == 64`. Even when every authorization refusal succeeds, the test fails its final assertion. I verified both list counts directly from the Git revisions. |
| - **Fix:** update the expected count and its explanatory message to include both region routes, then run this targeted test. |
| +1. **P1 — Tests: the closed-route test necessarily fails.** |
| + The two additions at [svcroutes_test.go:260](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:260) increase `closedDoors` from 64 to 66. [Line 1103](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:1103) still requires `seen == 64`. Even when every authorization refusal succeeds, the test fails its final assertion. I verified both list counts directly from the Git revisions. |
| + **Fix:** update the expected count and its explanatory message to include both region routes, then run this targeted test. |
| **Fault family:** the security-route inventory and its executable assertion must agree. |
| -2. **P1 — Write identity: an in-flight request can change a replacement app.** |
| +2. **P1 — Write identity: an in-flight request can change a replacement app.** |
| [appRegionApp](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:148) checks existence without capturing an incarnation. The first incarnation read occurs at [appregionset.go:311](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:311), after request parsing, remote reads and policy validation. |
| If `shop` is renamed away or purged and recreated during that interval, the handler captures the replacement’s incarnation and writes its region. The SQL comparison succeeds because it compares against the replacement it just read. Earlier policy checks can also belong to the previous app. |
| Furthermore, [SetAppRegion](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1705) ignores `AppIncarnation.freed`, comparing only second-resolution `created_at`. An in-memory check using the exact SQL confirmed that replacing a row with the same timestamp permits the stale update. |
| - **Fix:** capture the incarnation when resolving the app, then compare the complete identity under the existing app/name locking discipline before validation and commit. Preserve identity through the write. Add controlled rename/recreate and same-second replacement tests. |
| + **Fix:** capture the incarnation when resolving the app, then compare the complete identity under the existing app/name locking discipline before validation and commit. Preserve identity through the write. Add controlled rename/recreate and same-second replacement tests. |
| **Fault family:** a mutation must affect the app incarnation the request originally resolved. |
| -3. **P2 — Authorization: operator permission is lost on two supported paths.** |
| +3. **P2 — Authorization: operator permission is lost on two supported paths.** |
| The browser handler calls `accountApp` at [appregionset.go:394](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:394). Its underlying [account gate](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:2696) searches memberships only. An ops owner or listed system operator who is not a member receives 404 before CSRF or operator authorization is checked. They also cannot reach the Settings control. |
| Separately, an operator who is an ordinary member and addresses the API by account name falls through to [appregionset.go:139](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:139), which requires ownership and forgets their operator status. The equivalent sqid request succeeds. |
| - **Fix:** retain operator authority through account resolution; implement the browser’s session → CSRF → owner/operator gate and provide access to the advertised control. Add browser tests for both operator kinds without membership, and API tests for the name fallback. |
| + **Fix:** retain operator authority through account resolution; implement the browser’s session → CSRF → owner/operator gate and provide access to the advertised control. Add browser tests for both operator kinds without membership, and API tests for the name fallback. |
| **Fault family:** equivalent authorized requests must retain the same owner-or-operator permission. |
| -4. **P2 — CLI output: stored region is presented as effective placement for pooled apps.** |
| +4. **P2 — CLI output: stored region is presented as effective placement for pooled apps.** |
| [apps_region_cmd.go:106](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:106) always prints “new instances start there” for a non-fleet app. GET returns the stored region without reading pool policy. An app storing `uk` with a pooled manifest therefore reports London, although [regiondefault.go:70](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regiondefault.go:70) explicitly makes its no-region pooled creates use the home. |
| - **Fix:** describe GET’s result as the stored app region and qualify its applicability. Preserve the zero-bucket-read GET budget. Add a pooled-app output case and correct the equivalent documentation claim. |
| + **Fix:** describe GET’s result as the stored app region and qualify its applicability. Preserve the zero-bucket-read GET budget. Add a pooled-app output case and correct the equivalent documentation claim. |
| **Fault family:** stored defaults must not be presented as effective placement when another policy overrides them. |
| -5. **P2 — Configuration: an unnamed home makes the change one-way.** |
| +5. **P2 — Configuration: an unnamed home makes the change one-way.** |
| [appregionset.go:253](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:253) rejects an empty value but permits an eligible non-home code without requiring `HomeRegion`. With no named home, [explicitChoices](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regionclaim.go:83) omits the home, and [homeRegionIn](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/apiinstancemove.go:312) cannot map any nonempty input to it. |
| Consequently, a console with eligible `uk` boxes and no `CONSOLE_HOME_REGION` can change an app to `uk`, but neither this command nor an explicit instance-region value can select the home afterward. |
| - **Fix:** require a named home before accepting a non-home default, while retaining the approved switch-off behavior when the home is named. Test this configuration explicitly. |
| + **Fix:** require a named home before accepting a non-home default, while retaining the approved switch-off behavior when the home is named. Test this configuration explicitly. |
| **Fault family:** every stored non-home default must leave the home explicitly selectable. |
| No P3 findings. |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md| index 08a9080c6..65de99101 100644 |
| --- a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md |
| @@ -1,4 +1,4 @@ |
| -# Review brief: branch app-region-set (carlos apps region), round 2 of 3 |
| +# Review brief: branch app-region-set (carlos apps region), round 3 of 3 |
| Repo carlos/platform, branch `app-region-set`, commit named in the prompt |
| (the commit that adds this brief). |
| @@ -118,43 +118,42 @@ something, with evidence): |
| follow anything from a tenant-, app- or box-writable path or input, or |
| a check the basis relies on is weakened. |
| -## Round 2 |
| - |
| -Earlier rounds: round 1, `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md` |
| -(Astra, at f686d3d5; 2 P1, 3 P2; census approved). The round number counts |
| -every earlier review of this change. |
| - |
| -First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| -Carry every unresolved or partly resolved finding forward at its current |
| -severity, then add new findings. The verdict covers everything |
| -outstanding, earlier rounds included. The builder's dispositions: |
| - |
| -1. P1 closed-door count: the test now expects 66 and names the two |
| - region doors (svcroutes_test.go). |
| -2. P1 write identity: the API resolves the incarnation with the app |
| - (`appRegionApp`); the browser captures it right after its gates; |
| - `setAppRegion` re-reads it under `lockApp` and compares the whole |
| - `AppIncarnation`; `Store.SetAppRegion` takes the name lock that purge |
| - and rename hold, compares the whole incarnation again under it, then |
| - writes pinned to created_at and the region read. Test: |
| - `TestAppRegionSetRefusesAReplacedApp` (same-second purge and re-create). |
| -3. P2 operator paths: the member path keeps operator authority |
| - (`principalPlatformOperator`), tested by name in the API and in the |
| - browser (`TestAppRegionSetMemberOperator`). Ruling: the browser control |
| - serves members only (owners and member operators), because every |
| - account page is a member page; an operator who is no member uses the |
| - CLI. The docs now say so. |
| -4. P2 pooled display: AR-32 and the docs (Luna pass 3) no longer claim the |
| - region decides where a pooled app's instances start; GET still reads |
| - no bucket object. |
| -5. P2 unnamed home: refused up front (AR-22) when the console names no |
| - home region; `TestAppRegionSetNeedsANamedHome`. |
| - |
| -CI at f686d3d5 also failed the record-write census (two re-pinned route |
| -registrations); `internal/provision/app_region_set_census_test.go` layers |
| -the two new digests. Census: the root-read overlay was re-proposed under |
| -the same name (the console and root envelopes re-pinned); give the |
| -envelope verdicts again for the changed code. |
| +## Round 3 |
| + |
| +Earlier rounds: round 1 `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md` |
| +(f686d3d5: 2 P1, 3 P2), round 2 `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md` |
| +(6f8d3b5c: 2 P1, 1 P2; round 1's five dispositions recorded there). This is |
| +the last round the stopping rules allow. Stopping rule 2 has triggered for |
| +the write-identity family; this round's fix is the shared boundary you |
| +recommended. If a P1 remains in that family, say so and say whether |
| +refusing up front or cutting the browser write removes it. |
| + |
| +First give one line per round 2 P1 and P2: resolved, partly, or not. The |
| +builder's dispositions: |
| + |
| +1. P1 browser write identity: the browser door now resolves the app |
| + through `accountAppIncarnation`, whose existence check IS the |
| + incarnation read, before it reads the form body (CSRF included); |
| + `setAppRegion` and `Store.SetAppRegion` compare that incarnation as |
| + before. Test: `TestAppRegionBrowserRefusesAnAppReplacedMidRequest` |
| + pauses the body on a pipe, purges and re-creates the app, then |
| + finishes the body; it was watched to fail with the incarnation read |
| + moved after the CSRF check. |
| +2. P1 account collision: the operator branch (any account by sqid) is |
| + taken only with `?exact=sqid`, which the CLI always sends after |
| + resolving names against the caller's memberships; any other reference |
| + goes through `apiPrincipalAccount`'s symmetric member resolution. |
| + `exactSqidAsked` parses the raw query with `url.ParseQuery` (the |
| + census scanner reads a `.Query()` selector as a database read; this is |
| + URL parsing, named here so you can judge it). Test: |
| + `TestAppRegionSetNameNeverLosesToASqid`, watched to fail without the |
| + exact condition. |
| +3. P2 concurrent placement: `Store.SetAppRegion`'s UPDATE also requires |
| + `placement = ''`, the state the door validated (the placement writer |
| + writes that column). Test: `TestAppRegionSetRefusesAPlacementMadeMeanwhile`. |
| + |
| +CI passed at 6f8d3b5c. The census overlay was re-proposed under the same |
| +name (the console envelope re-pinned); give the envelope verdict again. |
| ## Severity |
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go| index aaa53a431..7a82647a5 100644 |
| --- a/internal/console/appregionset.go |
| +++ b/internal/console/appregionset.go |
| @@ -28,6 +28,7 @@ import ( |
| "fmt" |
| "log" |
| "net/http" |
| + "net/url" |
| "slices" |
| "sort" |
| "strings" |
| @@ -109,8 +110,11 @@ type appRegionView struct { |
| } |
| // appRegionCaller resolves the account a person may read or change an app's |
| -// region in. A deployment operator reaches any account by sqid; anyone else |
| -// goes through apiPrincipalAccount, so an unknown account and someone |
| +// region in. A deployment operator reaches any account by an exact sqid |
| +// (?exact=sqid, which the CLI always sends); anyone else, and any other |
| +// reference, goes through apiPrincipalAccount, so a name is only ever |
| +// matched against the caller's own memberships and a sqid can never take |
| +// over a name (apicli.go's symmetric resolution), so an unknown account and someone |
| // else's are the family's byte-identical 404. write adds the owner rule |
| // (apiOwnerAccountFor's: a member gets a 403, since membership is already |
| // proved). A service principal never gets here (the route allows no role); |
| @@ -121,7 +125,7 @@ func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write b |
| http.NotFound(w, r) |
| return "", nil, false |
| } |
| - if s.principalPlatformOperator(p) { |
| + if s.principalPlatformOperator(p) && exactSqidAsked(r) { |
| a, err := s.store.AccountBySqid(r.PathValue("account")) |
| if err != nil { |
| log.Printf("console: app region: account: %v", err) |
| @@ -131,8 +135,7 @@ func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write b |
| if a != nil { |
| return p.Address, a, true |
| } |
| - // Not a sqid: an operator who is a member may still name the |
| - // account, through the member path below. |
| + // No such account: the member path answers the family's 404. |
| } |
| p, acct, ok = s.apiPrincipalAccount(w, r) |
| if !ok { |
| @@ -145,6 +148,13 @@ func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write b |
| return p.Address, acct, true |
| } |
| +// exactSqidAsked is the ?exact=sqid switch (--account-id, and every |
| +// reference the CLI has resolved), read as apiPrincipalAccount reads it. |
| +func exactSqidAsked(r *http.Request) bool { |
| + v, _ := url.ParseQuery(r.URL.RawQuery) |
| + return v.Get("exact") == "sqid" |
| +} |
| + |
| // appRegionApp is the {app} half: a live app and the incarnation the |
| // request found, or the Trash refusal for a trashed one (the caller may |
| // already see the Trash), else the bare 404. |
| @@ -402,7 +412,7 @@ func (s *Server) canSetAppRegion(addr, role string) bool { |
| // General control: session, CSRF, then the owner-or-operator rule, whose |
| // refusal is the same 404 a non-member gets. |
| func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| - addr, raw, acct, role, app, ok := s.accountApp(w, r) |
| + addr, raw, acct, role, app, found, ok := s.accountAppIncarnation(w, r) |
| if !ok { |
| return |
| } |
| @@ -424,14 +434,6 @@ func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| defer cancel() |
| - found, live, err := s.store.AppIncarnationContext(ctx, acct.ID, app) |
| - if err != nil || !live { |
| - if err != nil { |
| - log.Printf("console: app region %s/%s: incarnation: %v", acct.Sqid, app, err) |
| - } |
| - back("err", sentenceCase(appRegionSetCopy.Changed)) |
| - return |
| - } |
| v, ref := s.setAppRegion(ctx, acct, app, found, r.FormValue("region"), addr, "") |
| if ref != nil { |
| back("err", sentenceCase(ref.Msg)) |
| @@ -444,6 +446,28 @@ func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| back("ok", fmt.Sprintf(appRegionSetCopy.FlashChanged, v.Label)) |
| } |
| +// accountAppIncarnation is accountApp whose existence check IS the |
| +// incarnation read: the app the browser door resolves, before it reads the |
| +// form body, is the one setAppRegion must find again under its locks. |
| +// Every answer is accountApp's, byte for byte. |
| +func (s *Server) accountAppIncarnation(w http.ResponseWriter, r *http.Request) (addr, raw string, acct *Account, role, app string, inc AppIncarnation, ok bool) { |
| + addr, raw, acct, role, ok = s.account(w, r) |
| + if !ok { |
| + return "", "", nil, "", "", AppIncarnation{}, false |
| + } |
| + app = r.PathValue("app") |
| + inc, live, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app) |
| + if err != nil { |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.") |
| + return "", "", nil, "", "", AppIncarnation{}, false |
| + } |
| + if !live { |
| + s.renderMessage(w, r, http.StatusNotFound, "Not found", "No such app here.") |
| + return "", "", nil, "", "", AppIncarnation{}, false |
| + } |
| + return addr, raw, acct, role, app, inc, true |
| +} |
| + |
| // sentenceCase capitalizes a door message's first letter for a flash. |
| func sentenceCase(msg string) string { |
| if msg == "" || msg[0] < 'a' || msg[0] > 'z' { |
diff --git a/internal/console/appregionset_test.go b/internal/console/appregionset_test.go| index 06b8e2f53..7b609a722 100644 |
| --- a/internal/console/appregionset_test.go |
| +++ b/internal/console/appregionset_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "encoding/json" |
| "fmt" |
| + "io" |
| "net/http" |
| "net/url" |
| "strings" |
| @@ -534,3 +535,111 @@ func TestAppRegionSetNeedsANamedHome(t *testing.T) { |
| t.Fatalf("stored %q", r) |
| } |
| } |
| + |
| +// The browser door resolves the app's incarnation before it reads the form |
| +// body: a rename-and-replace while the body is still arriving changes |
| +// nothing, and the replacement keeps its region. |
| +func TestAppRegionBrowserRefusesAnAppReplacedMidRequest(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + c, csrf := signInAs(t, fx.consoleFixture, arOwner, "code-ar-owner-web") |
| + pr, pw := io.Pipe() |
| + req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/a/"+arSqid+"/apps/shop/region", pr) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + done := make(chan *http.Response, 1) |
| + go func() { |
| + res, err := c.Do(req) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + done <- res |
| + }() |
| + // The handler has resolved shop once it waits on the body; give it the |
| + // first byte so the request is in flight, then replace the app. |
| + if _, err := pw.Write([]byte("csrf=")); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(200 * time.Millisecond) |
| + now := time.Now() |
| + if err := fx.st.TrashAppRow(42, "shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.PurgeAppRow(42, "shop"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(42, "shop", arOwner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := pw.Write([]byte(url.QueryEscape(csrf) + "®ion=uk")); err != nil { |
| + t.Fatal(err) |
| + } |
| + pw.Close() |
| + res := <-done |
| + if res == nil { |
| + t.Fatal("no response") |
| + } |
| + res.Body.Close() |
| + if res.StatusCode != http.StatusSeeOther { |
| + t.Fatalf("status = %d, want the flash redirect", res.StatusCode) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "" { |
| + t.Fatalf("the replacement's region became %q", r) |
| + } |
| + if evs := fx.regionEvents(t, "shop"); len(evs) != 0 { |
| + t.Fatalf("audited %+v", evs) |
| + } |
| +} |
| + |
| +// A name never loses to a sqid: an operator who is a member of an account |
| +// NAMED like another account's sqid, addressing it by name without |
| +// ?exact=sqid, changes the app in the account it is a member of. |
| +func TestAppRegionSetNameNeverLosesToASqid(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + fx.srv.cfg.SystemOperators = []string{"sysop@example.test"} |
| + now := time.Now() |
| + if err := fx.st.CreateAccount(44, "wxyz", arSqid, "sysop@example.test", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(44, "shop", "sysop@example.test", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + sysop := cliToken(t, fx.consoleFixture, "sysop@example.test", "code-ar-sysop") |
| + st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+arSqid+"/shop/region", sysop, `{"region":"uk"}`) |
| + if st != http.StatusOK { |
| + t.Fatalf("by name = %d %s", st, out) |
| + } |
| + if r, _, _ := fx.st.AppRegion(44, "shop"); r != "uk" { |
| + t.Fatalf("the named account's shop is %q, want uk", r) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "" { |
| + t.Fatalf("the sqid's account's shop became %q", r) |
| + } |
| + // With ?exact=sqid the operator reaches the sqid's account. |
| + if st, out := fx.put(t, sysop, "shop", "uk"); st != http.StatusOK { |
| + t.Fatalf("by exact sqid = %d %s", st, out) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "uk" { |
| + t.Fatalf("exact sqid left %q", r) |
| + } |
| +} |
| + |
| +// A fleet placement committed after the door's check stops the write. |
| +func TestAppRegionSetRefusesAPlacementMadeMeanwhile(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + ctx := context.Background() |
| + inc, ok, err := fx.st.AppIncarnationContext(ctx, 42, "shop") |
| + if err != nil || !ok { |
| + t.Fatal(ok, err) |
| + } |
| + if err := fx.st.SetAppPlacement(42, "shop", "fleet/racks"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, err := fx.st.SetAppRegion(ctx, 42, "shop", inc, "", "uk", time.Now()); err != nil || ok { |
| + t.Fatalf("write after a placement = %v %v, want false", ok, err) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "" { |
| + t.Fatalf("stored %q", r) |
| + } |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index 90da15618..229e79aa2 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1698,7 +1698,8 @@ func (s *Store) AppRegion(accountID int64, app string) (region, source string, e |
| // instances (carlos apps region --set). The update is pinned to the |
| // incarnation and the region the caller read (inc, from), so a delete, a |
| // rename that freed the name, a create that took it again, or another |
| -// change in between writes nothing: ok is false. region is in the record |
| +// change in between writes nothing: ok is false. So does a fleet placement |
| +// committed since the caller checked: the write is for an unplaced app. region is in the record |
| // vocabulary ("" is the home). The source becomes "changed" and |
| // region_set_at the time of the change. Nothing else reads the row's region |
| // to place an existing instance, so no instance moves. |
| @@ -1713,8 +1714,11 @@ func (s *Store) SetAppRegion(ctx context.Context, accountID int64, app string, i |
| if err != nil || !live || cur != inc { |
| return false, err |
| } |
| + // placement = '': the door refused a fleet-placed app, and a placement |
| + // committed since must not let the write through (fleets.go writes the |
| + // column without the app lock). |
| res, err := s.db.ExecContext(ctx, `UPDATE apps SET region = ?, region_source = 'changed', region_set_at = ? |
| -WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND region = ?`, |
| +WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND region = ? AND placement = ''`, |
| to, now.Unix(), accountID, app, inc.createdAt, from) |
| if err != nil { |
| return false, err |
diff --git a/internal/provision/testdata/plan14-root-reads-app-region-set.tsv b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv| index 3d845424e..2b17940d4 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-app-region-set.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv |
| @@ -11,6 +11,6 @@ internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;r |
| internal/console/store.go Store.migrateAppsKey legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: copies apps into the composite-key schema while preserving existing lifetimes and minting only missing ids;rev3=census-ruling-app-region-set;basis=carries region_set_at across the apps rebuild (column list and INSERT ... SELECT); console-owned table only; no read added file:Exec@2425,file:QueryRow@65 a6d4f9c819c32c9d311e793e3de0cbd9aa4f387fbaf3ca85b0e03d732a93182f |
| internal/console/templates/app_settings.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-design-edge-rate-limit-358;basis=the Settings page gains a Rate limit section: per instance host, a form of four numbers (busy at, per address while busy, backstop rate, backstop burst) and a reset form, both posting to /a/{sqid}/apps/{app}/ratelimit with the CSRF token, and the record's path rules listed read-only; embedded and rendered by the console (carlos-console), as before; no read added;rev3=census-ruling-console-ux-nav;basis=adds the Placement section (the existing POST /place form, moved from app_instances) and the Errors and analytics section; Advanced folds into General; link texts reworded; markup only; no read added;rev3=census-ruling-region-labels;basis=General gains a Region section (RC-18a, RC-18d, RC-19, RL-S1, or the unread sentence); the placement form's button reads Change fleet (RC-14); markup only; no read added;rev3=census-ruling-app-region-set;basis=the General Region section gains, for an owner or a deployment operator, a select of region codes and a Change region button posting to /a/{sqid}/apps/{app}/region with the CSRF token, and a note; markup only; no read added file:external@0 9a9cd510dbd50d7362db8355ecca9226eaf2c05dc89fe46ac33aa22abb33fca9 |
| @coverage . fc29f7b37d6a5b150c9d5955b40300da7a8e7b830e41ff8dc7e0f4633d94f00f |
| -@coverage internal/console d3116f625665419a5503b481761fe60c81b86d8a9191fbf605ec6c32438ccef4 |
| +@coverage internal/console 9dd6b5fe9d183f6e9a4e399583439cc05a63b42b28f3ea75a276cea0298657be |
| @coverage internal/console/templates 31b5a71a123d232e2f36cd8032b5ff8d9f43c1474f203c81b2dd1852aeedc6e7 |
| @coverage internal/regionlabel a4cc5a2ff624a1aa3215c711302c7dc68d2bdca9853eadc372f31a8c99113872 |