oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "bytes"
5 "context"
6 "html"
7 "io"
8 "log/slog"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "path/filepath"
13 "regexp"
14 "strings"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/home/connect"
19 "amadan.net/oficina/memoria/internal/memoria/seal"
20 "amadan.net/oficina/suite"
21 "amadan.net/rastrillo/rastrillo/assertion"
22 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
23 "amadan.net/rastrillo/rastrillo/db"
24)
25
26const homeTestOrigin = "https://memoria.example.test"
27const homeTestIssuer = "https://id.example.test"
28
29type homeTestMail struct{ body string }
30
31func (m *homeTestMail) Send(_ context.Context, _, _, body string) error { m.body = body; return nil }
32
33type homeRouterFixture struct {
34 app *app
35 handler http.Handler
36 key *assertioncrypto.Keypair
37 mail *homeTestMail
38 cookies map[string]*http.Cookie
39}
40
41func newHomeRouterFixture(t *testing.T) *homeRouterFixture {
42 t.Helper()
43 return newHomeRouterFixtureDir(t, "")
44}
45
46// newHomeRouterFixtureDir is the fixture with a hub directory origin
47// (HOME_DIRECTORY_ORIGIN), which is what puts the switcher in the bar.
48func newHomeRouterFixtureDir(t *testing.T, directory string) *homeRouterFixture {
49 t.Helper()
50 key, err := assertioncrypto.Generate()
51 if err != nil {
52 t.Fatal(err)
53 }
54 return newHomeRouterFixtureWith(t, key, Config{Origin: homeTestOrigin, Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: "memoria-test", Keys: map[string][]byte{"key": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32), Directory: directory}})
55}
56
57// newHomeRouterFixtureWith wires Home from cfg, signed by key under the
58// key ID "key". Each before runs on the app before Home is wired (a clock
59// the link store must start on, for one).
60func newHomeRouterFixtureWith(t *testing.T, key *assertioncrypto.Keypair, cfg Config, before ...func(*app)) *homeRouterFixture {
61 t.Helper()
62 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
63 d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), logger)
64 if err != nil {
65 t.Fatal(err)
66 }
67 t.Cleanup(func() { d.Close() })
68 cipher, err := seal.New(bytes.Repeat([]byte{6}, 32))
69 if err != nil {
70 t.Fatal(err)
71 }
72 mux, a, err := App(d, homeTestOrigin, cipher, logger)
73 if err != nil {
74 t.Fatal(err)
75 }
76 t.Cleanup(func() { a.store.ix.Close() })
77 a.SetOwners([]string{"alice@example.test"})
78 mail := &homeTestMail{}
79 auth, err := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: mail, HomeEnabled: true}, logger, a)
80 if err != nil {
81 t.Fatal(err)
82 }
83 a.UseAuth(auth)
84 for _, fn := range before {
85 fn(a)
86 }
87 if err = a.WireHome(mux, cfg); err != nil {
88 t.Fatal(err)
89 }
90 a.MountAuth(mux, homeTestOrigin)
91 return &homeRouterFixture{a, mux, key, mail, map[string]*http.Cookie{}}
92}
93func (f *homeRouterFixture) do(method, path, body string) *httptest.ResponseRecorder {
94 r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body))
95 for _, c := range f.cookies {
96 r.AddCookie(c)
97 }
98 if method == "POST" {
99 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
100 r.Header.Set("Origin", homeTestOrigin)
101 if path == "/auth/assertion" {
102 r.Header.Set("Origin", homeTestIssuer)
103 }
104 }
105 return f.send(r)
106}
107
108// send serves r with the fixture's cookies already on it, and keeps the
109// cookies the answer sets.
110func (f *homeRouterFixture) send(r *http.Request) *httptest.ResponseRecorder {
111 w := httptest.NewRecorder()
112 f.handler.ServeHTTP(w, r)
113 for _, c := range w.Result().Cookies() {
114 if c.MaxAge < 0 {
115 delete(f.cookies, c.Name)
116 } else {
117 f.cookies[c.Name] = c
118 }
119 }
120 return w
121}
122
123// confirmRe is the confirm door's form (rastrillo's signin partial, Confirm): the one
124// form on the page, posting the token in a hidden field.
125var confirmRe = regexp.MustCompile(`<form rst-signin-form method="post" action="([^"]+)">\s*<input type="hidden" name="token" value="([^"]*)">`)
126
127// confirmForm reads the confirm door off a page and returns where its Sign
128// in button posts and the token it carries. It fails the test unless the
129// page is the door with no address field — the shape renderConfirm draws.
130func confirmForm(t *testing.T, page string) (action, token string) {
131 t.Helper()
132 m := confirmRe.FindStringSubmatch(page)
133 if m == nil {
134 t.Fatalf("the link did not open the confirm door:\n%s", page)
135 }
136 if strings.Contains(page, `name="address"`) {
137 t.Error("the confirm door has an address field; it is one Sign in button")
138 }
139 if !strings.Contains(page, ">Sign in</button>") {
140 t.Error("the confirm door has no Sign in button")
141 }
142 return html.UnescapeString(m[1]), html.UnescapeString(m[2])
143}
144
145// openLink follows an emailed sign-in link the way a person does since
146// rastrillo #64: the GET draws the confirm door and spends nothing, and
147// the door's Sign in button POSTs the token back — same-origin, as a
148// browser submitting the door's own form says it is. It returns the
149// POST's answer, which is what the GET used to answer.
150func (f *homeRouterFixture) openLink(t *testing.T, uri string) *httptest.ResponseRecorder {
151 t.Helper()
152 w := f.do("GET", uri, "")
153 if w.Code != http.StatusOK {
154 t.Fatalf("GET %s = %d, want the confirm door", uri, w.Code)
155 }
156 action, token := confirmForm(t, w.Body.String())
157 r := httptest.NewRequest("POST", homeTestOrigin+action, strings.NewReader(url.Values{"token": {token}}.Encode()))
158 for _, c := range f.cookies {
159 r.AddCookie(c)
160 }
161 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
162 r.Header.Set("Origin", homeTestOrigin)
163 r.Header.Set("Sec-Fetch-Site", "same-origin")
164 return f.send(r)
165}
166func homeRedirect(t *testing.T, w *httptest.ResponseRecorder) string {
167 t.Helper()
168 if w.Code != 303 {
169 t.Fatalf("redirect status %d: %s", w.Code, w.Body.String())
170 }
171 return w.Header().Get("Location")
172}
173func (f *homeRouterFixture) local(t *testing.T) { f.localAs(t, "alice@example.test") }
174
175// localAs signs address in with the app's own email link and returns
176// where /auth/local/complete sent the browser.
177func (f *homeRouterFixture) localAs(t *testing.T, address string) string {
178 t.Helper()
179 homeRedirect(t, f.do("POST", "/auth/begin", "address="+url.QueryEscape(address)+"&force=1"))
180 link := regexp.MustCompile(`https://[^\s<>\"]+/auth/verify\?[^\s<>\"]+`).FindString(f.mail.body)
181 u, err := url.Parse(link)
182 if err != nil || link == "" {
183 t.Fatal("no captured local verification link")
184 }
185 landing := homeRedirect(t, f.openLink(t, u.RequestURI()))
186 if landing != "/auth/local/complete" {
187 t.Fatal("wrong local landing", landing)
188 }
189 return homeRedirect(t, f.do("GET", landing, ""))
190}
191func (f *homeRouterFixture) exchange(t *testing.T, start, subject string) *httptest.ResponseRecorder {
192 t.Helper()
193 return f.exchangeAt(t, start, subject, time.Now())
194}
195
196// exchangeAt is exchange with the assertion issued at at, for a test that
197// has set the app's clock to it.
198func (f *homeRouterFixture) exchangeAt(t *testing.T, start, subject string, at time.Time) *httptest.ResponseRecorder {
199 t.Helper()
200 target := homeRedirect(t, f.do("GET", start, ""))
201 u, err := url.Parse(target)
202 if err != nil || u.Query().Get("consumer") != "memoria-test" {
203 t.Fatal("bad issuer redirect")
204 }
205 nonce := u.Query().Get("nonce")
206 now := at.Unix()
207 jti, err := assertion.RandomID()
208 if err != nil {
209 t.Fatal(err)
210 }
211 token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: homeTestIssuer, Audience: homeTestOrigin, Subject: subject, KeyID: "key", ID: jti, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 90, AuthTime: now})
212 if err != nil {
213 t.Fatal(err)
214 }
215 callback := f.do("POST", "/auth/assertion", url.Values{"assertion": {token}}.Encode())
216 finish := homeRedirect(t, callback)
217 return f.do("GET", finish, "")
218}
219func TestHomeRouterLinkKeepsContentAndSiblingAddress(t *testing.T) {
220 f := newHomeRouterFixture(t)
221 custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}
222 f.app.store.custody = custody
223 for _, spec := range []IngestSpec{{Source: "Upload", Key: "own", Title: "Own nebula", Body: "nebula local content"}, {Source: "Docs", Key: "sibling", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}} {
224 if _, err := f.app.store.Ingest(t.Context(), spec); err != nil {
225 t.Fatal(err)
226 }
227 }
228 f.local(t)
229 localCookie := f.cookies[f.app.home.sessions.CookieName()].Value
230 before := f.do("GET", "/?q=nebula", "")
231 if before.Code != 200 || !strings.Contains(before.Body.String(), "Shared nebula") {
232 t.Fatal("local baseline failed", before.Code)
233 }
234 if w := f.do("GET", "/account/home", ""); w.Code != 200 {
235 t.Fatal("link page", w.Code, w.Body.String())
236 }
237 start := homeRedirect(t, f.do("POST", "/account/home", ""))
238 finish := f.exchange(t, start, "opaque-home-alice")
239 if homeRedirect(t, finish) != "/account/home/confirm" {
240 t.Fatal("wrong proof landing")
241 }
242 if f.cookies[f.app.home.sessions.CookieName()].Value != localCookie {
243 t.Fatal("proof replaced local session")
244 }
245 if w := f.do("GET", "/account/home/confirm", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "alice@example.test") {
246 t.Fatal("confirmation", w.Code, w.Body.String())
247 }
248 homeRedirect(t, f.do("POST", "/account/home/confirm", ""))
249 // Sign out chains to id.* (home/connect 01166fc, shared chrome §9.5): a
250 // 307, so the hop stays a POST, to the issuer's /signout.
251 if w := f.do("POST", "/signout", ""); w.Code != http.StatusTemporaryRedirect || w.Header().Get("Location") != homeTestIssuer+"/signout" {
252 t.Fatal("signout did not chain to id.*", w.Code, w.Header().Get("Location"))
253 }
254 if f.cookies[f.app.home.sessions.CookieName()] != nil {
255 t.Fatal("signout retained app cookie")
256 }
257 start = f.oficina(t, "/signin?return_to=%2F%3Fq%3Dnebula")
258 target := homeRedirect(t, f.exchange(t, start, "opaque-home-alice"))
259 after := f.do("GET", target, "")
260 if after.Code != 200 || !strings.Contains(after.Body.String(), "Shared nebula") || !strings.Contains(after.Body.String(), "Own nebula") {
261 t.Fatal("Home lost content", after.Code, after.Body.String())
262 }
263 if custody.asker.Kind != suite.SubjectAddress || custody.asker.Value != "alice@example.test" {
264 t.Fatal("Home changed S2 asker", custody.asker)
265 }
266 var docs, chunks int
267 f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&docs)
268 f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM chunks").Scan(&chunks)
269 if docs != 2 || chunks != 2 {
270 t.Fatal("link changed content", docs, chunks)
271 }
272 custody.give = suite.NOT_VISIBLE
273 denied := f.do("GET", "/?q=nebula", "")
274 if denied.Code != 200 || strings.Contains(denied.Body.String(), "nebula sibling content") || !strings.Contains(denied.Body.String(), "Own nebula") {
275 t.Fatal("Home bypassed sibling refusal", denied.Code)
276 }
277 enabled := f.app.home
278 f.app.home = nil
279 if w := f.do("GET", "/", ""); w.Code != 404 {
280 t.Fatal("Home session survived disabled integration", w.Code)
281 }
282 f.app.home = enabled
283 f.app.SetOwners([]string{"bob@example.test"})
284 // Removed: still not admitted, and now told so. The session is ended
285 // and a page request goes to the sign-in page's "removed" sentence,
286 // where it used to meet a 404 on every page until the session lapsed.
287 if w := f.do("GET", "/", ""); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" {
288 t.Fatal("removed owner still admitted, or not told", w.Code, w.Header().Get("Location"))
289 }
290 if f.cookies[f.app.home.sessions.CookieName()] != nil {
291 t.Fatal("a removed owner kept their session")
292 }
293}
294func TestHomeRouterUnknownSubjectCannotAllocateOrRead(t *testing.T) {
295 f := newHomeRouterFixture(t)
296 start := f.oficina(t, "/signin")
297 w := f.exchange(t, start, "opaque-unlinked-alice")
298 // "Oficina account", never "Home" (Paul's §13 answer 3; homeCopy).
299 if w.Code != 403 || !strings.Contains(w.Body.String(), "Oficina account not connected") {
300 t.Fatal("unknown subject", w.Code, w.Body.String())
301 }
302 var n int
303 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&n); err != nil || n != 0 {
304 t.Fatal("Home allocated identity", n, err)
305 }
306 if f.cookies[f.app.home.sessions.CookieName()] != nil {
307 t.Fatal("Home minted session before linking")
308 }
309}
310
311func TestHomeRouterMutationsKeepCSRFAndCookieGuards(t *testing.T) {
312 f := newHomeRouterFixture(t)
313 f.local(t)
314 for _, path := range []string{"/account/home", "/account/home/confirm", "/auth/begin", "/signout"} {
315 req := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader("address=alice%40example.test&force=1"))
316 req.Header.Set("Origin", "https://attacker.example")
317 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
318 for _, c := range f.cookies {
319 req.AddCookie(c)
320 }
321 rec := httptest.NewRecorder()
322 f.handler.ServeHTTP(rec, req)
323 if rec.Code != 403 {
324 t.Fatal("cross-origin mutation", path, rec.Code)
325 }
326 }
327 req := httptest.NewRequest("POST", homeTestOrigin+"/auth/assertion", strings.NewReader("assertion=invalid"))
328 req.Header.Set("Origin", "https://attacker.example")
329 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
330 rec := httptest.NewRecorder()
331 f.handler.ServeHTTP(rec, req)
332 if rec.Code != 400 {
333 t.Fatal("wrong issuer accepted", rec.Code)
334 }
335 req = httptest.NewRequest("GET", homeTestOrigin+"/account/home", nil)
336 c := f.cookies[f.app.home.sessions.CookieName()]
337 req.AddCookie(c)
338 req.AddCookie(c)
339 rec = httptest.NewRecorder()
340 f.handler.ServeHTTP(rec, req)
341 if rec.Code != 400 {
342 t.Fatal("duplicate app cookie accepted", rec.Code)
343 }
344 var n int
345 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&n); err != nil || n != 0 {
346 t.Fatal("refused route allocated identity", n, err)
347 }
348}
349
350func TestHomeRouterMissingKeymailFreshnessCannotAllocateLink(t *testing.T) {
351 f := newHomeRouterFixture(t)
352 f.local(t)
353 if _, err := f.app.db.Writer().Exec("UPDATE sessions SET method='keymail',auth_time=''"); err != nil {
354 t.Fatal(err)
355 }
356 w := f.do("GET", "/account/home", "")
357 // connect's link step-up (since the smart door): the email-only door,
358 // marked a step-up.
359 if homeRedirect(t, w) != "/signin/local?reauth=1" {
360 t.Fatal("missing Keymail freshness did not request local proof")
361 }
362 var n int
363 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&n); err != nil || n != 0 {
364 t.Fatal("missing freshness allocated identity", n, err)
365 }
366}
367func TestHomeSigninClearsOnlyDefinitivelyStaleSession(t *testing.T) {
368 f := newHomeRouterFixture(t)
369 f.local(t)
370 cookieName := f.app.home.sessions.CookieName()
371 saved := f.cookies[cookieName].Value
372 if _, err := f.app.db.Writer().Exec("ALTER TABLE sessions RENAME TO unavailable_sessions"); err != nil {
373 t.Fatal(err)
374 }
375 f.oficina(t, "/signin")
376 if f.cookies[cookieName] == nil || f.cookies[cookieName].Value != saved {
377 t.Fatal("temporary storage failure cleared valid cookie")
378 }
379 if _, err := f.app.db.Writer().Exec("ALTER TABLE unavailable_sessions RENAME TO sessions"); err != nil {
380 t.Fatal(err)
381 }
382 if _, err := f.app.db.Writer().Exec("DELETE FROM sessions"); err != nil {
383 t.Fatal(err)
384 }
385 start := f.oficina(t, "/signin")
386 if f.cookies[cookieName] != nil {
387 t.Fatal("stale cookie not cleared")
388 }
389 target := homeRedirect(t, f.do("GET", start, ""))
390 if !strings.HasPrefix(target, homeTestIssuer+"/") {
391 t.Fatal("stale cookie prevented Home sign-in", target)
392 }
393}
394
395// The footer's egress claim on the pages that exist only when Home is
396// configured. TestTheFooterStatesTheModelSwitch (memoriatest) walks every
397// declared route, but its harness does not configure Home, so these 404
398// there — this is where they are checked. They render through renderHome,
399// the Render callback both the Home routes and its Bridge are given.
400//
401// **Every route explicitly, at whatever status it renders.** The first
402// version accepted "at least one page made a claim" and checked only
403// 200s, so /account/home/confirm — which renders its failure page at 400 —
404// was never looked at, and removing ModelOn from renderHome left the
405// suite green until the next commit added this. A review found both.
406func TestHomePagesStateTheModelSwitch(t *testing.T) {
407 // Each route with the extra cookies that make it render. The four
408 // /auth/ routes are FAILURE pages — a duplicate or malformed cookie, or
409 // missing state — and a review found all four render the shared footer
410 // at 400 while this test did not look at them: making renderHome drop
411 // ModelOn only for /auth/ paths left the whole suite green. The
412 // cookie conditions are the Home library's own refusals
413 // (connect.homeCookie, Routes.LocalGuard, Bridge.Finish).
414 type visit struct {
415 path string
416 extra []*http.Cookie
417 }
418 dup := func(name string) []*http.Cookie {
419 v := strings.Repeat("A", 43)
420 return []*http.Cookie{{Name: name, Value: v}, {Name: name, Value: v}}
421 }
422 visits := []visit{
423 {path: "/account/home"},
424 {path: "/account/home/confirm"},
425 {path: "/auth/start", extra: dup("__Host-oficina-home-init")},
426 {path: "/auth/finish"},
427 {path: "/auth/callback", extra: dup("__Host-rastrillo_pending")},
428 {path: "/auth/verify", extra: dup("__Host-rastrillo_pending")},
429 }
430 // The sign-in pages carry no footer at all (shared chrome §9.2 retires
431 // the claim there): the claim is about searching, said only to somebody
432 // signed in. Checked as an absence, so a footer creeping back onto them
433 // is seen, not skipped.
434 signinPages := []string{"/signed-out", "/signin/local"}
435 for _, on := range []bool{true, false} {
436 f := newHomeRouterFixture(t)
437 if on {
438 f.app.store.extractor = &recorder{}
439 }
440 f.local(t)
441 for _, path := range signinPages {
442 w := f.do("GET", path, "")
443 if w.Code != 200 || strings.Contains(w.Body.String(), "<footer") || strings.Contains(w.Body.String(), "leaves this instance") {
444 t.Errorf("AI on=%v, %s (%d): a sign-in page carries the footer's claim", on, path, w.Code)
445 }
446 }
447 for _, v := range visits {
448 path := v.path
449 r := httptest.NewRequest("GET", homeTestOrigin+path, nil)
450 for _, c := range f.cookies {
451 r.AddCookie(c)
452 }
453 for _, c := range v.extra {
454 r.AddCookie(c)
455 }
456 w := httptest.NewRecorder()
457 f.handler.ServeHTTP(w, r)
458 b := w.Body.String()
459 i := strings.Index(b, "<footer")
460 if i < 0 {
461 t.Errorf("AI on=%v, %s (%d): no footer, so this route is unchecked", on, path, w.Code)
462 continue
463 }
464 foot := strings.Join(strings.Fields(b[i:]), " ")
465 if !strings.Contains(foot, "leaves this instance") {
466 t.Errorf("AI on=%v, %s (%d): the footer makes no egress claim", on, path, w.Code)
467 continue
468 }
469 if on && (strings.Contains(foot, "no document ever") || !strings.Contains(foot, "TensorX")) {
470 t.Errorf("AI on, %s (%d): footer does not disclose TensorX", path, w.Code)
471 }
472 if !on && (!strings.Contains(foot, "no document ever") || strings.Contains(foot, "TensorX")) {
473 t.Errorf("AI off, %s (%d): footer does not make the true claim", path, w.Code)
474 }
475 }
476 }
477}
478
479// Where sign-out lands is the door, like the sign-in page beside it:
480// Memoria's card on the sky, with the suite's signed-out words (spec §9.2)
481// rather than Home's "You can sign in again with Home", and a plain Sign
482// in back to /signin. The same page standalone and with Home.
483func TestSignedOutIsTheDoor(t *testing.T) {
484 f := newHomeRouterFixture(t)
485 w := f.do("GET", "/signed-out", "")
486 if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" {
487 t.Fatalf("/signed-out: %d, Cache-Control %q", w.Code, w.Header().Get("Cache-Control"))
488 }
489 b := html.UnescapeString(w.Body.String())
490 for _, want := range []string{
491 "<div estilo-door", "estilo-sky-layer", "<section estilo-signin", "<span>Memoria</span>",
492 "/static/chrome.", "/static/sky.", "<title>Signed out · Memoria</title>",
493 "<h1>You’re signed out</h1>", "You’ve signed out of Memoria on this device.", `href="/signin"`, ">Sign in<",
494 } {
495 if !strings.Contains(b, want) {
496 t.Errorf("/signed-out lacks %q", want)
497 }
498 }
499 // Home is never named to people (Paul, 2026-09-23).
500 if strings.Contains(b, "Home") {
501 t.Errorf("/signed-out names Home:\n%s", b)
502 }
503}
504