| 1 | package memoriatest |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "go/ast" |
| 6 | "go/parser" |
| 7 | "go/token" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | ) |
| 14 | |
| 15 | // Gate 17, spec §10: no route exists that the spec has not listed. |
| 16 | // |
| 17 | // This is the regression gate for the sibling-facing push surface draft 1 |
| 18 | // shipped by accident, and — since decision 14 — the gate that makes |
| 19 | // "memoria is a search page, not a chat" enforceable rather than prose. §10 |
| 20 | // had claimed this gate since draft 1 while nothing walked the router. |
| 21 | // |
| 22 | // It keys on METHOD and path together, because that is what §10's list |
| 23 | // declares. The first version keyed on path alone, and a review |
| 24 | // mutation-tested it and found five idioms that walked straight past: |
| 25 | // r.Route("/chat", …) with a declared "/" inside it; r.With(mw).Post, |
| 26 | // where the receiver is a call and not an identifier; r.Delete on a path |
| 27 | // declared only for GET; r.Handle("/"), which is every method at once; and |
| 28 | // worst, mux.HandleFunc("/documents", …), which serves a DECLARED path |
| 29 | // while bypassing requireSession entirely. Path-only blessed all five. |
| 30 | // |
| 31 | // The two namespaces are kept apart on purpose. A chi registration carries |
| 32 | // its method in the call (r.Get); an http.ServeMux pattern carries it in |
| 33 | // the string ("GET /static/"). Mixing them let "/" bless both mux.Handle |
| 34 | // and a chi r.Post at once. |
| 35 | // |
| 36 | // Known limits, stated because a gate's honest scope is part of it: |
| 37 | // - A route registered by a helper in a package this walk does not cover |
| 38 | // is not seen. The walk covers internal/memoria and cmd. |
| 39 | // - Chi's Route nests patterns; this checks outer and inner patterns |
| 40 | // against one flat list, so adopting Route means adding its relative |
| 41 | // segments here. That errs toward failing, which is the right direction. |
| 42 | // - A receiver renamed away from r/mux is not seen. The declared list is |
| 43 | // the real control; this walk is only the finder. |
| 44 | // |
| 45 | // MUTATION-TESTED 2026-09-05, each reverted. The first three were on the |
| 46 | // path-only version and still hold; the last five are the ones a review |
| 47 | // found green and this version now catches: |
| 48 | // |
| 49 | // r.Post("/chat", a.index) -> undeclared route: POST /chat |
| 50 | // r.Get(root, a.index) with root a var -> route pattern is not a literal |
| 51 | // walk root pointed at an empty directory -> seen == 0 |
| 52 | // r.Route("/chat", func(r chi.Router){...}) -> undeclared route: ANY /chat |
| 53 | // r.With(mw).Post("/chat", a.index) -> undeclared route: POST /chat |
| 54 | // r.Delete("/documents/{id}", a.index) -> undeclared route: DELETE /documents/{id} |
| 55 | // r.Handle("/", h) -> undeclared route: ANY / |
| 56 | // mux.HandleFunc("/documents", a.index) -> undeclared mux pattern: /documents |
| 57 | func TestNoUndeclaredRoutes(t *testing.T) { |
| 58 | // The list is at package scope — see declaredChiRoutes. |
| 59 | declaredChi := declaredChiRoutes |
| 60 | // http.ServeMux patterns, verbatim — these are mounts, and the method |
| 61 | // (where there is one) lives inside the string. |
| 62 | declaredMux := map[string]bool{ |
| 63 | // Delegated API: independent bearer verifier and current Home/local |
| 64 | // admission. Spec's Agent access addendum declares both mounts. |
| 65 | "/api/v1/operations": true, |
| 66 | "/api/v1/operations/": true, |
| 67 | "GET /static/credits.css": true, |
| 68 | "GET /static/": true, |
| 69 | "GET /static/estilo/fonts/v1/": true, |
| 70 | // The sign-in door's sky layers: public artwork, no session, |
| 71 | // the same bargain as the font. TestSkyRouteIsEstilosPrefix |
| 72 | // keeps the literal equal to sky.Prefix. |
| 73 | "GET /static/estilo/sky/v3/": true, |
| 74 | // The app switcher's tile icons: public artwork again. |
| 75 | // TestBrandRouteIsEstilosPrefix keeps the literal equal to |
| 76 | // brand.Prefix. |
| 77 | "GET /static/estilo/brand/": true, |
| 78 | // Team mode's readiness probe (team_config.go): public and |
| 79 | // no-store, {"team_mode":false} with team mode off, and in team |
| 80 | // mode {team_mode, consumer, roster} with no account data. |
| 81 | "GET /api/team": true, |
| 82 | "/": true, |
| 83 | "/auth/": true, |
| 84 | "POST /signout": true, |
| 85 | } |
| 86 | // Router method -> index of the pattern argument. Handle, HandleFunc, |
| 87 | // Mount and Route bind every method, so they read as ANY. |
| 88 | patternArg := map[string]int{ |
| 89 | "Get": 0, "Post": 0, "Put": 0, "Patch": 0, "Delete": 0, |
| 90 | "Head": 0, "Options": 0, "Connect": 0, "Trace": 0, |
| 91 | "Handle": 0, "HandleFunc": 0, "Mount": 0, "Route": 0, |
| 92 | "Method": 1, "MethodFunc": 1, |
| 93 | } |
| 94 | anyMethod := map[string]bool{ |
| 95 | "Handle": true, "HandleFunc": true, "Mount": true, "Route": true, |
| 96 | } |
| 97 | |
| 98 | // chi's chaining constructors, and only these. Following an arbitrary |
| 99 | // selector chain instead was the first attempt and it was wrong: `r` is |
| 100 | // also the conventional name for an *http.Request, so |
| 101 | // r.URL.Query().Get("err") resolved to "r" and reported the query |
| 102 | // parameter as an undeclared GET route. Two real handler lines, caught |
| 103 | // by running it. |
| 104 | chainThrough := map[string]bool{"With": true, "Group": true, "Route": true} |
| 105 | |
| 106 | // rootReceiver resolves r.With(mw).Post back to r, and refuses to |
| 107 | // resolve anything else, so the walk sees chi's standard middleware |
| 108 | // spelling without inventing routes out of request accessors. |
| 109 | var rootReceiver func(ast.Expr) string |
| 110 | rootReceiver = func(e ast.Expr) string { |
| 111 | switch v := e.(type) { |
| 112 | case *ast.Ident: |
| 113 | return v.Name |
| 114 | case *ast.CallExpr: |
| 115 | if s, ok := v.Fun.(*ast.SelectorExpr); ok && chainThrough[s.Sel.Name] { |
| 116 | return rootReceiver(s.X) |
| 117 | } |
| 118 | } |
| 119 | return "" |
| 120 | } |
| 121 | |
| 122 | var problems []string |
| 123 | seen := 0 |
| 124 | |
| 125 | inspect := func(path string, fset *token.FileSet, file *ast.File) { |
| 126 | ast.Inspect(file, func(n ast.Node) bool { |
| 127 | call, ok := n.(*ast.CallExpr) |
| 128 | if !ok { |
| 129 | return true |
| 130 | } |
| 131 | sel, ok := call.Fun.(*ast.SelectorExpr) |
| 132 | if !ok { |
| 133 | return true |
| 134 | } |
| 135 | recv := rootReceiver(sel.X) |
| 136 | if recv != "r" && recv != "mux" { |
| 137 | return true |
| 138 | } |
| 139 | idx, ok := patternArg[sel.Sel.Name] |
| 140 | if !ok || len(call.Args) <= idx { |
| 141 | return true |
| 142 | } |
| 143 | seen++ |
| 144 | line := fset.Position(call.Pos()).Line |
| 145 | lit, ok := call.Args[idx].(*ast.BasicLit) |
| 146 | if !ok || lit.Kind != token.STRING { |
| 147 | problems = append(problems, fmt.Sprintf( |
| 148 | "%s:%d: route pattern is not a literal, so this gate cannot read it", |
| 149 | path, line)) |
| 150 | return true |
| 151 | } |
| 152 | pattern, err := strconv.Unquote(lit.Value) |
| 153 | if err != nil { |
| 154 | problems = append(problems, fmt.Sprintf( |
| 155 | "%s:%d: unreadable route pattern %s", path, line, lit.Value)) |
| 156 | return true |
| 157 | } |
| 158 | if recv == "mux" { |
| 159 | if !declaredMux[pattern] { |
| 160 | problems = append(problems, fmt.Sprintf( |
| 161 | "%s:%d: undeclared mux pattern: %s", path, line, pattern)) |
| 162 | } |
| 163 | return true |
| 164 | } |
| 165 | method := strings.ToUpper(sel.Sel.Name) |
| 166 | if anyMethod[sel.Sel.Name] { |
| 167 | method = "ANY" |
| 168 | } |
| 169 | if key := method + " " + pattern; !declaredChi[key] { |
| 170 | problems = append(problems, fmt.Sprintf( |
| 171 | "%s:%d: undeclared route: %s", path, line, key)) |
| 172 | } |
| 173 | return true |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | walk := func(root string) error { |
| 178 | return filepath.Walk(root, func(p string, info os.FileInfo, err error) error { |
| 179 | if err != nil { |
| 180 | return err |
| 181 | } |
| 182 | if info.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { |
| 183 | return nil |
| 184 | } |
| 185 | fset := token.NewFileSet() |
| 186 | file, err := parser.ParseFile(fset, p, nil, parser.SkipObjectResolution) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | inspect(p, fset, file) |
| 191 | return nil |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | for _, root := range []string{ |
| 196 | filepath.Join("..", "memoria"), |
| 197 | filepath.Join("..", "..", "cmd"), |
| 198 | } { |
| 199 | if err := walk(root); err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // A count that fails is not a count of zero (AGENTS.md). If the walk |
| 205 | // found no registrations at all then the finder is broken, and a green |
| 206 | // gate over an empty set is this codebase's worst failure shape. |
| 207 | // |
| 208 | // Note what this does and does not prove: cmd/ registers no routes |
| 209 | // today, so emptying either root alone still trips it. It is a smoke |
| 210 | // check on the finder, not a census of what the finder should see. |
| 211 | if seen == 0 { |
| 212 | t.Fatal("found no route registrations at all: the walk is broken, not the app clean") |
| 213 | } |
| 214 | |
| 215 | for _, p := range problems { |
| 216 | t.Error(p) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // Production mounts auth through MountAuth, which is where the sign-in |
| 221 | // guard is attached. |
| 222 | // |
| 223 | // An adversarial pass mutated `main.go` to build its own chi router, |
| 224 | // register `POST /auth/begin` on it bare, and hand it to the mux — and |
| 225 | // every test stayed green, because the tests build their own app and |
| 226 | // nothing observed how production wires itself. Gate 17's route walk did |
| 227 | // not catch it either: it follows receivers named r and mux, and states |
| 228 | // that limit honestly. |
| 229 | // |
| 230 | // This is a source check and it buys one thing: main cannot quietly stop |
| 231 | // going through MountAuth. It does not prove the guard works — gate 33 |
| 232 | // does that — only that production is the thing gate 33 tested. |
| 233 | // |
| 234 | // MUTATION-TESTED 2026-09-05: deleting either call from main.go fails |
| 235 | // here. Reverted. |
| 236 | func TestProductionMountsAuthThroughTheGuardedPath(t *testing.T) { |
| 237 | src, err := os.ReadFile(filepath.Join("..", "..", "cmd", "memoria", "main.go")) |
| 238 | if err != nil { |
| 239 | t.Fatalf("read main.go: %v", err) |
| 240 | } |
| 241 | for _, want := range []string{"UseAuth(", "MountAuth("} { |
| 242 | if !strings.Contains(string(src), want) { |
| 243 | t.Errorf("cmd/memoria/main.go does not call %s — auth is being wired "+ |
| 244 | "some other way, and the sign-in guard is attached inside "+ |
| 245 | "MountAuth", want) |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // declaredChiRoutes is every chi registration, as METHOD + pattern. |
| 251 | // |
| 252 | // Package scope, 2026-09-27, so a second gate can walk it: the footer's |
| 253 | // egress claim must be right on EVERY page, and a hand-written list of |
| 254 | // pages is how the first build of §8.9 missed the footer altogether. |
| 255 | // TestNoUndeclaredRoutes is unchanged in behaviour. |
| 256 | // |
| 257 | // §9.1's /query is deliberately absent: the app serves GET / and it is the |
| 258 | // spec that is wrong, which §8.4 records. Adding to this list is a |
| 259 | // decision, which is the point of it being a list. |
| 260 | var declaredChiRoutes = map[string]bool{ |
| 261 | "POST /native/request": true, |
| 262 | "POST /native/exchange": true, |
| 263 | "GET /native/start": true, |
| 264 | "GET /native/authorize": true, |
| 265 | "POST /native/authorize": true, |
| 266 | "GET /api/native/session": true, |
| 267 | "POST /api/native/notes": true, |
| 268 | "POST /api/native/search": true, |
| 269 | "GET /help/open-source": true, |
| 270 | "GET /signin": true, |
| 271 | "GET /signin/local": true, |
| 272 | "GET /signed-out": true, |
| 273 | // The smart door (Home spec 2026-11-19-smart-door.md, step 6), |
| 274 | // declared 2026-11-22: Continue with Oficina ID (with Home only; |
| 275 | // 404 standalone); rastrillo auth's Forget ("Use a different email", |
| 276 | // "Forget me on this device"), a same-origin POST inside the CSRF |
| 277 | // check; and connect's member choice (team mode only; 404 without |
| 278 | // Home), with no session yet. |
| 279 | "GET /signin/oficina": true, |
| 280 | "POST /signin/forget": true, |
| 281 | "GET /account/home/choose": true, |
| 282 | "POST /account/home/choose": true, |
| 283 | "GET /account/home": true, |
| 284 | "POST /account/home": true, |
| 285 | "GET /account/home/confirm": true, |
| 286 | "POST /account/home/confirm": true, |
| 287 | "GET /auth/start": true, |
| 288 | "POST /auth/assertion": true, |
| 289 | "GET /auth/finish": true, |
| 290 | "GET /auth/local/complete": true, |
| 291 | "GET /": true, |
| 292 | // Adding content, moved off the index to its own page 2026-09-29. |
| 293 | "GET /add": true, |
| 294 | // GET /search renders the results region alone, from the same |
| 295 | // template GET /?q= renders it inside a page, so live search can |
| 296 | // replace that region on a keystroke. Same session gate, no passage |
| 297 | // the page did not already speak; delete the script and nothing |
| 298 | // calls it. Declared 2026-09-06 when this gate caught it arriving |
| 299 | // from main — the second time in one merge that a route could not |
| 300 | // reach the app until somebody wrote it down. |
| 301 | "GET /search": true, |
| 302 | // The document list, moved off the front page when it became a |
| 303 | // search box (Paul, 2026-10-29); same rows, same session gate, and |
| 304 | // each row asked of its app of record (VisibleDocuments). |
| 305 | "GET /documents": true, |
| 306 | // The typeahead (2026-10-29): the keystroke search reduced to one |
| 307 | // row per document, the box's one checked answer, never a model |
| 308 | // step. Member standing in team mode, like the AI answer. |
| 309 | "GET /suggest": true, |
| 310 | "POST /documents": true, |
| 311 | "GET /documents/{id}": true, |
| 312 | "POST /documents/{id}/delete": true, |
| 313 | // §8.10's corrections, 2026-10-26: the correction page and its POST, |
| 314 | // and the person's own reports. All inside the session group. |
| 315 | "GET /facts/correct": true, |
| 316 | "POST /facts/correct": true, |
| 317 | "GET /reports": true, |
| 318 | // §8.11's AI answer fragment, 2026-10-26, inside the session group. |
| 319 | "GET /answer": true, |
| 320 | // §8.11's 👍/👎, 2026-10-27, inside the session group. |
| 321 | "POST /answer/feedback": true, |
| 322 | "GET /answer/feedback/{id}": true, |
| 323 | "POST /answer/feedback/{id}": true, |
| 324 | "POST /answer/feedback/{id}/delete": true, |
| 325 | "POST /reports/{id}/delete": true, |
| 326 | // The shared chrome (estilo spec/shared-chrome, round 2), declared |
| 327 | // 2026-09-30: |
| 328 | // - GET /documents/{id}/delete asks before a delete (it was a |
| 329 | // one-click POST); same session gate as the POST beside it. |
| 330 | // - POST /appearance is estilo's chrome.HandleAppearance: one |
| 331 | // host-only preference cookie and a SafeReturn redirect. Inside |
| 332 | // the app-wide CSRF check, deliberately OUTSIDE the session gate |
| 333 | // (§8.3), and it reads and writes no content. |
| 334 | // - GET /auth/landed is where a verified magic link lands |
| 335 | // (standalone), and on to the page the person was heading for. |
| 336 | "GET /documents/{id}/delete": true, |
| 337 | "POST /appearance": true, |
| 338 | "GET /auth/landed": true, |
| 339 | "POST /auth/begin": true, |
| 340 | "GET /auth/callback": true, |
| 341 | "GET /auth/verify": true, |
| 342 | // rastrillo #64 (pin fb806a2, 2026-10-06): GET /auth/verify is the |
| 343 | // confirm door and spends nothing; this POST, from its Sign in |
| 344 | // button, redeems the link. auth's own same-origin check runs before |
| 345 | // the token is touched; in Home mode it sits under LocalGuard like |
| 346 | // the GET. |
| 347 | "POST /auth/verify": true, |
| 348 | "POST /signout": true, |
| 349 | |
| 350 | // The connector surface (§5.1), added by the Notion work and |
| 351 | // declared here on 2026-09-06 when this gate caught it — which is |
| 352 | // the gate working: five new routes arrived on main and none of |
| 353 | // them could reach the app until somebody wrote them down. |
| 354 | // |
| 355 | // All five sit inside requireOwner AND requireSession. They are |
| 356 | // memoria-owned content's ingest path (§4.2), not a sibling |
| 357 | // surface: decision 7 still holds, and §9.1's rule that a sibling |
| 358 | // presenting a connector token is refused is a different gate. |
| 359 | "GET /connectors": true, |
| 360 | "GET /connectors/notion": true, |
| 361 | "POST /connectors/notion": true, |
| 362 | "POST /connectors/notion/sync": true, |
| 363 | "POST /connectors/notion/disconnect": true, |
| 364 | } |
| 365 | |