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 "context"
5 "errors"
6 "io"
7 "log/slog"
8 "net/http"
9 "net/http/httptest"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/home/connect"
15 "amadan.net/oficina/home/roster"
16 "amadan.net/oficina/memoria/internal/memoria/notion"
17 "amadan.net/oficina/memoria/internal/memoria/sibling"
18 "amadan.net/oficina/memoria/internal/memoria/teamstate"
19 "amadan.net/oficina/suite"
20 "amadan.net/rastrillo/rastrillo/sessions"
21)
22
23// Team mode configured and no roster runtime — WireHome never ran — is
24// closed: every request is refused, and the owners list decides nothing.
25//
26// MUTATION-TESTED 2026-10-30: requireSession's teamMode-without-runtime
27// refusal removed → red (the owners list admitted the session).
28func TestTeamWithoutARuntimeRefusesEverything(t *testing.T) {
29 cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), teamKey(t), "owner@example.test")
30 d := teamDB(t)
31 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
32 mux, a, err := AppWith(d, cfg, logger)
33 if err != nil {
34 t.Fatal(err)
35 }
36 t.Cleanup(func() { a.store.ix.Close() })
37 a.SetOwners(cfg.Owners)
38 auth, err := NewAuth(d.Writer(), AuthEnv{Origin: cfg.Origin, InstanceKey: "k", Mailer: &homeTestMail{}, HomeEnabled: true}, logger, a)
39 if err != nil {
40 t.Fatal(err)
41 }
42 a.UseAuth(auth)
43 a.MountAuth(mux, cfg.Origin)
44 w := httptest.NewRecorder()
45 if err := a.sess.SignIn(w, httptest.NewRequest("GET", homeTestOrigin+"/", nil), sessions.Session{Subject: "owner@example.test", Method: "magiclink", AuthTime: time.Now()}); err != nil {
46 t.Fatal(err)
47 }
48 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
49 for _, c := range w.Result().Cookies() {
50 r.AddCookie(c)
51 }
52 got := httptest.NewRecorder()
53 mux.ServeHTTP(got, r)
54 if got.Code != http.StatusInternalServerError {
55 t.Fatalf("team mode with no runtime = %d, want every request refused", got.Code)
56 }
57}
58
59// lapsingCustody lapses the standing of the request it is asked in, while
60// the list is being built: a sibling passage is ruled mid-search.
61type lapsingCustody struct {
62 fixedCustody
63 lapse func()
64}
65
66func (l *lapsingCustody) Rule(ctx context.Context, asker suite.Subject, cands []sibling.Candidate) []sibling.Disposition {
67 if l.lapse != nil {
68 l.lapse()
69 }
70 return l.fixedCustody.Rule(ctx, asker, cands)
71}
72
73// A lapse while a list is being built: the page withholds what it built
74// and says partial; the native API's JSON list, which has nowhere to say
75// so, is the retryable 503. Deterministic, where the sweep in
76// team_review_test.go is statistical.
77//
78// MUTATION-TESTED 2026-10-30: nativeSearch's after-check removed →
79// "native"; index's teamPartial check removed → "page". 2026-11-02, the
80// search-home merge: the after-check removed from /documents and from
81// /suggest in turn → "showed the list"; withhold not clearing Recent →
82// "/: … showed the list".
83func TestTeamALapseWhileListingWithholdsTheList(t *testing.T) {
84 f := newTeamFixture(t)
85 custody := &lapsingCustody{fixedCustody: fixedCustody{apps: docsRoster(), give: suite.VISIBLE}}
86 f.app.store.custody = custody
87 f.ingest("plan", "Nebula plan", "The nebula plan is ready.")
88 if _, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "Docs", Key: "s", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}); err != nil {
89 t.Fatal(err)
90 }
91 f.member(teamSubject('a'), "member")
92
93 // The presence half.
94 if w := f.page("/?q=nebula"); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") || isPartial(w.Body.String()) {
95 t.Fatalf("member page = %d", w.Code)
96 }
97 if w := f.json("POST", "/api/native/search", `{"query":"nebula"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") {
98 t.Fatalf("member native search = %d %s", w.Code, w.Body.String())
99 }
100
101 custody.lapse = f.expired
102 w := f.page("/?q=nebula")
103 if w.Code != 200 || !isPartial(w.Body.String()) || strings.Contains(w.Body.String(), "Nebula plan") || strings.Contains(w.Body.String(), "Shared nebula") {
104 t.Fatalf("page: a lapse while listing = %d:\n%s", w.Code, w.Body.String())
105 }
106 // The front page's lists, the document list and the typeahead, which
107 // arrived from the search-home branch: each rules its sibling rows,
108 // so each sees the lapse, and each must drop what it built. The
109 // typeahead has no notice to show and says nothing (204).
110 for _, path := range []string{"/", "/documents", "/suggest?q=nebula"} {
111 f.recovered()
112 custody.lapse = nil
113 if w := f.page(path); w.Code != 200 || !strings.Contains(w.Body.String(), "nebula") {
114 t.Fatalf("%s: member = %d, want 200 listing the nebula documents:\n%s", path, w.Code, w.Body.String())
115 }
116 custody.lapse = f.expired
117 w := f.page(path)
118 body := w.Body.String()
119 if strings.Contains(body, "Nebula plan") || strings.Contains(body, "Shared nebula") {
120 t.Fatalf("%s: a lapse while listing showed the list (%d):\n%s", path, w.Code, body)
121 }
122 want := http.StatusOK
123 if path == "/suggest?q=nebula" {
124 want = http.StatusNoContent
125 } else if !isPartial(body) {
126 t.Fatalf("%s: a lapse while listing gave no notice:\n%s", path, body)
127 }
128 if w.Code != want {
129 t.Fatalf("%s: a lapse while listing = %d, want %d", path, w.Code, want)
130 }
131 }
132 f.recovered()
133 n := f.json("POST", "/api/native/search", `{"query":"nebula"}`)
134 if n.Code != http.StatusServiceUnavailable || strings.Contains(n.Body.String(), "Nebula") {
135 t.Fatalf("native: a lapse while listing = %d %s, want 503", n.Code, n.Body.String())
136 }
137}
138
139// onePage is a Notion with one page.
140type onePage struct{}
141
142func (onePage) Roots(context.Context) ([]notion.Ref, []notion.Ref, error) {
143 return []notion.Ref{{ID: "p1", Title: "Nebula page", EditedTime: "2026-10-30T00:00:00.000Z"}}, nil, nil
144}
145func (onePage) Fetch(context.Context, notion.Ref) (*notion.Content, error) {
146 return &notion.Content{Markdown: "the nebula page body"}, nil
147}
148
149// The instance's own work is not a person's write: a connector run and a
150// sibling poll import in team mode with no request's standing behind
151// them — after the owner who started the run has gone, too.
152//
153// MUTATION-TESTED 2026-10-30: systemWrite removed from Syncer.RunWith →
154// "connector run"; from Store.Poll → "sibling poll".
155func TestTeamTheInstancesOwnWorkIsNotAPersonsWrite(t *testing.T) {
156 f := newTeamFixture(t)
157 f.member(teamSubject('o'), "owner")
158 if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "t", "w"); err != nil {
159 t.Fatal(err)
160 }
161 run, err := f.app.store.StartRun(f.asMember(teamSubject('o')), 1)
162 if err != nil {
163 t.Fatal(err)
164 }
165 // The owner leaves before the run imports anything.
166 f.dir.Set(teamSubject('o'), "")
167 f.refreshed()
168 f.app.syncer.RunWith(f.asMemberOrNone(teamSubject('o')), onePage{}, 1, run.ID)
169 if f.count("documents") != 1 {
170 t.Fatalf("connector run: %d documents imported, want 1", f.count("documents"))
171 }
172
173 fs := &feedServer{t: t, pages: map[string]suite.Feed{"": {Cursor: "c1", Rows: []suite.FeedRow{row("d1", 1, false)}}, "c1": {Cursor: "c1", Rows: []suite.FeedRow{}}}, bodies: map[string]string{"d1": "a nebula sibling body"}}
174 sib, client := fs.start(t)
175 if _, err := f.app.store.Poll(context.Background(), client, sib); err != nil {
176 t.Fatalf("sibling poll: %v", err)
177 }
178 if f.count("documents") != 2 {
179 t.Fatalf("sibling poll: %d documents, want 2", f.count("documents"))
180 }
181}
182
183// asMemberOrNone is the context a request for subject would carry now,
184// whatever their standing: what a run started by them inherits.
185func (f *teamFixture) asMemberOrNone(subject string) context.Context {
186 return withTeamPerson(context.Background(), &teamPerson{subject: subject, access: f.app.team.Access(context.Background(), subject)})
187}
188
189// withhold is what keeps a list built on standing that did not last from
190// being shown. The templates also render nothing but the notice when
191// Partial is set, so through HTTP this is defence in depth that no page
192// can show missing (two mutations survived the page tests): it is called
193// directly here, and every list field it must clear is set first.
194//
195// MUTATION-TESTED 2026-10-30: each of withhold's clears dropped in turn
196// (Results, Documents, Facts, Answer, the reports' two lists) → red.
197// 2026-11-02: the front page's Recent, RecentNotices and Try, added with
198// the search-home merge, each dropped in turn → red.
199func TestTeamWithholdClearsEveryList(t *testing.T) {
200 p := page{Results: []Result{{}}, Documents: []Summary{{}}, Notices: []string{"n"}, Facts: []Fact{{}}, Explained: []FactExplanation{{}},
201 FactsDeferred: true, AnswerSlot: true, Answer: &AIAnswer{}, Primed: true, Chunks: 7,
202 Recent: []Summary{{}}, RecentNotices: []string{"n"}, Try: []string{"t"}}
203 p.withhold()
204 if !p.Partial || p.Results != nil || p.Documents != nil || p.Notices != nil || p.Facts != nil || p.Explained != nil ||
205 p.FactsDeferred || p.AnswerSlot || p.Answer != nil || p.Primed || p.Chunks != -1 ||
206 p.Recent != nil || p.RecentNotices != nil || p.Try != nil {
207 t.Fatalf("withhold left %+v", p)
208 }
209 r := reportsPage{Reports: []ReportView{{}}, Feedback: []FeedbackView{{}}}
210 r.withhold()
211 if !r.Partial || r.Reports != nil || r.Feedback != nil {
212 t.Fatalf("reports withhold left %+v", r)
213 }
214}
215
216// MEMORIA_OWNERS still decides a LOCAL session in team mode: an address
217// taken off it is signed out and told so, as always, whatever its link
218// says. (It decides nothing about a Home session: see
219// TestTeamLinkedAccountStandsOnTheRoster.)
220//
221// MUTATION-TESTED 2026-10-30: teamIdentify ignoring the owners list for a
222// local session → red.
223func TestTeamOwnersListStillGatesALocalSession(t *testing.T) {
224 f := newTeamFixture(t, "alice@example.test")
225 subject := teamSubject('l')
226 f.dir.Set(subject, "member")
227 f.refreshed()
228 f.local(t)
229 if got := f.linkFromMenu(t, subject); got.Code != http.StatusSeeOther {
230 t.Fatalf("link = %d", got.Code)
231 }
232 if w := f.page("/"); w.Code != 200 {
233 t.Fatalf("linked local session = %d", w.Code)
234 }
235 f.app.SetOwners(nil)
236 if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" {
237 t.Fatalf("local session off the owners list = %d %q", w.Code, w.Header().Get("Location"))
238 }
239}
240
241// teamstate refuses, itself, what its callers should never ask: a person
242// for a subject that is linked to a local account, and a subject shaped
243// like an address. Both are also refused elsewhere (a trigger; roster's
244// subject check before any lookup), which is why each is tested here,
245// directly, where only this layer can answer.
246//
247// MUTATION-TESTED 2026-10-30: EnsureHomeMember's link check dropped →
248// "linked" (the trigger then answers, as unavailable rather than
249// refused); Opaque accepting "@" → "address".
250func TestTeamStateRefusesLinkedSubjectsAndAddresses(t *testing.T) {
251 f := newTeamFixture(t)
252 w := f.d.Writer()
253 if _, err := w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('abc',X'01')"); err != nil {
254 t.Fatal(err)
255 }
256 if _, err := w.Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,1)", homeTestIssuer, teamSubject('k')); err != nil {
257 t.Fatal(err)
258 }
259 people := f.count("memoria_home_local_identities")
260 if _, err := teamstate.EnsureHomeMember(context.Background(), w, homeTestIssuer, teamSubject('k')); !errors.Is(err, teamstate.ErrRefused) {
261 t.Fatalf("linked: EnsureHomeMember = %v, want ErrRefused", err)
262 }
263 if _, err := teamstate.EnsureHomeMember(context.Background(), w, homeTestIssuer, "someone@example.test"); !errors.Is(err, teamstate.ErrRefused) {
264 t.Fatalf("address: EnsureHomeMember = %v, want ErrRefused", err)
265 }
266 if f.count("memoria_home_local_identities") != people {
267 t.Fatal("a refused subject was allocated a person")
268 }
269 // The trigger under it, for a writer that skips the check.
270 res, err := w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('home-only:z',X'')")
271 if err != nil {
272 t.Fatal(err)
273 }
274 id, _ := res.LastInsertId()
275 if _, err := w.Exec("INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('k'), id); err == nil {
276 t.Fatal("a linked subject was made Home-only beneath the check")
277 }
278}
279
280// tools/drive's preview of Unknown acts only under AppForTest: on an app
281// built for production it changes nothing.
282func TestTeamPreviewUnknownIsDriveOnly(t *testing.T) {
283 f := newHomeRouterFixture(t)
284 f.app.store.Ingest(context.Background(), IngestSpec{Source: "upload", Key: "n", Title: "Nebula plan", Body: "The nebula plan is ready."})
285 f.app.PreviewUnknownStanding()
286 f.local(t)
287 if w := f.do("GET", "/?q=nebula", ""); w.Code != 200 || isPartial(w.Body.String()) || !strings.Contains(w.Body.String(), "Nebula plan") {
288 t.Fatalf("a production app previewing Unknown = %d, partial %v", w.Code, isPartial(w.Body.String()))
289 }
290}
291
292// A Home session whose subject no longer resolves to anybody here — no
293// link, no Home-only person — speaks for nobody: it is signed out and told
294// so, on a page and at /signin alike, never an endless 503.
295//
296// MUTATION-TESTED 2026-10-30 (independent pass, 05 and 15): an
297// unresolvable Home subject read as unavailable → red; teamAdmission
298// reading it as unresolved → red ("signin").
299func TestTeamAHomeSessionForNobodyIsSignedOut(t *testing.T) {
300 f := newTeamFixture(t)
301 f.dir.Set(teamSubject('z'), "member")
302 f.refreshed()
303 mint := func() {
304 f.cookies = map[string]*http.Cookie{}
305 w := httptest.NewRecorder()
306 if err := f.app.home.sessions.SignIn(w, httptest.NewRequest("GET", homeTestOrigin+"/", nil), sessions.Session{Subject: teamSubject('z'), Method: connect.HomeMethod, AuthTime: time.Now()}); err != nil {
307 t.Fatal(err)
308 }
309 for _, c := range w.Result().Cookies() {
310 f.cookies[c.Name] = c
311 }
312 }
313 mint()
314 if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" {
315 t.Fatalf("page: a Home session for nobody = %d %q", w.Code, w.Header().Get("Location"))
316 }
317 if _, ok := f.sessionNow(); ok {
318 t.Fatal("page: a Home session for nobody survived")
319 }
320 mint()
321 if w := f.page("/signin"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), signinRemoved) {
322 t.Fatalf("signin: a Home session for nobody = %d %q, want the door with the removal", w.Code, w.Header().Get("Location"))
323 }
324 if _, ok := f.sessionNow(); ok {
325 t.Fatal("signin: a Home session for nobody survived the door")
326 }
327}
328
329// The roster owner's /connectors under a lease ending mid-request: the
330// owner's own page, or a retryable 503 — never the 404 a member gets,
331// which would tell an owner the page does not exist because Home was slow.
332//
333// MUTATION-TESTED 2026-10-30 (independent pass, 03): the owner branch's
334// lapse read as NotMember → red.
335func TestTeamOwnerScreensUnderALapseAreNever404(t *testing.T) {
336 f := newTeamFixture(t)
337 f.member(teamSubject('o'), "owner")
338 var ok, unavailable int
339 for k := 0; k <= 10; k++ {
340 f.clock.SetTick(0)
341 f.recovered()
342 f.dir.SetDown(true)
343 f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Second)
344 f.clock.SetTick(time.Second)
345 w := f.page("/connectors")
346 f.clock.SetTick(0)
347 switch w.Code {
348 case 200:
349 ok++
350 case http.StatusServiceUnavailable:
351 unavailable++
352 default:
353 t.Fatalf("k=%d owner's /connectors = %d", k, w.Code)
354 }
355 }
356 if ok == 0 || unavailable == 0 {
357 t.Fatalf("the sweep saw %d pages and %d 503s; it must see both", ok, unavailable)
358 }
359}
360
361// Team mode off, the Home hooks are not wired: an unknown Home subject is
362// connect's 403 and nothing is allocated, exactly as before.
363//
364// MUTATION-TESTED 2026-10-30 (independent pass, 14): the hooks wired
365// whenever Home is → red.
366func TestTeamOffAnUnknownHomeSubjectIsStillRefused(t *testing.T) {
367 f := newHomeRouterFixture(t)
368 var before int
369 f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&before)
370 w := f.exchange(t, f.oficina(t, "/signin"), teamSubject('u'))
371 if w.Code != http.StatusForbidden {
372 t.Fatalf("team mode off, unknown Home subject = %d, want 403", w.Code)
373 }
374 var after int
375 f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&after)
376 if after != before {
377 t.Fatal("team mode off allocated a person for an unknown Home subject")
378 }
379}
380
381// Under Unknown the lists ask nobody: standing is read before a list is
382// built (teamReaches), so no S2 question goes out on behalf of a person
383// whose standing is not known. /documents' before-check survived removal
384// because its after-check withholds anyway (Fable, 2026-11-02); this is
385// what it is for. MUTATION-TESTED 2026-11-02: the before-check removed
386// from documents() → "asked".
387func TestTeamUnknownListsAskNobody(t *testing.T) {
388 f := newTeamFixture(t)
389 custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE}
390 f.app.store.custody = custody
391 if _, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "Docs", Key: "s", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}); err != nil {
392 t.Fatal(err)
393 }
394 f.member(teamSubject('a'), "member")
395 if w := f.page("/documents"); !strings.Contains(w.Body.String(), "Shared nebula") || custody.calls == 0 {
396 t.Fatalf("a Member's list did not ask (calls=%d), so the absence below proves nothing", custody.calls)
397 }
398 f.expired()
399 custody.calls = 0
400 for _, path := range []string{"/documents", "/", "/?q=nebula"} {
401 f.page(path)
402 if custody.calls != 0 {
403 t.Fatalf("%s under Unknown asked the app of record %d times", path, custody.calls)
404 }
405 }
406}
407