carlos / platform Public

console: refuse linked apps at doors that take the app in the body

Fable's final review, Important 1. The policy table sees only {app}
routes, so a domain purchase (app in the JSON body) reached billing and
its completion's attach for a linked app. linkedRefusalFor is the guard
under an explicit policy: startDomainPurchase refuses a linked app with
LD-C12 before any billing, attachDomainAs refuses it for every caller,
and placeAppTarget refuses it with LD-C11 (the fleet page's Place form
names its app in the form, another bypass the walk found).

TestLinkedPolicyCoversBodyAppDoors walks every non-link route without
an {app} and fails on a handler whose body reads an app (a json:"app"
field, FormValue/PostFormValue/Get("app")) that linkedBodyAppDoors does
not classify. TestBodyAppDoorsRefuseLinkedApps checks the refusals.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6548f5675c5a88db115e63b22d707894d267f701 parent ec33817
5 files changed, +187 −1
  • internal/console/apilinks_test.go +159 −0
  • internal/console/domainattach.go +6 −0
  • internal/console/domainbuy.go +6 −0
  • internal/console/fleets.go +6 −0
  • internal/console/linkedpolicy.go +10 −1
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index b15851ce2..740556c89 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
+ "go/ast"
"go/parser"
"go/token"
"io"
@@ -12,13 +13,17 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "os"
"path/filepath"
+ "reflect"
"regexp"
+ "runtime"
"strings"
"sync"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/billing"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/registry"
@@ -448,6 +453,160 @@ func TestLinkedPolicyCoversEveryAppRoute(t *testing.T) {
}
}
+// linkedBodyAppDoors classifies every route without an {app} in its pattern
+// whose handler reads an app name from its body, form or query (Fable final
+// review, Important 1: the policy table sees only {app} routes, so such a
+// door is invisible to it). Each entry says where the linked guard sits, or
+// why the door cannot act on a linked app.
+var linkedBodyAppDoors = map[string]string{
+ // Guarded with linkedRefusalFor.
+ "POST /api/cli/accounts/{account}/domains/purchases": "startDomainPurchase refuses a linked app with LD-C12 before any billing; the completion's attachDomain refuses it too",
+ "POST /a/{sqid}/fleets/{fleet}/place": "placeAppTarget refuses a linked app with LD-C11",
+ // Cannot act on a linked app.
+ "POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed",
+ "POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed",
+ "POST /a/{sqid}/services/new": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards",
+ "POST /api/cli/services/{account}": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards",
+ "GET /api/cli/system/pointer-digests": "app is a field of the answer, not of the request",
+ "POST /api/cli/system/pointer-digests": "app is a field of the answer, not of the request",
+ "POST /api/cli/link/publications": "the home console's own publish of a home app through its link; no serving-side app",
+}
+
+// TestLinkedPolicyCoversBodyAppDoors finds every declared non-link route
+// without an {app} whose handler body declares a struct field tagged
+// json:"app" or reads FormValue/PostFormValue/Query().Get("app"), and fails
+// on any that linkedBodyAppDoors does not classify (and on an entry that no
+// longer matches such a door). It reads the handler's own body, not the
+// helpers it calls: a door that hands its whole request to a helper that
+// reads the app is outside what it can see.
+func TestLinkedPolicyCoversBodyAppDoors(t *testing.T) {
+ fset := token.NewFileSet()
+ methods := map[string]*ast.FuncDecl{}
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range f.Decls {
+ if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && fd.Body != nil {
+ methods[fd.Name.Name] = fd
+ }
+ }
+ }
+ readsApp := func(fd *ast.FuncDecl) bool {
+ found := false
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.Field:
+ if n.Tag != nil && (strings.Contains(n.Tag.Value, `json:"app"`) || strings.Contains(n.Tag.Value, `json:"app,`)) {
+ found = true
+ }
+ case *ast.CallExpr:
+ sel, ok := n.Fun.(*ast.SelectorExpr)
+ if !ok || len(n.Args) == 0 {
+ break
+ }
+ switch sel.Sel.Name {
+ case "FormValue", "PostFormValue", "Get":
+ if lit, ok := n.Args[0].(*ast.BasicLit); ok && lit.Value == `"app"` {
+ found = true
+ }
+ }
+ }
+ return !found
+ })
+ return found
+ }
+ resolved, eligible := 0, 0
+ var unresolved []string
+ flagged := map[string]bool{}
+ for _, d := range routeDecls {
+ if d.Kind == kindLink || strings.Contains(d.Pattern, "{app}") || d.Handler == nil {
+ continue
+ }
+ eligible++
+ full := runtime.FuncForPC(reflect.ValueOf(d.Handler).Pointer()).Name()
+ name := strings.TrimSuffix(full[strings.LastIndex(full, ".")+1:], "-fm")
+ fd, ok := methods[name]
+ if !ok {
+ unresolved = append(unresolved, d.Pattern+" -> "+full)
+ continue
+ }
+ resolved++
+ if readsApp(fd) {
+ flagged[d.Pattern] = true
+ if _, ok := linkedBodyAppDoors[d.Pattern]; !ok {
+ t.Errorf("%s (%s) reads an app from its request but linkedBodyAppDoors does not classify it: guard it with linkedRefusalFor or say why it cannot act on a linked app", d.Pattern, name)
+ }
+ }
+ }
+ if len(unresolved) != 0 || resolved < 150 {
+ t.Fatalf("resolved %d of %d handlers; is the walk reading the package? unresolved:\n%s", resolved, eligible, strings.Join(unresolved, "\n"))
+ }
+ for pattern := range linkedBodyAppDoors {
+ if !flagged[pattern] {
+ t.Errorf("linkedBodyAppDoors classifies %s, which is not a door the walk finds reading an app", pattern)
+ }
+ }
+}
+
+// TestBodyAppDoorsRefuseLinkedApps: the doors linkedBodyAppDoors says are
+// guarded refuse a linked app. A domain purchase answers LD-C12 before any
+// billing and writes no purchase; an attach (what a purchase's completion
+// runs) answers LD-C12 and writes no claim; a placement answers LD-C11.
+func TestBodyAppDoorsRefuseLinkedApps(t *testing.T) {
+ t.Run("domain purchase and attach", func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ if _, err := f.st.CreateLinkedApp(f.acct.ID, "blog", "link:0123456789ab", "0123456789ab", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "blog", "contact": purchaseContact(), "currency": "usd", "price": 1500})
+ status, out := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), string(body))
+ if status != http.StatusConflict || linkJSONErr(out) != copyLD12 {
+ t.Fatalf("purchase for a linked app = %d %s; want 409 %q", status, out, copyLD12)
+ }
+ if n := f.sent(billing.PreparedPaymentCheckout); n != 0 {
+ t.Fatalf("a purchase for a linked app sent %d checkout(s)", n)
+ }
+ if p, err := f.srv.ownLiveDomainPurchase(context.Background(), f.acct.ID, "shop.com"); err != nil || p != nil {
+ t.Fatalf("a purchase for a linked app was stored: %+v, %v", p, err)
+ }
+ // The ordinary app still buys.
+ if status, out := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), buyBody()); status != http.StatusOK {
+ t.Fatalf("purchase for an ordinary app = %d %s", status, out)
+ }
+ _, ref := f.srv.attachDomain(context.Background(), f.acct, "blog", "www.shop.com", "", "", "owner@example.com")
+ if ref == nil || ref.Status != http.StatusConflict || ref.Msg != copyLD12 {
+ t.Fatalf("attach to a linked app = %+v; want 409 %q", ref, copyLD12)
+ }
+ if c, err := domains.GetClaim(context.Background(), f.srv.cfg.Releases, "www.shop.com"); err == nil && c != nil {
+ t.Fatalf("the refused attach wrote a claim: %+v", c)
+ }
+ })
+ t.Run("placement", 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)
+ }
+ status, msg := fx.srv.placeAppTarget(context.Background(), linkOpsAccount(t, fx), "shop", registry.PlacementTarget("acme"))
+ if want := linkCopy(copyLD11, "app", "shop", "home", "shop-home"); status != http.StatusConflict || msg != want {
+ t.Fatalf("placing a linked app = %d %q; want 409 %q", status, msg, want)
+ }
+ })
+}
+
// 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
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index 7ac4b18e5..764f538ed 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -122,6 +122,12 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
if ref := s.bucketRefusal(); ref != nil {
return attachResult{}, ref
}
+ // Every attach, whichever door or pass asks (a purchase's completion
+ // names its app from the stored purchase): a linked app takes no custom
+ // domain (LD-C12).
+ if ref := s.linkedRefusalFor(acct, app, linkedRefuseDomains); ref != nil {
+ return attachResult{}, ref
+ }
if msg, status := s.temporaryRefusal(acct, app, "attach a domain to it"); msg != "" {
return attachResult{}, &doorRefusal{Status: status, Msg: msg}
}
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go
index 8f5c49c8e..c04f460a9 100644
--- a/internal/console/domainbuy.go
+++ b/internal/console/domainbuy.go
@@ -153,6 +153,12 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
if !exists {
return nil, "", nil, &doorRefusal{Status: http.StatusNotFound}
}
+ // The app comes from the request body, so no route policy saw it: a
+ // linked app takes no custom domain (LD-C12), refused before any
+ // billing.
+ if ref := s.linkedRefusalFor(acct, app, linkedRefuseDomains); ref != nil {
+ return nil, "", nil, ref
+ }
if err := c.Validate(); err != nil {
return nil, "", nil, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: domainBuyCopy["contactError"]}
}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 3cf0f4b18..06f861fbc 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -810,6 +810,12 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
if ref := s.demoMutationRefusal(acct, app); ref != nil {
return ref.Status, ref.Msg
}
+ // A linked app is served from its home deployment: nothing here places
+ // it (LD-C11). The fleet page's Place form names its app in the form,
+ // where no route policy sees it.
+ if ref := s.linkedRefusalFor(acct, app, linkedRefuse); ref != nil {
+ return ref.Status, ref.Msg
+ }
if s.cfg.Demo.Fleet != "" && target == "fleet/"+s.cfg.Demo.Fleet {
return http.StatusConflict, demoCopy["DEMO-POLICY"]
}
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index 48ffb1d5e..943e735b7 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -314,7 +314,16 @@ func (s *Server) refuseLinkedPage(w http.ResponseWriter, r *http.Request, acct *
// 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)
+ return s.linkedRefusalFor(acct, app, linkedAppPolicy(r.Pattern))
+}
+
+// linkedRefusalFor is linkedAppRefusal under policy pol rather than the
+// matched route's: the guard for the paths that take their app from a
+// body, a form or a stored record instead of an {app} in the route
+// (TestLinkedPolicyCoversBodyAppDoors lists those doors): a domain
+// purchase and its completion's attach (linkedRefuseDomains), and a
+// placement (linkedRefuse).
+func (s *Server) linkedRefusalFor(acct *Account, app string, pol linkedPolicy) *doorRefusal {
if pol == linkedAllow {
return nil
}