console: one route declaration list, scanners read it
The registration helpers now take their pattern, roles, scope target and refusal hook from a routeDecl, and registerDecls is their only caller besides the cli helpers forwarding to registerRoute. The group wrappers kept for tests are gone; tests re-register a group with registerDecls and a gate match. scanCLISource reads the routeDecls literal instead of registration calls: Pattern, Kind, Gate, Allow and the handler of every element, and refuses a routeDecl literal anywhere else, an assignment to the list, and any helper or mux registration outside the allowed sites (registrarViolations, also behind TestClaimConsoleMuxHasOneRegistrar). TestEveryCLIDoorNamesItsRoles checks the switch-only doors carry their switches' gates and that each configuration records exactly the cli declarations whose gate holds. billingDoorRoutes reads the list. TestRouteDeclsMatchRegistrations builds NewServer under six configurations and checks each registered exactly the declarations whose gate holds, that every gate flips and every declaration is registered somewhere (checkDeclRegistration, with fixtures).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/apidemo.go+0 −6internal/console/apidemo_test.go+1 −1internal/console/apidemooperator.go+0 −6internal/console/apiinstancemove.go+0 −7internal/console/apiinstancemove_j4_test.go+2 −2internal/console/apiinstancemove_test.go+1 −1internal/console/authcli.go+12 −5internal/console/claim_invariant_test.go+5 −5internal/console/claim_probe_all_apps_test.go+2 −2internal/console/claim_routes.go+13 −2internal/console/claim_routes_test.go+13 −40internal/console/demo_claim_countdown_test.go+1 −1internal/console/demo_claim_page_test.go+3 −3internal/console/demo_claim_ready_test.go+1 −1internal/console/demo_claim_resume_browser_test.go+3 −3internal/console/demo_claim_resume_test.go+2 −2internal/console/demo_e2e_test.go+1 −1internal/console/demo_gate_test.go+1 −1internal/console/demo_protections_e2e_test.go+1 −1internal/console/demo_spent_token_test.go+1 −1internal/console/movesrecovery_test.go+2 −2internal/console/perfquickwins_test.go+1 −1internal/console/planexempt_test.go+8 −31internal/console/routedecls.go+4 −5internal/console/routedecls_test.go+202 −0internal/console/server.go+1 −1internal/console/svcroutes_test.go+416 −145internal/console/teamdoors.go+3 −2internal/console/teamdoors_test.go+2 −2
Intent
<task-notification> <task-id>b8irxa405</task-id> <summary>Monitor event: "Task 2 commits landing on design-parity-guard"</summary> <event>82d76a69 console: declare apimail.go routes in routeDecls</event> </task-notification>
<task-notification> <task-id>b8irxa405</task-id> <summary>Monitor event: "Task 2 commits landing on design-parity-guard"</summary> <event>[Monitor expired after 30m with 8 events delivered. Re-arm it if you still need the watch.]</event> </task-notification>
<task-notification> <task-id>a1f0482034841246c</task-id> <tool-use-id>toolu_0169d5yWRKyby2UFVWmZifNA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2185be7a-bc2c-4a32-953d-1ee7721363e3/tasks/a1f0482034841246c.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: console routeDecls" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting for the targeted run (monitor b80i521n9 is still watching).</result> <usage><subagent_tokens>250022</subagent_tokens><tool_uses>126</tool_uses><duration_ms>1866165</duration_ms></usage> </task-notification>
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index 0aa0366ec..a64dcac11 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -266,12 +266,6 @@ func (s *Server) demoAdmissionReady(ctx context.Context) error { |
| return nil |
| } |
| -// registerDemoRoutes registers the gateDemo declarations again, for the |
| -// tests that rebuild the mux after changing the demo configuration. Removed |
| -// once those tests call registerDecls themselves. |
| -func (s *Server) registerDemoRoutes() { |
| - s.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo }) |
| -} |
| func demoTokenRefusal(err error) (reason, message string) { |
| switch { |
| case errors.Is(err, ErrDemoExpired): |
diff --git a/internal/console/apidemo_test.go b/internal/console/apidemo_test.go| index df8a8e214..7347ec207 100644 |
| --- a/internal/console/apidemo_test.go |
| +++ b/internal/console/apidemo_test.go |
| @@ -28,7 +28,7 @@ func demoTestServer(t *testing.T) *Server { |
| st, _ := demoTestStore(t) |
| s := &Server{store: st, cfg: demoTestDeploymentConfig(t), mux: http.NewServeMux()} |
| demoTestWorker(t, s) |
| - s.registerDemoRoutes() |
| + s.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo }) |
| return s |
| } |
| func demoTestWorker(t *testing.T, s *Server) { |
diff --git a/internal/console/apidemooperator.go b/internal/console/apidemooperator.go| index 5e8e56377..97d705628 100644 |
| --- a/internal/console/apidemooperator.go |
| +++ b/internal/console/apidemooperator.go |
| @@ -12,12 +12,6 @@ import ( |
| "github.com/carlosframework/platform/internal/demobuild" |
| ) |
| -// registerDemoOperatorRoutes registers the gateNoHostClaim declarations |
| -// again, for the test that adds them to a server built without them. |
| -// Removed once that test calls registerDecls itself. |
| -func (s *Server) registerDemoOperatorRoutes() { |
| - s.registerDecls(func(d routeDecl) bool { return d.Gate == gateNoHostClaim }) |
| -} |
| func (s *Server) demoOperator(w http.ResponseWriter, r *http.Request) (string, bool) { |
| actor, _, ok := s.apiSystemRoller(w, r) |
| if !ok { |
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go| index c56e9e3a0..ef30dfb67 100644 |
| --- a/internal/console/apiinstancemove.go |
| +++ b/internal/console/apiinstancemove.go |
| @@ -1313,13 +1313,6 @@ func claimConsoleMoveFailed(w http.ResponseWriter, acct *Account, app, host stri |
| } |
| } |
| -// registerMovesPhase1Routes registers the gateMoves declarations again, |
| -// for the tests that turn the switch on after building the server. Removed |
| -// once those tests call registerDecls themselves. |
| -func (s *Server) registerMovesPhase1Routes() { |
| - s.registerDecls(func(d routeDecl) bool { return d.Gate == gateMoves }) |
| -} |
| - |
| // errMoveChanged refuses a write whose move is no longer the one the door |
| // read. It wraps ErrMoveConflict so moveTransition answers 409. |
| var errMoveChanged = fmt.Errorf("%w: %s", provision.ErrMoveConflict, moveChangedSentence) |
diff --git a/internal/console/apiinstancemove_j4_test.go b/internal/console/apiinstancemove_j4_test.go| index 0cdd839a1..2a397cdda 100644 |
| --- a/internal/console/apiinstancemove_j4_test.go |
| +++ b/internal/console/apiinstancemove_j4_test.go |
| @@ -217,8 +217,8 @@ func TestJ4HostDoorRoutesOnlyMoveKinds(t *testing.T) { |
| fx, token, _ := j4LandingMove(t, "code-j4-hostdoor") |
| fx.srv.cfg.Bucket = moveTestBucket |
| // NewServer registers the host routes only with HostClaim on at build. |
| - fx.srv.cliRoute("POST /api/cli/ops/hosts/{host}/resolve/inspect", svcrole.Set{}, fx.srv.handleAPIHostResolveInspect) |
| - fx.srv.cliRoute("POST /api/cli/ops/hosts/{host}/resolve", svcrole.Set{}, fx.srv.handleAPIHostResolve) |
| + fx.srv.cliRoute(routeDecl{Pattern: "POST /api/cli/ops/hosts/{host}/resolve/inspect", Kind: kindCLI, Allow: svcrole.Set{}}, fx.srv.handleAPIHostResolveInspect) |
| + fx.srv.cliRoute(routeDecl{Pattern: "POST /api/cli/ops/hosts/{host}/resolve", Kind: kindCLI, Allow: svcrole.Set{}}, fx.srv.handleAPIHostResolve) |
| if err := hostfloor.Publish(ctx, fx.rel, release.RootSigner(fx.priv), moveTestBucket, hostfloor.Floor{Min: 1, MinRelease: "v1.0.0"}); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/apiinstancemove_test.go b/internal/console/apiinstancemove_test.go| index 3ecf3f773..29fd5a3bb 100644 |
| --- a/internal/console/apiinstancemove_test.go |
| +++ b/internal/console/apiinstancemove_test.go |
| @@ -346,7 +346,7 @@ func operatorInstanceFixture(t *testing.T, code string) (*consoleFixture, string |
| // the config field, and the routes NewServer registers only when it is on. |
| func enableMovesPhase1(fx *consoleFixture) { |
| fx.srv.cfg.MovesEnabled = true |
| - fx.srv.registerMovesPhase1Routes() |
| + fx.srv.registerDecls(func(d routeDecl) bool { return d.Gate == gateMoves }) |
| } |
| // errorText is a JSON error body's sentence, "" when the body is not one. |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ac82cd51b..ebd35585c 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -445,7 +445,8 @@ func principalFrom(ctx context.Context) (Principal, bool) { |
| // allow is never optional and the zero Set permits nothing — not even admin — |
| // so a door added without naming its roles is unreachable by every service |
| // principal rather than open to all of them. |
| -func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc) { |
| +func (s *Server) cliRoute(d routeDecl, h http.HandlerFunc) { |
| + pattern, allow := d.Pattern, d.Allow |
| if allow.Permits(svcrole.Team) { |
| // A team credential is admitted only by cliScopedRoute, which runs |
| // the scope check before the handler (teamdoors.go). A plain |
| @@ -460,15 +461,21 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc) |
| if pattern == "GET /api/cli/apps/{account}/{app}/source" { |
| gate = s.sourceAdmission(gate, true) |
| } |
| - s.registerRoute(pattern, gate) |
| + s.registerRoute(d, gate) |
| } |
| // cliRouteJournaled is cliRoute whose role gate, when it refuses a service |
| // credential, also calls refused with the request, the principal and the |
| -// status, before the same refusal: the interactive session door's journal |
| +// status, before the same refusal (d.Refused, a method expression called |
| +// with the server): the interactive session door's journal |
| // line for a caller the gate stops before the door (rootfs apps Plan 6, |
| // branch review R1 P2). |
| -func (s *Server) cliRouteJournaled(pattern string, allow svcrole.Set, h http.HandlerFunc, refused func(*http.Request, Principal, int)) { |
| +func (s *Server) cliRouteJournaled(d routeDecl, h http.HandlerFunc) { |
| + pattern, allow := d.Pattern, d.Allow |
| + var refused func(*http.Request, Principal, int) |
| + if d.Refused != nil { |
| + refused = func(r *http.Request, p Principal, status int) { d.Refused(s, r, p, status) } |
| + } |
| if allow.Permits(svcrole.Team) { |
| panic("console: cliRouteJournaled " + pattern + " admits the team role; a team door is registered through cliScopedRoute") |
| } |
| @@ -476,7 +483,7 @@ func (s *Server) cliRouteJournaled(pattern string, allow svcrole.Set, h http.Han |
| s.cliRoles = map[string]svcrole.Set{} |
| } |
| s.cliRoles[pattern] = allow |
| - s.registerRoute(pattern, s.cliGateRefused(allow, h, refused)) |
| + s.registerRoute(d, s.cliGateRefused(allow, h, refused)) |
| } |
| // cliGate is the handler cliRoute and cliScopedRoute register: the bearer |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 87ffa4cfd..9d00e43f9 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -848,7 +848,7 @@ func claimWitnessDoor(path string, write func(cx *claimCase) func(r *http.Reques |
| return &claimDoor{ |
| apps: claimWitnessApps, |
| setup: func(t *testing.T, cx *claimCase) { |
| - cx.srv.registerRoute("POST "+path, claimWitnessHandler(cx, write(cx))) |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessHandler(cx, write(cx))) |
| }, |
| do: func(t *testing.T, cx *claimCase) int { |
| token := "" |
| @@ -871,7 +871,7 @@ func TestClaimConsoleMutationInvariantWitnesses(t *testing.T) { |
| t.Run("missing fixture", func(t *testing.T) { |
| cx := newClaimCase(t) |
| - cx.srv.registerRoute("POST /claim-witness/missing", cx.srv.handleHome) |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST /claim-witness/missing"}, cx.srv.handleHome) |
| problems := claimFixtureCensus(cx.srv.claimEntries.snapshot(), claimFixtures) |
| if !slices.ContainsFunc(problems, func(p string) bool { return strings.Contains(p, "route POST /claim-witness/missing") }) { |
| t.Fatalf("a route with no fixture passed the census: %v", problems) |
| @@ -967,7 +967,7 @@ func TestClaimConsoleMutationInvariantWitnesses(t *testing.T) { |
| if write != nil { |
| w = write(cx) |
| } |
| - cx.srv.registerRoute("POST "+path, claimWitnessRefusalHandler(cx, w)) |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessRefusalHandler(cx, w)) |
| }, |
| do: func(t *testing.T, cx *claimCase) (int, string) { |
| token := "" |
| @@ -1032,7 +1032,7 @@ func TestClaimConsoleMutationInvariantWitnesses(t *testing.T) { |
| stage := d.setup |
| d.setup = func(t *testing.T, cx *claimCase) { |
| stage(t, cx) |
| - cx.srv.registerRoute("POST "+path, claimWitnessHandler(cx, func(r *http.Request) error { |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessHandler(cx, func(r *http.Request) error { |
| return cx.st.claimRawRevokeCLIToken(claimFxOwner, cx.vars["apptok"]) |
| })) |
| } |
| @@ -1054,7 +1054,7 @@ func TestClaimConsoleMutationInvariantWitnesses(t *testing.T) { |
| stage := d.setup |
| d.setup = func(t *testing.T, cx *claimCase) { |
| stage(t, cx) |
| - cx.srv.registerRoute("POST "+path, claimWitnessHandler(cx, func(r *http.Request) error { |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessHandler(cx, func(r *http.Request) error { |
| // Deliberately simulate a forgotten gate that reaches raw SQL. |
| // This test-only bypass proves the census detects a LANDED |
| // mutation independently of the production SQL trigger. |
diff --git a/internal/console/claim_probe_all_apps_test.go b/internal/console/claim_probe_all_apps_test.go| index 12ee18292..f927e8652 100644 |
| --- a/internal/console/claim_probe_all_apps_test.go |
| +++ b/internal/console/claim_probe_all_apps_test.go |
| @@ -29,7 +29,7 @@ func TestClaimProbeDetectsSQLMutationOutsideDefaultApps(t *testing.T) { |
| const path = "/claim-witness/third-app" |
| p := claimProbe{setup: func(t *testing.T, cx *claimCase) { |
| id := cx.enroll(t, "bab", "third") |
| - cx.srv.registerRoute("POST "+path, claimWitnessHandler(cx, func(r *http.Request) error { |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessHandler(cx, func(r *http.Request) error { |
| scopes := []claimSQLScope{{AccountID: OpsAccountID, App: "third", AppID: id, Mode: claimModeEffect}} |
| return cx.st.withClaimSQL(gateCtx(t), scopes, allowAllClaimSQL, func(st *Store) error { |
| _, err := st.db.Exec(`UPDATE apps SET claim_op='ungated' WHERE account_id=? AND app=?`, OpsAccountID, "third") |
| @@ -109,7 +109,7 @@ func TestClaimProbeDetectsOrphanSQLMutation(t *testing.T) { |
| }); err != nil { |
| t.Fatal(err) |
| } |
| - cx.srv.registerRoute("POST "+path, claimWitnessHandler(cx, func(r *http.Request) error { |
| + cx.srv.registerRoute(routeDecl{Pattern: "POST " + path}, claimWitnessHandler(cx, func(r *http.Request) error { |
| return cx.st.withClaimSQL(gateCtx(t), scopes, allowAllClaimSQL, func(st *Store) error { _, err := st.db.Exec(`DELETE FROM audit WHERE app='orphan'`); return err }) |
| })) |
| }, do: claimAPIReply(http.MethodPost, path, `{}`), effect: func(*testing.T, *claimCase, claimReply) string { return "" }} |
diff --git a/internal/console/claim_routes.go b/internal/console/claim_routes.go| index 91097dcdb..7dfb7f90d 100644 |
| --- a/internal/console/claim_routes.go |
| +++ b/internal/console/claim_routes.go |
| @@ -65,8 +65,19 @@ func claimHandlerName(h any) string { |
| // Every GET and HEAD request gets a request memo of its own (reqmemo.go), |
| // so one page view reads each box report set, the edges files and the |
| // app's instances.json at most once. Other requests get none. |
| -func (s *Server) registerRoute(pattern string, h http.HandlerFunc) { |
| - e := claimEntry{Kind: "route", Pattern: pattern, Handler: claimHandlerName(h)} |
| +// |
| +// It takes its pattern only from a declaration: registerDecls and the cli |
| +// helpers forwarding to it are its only callers, and it is the only mux |
| +// registration in the package (TestClaimConsoleMuxHasOneRegistrar). A |
| +// plain declaration's provenance names its method expression, since the |
| +// h registerDecls hands over is a closure around it. |
| +func (s *Server) registerRoute(d routeDecl, h http.HandlerFunc) { |
| + pattern := d.Pattern |
| + name := claimHandlerName(h) |
| + if d.Kind == kindPlain && d.Handler != nil { |
| + name = claimHandlerName(d.Handler) |
| + } |
| + e := claimEntry{Kind: "route", Pattern: pattern, Handler: name} |
| s.claimEntries.add(e) |
| h = withReqMemoOnViews(s.withFrameClear(pattern, h)) |
| if !s.cfg.HostClaim { |
diff --git a/internal/console/claim_routes_test.go b/internal/console/claim_routes_test.go| index f1a313231..21ba10c47 100644 |
| --- a/internal/console/claim_routes_test.go |
| +++ b/internal/console/claim_routes_test.go |
| @@ -1,11 +1,7 @@ |
| package console |
| import ( |
| - "go/ast" |
| - "go/parser" |
| - "go/token" |
| "os" |
| - "path/filepath" |
| "slices" |
| "strings" |
| "testing" |
| @@ -46,47 +42,24 @@ func TestClaimConsoleRouteCensus(t *testing.T) { |
| } |
| t.FailNow() |
| } |
| - s.registerRoute("POST /claim-unreviewed-door", s.handleHome) |
| + s.registerRoute(routeDecl{Pattern: "POST /claim-unreviewed-door"}, s.handleHome) |
| if compareClaimInventory(s.claimEntries.snapshot(), want) { |
| t.Fatal("new route escaped census") |
| } |
| } |
| + |
| +// TestClaimConsoleMuxHasOneRegistrar: in non-test code the only mux |
| +// registration is registerRoute's, and the registration helpers are named |
| +// only by registerDecls (the loop over routeDecls) and by the cli helpers |
| +// forwarding to registerRoute. Anything else is a route registered outside |
| +// the declaration list, and fails with its position. |
| func TestClaimConsoleMuxHasOneRegistrar(t *testing.T) { |
| - fs := token.NewFileSet() |
| - entries, err := os.ReadDir(".") |
| - if err != nil { |
| - t.Fatal(err) |
| + fset, files := parseConsoleSource(t) |
| + violations, muxSites := registrarViolations(fset, files) |
| + for _, v := range violations { |
| + t.Error(v) |
| } |
| - for _, entry := range entries { |
| - if !strings.HasSuffix(entry.Name(), ".go") || strings.HasSuffix(entry.Name(), "_test.go") { |
| - continue |
| - } |
| - f, err := parser.ParseFile(fs, entry.Name(), nil, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, d := range f.Decls { |
| - fd, ok := d.(*ast.FuncDecl) |
| - if !ok || fd.Body == nil { |
| - continue |
| - } |
| - ast.Inspect(fd.Body, func(n ast.Node) bool { |
| - call, ok := n.(*ast.CallExpr) |
| - if !ok { |
| - return true |
| - } |
| - sel, ok := call.Fun.(*ast.SelectorExpr) |
| - if !ok { |
| - return true |
| - } |
| - if sel.Sel.Name != "Handle" && sel.Sel.Name != "HandleFunc" { |
| - return true |
| - } |
| - if filepath.Base(entry.Name()) != "claim_routes.go" || fd.Name.Name != "registerRoute" { |
| - t.Errorf("mux registration outside registerRoute: %s", fs.Position(n.Pos())) |
| - } |
| - return true |
| - }) |
| - } |
| + if muxSites == 0 { |
| + t.Fatal("found no mux registration in registerRoute; the walk is broken") |
| } |
| } |
diff --git a/internal/console/demo_claim_countdown_test.go b/internal/console/demo_claim_countdown_test.go| index 85ca9ba9c..e9ea6f92a 100644 |
| --- a/internal/console/demo_claim_countdown_test.go |
| +++ b/internal/console/demo_claim_countdown_test.go |
| @@ -106,7 +106,7 @@ func TestDemoClaimCountdownBrowser(t *testing.T) { |
| if _, err := s.store.db.Exec(`UPDATE apps SET expires_at=? WHERE demo_id<>''`, expiry); err != nil { |
| t.Fatal(err) |
| } |
| - s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + s.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, s.handleStatic) |
| ts := httptest.NewServer(s.mux) |
| defer ts.Close() |
| s.cfg.Origin = ts.URL |
diff --git a/internal/console/demo_claim_page_test.go b/internal/console/demo_claim_page_test.go| index 9961491a1..2812a34d3 100644 |
| --- a/internal/console/demo_claim_page_test.go |
| +++ b/internal/console/demo_claim_page_test.go |
| @@ -79,8 +79,8 @@ func (b *claimBrowser) post(path string, form url.Values) *httptest.ResponseReco |
| func newClaimBrowser(t *testing.T, s *Server, token string) *claimBrowser { |
| t.Helper() |
| if _, pattern := s.mux.Handler(httptest.NewRequest("GET", "/auth/email/link", nil)); pattern == "" { |
| - s.registerRoute("GET /auth/email/link", s.handleEmailLinkPage) |
| - s.registerRoute("POST /auth/email/link", s.handleEmailLink) |
| + s.registerRoute(routeDecl{Pattern: "GET /auth/email/link"}, s.handleEmailLinkPage) |
| + s.registerRoute(routeDecl{Pattern: "POST /auth/email/link"}, s.handleEmailLink) |
| } |
| b := &claimBrowser{t: t, s: s} |
| if w := b.request("GET", "/demo/claim", nil); w.Code != 200 { |
| @@ -176,7 +176,7 @@ func TestDemoClaimBrowserHeadless(t *testing.T) { |
| t.Skip("no installed node for browser protocol") |
| } |
| s, m, token := claimTestServer(t) |
| - s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + s.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, s.handleStatic) |
| var mu sync.Mutex |
| var leaked bool |
| var exchange int |
diff --git a/internal/console/demo_claim_ready_test.go b/internal/console/demo_claim_ready_test.go| index 0d192b4d3..5c6e60940 100644 |
| --- a/internal/console/demo_claim_ready_test.go |
| +++ b/internal/console/demo_claim_ready_test.go |
| @@ -123,7 +123,7 @@ func TestDemoClaimRecoveryRoutes(t *testing.T) { |
| // Register on a fresh mux, as after a console restart with admission off. |
| s.mux = http.NewServeMux() |
| s.claimEntries = claimInventory{} |
| - s.registerDemoRoutes() |
| + s.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo }) |
| for _, route := range []struct{ method, path string }{{"GET", "/api/demo/claims/status"}, {"GET", "/demo/claim"}, {"GET", "/demo/claim/status"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/pickup"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/snapshot"}, {"POST", "/api/box/demo-claims/AAAAAAAAAAAAAAAAAAAAAA/ack"}, {"POST", "/api/box/demo-retirements/ack"}, {"GET", demoBuildStreamPath}} { |
| r := httptest.NewRequest(route.method, route.path, nil) |
| if _, p := s.mux.Handler(r); p == "" { |
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go| index bebf6a2b0..29ecc78cc 100644 |
| --- a/internal/console/demo_claim_resume_browser_test.go |
| +++ b/internal/console/demo_claim_resume_browser_test.go |
| @@ -27,7 +27,7 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) { |
| } |
| s, _, token := claimTestServer(t) |
| fk := claimStepUpStub(t, s) |
| - s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + s.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, s.handleStatic) |
| var polls, mode atomic.Int32 |
| ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| if r.URL.Path == "/demo/claim" && r.URL.Query().Has("testProgress") { |
| @@ -122,7 +122,7 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) { |
| // A second real flow renders the one-account state without changing the |
| // multi-account flow used for the keyboard and fresh-auth round trip. |
| single, _, singleToken := claimTestServer(t) |
| - single.registerRoute("GET /static/{hash}/{file...}", single.handleStatic) |
| + single.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, single.handleStatic) |
| singleServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| if r.URL.Query().Has("long") { |
| if _, err := single.store.db.Exec(`UPDATE accounts SET name=? WHERE id=601`, strings.Repeat("LongAccountName", 10)); err != nil { |
| @@ -143,7 +143,7 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) { |
| claimAccount(t, single, 601, "shop@example.com", RoleOwner) |
| single.cfg.PlanCatalog = examplePlanCatalog(t) |
| capacity, _, capacityToken := claimTestServer(t) |
| - capacity.registerRoute("GET /static/{hash}/{file...}", capacity.handleStatic) |
| + capacity.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, capacity.handleStatic) |
| capacityServer := httptest.NewServer(capacity.mux) |
| defer capacityServer.Close() |
| capacity.cfg.Origin = capacityServer.URL |
diff --git a/internal/console/demo_claim_resume_test.go b/internal/console/demo_claim_resume_test.go| index 8d02f2430..c0a347595 100644 |
| --- a/internal/console/demo_claim_resume_test.go |
| +++ b/internal/console/demo_claim_resume_test.go |
| @@ -27,8 +27,8 @@ func claimStepUpStub(t *testing.T, s *Server) *fakeKeymail { |
| }) |
| s.km = NewKeymail(fk.srv.URL, s.cfg.Origin) |
| s.km.SetSigningKey(testSigningKey(t)) |
| - s.registerRoute("GET /auth/stepup/callback", s.handleStepUpCallback) |
| - s.registerRoute("POST /auth/email/stepup/code", s.handleStepUpEmailCode) |
| + s.registerRoute(routeDecl{Pattern: "GET /auth/stepup/callback"}, s.handleStepUpCallback) |
| + s.registerRoute(routeDecl{Pattern: "POST /auth/email/stepup/code"}, s.handleStepUpEmailCode) |
| return fk |
| } |
diff --git a/internal/console/demo_e2e_test.go b/internal/console/demo_e2e_test.go| index 8bb1ece1f..210c9e56c 100644 |
| --- a/internal/console/demo_e2e_test.go |
| +++ b/internal/console/demo_e2e_test.go |
| @@ -615,7 +615,7 @@ func TestDemoDisabledCompatibility(t *testing.T) { |
| _, beforePattern := s.mux.Handler(request) |
| before := httptest.NewRecorder() |
| s.mux.ServeHTTP(before, request) |
| - s.registerDemoRoutes() |
| + s.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo }) |
| _, afterPattern := s.mux.Handler(request) |
| after := httptest.NewRecorder() |
| s.mux.ServeHTTP(after, request) |
diff --git a/internal/console/demo_gate_test.go b/internal/console/demo_gate_test.go| index 5c7177474..df25e686e 100644 |
| --- a/internal/console/demo_gate_test.go |
| +++ b/internal/console/demo_gate_test.go |
| @@ -105,7 +105,7 @@ func TestDemoProtectionsSQLScopes(t *testing.T) { |
| func TestDemoProtectionsClaimsMode(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.Demo = demoTestConfig(t) |
| - fx.srv.registerDemoRoutes() |
| + fx.srv.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo }) |
| fx.srv.cfg.SystemOperators = []string{"operator@example.com"} |
| token := cliToken(t, fx, "operator@example.com", "demo-claims") |
| if code, _, body := rawReq(t, "GET", fx.ts.URL+"/api/cli/system/demos", token, ""); code != 200 { |
diff --git a/internal/console/demo_protections_e2e_test.go b/internal/console/demo_protections_e2e_test.go| index f62340195..7d87e5d4c 100644 |
| --- a/internal/console/demo_protections_e2e_test.go |
| +++ b/internal/console/demo_protections_e2e_test.go |
| @@ -175,7 +175,7 @@ func TestDemoProtectionsSourceToLimitAndTakedown(t *testing.T) { |
| s.cfg.Demo.BandwidthCapBytes = 100000 |
| s.cfg.Demo.RequestCap = 100 |
| s.cfg.SystemOperators = []string{"operator@example.com"} |
| - s.registerDemoOperatorRoutes() |
| + s.registerDecls(func(d routeDecl) bool { return d.Gate == gateNoHostClaim }) |
| bucket := filepath.Join(dir, "bucket") |
| storage.Store = release.NewDirStore(bucket) |
| if _, err = s.store.db.Exec(`UPDATE accounts SET sqid=? WHERE id=42`, s.cfg.Demo.Account); err != nil { |
diff --git a/internal/console/demo_spent_token_test.go b/internal/console/demo_spent_token_test.go| index b7417dcc8..716ebb37c 100644 |
| --- a/internal/console/demo_spent_token_test.go |
| +++ b/internal/console/demo_spent_token_test.go |
| @@ -277,7 +277,7 @@ func TestDemoSpentTokenBrowserHeadless(t *testing.T) { |
| if err = s.retireDemoLocked(t.Context(), d, time.Unix(d.CreatedAt+86400, 0), "expired"); err != nil { |
| t.Fatal(err) |
| } |
| - s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + s.registerRoute(routeDecl{Pattern: "GET /static/{hash}/{file...}"}, s.handleStatic) |
| ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| if strings.Contains(r.URL.String(), token) || strings.Contains(r.Header.Get("Referer"), token) { |
| t.Error("token leaked in URL or referrer") |
diff --git a/internal/console/movesrecovery_test.go b/internal/console/movesrecovery_test.go| index 6e0922a83..fa669b2a4 100644 |
| --- a/internal/console/movesrecovery_test.go |
| +++ b/internal/console/movesrecovery_test.go |
| @@ -1415,8 +1415,8 @@ func TestDeclaredLostIsLoggedByTheConsole(t *testing.T) { |
| func j4HostDoor(t *testing.T, fx *consoleFixture) string { |
| t.Helper() |
| fx.srv.cfg.Bucket = moveTestBucket |
| - fx.srv.cliRoute("POST /api/cli/ops/hosts/{host}/resolve/inspect", svcrole.Set{}, fx.srv.handleAPIHostResolveInspect) |
| - fx.srv.cliRoute("POST /api/cli/ops/hosts/{host}/resolve", svcrole.Set{}, fx.srv.handleAPIHostResolve) |
| + fx.srv.cliRoute(routeDecl{Pattern: "POST /api/cli/ops/hosts/{host}/resolve/inspect", Kind: kindCLI, Allow: svcrole.Set{}}, fx.srv.handleAPIHostResolveInspect) |
| + fx.srv.cliRoute(routeDecl{Pattern: "POST /api/cli/ops/hosts/{host}/resolve", Kind: kindCLI, Allow: svcrole.Set{}}, fx.srv.handleAPIHostResolve) |
| if err := hostfloor.Publish(context.Background(), fx.rel, release.RootSigner(fx.priv), moveTestBucket, hostfloor.Floor{Min: 1, MinRelease: "v1.0.0"}); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/perfquickwins_test.go b/internal/console/perfquickwins_test.go| index 905658b33..314150515 100644 |
| --- a/internal/console/perfquickwins_test.go |
| +++ b/internal/console/perfquickwins_test.go |
| @@ -351,7 +351,7 @@ func TestReqMemoOnlyOnViews(t *testing.T) { |
| t.Run(tc.method+" "+tc.pattern, func(t *testing.T) { |
| s := &Server{mux: http.NewServeMux()} |
| held := map[string]bool{} |
| - s.registerRoute(tc.pattern, func(w http.ResponseWriter, r *http.Request) { |
| + s.registerRoute(routeDecl{Pattern: tc.pattern}, func(w http.ResponseWriter, r *http.Request) { |
| for _, key := range []string{"edges", boxesMemoKey(""), boxesMemoKey("fleets/f/"), "instances-manifest:bab/kass", "k"} { |
| held[key] = memoOf(r.Context(), key) != nil |
| } |
diff --git a/internal/console/planexempt_test.go b/internal/console/planexempt_test.go| index e77526221..99a1207a1 100644 |
| --- a/internal/console/planexempt_test.go |
| +++ b/internal/console/planexempt_test.go |
| @@ -5,12 +5,10 @@ import ( |
| "database/sql" |
| "errors" |
| "go/ast" |
| - "go/token" |
| "net/http" |
| "net/url" |
| "slices" |
| "sort" |
| - "strconv" |
| "strings" |
| "sync/atomic" |
| "testing" |
| @@ -582,37 +580,16 @@ func TestPlanExemptBillingHoldRefused(t *testing.T) { |
| } |
| } |
| -// billingDoorRoutes is every route registered under /a/{sqid}/billing/ in |
| -// server.go, with its handler's name. |
| -func billingDoorRoutes(t *testing.T, files map[string]*ast.File) map[string]string { |
| +// billingDoorRoutes is every plain declaration under /a/{sqid}/billing/ in |
| +// routeDecls, with its handler method's name. |
| +func billingDoorRoutes(t *testing.T) map[string]string { |
| t.Helper() |
| out := map[string]string{} |
| - f := files["server.go"] |
| - if f == nil { |
| - t.Fatal("no server.go") |
| - } |
| - ast.Inspect(f, func(n ast.Node) bool { |
| - call, ok := n.(*ast.CallExpr) |
| - if !ok || len(call.Args) != 2 { |
| - return true |
| - } |
| - sel, ok := call.Fun.(*ast.SelectorExpr) |
| - if !ok || sel.Sel.Name != "registerRoute" { |
| - return true |
| - } |
| - lit, ok := call.Args[0].(*ast.BasicLit) |
| - if !ok || lit.Kind != token.STRING { |
| - return true |
| + for _, d := range scanCLISource(t).decls { |
| + if d.Kind == "kindPlain" && d.Handler != "" && strings.Contains(d.Pattern, "/a/{sqid}/billing/") { |
| + out[d.Pattern] = d.Handler |
| } |
| - pattern, err := strconv.Unquote(lit.Value) |
| - if err != nil || !strings.Contains(pattern, "/a/{sqid}/billing/") { |
| - return true |
| - } |
| - if h, ok := call.Args[1].(*ast.SelectorExpr); ok { |
| - out[pattern] = h.Sel.Name |
| - } |
| - return true |
| - }) |
| + } |
| return out |
| } |
| @@ -621,7 +598,7 @@ func billingDoorRoutes(t *testing.T, files map[string]*ast.File) map[string]stri |
| // and never through owner or account directly. |
| func TestBillingDoorsEnterThroughBillingOwner(t *testing.T) { |
| _, files := parsePackageSources(t) |
| - routes := billingDoorRoutes(t, files) |
| + routes := billingDoorRoutes(t) |
| if len(routes) < 8 { |
| t.Fatalf("found %d billing door routes, want at least 8: %v", len(routes), routes) |
| } |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index 9d7245717..bf088914f 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -1187,14 +1187,13 @@ func (s *Server) registerDecls(match func(routeDecl) bool) { |
| } |
| switch d.Kind { |
| case kindPlain: |
| - s.registerRoute(d.Pattern, h) |
| + s.registerRoute(d, h) |
| case kindCLI: |
| - s.cliRoute(d.Pattern, d.Allow, h) |
| + s.cliRoute(d, h) |
| case kindCLIJournaled: |
| - refused := d.Refused |
| - s.cliRouteJournaled(d.Pattern, d.Allow, h, func(r *http.Request, p Principal, status int) { refused(s, r, p, status) }) |
| + s.cliRouteJournaled(d, h) |
| case kindCLIScoped: |
| - s.cliScopedRoute(d.Pattern, d.Allow, d.Target, h) |
| + s.cliScopedRoute(d, 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| new file mode 100644 |
| index 000000000..bde3f67ca |
| --- /dev/null |
| +++ b/internal/console/routedecls_test.go |
| @@ -0,0 +1,202 @@ |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +// checkDeclRegistration compares what each configuration registered with |
| +// what routeDecls says it should have. registered[i] is the route patterns |
| +// the server built with cfgs[i] registered. It reports: |
| +// - an empty declaration list; |
| +// - a declaration whose gate is not in routeGates (a group disconnected |
| +// from the gates the matrix flips); |
| +// - a gate in routeGates the matrix never turns on, or never turns off; |
| +// - a declaration no configuration registers (its gate never holds); |
| +// - for each configuration, a declaration whose gate holds that was not |
| +// registered, and a registered pattern no holding declaration names (a |
| +// registration outside the list). |
| +func checkDeclRegistration(decls []routeDecl, cfgs []Config, registered [][]string) []string { |
| + var problems []string |
| + if len(decls) == 0 { |
| + return []string{"routeDecls is empty"} |
| + } |
| + if len(cfgs) != len(registered) { |
| + return []string{fmt.Sprintf("%d configurations but %d registrations", len(cfgs), len(registered))} |
| + } |
| + for _, d := range decls { |
| + if d.Gate != nil && !slices.Contains(routeGates, d.Gate) { |
| + problems = append(problems, fmt.Sprintf("%s: gate %q is not in routeGates", d.Pattern, d.Gate.name)) |
| + } |
| + } |
| + for _, g := range routeGates { |
| + on, off := false, false |
| + for _, c := range cfgs { |
| + if g.holds(c) { |
| + on = true |
| + } else { |
| + off = true |
| + } |
| + } |
| + if !on || !off { |
| + problems = append(problems, fmt.Sprintf("gate %q is never %s in the configuration matrix", g.name, map[bool]string{true: "off", false: "on"}[on])) |
| + } |
| + } |
| + holds := func(d routeDecl, c Config) bool { return d.Gate == nil || d.Gate.holds(c) } |
| + for _, d := range decls { |
| + ever := false |
| + for _, c := range cfgs { |
| + ever = ever || holds(d, c) |
| + } |
| + if !ever { |
| + problems = append(problems, fmt.Sprintf("%s: no configuration registers it (gate %q never holds)", d.Pattern, d.Gate.name)) |
| + } |
| + } |
| + for i, c := range cfgs { |
| + want := map[string]bool{} |
| + for _, d := range decls { |
| + if holds(d, c) { |
| + want[d.Pattern] = true |
| + } |
| + } |
| + got := map[string]bool{} |
| + for _, p := range registered[i] { |
| + got[p] = true |
| + if !want[p] { |
| + problems = append(problems, fmt.Sprintf("configuration %d: %s is registered but no declaration whose gate holds names it", i, p)) |
| + } |
| + } |
| + for p := range want { |
| + if !got[p] { |
| + problems = append(problems, fmt.Sprintf("configuration %d: %s is declared and its gate holds, but it was not registered", i, p)) |
| + } |
| + } |
| + } |
| + slices.Sort(problems) |
| + return problems |
| +} |
| + |
| +// TestRouteDeclsMatchRegistrations: under every configuration of the |
| +// matrix, the routes NewServer registered (claimEntries of kind route) are |
| +// exactly the declarations whose gate holds; every gate is on in one |
| +// configuration and off in another; every declaration is registered in at |
| +// least one. |
| +func TestRouteDeclsMatchRegistrations(t *testing.T) { |
| + if len(routeDecls) == 0 { |
| + t.Fatal("routeDecls is empty") |
| + } |
| + base := func(*testing.T) Config { |
| + return Config{Origin: "https://console.example", Keymail: "https://keymail.example"} |
| + } |
| + demoCfg := func(t *testing.T) Config { |
| + c := demoTestDeploymentConfig(t) |
| + c.Keymail = "https://keymail.example" |
| + return c |
| + } |
| + matrix := []struct { |
| + name string |
| + cfg func(t *testing.T) Config |
| + }{ |
| + {"default", base}, |
| + {"host-claim", func(t *testing.T) Config { c := base(t); c.HostClaim = true; return c }}, |
| + {"host-claim-region-ha", func(t *testing.T) Config { c := base(t); c.HostClaim, c.RegionHA = true, true; return c }}, |
| + {"moves", func(t *testing.T) Config { c := base(t); c.MovesEnabled = true; return c }}, |
| + {"demo", demoCfg}, |
| + // A host-claim console refuses demos at startup (validateDemoConfig), |
| + // so demos and host claims together are a demo box: gateDemo |
| + // holds through Demo.BoxMode while gateNoHostClaim does not. |
| + {"demo-box-host-claim", func(t *testing.T) Config { c := demoCfg(t); c.Demo.Enabled = false; c.HostClaim = true; return c }}, |
| + } |
| + var cfgs []Config |
| + var registered [][]string |
| + for _, tc := range matrix { |
| + cfg := tc.cfg(t) |
| + st := openTestStore(t) |
| + if cfg.Demo.Enabled { |
| + st, _ = demoTestStore(t) |
| + } |
| + if cfg.HostClaim { |
| + var err error |
| + st, err = OpenGated(filepath.Join(t.TempDir(), tc.name+".db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { st.Close() }) |
| + } |
| + s, err := NewServer(cfg, st) |
| + if err != nil { |
| + t.Fatalf("%s: %v", tc.name, err) |
| + } |
| + var got []string |
| + for _, e := range s.claimEntries.snapshot() { |
| + if e.Kind == "route" { |
| + got = append(got, e.Pattern) |
| + } |
| + } |
| + cfgs = append(cfgs, s.cfg) |
| + registered = append(registered, got) |
| + } |
| + if problems := checkDeclRegistration(routeDecls, cfgs, registered); len(problems) > 0 { |
| + for i, tc := range matrix { |
| + t.Logf("configuration %d is %s", i, tc.name) |
| + } |
| + for _, p := range problems { |
| + t.Error(p) |
| + } |
| + } |
| +} |
| + |
| +// TestCheckDeclRegistrationRefuses: the comparison reports each way the |
| +// declarations and the registrations can part company. |
| +func TestCheckDeclRegistrationRefuses(t *testing.T) { |
| + h := func(*Server, http.ResponseWriter, *http.Request) {} |
| + // Off and on for every gate in routeGates. |
| + flip := []Config{{}, {HostClaim: true, RegionHA: true, MovesEnabled: true, Demo: demo.Config{Enabled: true}}} |
| + decls := []routeDecl{ |
| + {Pattern: "GET /a", Handler: h}, |
| + {Pattern: "GET /b", Gate: gateHostClaim, Handler: h}, |
| + } |
| + clean := [][]string{{"GET /a"}, {"GET /a", "GET /b"}} |
| + if p := checkDeclRegistration(decls, flip, clean); len(p) != 0 { |
| + t.Fatalf("matching declarations and registrations reported %q", p) |
| + } |
| + orphan := &routeGate{"orphan", func(Config) bool { return true }} |
| + for _, c := range []struct { |
| + name string |
| + decls []routeDecl |
| + cfgs []Config |
| + registered [][]string |
| + want string |
| + }{ |
| + {"empty list", nil, flip, clean, "routeDecls is empty"}, |
| + {"gate never true", |
| + append(slices.Clone(decls), routeDecl{Pattern: "GET /c", Gate: gateMoves, Handler: h}), |
| + []Config{{}, {HostClaim: true}}, [][]string{{"GET /a"}, {"GET /a", "GET /b"}}, |
| + `GET /c: no configuration registers it (gate "moves" never holds)`}, |
| + {"gate the matrix never flips", |
| + decls, []Config{{}, {HostClaim: true}}, clean, |
| + `gate "moves" is never on in the configuration matrix`}, |
| + {"disconnected group", |
| + append(slices.Clone(decls), routeDecl{Pattern: "GET /d", Gate: orphan, Handler: h}), |
| + flip, [][]string{{"GET /a", "GET /d"}, {"GET /a", "GET /b", "GET /d"}}, |
| + `GET /d: gate "orphan" is not in routeGates`}, |
| + {"direct registration", |
| + decls, flip, [][]string{{"GET /a", "GET /direct"}, {"GET /a", "GET /b"}}, |
| + "configuration 0: GET /direct is registered but no declaration whose gate holds names it"}, |
| + {"declared but not registered", |
| + decls, flip, [][]string{{"GET /a"}, {"GET /a"}}, |
| + "configuration 1: GET /b is declared and its gate holds, but it was not registered"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + p := checkDeclRegistration(c.decls, c.cfgs, c.registered) |
| + if !slices.Contains(p, c.want) { |
| + t.Errorf("want %q among %q", c.want, p) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index b24bc8003..40786de4c 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1182,7 +1182,7 @@ type Server struct { |
| dbf dbForwardTimes |
| // cliRoles is pattern -> allowed roles, recorded by cliRoute as it |
| // registers each /api/cli/ door (authcli.go). Written once, during |
| - // registerCLIRoutes, before the server serves anything, and only read |
| + // registerDecls, before the server serves anything, and only read |
| // afterwards. It exists for two readers: the coverage tests, which |
| // assert that every door names its roles and that the closed ones stay |
| // closed, and the services API, which hands an operator the door list |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index ab86d009e..b849698c9 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -15,6 +15,7 @@ package console |
| import ( |
| "context" |
| + "fmt" |
| "go/ast" |
| "go/parser" |
| "go/token" |
| @@ -407,14 +408,14 @@ var demoOperatorDoors = []string{ |
| } |
| // TestEveryCLIDoorNamesItsRoles is the default-deny guarantee for the |
| -// /api/cli/ half. A door registered with plain mux.HandleFunc would not |
| -// appear in cliRoles at all; a door registered with an accidental empty Set |
| +// /api/cli/ half. A door declared plain would not appear in cliRoles at |
| +// all (and the scan refuses it); a door declared with an accidental empty Set |
| // is unreachable by every service principal. Both are failures worth catching |
| // at build time rather than in production. |
| func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| - // Doors registered only behind a switch. Each is in the source (the |
| - // default-deny scan sees it) and may be absent from cliRoles only while |
| - // its switch is off. The host claim's are closed doors (the zero Set); |
| + // Doors registered only behind a switch. Each is declared with its |
| + // switch's gate (the default-deny scan sees it) and may be absent from |
| + // cliRoles only while that gate is off. The host claim's are closed doors (the zero Set); |
| // CARLOS_MOVES_PHASE1's resolve keeps the Instance role so a service |
| // token meets the family's 404 rather than the role gate's 403. |
| hostClaimDoors := []string{ |
| @@ -430,7 +431,57 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| movesDoors := []string{ |
| "POST /api/cli/apps/{account}/{app}/instances/{host}/move/resolve", |
| } |
| - registered := scanCLISource(t).gated |
| + src := scanCLISource(t) |
| + // gateNamed maps each gate's identifier to the gate, so a declaration's |
| + // Gate as the source spells it can be evaluated against a Config. |
| + gateNamed := map[string]*routeGate{ |
| + "gateDemo": gateDemo, |
| + "gateHostClaim": gateHostClaim, |
| + "gateNoHostClaim": gateNoHostClaim, |
| + "gateRegionHA": gateRegionHA, |
| + "gateMoves": gateMoves, |
| + } |
| + named := map[*routeGate]bool{} |
| + for _, g := range gateNamed { |
| + named[g] = true |
| + } |
| + for _, g := range routeGates { |
| + if !named[g] { |
| + t.Fatalf("gate %q is in routeGates but not named here", g.name) |
| + } |
| + } |
| + if len(gateNamed) != len(routeGates) { |
| + t.Fatalf("this test names %d gates, routeGates holds %d", len(gateNamed), len(routeGates)) |
| + } |
| + cliGate := map[string]string{} |
| + for _, d := range src.decls { |
| + if d.Kind == "kindPlain" { |
| + continue |
| + } |
| + if d.Gate != "" && gateNamed[d.Gate] == nil { |
| + t.Errorf("%s: declared with gate %s, which is not a named gate", d.Pattern, d.Gate) |
| + } |
| + cliGate[d.Pattern] = d.Gate |
| + } |
| + // The switch-only doors carry the gates of their switches. |
| + for _, c := range []struct { |
| + doors []string |
| + gate string |
| + }{ |
| + {hostClaimDoors, "gateHostClaim"}, |
| + {regionHADoors, "gateRegionHA"}, |
| + {movesDoors, "gateMoves"}, |
| + {demoOperatorDoors, "gateNoHostClaim"}, |
| + } { |
| + for _, pattern := range c.doors { |
| + g, ok := cliGate[pattern] |
| + if !ok { |
| + t.Errorf("%s: no cli declaration in routeDecls", pattern) |
| + } else if g != c.gate { |
| + t.Errorf("%s: declared with gate %q, want %s", pattern, g, c.gate) |
| + } |
| + } |
| + } |
| for _, tc := range []struct { |
| name string |
| hostClaim bool |
| @@ -481,69 +532,52 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) { |
| t.Errorf("doors registered with an empty role set: got %q, want %q", empty, wantClosed) |
| } |
| - // Only these named routes may be absent with their switch off. |
| - // All source registrations remain subject to the default-deny |
| - // scan. |
| + // The doors the server recorded are exactly the cli |
| + // declarations whose gate holds for this configuration: a door |
| + // may be absent only while its gate is off. |
| wantRegistered := make(map[string]bool) |
| - for _, pattern := range registered { |
| - wantRegistered[pattern] = true |
| + for pattern, g := range cliGate { |
| + if g == "" || gateNamed[g] != nil && gateNamed[g].holds(s.cfg) { |
| + wantRegistered[pattern] = true |
| + } |
| } |
| - for _, pattern := range hostClaimDoors { |
| - if !wantRegistered[pattern] { |
| - t.Errorf("host claim route missing from source: %s", pattern) |
| + for pattern := range wantRegistered { |
| + if _, ok := s.cliRoles[pattern]; !ok { |
| + t.Errorf("%s: declared, its gate holds, and the server did not record it", pattern) |
| } |
| - if !tc.hostClaim { |
| - delete(wantRegistered, pattern) |
| + } |
| + for pattern := range s.cliRoles { |
| + if !wantRegistered[pattern] { |
| + t.Errorf("%s: the server recorded it, but no cli declaration whose gate holds here names it", pattern) |
| } |
| + } |
| + |
| + // The switches by hand, independent of the gates' own |
| + // predicates: present exactly while the switch is on. |
| + for _, pattern := range hostClaimDoors { |
| set, present := s.cliRoles[pattern] |
| if present != tc.hostClaim || (present && !set.Empty()) { |
| t.Errorf("%s: present=%v empty=%v, want present=%v and no service roles", pattern, present, set.Empty(), tc.hostClaim) |
| } |
| } |
| for _, pattern := range regionHADoors { |
| - if !wantRegistered[pattern] { |
| - t.Errorf("region HA route missing from source: %s", pattern) |
| - } |
| - if !roles { |
| - delete(wantRegistered, pattern) |
| - } |
| set, present := s.cliRoles[pattern] |
| if present != roles || (present && !set.Empty()) { |
| t.Errorf("%s: present=%v empty=%v, want present=%v and no service roles", pattern, present, set.Empty(), roles) |
| } |
| } |
| for _, pattern := range movesDoors { |
| - if !wantRegistered[pattern] { |
| - t.Errorf("moves route missing from source: %s", pattern) |
| - } |
| - if !tc.moves { |
| - delete(wantRegistered, pattern) |
| - } |
| set, present := s.cliRoles[pattern] |
| if present != tc.moves || (present && set.Empty()) { |
| t.Errorf("%s: present=%v empty=%v, want present=%v and a role set", pattern, present, set.Empty(), tc.moves) |
| } |
| } |
| for _, pattern := range demoOperatorDoors { |
| - if !wantRegistered[pattern] { |
| - t.Errorf("demo operator route missing from source: %s", pattern) |
| - } |
| - if tc.hostClaim { |
| - delete(wantRegistered, pattern) |
| - } |
| set, present := s.cliRoles[pattern] |
| if present == tc.hostClaim || (present && !set.Empty()) { |
| t.Errorf("%s: present=%v empty=%v, want present=%v and no service roles", pattern, present, set.Empty(), !tc.hostClaim) |
| } |
| } |
| - for pattern := range wantRegistered { |
| - if _, ok := s.cliRoles[pattern]; !ok { |
| - t.Errorf("%s: the source registers it, the server did not record it", pattern) |
| - } |
| - } |
| - if len(s.cliRoles) != len(wantRegistered) { |
| - t.Errorf("cliRoles holds %d doors, want %d for this flag state", len(s.cliRoles), len(wantRegistered)) |
| - } |
| }) |
| } |
| } |
| @@ -797,41 +831,84 @@ func TestInstanceRoleMatchesTodaysAppTokenReach(t *testing.T) { |
| // |
| // http.ServeMux cannot be enumerated: there is no way to ask a live server |
| // which patterns it holds, so a test that wants to prove EVERY door is gated |
| -// has to read the source that registers them. That is an unusual shape for a |
| -// test and it earns its place — it is the only thing that catches a door |
| -// added tomorrow with plain mux.HandleFunc, which is the exact way |
| -// default-deny would be lost. |
| +// has to read the source that declares them. That is an unusual shape for a |
| +// test and it earns its place: it is the only thing that catches a door |
| +// added tomorrow as a plain declaration, or registered outside the list |
| +// altogether, which are the exact ways default-deny would be lost. |
| // |
| -// It is one go/ast pass over every non-test file in the package, not a scan |
| -// of one file's lines. Both parts of that matter. Package-wide, because the |
| -// services API arrives in a file of its own with a registration function of |
| -// its own, and those are the doors that MINT credentials: a scanner that read |
| -// only authcli.go would report 47 gated doors out of 47 and be silent about |
| -// them. And AST rather than strings, because a registration split across two |
| -// lines escapes a substring match, and because a line scanner keying on |
| -// "s.mux.HandleFunc(" fails the build for any COMMENT that happens to quote |
| -// it — a standing tax on the wording of the most heavily commented function |
| -// in the file. |
| +// Every route is one element of routeDecls (routedecls.go), registered by |
| +// registerDecls through its kind's helper. So the scan reads that composite |
| +// literal: each element's Pattern, Kind, Gate, Allow and handler. And it is |
| +// still one go/ast pass over every non-test file in the package, because |
| +// the list is only the whole story if nothing registers around it: any call |
| +// of registerRoute, cliRoute, cliRouteJournaled or cliScopedRoute outside |
| +// registerDecls and the helpers forwarding to registerRoute, any mux |
| +// registration outside registerRoute, and any routeDecl literal outside |
| +// routeDecls is reported with its position (registrarViolations). AST rather |
| +// than strings, because a declaration split across lines escapes a |
| +// substring match, and because a line scanner keying on "s.mux.HandleFunc(" |
| +// fails the build for any COMMENT that happens to quote it. |
| -// muxDoor is one pattern registered straight onto the mux, with the handler |
| -// expression it was given. |
| +// muxDoor is one plain declaration: its pattern and the handler expression |
| +// the scan can read, a method expression's selector or the function literal |
| +// a Build returns. handler is nil when the declaration's handler is in |
| +// neither shape, which TestAuthCLIFamilyResolvesOnlyPersons refuses. |
| type muxDoor struct { |
| pattern string |
| handler ast.Expr |
| } |
| +// scannedDecl is one element of routeDecls as the source spells it. |
| +type scannedDecl struct { |
| + Pattern string |
| + Kind string // the kind constant's name; kindPlain when unnamed |
| + Gate string // the gate variable's name; "" when unnamed |
| + Handler string // the method a Handler: (*Server).X names, else "" |
| +} |
| + |
| // cliSource is what that single pass yields. |
| type cliSource struct { |
| fset *token.FileSet |
| funcs map[string]*ast.FuncDecl // by bare name |
| - gated []string // patterns registered through cliRoute |
| - plain []muxDoor // patterns registered outside /api/cli/ |
| + gated []string // patterns of cli-kind declarations |
| + plain []muxDoor // plain declarations |
| + decls []scannedDecl // every declaration, in order |
| } |
| -// scanCLISource parses the package and classifies every route registration in |
| -// it. Anything it cannot classify is an error rather than a silent skip: a |
| -// registration this test cannot read is a registration it cannot vouch for. |
| +// routeKindNames are the kinds a declaration may name. |
| +var routeKindNames = map[string]bool{"kindPlain": true, "kindCLI": true, "kindCLIJournaled": true, "kindCLIScoped": true} |
| + |
| +// scanCLISource parses the package and classifies every route declaration |
| +// in it. Anything it cannot classify is an error rather than a silent skip: |
| +// a declaration this test cannot read is a declaration it cannot vouch for. |
| +// A scan that finds no declarations at all fails before anything else. |
| func scanCLISource(t *testing.T) *cliSource { |
| + t.Helper() |
| + fset, files := parseConsoleSource(t) |
| + src := &cliSource{fset: fset, funcs: map[string]*ast.FuncDecl{}} |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok && fd.Name != nil && fd.Body != nil { |
| + src.funcs[fd.Name.Name] = fd |
| + } |
| + } |
| + } |
| + violations, _ := registrarViolations(fset, files) |
| + for _, v := range violations { |
| + t.Error(v) |
| + } |
| + lit := findRouteDecls(t, fset, files) |
| + for _, el := range lit.Elts { |
| + src.readDecl(t, el) |
| + } |
| + if len(src.decls) == 0 { |
| + t.Fatal("routeDecls holds no declarations; the scan has nothing to vouch for") |
| + } |
| + return src |
| +} |
| + |
| +// parseConsoleSource parses every non-test file of the package. |
| +func parseConsoleSource(t *testing.T) (*token.FileSet, []*ast.File) { |
| t.Helper() |
| fset := token.NewFileSet() |
| pkgs, err := parser.ParseDir(fset, ".", func(fi os.FileInfo) bool { |
| @@ -844,95 +921,292 @@ func scanCLISource(t *testing.T) *cliSource { |
| if !ok { |
| t.Fatal("package console not found by the parser") |
| } |
| - src := &cliSource{fset: fset, funcs: map[string]*ast.FuncDecl{}} |
| - for _, f := range pkg.Files { |
| - for _, d := range f.Decls { |
| - if fd, ok := d.(*ast.FuncDecl); ok && fd.Name != nil && fd.Body != nil { |
| - src.funcs[fd.Name.Name] = fd |
| - } |
| - } |
| + names := make([]string, 0, len(pkg.Files)) |
| + for name := range pkg.Files { |
| + names = append(names, name) |
| } |
| - for _, f := range pkg.Files { |
| + sort.Strings(names) |
| + files := make([]*ast.File, 0, len(names)) |
| + for _, name := range names { |
| + files = append(files, pkg.Files[name]) |
| + } |
| + return fset, files |
| +} |
| + |
| +// findRouteDecls returns the routeDecls composite literal. It fails if |
| +// there is none, if there are two, if anything assigns to routeDecls or |
| +// takes its address, or if a routeDecl literal appears anywhere else: a |
| +// declaration outside the list is a route the scan would not see. |
| +func findRouteDecls(t *testing.T, fset *token.FileSet, files []*ast.File) *ast.CompositeLit { |
| + t.Helper() |
| + var lit *ast.CompositeLit |
| + for _, f := range files { |
| for _, d := range f.Decls { |
| - fd, ok := d.(*ast.FuncDecl) |
| - if !ok || fd.Body == nil { |
| + gd, ok := d.(*ast.GenDecl) |
| + if !ok || gd.Tok != token.VAR { |
| continue |
| } |
| - // cliRoute is the gate itself. Its own mux.HandleFunc call is |
| - // the one registration in the package whose pattern is a |
| - // variable rather than a literal, and it is the mechanism these |
| - // tests are asserting ABOUT — reading it as a door would be |
| - // reading the lock as a way in. It is the only exemption. |
| - if fd.Name != nil && (fd.Name.Name == "cliRoute" || fd.Name.Name == "cliScopedRoute" || fd.Name.Name == "cliRouteJournaled" || fd.Name.Name == "registerRoute") { |
| - continue |
| + for _, spec := range gd.Specs { |
| + vs := spec.(*ast.ValueSpec) |
| + for i, name := range vs.Names { |
| + if name.Name != "routeDecls" { |
| + continue |
| + } |
| + if lit != nil { |
| + t.Fatalf("routeDecls declared twice, again at %s", fset.Position(name.Pos())) |
| + } |
| + if i >= len(vs.Values) { |
| + t.Fatalf("routeDecls at %s has no literal value", fset.Position(name.Pos())) |
| + } |
| + cl, ok := vs.Values[i].(*ast.CompositeLit) |
| + if !ok { |
| + t.Fatalf("routeDecls at %s is not a composite literal, so this test cannot read it", fset.Position(name.Pos())) |
| + } |
| + lit = cl |
| + } |
| } |
| - src.inspect(t, fd.Body) |
| } |
| } |
| - return src |
| + if lit == nil { |
| + t.Fatal("no routeDecls composite literal in the package; every route is declared there") |
| + } |
| + elements := map[ast.Node]bool{lit: true} |
| + for _, el := range lit.Elts { |
| + elements[el] = true |
| + } |
| + for _, f := range files { |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.CompositeLit: |
| + if !elements[n] && n.Type != nil && mentionsIdent(n.Type, "routeDecl") { |
| + t.Errorf("a routeDecl literal outside routeDecls at %s; every route is declared in routeDecls", fset.Position(n.Pos())) |
| + } |
| + case *ast.AssignStmt: |
| + for _, lhs := range n.Lhs { |
| + if mentionsIdent(lhs, "routeDecls") { |
| + t.Errorf("routeDecls is assigned at %s; it is written once, by its declaration", fset.Position(n.Pos())) |
| + } |
| + } |
| + case *ast.UnaryExpr: |
| + if n.Op == token.AND && mentionsIdent(n.X, "routeDecls") { |
| + t.Errorf("routeDecls has its address taken at %s", fset.Position(n.Pos())) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + return lit |
| } |
| -func (src *cliSource) inspect(t *testing.T, body *ast.BlockStmt) { |
| +// mentionsIdent reports whether name appears as an identifier in e. |
| +func mentionsIdent(e ast.Node, name string) bool { |
| + found := false |
| + ast.Inspect(e, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && id.Name == name { |
| + found = true |
| + } |
| + return !found |
| + }) |
| + return found |
| +} |
| + |
| +// readDecl classifies one element of routeDecls. |
| +func (src *cliSource) readDecl(t *testing.T, el ast.Expr) { |
| t.Helper() |
| - ast.Inspect(body, func(n ast.Node) bool { |
| - call, ok := n.(*ast.CallExpr) |
| + at := src.fset.Position(el.Pos()) |
| + cl, ok := el.(*ast.CompositeLit) |
| + if !ok { |
| + t.Errorf("routeDecls element at %s is not a literal, so this test cannot classify it", at) |
| + return |
| + } |
| + fields := map[string]ast.Expr{} |
| + for _, e := range cl.Elts { |
| + kv, ok := e.(*ast.KeyValueExpr) |
| if !ok { |
| - return true |
| + t.Errorf("routeDecls element at %s has an unkeyed field, so this test cannot classify it", at) |
| + return |
| } |
| - sel, ok := call.Fun.(*ast.SelectorExpr) |
| + id, ok := kv.Key.(*ast.Ident) |
| if !ok { |
| - return true |
| + t.Errorf("routeDecls element at %s has a field key this test cannot read", at) |
| + return |
| } |
| - switch sel.Sel.Name { |
| - case "cliRoute", "cliScopedRoute", "cliRouteJournaled": |
| - // cliScopedRoute (teamdoors.go) is the team role's registration: |
| - // the same gate with a scope target between the Set and the |
| - // handler. cliRouteJournaled is cliRoute with a hook told of |
| - // each service credential the gate refuses (the interactive |
| - // door's journal line). All are gated doors to this scan. |
| - want := 3 |
| - if sel.Sel.Name != "cliRoute" { |
| - want = 4 |
| - } |
| - if len(call.Args) != want { |
| - t.Errorf("%s at %s takes %d arguments; this test expects %d", |
| - sel.Sel.Name, src.fset.Position(call.Pos()), len(call.Args), want) |
| - return true |
| - } |
| - pattern, ok := stringLit(call.Args[0]) |
| + fields[id.Name] = kv.Value |
| + } |
| + pattern, ok := stringLit(fields["Pattern"]) |
| + if !ok { |
| + t.Errorf("routeDecls element at %s: pattern is not a string literal, so this test cannot classify it", at) |
| + return |
| + } |
| + d := scannedDecl{Pattern: pattern, Kind: "kindPlain"} |
| + if k, ok := fields["Kind"]; ok { |
| + id, isIdent := k.(*ast.Ident) |
| + if !isIdent || !routeKindNames[id.Name] { |
| + t.Errorf("%s at %s: Kind is not one of the route kinds, so this test cannot classify it", pattern, at) |
| + return |
| + } |
| + d.Kind = id.Name |
| + } |
| + if g, ok := fields["Gate"]; ok { |
| + id, isIdent := g.(*ast.Ident) |
| + if !isIdent { |
| + t.Errorf("%s at %s: Gate is not a named gate, so this test cannot classify it", pattern, at) |
| + return |
| + } |
| + d.Gate = id.Name |
| + } |
| + var handler ast.Expr |
| + h, hasHandler := fields["Handler"] |
| + b, hasBuild := fields["Build"] |
| + if hasHandler == hasBuild { |
| + t.Errorf("%s at %s: sets %s of Handler and Build; a declaration sets exactly one", pattern, at, map[bool]string{true: "both", false: "neither"}[hasHandler]) |
| + } |
| + if hasHandler { |
| + if sel, ok := h.(*ast.SelectorExpr); ok && isServerMethodExpr(sel.X) { |
| + handler = sel |
| + d.Handler = sel.Sel.Name |
| + } |
| + } |
| + if hasBuild && !hasHandler { |
| + handler = buildLiteral(b) |
| + } |
| + cli := d.Kind != "kindPlain" |
| + _, hasAllow := fields["Allow"] |
| + _, hasTarget := fields["Target"] |
| + _, hasRefused := fields["Refused"] |
| + 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) |
| + } |
| + if !hasAllow { |
| + t.Errorf("%s at %s: a %s door names no roles; write Allow (svcrole.Set{} for a closed door)", pattern, at, d.Kind) |
| + } |
| + if hasTarget != (d.Kind == "kindCLIScoped") { |
| + t.Errorf("%s at %s: Target belongs to kindCLIScoped doors only, and every one of them names it", pattern, at) |
| + } |
| + if hasRefused != (d.Kind == "kindCLIJournaled") { |
| + t.Errorf("%s at %s: Refused belongs to kindCLIJournaled doors only, and every one of them names it", pattern, at) |
| + } |
| + } else { |
| + // The bypass guard: an /api/cli/ door declared plain names no roles |
| + // and is therefore gated by nothing at all. |
| + if strings.Contains(pattern, "/api/cli/") { |
| + t.Errorf("%s at %s: declared kindPlain, bypassing the role gate", 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) |
| + } |
| + src.plain = append(src.plain, muxDoor{pattern: pattern, handler: handler}) |
| + } |
| + src.decls = append(src.decls, d) |
| +} |
| + |
| +// isServerMethodExpr reports whether x is (*Server), the receiver of a |
| +// method expression. |
| +func isServerMethodExpr(x ast.Expr) bool { |
| + p, ok := x.(*ast.ParenExpr) |
| + if !ok { |
| + return false |
| + } |
| + star, ok := p.X.(*ast.StarExpr) |
| + if !ok { |
| + return false |
| + } |
| + id, ok := star.X.(*ast.Ident) |
| + return ok && id.Name == "Server" |
| +} |
| + |
| +// buildLiteral returns the function literal a Build returns, when the |
| +// Build is exactly `func(s *Server) http.HandlerFunc { return func(...) {...} }`, |
| +// and nil otherwise. |
| +func buildLiteral(b ast.Expr) ast.Expr { |
| + fl, ok := b.(*ast.FuncLit) |
| + if !ok || len(fl.Body.List) != 1 { |
| + return nil |
| + } |
| + ret, ok := fl.Body.List[0].(*ast.ReturnStmt) |
| + if !ok || len(ret.Results) != 1 { |
| + return nil |
| + } |
| + inner, ok := ret.Results[0].(*ast.FuncLit) |
| + if !ok { |
| + return nil |
| + } |
| + return inner |
| +} |
| + |
| +// registrationHelpers are the functions that put a route on the mux. |
| +var registrationHelpers = map[string]bool{"registerRoute": true, "cliRoute": true, "cliRouteJournaled": true, "cliScopedRoute": true} |
| + |
| +// registrarSites is where each helper may be named: registerDecls calls |
| +// every helper (THE loop), and the cli helpers forward to registerRoute. |
| +// These are the only exemptions; they are the mechanism the scans assert |
| +// ABOUT, and reading them as doors would be reading the lock as a way in. |
| +var registrarSites = map[string]map[string]bool{ |
| + "registerDecls": {"registerRoute": true, "cliRoute": true, "cliRouteJournaled": true, "cliScopedRoute": true}, |
| + "cliRoute": {"registerRoute": true}, |
| + "cliRouteJournaled": {"registerRoute": true}, |
| + "cliScopedRoute": {"registerRoute": true}, |
| +} |
| + |
| +// registrarViolations reports, with its position, every mention of a |
| +// registration helper outside registrarSites (a call, a method value or a |
| +// method expression alike) and every mux registration outside |
| +// registerRoute. muxSites counts registerRoute's own mux registrations, so |
| +// a caller can tell an empty walk from a clean one. |
| +func registrarViolations(fset *token.FileSet, files []*ast.File) (violations []string, muxSites int) { |
| + for _, f := range files { |
| + var enclosing *ast.FuncDecl |
| + var visit func(n ast.Node) bool |
| + visit = func(n ast.Node) bool { |
| + sel, ok := n.(*ast.SelectorExpr) |
| if !ok { |
| - t.Errorf("%s at %s: pattern is not a string literal, so this test cannot classify it", |
| - sel.Sel.Name, src.fset.Position(call.Pos())) |
| return true |
| } |
| - src.gated = append(src.gated, pattern) |
| - if !strings.Contains(pattern, "/api/cli/") { |
| - t.Errorf("%s: registered through %s but is not under /api/cli/", pattern, sel.Sel.Name) |
| - } |
| - case "Handle", "HandleFunc", "registerRoute": |
| - pattern, isLit := stringLit(call.Args[0]) |
| - // The bypass guard, and the reason this pass is package-wide: an |
| - // /api/cli/ door registered anywhere but cliRoute names no roles |
| - // and is therefore gated by nothing at all. |
| - if isLit && strings.Contains(pattern, "/api/cli/") { |
| - t.Errorf("%s at %s: registered with %s, bypassing the role gate", |
| - pattern, src.fset.Position(call.Pos()), sel.Sel.Name) |
| - return true |
| + name := sel.Sel.Name |
| + site, onServer := "", false |
| + if enclosing != nil { |
| + site, onServer = enclosing.Name.Name, receiverIsServer(enclosing) |
| } |
| - if sel.Sel.Name != "registerRoute" && !isMuxRegistration(sel) { |
| - return true |
| + if registrationHelpers[name] && !(onServer && registrarSites[site][name]) { |
| + violations = append(violations, fmt.Sprintf("%s outside registerDecls and the helpers forwarding to registerRoute: %s", name, fset.Position(sel.Pos()))) |
| } |
| - if !isLit { |
| - t.Errorf("mux.%s at %s: pattern is not a string literal, so this test cannot classify it", |
| - sel.Sel.Name, src.fset.Position(call.Pos())) |
| - return true |
| + if (name == "Handle" || name == "HandleFunc") && isMuxRegistration(sel) { |
| + if onServer && site == "registerRoute" { |
| + muxSites++ |
| + } else { |
| + violations = append(violations, fmt.Sprintf("mux registration outside registerRoute: %s", fset.Position(sel.Pos()))) |
| + } |
| } |
| - if len(call.Args) == 2 { |
| - src.plain = append(src.plain, muxDoor{pattern: pattern, handler: call.Args[1]}) |
| + return true |
| + } |
| + for _, d := range f.Decls { |
| + enclosing = nil |
| + if fd, ok := d.(*ast.FuncDecl); ok { |
| + enclosing = fd |
| + if fd.Body != nil { |
| + ast.Inspect(fd.Body, visit) |
| + } |
| + continue |
| } |
| + ast.Inspect(d, visit) |
| } |
| - return true |
| - }) |
| + } |
| + return violations, muxSites |
| +} |
| + |
| +// receiverIsServer reports whether fd is a method on *Server. |
| +func receiverIsServer(fd *ast.FuncDecl) bool { |
| + if fd.Recv == nil || len(fd.Recv.List) != 1 { |
| + return false |
| + } |
| + star, ok := fd.Recv.List[0].Type.(*ast.StarExpr) |
| + if !ok { |
| + return false |
| + } |
| + id, ok := star.X.(*ast.Ident) |
| + return ok && id.Name == "Server" |
| } |
| // isMuxRegistration reports whether a selector is a call on something's `mux` |
| @@ -964,8 +1238,8 @@ func stringLit(e ast.Expr) (string, bool) { |
| // construction; this makes it true by test, so the day someone reaches for |
| // CLIPrincipal over there the build says so. |
| // |
| -// It asserts over EVERY door the package registers outside /api/cli/, not |
| -// just the CLI family, because the property is the same one everywhere: a |
| +// It asserts over EVERY plain declaration in routeDecls, not just the CLI |
| +// family, because the property is the same one everywhere: a |
| // handler the role gate does not stand in front of must not be resolving a |
| // service credential. A browser page passes it trivially, which is the |
| // correct answer for a browser page. |
| @@ -975,12 +1249,10 @@ func TestAuthCLIFamilyResolvesOnlyPersons(t *testing.T) { |
| switch h := d.handler.(type) { |
| case *ast.SelectorExpr: |
| assertResolvesOnlyPersons(t, src, d.pattern, src.funcs[h.Sel.Name]) |
| - case *ast.Ident: |
| - assertResolvesOnlyPersons(t, src, d.pattern, src.funcs[h.Name]) |
| case *ast.FuncLit: |
| assertBodyResolvesOnlyPersons(t, src, d.pattern, h.Body) |
| default: |
| - t.Errorf("%s: handler is neither a named function nor a literal; this test cannot see inside it", d.pattern) |
| + t.Errorf("%s: handler is neither a (*Server) method expression nor a Build returning a function literal; this test cannot see inside it", d.pattern) |
| } |
| } |
| @@ -1006,7 +1278,7 @@ func TestAuthCLIFamilyResolvesOnlyPersons(t *testing.T) { |
| "POST /auth/cli/accounts", |
| } { |
| if !seen[pattern] { |
| - t.Errorf("%s: not found as a plain mux registration; either it moved or the walker is broken", pattern) |
| + t.Errorf("%s: not found as a plain declaration; either it moved or the walker is broken", pattern) |
| } |
| } |
| @@ -1329,15 +1601,14 @@ func TestCLIRouteUnauthorizedMatchesCLIUser(t *testing.T) { |
| func TestPrincipalReachesTheHandler(t *testing.T) { |
| fx := newConsoleFixture(t) |
| got := make(chan Principal, 1) |
| - fx.srv.cliRoute("GET /api/cli/probe", svcrole.Allow(svcrole.Publish), |
| - func(w http.ResponseWriter, r *http.Request) { |
| - p, ok := principalFrom(r.Context()) |
| - if !ok { |
| - t.Error("principalFrom: no principal on a cliRoute request") |
| - } |
| - got <- p |
| - w.WriteHeader(http.StatusNoContent) |
| - }) |
| + fx.srv.cliRoute(routeDecl{Pattern: "GET /api/cli/probe", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish)}, func(w http.ResponseWriter, r *http.Request) { |
| + p, ok := principalFrom(r.Context()) |
| + if !ok { |
| + t.Error("principalFrom: no principal on a cliRoute request") |
| + } |
| + got <- p |
| + w.WriteHeader(http.StatusNoContent) |
| + }) |
| tok := serviceToken(t, fx.st, OpsAccountID, "shipper", "kass", svcrole.Publish) |
| if status, body := getRaw(t, fx.ts.URL+"/api/cli/probe", tok); status != http.StatusNoContent { |
diff --git a/internal/console/teamdoors.go b/internal/console/teamdoors.go| index 22031d2bf..45983a6ab 100644 |
| --- a/internal/console/teamdoors.go |
| +++ b/internal/console/teamdoors.go |
| @@ -73,7 +73,8 @@ const teamScopeBodyMax = configPutMaxBytes + 1 |
| // principal after the role gate and the app binding, before the handler. |
| // It is the only registration that admits Team: cliRoute panics on a Set |
| // that permits it, and svcrole.Allow and Exactly refuse to build one. |
| -func (s *Server) cliScopedRoute(pattern string, allow svcrole.Set, target scopeTarget, h http.HandlerFunc) { |
| +func (s *Server) cliScopedRoute(d routeDecl, h http.HandlerFunc) { |
| + pattern, allow, target := d.Pattern, d.Allow, d.Target |
| if allow.Permits(svcrole.Team) { |
| panic("console: cliScopedRoute " + pattern + ": allow already permits team; pass the non-team set") |
| } |
| @@ -82,7 +83,7 @@ func (s *Server) cliScopedRoute(pattern string, allow svcrole.Set, target scopeT |
| s.cliRoles = map[string]svcrole.Set{} |
| } |
| s.cliRoles[pattern] = set |
| - s.registerRoute(pattern, s.cliGate(set, func(w http.ResponseWriter, r *http.Request) { |
| + s.registerRoute(d, s.cliGate(set, func(w http.ResponseWriter, r *http.Request) { |
| p, _ := principalFrom(r.Context()) |
| if p.Kind == PrincipalService && p.Role == svcrole.Team { |
| tv, ok := s.teamInScope(w, r, p, target) |
diff --git a/internal/console/teamdoors_test.go b/internal/console/teamdoors_test.go| index aaf771069..ea973e529 100644 |
| --- a/internal/console/teamdoors_test.go |
| +++ b/internal/console/teamdoors_test.go |
| @@ -151,10 +151,10 @@ func TestCLIRouteRefusesATeamSet(t *testing.T) { |
| f func() |
| }{ |
| {"cliRoute", func() { |
| - s.cliRoute("GET /api/cli/probe-team", svcrole.Scoped(svcrole.Allow(svcrole.Operate)), func(http.ResponseWriter, *http.Request) {}) |
| + s.cliRoute(routeDecl{Pattern: "GET /api/cli/probe-team", Kind: kindCLI, Allow: svcrole.Scoped(svcrole.Allow(svcrole.Operate))}, func(http.ResponseWriter, *http.Request) {}) |
| }}, |
| {"cliScopedRoute", func() { |
| - s.cliScopedRoute("GET /api/cli/probe-team-2", svcrole.Scoped(svcrole.Allow(svcrole.Operate)), scopeList, func(http.ResponseWriter, *http.Request) {}) |
| + s.cliScopedRoute(routeDecl{Pattern: "GET /api/cli/probe-team-2", Kind: kindCLIScoped, Allow: svcrole.Scoped(svcrole.Allow(svcrole.Operate)), Target: scopeList}, func(http.ResponseWriter, *http.Request) {}) |
| }}, |
| } { |
| func() { |