console: link API, linked apps and the linked-app guard
Linked deployments slice 1, Task 5 (spec §5.2, §5.3, §6.0, §6.1, §6.7).
- kindLink doors under /api/link behind linkRoute, their one gate and
resolver: read, publish, unpublish, rotate, unlink. Rotate and unlink
retry their channel sync three times; linkSyncPass finishes unlinks.
- A publication is an apps row with linked_link_id plus a link-placed
forward row; app create's name rules and the running-things cap apply,
and a retry by the same link completes instead of answering taken.
- Linked rows leave only by unpublish and unlink: every other apps
delete and trash skips them, the convergence and expiry passes leave
them, and reaping an account unlinks first.
- linkedAppPolicy classifies every {app} route; linkedAppRefusal is
consulted by apiAccountAppSaying, accountApp and the eight other app
resolvers the walk found.
- Host-claim consoles refuse publish and unpublish (claim fixtures).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
37 files changed,
+2,697
−96
internal/console/apicli.go+9 −0internal/console/apienv.go+3 −0internal/console/apilinks.go+477 −0internal/console/apilinks_test.go+1,251 −0internal/console/apimail.go+3 −0internal/console/apipolicy.go+3 −0internal/console/appregionset.go+6 −0internal/console/appswap.go+3 −0internal/console/browserrestart.go+3 −0internal/console/browserretry.go+3 −0internal/console/browserupdates.go+3 −0internal/console/claim_app_identity.go+3 −3internal/console/claim_invariant_fixtures_test.go+42 −25internal/console/claim_invariant_probes_nonapp_test.go+30 −0internal/console/claim_invariant_probes_read_test.go+7 −0internal/console/claim_invariant_test.go+2 −0internal/console/demo_claim_transfer.go+1 −1internal/console/demo_expiry.go+1 −1internal/console/expirypass.go+3 −2internal/console/expirypass_test.go+1 −1internal/console/lifetimes_purge.go+2 −2internal/console/lifetimes_store.go+7 −3internal/console/linkedpolicy.go+330 −0internal/console/links_auth_test.go+109 −3internal/console/links_copy.go+23 −0internal/console/links_store.go+135 −0internal/console/links_sync.go+15 −2internal/console/materialize.go+20 −2internal/console/parity_test.go+7 −7internal/console/routedecls.go+24 −1internal/console/routedecls_test.go+15 −0internal/console/server.go+12 −2internal/console/settle.go+5 −0internal/console/store.go+50 −34internal/console/svcroutes_test.go+79 −4internal/console/tempstore.go+5 −3internal/console/testdata/claim-routes.txt+5 −0
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index 78a074f3c..45558c8a8 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -82,6 +82,15 @@ func (s *Server) apiAccountAppSaying(w http.ResponseWriter, r *http.Request, has |
| http.NotFound(w, r) |
| return "", nil, "", false |
| } |
| + // A linked app (spec §6.0) is managed at home: every method, reads |
| + // included, by the door's own policy (linkedpolicy.go). Before the |
| + // door's own existence lookup, so a door whose subject is not a live |
| + // app (restore's trashed one) refuses a linked name too; the caller is |
| + // already a member of the account, so this tells it nothing new. |
| + if ref := s.linkedAppRefusal(r, acct, app); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return "", nil, "", false |
| + } |
| found, err := has(acct.ID, app) |
| if err != nil { |
| log.Printf("console: api has-app %s/%s: %v", acct.Sqid, app, err) |
diff --git a/internal/console/apienv.go b/internal/console/apienv.go| index 78941b821..6982b5f98 100644 |
| --- a/internal/console/apienv.go |
| +++ b/internal/console/apienv.go |
| @@ -41,6 +41,9 @@ func (s *Server) environmentOwnerGate(w http.ResponseWriter, r *http.Request, pu |
| http.NotFound(w, r) |
| return Principal{}, nil, "", false |
| } |
| + if s.refuseLinkedJSON(w, r, acct, app) { |
| + return Principal{}, nil, "", false |
| + } |
| if !s.allowWrite(p, time.Now()) { |
| jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| return Principal{}, nil, "", false |
diff --git a/internal/console/apilinks.go b/internal/console/apilinks.go| new file mode 100644 |
| index 000000000..6388c8669 |
| --- /dev/null |
| +++ b/internal/console/apilinks.go |
| @@ -0,0 +1,477 @@ |
| +package console |
| + |
| +// A linked deployment's own doors on the serving console (linked |
| +// deployments spec §5.2, §5.3, §6.0, §6.1): read the link, publish and |
| +// unpublish its apps, rotate its credential, and unlink. |
| +// |
| +// The link credential reaches these doors and nothing else. linkRoute is |
| +// their one gate and their one resolver: it admits only a link principal |
| +// (every other bearer, and none, gets cliNotSignedIn's 401), syncs the |
| +// link's channel from the console row before the handler runs (so a channel |
| +// write that failed earlier heals on the next request), and hands the |
| +// principal down on the context. The handlers resolve nothing themselves |
| +// (TestAuthCLIFamilyResolvesOnlyPersons). |
| +// |
| +// A publication is an app record (§6.0): an ordinary apps row marked with |
| +// its link (linked_link_id), counted against the account's caps, plus a |
| +// forward row in the hub registry placed on the link ("link/<id>"). Linked |
| +// app rows are removed only by unpublish and unlink (deleteLinkedAppRow); |
| +// every other app door refuses a linked app (linkedpolicy.go). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// linkRouteKey carries the link principal linkRoute resolved. |
| +type linkRouteKey struct{} |
| + |
| +// linkPrincipalFrom is the principal linkRoute put on the request context. |
| +func linkPrincipalFrom(ctx context.Context) (Principal, bool) { |
| + p, ok := ctx.Value(linkRouteKey{}).(Principal) |
| + return p, ok && p.Kind == PrincipalLink |
| +} |
| + |
| +// linkRoute is the gate every kindLink door is registered behind, and the |
| +// one place a link door resolves a bearer. It resolves the bearer with |
| +// CLIPrincipal and admits only a link principal; anything else gets the |
| +// same 401 as no bearer. It then syncs the link's channel (syncLinkChannel, |
| +// the one writer), answering 503 when that fails, and resolves the bearer a |
| +// second time: a rotation or an unlink that landed while the sync ran ends |
| +// this request here rather than in the handler. |
| +func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + tok := bearer(r) |
| + p, ok := s.store.CLIPrincipal(tok, time.Now()) |
| + if !ok || p.Kind != PrincipalLink || p.LinkID == "" { |
| + s.cliNotSignedIn(w) |
| + return |
| + } |
| + if err := s.syncLinkChannel(r.Context(), p.LinkID); err != nil { |
| + log.Printf("console: link door %s: %v", r.Pattern, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + if again, ok := s.store.CLIPrincipal(tok, time.Now()); !ok || again.Kind != PrincipalLink || again.LinkID != p.LinkID { |
| + s.cliNotSignedIn(w) |
| + return |
| + } |
| + h(w, r.WithContext(context.WithValue(r.Context(), linkRouteKey{}, p))) |
| + } |
| +} |
| + |
| +// linkCaller reads the link principal linkRoute resolved, with its link and |
| +// its account. A link or account gone since is the gate's 401; a store |
| +// error is the link doors' 503. |
| +func (s *Server) linkCaller(w http.ResponseWriter, r *http.Request) (Principal, *Link, *Account, bool) { |
| + p, ok := linkPrincipalFrom(r.Context()) |
| + if !ok { |
| + s.cliNotSignedIn(w) |
| + return Principal{}, nil, nil, false |
| + } |
| + l, err := s.store.LinkByID(p.LinkID) |
| + if err != nil { |
| + log.Printf("console: link %s: read: %v", p.LinkID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return Principal{}, nil, nil, false |
| + } |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + log.Printf("console: link %s: account %d: %v", p.LinkID, p.AccountID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return Principal{}, nil, nil, false |
| + } |
| + if l == nil || !l.RevokedAt.IsZero() || l.AccountID != p.AccountID || acct == nil { |
| + s.cliNotSignedIn(w) |
| + return Principal{}, nil, nil, false |
| + } |
| + return p, l, acct, true |
| +} |
| + |
| +// refuseLinkedHostClaim answers the publish and unpublish doors' 409 on a |
| +// console with host claims on: a linked app's row is app-scoped state, and |
| +// no claim operation gates it, so such a console holds no linked apps (and |
| +// unlink there removes only the link). It reports whether it refused. |
| +func (s *Server) refuseLinkedHostClaim(w http.ResponseWriter) bool { |
| + if !s.cfg.HostClaim { |
| + return false |
| + } |
| + jsonError(w, http.StatusConflict, copyLinkedHostClaim) |
| + return true |
| +} |
| + |
| +// linkPublicationURL is a published app's public address. |
| +func (s *Server) linkPublicationURL(acct *Account, app string) string { |
| + return "https://" + s.apexHost(acct.Sqid, app) |
| +} |
| + |
| +// linkForward is the forward row that serves a linked app: the app's |
| +// platform hostname, placed on the link. |
| +func (s *Server) linkForward(acct *Account, app, linkID string) registry.Route { |
| + return registry.Route{Kind: registry.KindForward, Host: s.apexHost(acct.Sqid, app), App: app, |
| + Account: acct.Sqid, Region: registry.LinkPlacementPrefix + linkID} |
| +} |
| + |
| +// handleLinkGet is GET /api/link: the link and its publications. |
| +func (s *Server) handleLinkGet(w http.ResponseWriter, r *http.Request) { |
| + _, l, acct, ok := s.linkCaller(w, r) |
| + if !ok { |
| + return |
| + } |
| + apps, err := s.store.LinkedApps(l.ID) |
| + if err != nil { |
| + log.Printf("console: link %s: publications: %v", l.ID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + type publication struct { |
| + App string `json:"app"` |
| + URL string `json:"url"` |
| + CreatedAt time.Time `json:"created_at"` |
| + } |
| + pubs := []publication{} |
| + for _, a := range apps { |
| + pubs = append(pubs, publication{App: a.App, URL: s.linkPublicationURL(acct, a.App), CreatedAt: a.CreatedAt}) |
| + } |
| + writeJSON(w, http.StatusOK, map[string]any{ |
| + "link_id": l.ID, "account": acct.Sqid, "name": l.Name, "publications": pubs, |
| + }) |
| +} |
| + |
| +// The stages handleLinkPublish reports to linkPublishHook (tests only). |
| +const linkPublishAfterInsert = "after-insert" |
| + |
| +// handleLinkPublish is POST /api/link/publications {"app": name}: create |
| +// the linked app name in the link's account and serve it from the link. |
| +// |
| +// The name rules are app create's (validateClaimAppName), under the plan |
| +// lock with the running-things cap (checkCreateApp), on the link's own |
| +// 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. |
| +func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) { |
| + p, l, acct, ok := s.linkCaller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if s.refuseLinkedHostClaim(w) { |
| + return |
| + } |
| + if !s.allowAppCreate(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, copyLinkPublishRateLimited) |
| + return |
| + } |
| + var req struct { |
| + App string `json:"app"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + name := normalizeAppName(req.App) |
| + if !release.ValidApp(name) { |
| + jsonError(w, http.StatusBadRequest, |
| + "invalid app name — lowercase letters, digits, and dashes, starting with a letter") |
| + return |
| + } |
| + if s.apexHost(acct.Sqid, name) == "" { |
| + jsonError(w, http.StatusServiceUnavailable, copyLinkNoAppsDomain) |
| + return |
| + } |
| + reg, err := s.linkReg() |
| + if err != nil { |
| + log.Printf("console: link %s: publish %s: open registry: %v", l.ID, name, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + taken := func() { |
| + 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() |
| + |
| + // The same link publishing the same name again: finish what an earlier |
| + // attempt started. |
| + owner, err := s.store.appLinkID(acct.ID, name) |
| + if err != nil { |
| + log.Printf("console: link %s: publish %s: read row: %v", l.ID, name, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + 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 |
| + } |
| + writeJSON(w, http.StatusOK, body) |
| + return |
| + } |
| + if owner != "" { |
| + taken() |
| + return |
| + } |
| + |
| + if err := s.checkCreateApp(r.Context(), acct, name); err != nil { |
| + if isPlanCap(err) { |
| + writeJSON(w, http.StatusConflict, map[string]any{"error": err.Error(), "code": "cap"}) |
| + 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") |
| + 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") |
| + return |
| + case claimReserved: |
| + jsonError(w, http.StatusConflict, "that name is reserved") |
| + return |
| + case claimTemporaryReserved: |
| + jsonError(w, http.StatusConflict, |
| + "names starting with tmp- are kept for temporary sites. Use carlos deploy --temporary, or choose another name") |
| + return |
| + case claimTaken, claimApexHeld: |
| + taken() |
| + return |
| + case claimStoreFailed: |
| + jsonError(w, http.StatusBadGateway, "could not check the release store — try again") |
| + return |
| + default: |
| + jsonError(w, http.StatusInternalServerError, "could not create the app — try again") |
| + return |
| + } |
| + created, err := s.createClaimAppRow(r.Context(), acct, name, func(st *Store) (bool, error) { |
| + return st.CreateLinkedApp(acct.ID, name, auditActor(p, acct), l.ID, time.Now()) |
| + }) |
| + if err != nil { |
| + var refused policyWriterRefused |
| + switch { |
| + case errors.As(err, &refused): |
| + 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") |
| + } |
| + return |
| + } |
| + if !created { // lost a race for the name after the checks |
| + taken() |
| + return |
| + } |
| + 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) |
| + return |
| + } |
| + log.Printf("console: link %s published %s/%s", l.ID, acct.Sqid, name) |
| + writeJSON(w, http.StatusCreated, body) |
| +} |
| + |
| +// 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. |
| +func (s *Server) linkPublishFailed(w http.ResponseWriter, l *Link, acct *Account, name string, err error, inserted bool) { |
| + log.Printf("console: link %s: publish %s/%s: forward row: %v", l.ID, acct.Sqid, name, err) |
| + if inserted { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + if _, derr := s.store.deleteLinkedAppRow(ctx, acct.ID, name, l.ID); derr != nil { |
| + log.Printf("console: link %s: publish %s/%s: remove the row again: %v (linkSyncPass retries after an unlink)", l.ID, acct.Sqid, name, derr) |
| + } |
| + } |
| + if errors.Is(err, registry.ErrHostHeld) { |
| + jsonError(w, http.StatusConflict, linkCopy(copyLD10, "app", name, "account", acct.Name)) |
| + return |
| + } |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| +} |
| + |
| +// handleLinkUnpublish is DELETE /api/link/publications/{app}: the forward |
| +// row first, then the apps row, each only where it is this link's. A |
| +// missing row on either side is not an error, so a retry completes. |
| +func (s *Server) handleLinkUnpublish(w http.ResponseWriter, r *http.Request) { |
| + _, l, acct, ok := s.linkCaller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if s.refuseLinkedHostClaim(w) { |
| + return |
| + } |
| + name := normalizeAppName(r.PathValue("app")) |
| + if err := s.unpublish(r.Context(), l, acct, name); err != nil { |
| + log.Printf("console: link %s: unpublish %s/%s: %v", l.ID, acct.Sqid, name, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +// unpublish removes l's publication name in acct: DeleteLinkForward, then |
| +// deleteLinkedAppRow. Both act only on rows of this link. |
| +func (s *Server) unpublish(ctx context.Context, l *Link, acct *Account, name string) error { |
| + if host := s.apexHost(acct.Sqid, name); host != "" && release.ValidApp(name) { |
| + reg, err := s.linkReg() |
| + if err != nil { |
| + return fmt.Errorf("open registry: %w", err) |
| + } |
| + if _, err := reg.DeleteLinkForward(host, l.ID); err != nil { |
| + return fmt.Errorf("delete forward row: %w", err) |
| + } |
| + } |
| + if _, err := s.store.deleteLinkedAppRow(ctx, acct.ID, name, l.ID); err != nil { |
| + return fmt.Errorf("delete app row: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// linkSyncTimeout bounds a door's own sync after its change committed. |
| +const linkSyncTimeout = 10 * time.Second |
| + |
| +// handleLinkRotate is POST /api/link/rotate: a new credential in one |
| +// console transaction (RotateLinkToken), then the channel synced to its |
| +// hash, which makes the hub close the connection on the old one (Task 3's |
| +// SetDynamicAuth). The new token is answered even when the sync keeps |
| +// failing: the old one is already revoked here, and linkSyncLoop moves the |
| +// channel later. |
| +func (s *Server) handleLinkRotate(w http.ResponseWriter, r *http.Request) { |
| + _, l, _, ok := s.linkCaller(w, r) |
| + if !ok { |
| + return |
| + } |
| + raw, err := s.store.RotateLinkToken(l.ID, time.Now()) |
| + if errors.Is(err, ErrNoLink) { |
| + s.cliNotSignedIn(w) |
| + return |
| + } |
| + if err != nil { |
| + log.Printf("console: link %s: rotate: %v", l.ID, err) |
| + jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), linkSyncTimeout) |
| + defer cancel() |
| + if err := s.syncLinkRetry(ctx, l.ID); err != nil { |
| + log.Printf("console: link %s: rotate: channel sync: %v (linkSyncLoop retries)", l.ID, err) |
| + } |
| + log.Printf("console: link %s rotated its credential", l.ID) |
| + 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. |
| +func (s *Server) handleLinkUnlink(w http.ResponseWriter, r *http.Request) { |
| + p, l, acct, ok := s.linkCaller(w, r) |
| + if !ok { |
| + 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) |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +// 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. |
| +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 s.dropLinkedApps(ctx, l.ID) |
| +} |
| + |
| +// dropLinkedApps deletes every apps row of linkID, the last step of an |
| +// unlink. |
| +func (s *Server) dropLinkedApps(ctx context.Context, linkID string) error { |
| + apps, err := s.store.LinkedApps(linkID) |
| + if err != nil { |
| + return fmt.Errorf("list linked apps: %w", err) |
| + } |
| + var errs []error |
| + for _, a := range apps { |
| + if _, err := s.store.deleteLinkedAppRow(ctx, a.AccountID, a.App, linkID); err != nil { |
| + errs = append(errs, fmt.Errorf("delete %s: %w", a.App, err)) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// 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 |
| +// itself and linkSyncPass finishes them. |
| +func (s *Server) unlinkAccountLinks(ctx context.Context, accountID int64) { |
| + links, err := s.store.LinksForAccount(accountID) |
| + if err != nil { |
| + log.Printf("console: unlink the links of account %d: %v", accountID, err) |
| + return |
| + } |
| + for i := range links { |
| + if !links[i].RevokedAt.IsZero() { |
| + continue |
| + } |
| + if err := s.unlink(ctx, &links[i], "account-reap"); err != nil { |
| + log.Printf("console: unlink %s of account %d: %v (linkSyncPass finishes it)", links[i].ID, accountID, err) |
| + } |
| + } |
| +} |
| + |
| +// linkSyncRetryBackoff is the wait before each retry of a door's own sync: |
| +// three retries after the first try. |
| +var linkSyncRetryBackoff = []time.Duration{50 * time.Millisecond, 150 * time.Millisecond, 400 * time.Millisecond} |
| + |
| +// syncLinkRetry is syncLinkChannel retried three times with a short |
| +// backoff: the rotate and unlink doors' own sync after their transaction. |
| +func (s *Server) syncLinkRetry(ctx context.Context, linkID string) error { |
| + err := s.syncLinkChannel(ctx, linkID) |
| + for _, d := range linkSyncRetryBackoff { |
| + if err == nil { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return errors.Join(err, ctx.Err()) |
| + case <-time.After(d): |
| + } |
| + err = s.syncLinkChannel(ctx, linkID) |
| + } |
| + return err |
| +} |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| new file mode 100644 |
| index 000000000..ab7d0a310 |
| --- /dev/null |
| +++ b/internal/console/apilinks_test.go |
| @@ -0,0 +1,1251 @@ |
| +package console |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "go/parser" |
| + "go/token" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// Linked deployments, Task 5 (spec §5.2, §5.3, §6.0, §6.1, §6.7): the link |
| +// doors, linked apps and the linked-app guard. |
| + |
| +// linked is one link minted through the whole ceremony on fx. |
| +type linked struct { |
| + token, id string |
| +} |
| + |
| +// mintLink runs the link ceremony for home on fx's account. |
| +func mintLink(t *testing.T, fx *consoleFixture, browser *http.Client, home string) linked { |
| + t.Helper() |
| + poll := linkCeremony(t, fx, browser, home, fx.sqid) |
| + return linked{token: str(t, poll, "token"), id: str(t, poll, "link_id")} |
| +} |
| + |
| +// linkDoor sends one request to a link door with bearer token. |
| +func linkDoor(t *testing.T, fx *consoleFixture, method, path, token, body string) (int, string) { |
| + t.Helper() |
| + status, _, out := rawReq(t, method, fx.ts.URL+path, token, body) |
| + return status, out |
| +} |
| + |
| +func publish(t *testing.T, fx *consoleFixture, token, app string) (int, map[string]any) { |
| + t.Helper() |
| + status, out := linkDoor(t, fx, http.MethodPost, "/api/link/publications", token, `{"app":"`+app+`"}`) |
| + var m map[string]any |
| + _ = json.Unmarshal([]byte(out), &m) |
| + return status, m |
| +} |
| + |
| +func linkJSONErr(body string) string { |
| + var m struct { |
| + Error string `json:"error"` |
| + } |
| + _ = json.Unmarshal([]byte(body), &m) |
| + return m.Error |
| +} |
| + |
| +func linkHost(fx *consoleFixture, app string) string { |
| + return app + "." + fx.sqid + ".apps.example.com" |
| +} |
| + |
| +func linkOpsAccount(t *testing.T, fx *consoleFixture) *Account { |
| + t.Helper() |
| + acct, err := fx.st.AccountBySqid(fx.sqid) |
| + if err != nil || acct == nil { |
| + t.Fatal(acct, err) |
| + } |
| + return acct |
| +} |
| + |
| +func linkForwardHosts(t *testing.T, fx *consoleFixture, linkID string) []string { |
| + t.Helper() |
| + rows, err := linkRegistryOf(t, fx).LinkForwards(linkID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, r := range rows { |
| + out = append(out, r.Host) |
| + } |
| + return out |
| +} |
| + |
| +func TestPublishCreatesLinkedAppAndRow(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + |
| + status, out := publish(t, fx, l.token, "shop") |
| + wantURL := "https://" + linkHost(fx, "shop") |
| + if status != http.StatusCreated || out["app"] != "shop" || out["url"] != wantURL { |
| + t.Fatalf("publish = %d %v, want 201 shop at %s", status, out, wantURL) |
| + } |
| + acct := linkOpsAccount(t, fx) |
| + if id, err := fx.st.appLinkID(acct.ID, "shop"); err != nil || id != l.id { |
| + t.Fatalf("apps row linked_link_id = %q %v, want %s", id, err, l.id) |
| + } |
| + if has, _ := fx.st.HasAppIn(acct.ID, "shop"); !has { |
| + t.Fatal("the linked app is not a live app of the account") |
| + } |
| + rows, err := linkRegistryOf(t, fx).LinkForwards(l.id) |
| + if err != nil || len(rows) != 1 { |
| + t.Fatalf("LinkForwards = %v %v, want one row", rows, err) |
| + } |
| + r := rows[0] |
| + if r.Host != linkHost(fx, "shop") || r.Region != "link/"+l.id || r.App != "shop" || r.Account != fx.sqid || !r.IsForward() { |
| + t.Fatalf("forward row = %+v", r) |
| + } |
| + // GET /api/link lists it. |
| + code, body := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, "") |
| + var got struct { |
| + LinkID string `json:"link_id"` |
| + Account string `json:"account"` |
| + Name string `json:"name"` |
| + Publications []struct { |
| + App, URL string |
| + CreatedAt time.Time `json:"created_at"` |
| + } `json:"publications"` |
| + } |
| + if err := json.Unmarshal([]byte(body), &got); code != http.StatusOK || err != nil { |
| + t.Fatalf("GET /api/link = %d %s %v", code, body, err) |
| + } |
| + if got.LinkID != l.id || got.Account != fx.sqid || got.Name != "shop-home" || len(got.Publications) != 1 || |
| + got.Publications[0].App != "shop" || got.Publications[0].URL != wantURL || got.Publications[0].CreatedAt.IsZero() { |
| + t.Fatalf("GET /api/link = %+v", got) |
| + } |
| +} |
| + |
| +func TestPublishRefusesTakenName(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + acct := linkOpsAccount(t, fx) |
| + if _, err := fx.st.CreateAppIn(acct.ID, "blog", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, app := range []string{"blog", "kass"} { |
| + status, out := publish(t, fx, l.token, app) |
| + want := linkCopy(copyLD10, "app", app, "account", acct.Name) |
| + if status != http.StatusConflict || out["error"] != want { |
| + t.Fatalf("publish %s = %d %v, want 409 %q", app, status, out, want) |
| + } |
| + if id, _ := fx.st.appLinkID(acct.ID, app); id != "" { |
| + t.Fatalf("%s became linked", app) |
| + } |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after refused publishes: %v", hosts) |
| + } |
| +} |
| + |
| +func TestPublishRespectsCap(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + acct := atRunningCap(t, fx, 3) |
| + status, out := publish(t, fx, l.token, "shop") |
| + if status != http.StatusConflict || out["code"] != "cap" || out["error"] == nil { |
| + t.Fatalf("publish at the cap = %d %v, want 409 cap", status, out) |
| + } |
| + if has, _ := fx.st.HasAppIn(acct.ID, "shop"); has { |
| + t.Fatal("published past the cap") |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows past the cap: %v", hosts) |
| + } |
| + // A publication counts as an app: below the cap it fits, and then the |
| + // account is at the cap again. |
| + raiseRunningCap(t, fx, acct, 1) |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish below the cap = %d %v", status, out) |
| + } |
| + if status, out := publish(t, fx, l.token, "blog"); status != http.StatusConflict || out["code"] != "cap" { |
| + t.Fatalf("second publish = %d %v, want 409 cap: the first counted", status, out) |
| + } |
| +} |
| + |
| +// orderRegistry records whether the apps row was still there when the |
| +// forward row was deleted. |
| +type orderRegistry struct { |
| + consoleRegistry |
| + st *Store |
| + acct int64 |
| + rowAtDelete []bool |
| +} |
| + |
| +func (o *orderRegistry) DeleteLinkForward(host, linkID string) (bool, error) { |
| + has, _ := o.st.HasAppIn(o.acct, strings.SplitN(host, ".", 2)[0]) |
| + o.rowAtDelete = append(o.rowAtDelete, has) |
| + return o.consoleRegistry.DeleteLinkForward(host, linkID) |
| +} |
| + |
| +func TestUnpublishRemovesRowThenApp(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + browser := signInPaul(t, fx) |
| + l := mintLink(t, fx, browser, "shop-home") |
| + acct := linkOpsAccount(t, fx) |
| + order := &orderRegistry{consoleRegistry: linkRegistryOf(t, fx), st: fx.st, acct: acct.ID} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return order, nil } |
| + |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + // Name-keyed state a later app of the name must not inherit. |
| + life, err := fx.st.AppLife(acct.ID, "shop") |
| + if err != nil || life == nil { |
| + t.Fatal(life, err) |
| + } |
| + if err := fx.st.SetAppStar(acct.ID, "paul@keymail.dev", life.Lifetime, true, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link/publications/shop", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("unpublish = %d %s", status, body) |
| + } |
| + if len(order.rowAtDelete) != 1 || !order.rowAtDelete[0] { |
| + t.Fatalf("apps row present at the forward delete = %v, want [true]: the forward row goes first", order.rowAtDelete) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after unpublish: %v", hosts) |
| + } |
| + if has, _ := fx.st.HasAppIn(acct.ID, "shop"); has { |
| + t.Fatal("the apps row outlived unpublish") |
| + } |
| + var stars int |
| + if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM app_stars WHERE account_id = ?`, acct.ID).Scan(&stars); err != nil || stars != 0 { |
| + t.Fatalf("stars after unpublish = %d %v, want none", stars, err) |
| + } |
| + // A missing row on either side is not an error. |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link/publications/shop", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("second unpublish = %d %s", status, body) |
| + } |
| + // The name is free again, for a fresh publication. |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish again = %d %v", status, out) |
| + } |
| +} |
| + |
| +func TestUnlinkRemovesEverything(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + acct := linkOpsAccount(t, fx) |
| + for _, app := range []string{"shop", "blog"} { |
| + if status, out := publish(t, fx, l.token, app); status != http.StatusCreated { |
| + t.Fatalf("publish %s = %d %v", app, status, out) |
| + } |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("unlink = %d %s", status, body) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after unlink: %v", hosts) |
| + } |
| + if apps, err := fx.st.LinkedApps(l.id); err != nil || len(apps) != 0 { |
| + t.Fatalf("linked apps after unlink = %v %v", apps, err) |
| + } |
| + for _, app := range []string{"shop", "blog"} { |
| + if has, _ := fx.st.HasAppIn(acct.ID, app); has { |
| + t.Fatalf("%s outlived unlink", app) |
| + } |
| + } |
| + if _, ok := fx.st.CLIPrincipal(l.token, time.Now()); ok { |
| + t.Fatal("the link token still resolves after unlink") |
| + } |
| + auth, err := linkRegistryOf(t, fx).LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if h, has := auth[registry.LinkChannelName(l.id)]; has { |
| + t.Fatalf("LinkChannelAuth still holds the link (%s)", h) |
| + } |
| + if status, _ := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, ""); status != http.StatusUnauthorized { |
| + t.Fatalf("GET /api/link after unlink = %d, want 401", status) |
| + } |
| +} |
| + |
| +func TestRotateReplacesHash(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + status, body := linkDoor(t, fx, http.MethodPost, "/api/link/rotate", l.token, "") |
| + var out map[string]string |
| + if err := json.Unmarshal([]byte(body), &out); status != http.StatusOK || err != nil || out["token"] == "" || out["token"] == l.token { |
| + t.Fatalf("rotate = %d %s", status, body) |
| + } |
| + tokenB := out["token"] |
| + if _, ok := fx.st.CLIPrincipal(l.token, time.Now()); ok { |
| + t.Fatal("the old token still resolves") |
| + } |
| + if status, _ := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, ""); status != http.StatusUnauthorized { |
| + t.Fatalf("old token at GET /api/link = %d, want 401", status) |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodGet, "/api/link", tokenB, ""); status != http.StatusOK { |
| + t.Fatalf("new token at GET /api/link = %d %s", status, body) |
| + } |
| + auth, err := linkRegistryOf(t, fx).LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := auth[registry.LinkChannelName(l.id)]; got != hashToken(tokenB) || got == hashToken(l.token) { |
| + t.Fatalf("registry hash = %q, want the new token's", got) |
| + } |
| +} |
| + |
| +// handDialHub registers name with token on the hub at hubURL by hand and |
| +// serves the channel until the hub closes it; done closes then. status is |
| +// the registration's answer. |
| +func handDialHub(t *testing.T, hubURL, hubHost, name, token string) (status int, done chan struct{}) { |
| + t.Helper() |
| + u, err := url.Parse(hubURL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + conn, err := net.Dial("tcp", u.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { conn.Close() }) |
| + req, err := http.NewRequest(http.MethodGet, "http://"+hubHost+"/register", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Connection", "Upgrade") |
| + req.Header.Set("Upgrade", "carlos-tunnel/1") |
| + req.Header.Set("Carlos-Tunnel-Name", name) |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + if err := req.Write(conn); err != nil { |
| + t.Fatal(err) |
| + } |
| + br := bufio.NewReader(conn) |
| + res, err := http.ReadResponse(br, req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + done = make(chan struct{}) |
| + if res.StatusCode != http.StatusSwitchingProtocols { |
| + conn.Close() |
| + close(done) |
| + return res.StatusCode, done |
| + } |
| + go func() { |
| + tunnelclient.Serve(&bufConn{Conn: conn, r: io.MultiReader(br, conn)}, http.NotFoundHandler()) |
| + close(done) |
| + }() |
| + return res.StatusCode, done |
| +} |
| + |
| +type bufConn struct { |
| + net.Conn |
| + r io.Reader |
| +} |
| + |
| +func (b *bufConn) Read(p []byte) (int, error) { return b.r.Read(p) } |
| + |
| +// TestRotateClosesTheLiveConnection: the hash the rotate door's sync writes |
| +// is the one the hub reads, and the hub closes the connection that |
| +// authenticated on the old one (Task 3's SetDynamicAuth). The hub here is |
| +// the edge's own TunnelHub fed from the console's registry, as the edge's |
| +// Reload feeds it. |
| +func TestRotateClosesTheLiveConnection(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + reg := linkRegistryOf(t, fx) |
| + hub := edge.NewTunnelHub("tunnel.example.com", nil) |
| + reload := func() { |
| + auth, err := reg.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, done := handDialHub(t, hts.URL, hub.Host(), name, l.token) |
| + if status != http.StatusSwitchingProtocols { |
| + t.Fatalf("dial with the link token = %d, want 101", status) |
| + } |
| + waitHubState(t, hub, name, "connected") |
| + |
| + code, body := linkDoor(t, fx, http.MethodPost, "/api/link/rotate", l.token, "") |
| + var out map[string]string |
| + if err := json.Unmarshal([]byte(body), &out); code != http.StatusOK || err != nil { |
| + t.Fatalf("rotate = %d %s", code, body) |
| + } |
| + reload() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the hub kept the connection on the rotated-away token") |
| + } |
| + if status, _ := handDialHub(t, hts.URL, hub.Host(), name, l.token); status != http.StatusUnauthorized { |
| + t.Fatalf("redial with the old token = %d, want 401", status) |
| + } |
| + if status, _ := handDialHub(t, hts.URL, hub.Host(), name, out["token"]); status != http.StatusSwitchingProtocols { |
| + t.Fatalf("dial with the new token = %d, want 101", status) |
| + } |
| +} |
| + |
| +func waitHubState(t *testing.T, hub *edge.TunnelHub, name, want string) { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for time.Now().Before(deadline) { |
| + if hub.State(name) == want { |
| + return |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + t.Fatalf("%s never became %s (is %s)", name, want, hub.State(name)) |
| +} |
| + |
| +// TestLinkedPolicyCoversEveryAppRoute: every route declaration that names an |
| +// {app}, browser and CLI alike, is classified by linkedAppPolicy's table, |
| +// whichever helper its handler uses; and every entry is a declared route. |
| +// The link's own doors are not app doors: they act only on the link's own |
| +// linked apps and never consult the guard. |
| +func TestLinkedPolicyCoversEveryAppRoute(t *testing.T) { |
| + declared := map[string]bool{} |
| + appRoutes := 0 |
| + for _, d := range routeDecls { |
| + declared[d.Pattern] = true |
| + if d.Kind == kindLink || !strings.Contains(d.Pattern, "{app}") { |
| + continue |
| + } |
| + appRoutes++ |
| + if _, ok := linkedPolicies[d.Pattern]; !ok { |
| + t.Errorf("%s names an {app} but linkedAppPolicy does not classify it: add it to linkedPolicies", d.Pattern) |
| + } |
| + } |
| + if appRoutes < 200 { |
| + t.Fatalf("saw %d {app} routes, want at least 200; is routeDecls being read?", appRoutes) |
| + } |
| + for pattern := range linkedPolicies { |
| + if !declared[pattern] { |
| + t.Errorf("linkedPolicies classifies %s, which is not a declared route", pattern) |
| + } |
| + } |
| + // Unknown patterns refuse. |
| + if linkedAppPolicy("GET /a/{sqid}/apps/{app}/brand-new") != linkedRefuse || linkedAppPolicy("") != linkedRefuse { |
| + t.Error("an unclassified pattern does not refuse") |
| + } |
| +} |
| + |
| +// linkedWalkBoxDoors are the {app} routes no person or browser session can |
| +// reach: box doors that resolve the app from a box-signed instance record |
| +// in the bucket. A linked app has none (publish refuses a name with any |
| +// object under its prefix, and every door that could write one refuses a |
| +// linked app), so these are classified linkedRefuse and not walked. |
| +// linkedWalkOpaqueDoors answer every refusal of their gate, the linked |
| +// one included, with the same byte-identical 404 (app_source.go: the claimed |
| +// source door is not an oracle). The walk holds them to that 404 and to |
| +// changing nothing. |
| +var linkedWalkOpaqueDoors = map[string]bool{ |
| + "GET /a/{sqid}/apps/{app}/source": true, |
| + "GET /api/cli/apps/{account}/{app}/source": true, |
| +} |
| + |
| +var linkedWalkBoxDoors = map[string]bool{ |
| + "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": true, |
| + "POST /api/fleet/replicas/{account}/{app}/{host}/release": true, |
| +} |
| + |
| +// worldSnapshot is what a refused request must not change: every console |
| +// table but the sign-in bookkeeping, the bucket, and the registry. |
| +func worldSnapshot(t *testing.T, fx *consoleFixture) map[string]string { |
| + t.Helper() |
| + out := map[string]string{} |
| + rows, err := fx.st.db.Query(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var tables []string |
| + for rows.Next() { |
| + var n string |
| + if err := rows.Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + tables = append(tables, n) |
| + } |
| + rows.Close() |
| + for _, table := range tables { |
| + if linkedWalkBookkeeping[table] { |
| + continue |
| + } |
| + r, err := fx.st.db.Query(`SELECT * FROM "` + table + `"`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, _ := r.Columns() |
| + var b strings.Builder |
| + for r.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + if err := r.Scan(ptrs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, v := range vals { |
| + if bs, ok := v.([]byte); ok { |
| + v = string(bs) |
| + } |
| + b.WriteString(strings.ReplaceAll(strings.TrimSpace(fmtAny(v)), "\n", " ")) |
| + b.WriteByte('|') |
| + } |
| + b.WriteByte('\n') |
| + } |
| + r.Close() |
| + out["table "+table] = b.String() |
| + } |
| + keys, err := fx.rel.List(context.Background(), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range keys { |
| + body, _, err := fx.rel.Get(context.Background(), k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out["object "+k] = string(body) |
| + } |
| + fp, err := linkRegistryOf(t, fx).(*registry.Registry).Fingerprint() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out["registry"] = fp |
| + return out |
| +} |
| + |
| +func fmtAny(v any) string { |
| + b, _ := json.Marshal(v) |
| + return string(b) |
| +} |
| + |
| +// linkedWalkBookkeeping are the tables a request's sign-in touches whatever |
| +// door it reaches: a session's or a token's last use. Nothing a door acts on |
| +// lives in them. |
| +var linkedWalkBookkeeping = map[string]bool{ |
| + "sessions": true, "users": true, "cli_tokens": true, |
| +} |
| + |
| +// TestLinkedAppRefusedOnAppRoutes walks every declared {app} route with a |
| +// request for a linked app, by a person token at the CLI's doors and by a |
| +// browser session (stepped up, CSRF token in the form) at the browser's: |
| +// every linkedRefuse door answers 409 with LD-C11 (LD-C12 at the domains |
| +// doors), GET and non-GET alike, with nothing changed in the console's |
| +// tables, the bucket or the registry; no linkedAllow door gives the linked |
| +// refusal. |
| +func TestLinkedAppRefusedOnAppRoutes(t *testing.T) { |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) { |
| + c.TunnelHost = "tunnel.example.com" |
| + c.AppsDomain = "apps.example.com" |
| + c.MovesEnabled = true |
| + // The email pause door is an operator's; paul is one here so the |
| + // walk reaches its resolver. |
| + c.MailOperators = []string{"paul@keymail.dev"} |
| + }}) |
| + if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + acct := linkOpsAccount(t, fx) |
| + linkToken := mintWalkLinkIn(t, fx.st, acct.ID) |
| + p, _ := fx.st.CLIPrincipal(linkToken, time.Now()) |
| + if _, err := fx.st.CreateLinkedApp(acct.ID, "shop", "link:"+fx.sqid+"/"+p.LinkID, p.LinkID, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + person := mintWalkPerson(t, fx.st) |
| + session, err := fx.st.CreateSession("paul@keymail.dev", "test", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.RecordStepUp(session, "paul@keymail.dev", time.Now(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + home := "walk-home" |
| + refusal := linkCopy(copyLD11, "app", "shop", "home", home) |
| + client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + |
| + refused, allowed := 0, 0 |
| + for _, d := range routeDecls { |
| + if d.Kind == kindLink || !strings.Contains(d.Pattern, "{app}") || linkedWalkBoxDoors[d.Pattern] { |
| + continue |
| + } |
| + if d.Gate != nil && !d.Gate.holds(fx.srv.cfg) { |
| + t.Fatalf("%s: its gate does not hold in the walk's world", d.Pattern) |
| + } |
| + method, path := linkWalkRequest(t, d.Pattern) |
| + path = strings.ReplaceAll(path, linkWalkSqid, fx.sqid) |
| + browser := !strings.HasPrefix(path, "/api/") |
| + var body io.Reader |
| + var req *http.Request |
| + if browser { |
| + if method != http.MethodGet { |
| + body = strings.NewReader(url.Values{"csrf": {session}}.Encode()) |
| + } |
| + req, _ = http.NewRequest(method, fx.ts.URL+path, body) |
| + if body != nil { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + } |
| + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: session}) |
| + } else { |
| + if method != http.MethodGet && method != http.MethodDelete { |
| + body = strings.NewReader(`{}`) |
| + } |
| + req, _ = http.NewRequest(method, fx.ts.URL+path, body) |
| + if body != nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + req.Header.Set("Authorization", "Bearer "+person) |
| + } |
| + pol := linkedAppPolicy(d.Pattern) |
| + want := refusal |
| + if pol == linkedRefuseDomains { |
| + want = copyLD12 |
| + } |
| + var before map[string]string |
| + if pol != linkedAllow { |
| + before = worldSnapshot(t, fx) |
| + } |
| + res, err := client.Do(req) |
| + if err != nil { |
| + t.Fatalf("%s: %v", d.Pattern, err) |
| + } |
| + raw, _ := io.ReadAll(res.Body) |
| + res.Body.Close() |
| + got := string(raw) |
| + saysRefusal := strings.Contains(got, esc(want)) || linkJSONErr(got) == want |
| + if pol == linkedAllow { |
| + allowed++ |
| + 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) |
| + } |
| + continue |
| + } |
| + refused++ |
| + if linkedWalkOpaqueDoors[d.Pattern] { |
| + if res.StatusCode != http.StatusNotFound { |
| + t.Errorf("%s %s = %d, want the source door's 404", method, path, res.StatusCode) |
| + } |
| + } else if res.StatusCode != http.StatusConflict || !saysRefusal { |
| + t.Errorf("%s %s = %d, want 409 with %q:\n%.300s", method, path, res.StatusCode, want, got) |
| + continue |
| + } |
| + after := worldSnapshot(t, fx) |
| + for k, v := range after { |
| + if before[k] != v { |
| + t.Errorf("%s: the refused request changed %s", d.Pattern, k) |
| + } |
| + } |
| + for k := range before { |
| + if _, ok := after[k]; !ok { |
| + t.Errorf("%s: the refused request removed %s", d.Pattern, k) |
| + } |
| + } |
| + } |
| + if refused < 150 || allowed < 5 { |
| + t.Fatalf("walked %d refused and %d allowed doors; the walk proves nothing", refused, allowed) |
| + } |
| + // The ordinary app is untouched by the guard: the same walk's doors |
| + // answer a non-linked app as before (spot check, both families). |
| + if status, _, body := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/kass/config", person, ""); status == http.StatusConflict { |
| + t.Fatalf("an ordinary app got %d %s", status, body) |
| + } |
| +} |
| + |
| +func TestPublishIsIdempotent(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + browser := signInPaul(t, fx) |
| + l1 := mintLink(t, fx, browser, "shop-home") |
| + l2 := mintLink(t, fx, browser, "blog-home") |
| + status, first := publish(t, fx, l1.token, "shop") |
| + if status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, first) |
| + } |
| + reg := linkRegistryOf(t, fx) |
| + if ok, err := reg.DeleteLinkForward(linkHost(fx, "shop"), l1.id); err != nil || !ok { |
| + t.Fatalf("delete the forward row behind the console's back: %v %v", ok, err) |
| + } |
| + status, again := publish(t, fx, l1.token, "shop") |
| + if status != http.StatusOK || again["app"] != first["app"] || again["url"] != first["url"] { |
| + t.Fatalf("publish again = %d %v, want 200 with %v", status, again, first) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l1.id); len(hosts) != 1 || hosts[0] != linkHost(fx, "shop") { |
| + t.Fatalf("forward rows after the retry = %v", hosts) |
| + } |
| + status, other := publish(t, fx, l2.token, "shop") |
| + if want := linkCopy(copyLD10, "app", "shop", "account", linkOpsAccount(t, fx).Name); status != http.StatusConflict || other["error"] != want { |
| + t.Fatalf("another link publishing shop = %d %v, want 409 %q", status, other, want) |
| + } |
| +} |
| + |
| +func TestUnlinkUsesRegistryRows(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + reg := linkRegistryOf(t, fx) |
| + orphan := linkHost(fx, "orphan") |
| + if err := reg.PutForward(registry.Route{Kind: registry.KindForward, Host: orphan, App: "orphan", Account: fx.sqid, |
| + Region: registry.LinkPlacementPrefix + l.id}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if has, _ := fx.st.HasAppIn(linkOpsAccount(t, fx).ID, "orphan"); has { |
| + t.Fatal("the fixture has an apps row for the orphan") |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("unlink = %d %s", status, body) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l.id); len(hosts) != 0 { |
| + t.Fatalf("forward rows after unlink: %v, want the orphan gone too", hosts) |
| + } |
| +} |
| + |
| +func TestPublishRacingUnlink(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{}) |
| + fx.srv.linkPublishHook = func(id, stage string) { |
| + if id == l.id && stage == linkPublishAfterInsert { |
| + close(paused) |
| + <-release |
| + } |
| + } |
| + type answer struct { |
| + status int |
| + out map[string]any |
| + } |
| + done := make(chan answer, 1) |
| + go func() { |
| + status, out := publish(t, fx, l.token, "shop") |
| + done <- answer{status, out} |
| + }() |
| + <-paused |
| + 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) |
| + } |
| + close(release) |
| + 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) |
| + } |
| + 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 racing publish left its apps row") |
| + } |
| +} |
| + |
| +// TestEveryAppDeleteRespectsLinked: every statement in the package that |
| +// deletes or trashes an apps row skips a linked one, except the one that |
| +// exists to delete it (deleteLinkedAppRow); and the passes that act on the |
| +// bucket's word leave a linked row alone. |
| +func TestEveryAppDeleteRespectsLinked(t *testing.T) { |
| + t.Run("scan", func(t *testing.T) { |
| + del := regexp.MustCompile(`(?is)\bDELETE\s+FROM\s+apps\b`) |
| + trash := regexp.MustCompile(`(?is)\bUPDATE\s+apps\s+SET\s+deleted_at\s*=\s*\?`) |
| + guard := regexp.MustCompile(`linked_link_id\s*=\s*''`) |
| + allowed := map[string]bool{"links_store.go:deleteLinkedAppRow": true} |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seen := 0 |
| + for _, name := range files { |
| + if strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range f.Decls { |
| + unit := name + ":" + declUnit(decl) |
| + for _, lit := range sqlStringsIn(decl) { |
| + if !del.MatchString(lit) && !trash.MatchString(lit) { |
| + continue |
| + } |
| + seen++ |
| + if allowed[unit] { |
| + if !strings.Contains(lit, "linked_link_id = ?") { |
| + t.Errorf("%s deletes apps rows without naming the link: %s", unit, lit) |
| + } |
| + continue |
| + } |
| + if !guard.MatchString(lit) { |
| + t.Errorf("%s deletes or trashes an apps row without skipping a linked one (linked_link_id = ''):\n%s", unit, lit) |
| + } |
| + } |
| + } |
| + } |
| + if seen < 8 { |
| + t.Fatalf("found %d apps deletes and trashes; is the scan reading the package?", seen) |
| + } |
| + }) |
| + |
| + t.Run("tombstone", func(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) |
| + } |
| + ctx := context.Background() |
| + now := time.Now() |
| + if err := release.TrashApp(ctx, fx.rel, fx.sqid, "shop", "someone", now.Add(-40*24*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := MaterializeApps(ctx, fx.rel, fx.st); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.settleApp(ctx, OpsAccountID, fx.sqid, "shop", now, always(true)); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.sweepTrashedApp(ctx, release.TrashedApp{Account: fx.sqid, App: "shop"}, now) |
| + if life, err := fx.st.AppLife(OpsAccountID, "shop"); err != nil || life == nil || life.Trashed() || life.LinkID != l.id { |
| + t.Fatalf("after a tombstone the linked row = %+v %v, want live and linked", life, err) |
| + } |
| + if err := fx.st.claimRawTrashAppRow(OpsAccountID, "shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.PurgeAppRow(OpsAccountID, "shop"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if life, _ := fx.st.AppLife(OpsAccountID, "shop"); life == nil || life.Trashed() { |
| + t.Fatalf("TrashAppRow or PurgeAppRow touched the linked row: %+v", life) |
| + } |
| + }) |
| + |
| + t.Run("expiry", func(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) |
| + } |
| + now := time.Now().Truncate(time.Second) |
| + // A linked row that somehow carries an expiry: the pass still |
| + // leaves it. |
| + if _, err := fx.st.db.Exec(`UPDATE apps SET expires_at = ? WHERE app = 'shop'`, now.Add(-time.Minute).Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.expiryPass(context.Background(), now) |
| + if markerOf(t, fx, "shop") != nil { |
| + t.Fatal("the expiry pass trashed a linked app in the bucket") |
| + } |
| + if life := lifeOf(t, fx, "shop"); life == nil || life.Trashed() { |
| + t.Fatalf("after the expiry pass the linked row = %+v", life) |
| + } |
| + if ok, err := fx.st.claimRawExpireAppRow(OpsAccountID, "shop", now); err != nil || ok { |
| + t.Fatalf("ExpireAppRow on a linked row = %v %v, want no change", ok, err) |
| + } |
| + }) |
| + |
| + t.Run("reap unlinks first", func(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + const 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) |
| + } |
| + tok := mintWalkLinkIn(t, fx.st, id) |
| + p, _ := fx.st.CLIPrincipal(tok, now) |
| + if err := fx.srv.syncLinkChannel(context.Background(), p.LinkID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, out := publish(t, fx, tok, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + 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) |
| + } |
| + // The registry the unlink writes records what it saw: the app row |
| + // is still there when the channel is revoked, so the unlink ran |
| + // before the reap. |
| + real := linkRegistryOf(t, fx) |
| + spy := &revokeSpy{consoleRegistry: real, st: fx.st, acct: id} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return spy, nil } |
| + if _, err := materializeAccounts(context.Background(), fx.rel, fx.st, fx.srv.unlinkAccountLinks); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(spy.accountLive) != 1 || !spy.accountLive[0] { |
| + t.Fatalf("account live at the channel revoke = %v, want [true]: unlink runs before the reap", spy.accountLive) |
| + } |
| + rows, err := real.LinkForwards(p.LinkID) |
| + if err != nil || len(rows) != 0 { |
| + t.Fatalf("forward rows after the reap = %v %v", rows, err) |
| + } |
| + if apps, _ := fx.st.LinkedApps(p.LinkID); len(apps) != 0 { |
| + t.Fatalf("linked apps after the reap = %v", apps) |
| + } |
| + if a, deleted, _ := fx.st.AccountAnyBySqid(sqid); a == nil || !deleted { |
| + t.Fatalf("account after the reap = %+v deleted=%v", a, deleted) |
| + } |
| + }) |
| +} |
| + |
| +// revokeSpy records, at each channel revoke, whether the account was still |
| +// live (not yet reaped). |
| +type revokeSpy struct { |
| + consoleRegistry |
| + st *Store |
| + acct int64 |
| + accountLive []bool |
| +} |
| + |
| +func (r *revokeSpy) RevokeLinkChannel(linkID string) (bool, error) { |
| + a, err := r.st.AccountByID(r.acct) |
| + r.accountLive = append(r.accountLive, err == nil && a != nil) |
| + return r.consoleRegistry.RevokeLinkChannel(linkID) |
| +} |
| + |
| +func TestLinkCannotTouchAnotherLinksApps(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + browser := signInPaul(t, fx) |
| + l1 := mintLink(t, fx, browser, "shop-home") |
| + l2 := mintLink(t, fx, browser, "blog-home") |
| + if status, out := publish(t, fx, l2.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("L2 publish = %d %v", status, out) |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link/publications/shop", l1.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("L1 unpublish of L2's app = %d %s", status, body) |
| + } |
| + acct := linkOpsAccount(t, fx) |
| + if id, _ := fx.st.appLinkID(acct.ID, "shop"); id != l2.id { |
| + t.Fatalf("L2's app row after L1's unpublish: linked to %q", id) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l2.id); len(hosts) != 1 { |
| + t.Fatalf("L2's forward rows after L1's unpublish = %v", hosts) |
| + } |
| + // L1's unlink leaves L2's publication too. |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l1.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("L1 unlink = %d %s", status, body) |
| + } |
| + if id, _ := fx.st.appLinkID(acct.ID, "shop"); id != l2.id { |
| + t.Fatalf("L2's app row after L1's unlink: linked to %q", id) |
| + } |
| + if hosts := linkForwardHosts(t, fx, l2.id); len(hosts) != 1 { |
| + t.Fatalf("L2's forward rows after L1's unlink = %v", hosts) |
| + } |
| +} |
| + |
| +// ---- carried from Task 4's reviews ------------------------------------------ |
| + |
| +// linkGenFault fails PutLinkChannel at generation gen or above, and |
| +// RevokeLinkChannel, while their counters are above zero, counting calls. |
| +type linkGenFault struct { |
| + consoleRegistry |
| + mu sync.Mutex |
| + gen uint64 |
| + putFail, revFail int |
| + putCalls, revCalls int |
| +} |
| + |
| +func (f *linkGenFault) PutLinkChannel(c registry.LinkChannel) (bool, error) { |
| + f.mu.Lock() |
| + if c.Generation >= f.gen { |
| + f.putCalls++ |
| + if f.putFail > 0 { |
| + f.putFail-- |
| + f.mu.Unlock() |
| + return false, errors.New("injected put failure") |
| + } |
| + } |
| + f.mu.Unlock() |
| + return f.consoleRegistry.PutLinkChannel(c) |
| +} |
| + |
| +func (f *linkGenFault) RevokeLinkChannel(id string) (bool, error) { |
| + f.mu.Lock() |
| + f.revCalls++ |
| + if f.revFail > 0 { |
| + f.revFail-- |
| + f.mu.Unlock() |
| + return false, errors.New("injected revoke failure") |
| + } |
| + f.mu.Unlock() |
| + return f.consoleRegistry.RevokeLinkChannel(id) |
| +} |
| + |
| +// TestRotateAndUnlinkRetryTheirSync: the rotate and unlink doors retry their |
| +// own sync three times before returning; past that the change stands and |
| +// linkSyncPass finishes it. |
| +func TestRotateAndUnlinkRetryTheirSync(t *testing.T) { |
| + setup := func(t *testing.T) (*consoleFixture, linked, *linkGenFault) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + fault := &linkGenFault{consoleRegistry: linkRegistryOf(t, fx), gen: 2} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return fault, nil } |
| + return fx, l, fault |
| + } |
| + rotate := func(t *testing.T, fx *consoleFixture, l linked) string { |
| + status, body := linkDoor(t, fx, http.MethodPost, "/api/link/rotate", l.token, "") |
| + var out map[string]string |
| + if err := json.Unmarshal([]byte(body), &out); status != http.StatusOK || err != nil || out["token"] == "" { |
| + t.Fatalf("rotate = %d %s", status, body) |
| + } |
| + return out["token"] |
| + } |
| + channel := func(t *testing.T, fx *consoleFixture, id string) (string, bool) { |
| + auth, err := linkRegistryOf(t, fx).LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h, ok := auth[registry.LinkChannelName(id)] |
| + return h, ok |
| + } |
| + t.Run("rotate heals within its retries", func(t *testing.T) { |
| + fx, l, fault := setup(t) |
| + fault.putFail = 3 |
| + tokenB := rotate(t, fx, l) |
| + if h, _ := channel(t, fx, l.id); h != hashToken(tokenB) || fault.putCalls != 4 { |
| + t.Fatalf("after rotate the channel = %q after %d tries, want the new hash after 4", h, fault.putCalls) |
| + } |
| + }) |
| + t.Run("rotate answers the token when every try fails", func(t *testing.T) { |
| + fx, l, fault := setup(t) |
| + fault.putFail = 4 |
| + tokenB := rotate(t, fx, l) |
| + if fault.putCalls != 4 { |
| + t.Fatalf("rotate tried the sync %d times, want 4", fault.putCalls) |
| + } |
| + if h, _ := channel(t, fx, l.id); h != hashToken(l.token) { |
| + t.Fatalf("channel = %q, want still the old hash", h) |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h, _ := channel(t, fx, l.id); h != hashToken(tokenB) { |
| + t.Fatalf("after the pass the channel = %q, want the new hash", h) |
| + } |
| + }) |
| + t.Run("unlink heals within its retries", func(t *testing.T) { |
| + fx, l, fault := setup(t) |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + t.Fatalf("publish = %d %v", status, out) |
| + } |
| + fault.revFail = 3 |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("unlink = %d %s", status, body) |
| + } |
| + if _, has := channel(t, fx, l.id); has || fault.revCalls != 4 { |
| + t.Fatalf("channel present=%v after %d tries, want revoked after 4", has, fault.revCalls) |
| + } |
| + if apps, _ := fx.st.LinkedApps(l.id); len(apps) != 0 { |
| + t.Fatalf("linked apps = %v", apps) |
| + } |
| + }) |
| + t.Run("unlink stands when every try fails; the pass finishes it", func(t *testing.T) { |
| + fx, l, fault := setup(t) |
| + if status, out := publish(t, fx, l.token, "shop"); status != http.StatusCreated { |
| + 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 fault.revCalls != 4 { |
| + t.Fatalf("unlink tried the sync %d times, want 4", fault.revCalls) |
| + } |
| + if _, ok := fx.st.CLIPrincipal(l.token, time.Now()); ok { |
| + t.Fatal("the token resolves after an unlink whose sync failed") |
| + } |
| + if apps, _ := fx.st.LinkedApps(l.id); len(apps) != 1 { |
| + t.Fatalf("linked apps before the pass = %v, want the row kept until the registry is revoked", apps) |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := channel(t, fx, l.id); has { |
| + t.Fatal("the pass did not revoke the channel") |
| + } |
| + 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) |
| + } |
| + }) |
| +} |
| + |
| +// TestSyncCannotResurrectThroughTheDoors is TestSyncCannotResurrect with |
| +// every step an HTTP request: a request on token A paused inside linkRoute's |
| +// sync while a rotate or an unlink, through its own door, completes. The |
| +// paused sync cannot move the channel back, and the paused request ends in |
| +// the gate's 401. |
| +func TestSyncCannotResurrectThroughTheDoors(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + stage string |
| + unlink bool |
| + }{ |
| + {"rotate/paused-before-read", linkSyncBeforeRead, false}, |
| + {"rotate/paused-before-write", linkSyncBeforeWrite, false}, |
| + {"unlink/paused-before-read", linkSyncBeforeRead, true}, |
| + {"unlink/paused-before-write", linkSyncBeforeWrite, true}, |
| + } { |
| + t.Run(tc.name, func(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.linkSyncHook = func(id, stage string) { |
| + if id != l.id || stage != tc.stage { |
| + return |
| + } |
| + first := false |
| + once.Do(func() { first = true }) |
| + if first { |
| + close(paused) |
| + <-release |
| + } |
| + } |
| + done := make(chan int, 1) |
| + go func() { |
| + status, _ := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, "") |
| + done <- status |
| + }() |
| + <-paused |
| + var tokenB string |
| + if tc.unlink { |
| + if status, body := linkDoor(t, fx, http.MethodDelete, "/api/link", l.token, ""); status != http.StatusNoContent { |
| + t.Fatalf("unlink = %d %s", status, body) |
| + } |
| + } else { |
| + status, body := linkDoor(t, fx, http.MethodPost, "/api/link/rotate", l.token, "") |
| + var out map[string]string |
| + if err := json.Unmarshal([]byte(body), &out); status != http.StatusOK || err != nil { |
| + t.Fatalf("rotate = %d %s", status, body) |
| + } |
| + tokenB = out["token"] |
| + } |
| + close(release) |
| + if status := <-done; status != http.StatusUnauthorized { |
| + t.Fatalf("the paused request on token A = %d, want 401", status) |
| + } |
| + auth, err := linkRegistryOf(t, fx).LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, has := auth[registry.LinkChannelName(l.id)] |
| + if tc.unlink { |
| + if has { |
| + t.Fatalf("the paused request resurrected the unlinked channel (%s)", got) |
| + } |
| + return |
| + } |
| + if got != hashToken(tokenB) { |
| + t.Fatalf("registry holds %q, want token B's hash", got) |
| + } |
| + if status, _ := linkDoor(t, fx, http.MethodGet, "/api/link", tokenB, ""); status != http.StatusOK { |
| + t.Fatalf("token B at GET /api/link = %d", status) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestPollDeliversTokenWhenSyncFailsThroughTheDoors: the poll's first sync |
| +// fails, the token is still delivered, and the first request to a link door |
| +// heals the channel before its handler runs; while the registry keeps |
| +// failing, the door answers LD-C13's 503. |
| +func TestPollDeliversTokenWhenSyncFailsThroughTheDoors(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + real := linkRegistryOf(t, fx) |
| + fault := &linkFaultRegistry{consoleRegistry: real, fail: 2} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return fault, nil } |
| + l := mintLink(t, fx, signInPaul(t, fx), "shop-home") |
| + auth, err := real.LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := auth[registry.LinkChannelName(l.id)]; has { |
| + t.Fatal("the failed first sync wrote the channel") |
| + } |
| + status, body := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, "") |
| + if status != http.StatusServiceUnavailable || linkJSONErr(body) != copyLD13 { |
| + t.Fatalf("GET /api/link while the sync fails = %d %s, want 503 LD-C13", status, body) |
| + } |
| + if status, body := linkDoor(t, fx, http.MethodGet, "/api/link", l.token, ""); status != http.StatusOK { |
| + t.Fatalf("GET /api/link once the registry answers = %d %s", status, body) |
| + } |
| + auth, err = real.LinkChannelAuth() |
| + if err != nil || auth[registry.LinkChannelName(l.id)] != hashToken(l.token) { |
| + t.Fatalf("after the door's sync LinkChannelAuth = %v %v, want the token's hash", auth, err) |
| + } |
| +} |
| + |
| +// ---- the claim invariant's link fixtures -------------------------------------- |
| + |
| +// claimMintLink mints a link for the claim case's ops account, approved by |
| +// its owner, with its channel written; it returns the token and link ID. |
| +func claimMintLink(t *testing.T, cx *claimCase) (token, id string) { |
| + t.Helper() |
| + now := time.Now() |
| + userCode, deviceCode, err := cx.st.NewLinkAuth("shop-home", "operator@home", "192.0.2.9", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.st.ApproveLinkAuth(userCode, claimFxOwner, OpsAccountID, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + res, err := cx.st.pollCLIAuth(deviceCode, now) |
| + if err != nil || res.LinkID == "" { |
| + t.Fatalf("mint the link: %+v %v", res, err) |
| + } |
| + if err := cx.srv.syncLinkChannel(context.Background(), res.LinkID); err != nil { |
| + t.Fatal(err) |
| + } |
| + return res.Token, res.LinkID |
| +} |
| + |
| +// claimLinkRefusedAPI is claimRefusedAPI with the link's own token. |
| +func claimLinkRefusedAPI(method, path, body string) func(*testing.T, *claimCase) (int, string) { |
| + return func(t *testing.T, cx *claimCase) (int, string) { |
| + status, _, out := rawReq(t, method, cx.ts.URL+cx.expand(path), cx.vars["linktoken"], cx.expand(body)) |
| + return status, out |
| + } |
| +} |
| + |
| +// claimLinkChannelIs reports "" when the case's link channel holds hash |
| +// ("" for no channel at all). |
| +func claimLinkChannelIs(t *testing.T, cx *claimCase, hash string) string { |
| + t.Helper() |
| + reg, err := cx.srv.linkReg() |
| + if err != nil { |
| + return err.Error() |
| + } |
| + auth, err := reg.LinkChannelAuth() |
| + if err != nil { |
| + return err.Error() |
| + } |
| + got, has := auth[registry.LinkChannelName(cx.vars["linkid"])] |
| + switch { |
| + case hash == "" && has: |
| + return "the link's channel is still in the registry" |
| + case hash != "" && got != hash: |
| + return "the registry does not hold the new token's hash" |
| + } |
| + return "" |
| +} |
diff --git a/internal/console/apimail.go b/internal/console/apimail.go| index 18b4ec152..99bfd78d7 100644 |
| --- a/internal/console/apimail.go |
| +++ b/internal/console/apimail.go |
| @@ -226,6 +226,9 @@ func (s *Server) mailPauseTarget(w http.ResponseWriter, r *http.Request) (*Accou |
| http.NotFound(w, r) |
| return nil, "", false |
| } |
| + if s.refuseLinkedJSON(w, r, acct, app) { |
| + return nil, "", false |
| + } |
| return acct, app, true |
| } |
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go| index d1e504df6..03b8628fa 100644 |
| --- a/internal/console/apipolicy.go |
| +++ b/internal/console/apipolicy.go |
| @@ -366,6 +366,9 @@ func (s *Server) policyAccountApp(w http.ResponseWriter, r *http.Request) (*Acco |
| http.NotFound(w, r) |
| return nil, "", AppIncarnation{}, false |
| } |
| + if s.refuseLinkedJSON(w, r, acct, app) { |
| + return nil, "", AppIncarnation{}, false |
| + } |
| return acct, app, inc, true |
| } |
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go| index 9624c826f..00d21923f 100644 |
| --- a/internal/console/appregionset.go |
| +++ b/internal/console/appregionset.go |
| @@ -167,6 +167,9 @@ func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Acco |
| return "", AppIncarnation{}, false |
| } |
| if live { |
| + if s.refuseLinkedJSON(w, r, acct, app) { |
| + return "", AppIncarnation{}, false |
| + } |
| return app, inc, true |
| } |
| trashed, err := s.store.HasTrashedAppIn(acct.ID, app) |
| @@ -468,6 +471,9 @@ func (s *Server) accountAppIncarnation(w http.ResponseWriter, r *http.Request) ( |
| s.renderMessage(w, r, http.StatusNotFound, "Not found", "No such app here.") |
| return "", "", nil, "", "", AppIncarnation{}, false |
| } |
| + if s.refuseLinkedPage(w, r, acct, app) { |
| + return "", "", nil, "", "", AppIncarnation{}, false |
| + } |
| return addr, raw, acct, role, app, inc, true |
| } |
diff --git a/internal/console/appswap.go b/internal/console/appswap.go| index fbd7a90e6..04e6f38c5 100644 |
| --- a/internal/console/appswap.go |
| +++ b/internal/console/appswap.go |
| @@ -36,6 +36,9 @@ func (s *Server) handleAppSwap(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + if s.refuseLinkedPage(w, r, acct, app) { |
| + return |
| + } |
| s.captureCopiesAdmission(r, acct, app) |
| back := func(kind, msg string) { |
| s.setFlash(w, kind, msg) |
diff --git a/internal/console/browserrestart.go b/internal/console/browserrestart.go| index 23a093c70..dd0b45395 100644 |
| --- a/internal/console/browserrestart.go |
| +++ b/internal/console/browserrestart.go |
| @@ -62,6 +62,9 @@ func (s *Server) handleBrowserRestart(w http.ResponseWriter, r *http.Request, ho |
| http.NotFound(w, r) |
| return |
| } |
| + if s.refuseLinkedPage(w, r, acct, app) { |
| + return |
| + } |
| if scoped && host == "" { |
| http.NotFound(w, r) |
| return |
diff --git a/internal/console/browserretry.go b/internal/console/browserretry.go| index 24ce45c06..eef5b7703 100644 |
| --- a/internal/console/browserretry.go |
| +++ b/internal/console/browserretry.go |
| @@ -49,6 +49,9 @@ func (s *Server) handleInstanceRetry(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + if s.refuseLinkedPage(w, r, acct, app) { |
| + return |
| + } |
| if s.cfg.Key == nil { |
| // A retry is a grant the root key signs (spec §11): a read-only |
| // console asks nothing, not even the confirmation. |
diff --git a/internal/console/browserupdates.go b/internal/console/browserupdates.go| index 49f3e686e..3100074a6 100644 |
| --- a/internal/console/browserupdates.go |
| +++ b/internal/console/browserupdates.go |
| @@ -239,6 +239,9 @@ func (s *Server) updatesFormGate(w http.ResponseWriter, r *http.Request, ctx con |
| http.NotFound(w, r) |
| return updatesFormTarget{}, false |
| } |
| + if s.refuseLinkedPage(w, r, acct, app) { |
| + return updatesFormTarget{}, false |
| + } |
| t := updatesFormTarget{addr: addr, raw: raw, role: role, app: app, host: host, acct: acct, |
| back: "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/instances/" + url.PathEscape(host)} |
| rec, etag, policy, st, msg := s.readUpdatesTarget(ctx, acct, app, host) |
diff --git a/internal/console/claim_app_identity.go b/internal/console/claim_app_identity.go| index 0d2bc9bad..fa5dc6fda 100644 |
| --- a/internal/console/claim_app_identity.go |
| +++ b/internal/console/claim_app_identity.go |
| @@ -102,7 +102,7 @@ func (s *Store) TrashClaimAppRow(accountID int64, app, appID string, at time.Tim |
| return s.changed(`UPDATE apps SET deleted_at = ?, |
| purge_for = CASE WHEN expires_at > 0 THEN ? ELSE 0 END, |
| purge_after = CASE WHEN expires_at > 0 THEN ? ELSE 0 END |
| -WHERE account_id = ? AND app = ? AND app_id = ? AND deleted_at = 0`, |
| +WHERE account_id = ? AND app = ? AND app_id = ? AND deleted_at = 0 AND linked_link_id = ''`, |
| sec, sec, sec+temporaryCooloffSeconds, accountID, app, appID) |
| } |
| @@ -140,7 +140,7 @@ WHERE account_id = ? AND app = ? AND app_id = ? AND deleted_at = ?`, |
| // retired, so PurgeClaimAppRow's deleted_at != 0 guard holds on a console |
| // that never saw the marker. |
| func (s *Store) MarkClaimAppRetired(accountID int64, app, appID string, now time.Time) error { |
| - _, err := s.db.Exec(`UPDATE apps SET deleted_at=? WHERE account_id=? AND app=? AND app_id=? AND deleted_at=0`, now.Unix(), accountID, app, appID) |
| + _, err := s.db.Exec(`UPDATE apps SET deleted_at=? WHERE account_id=? AND app=? AND app_id=? AND deleted_at=0 AND linked_link_id=''`, now.Unix(), accountID, app, appID) |
| return err |
| } |
| @@ -161,7 +161,7 @@ func (s *Store) PurgeClaimAppRow(ctx context.Context, accountID int64, app, appI |
| if current != appID { |
| return hostops.ErrIdentity |
| } |
| - res, err := tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id=? AND app=? AND app_id=? AND claim_op=? AND deleted_at!=0`, accountID, app, appID, op) |
| + res, err := tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id=? AND app=? AND app_id=? AND claim_op=? AND deleted_at!=0 AND linked_link_id=''`, accountID, app, appID, op) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 7d41e2de6..b61abe5c0 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -922,31 +922,48 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /auth/cli": claimRead("renders the device-code approval page"), |
| "route GET /auth/cli/tokens": claimRead("redirects to /settings"), |
| "route GET /auth/cli/whoami": claimRead("names the bearer's principal"), |
| - "route GET /auth/confirm": claimRead("the retired confirmation link: renders the expired message for any token"), |
| - "route GET /auth/email/link": claimNonApp("an emailed link's confirm page: sets the login-CSRF nonce cookie; spends nothing"), |
| - "route GET /auth/signin": claimNonApp("starts an OAuth flow: the auth cookie and its PKCE state"), |
| - "route GET /fleet": claimRead("operator dashboard: SQLite counts, fleet.json, box snapshots, the storage queue"), |
| - "route GET /fleet/boxes": claimRead("operator boxes view: fleet.json, box snapshots, the storage queue"), |
| - "route GET /fleet/economics": claimRead("operator economics view"), |
| - "route GET /fleet/activity": claimRead("operator activity feed; SQLite only"), |
| - "route GET /fleet/alerts/history": claimRead("operator alert incidents; SQLite only, writes nothing"), |
| - "route GET /alerts/confirm/{token}": claimRead("an alert confirm link's page: reads the token and its connector; confirming is the POST"), |
| - "route GET /alerts/unsubscribe/{token}": claimRead("an alert unsubscribe link's page: reads the token and its connector; turning off is the POST"), |
| - "route GET /alerts/snooze/{token}": claimRead("an alert snooze link's page: reads the token; snoozing is the POST"), |
| - "route GET /fleet/economics/accounts": claimRead("operator per-account economics table"), |
| - "route GET /fleet/index": claimRead("operator section index; reads nothing remote"), |
| - "route GET /fleet/metrics": claimRead("operator box metrics"), |
| - "route GET /fleet/people": claimRead("operator people and accounts list; SQLite only"), |
| - "route GET /fleet/people/{address}": claimRead("operator person page; SQLite only, writes nothing"), |
| - "route GET /fleet/protection": claimRead("operator protection page: the edge days of every fleet and the root boxes, read from the bucket; writes nothing"), |
| - "route GET /fleet/protection/data": claimRead("the operator protection page as JSON; writes nothing"), |
| - "route GET /fleet/store": claimRead("operator entitlement queue page"), |
| - "route GET /healthz": claimRead("answers ok and the build"), |
| - "route GET /invite/{token}": claimRead("shows an invitation; joining is the POST"), |
| - "route GET /settings": claimRead("personal settings: the caller's own tokens"), |
| - "route GET /static/{hash}/{file...}": claimRead("public design-system file from the binary; reads nothing"), |
| - "route GET /upgrade": claimRead("the pricing page's upgrade entry (plans 6b): redirects to the billing page of the account the caller owns, or the front door; writes nothing"), |
| - "route GET /{$}": claimRead("the front door: redirects or renders sign-in"), |
| + "route GET /api/link": claimRead("names the link and its linked apps; linkRoute's sync rewrites only the link's own channel and links row"), |
| + "route POST /api/link/rotate": claimNonApp("replaces the link's credential: its cli_tokens rows, its links row and its channel in the hub registry; names no app"), |
| + "route DELETE /api/link": claimNonApp("revokes the link: its links row, its credential and its channel; a host-claim console holds no linked apps (publish refuses there)"), |
| + "route POST /api/link/publications": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.vars["linktoken"], cx.vars["linkid"] = claimMintLink(t, cx) }, |
| + do: claimLinkRefusedAPI(http.MethodPost, "/api/link/publications", `{"app":"titogo"}`), |
| + status: http.StatusConflict, |
| + msg: copyLinkedHostClaim, |
| + }}, |
| + "route DELETE /api/link/publications/{app}": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + setup: func(t *testing.T, cx *claimCase) { cx.vars["linktoken"], cx.vars["linkid"] = claimMintLink(t, cx) }, |
| + do: claimLinkRefusedAPI(http.MethodDelete, "/api/link/publications/titogo", ""), |
| + status: http.StatusConflict, |
| + msg: copyLinkedHostClaim, |
| + }}, |
| + "route GET /auth/confirm": claimRead("the retired confirmation link: renders the expired message for any token"), |
| + "route GET /auth/email/link": claimNonApp("an emailed link's confirm page: sets the login-CSRF nonce cookie; spends nothing"), |
| + "route GET /auth/signin": claimNonApp("starts an OAuth flow: the auth cookie and its PKCE state"), |
| + "route GET /fleet": claimRead("operator dashboard: SQLite counts, fleet.json, box snapshots, the storage queue"), |
| + "route GET /fleet/boxes": claimRead("operator boxes view: fleet.json, box snapshots, the storage queue"), |
| + "route GET /fleet/economics": claimRead("operator economics view"), |
| + "route GET /fleet/activity": claimRead("operator activity feed; SQLite only"), |
| + "route GET /fleet/alerts/history": claimRead("operator alert incidents; SQLite only, writes nothing"), |
| + "route GET /alerts/confirm/{token}": claimRead("an alert confirm link's page: reads the token and its connector; confirming is the POST"), |
| + "route GET /alerts/unsubscribe/{token}": claimRead("an alert unsubscribe link's page: reads the token and its connector; turning off is the POST"), |
| + "route GET /alerts/snooze/{token}": claimRead("an alert snooze link's page: reads the token; snoozing is the POST"), |
| + "route GET /fleet/economics/accounts": claimRead("operator per-account economics table"), |
| + "route GET /fleet/index": claimRead("operator section index; reads nothing remote"), |
| + "route GET /fleet/metrics": claimRead("operator box metrics"), |
| + "route GET /fleet/people": claimRead("operator people and accounts list; SQLite only"), |
| + "route GET /fleet/people/{address}": claimRead("operator person page; SQLite only, writes nothing"), |
| + "route GET /fleet/protection": claimRead("operator protection page: the edge days of every fleet and the root boxes, read from the bucket; writes nothing"), |
| + "route GET /fleet/protection/data": claimRead("the operator protection page as JSON; writes nothing"), |
| + "route GET /fleet/store": claimRead("operator entitlement queue page"), |
| + "route GET /healthz": claimRead("answers ok and the build"), |
| + "route GET /invite/{token}": claimRead("shows an invitation; joining is the POST"), |
| + "route GET /settings": claimRead("personal settings: the caller's own tokens"), |
| + "route GET /static/{hash}/{file...}": claimRead("public design-system file from the binary; reads nothing"), |
| + "route GET /upgrade": claimRead("the pricing page's upgrade entry (plans 6b): redirects to the billing page of the account the caller owns, or the front door; writes nothing"), |
| + "route GET /{$}": claimRead("the front door: redirects or renders sign-in"), |
| // The page and the plain-text key both make the webhook signing key on |
| // first use (a keys row, as the first webhook send would): deployment |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index fabae867d..1d3ca2eb6 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -623,6 +623,36 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route POST /api/link/rotate": { |
| + setup: func(t *testing.T, cx *claimCase) { cx.vars["linktoken"], cx.vars["linkid"] = claimMintLink(t, cx) }, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + return cx.apiReplyAs(t, cx.vars["linktoken"], http.MethodPost, "/api/link/rotate", "") |
| + }, |
| + body: []string{`"token"`}, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + var out struct{ Token string } |
| + if err := json.Unmarshal([]byte(r.Body), &out); err != nil || out.Token == "" { |
| + return "no token in the answer" |
| + } |
| + if _, ok := cx.st.CLIPrincipal(cx.vars["linktoken"], time.Now()); ok { |
| + return "the old link token still resolves" |
| + } |
| + return claimLinkChannelIs(t, cx, hashToken(out.Token)) |
| + }, |
| + }, |
| + "route DELETE /api/link": { |
| + setup: func(t *testing.T, cx *claimCase) { cx.vars["linktoken"], cx.vars["linkid"] = claimMintLink(t, cx) }, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + return cx.apiReplyAs(t, cx.vars["linktoken"], http.MethodDelete, "/api/link", "") |
| + }, |
| + status: http.StatusNoContent, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + if _, ok := cx.st.CLIPrincipal(cx.vars["linktoken"], time.Now()); ok { |
| + return "the link token still resolves after unlink" |
| + } |
| + return claimLinkChannelIs(t, cx, "") |
| + }, |
| + }, |
| "route POST /auth/cli/revoke": { |
| setup: func(t *testing.T, cx *claimCase) { |
| // A second terminal of the owner's: the request revokes ITSELF. |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index f07a4431f..426b922d6 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -384,6 +384,13 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /api/cli/system/status": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.systemRelease(t, "canary", "66587fa") }, |
| "/api/cli/system/status", `"pointers"`, `"version":"66587fa"`), |
| "route GET /auth/cli/whoami": claimAPIRead(nil, "/auth/cli/whoami", `"address":"`+claimFxOwner+`"`), |
| + "route GET /api/link": { |
| + setup: func(t *testing.T, cx *claimCase) { cx.vars["linktoken"], cx.vars["linkid"] = claimMintLink(t, cx) }, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + return cx.apiReplyAs(t, cx.vars["linktoken"], http.MethodGet, "/api/link", "") |
| + }, |
| + body: []string{`"link_id":"<linkid>"`, `"name":"shop-home"`}, |
| + }, |
| // ---- POSTs that only read ---- |
| "route POST /a/{sqid}/apps/new/region": { |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 9d00e43f9..bb1da2a46 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -126,6 +126,8 @@ var claimUnsupported = map[string]string{ |
| placementsHostClaimMsg: "a regional claim is written by SetClaimPlacements, which no host-claim operation gates (#447 plan note 9); " + |
| "the placements PUT refuses after its caller gates and before it reads or writes anything", |
| errManagedHostClaim.Error(): "managed enrolment refuses host-claim consoles before reading reservations or granting authority; claim-bound reservation transactions remain unavailable", |
| + copyLinkedHostClaim: "a linked app is an apps row that no claim operation gates (linked deployments slice 1); " + |
| + "the publish and unpublish doors refuse after linkRoute's gate and before they read or write any app", |
| claimFleetDrainUnsupportedMsg: "a drain relabels the box's instance records (managed fleets 1b, rule 5), which no claim operation gates; " + |
| "the drain door refuses after its caller gates and the box lookup, before it reads the fleet's records or writes anything", |
| seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " + |
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go| index 33822745e..ff5656e3d 100644 |
| --- a/internal/console/demo_claim_transfer.go |
| +++ b/internal/console/demo_claim_transfer.go |
| @@ -934,7 +934,7 @@ func (s *Server) finishDemoClaimAbort(ctx context.Context, op claimOp) error { |
| return err |
| } |
| defer tx.Rollback() |
| - if _, err = tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id=? AND app=? AND lifetime=? AND demo_claim_op=?`, op.Target.AccountID, op.Target.App, op.Target.Lifetime, op.ID); err != nil { |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id=? AND app=? AND lifetime=? AND demo_claim_op=? AND linked_link_id=''`, op.Target.AccountID, op.Target.App, op.Target.Lifetime, op.ID); err != nil { |
| return err |
| } |
| if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_ops SET phase='aborted' WHERE id=? AND phase='aborting'`, op.ID); err != nil { |
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go| index eb761fb03..b4c8ced1f 100644 |
| --- a/internal/console/demo_expiry.go |
| +++ b/internal/console/demo_expiry.go |
| @@ -360,7 +360,7 @@ func (s *Server) finishDemoPurge(ctx context.Context, d DemoRow, now time.Time) |
| args []any |
| }{ |
| {`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,?) ON CONFLICT(host) DO NOTHING`, []any{d.Host, d.ID, now.Unix()}}, |
| - {`DELETE FROM apps WHERE account_id=? AND app=? AND demo_id=? AND deleted_at!=0`, []any{d.AccountID, d.App, d.ID}}, |
| + {`DELETE FROM apps WHERE account_id=? AND app=? AND demo_id=? AND deleted_at!=0 AND linked_link_id=''`, []any{d.AccountID, d.App, d.ID}}, |
| {`UPDATE demo_apps SET state='retired',purged_at=? WHERE demo_id=?`, []any{now.Unix(), d.ID}}, |
| {`DELETE FROM demo_retirements WHERE demo_id=?`, []any{d.ID}}, |
| } { |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 93e41b972..0919d80a8 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -174,7 +174,8 @@ func (s *Server) expireOne(ctx context.Context, r AppRow, now time.Time, ev evid |
| return |
| } |
| // A keep that ran after the listing set expires_at = 0, which fails > 0. |
| - if life == nil || life.DemoID != "" || life.ExpiresAt <= 0 || life.ExpiresAt > now.Unix() || life.Trashed() || life.Restoring { |
| + // A linked app (spec §6.0) leaves only by unpublish or unlink. |
| + if life == nil || life.DemoID != "" || life.LinkID != "" || life.ExpiresAt <= 0 || life.ExpiresAt > now.Unix() || life.Trashed() || life.Restoring { |
| return |
| } |
| acct := &Account{ID: r.AccountID, Sqid: r.Sqid} |
| @@ -221,7 +222,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| jobFailed(ctx, fmt.Errorf("expiry pass: read %s/%s: %w", r.Sqid, r.App, err)) |
| return |
| } |
| - if life == nil || life.DemoID != "" || !life.Trashed() || life.PurgeAfter <= 0 || life.PurgeAfter > now.Unix() || life.PurgeFor <= 0 { |
| + if life == nil || life.DemoID != "" || life.LinkID != "" || !life.Trashed() || life.PurgeAfter <= 0 || life.PurgeAfter > now.Unix() || life.PurgeFor <= 0 { |
| return // restored, purged, or never due: settling answered it |
| } |
| acct := &Account{ID: r.AccountID, Sqid: r.Sqid} |
diff --git a/internal/console/expirypass_test.go b/internal/console/expirypass_test.go| index ed5a96109..1a6bf9eac 100644 |
| --- a/internal/console/expirypass_test.go |
| +++ b/internal/console/expirypass_test.go |
| @@ -240,7 +240,7 @@ func TestExpiryPassAgainstTheWrongBucket(t *testing.T) { |
| release.TrashApp(ctx, wrong, fx.sqid, "someone-else", "paul@keymail.dev", now) |
| } |
| fx.srv.cfg.Releases = wrong |
| - materializeQuietly(ctx, wrong, fx.st) |
| + materializeQuietly(ctx, wrong, fx.st, nil) |
| for i := 0; i < 3; i++ { |
| fx.srv.expiryPass(ctx, now.Add(time.Duration(i)*5*time.Minute)) |
| } |
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go| index 5134c10fd..dfeedae6d 100644 |
| --- a/internal/console/lifetimes_purge.go |
| +++ b/internal/console/lifetimes_purge.go |
| @@ -218,8 +218,8 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| jobFailed(ctx, fmt.Errorf("trash sweep: %s/%s: %w", a.Account, a.App, err)) |
| return |
| } |
| - if life != nil && life.DemoID != "" { |
| - return |
| + if life != nil && (life.DemoID != "" || life.LinkID != "") { |
| + return // a linked app leaves only by unpublish or unlink |
| } |
| if life != nil && life.ControlPlane { |
| s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s is marked as the control plane; not purging it", a.Account, a.App) |
diff --git a/internal/console/lifetimes_store.go b/internal/console/lifetimes_store.go| index 6481c52ae..55b48024c 100644 |
| --- a/internal/console/lifetimes_store.go |
| +++ b/internal/console/lifetimes_store.go |
| @@ -439,6 +439,10 @@ type newAppRow struct { |
| // UnclaimedEverywhere inserts only when no account holds the app name at |
| // all (the ops backfill's rule). |
| UnclaimedEverywhere bool |
| + // LinkID marks the row a linked app (linked deployments spec §6.0): a |
| + // publication of the link with this ID, served from its home |
| + // deployment. "" for every other app. |
| + LinkID string |
| } |
| // insertAppRow is the one place an apps row is inserted, so every row gets a |
| @@ -455,11 +459,11 @@ func insertAppRow(ex appExecer, r newAppRow) (bool, error) { |
| if r.UnclaimedEverywhere { |
| unclaimed = 1 |
| } |
| - res, err := ex.Exec(`INSERT INTO apps (app, account_id, created_by, created_at, region, region_source, expires_at, lifetime, demo_claim_op) |
| -SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? |
| + res, err := ex.Exec(`INSERT INTO apps (app, account_id, created_by, created_at, region, region_source, expires_at, lifetime, demo_claim_op, linked_link_id) |
| +SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? |
| WHERE ? = 0 OR NOT EXISTS (SELECT 1 FROM apps WHERE app = ?) |
| ON CONFLICT(account_id, app) DO NOTHING`, |
| - r.App, r.AccountID, r.CreatedBy, r.CreatedAt, r.Region, r.RegionSource, r.ExpiresAt, id, r.DemoClaimOp, unclaimed, r.App) |
| + r.App, r.AccountID, r.CreatedBy, r.CreatedAt, r.Region, r.RegionSource, r.ExpiresAt, id, r.DemoClaimOp, r.LinkID, unclaimed, r.App) |
| if err != nil { |
| return false, err |
| } |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| new file mode 100644 |
| index 000000000..bad804a07 |
| --- /dev/null |
| +++ b/internal/console/linkedpolicy.go |
| @@ -0,0 +1,330 @@ |
| +package console |
| + |
| +// The linked-app guard (linked deployments spec §6.0): one policy for every |
| +// app door, browser and CLI alike. A linked app is an ordinary apps row |
| +// marked with its link, served from its home deployment; Carloku keeps only |
| +// the reads the spec names (analytics, protection, usage and the app's |
| +// overview), and every door that acts on the app's code, config, |
| +// instances, data, identity or lifetime refuses it, saying it is managed at |
| +// home. Custom domains are refused too in slice 1, with their own sentence. |
| +// |
| +// The table is keyed by route pattern, exactly as routeDecls declares it. |
| +// TestLinkedPolicyCoversEveryAppRoute fails on any {app} route the table |
| +// does not classify, and on any entry that is no longer a declared route; |
| +// a pattern the table does not know is refused (fail closed). |
| + |
| +import ( |
| + "log" |
| + "net/http" |
| +) |
| + |
| +// linkedPolicy is what an app door does for a linked app. |
| +type linkedPolicy uint8 |
| + |
| +const ( |
| + // linkedRefuse: the door acts on what lives at home (code, config, |
| + // instances, data, identity, lifetime) and refuses with LD-C11. The |
| + // zero value, so an unclassified pattern refuses. |
| + linkedRefuse linkedPolicy = iota |
| + // linkedAllow: a read the spec keeps on Carloku for a linked app. |
| + linkedAllow |
| + // linkedRefuseDomains: a custom-domain door, refused in slice 1 with |
| + // LD-C12. |
| + linkedRefuseDomains |
| +) |
| + |
| +// linkedAppPolicy is the policy of the app door whose mux pattern is |
| +// pattern. A pattern the table does not hold is linkedRefuse. |
| +func linkedAppPolicy(pattern string) linkedPolicy { |
| + return linkedPolicies[pattern] // the zero value is linkedRefuse |
| +} |
| + |
| +// linkedPolicies classifies every route declaration whose pattern names an |
| +// {app}. Only linkedAllow and linkedRefuseDomains need an entry to take |
| +// effect; the linkedRefuse entries are written out so the coverage test can |
| +// 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, |
| + "GET /api/cli/apps/{account}/{app}/analytics": linkedAllow, |
| + "GET /api/cli/apps/{account}/{app}/geo": linkedAllow, |
| + |
| + // Custom domains, slice 1: refused with their own sentence (LD-C12). |
| + "GET /a/{sqid}/apps/{app}/domains/buy": linkedRefuseDomains, |
| + "POST /a/{sqid}/apps/{app}/domains/check": linkedRefuseDomains, |
| + "POST /a/{sqid}/apps/{app}/domains/buy": linkedRefuseDomains, |
| + "GET /a/{sqid}/apps/{app}/domains/purchases/{id}": linkedRefuseDomains, |
| + "GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status": linkedRefuseDomains, |
| + "POST /a/{sqid}/apps/{app}/domains/attach": linkedRefuseDomains, |
| + "POST /a/{sqid}/apps/{app}/domains/detach": linkedRefuseDomains, |
| + "GET /api/cli/apps/{account}/{app}/domains": linkedRefuseDomains, |
| + "GET /api/cli/apps/{account}/{app}/domains/{host}": linkedRefuseDomains, |
| + "GET /api/cli/apps/{account}/{app}/domains/{host}/placements": linkedRefuseDomains, |
| + "PUT /api/cli/apps/{account}/{app}/domains/{host}/placements": linkedRefuseDomains, |
| + "POST /api/cli/apps/{account}/{app}/domains": linkedRefuseDomains, |
| + "DELETE /api/cli/apps/{account}/{app}/domains/{host}": linkedRefuseDomains, |
| + "PUT /api/cli/apps/{account}/{app}/domains/{host}/paths": linkedRefuseDomains, |
| + |
| + // The browser's app doors that act on what lives at home. |
| + "GET /a/{sqid}/apps/{app}/source": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/releases": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/deployments": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/account-review": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/instances": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/instances/{host}": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/restart": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/instances/{host}/restart": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/instances/{host}/retry": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/instances/{host}/updates": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/instances/{host}/updates/install": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/logs": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/logs/data": linkedRefuse, |
| + "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, |
| + "GET /a/{sqid}/apps/{app}/settings/index": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/settings/environments": linkedRefuse, |
| + "GET /a/{sqid}/apps/{app}/pipeline": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/pipeline": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/promote": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/rollback": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/production": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/fasttrack": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/pending/{id}/confirm": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/pending/{id}/reject": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/canary": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/canary/retire": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/place": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/gate": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/ratelimit": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/swap": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/rename": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/region": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/keep": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/extend": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/delete": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/move": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/control-plane/clear": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/control-plane/set": linkedRefuse, |
| + "POST /a/{sqid}/apps/{app}/store/destroy": linkedRefuse, |
| + |
| + // The CLI's app doors that act on what lives at home. |
| + "POST /api/cli/apps/{account}/{app}/ttl": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/keep": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/source": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/region": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/region": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/channels": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/promote": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/rollback": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/channels/resign": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/releases/{version}/authorize": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/releases": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/restart": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/restart/scope": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/schedules": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/schedules": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/schedules/{name}/delete": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/schedules/{name}/run": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/retention": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/retention": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/version-target": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/version-target": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/tags": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/tags/{version}": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/releases": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/pipeline": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/pipeline": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/pending": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/delete": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/restore": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/ledgers": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/ledgers/publish": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/ledgers/{ledger}/head": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/append": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/blobs": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/instances-manifest": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/regions": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/regions/guess": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/channel": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/updates": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/instances/{host}/updates": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/updates/install": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/updates": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/logs": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/edge-refs/{code}": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/errors": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/availability": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/telemetry": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/telemetry": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}": linkedRefuse, |
| + "PATCH /api/cli/apps/{account}/{app}/instances/{host}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/assets/purge": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/assets": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/gate-pass": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/move": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/rate-limit": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/cut": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}/move": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/move/offline": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/stage": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/seal": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/flip": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/open": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/finish": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/offline/abort": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/instances/{host}": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/instances/{host}/import": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/import/stopped": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/import/commit": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/import/abort": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/runs": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/runs": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/cancel": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/expire": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/ack": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/instances/{host}/interactive": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/retry": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}/{span}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/db/{host}/reads": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instance-token": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/door-keys": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/door-keys": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/door-keys/{id}/revoke": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/sidecars-manifest": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/sidecars": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/sidecars": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/sidecars/{name}": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/sidecars/{name}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/sidecars/{name}/wake": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/features": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/features": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/config": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/config": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/config/sync": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/routes": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/place": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/build-probe": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/copies": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/swap": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/interactive": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/policy": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/policy": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/store": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/provision": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/grant": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/rotate": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/rotate/finish": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/store/scan": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/grant": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/revoke": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/sweep": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/enforce": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/callback-key/rotate": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/store/scan/object": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/store/scan/object": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/pdf/{route...}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/relay": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/relay": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/relay/disable": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/relay/adopted": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/environments/{name}/adopt": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/environments/{name}/release": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/environments/fork": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/instances/{host}/move/resolve": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/email": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/email/events": linkedRefuse, |
| + "GET /api/cli/apps/{account}/{app}/email/events/push": linkedRefuse, |
| + "PUT /api/cli/apps/{account}/{app}/email/events/push": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/email/events/push": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/enable": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/rotate": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/credentials": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/email/credentials/{name}": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/pause": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/domains": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/email/domains/{domain}/verify": linkedRefuse, |
| + "DELETE /api/cli/apps/{account}/{app}/email/domains/{domain}": linkedRefuse, |
| + |
| + // The box doors: a linked app has no instance records for them to name. |
| + "POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": linkedRefuse, |
| + "POST /api/fleet/replicas/{account}/{app}/{host}/release": linkedRefuse, |
| +} |
| + |
| +// refuseLinkedJSON answers an API door's linked refusal, if any, and |
| +// reports whether it did: linkedAppRefusal for the resolvers that do not go |
| +// through apiAccountAppSaying. |
| +func (s *Server) refuseLinkedJSON(w http.ResponseWriter, r *http.Request, acct *Account, app string) bool { |
| + ref := s.linkedAppRefusal(r, acct, app) |
| + if ref == nil { |
| + return false |
| + } |
| + jsonError(w, ref.Status, ref.Msg) |
| + return true |
| +} |
| + |
| +// refuseLinkedPage is refuseLinkedJSON for a browser door: the refusal as |
| +// accountApp renders it. |
| +func (s *Server) refuseLinkedPage(w http.ResponseWriter, r *http.Request, acct *Account, app string) bool { |
| + ref := s.linkedAppRefusal(r, acct, app) |
| + if ref == nil { |
| + return false |
| + } |
| + s.renderMessage(w, r, ref.Status, "Refused", ref.Msg) |
| + return true |
| +} |
| + |
| +// linkedAppRefusal is the guard every app door's resolver consults |
| +// (apiAccountAppSaying, accountApp and the other app resolvers): nil when the |
| +// door may go ahead, else a 409 with the deck's sentence when app is a |
| +// linked app and the matched route's policy refuses it. Consulted for every |
| +// method, reads included. The policy is read first, so an allowed door |
| +// costs no lookup. A store error refuses (503): the guard fails closed. |
| +func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *doorRefusal { |
| + pol := linkedAppPolicy(r.Pattern) |
| + if pol == linkedAllow { |
| + return nil |
| + } |
| + linkID, err := s.store.appLinkID(acct.ID, app) |
| + if err != nil { |
| + log.Printf("console: linked check %s/%s: %v", acct.Sqid, app, err) |
| + return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copyLinkedCheckFailed} |
| + } |
| + if linkID == "" { |
| + return nil |
| + } |
| + if pol == linkedRefuseDomains { |
| + return &doorRefusal{Status: http.StatusConflict, Msg: copyLD12} |
| + } |
| + home := linkID |
| + if l, err := s.store.LinkByID(linkID); err != nil { |
| + log.Printf("console: linked check %s/%s: link %s: %v", acct.Sqid, app, linkID, err) |
| + } else if l != nil && l.Name != "" { |
| + home = l.Name |
| + } |
| + return &doorRefusal{Status: http.StatusConflict, Msg: linkCopy(copyLD11, "app", app, "home", home)} |
| +} |
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go| index d05e140e6..8b090cd12 100644 |
| --- a/internal/console/links_auth_test.go |
| +++ b/internal/console/links_auth_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| "github.com/carlosframework/platform/internal/tunnelclient" |
| ) |
| @@ -692,12 +693,19 @@ func TestLinkTokenRefusedEverywhereElse(t *testing.T) { |
| t.Run(w.name, func(t *testing.T) { |
| none, _, _ := linkWalk(t, w, nil, nil) |
| fabricated, _, _ := linkWalk(t, w, mintWalkFabricated, nil) |
| - link, st, token := linkWalk(t, w, mintWalkLink, nil) |
| + // The link's own doors are the one place the link token is a |
| + // credential (TestLinkDoorsRefuseEveryOtherBearer is their |
| + // reverse half); its walk skips them, as their rotate and |
| + // unlink would end the token half way through. |
| + link, st, token := linkWalk(t, w, mintWalkLink, linkDoorPatterns()) |
| // The person control skips the logout door, which would end |
| // its token half way through the walk. |
| person, _, _ := linkWalk(t, w, mintWalkPerson, map[string]bool{"POST /auth/cli/revoke": true}) |
| for pattern, want := range none { |
| walked[pattern] = true |
| + if linkDoorPatterns()[pattern] { |
| + continue |
| + } |
| if want == -1 { |
| t.Errorf("%s: no-bearer request failed in transport", pattern) |
| } |
| @@ -733,8 +741,106 @@ func TestLinkTokenRefusedEverywhereElse(t *testing.T) { |
| if reached < 50 { |
| t.Errorf("a person's token reached %d handlers the no-bearer walk did not, want at least 50; the walk proves nothing", reached) |
| } |
| - // The reverse half, every kindLink door refusing person, app and |
| - // service tokens, arrives with the kindLink doors (Task 5). |
| + // The reverse half: TestLinkDoorsRefuseEveryOtherBearer. |
| +} |
| + |
| +// linkDoorPatterns is every kindLink declaration's pattern. |
| +func linkDoorPatterns() map[string]bool { |
| + out := map[string]bool{} |
| + for _, d := range routeDecls { |
| + if d.Kind == kindLink { |
| + out[d.Pattern] = true |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestLinkDoorsRefuseEveryOtherBearer is the walk's reverse half: at every |
| +// kindLink door, no bearer, a bearer never minted, a person's token, a |
| +// legacy app token and a service token of every role all get exactly the |
| +// 401 cliNotSignedIn gives, while the link token is admitted. |
| +func TestLinkDoorsRefuseEveryOtherBearer(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + acct, err := fx.st.AccountBySqid(fx.sqid) |
| + if err != nil || acct == nil { |
| + t.Fatal(acct, err) |
| + } |
| + legacy, err := fx.st.NewAppToken(acct.ID, "kass", "paul@keymail.dev", "walk", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bearers := map[string]string{ |
| + "none": "", |
| + "fabricated": mintWalkFabricated(t, fx.st), |
| + "person": mintWalkPerson(t, fx.st), |
| + "legacy app": legacy, |
| + } |
| + // A service credential of every role, app-bound and (where the role |
| + // may be) account-wide; a role whose credential needs more than a role |
| + // (a deploy's rungs, a team's scope) is minted with it. |
| + for _, role := range svcrole.All() { |
| + for _, app := range []string{"kass", ""} { |
| + var rungs []string |
| + var commands [][]string |
| + scope := "" |
| + switch role { |
| + case svcrole.Deploy: |
| + rungs = []string{"edge"} |
| + case svcrole.Run: |
| + commands = [][]string{{"migrate"}} |
| + case svcrole.Team: |
| + if app == "" { |
| + continue |
| + } |
| + scope = "alta" |
| + } |
| + raw, err := fx.st.NewServicePrincipalWithScopeContext(context.Background(), acct.ID, "walk-"+string(role)+"-"+app, app, role, rungs, commands, scope, "paul@keymail.dev", time.Now()) |
| + if err != nil { |
| + t.Logf("no %s credential bound to %q: %v", role, app, err) |
| + continue |
| + } |
| + bearers["service "+string(role)+" "+app] = raw |
| + } |
| + } |
| + if len(bearers) < 4+len(svcrole.All()) { |
| + t.Fatalf("minted %d bearers, too few to walk", len(bearers)) |
| + } |
| + _, _, want := rawReq(t, http.MethodGet, fx.ts.URL+"/api/link", "", "") |
| + if !strings.Contains(want, "not signed in") { |
| + t.Fatalf("the no-bearer answer is %q, want cliNotSignedIn's", want) |
| + } |
| + doors := linkDoorPatterns() |
| + if len(doors) != 5 { |
| + t.Fatalf("found %d kindLink doors, want 5", len(doors)) |
| + } |
| + for pattern := range doors { |
| + method, path := linkWalkRequest(t, pattern) |
| + body := "" |
| + if method == http.MethodPost { |
| + body = `{"app":"shop"}` |
| + } |
| + for who, tok := range bearers { |
| + status, _, got := rawReq(t, method, fx.ts.URL+path, tok, body) |
| + if status != http.StatusUnauthorized || got != want { |
| + t.Errorf("%s with %s = %d %q, want 401 %q", pattern, who, status, got, want) |
| + } |
| + } |
| + } |
| + // None of them changed anything a link door would. |
| + if apps, err := fx.st.AppLivesIn(acct.ID); err != nil { |
| + t.Fatal(err) |
| + } else { |
| + for _, a := range apps { |
| + if a.LinkID != "" { |
| + t.Fatalf("a refused bearer published %s", a.App) |
| + } |
| + } |
| + } |
| + // The positive control: the link token is admitted at a read door. |
| + poll := linkCeremony(t, fx, signInPaul(t, fx), "shop-home", fx.sqid) |
| + if status, _, got := rawReq(t, http.MethodGet, fx.ts.URL+"/api/link", str(t, poll, "token"), ""); status != http.StatusOK { |
| + t.Fatalf("the link token at GET /api/link = %d %s", status, got) |
| + } |
| } |
| // TestLinkMintRechecksTheRole: an approver who loses the create role between |
diff --git a/internal/console/links_copy.go b/internal/console/links_copy.go| index 2e44c3f76..2941e63bb 100644 |
| --- a/internal/console/links_copy.go |
| +++ b/internal/console/links_copy.go |
| @@ -24,6 +24,15 @@ const ( |
| copyLD08 = "If you didn't just ask a deployment to link, press That wasn't me." |
| // LD-C09: the approved page. |
| copyLD09 = "Linked. {home} can now publish apps under {account}. Go back to it: it carries on by itself." |
| + // LD-C10: POST /api/link/publications 409, the name is taken. |
| + copyLD10 = "An app called {app} already exists in {account}. Publish under another name with --name." |
| + // LD-C11: linkedAppRefusal's 409 on every refused app door, browser |
| + // and CLI (spec §6.0). |
| + copyLD11 = "{app} is managed by its home deployment, {home}. Make this change there. To take it off Carloku, run carlos link unpublish {app} on {home}." |
| + // LD-C12: the refused domains doors for a linked app (slice 1). |
| + copyLD12 = "Custom domains can't be attached to an app served from a home deployment yet. Its Carloku address keeps working." |
| + // LD-C13: a link door's 503 when the link sync fails. |
| + copyLD13 = "Carloku couldn't update this link just now. Try again in a minute." |
| ) |
| // linkCopy fills a deck string's {placeholders} from kv pairs (key, value, |
| @@ -62,4 +71,18 @@ const ( |
| // code expired or was already used, in place of the person login's |
| // "Run carlos auth login again". |
| copyLinkApproveExpired = "That code has expired or was already used. Run carlos link create again for a fresh one." |
| + // The 503 an app door answers when the linked-app guard could not read |
| + // whether the app is linked (linkedAppRefusal fails closed). |
| + copyLinkedCheckFailed = "Could not check this app just now. Try again in a minute." |
| + // The 429 from POST /api/link/publications when the link has spent its |
| + // daily create budget; read by the home CLI. |
| + copyLinkPublishRateLimited = "this link has published as many apps as it may today. Try again tomorrow" |
| + // The 503 from POST /api/link/publications on a console with no apps |
| + // domain (CARLOS_APPS_DOMAIN), so no public address to give; read by |
| + // the home CLI. |
| + copyLinkNoAppsDomain = "this console has no apps domain, so it cannot publish apps" |
| + // The 409 from the publish and unpublish doors on a console with host |
| + // claims on, where no claim operation gates a linked app's row; read by |
| + // the home CLI. |
| + copyLinkedHostClaim = "this console cannot publish linked apps while host claims are on" |
| ) |
diff --git a/internal/console/links_store.go b/internal/console/links_store.go| index c350cefca..5f6862f37 100644 |
| --- a/internal/console/links_store.go |
| +++ b/internal/console/links_store.go |
| @@ -14,12 +14,16 @@ package console |
| // the one writer of the channel and reads nothing but this row. |
| import ( |
| + "context" |
| "crypto/rand" |
| "database/sql" |
| "encoding/hex" |
| "errors" |
| "fmt" |
| + "strings" |
| "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| // Link is one linked deployment as the serving console records it. Name is |
| @@ -62,6 +66,13 @@ func (s *Store) migrateLinks() error { |
| return err |
| } |
| } |
| + // A linked app's row names its link (spec §6.0); '' for every other |
| + // app. An ALTER after migrateAppsKey (Store.migrate calls this after |
| + // it), so the rebuild never has to carry the column. |
| + if _, err := s.db.Exec(`ALTER TABLE apps ADD COLUMN linked_link_id TEXT NOT NULL DEFAULT ''`); err != nil && |
| + !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| return nil |
| } |
| @@ -341,3 +352,127 @@ FROM links l JOIN accounts a ON a.id = l.account_id |
| WHERE l.id = ? AND a.deleted_at = 0`, linkID).Scan(&acct, &revoked, ¤t) |
| return err == nil && revoked == 0 && acct == accountID && current == hash |
| } |
| + |
| +// ---- linked apps (spec §6.0) ---------------------------------------------- |
| + |
| +// linkedApp is one linked app: a live apps row of the link's account whose |
| +// linked_link_id names the link. |
| +type linkedApp struct { |
| + AccountID int64 |
| + App string |
| + CreatedAt time.Time |
| +} |
| + |
| +// CreateLinkedApp inserts app as a linked app of linkID in accountID, through |
| +// insertAppRow (a fresh lifetime). created is false when the account already |
| +// holds the name, live or trashed, linked or not. |
| +func (s *Store) CreateLinkedApp(accountID int64, app, createdBy, linkID string, now time.Time) (created bool, err error) { |
| + if !registry.ValidLinkID(linkID) { |
| + return false, fmt.Errorf("console: linked app %s: invalid link id %q", app, linkID) |
| + } |
| + return insertAppRow(s.db, newAppRow{AccountID: accountID, App: app, CreatedBy: createdBy, CreatedAt: now.Unix(), LinkID: linkID}) |
| +} |
| + |
| +// appLinkID reads the link app belongs to in accountID: "" for an ordinary |
| +// app and for no row at all. |
| +func (s *Store) appLinkID(accountID int64, app string) (string, error) { |
| + var id string |
| + err := s.db.QueryRow(`SELECT linked_link_id FROM apps WHERE account_id = ? AND app = ?`, accountID, app).Scan(&id) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", nil |
| + } |
| + return id, err |
| +} |
| + |
| +// 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) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []linkedApp |
| + for rows.Next() { |
| + var a linkedApp |
| + var created int64 |
| + if err := rows.Scan(&a.AccountID, &a.App, &created); err != nil { |
| + return nil, err |
| + } |
| + a.CreatedAt = time.Unix(created, 0).UTC() |
| + out = append(out, a) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// deleteLinkedAppRow deletes app's row in accountID only while it is a |
| +// linked app of linkID, with everything keyed by the name that PurgeAppRow |
| +// also forgets (forgetAppTx), so a later app of the name inherits nothing. |
| +// It is the one statement that deletes a linked app's row: unpublish and |
| +// unlink reach it, and every other app delete and trash skips linked rows |
| +// (TestEveryAppDeleteRespectsLinked). A row that is not there, or is not |
| +// this link's, is not an error: deleted is false. |
| +func (s *Store) deleteLinkedAppRow(ctx context.Context, accountID int64, app, linkID string) (deleted bool, err error) { |
| + if !registry.ValidLinkID(linkID) { |
| + return false, fmt.Errorf("console: unpublish %s: invalid link id %q", app, linkID) |
| + } |
| + defer s.lockAppNames(appNameKey{accountID, app})() |
| + err = s.withAutoAppSQL(ctx, accountID, app, "sql.DeleteLinkedApp", func(st *Store) error { |
| + tx, err := st.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM app_stars WHERE account_id = ? AND lifetime IN (SELECT lifetime FROM apps WHERE account_id = ? AND app = ? AND linked_link_id = ?)`, |
| + accountID, accountID, app, linkID); err != nil { |
| + return err |
| + } |
| + res, err := tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id = ? AND app = ? AND linked_link_id = ?`, accountID, app, linkID) |
| + if err != nil { |
| + return err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + if err := forgetAppTx(ctx, tx, accountID, app); err != nil { |
| + return err |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return err |
| + } |
| + deleted = n > 0 |
| + return nil |
| + }) |
| + if err != nil { |
| + return false, err |
| + } |
| + if deleted { |
| + s.appNameFreed(accountID, app) |
| + } |
| + return deleted, nil |
| +} |
| + |
| +// revokedLinksHoldingApps lists the revoked links whose revocation the hub |
| +// registry already holds (revoke_synced) but which still have linked app |
| +// rows: an unlink whose last step did not run (a failed sync, a reaped |
| +// account). linkSyncPass finishes each one. |
| +func (s *Store) revokedLinksHoldingApps() ([]string, error) { |
| + rows, err := s.db.Query(`SELECT l.id FROM links l WHERE l.revoked_at != 0 AND l.revoke_synced = 1 |
| +AND EXISTS (SELECT 1 FROM apps p WHERE p.linked_link_id = l.id) ORDER BY l.id`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var id string |
| + if err := rows.Scan(&id); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, id) |
| + } |
| + return out, rows.Err() |
| +} |
diff --git a/internal/console/links_sync.go b/internal/console/links_sync.go| index ed82b417d..9cb339b1f 100644 |
| --- a/internal/console/links_sync.go |
| +++ b/internal/console/links_sync.go |
| @@ -150,8 +150,9 @@ func (s *Server) linkSyncLoop(ctx context.Context) { |
| } |
| } |
| -// linkSyncPass syncs every link the registry is behind on. One link's |
| -// failure does not stop the others; the pass returns them all joined. |
| +// linkSyncPass syncs every link the registry is behind on, then finishes |
| +// every unlink whose apps rows outlived it. One link's failure does not |
| +// stop the others; the pass returns them all joined. |
| func (s *Server) linkSyncPass(ctx context.Context) error { |
| ids, err := s.store.linksNeedingSync() |
| if err != nil { |
| @@ -163,5 +164,17 @@ func (s *Server) linkSyncPass(ctx context.Context) error { |
| errs = append(errs, err) |
| } |
| } |
| + // An unlink whose last step did not run (its sync failed, or the |
| + // account was reaped): the registry holds the revocation, so the |
| + // link's apps rows go now. |
| + revoked, err := s.store.revokedLinksHoldingApps() |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("revoked links holding apps: %w", err)) |
| + } |
| + for _, id := range revoked { |
| + if err := s.dropLinkedApps(ctx, id); err != nil { |
| + errs = append(errs, fmt.Errorf("link %s: finish unlink: %w", id, err)) |
| + } |
| + } |
| return errors.Join(errs...) |
| } |
diff --git a/internal/console/materialize.go b/internal/console/materialize.go| index 1e9dca1fc..0068949e9 100644 |
| --- a/internal/console/materialize.go |
| +++ b/internal/console/materialize.go |
| @@ -39,6 +39,16 @@ import ( |
| // unreachable bucket must never be what stops an operator removing a |
| // membership, which is the emergency this whole verb family exists for. |
| func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int, error) { |
| + return materializeAccounts(ctx, s, st, nil) |
| +} |
| + |
| +// materializeAccounts is MaterializeAccounts with unlinkFirst, when not nil, |
| +// run for an account before it is reaped: its links are unlinked (the |
| +// console's Server.unlinkAccountLinks), so its linked apps leave by the |
| +// unlink path. Without it (the box-side member verb) ReapAccount still |
| +// revokes the links' rows, and the running console's linkSyncPass finishes |
| +// them. |
| +func materializeAccounts(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64)) (int, error) { |
| if s == nil { |
| return 0, nil |
| } |
| @@ -117,6 +127,9 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int, |
| // deletion performed anywhere — another box, `carlos accounts |
| // delete`, an operator with only bucket access — become real here |
| // without hand-run SQL (the Kass gap). |
| + if unlinkFirst != nil { |
| + unlinkFirst(ctx, a.ID) |
| + } |
| if err := st.ReapAccount(a.ID, time.Now()); err != nil { |
| log.Printf("console: reap deleted account %s: %v", sqid, err) |
| } else { |
| @@ -360,6 +373,11 @@ func MaterializeApps(ctx context.Context, s release.Store, st *Store, claimEnabl |
| } |
| } |
| for _, r := range rows { |
| + if r.LinkID != "" { |
| + // A linked app (spec §6.0) leaves only by unpublish or unlink: |
| + // no marker or absence in the bucket speaks for it. |
| + continue |
| + } |
| if len(claimEnabled) > 0 && claimEnabled[0] { |
| handled, claimErr := materializeClaimApp(ctx, s, st, r.AccountID, r.Sqid, r.App, time.Now()) |
| if claimErr != nil { |
| @@ -443,8 +461,8 @@ func MaterializeApps(ctx context.Context, s release.Store, st *Store, claimEnabl |
| // up if we can, log and carry on if we cannot. Separated from |
| // MaterializeAccounts so the failure policy lives in ONE place rather than |
| // being re-decided by the server, the member verb and whatever comes next. |
| -func materializeQuietly(ctx context.Context, s release.Store, st *Store, claimEnabled ...bool) { |
| - if _, err := MaterializeAccounts(ctx, s, st); err != nil { |
| +func materializeQuietly(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64), claimEnabled ...bool) { |
| + if _, err := materializeAccounts(ctx, s, st, unlinkFirst); err != nil { |
| log.Printf("console: could not materialize accounts from the bucket: %v", err) |
| } |
| // After accounts, always: a reaped account's app rows are gone with it, so |
diff --git a/internal/console/parity_test.go b/internal/console/parity_test.go| index 08ba79d30..dd94f0fce 100644 |
| --- a/internal/console/parity_test.go |
| +++ b/internal/console/parity_test.go |
| @@ -8,9 +8,9 @@ import ( |
| // TestParityTableCoversConsoleRoutes holds parity/parity.tsv against |
| // routeDecls (spec C1): every route the console declares, other than the |
| -// /api/cli/ doors, is a console member of at least one row, and every |
| -// console member is a route the console declares and not one of those |
| -// doors. |
| +// /api/cli/ doors and the link doors (kindLink), is a console member of at |
| +// least one row, and every console member is a route the console declares |
| +// and not one of those doors. |
| func TestParityTableCoversConsoleRoutes(t *testing.T) { |
| rows, err := parity.Load("../../parity/parity.tsv") |
| if err != nil { |
| @@ -21,7 +21,7 @@ func TestParityTableCoversConsoleRoutes(t *testing.T) { |
| nonCLI := 0 |
| for _, d := range routeDecls { |
| kinds[d.Pattern] = d.Kind |
| - if !d.Kind.isCLI() { |
| + if d.Kind.parityMember() { |
| nonCLI++ |
| } |
| } |
| @@ -38,15 +38,15 @@ func TestParityTableCoversConsoleRoutes(t *testing.T) { |
| switch { |
| case !ok: |
| t.Errorf("parity/parity.tsv:%d: row %s: console member `%s` is not a route the console declares; fix the pattern or remove it", r.Line, r.ID, m.Text) |
| - case kind.isCLI(): |
| - t.Errorf("parity/parity.tsv:%d: row %s: `%s` is an /api/cli door, outside parity", r.Line, r.ID, m.Text) |
| + case !kind.parityMember(): |
| + t.Errorf("parity/parity.tsv:%d: row %s: `%s` is an /api/cli or link door, outside parity", r.Line, r.ID, m.Text) |
| default: |
| covered[m.Text] = true |
| } |
| } |
| } |
| for _, d := range routeDecls { |
| - if !d.Kind.isCLI() && !covered[d.Pattern] { |
| + if d.Kind.parityMember() && !covered[d.Pattern] { |
| t.Errorf("console declares `%s` but no row covers it: add a row to parity/parity.tsv with console member `%s`", d.Pattern, d.Pattern) |
| } |
| } |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index c7eb06a09..8aa097413 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -24,10 +24,23 @@ const ( |
| // kindCLIScoped is cliScopedRoute: the team role admitted, with the |
| // scope step for Target before the handler. |
| kindCLIScoped |
| + // kindLink is linkRoute: a linked deployment's own doors under |
| + // /api/link (linked deployments spec §6.1). Only a link credential is |
| + // admitted, its channel is synced, and the principal is handed down; |
| + // every other bearer gets the no-bearer 401. Machine-to-machine doors |
| + // with no browser twin, so not parity members. |
| + kindLink |
| ) |
| // isCLI reports whether the kind is one of the /api/cli/ door kinds. |
| -func (k routeKind) isCLI() bool { return k != kindPlain } |
| +func (k routeKind) isCLI() bool { |
| + return k == kindCLI || k == kindCLIJournaled || k == kindCLIScoped |
| +} |
| + |
| +// parityMember reports whether a declaration of this kind is a console |
| +// parity member: the browser's and the plain doors, not the /api/cli/ doors |
| +// nor the link doors. |
| +func (k routeKind) parityMember() bool { return k == kindPlain } |
| // routeGate is a named predicate over Config. A declaration with a gate is |
| // registered only when the gate holds for the console's configuration at |
| @@ -434,6 +447,14 @@ var routeDecls = []routeDecl{ |
| {Pattern: "GET /auth/cli/whoami", Handler: (*Server).handleCLIWhoami}, |
| {Pattern: "POST /auth/cli/revoke", Handler: (*Server).handleCLIRevoke}, |
| {Pattern: "POST /auth/cli/accounts", Handler: (*Server).handleCLINewAccount}, |
| + // A linked deployment's doors (apilinks.go, linked deployments spec |
| + // §5.2, §5.3, §6.1): the link credential's whole reach. linkRoute is |
| + // their one gate and their one resolver. |
| + {Pattern: "GET /api/link", Kind: kindLink, Handler: (*Server).handleLinkGet}, |
| + {Pattern: "DELETE /api/link", Kind: kindLink, Handler: (*Server).handleLinkUnlink}, |
| + {Pattern: "POST /api/link/publications", Kind: kindLink, Handler: (*Server).handleLinkPublish}, |
| + {Pattern: "DELETE /api/link/publications/{app}", Kind: kindLink, Handler: (*Server).handleLinkUnpublish}, |
| + {Pattern: "POST /api/link/rotate", Kind: kindLink, Handler: (*Server).handleLinkRotate}, |
| // The CLI's read-only API (apicli.go) — deliberately a different prefix |
| // (/api/cli/) from the identity routes above (/auth/cli/), which must not |
| // move now that CLIs depend on them. |
| @@ -1208,6 +1229,8 @@ func (s *Server) registerDecls(match func(routeDecl) bool) { |
| s.cliRouteJournaled(d, h) |
| case kindCLIScoped: |
| s.cliScopedRoute(d, h) |
| + case kindLink: |
| + s.registerRoute(d, s.linkRoute(h)) |
| default: |
| panic(fmt.Sprintf("console: route %s has unknown kind %d", d.Pattern, d.Kind)) |
| } |
diff --git a/internal/console/routedecls_test.go b/internal/console/routedecls_test.go| index bde3f67ca..d2e5e7e50 100644 |
| --- a/internal/console/routedecls_test.go |
| +++ b/internal/console/routedecls_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "net/http" |
| "path/filepath" |
| "slices" |
| + "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/demo" |
| @@ -133,11 +134,25 @@ func TestRouteDeclsMatchRegistrations(t *testing.T) { |
| t.Fatalf("%s: %v", tc.name, err) |
| } |
| var got []string |
| + linkDoors := 0 |
| for _, e := range s.claimEntries.snapshot() { |
| if e.Kind == "route" { |
| got = append(got, e.Pattern) |
| + // A kindLink door is registered behind linkRoute, its one |
| + // gate, and no other route is. |
| + behindLinkRoute := strings.Contains(e.Handler, ".linkRoute.") |
| + if linkDoorPatterns()[e.Pattern] != behindLinkRoute { |
| + t.Errorf("%s: %s is registered with handler %s; kindLink doors, and only they, go through linkRoute", |
| + tc.name, e.Pattern, e.Handler) |
| + } |
| + if behindLinkRoute { |
| + linkDoors++ |
| + } |
| } |
| } |
| + if linkDoors != len(linkDoorPatterns()) { |
| + t.Errorf("%s: %d routes registered behind linkRoute, want the %d kindLink doors", tc.name, linkDoors, len(linkDoorPatterns())) |
| + } |
| cfgs = append(cfgs, s.cfg) |
| registered = append(registered, got) |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index d53c48af4..e2b6c4904 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1403,6 +1403,10 @@ type Server struct { |
| // linkFirstSyncs counts the poll's background first syncs |
| // (firstLinkSync), so a test can wait for them. |
| linkFirstSyncs sync.WaitGroup |
| + // linkPublishHook, when non-nil, is called at each stage of a publish |
| + // (apilinks.go). Tests only: the barrier between the apps row and the |
| + // forward row. |
| + linkPublishHook func(linkID, stage string) |
| // delegationZone and lookupCNAME are the wildcard-capability door's two |
| // seams (apidomains.go). delegationZone is cfg.DelegationZone, shape- |
| // validated and normalized once here (normalizeDelegationZone); |
| @@ -1981,9 +1985,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // first admitted iteration of the lifetimes cutover watch, so no listing |
| // runs before the admission gate has a state (lifetimes_cutover.go). |
| if cfg.HostClaim { |
| - materializeQuietly(context.Background(), cfg.Releases, st, cfg.HostClaim) |
| + materializeQuietly(context.Background(), cfg.Releases, st, s.unlinkAccountLinks, cfg.HostClaim) |
| } else { |
| - if _, err := MaterializeAccounts(context.Background(), cfg.Releases, st); err != nil { |
| + if _, err := materializeAccounts(context.Background(), cfg.Releases, st, s.unlinkAccountLinks); err != nil { |
| log.Printf("console: could not materialize accounts from the bucket: %v", err) |
| } |
| s.judge = provision.NewLifetimeJudge() |
| @@ -4190,6 +4194,12 @@ func (s *Server) accountApp(w http.ResponseWriter, r *http.Request) (addr, raw s |
| s.renderMessage(w, r, http.StatusNotFound, "Not found", "No such app here.") |
| return "", "", nil, "", "", false |
| } |
| + // A linked app (spec §6.0) is managed at home: every method, reads |
| + // included, by the door's own policy (linkedpolicy.go). |
| + if ref := s.linkedAppRefusal(r, acct, app); ref != nil { |
| + s.renderMessage(w, r, ref.Status, "Refused", ref.Msg) |
| + return "", "", nil, "", "", false |
| + } |
| if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| s.renderMessage(w, r, ref.Status, "Demo", ref.Msg) |
diff --git a/internal/console/settle.go b/internal/console/settle.go| index 7daa8f396..121cf7c12 100644 |
| --- a/internal/console/settle.go |
| +++ b/internal/console/settle.go |
| @@ -92,6 +92,11 @@ func (s *Server) settleApp(ctx context.Context, accountID int64, sqid, app strin |
| if life.DemoID != "" { |
| return nil |
| } // Demo retirement never infers restoration from absence. |
| + if life.LinkID != "" { |
| + // A linked app (spec §6.0) has no bucket life to settle: it leaves |
| + // only by unpublish or unlink, whatever a marker says. |
| + return nil |
| + } |
| tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, sqid, app) |
| if err != nil { |
| return err |
diff --git a/internal/console/store.go b/internal/console/store.go| index 8aa500108..5ff6ae864 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1830,7 +1830,9 @@ func (s *Store) ReapAccount(accountID int64, now time.Time) error { |
| `DELETE FROM getting_started_marks WHERE account_id = ?`, |
| `DELETE FROM memberships WHERE account_id = ?`, |
| `DELETE FROM invites WHERE account_id = ?`, |
| - `DELETE FROM apps WHERE account_id = ?`, |
| + // A linked app's row goes only by unlink (deleteLinkedAppRow): the |
| + // caller unlinks first, and linkSyncPass finishes any it could not. |
| + `DELETE FROM apps WHERE account_id = ? AND linked_link_id = ''`, |
| } { |
| if _, err := tx.Exec(stmt, accountID); err != nil { |
| return err |
| @@ -2114,7 +2116,7 @@ func (s *Store) claimRawTrashAppRow(accountID int64, app string, now time.Time) |
| _, err := s.db.Exec(`UPDATE apps SET deleted_at = ?, |
| purge_for = CASE WHEN expires_at > 0 THEN ? ELSE 0 END, |
| purge_after = CASE WHEN demo_id != '' THEN ? WHEN expires_at > 0 THEN ? ELSE 0 END |
| -WHERE account_id = ? AND app = ? AND deleted_at = 0`, |
| +WHERE account_id = ? AND app = ? AND deleted_at = 0 AND linked_link_id = ''`, |
| at, at, at, at+temporaryCooloffSeconds, accountID, app) |
| return err |
| } |
| @@ -2150,43 +2152,16 @@ func (s *Store) PurgeAppRow(accountID int64, app string) error { |
| return err |
| } |
| defer tx.Rollback() |
| - if _, err := tx.ExecContext(ctx, `DELETE FROM app_stars WHERE account_id = ? AND lifetime IN (SELECT lifetime FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0)`, accountID, accountID, app); err != nil { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM app_stars WHERE account_id = ? AND lifetime IN (SELECT lifetime FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0 AND linked_link_id = '')`, accountID, accountID, app); err != nil { |
| return err |
| } |
| - res, err := tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0`, accountID, app) |
| + res, err := tx.ExecContext(ctx, `DELETE FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0 AND linked_link_id = ''`, accountID, app) |
| if err != nil { |
| return err |
| } |
| 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 |
| - if err := tx.QueryRowContext(ctx, `SELECT sqid FROM accounts WHERE id = ?`, accountID).Scan(&sqid); err == nil { |
| - if err := forgetMailApp(ctx, tx, sqid, app); err != nil { |
| - return err |
| - } |
| - } else if err != sql.ErrNoRows { |
| - return err |
| - } |
| - // The same for the app's credentials (discussion #219, item 1). App |
| - // tokens of both kinds are bound (account, name), so a later app of |
| - // this name would inherit them unminted; they are DELETED rather than |
| - // revoked, because RenameAppIn and MoveApp refuse a name that still |
| - // carries any such row, revoked or not. Door keys are revoked rather |
| - // than deleted: the revision has to keep climbing past what boxes |
| - // already admitted, and the re-sign pass publishes the now-empty |
| - // record (apidoorkeys.go). |
| - if _, err := tx.ExecContext(ctx, `DELETE FROM cli_tokens WHERE kind IN (?, ?) AND account_id = ? AND app = ?`, |
| - cliKindApp, cliKindService, accountID, app); err != nil { |
| - return err |
| - } |
| - if err := revokeAllDoorKeys(tx, accountID, app); err != nil { |
| - return err |
| - } |
| - // Plans 4d: the app's lapse bookkeeping goes with its identity |
| - // (Astra finding 6); nothing could admit a delete of it later. |
| - if _, err := tx.ExecContext(ctx, `DELETE FROM plan_lapse_items WHERE account_id = ? AND app = ?`, accountID, app); err != nil { |
| + if err := forgetAppTx(ctx, tx, accountID, app); err != nil { |
| return err |
| } |
| } |
| @@ -2199,6 +2174,44 @@ func (s *Store) PurgeAppRow(accountID int64, app string) error { |
| return nil |
| } |
| +// forgetAppTx removes, inside tx, everything keyed by app's name in |
| +// accountID that must not outlive its row: the mail state, the app's |
| +// credentials, its door keys and its lapse items. PurgeAppRow and |
| +// deleteLinkedAppRow call it once their DELETE of the row took effect. |
| +func forgetAppTx(ctx context.Context, tx *sql.Tx, accountID int64, app string) error { |
| + // 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 |
| + if err := tx.QueryRowContext(ctx, `SELECT sqid FROM accounts WHERE id = ?`, accountID).Scan(&sqid); err == nil { |
| + if err := forgetMailApp(ctx, tx, sqid, app); err != nil { |
| + return err |
| + } |
| + } else if err != sql.ErrNoRows { |
| + return err |
| + } |
| + // The same for the app's credentials (discussion #219, item 1). App |
| + // tokens of both kinds are bound (account, name), so a later app of |
| + // this name would inherit them unminted; they are DELETED rather than |
| + // revoked, because RenameAppIn and MoveApp refuse a name that still |
| + // carries any such row, revoked or not. Door keys are revoked rather |
| + // than deleted: the revision has to keep climbing past what boxes |
| + // already admitted, and the re-sign pass publishes the now-empty |
| + // record (apidoorkeys.go). |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM cli_tokens WHERE kind IN (?, ?) AND account_id = ? AND app = ?`, |
| + cliKindApp, cliKindService, accountID, app); err != nil { |
| + return err |
| + } |
| + if err := revokeAllDoorKeys(tx, accountID, app); err != nil { |
| + return err |
| + } |
| + // Plans 4d: the app's lapse bookkeeping goes with its identity |
| + // (Astra finding 6); nothing could admit a delete of it later. |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM plan_lapse_items WHERE account_id = ? AND app = ?`, accountID, app); err != nil { |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| // TrashedApp is one app in an account's Trash: past-tense on purpose, since a |
| // trashed row is inert until restored or purged. |
| type TrashedApp struct { |
| @@ -2272,18 +2285,21 @@ type AppRow struct { |
| Restoring bool |
| PurgeAfter int64 // 0 = no early purge |
| PurgeFor int64 |
| + // LinkID is a linked app's link (spec §6.0), "" for any other app. The |
| + // convergence passes leave a linked row alone. |
| + LinkID string |
| } |
| // appRowCols is the SELECT list every AppRow query uses, in scanAppRows' |
| // order: p is apps, a is accounts. |
| -const appRowCols = `p.account_id, a.sqid, p.app, p.deleted_at, p.expires_at, p.restoring, p.purge_after, p.purge_for` |
| +const appRowCols = `p.account_id, a.sqid, p.app, p.deleted_at, p.expires_at, p.restoring, p.purge_after, p.purge_for, p.linked_link_id` |
| func scanAppRows(rows *sql.Rows) ([]AppRow, error) { |
| defer rows.Close() |
| var out []AppRow |
| for rows.Next() { |
| var r AppRow |
| - if err := rows.Scan(&r.AccountID, &r.Sqid, &r.App, &r.DeletedAt, &r.ExpiresAt, &r.Restoring, &r.PurgeAfter, &r.PurgeFor); err != nil { |
| + if err := rows.Scan(&r.AccountID, &r.Sqid, &r.App, &r.DeletedAt, &r.ExpiresAt, &r.Restoring, &r.PurgeAfter, &r.PurgeFor, &r.LinkID); err != nil { |
| return nil, err |
| } |
| r.Deleted = r.DeletedAt != 0 |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index a224e0720..2573da2c0 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -457,7 +457,9 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| } |
| cliGate := map[string]string{} |
| for _, d := range src.decls { |
| - if d.Kind == "kindPlain" { |
| + // The link doors name no roles: linkRoute admits a link |
| + // credential alone (TestLinkDoorsRefuseEveryOtherBearer). |
| + if d.Kind == "kindPlain" || d.Kind == "kindLink" { |
| continue |
| } |
| if d.Gate != "" && gateNamed[d.Gate] == nil { |
| @@ -874,11 +876,12 @@ type cliSource struct { |
| funcs map[string]*ast.FuncDecl // by bare name |
| gated []string // patterns of cli-kind declarations |
| plain []muxDoor // plain declarations |
| + link []muxDoor // kindLink declarations |
| decls []scannedDecl // every declaration, in order |
| } |
| // routeKindNames are the kinds a declaration may name. |
| -var routeKindNames = map[string]bool{"kindPlain": true, "kindCLI": true, "kindCLIJournaled": true, "kindCLIScoped": true} |
| +var routeKindNames = map[string]bool{"kindPlain": true, "kindCLI": true, "kindCLIJournaled": true, "kindCLIScoped": true, "kindLink": true} |
| // scanCLISource parses the package and classifies every route declaration |
| // in it. Anything it cannot classify is an error rather than a silent skip: |
| @@ -1072,11 +1075,21 @@ func (src *cliSource) readDecl(t *testing.T, el ast.Expr) { |
| if hasBuild && !hasHandler { |
| handler = buildLiteral(b) |
| } |
| - cli := d.Kind != "kindPlain" |
| + cli := d.Kind != "kindPlain" && d.Kind != "kindLink" |
| _, hasAllow := fields["Allow"] |
| _, hasTarget := fields["Target"] |
| _, hasRefused := fields["Refused"] |
| - if cli { |
| + if d.Kind == "kindLink" { |
| + // A linked deployment's door: under /api/link, behind linkRoute |
| + // alone, which admits no role (a link principal holds none). |
| + if !strings.HasPrefix(strings.TrimPrefix(pattern[strings.Index(pattern, " ")+1:], " "), "/api/link") { |
| + t.Errorf("%s: declared kindLink but is not under /api/link", pattern) |
| + } |
| + if hasAllow || hasTarget || hasRefused { |
| + t.Errorf("%s at %s: a kindLink declaration with Allow, Target or Refused, which only cli kinds read", pattern, at) |
| + } |
| + src.link = append(src.link, muxDoor{pattern: pattern, handler: handler}) |
| + } else if cli { |
| src.gated = append(src.gated, pattern) |
| if !strings.Contains(pattern, "/api/cli/") { |
| t.Errorf("%s: declared %s but is not under /api/cli/", pattern, d.Kind) |
| @@ -1096,6 +1109,9 @@ func (src *cliSource) readDecl(t *testing.T, el ast.Expr) { |
| if strings.Contains(pattern, "/api/cli/") { |
| t.Errorf("%s at %s: declared kindPlain, bypassing the role gate", pattern, at) |
| } |
| + if strings.Contains(pattern, "/api/link") { |
| + t.Errorf("%s at %s: declared kindPlain, bypassing linkRoute", pattern, at) |
| + } |
| if hasAllow || hasTarget || hasRefused { |
| t.Errorf("%s at %s: a plain declaration with Allow, Target or Refused, which only cli kinds read", pattern, at) |
| } |
| @@ -1459,6 +1475,30 @@ func TestAuthCLIFamilyResolvesOnlyPersons(t *testing.T) { |
| } |
| } |
| + // The link doors: linkRoute is the one resolver site for kindLink. A |
| + // link handler reads the principal linkRoute put on the context |
| + // (linkPrincipalFrom) and resolves no bearer itself, nor reads the CLI |
| + // gate's principal; linkRoute itself resolves through CLIPrincipal. |
| + if len(src.link) == 0 { |
| + t.Error("no kindLink declarations found; the link doors moved or the walker is broken") |
| + } |
| + for _, d := range src.link { |
| + sel, ok := d.handler.(*ast.SelectorExpr) |
| + if !ok { |
| + t.Errorf("%s: a kindLink handler must be a (*Server) method expression", d.pattern) |
| + continue |
| + } |
| + fd := src.funcs[sel.Sel.Name] |
| + if fd == nil { |
| + t.Errorf("%s: handler %s not found", d.pattern, sel.Sel.Name) |
| + continue |
| + } |
| + assertNoLinkResolver(t, src, d.pattern, fd.Body, map[string]bool{}) |
| + } |
| + if lr := src.funcs["linkRoute"]; lr == nil || !callsSelector(lr.Body, "CLIPrincipal") { |
| + t.Error("linkRoute does not resolve the bearer through CLIPrincipal") |
| + } |
| + |
| // The positive half: the three doors of the family that DO read a |
| // bearer must read it through cliUser. Without this the test above |
| // would still pass if a handler stopped authenticating altogether. |
| @@ -1511,6 +1551,41 @@ func assertBodyResolvesOnlyPersons(t *testing.T, src *cliSource, what string, bo |
| }) |
| } |
| +// assertNoLinkResolver fails if body, or a (*Server) method or package |
| +// function it calls (transitively, within the package), resolves a bearer: |
| +// CLIPrincipal, CLITokenAddress, cliUser or bearer, or reads the CLI gate's |
| +// principal (principalFrom). seen stops the descent at a function already |
| +// read. |
| +func assertNoLinkResolver(t *testing.T, src *cliSource, what string, body *ast.BlockStmt, seen map[string]bool) { |
| + t.Helper() |
| + if body == nil { |
| + return |
| + } |
| + ast.Inspect(body, func(n ast.Node) bool { |
| + var name string |
| + switch n := n.(type) { |
| + case *ast.SelectorExpr: |
| + name = n.Sel.Name |
| + case *ast.Ident: |
| + name = n.Name |
| + default: |
| + return true |
| + } |
| + switch name { |
| + case "CLIPrincipal", "CLITokenAddress", "cliUser", "bearer", "principalFrom": |
| + t.Errorf("%s: resolves a bearer through %s at %s; a link door reads linkRoute's principal (linkPrincipalFrom)", |
| + what, name, src.fset.Position(n.Pos())) |
| + case "linkRoute": |
| + default: |
| + if fd, ok := src.funcs[name]; ok && !seen[name] { |
| + seen[name] = true |
| + assertNoLinkResolver(t, src, what, fd.Body, seen) |
| + } |
| + } |
| + return true |
| + }) |
| +} |
| + |
| // callsSelector reports whether body calls something named name. |
| func callsSelector(body *ast.BlockStmt, name string) bool { |
| found := false |
diff --git a/internal/console/tempstore.go b/internal/console/tempstore.go| index b52d957d2..edcb52557 100644 |
| --- a/internal/console/tempstore.go |
| +++ b/internal/console/tempstore.go |
| @@ -34,17 +34,19 @@ type AppLife struct { |
| PurgeFor int64 // the marker deleted_at purge_after was computed from |
| ControlPlane bool |
| Lifetime string // the row's lifetime id; equal values mean the same app lifetime |
| + // LinkID is a linked app's link (spec §6.0), "" for any other app. |
| + LinkID string |
| } |
| func (l *AppLife) Temporary() bool { return l.ExpiresAt > 0 } |
| func (l *AppLife) Trashed() bool { return l.DeletedAt != 0 } |
| -const appLifeCols = `account_id, app, created_at, deleted_at, expires_at, restoring, purge_after, purge_for, control_plane, lifetime, demo_id` |
| +const appLifeCols = `account_id, app, created_at, deleted_at, expires_at, restoring, purge_after, purge_for, control_plane, lifetime, demo_id, linked_link_id` |
| func scanAppLife(sc interface{ Scan(...any) error }) (AppLife, error) { |
| var l AppLife |
| err := sc.Scan(&l.AccountID, &l.App, &l.CreatedAt, &l.DeletedAt, &l.ExpiresAt, &l.Restoring, |
| - &l.PurgeAfter, &l.PurgeFor, &l.ControlPlane, &l.Lifetime, &l.DemoID) |
| + &l.PurgeAfter, &l.PurgeFor, &l.ControlPlane, &l.Lifetime, &l.DemoID, &l.LinkID) |
| return l, err |
| } |
| @@ -130,7 +132,7 @@ func (s *Store) changed(query string, args ...any) (bool, error) { |
| func (s *Store) claimRawExpireAppRow(accountID int64, app string, deletedAt time.Time) (bool, error) { |
| at := deletedAt.Unix() |
| return s.changed(`UPDATE apps SET deleted_at = ?, purge_for = ?, purge_after = CASE WHEN demo_id != '' THEN ? ELSE ? END |
| -WHERE account_id = ? AND app = ? AND expires_at > 0 AND deleted_at = 0`, |
| +WHERE account_id = ? AND app = ? AND expires_at > 0 AND deleted_at = 0 AND linked_link_id = ''`, |
| at, at, at, at+temporaryCooloffSeconds, accountID, app) |
| } |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 2168b380a..f049f2790 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -23,6 +23,8 @@ route DELETE /api/cli/apps/{account}/{app}/instances/{host} |
| route DELETE /api/cli/apps/{account}/{app}/instances/{host}/move |
| route DELETE /api/cli/apps/{account}/{app}/sidecars/{name} |
| route DELETE /api/cli/system/geoip |
| +route DELETE /api/link |
| +route DELETE /api/link/publications/{app} |
| route GET /a/{sqid}/apps/new |
| route GET /a/{sqid}/apps/{app} |
| route GET /a/{sqid}/apps/{app}/account-review |
| @@ -141,6 +143,7 @@ route GET /api/cli/system/managed-fleets |
| route GET /api/cli/system/pdf |
| route GET /api/cli/system/pointer-digests |
| route GET /api/cli/system/status |
| +route GET /api/link |
| route GET /apps |
| route GET /apps/{app} |
| route GET /auth/callback |
| @@ -358,6 +361,8 @@ route POST /api/cli/system/update |
| route POST /api/fleet/enrol |
| route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator |
| route POST /api/fleet/replicas/{account}/{app}/{host}/release |
| +route POST /api/link/publications |
| +route POST /api/link/rotate |
| route POST /api/ses/events |
| route POST /auth/cli/accounts |
| route POST /auth/cli/approve |