console: link fixes: serialize publish, 202 pending unlink, edge settings
Task 5 fix round 1 (Astra and Fable; Paul's ruling 2026-11-10).
- Publish, unpublish and unlink's row removal share the app lock,
independent of plan catalogs; publish re-reads its row after
PutForward and removes a forward row whose app row is gone.
- Unlink answers 202 {"revocation":"pending"} until the registry has
applied the revocation; the revoked link's last credential reaches
the unlink door alone, so a repeat answers 204 once it has.
- The publish rate limit is charged after the idempotent branch.
- The protection and analytics setting doors stay editable for a
linked app (the hub applies both to its forward row); gate and rate
limit stay refused.
- Witnesses for the NewServer reap wiring and the nil-hook pass path;
allowed doors held to exact answers; shared create-door sentences.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+636
−77
internal/console/apicli.go+17 −7internal/console/apilinks.go+141 −49internal/console/apilinks_test.go+430 −6internal/console/apitemporary.go+1 −1internal/console/linkedpolicy.go+21 −12internal/console/links_store.go+26 −2
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index 45558c8a8..cb66c3062 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -375,6 +375,16 @@ func (s *Server) apiPerson(w http.ResponseWriter, r *http.Request) bool { |
| return true |
| } |
| +// The app-create door's refusals, shared with the doors that create apps by |
| +// its rules (the link's publish door, /new-temporary): one sentence each. |
| +const ( |
| + appCreateInvalidNameMsg = "invalid app name — lowercase letters, digits, and dashes, starting with a letter" |
| + appCreateReservedMsg = "that name is reserved" |
| + appCreateTemporaryReservedMsg = "names starting with tmp- are kept for temporary sites. Use carlos deploy --temporary, or choose another name" |
| + appCreateFailedMsg = "could not create the app — try again" |
| + appCreateStoreFailedMsg = "could not check the release store — try again" |
| +) |
| + |
| // handleAPICreateApp answers `carlos apps create`: the CLI door onto the |
| // same claim the browser's New app form posts to. claimApp holds the checks |
| // for both doors — including the ops account's legacy claim-proofing — so |
| @@ -537,7 +547,7 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| log.Printf("console: api create %s/%s: plan cap: %v", acct.Sqid, name, err) |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| return |
| } |
| // The answer's region lines read the live edges snapshot, which nothing |
| @@ -548,22 +558,22 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| switch outcome { |
| case claimInvalid: |
| jsonError(w, http.StatusBadRequest, |
| - "invalid app name — lowercase letters, digits, and dashes, starting with a letter") |
| + appCreateInvalidNameMsg) |
| case claimReserved: |
| - jsonError(w, http.StatusConflict, "that name is reserved") |
| + jsonError(w, http.StatusConflict, appCreateReservedMsg) |
| case claimTemporaryReserved: |
| jsonError(w, http.StatusConflict, |
| - "names starting with tmp- are kept for temporary sites. Use carlos deploy --temporary, or choose another name") |
| + appCreateTemporaryReservedMsg) |
| case claimTaken: |
| jsonError(w, http.StatusConflict, "that name is taken") |
| case claimApexHeld: |
| jsonError(w, http.StatusConflict, "that name is not free: "+apexHeldSentence(s.apexHost(acct.Sqid, name), held)) |
| case claimCheckFailed, claimCreateFailed: |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| case claimStoreFailed: |
| // A bucket error, like handleCLINewAccount's: the detail stays on |
| // the box (key names and endpoints don't belong in API bodies). |
| - jsonError(w, http.StatusBadGateway, "could not check the release store — try again") |
| + jsonError(w, http.StatusBadGateway, appCreateStoreFailedMsg) |
| case claimPolicyClearFailed: |
| jsonError(w, http.StatusServiceUnavailable, fmt.Sprintf(appCreatePolicyClearMsg, apppolicy.Key(acct.Sqid, name))) |
| case claimPolicyWriterRefused: |
| @@ -639,7 +649,7 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) { |
| default: |
| // Any future claimOutcome lands here rather than silently 200ing |
| // with an empty body — see the reserved-name finding this guards. |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| } |
| } |
diff --git a/internal/console/apilinks.go b/internal/console/apilinks.go| index 6388c8669..35ada2ee3 100644 |
| --- a/internal/console/apilinks.go |
| +++ b/internal/console/apilinks.go |
| @@ -30,6 +30,10 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| +// linkUnlinkPattern is the unlink door's pattern: the one door a revoked |
| +// link's last credential still reaches (linkRoute). |
| +const linkUnlinkPattern = "DELETE /api/link" |
| + |
| // linkRouteKey carries the link principal linkRoute resolved. |
| type linkRouteKey struct{} |
| @@ -51,6 +55,16 @@ func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc { |
| tok := bearer(r) |
| p, ok := s.store.CLIPrincipal(tok, time.Now()) |
| if !ok || p.Kind != PrincipalLink || p.LinkID == "" { |
| + // A revoked link's last credential reaches the unlink door and |
| + // no other: its only power there is to run the revocation |
| + // through to the hub registry again (handleLinkUnlink's 202). |
| + // No sync first: the door's own unlink is the sync. |
| + if r.Pattern == linkUnlinkPattern { |
| + if rp, ok := s.store.revokedLinkPrincipal(tok); ok { |
| + h(w, r.WithContext(context.WithValue(r.Context(), linkRouteKey{}, rp))) |
| + return |
| + } |
| + } |
| s.cliNotSignedIn(w) |
| return |
| } |
| @@ -146,7 +160,10 @@ func (s *Server) handleLinkGet(w http.ResponseWriter, r *http.Request) { |
| } |
| // The stages handleLinkPublish reports to linkPublishHook (tests only). |
| -const linkPublishAfterInsert = "after-insert" |
| +const ( |
| + linkPublishAfterInsert = "after-insert" |
| + linkPublishAfterForward = "after-forward" |
| +) |
| // handleLinkPublish is POST /api/link/publications {"app": name}: create |
| // the linked app name in the link's account and serve it from the link. |
| @@ -156,12 +173,19 @@ const linkPublishAfterInsert = "after-insert" |
| // create budget (allowAppCreate keys a link on its ID). A name the account |
| // holds by anything other than this link's own linked app is LD-C10. |
| // |
| -// It writes the apps row first, then the forward row. A forward row that |
| -// cannot be written (the link was revoked meanwhile, ErrLinkInactive, or |
| -// another row holds the host) removes the apps row again, so no row |
| -// outlives a failed publish. A retry of the same name by the same link, |
| -// after a partial failure, finds its own row, writes the forward row again |
| -// and answers 200 with the same body. |
| +// The whole publish, its idempotent retry and its rollback included, runs |
| +// under the app lock (lockApp), which unpublish and unlink's row removal |
| +// also take, whatever the plan catalog: a publish and an unpublish of one |
| +// name, or two publishes of it, never interleave. |
| +// |
| +// It writes the apps row first, then the forward row, then reads the row |
| +// again: a forward row whose apps row is gone (or is not this link's) is |
| +// deleted and the publish fails, so no forward row serves without the |
| +// app record that counts it. A forward row that cannot be written (the |
| +// link was revoked meanwhile, ErrLinkInactive, or another row holds the |
| +// host) removes the apps row again. A retry of the same name by the same |
| +// link, after a partial failure, finds its own row, writes the forward row |
| +// again and answers 200 with the same body; it spends no create budget. |
| func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| p, l, acct, ok := s.linkCaller(w, r) |
| if !ok { |
| @@ -170,10 +194,6 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| if s.refuseLinkedHostClaim(w) { |
| return |
| } |
| - if !s.allowAppCreate(p, time.Now()) { |
| - jsonError(w, http.StatusTooManyRequests, copyLinkPublishRateLimited) |
| - return |
| - } |
| var req struct { |
| App string `json:"app"` |
| } |
| @@ -182,8 +202,7 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| } |
| name := normalizeAppName(req.App) |
| if !release.ValidApp(name) { |
| - jsonError(w, http.StatusBadRequest, |
| - "invalid app name — lowercase letters, digits, and dashes, starting with a letter") |
| + jsonError(w, http.StatusBadRequest, appCreateInvalidNameMsg) |
| return |
| } |
| if s.apexHost(acct.Sqid, name) == "" { |
| @@ -200,8 +219,9 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, http.StatusConflict, linkCopy(copyLD10, "app", name, "account", acct.Name)) |
| } |
| body := map[string]string{"app": name, "url": s.linkPublicationURL(acct, name)} |
| - unlock := s.planLock(acct) |
| - defer unlock() |
| + // LOCK ORDER (applocks.go): the account lock (planLock), then the app's. |
| + defer s.planLock(acct)() |
| + defer s.lockApp(acct.Sqid, name)() |
| // The same link publishing the same name again: finish what an earlier |
| // attempt started. |
| @@ -212,17 +232,19 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if owner == l.ID { |
| - if err := reg.PutForward(s.linkForward(acct, name, l.ID)); err != nil { |
| - s.linkPublishFailed(w, l, acct, name, err, false) |
| - return |
| + if s.linkPublishForward(w, reg, l, acct, name, false) { |
| + writeJSON(w, http.StatusOK, body) |
| } |
| - writeJSON(w, http.StatusOK, body) |
| return |
| } |
| if owner != "" { |
| taken() |
| return |
| } |
| + if !s.allowAppCreate(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, copyLinkPublishRateLimited) |
| + return |
| + } |
| if err := s.checkCreateApp(r.Context(), acct, name); err != nil { |
| if isPlanCap(err) { |
| @@ -230,31 +252,29 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| log.Printf("console: link %s: publish %s: plan cap: %v", l.ID, name, err) |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| return |
| } |
| outcome, _, _ := s.validateClaimAppName(r.Context(), acct, name, "", false, time.Time{}) |
| switch outcome { |
| case claimOK: |
| case claimInvalid: |
| - jsonError(w, http.StatusBadRequest, |
| - "invalid app name — lowercase letters, digits, and dashes, starting with a letter") |
| + jsonError(w, http.StatusBadRequest, appCreateInvalidNameMsg) |
| return |
| case claimReserved: |
| - jsonError(w, http.StatusConflict, "that name is reserved") |
| + jsonError(w, http.StatusConflict, appCreateReservedMsg) |
| return |
| case claimTemporaryReserved: |
| - jsonError(w, http.StatusConflict, |
| - "names starting with tmp- are kept for temporary sites. Use carlos deploy --temporary, or choose another name") |
| + jsonError(w, http.StatusConflict, appCreateTemporaryReservedMsg) |
| return |
| case claimTaken, claimApexHeld: |
| taken() |
| return |
| case claimStoreFailed: |
| - jsonError(w, http.StatusBadGateway, "could not check the release store — try again") |
| + jsonError(w, http.StatusBadGateway, appCreateStoreFailedMsg) |
| return |
| default: |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| return |
| } |
| created, err := s.createClaimAppRow(r.Context(), acct, name, func(st *Store) (bool, error) { |
| @@ -267,7 +287,7 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, http.StatusServiceUnavailable, refused.ref.Msg) |
| default: |
| log.Printf("console: link %s: publish %s: create row: %v", l.ID, name, err) |
| - jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + jsonError(w, http.StatusInternalServerError, appCreateFailedMsg) |
| } |
| return |
| } |
| @@ -278,14 +298,39 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| if s.linkPublishHook != nil { |
| s.linkPublishHook(l.ID, linkPublishAfterInsert) |
| } |
| - if err := reg.PutForward(s.linkForward(acct, name, l.ID)); err != nil { |
| - s.linkPublishFailed(w, l, acct, name, err, true) |
| + if !s.linkPublishForward(w, reg, l, acct, name, true) { |
| return |
| } |
| log.Printf("console: link %s published %s/%s", l.ID, acct.Sqid, name) |
| writeJSON(w, http.StatusCreated, body) |
| } |
| +// linkPublishForward writes name's forward row and then confirms its apps |
| +// row is still this link's. On any failure it answers and reports false: |
| +// the forward row it may have written is deleted again when the row is |
| +// gone, and, when this request inserted the row (inserted), the row is |
| +// removed after a failed write. The caller holds the app lock. |
| +func (s *Server) linkPublishForward(w http.ResponseWriter, reg consoleRegistry, l *Link, acct *Account, name string, inserted bool) bool { |
| + if err := reg.PutForward(s.linkForward(acct, name, l.ID)); err != nil { |
| + s.linkPublishFailed(w, l, acct, name, err, inserted) |
| + return false |
| + } |
| + if s.linkPublishHook != nil { |
| + s.linkPublishHook(l.ID, linkPublishAfterForward) |
| + } |
| + owner, err := s.store.appLinkID(acct.ID, name) |
| + if err == nil && owner == l.ID { |
| + return true |
| + } |
| + log.Printf("console: link %s: publish %s/%s: the apps row is gone after the forward row was written (owner %q, %v); removing the forward row", |
| + l.ID, acct.Sqid, name, owner, err) |
| + if _, derr := reg.DeleteLinkForward(s.apexHost(acct.Sqid, name), l.ID); derr != nil { |
| + log.Printf("console: link %s: publish %s/%s: remove the forward row: %v", l.ID, acct.Sqid, name, derr) |
| + } |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return false |
| +} |
| + |
| // linkPublishFailed answers a publish whose forward row could not be |
| // written and, when this request inserted the apps row (inserted), removes |
| // it again: a publish that does not serve leaves no app behind. |
| @@ -326,8 +371,10 @@ func (s *Server) handleLinkUnpublish(w http.ResponseWriter, r *http.Request) { |
| } |
| // unpublish removes l's publication name in acct: DeleteLinkForward, then |
| -// deleteLinkedAppRow. Both act only on rows of this link. |
| +// deleteLinkedAppRow. Both act only on rows of this link, under the app lock |
| +// a publish of the name holds. |
| func (s *Server) unpublish(ctx context.Context, l *Link, acct *Account, name string) error { |
| + defer s.lockApp(acct.Sqid, name)() |
| if host := s.apexHost(acct.Sqid, name); host != "" && release.ValidApp(name) { |
| reg, err := s.linkReg() |
| if err != nil { |
| @@ -376,46 +423,83 @@ func (s *Server) handleLinkRotate(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusOK, map[string]string{"token": raw}) |
| } |
| -// handleLinkUnlink is DELETE /api/link: unlink, by the link itself. Once |
| -// the console transaction has revoked the link the answer is 204, even if |
| -// a later step failed: the credential is already refused everywhere, and |
| -// linkSyncPass finishes the channel and the apps rows. |
| +// handleLinkUnlink is DELETE /api/link: unlink, by the link itself. |
| +// |
| +// - 204: the link is revoked and the hub registry has applied the |
| +// revocation (RevokeLinkChannel): the channel and every forward row of |
| +// the link are gone. Apps rows a failed delete left behind are |
| +// finished by linkSyncPass; they serve nothing. |
| +// - 202 {"revocation":"pending"}: the link is revoked on the console, but |
| +// the registry did not take the revocation after every retry, so the |
| +// hub may still accept the credential and serve until linkSyncPass |
| +// gets it through. The same request may be sent again: linkRoute |
| +// admits the revoked link's last credential at this one door, and the |
| +// answer is 204 once the revocation has applied. |
| +// - 503 LD-C13: the console transaction itself failed; nothing changed. |
| func (s *Server) handleLinkUnlink(w http.ResponseWriter, r *http.Request) { |
| - p, l, acct, ok := s.linkCaller(w, r) |
| + p, ok := linkPrincipalFrom(r.Context()) |
| if !ok { |
| + s.cliNotSignedIn(w) |
| + return |
| + } |
| + l, err := s.store.LinkByID(p.LinkID) |
| + if err != nil { |
| + log.Printf("console: link %s: unlink: read: %v", p.LinkID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + if l == nil || l.AccountID != p.AccountID { |
| + s.cliNotSignedIn(w) |
| return |
| } |
| ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), linkSyncTimeout) |
| defer cancel() |
| - if err := s.unlink(ctx, l, auditActor(p, acct)); err != nil { |
| - cur, rerr := s.store.LinkByID(l.ID) |
| - if rerr != nil || cur == nil || cur.RevokedAt.IsZero() { |
| - log.Printf("console: link %s: unlink: %v", l.ID, err) |
| - jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| - return |
| - } |
| - log.Printf("console: link %s: unlink committed, then: %v (linkSyncPass finishes it)", l.ID, err) |
| + switch err := s.unlink(ctx, l, "link:"+l.ID); { |
| + case err == nil: |
| + case errors.Is(err, errUnlinkPending): |
| + log.Printf("console: link %s: unlink: %v (linkSyncPass retries)", l.ID, err) |
| + writeJSON(w, http.StatusAccepted, map[string]string{"revocation": "pending"}) |
| + return |
| + case errors.Is(err, errUnlinkAppsLeft): |
| + log.Printf("console: link %s: unlink revoked, then: %v (linkSyncPass finishes it)", l.ID, err) |
| + default: |
| + log.Printf("console: link %s: unlink: %v", l.ID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| } |
| w.WriteHeader(http.StatusNoContent) |
| } |
| +// unlink's errors past its console transaction: errUnlinkPending, the hub |
| +// registry has not applied the revocation (the credential may still serve |
| +// there); errUnlinkAppsLeft, it has, and some apps rows are still to go. |
| +// linkSyncPass finishes both. |
| +var ( |
| + errUnlinkPending = errors.New("console: the link is revoked here, but the hub registry has not applied the revocation") |
| + errUnlinkAppsLeft = errors.New("console: the link is revoked, but some of its apps rows are left") |
| +) |
| + |
| // unlink ends link l, by whoever by names: one console transaction revokes |
| // the link and its credential (RevokeLink); then syncLinkChannel (with its |
| // retries) revokes the channel in the hub registry, which removes every |
| // link/<id> forward row in the same registry transaction; then every apps |
| // row of the link is deleted. The registry's rows are the ones removed, not |
| // a list derived from the apps rows, so a forward row with no apps row goes |
| -// too. An error after the transaction leaves the link revoked; linkSyncPass |
| -// finishes the rest. |
| +// too. Unlinking a revoked link runs the remaining steps again. An error |
| +// after the transaction wraps errUnlinkPending or errUnlinkAppsLeft and |
| +// leaves the link revoked; linkSyncPass finishes the rest. |
| func (s *Server) unlink(ctx context.Context, l *Link, by string) error { |
| if err := s.store.RevokeLink(l.ID, time.Now()); err != nil { |
| return fmt.Errorf("revoke: %w", err) |
| } |
| log.Printf("console: link %s (%q, account %d) unlinked by %s", l.ID, l.Name, l.AccountID, by) |
| if err := s.syncLinkRetry(ctx, l.ID); err != nil { |
| - return fmt.Errorf("channel sync: %w", err) |
| + return fmt.Errorf("%w: %w", errUnlinkPending, err) |
| + } |
| + if err := s.dropLinkedApps(ctx, l.ID); err != nil { |
| + return fmt.Errorf("%w: %w", errUnlinkAppsLeft, err) |
| } |
| - return s.dropLinkedApps(ctx, l.ID) |
| + return nil |
| } |
| // dropLinkedApps deletes every apps row of linkID, the last step of an |
| @@ -427,13 +511,21 @@ func (s *Server) dropLinkedApps(ctx context.Context, linkID string) error { |
| } |
| var errs []error |
| for _, a := range apps { |
| - if _, err := s.store.deleteLinkedAppRow(ctx, a.AccountID, a.App, linkID); err != nil { |
| + if err := s.dropLinkedApp(ctx, a, linkID); err != nil { |
| errs = append(errs, fmt.Errorf("delete %s: %w", a.App, err)) |
| } |
| } |
| return errors.Join(errs...) |
| } |
| +// dropLinkedApp deletes one apps row of linkID under the app lock a |
| +// publish of the name holds. |
| +func (s *Server) dropLinkedApp(ctx context.Context, a linkedApp, linkID string) error { |
| + defer s.lockApp(a.Sqid, a.App)() |
| + _, err := s.store.deleteLinkedAppRow(ctx, a.AccountID, a.App, linkID) |
| + return err |
| +} |
| + |
| // unlinkAccountLinks unlinks every live link of accountID: what reaping an |
| // account does first (materializeAccounts), so its linked apps go by the |
| // unlink path. Failures are logged; ReapAccount revokes the links' rows |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| index ab7d0a310..0b015f024 100644 |
| --- a/internal/console/apilinks_test.go |
| +++ b/internal/console/apilinks_test.go |
| @@ -23,6 +23,7 @@ import ( |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/tunnelclient" |
| ) |
| @@ -461,6 +462,39 @@ var linkedWalkOpaqueDoors = map[string]bool{ |
| "GET /api/cli/apps/{account}/{app}/source": true, |
| } |
| +// linkedAllowAnswers is what each linkedAllow door answers a linked app |
| +// with no bucket state: the page or the JSON (200), the star's redirect |
| +// back, and the legacy URL's redirect to the overview. |
| +var linkedAllowAnswers = map[string]int{ |
| + "GET /a/{sqid}/apps/{app}": http.StatusOK, |
| + "GET /a/{sqid}/apps/{app}/index": http.StatusOK, |
| + "GET /a/{sqid}/apps/{app}/analytics": http.StatusOK, |
| + "GET /a/{sqid}/apps/{app}/analytics/live": http.StatusOK, |
| + "GET /a/{sqid}/apps/{app}/protection": http.StatusOK, |
| + "GET /a/{sqid}/apps/{app}/protection/data": http.StatusOK, |
| + "POST /a/{sqid}/apps/{app}/star": http.StatusSeeOther, |
| + "GET /apps/{app}": http.StatusFound, |
| + "GET /api/cli/apps/{account}/{app}/analytics": http.StatusOK, |
| + // The fixture deployment has no GeoIP database: the door's own answer. |
| + "GET /api/cli/apps/{account}/{app}/geo": http.StatusServiceUnavailable, |
| + // Paul's ruling (2026-11-10): the hub applies these to a link's forward |
| + // row, so they stay editable; each redirects back with its flash. |
| + "POST /a/{sqid}/apps/{app}/analytics/setting": http.StatusSeeOther, |
| + "POST /a/{sqid}/apps/{app}/protection/setting": http.StatusSeeOther, |
| +} |
| + |
| +// linkedAllowForm and linkedAllowQuery are the fields an allowed door needs |
| +// to answer rather than refuse a malformed request. |
| +var linkedAllowForm = map[string]url.Values{ |
| + "POST /a/{sqid}/apps/{app}/star": {"starred": {"true"}}, |
| + "POST /a/{sqid}/apps/{app}/analytics/setting": {"count": {"edge"}}, |
| + "POST /a/{sqid}/apps/{app}/protection/setting": {"mode": {"record"}}, |
| +} |
| + |
| +var linkedAllowQuery = map[string]string{ |
| + "GET /api/cli/apps/{account}/{app}/geo": "?ip=192.0.2.1", |
| +} |
| + |
| var linkedWalkBoxDoors = map[string]bool{ |
| "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": true, |
| "POST /api/fleet/replicas/{account}/{app}/{host}/release": true, |
| @@ -598,7 +632,11 @@ func TestLinkedAppRefusedOnAppRoutes(t *testing.T) { |
| var req *http.Request |
| if browser { |
| if method != http.MethodGet { |
| - body = strings.NewReader(url.Values{"csrf": {session}}.Encode()) |
| + form := url.Values{"csrf": {session}} |
| + for k, v := range linkedAllowForm[d.Pattern] { |
| + form[k] = v |
| + } |
| + body = strings.NewReader(form.Encode()) |
| } |
| req, _ = http.NewRequest(method, fx.ts.URL+path, body) |
| if body != nil { |
| @@ -609,7 +647,7 @@ func TestLinkedAppRefusedOnAppRoutes(t *testing.T) { |
| if method != http.MethodGet && method != http.MethodDelete { |
| body = strings.NewReader(`{}`) |
| } |
| - req, _ = http.NewRequest(method, fx.ts.URL+path, body) |
| + req, _ = http.NewRequest(method, fx.ts.URL+path+linkedAllowQuery[d.Pattern], body) |
| if body != nil { |
| req.Header.Set("Content-Type", "application/json") |
| } |
| @@ -637,6 +675,11 @@ func TestLinkedAppRefusedOnAppRoutes(t *testing.T) { |
| if res.StatusCode == http.StatusConflict && (strings.Contains(got, esc(refusal)) || linkJSONErr(got) == refusal) { |
| t.Errorf("%s is linkedAllow but gave the linked refusal", d.Pattern) |
| } |
| + // The reads the spec keeps work for a linked app with no bucket |
| + // state at all: an answer, not an error page or a refusal. |
| + if want, ok := linkedAllowAnswers[d.Pattern]; !ok || res.StatusCode != want { |
| + t.Errorf("%s %s = %d, want %d for a linked app:\n%.300s", method, path, res.StatusCode, want, got) |
| + } |
| continue |
| } |
| refused++ |
| @@ -739,10 +782,32 @@ func TestPublishRacingUnlink(t *testing.T) { |
| if has, _ := fx.st.HasAppIn(linkOpsAccount(t, fx).ID, "shop"); !has { |
| t.Fatal("the barrier is not between the apps insert and the forward row") |
| } |
| - if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| - t.Fatalf("unlink = %d %s", status, body) |
| + // The unlink revokes the channel at once (which removes every forward |
| + // row of the link), then waits on the app lock the paused publish holds |
| + // before it drops the apps rows. |
| + unlinked := make(chan int, 1) |
| + go func() { |
| + status, _ := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, "") |
| + unlinked <- status |
| + }() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for { |
| + auth, err := linkRegistryOf(t, fx).LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := auth[registry.LinkChannelName(l.id)]; !has { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("the unlink never revoked the channel") |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| } |
| close(release) |
| + if status := <-unlinked; status != http.StatusNoContent { |
| + t.Fatalf("unlink = %d", status) |
| + } |
| a := <-done |
| if a.status == http.StatusCreated || a.status == http.StatusOK { |
| t.Fatalf("the publish racing the unlink succeeded: %d %v", a.status, a.out) |
| @@ -1063,8 +1128,9 @@ func TestRotateAndUnlinkRetryTheirSync(t *testing.T) { |
| t.Fatalf("publish = %d %v", status, out) |
| } |
| fault.revFail = 4 |
| - if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| - t.Fatalf("unlink = %d %s", status, body) |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusAccepted || |
| + strings.TrimSpace(body) != `{"revocation":"pending"}` { |
| + t.Fatalf("unlink = %d %s, want 202 revocation pending", status, body) |
| } |
| if fault.revCalls != 4 { |
| t.Fatalf("unlink tried the sync %d times, want 4", fault.revCalls) |
| @@ -1249,3 +1315,361 @@ func claimLinkChannelIs(t *testing.T, cx *claimCase, hash string) string { |
| } |
| return "" |
| } |
| + |
| +// ---- fix round 1 ------------------------------------------------------------- |
| + |
| +// TestPublishRacingUnpublish: an unpublish of the name sent while a publish |
| +// is between its apps row and its forward row waits for the publish, then |
| +// removes both; nothing serves without its row. |
| +func TestPublishRacingUnpublish(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + paused, release := make(chan struct{}), make(chan struct{}) |
| + var once sync.Once |
| + fx.srv.linkPublishHook = func(id, stage string) { |
| + if id == l.id && stage == linkPublishAfterInsert { |
| + once.Do(func() { close(paused); <-release }) |
| + } |
| + } |
| + pub := make(chan int, 1) |
| + go func() { status, _ := publish(t, fx, l.token, "shop"); pub <- status }() |
| + <-paused |
| + unpub := make(chan int, 1) |
| + go func() { |
| + status, _ := linkDoor(t, fx, http.MethodDelete, "/api/link/publications/shop", l.token, "") |
| + unpub <- status |
| + }() |
| + select { |
| + case status := <-unpub: |
| + t.Fatalf("the unpublish landed (%d) while the publish was between its row and its forward row", status) |
| + case <-time.After(300 * time.Millisecond): |
| + } |
| + close(release) |
| + if status := <-pub; status != http.StatusCreated { |
| + t.Fatalf("publish = %d", status) |
| + } |
| + if status := <-unpub; status != http.StatusNoContent { |
| + t.Fatalf("unpublish = %d", status) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after the race = %v", hosts) |
| + } |
| + if has, _ := fx.st.HasAppIn(linkOpsAccount(t, fx).ID, "shop"); has { |
| + t.Fatal("the apps row outlived the unpublish") |
| + } |
| +} |
| + |
| +// TestConcurrentSamePublish: two publishes of one name by one link, the |
| +// second sent while the first is between its row and its forward row: the |
| +// second waits and answers the idempotent 200, with or without a plan |
| +// catalog. |
| +func TestConcurrentSamePublish(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + if fx.srv.cfg.PlanCatalog != nil { |
| + t.Fatal("the fixture has a plan catalog; this test is about a console without one") |
| + } |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + paused, release := make(chan struct{}), make(chan struct{}) |
| + var once sync.Once |
| + fx.srv.linkPublishHook = func(id, stage string) { |
| + if id == l.id && stage == linkPublishAfterInsert { |
| + once.Do(func() { close(paused); <-release }) |
| + } |
| + } |
| + first := make(chan int, 1) |
| + go func() { status, _ := publish(t, fx, l.token, "shop"); first <- status }() |
| + <-paused |
| + second := make(chan map[string]any, 1) |
| + secondStatus := make(chan int, 1) |
| + go func() { status, out := publish(t, fx, l.token, "shop"); secondStatus <- status; second <- out }() |
| + time.Sleep(200 * time.Millisecond) |
| + close(release) |
| + if status := <-first; status != http.StatusCreated { |
| + t.Fatalf("first publish = %d", status) |
| + } |
| + if status, out := <-secondStatus, <-second; status != http.StatusOK || out["url"] != "https://"+linkHost(fx, "shop") { |
| + t.Fatalf("second publish = %d %v, want the idempotent 200", status, out) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 1 { |
| + t.Fatalf("forward rows = %v, want one", hosts) |
| + } |
| +} |
| + |
| +// TestPublishRechecksTheRowAfterTheForward: when the apps row is gone by |
| +// the time the forward row is written (here removed behind the console's |
| +// back), the publish deletes the forward row and fails. |
| +func TestPublishRechecksTheRowAfterTheForward(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + acct := linkOpsAccount(t, fx) |
| + fx.srv.linkPublishHook = func(id, stage string) { |
| + if id == l.id && stage == linkPublishAfterForward { |
| + if _, err := fx.st.deleteLinkedAppRow(context.Background(), acct.ID, "shop", l.id); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + } |
| + status, out := publish(t, fx, l.token, "shop") |
| + if status != http.StatusServiceUnavailable || out["error"] != copyLD13 { |
| + t.Fatalf("publish = %d %v, want 503 LD-C13", status, out) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("a forward row serves with no apps row: %v", hosts) |
| + } |
| +} |
| + |
| +// TestPublishRetrySpendsNoBudget: the create budget is charged for a new |
| +// publication only, never for the idempotent retry of one. |
| +func TestPublishRetrySpendsNoBudget(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + p, _ := fx.st.CLIPrincipal(l.token, time.Now()) |
| + for i := 0; fx.srv.allowAppCreate(p, time.Now()); i++ { |
| + if i > 10000 { |
| + t.Fatal("the create budget never runs out") |
| + } |
| + } |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusOK { |
| + t.Fatalf("retry with the budget spent = %d %v, want the idempotent 200", status, out) |
| + } |
| + if status, out := publish(t, fx, l.token, "blog"); status != http.StatusTooManyRequests || out["error"] != copyLinkPublishRateLimited { |
| + t.Fatalf("a new name with the budget spent = %d %v, want 429", status, out) |
| + } |
| + if status, out := publish(t, fx, l.token, "Not A Name"); status != http.StatusBadRequest { |
| + t.Fatalf("an invalid name = %d %v, want 400 whatever the budget", status, out) |
| + } |
| +} |
| + |
| +// TestUnlinkPendingUntilTheRegistryRevokes: with the registry refusing the |
| +// revocation, unlink answers 202 pending and the hub still takes the old |
| +// credential; once the registry answers, a sync pass revokes it, the hub |
| +// refuses it, and the same unlink, sent again, answers 204. |
| +func TestUnlinkPendingUntilTheRegistryRevokes(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + real := linkRegistryOf(t, fx) |
| + fault := &linkGenFault{consoleRegistry: real, gen: 1 << 62, revFail: 1 << 30} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return fault, nil } |
| + hub := edge.NewTunnelHub("tunnel.example.com", nil) |
| + reload := func() { |
| + auth, err := real.LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hub.SetDynamicAuth(auth) |
| + } |
| + reload() |
| + hts := httptest.NewServer(hub) |
| + t.Cleanup(hts.Close) |
| + name := registry.LinkChannelName(l.id) |
| + |
| + status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, "") |
| + if status != http.StatusAccepted || strings.TrimSpace(body) != `{"revocation":"pending"}` { |
| + t.Fatalf("unlink with the registry failing = %d %s, want 202 pending", status, body) |
| + } |
| + reload() |
| + if status, _ := handDialHub(t, hts.URL, hub.Host(), name, l.token); status != http.StatusSwitchingProtocols { |
| + t.Fatalf("hub with the revocation pending = %d, want it still to take the credential (101)", status) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 1 { |
| + t.Fatalf("forward rows while pending = %v", hosts) |
| + } |
| + // Still pending: the same unlink answers 202 again, and no other door |
| + // takes the revoked credential. |
| + if status, _ := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusAccepted { |
| + t.Fatalf("repeated unlink while pending = %d, want 202", status) |
| + } |
| + if status, _ := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, ""); status != http.StatusUnauthorized { |
| + t.Fatalf("GET /api/link with the revoked credential = %d, want 401", status) |
| + } |
| + |
| + fault.mu.Lock() |
| + fault.revFail = 0 |
| + fault.mu.Unlock() |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + reload() |
| + if status, _ := handDialHub(t, hts.URL, hub.Host(), name, l.token); status != http.StatusUnauthorized { |
| + t.Fatalf("hub after the pass = %d, want 401", status) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after the pass = %v", hosts) |
| + } |
| + if apps, _ := fx.st.LinkedApps(l.id); len(apps) != 0 { |
| + t.Fatalf("linked apps after the pass = %v", apps) |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("repeated unlink after the pass = %d %s, want 204", status, body) |
| + } |
| + // A rotated-away credential is not the link's last one: refused even at |
| + // the unlink door. |
| + fx2 := newLinkFixture(t, "tunnel.example.com") |
| + l2 := mintLink(t, fx2, signInPaul(t, fx2), "blog-home") |
| + if status, _ := linkDoor(t, fx2, http.MethodPost, "/api/link/rotate", l2.token, ""); status != http.StatusOK { |
| + t.Fatal("rotate") |
| + } |
| + if status, _ := linkDoor(t, fx2, http.MethodDelete, "/api/link", l2.token, ""); status != http.StatusUnauthorized { |
| + t.Fatalf("unlink with a rotated-away credential = %d, want 401", status) |
| + } |
| +} |
| + |
| +// TestReapUnlinksThroughNewServer: NewServer's materialization reaps a |
| +// tombstoned account through the unlink path (its wiring, not a hook a test |
| +// passes): right after NewServer, with no sync pass, the channel and the |
| +// forward rows are gone and so are the linked apps. |
| +func TestReapUnlinksThroughNewServer(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + id, sqid, tok, linkID := reapableLinkedAccount(t, fx) |
| + _ = tok |
| + tombstoneAccount(t, fx, id, sqid) |
| + if _, err := NewServer(fx.srv.cfg, fx.st); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := linkRegistryOf(t, fx) |
| + auth, err := reg.LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := auth[registry.LinkChannelName(linkID)]; has { |
| + t.Fatal("NewServer's reap left the link's channel: it did not unlink first") |
| + } |
| + if rows, _ := reg.LinkForwards(linkID); len(rows) != 0 { |
| + t.Fatalf("forward rows after NewServer's reap = %v", rows) |
| + } |
| + if apps, _ := fx.st.LinkedApps(linkID); len(apps) != 0 { |
| + t.Fatalf("linked apps after NewServer's reap = %v", apps) |
| + } |
| + if a, deleted, _ := fx.st.AccountAnyBySqid(sqid); a == nil || !deleted { |
| + t.Fatalf("account after the reap = %+v deleted=%v", a, deleted) |
| + } |
| +} |
| + |
| +// TestReapWithoutUnlinkIsFinishedByThePass: the box-side path |
| +// (MaterializeAccounts, no unlink hook) revokes the link's rows in the reap; |
| +// the channel, its forward rows and the linked apps stay until the console's |
| +// sync pass, which removes them all. |
| +func TestReapWithoutUnlinkIsFinishedByThePass(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + id, sqid, tok, linkID := reapableLinkedAccount(t, fx) |
| + tombstoneAccount(t, fx, id, sqid) |
| + if _, err := MaterializeAccounts(context.Background(), fx.rel, fx.st); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := fx.st.CLIPrincipal(tok, time.Now()); ok { |
| + t.Fatal("the link token resolves after the reap") |
| + } |
| + if apps, _ := fx.st.LinkedApps(linkID); len(apps) != 1 { |
| + t.Fatalf("linked apps right after the reap = %v, want the row kept for the unlink path", apps) |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := linkRegistryOf(t, fx) |
| + auth, _ := reg.LinkChannelAuth() |
| + if _, has := auth[registry.LinkChannelName(linkID)]; has { |
| + t.Fatal("the pass left the reaped account's channel") |
| + } |
| + if rows, _ := reg.LinkForwards(linkID); len(rows) != 0 { |
| + t.Fatalf("forward rows after the pass = %v", rows) |
| + } |
| + if apps, _ := fx.st.LinkedApps(linkID); len(apps) != 0 { |
| + t.Fatalf("linked apps after the pass = %v", apps) |
| + } |
| +} |
| + |
| +// reapableLinkedAccount makes account 4242 with a live link that has |
| +// published shop. |
| +func reapableLinkedAccount(t *testing.T, fx *consoleFixture) (id int64, sqid, token, linkID string) { |
| + t.Helper() |
| + id = 4242 |
| + sqid = domains.Sqid(id) |
| + now := time.Now() |
| + if err := fx.st.CreateAccount(id, sqid, "reaped", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + token = mintWalkLinkIn(t, fx.st, id) |
| + p, _ := fx.st.CLIPrincipal(token, now) |
| + if err := fx.srv.syncLinkChannel(context.Background(), p.LinkID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, out := publish(t, fx, token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + return id, sqid, token, p.LinkID |
| +} |
| + |
| +// tombstoneAccount writes account id's manifest marked deleted. |
| +func tombstoneAccount(t *testing.T, fx *consoleFixture, id int64, sqid string) { |
| + t.Helper() |
| + now := time.Now() |
| + body, err := json.Marshal(accountManifest{ID: id, Sqid: sqid, Name: "reaped", CreatedAt: now, DeletedAt: now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(context.Background(), domains.AccountManifestKey(sqid), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestLinkedAppEdgeSettingsLand: a linked app's protection and analytics |
| +// switches (Paul's ruling, 2026-11-10: they live on Carloku's edge) are |
| +// written by their browser doors to the app's telemetry object, the record |
| +// the hub's telemetry pass reads for every route with an app |
| +// (internal/host/telemetry_pass.go telemetrySettle: reg.List(), then |
| +// telemetry.AppKey(RouteAccount(rt), rt.App)), and the link's forward row |
| +// is such a route. |
| +func TestLinkedAppEdgeSettingsLand(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + browser := signInPaul(t, fx) |
| + l := mintLink(t, fx, browser, "shop-home") |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + csrf := sessionToken(t, fx, browser) |
| + if status, loc, body := postForm(t, browser, fx.u("/apps/shop/protection/setting"), url.Values{"csrf": {csrf}, "mode": {"record"}}); status != http.StatusSeeOther { |
| + t.Fatalf("protection setting = %d %s %s", status, loc, body) |
| + } |
| + if status, loc, body := postForm(t, browser, fx.u("/apps/shop/analytics/setting"), url.Values{"csrf": {csrf}, "count": {"edge"}}); status != http.StatusSeeOther { |
| + t.Fatalf("analytics setting = %d %s %s", status, loc, body) |
| + } |
| + st, _, err := telemetry.Read(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "shop")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !telemetry.RecordOnly(st) { |
| + t.Fatalf("the app's telemetry object = %+v, want protection record only", st) |
| + } |
| + if st.Analytics == nil || st.Analytics.Count != telemetry.CountEdge { |
| + t.Fatalf("the app's telemetry object = %+v, want analytics counted at the edge", st) |
| + } |
| + // The hub's pass keys those reads on the routes it lists: the forward |
| + // row names the account and the app. |
| + routes, err := linkRegistryOf(t, fx).(*registry.Registry).List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := false |
| + for _, rt := range routes { |
| + if rt.Host == linkHost(fx, "shop") && rt.IsForward() && release.RouteAccount(rt) == fx.sqid && rt.App == "shop" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatal("the registry's route list has no forward row naming the linked app, so no pass would read its settings") |
| + } |
| + // The gate and rate-limit doors stay refused: they write an instance |
| + // record a linked app does not have, and the forward row carries no gate. |
| + for _, door := range []string{"/apps/shop/gate", "/apps/shop/ratelimit"} { |
| + status, _, body := postForm(t, browser, fx.u(door), url.Values{"csrf": {csrf}}) |
| + if status != http.StatusConflict || !strings.Contains(body, esc(linkCopy(copyLD11, "app", "shop", "home", "shop-home"))) { |
| + t.Fatalf("%s = %d, want the linked refusal", door, status) |
| + } |
| + } |
| +} |
diff --git a/internal/console/apitemporary.go b/internal/console/apitemporary.go| index 2ffc05bb8..8f137f9d6 100644 |
| --- a/internal/console/apitemporary.go |
| +++ b/internal/console/apitemporary.go |
| @@ -204,7 +204,7 @@ func (s *Server) handleAPICreateTemporaryApp(w http.ResponseWriter, r *http.Requ |
| "a temporary app's name is tmp- followed by lowercase letters, digits and dashes, 32 characters in all, ending in a letter or digit") |
| return |
| case claimReserved: |
| - writeJSON(w, http.StatusConflict, map[string]any{"error": "that name is reserved", "code": "name_taken"}) |
| + writeJSON(w, http.StatusConflict, map[string]any{"error": appCreateReservedMsg, "code": "name_taken"}) |
| return |
| case claimTaken: |
| writeJSON(w, http.StatusConflict, map[string]any{"error": "that name is taken", "code": "name_taken"}) |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| index bad804a07..48ffb1d5e 100644 |
| --- a/internal/console/linkedpolicy.go |
| +++ b/internal/console/linkedpolicy.go |
| @@ -45,16 +45,27 @@ func linkedAppPolicy(pattern string) linkedPolicy { |
| // tell a classified door from a forgotten one. |
| var linkedPolicies = map[string]linkedPolicy{ |
| // The reads the spec keeps: the overview and its index, analytics, |
| - // protection; the personal star (the app list shows linked apps); and |
| - // the pre-accounts URL, which only redirects to the overview. |
| - "GET /a/{sqid}/apps/{app}": linkedAllow, |
| - "GET /a/{sqid}/apps/{app}/index": linkedAllow, |
| - "GET /a/{sqid}/apps/{app}/analytics": linkedAllow, |
| - "GET /a/{sqid}/apps/{app}/analytics/live": linkedAllow, |
| - "GET /a/{sqid}/apps/{app}/protection": linkedAllow, |
| - "GET /a/{sqid}/apps/{app}/protection/data": linkedAllow, |
| - "POST /a/{sqid}/apps/{app}/star": linkedAllow, |
| - "GET /apps/{app}": linkedAllow, |
| + // protection; the personal star (the app list shows linked apps); the |
| + // pre-accounts URL, which only redirects to the overview; and the edge |
| + // switches below. |
| + "GET /a/{sqid}/apps/{app}": linkedAllow, |
| + "GET /a/{sqid}/apps/{app}/index": linkedAllow, |
| + "GET /a/{sqid}/apps/{app}/analytics": linkedAllow, |
| + "GET /a/{sqid}/apps/{app}/analytics/live": linkedAllow, |
| + "GET /a/{sqid}/apps/{app}/protection": linkedAllow, |
| + "GET /a/{sqid}/apps/{app}/protection/data": linkedAllow, |
| + "POST /a/{sqid}/apps/{app}/star": linkedAllow, |
| + // Paul's ruling (2026-11-10): a published app's protection and |
| + // analytics switches live on Carloku's edge, and the hub applies them to |
| + // the link's forward row (internal/host/telemetry_pass.go reads |
| + // telemetry.AppKey for every listed route with an app; edge guard.go |
| + // protectionRecordOnly and analytics.go analyticsEnabled key on the |
| + // route's account and app). The gate and rate-limit doors stay refused: |
| + // they write a per-instance record, and the forward row carries no gate |
| + // (registry forwardShape: Gate forbidden). |
| + "POST /a/{sqid}/apps/{app}/analytics/setting": linkedAllow, |
| + "POST /a/{sqid}/apps/{app}/protection/setting": linkedAllow, |
| + "GET /apps/{app}": linkedAllow, |
| "GET /api/cli/apps/{account}/{app}/analytics": linkedAllow, |
| "GET /api/cli/apps/{account}/{app}/geo": linkedAllow, |
| @@ -91,8 +102,6 @@ var linkedPolicies = map[string]linkedPolicy{ |
| "GET /a/{sqid}/apps/{app}/errors": linkedRefuse, |
| "POST /a/{sqid}/apps/{app}/errors/level": linkedRefuse, |
| "GET /a/{sqid}/apps/{app}/availability": linkedRefuse, |
| - "POST /a/{sqid}/apps/{app}/analytics/setting": linkedRefuse, |
| - "POST /a/{sqid}/apps/{app}/protection/setting": linkedRefuse, |
| "GET /a/{sqid}/apps/{app}/activity": linkedRefuse, |
| "GET /a/{sqid}/apps/{app}/settings": linkedRefuse, |
| "GET /a/{sqid}/apps/{app}/settings/{section}": linkedRefuse, |
diff --git a/internal/console/links_store.go b/internal/console/links_store.go| index 5f6862f37..649bb0747 100644 |
| --- a/internal/console/links_store.go |
| +++ b/internal/console/links_store.go |
| @@ -359,6 +359,7 @@ WHERE l.id = ? AND a.deleted_at = 0`, linkID).Scan(&acct, &revoked, ¤t) |
| // linked_link_id names the link. |
| type linkedApp struct { |
| AccountID int64 |
| + Sqid string // the account's sqid, deleted account or not; "" with no row |
| App string |
| CreatedAt time.Time |
| } |
| @@ -387,7 +388,9 @@ func (s *Store) appLinkID(accountID int64, app string) (string, error) { |
| // LinkedApps lists linkID's linked apps by name. Linked rows are never |
| // trashed (every trash statement skips them), so every row is live. |
| func (s *Store) LinkedApps(linkID string) ([]linkedApp, error) { |
| - rows, err := s.db.Query(`SELECT account_id, app, created_at FROM apps WHERE linked_link_id = ? AND linked_link_id != '' ORDER BY app`, linkID) |
| + rows, err := s.db.Query(`SELECT p.account_id, COALESCE(a.sqid, ''), p.app, p.created_at FROM apps p |
| +LEFT JOIN accounts a ON a.id = p.account_id |
| +WHERE p.linked_link_id = ? AND p.linked_link_id != '' ORDER BY p.app`, linkID) |
| if err != nil { |
| return nil, err |
| } |
| @@ -396,7 +399,7 @@ func (s *Store) LinkedApps(linkID string) ([]linkedApp, error) { |
| for rows.Next() { |
| var a linkedApp |
| var created int64 |
| - if err := rows.Scan(&a.AccountID, &a.App, &created); err != nil { |
| + if err := rows.Scan(&a.AccountID, &a.Sqid, &a.App, &created); err != nil { |
| return nil, err |
| } |
| a.CreatedAt = time.Unix(created, 0).UTC() |
| @@ -476,3 +479,24 @@ AND EXISTS (SELECT 1 FROM apps p WHERE p.linked_link_id = l.id) ORDER BY l.id`) |
| } |
| return out, rows.Err() |
| } |
| + |
| +// revokedLinkPrincipal resolves raw when it is the last credential of a |
| +// revoked link: a kind='link' token whose hash is still the links row's |
| +// current one (so not one a rotation replaced) on a link that is revoked. |
| +// Only the unlink door asks (linkRoute), to run the revocation again; every |
| +// other door resolves through CLIPrincipal, which refuses it. |
| +func (s *Store) revokedLinkPrincipal(raw string) (Principal, bool) { |
| + if raw == "" { |
| + return Principal{}, false |
| + } |
| + hash := hashToken(raw) |
| + var p Principal |
| + err := s.db.QueryRow(`SELECT t.account_id, l.id FROM cli_tokens t JOIN links l ON l.id = t.name |
| +WHERE t.token_hash = ? AND t.kind = ? AND l.token_hash = t.token_hash AND l.account_id = t.account_id AND l.revoked_at != 0`, |
| + hash, cliKindLink).Scan(&p.AccountID, &p.LinkID) |
| + if err != nil { |
| + return Principal{}, false |
| + } |
| + p.Kind = PrincipalLink |
| + return p, true |
| +} |