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/home/roster"
20 "amadan.net/oficina/home/teammode"
21 "amadan.net/oficina/home/teammode/teammodetest"
22 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
23 "amadan.net/rastrillo/rastrillo/db"
24 "amadan.net/rastrillo/rastrillo/sessions"
25
26 "amadan.net/oficina/memoria/internal/memoria/seal"
27)
28
29// Team mode's fixture: Home configured exactly as homeRouterFixture does
30// (so its exchange, local sign-in and link helpers all apply), plus
31// home/teammode's test directory (teammodetest) answering the roster in
32// memory from a member list a test can change or take down, with a roster
33// clock a test can step past the lease. The app is built the way main
34// builds it: AppWith, SetOwners, NewAuth, UseAuth, WireHome, MountAuth.
35
36const teamTestConsumer = "memoria-test"
37
38// teamSubject is a well-formed person ref: "pr_" and 26 copies of c.
39func teamSubject(c byte) string { return teammodetest.Subject(c) }
40
41// teamTestBindings are this instance's: Home's issuer and consumer ID as
42// homeRouterFixture configures them, the test directory and team,
43// Memoria, and origin.
44func teamTestBindings(origin string) roster.Bindings {
45 b := teammodetest.Bindings("memoria", teamTestConsumer, origin)
46 b.Issuer = homeTestIssuer
47 return b
48}
49
50func teamKey(t *testing.T) *assertioncrypto.Keypair {
51 t.Helper()
52 key, err := assertioncrypto.Generate()
53 if err != nil {
54 t.Fatal(err)
55 }
56 return key
57}
58
59func teamSealer(t *testing.T) *seal.Sealer {
60 t.Helper()
61 s, err := seal.New(bytes.Repeat([]byte{6}, 32))
62 if err != nil {
63 t.Fatal(err)
64 }
65 return s
66}
67
68// teamConfigFor is a Config for a team-mode instance on bindings b: Home
69// as homeRouterFixture has it, the record signed for b, and the test
70// directory and clock. owners is MEMORIA_OWNERS, which in team mode only
71// admits a local sign-in; none is Alta's shape.
72func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, owners ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) {
73 t.Helper()
74 tcfg, dir := teammodetest.Provision(t, b)
75 clock := teammodetest.NewClock()
76 cfg := Config{Origin: b.Audience, Sealer: teamSealer(t), Owners: owners,
77 Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, Keys: map[string][]byte{"key": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)},
78 Team: tcfg, teamTransport: dir, teamClock: clock}
79 return cfg, dir, clock
80}
81
82func teamDB(t *testing.T) *db.DB {
83 t.Helper()
84 d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
85 if err != nil {
86 t.Fatal(err)
87 }
88 t.Cleanup(func() { d.Close() })
89 return d
90}
91
92// bootTeam builds the app over d from cfg as main does, and returns it
93// (nil with the error when boot is refused).
94func bootTeam(t *testing.T, d *db.DB, cfg Config) (*http.ServeMux, *app, *homeTestMail, error) {
95 t.Helper()
96 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
97 mux, a, err := AppWith(d, cfg, logger)
98 if err != nil {
99 return nil, nil, nil, err
100 }
101 t.Cleanup(func() { a.store.ix.Close() })
102 a.SetOwners(cfg.Owners)
103 mail := &homeTestMail{}
104 auth, err := NewAuth(d.Writer(), AuthEnv{Origin: cfg.Origin, InstanceKey: "isolated-test-instance-key", Mailer: mail, HomeEnabled: true}, logger, a)
105 if err != nil {
106 t.Fatal(err)
107 }
108 a.UseAuth(auth)
109 if err := a.WireHome(mux, cfg); err != nil {
110 return nil, nil, nil, err
111 }
112 a.MountAuth(mux, cfg.Origin)
113 return mux, a, mail, nil
114}
115
116type teamFixture struct {
117 *homeRouterFixture
118 t *testing.T
119 d *db.DB
120 dir *teammodetest.Directory
121 clock *teammodetest.Clock
122}
123
124func newTeamFixture(t *testing.T, owners ...string) *teamFixture {
125 t.Helper()
126 key := teamKey(t)
127 cfg, dir, clock := teamConfigFor(t, teamTestBindings(homeTestOrigin), key, owners...)
128 d := teamDB(t)
129 mux, a, mail, err := bootTeam(t, d, cfg)
130 if err != nil {
131 t.Fatalf("boot in team mode: %v", err)
132 }
133 return &teamFixture{homeRouterFixture: &homeRouterFixture{a, mux, key, mail, map[string]*http.Cookie{}}, t: t, d: d, dir: dir, clock: clock}
134}
135
136// page is GET path as a browser asks for it (Accept: text/html, so an
137// error is the page and not plain text).
138func (f *teamFixture) page(path string) *httptest.ResponseRecorder {
139 r := httptest.NewRequest("GET", homeTestOrigin+path, nil)
140 r.Header.Set("Accept", "text/html")
141 for _, c := range f.cookies {
142 r.AddCookie(c)
143 }
144 return f.send(r)
145}
146
147// form POSTs values as a browser's same-origin form does.
148func (f *teamFixture) form(path, body string) *httptest.ResponseRecorder {
149 r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body))
150 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
151 r.Header.Set("Origin", homeTestOrigin)
152 r.Header.Set("Accept", "text/html")
153 for _, c := range f.cookies {
154 r.AddCookie(c)
155 }
156 return f.send(r)
157}
158
159// signIn runs a whole Home sign-in for subject from wherever the jar is,
160// and returns the finish answer.
161//
162// A roster Member with no account here yet is asked to choose (Home spec
163// 2026-11-14-oficina-id-native.md §8); signIn answers "I'm new here", as a
164// new member would, and returns that answer. signInChoosing stops at the
165// choice.
166func (f *teamFixture) signIn(subject string) *httptest.ResponseRecorder {
167 f.t.Helper()
168 fin := f.signInChoosing(subject)
169 if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
170 return fin
171 }
172 return f.choose("new")
173}
174
175// signInChoosing is signIn, stopping at the member choice.
176func (f *teamFixture) signInChoosing(subject string) *httptest.ResponseRecorder {
177 f.t.Helper()
178 return f.exchange(f.t, "/auth/start", subject)
179}
180
181// choose reads the choice page's form token and posts choice with it.
182func (f *teamFixture) choose(choice string) *httptest.ResponseRecorder {
183 f.t.Helper()
184 page := f.page(connect.ChoosePath)
185 if page.Code != http.StatusOK {
186 f.t.Fatalf("choose page = %d %s", page.Code, page.Body.String())
187 }
188 m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String())
189 if m == nil {
190 f.t.Fatalf("choose page has no form token: %s", page.Body.String())
191 }
192 return f.form(connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}}.Encode())
193}
194
195// freshSignIn is signIn from an empty jar.
196func (f *teamFixture) freshSignIn(subject string) *httptest.ResponseRecorder {
197 f.cookies = map[string]*http.Cookie{}
198 return f.signIn(subject)
199}
200
201// member puts subject on the roster with role, refreshes, and signs them
202// in with Home from an empty jar, failing unless they got a session.
203func (f *teamFixture) member(subject, role string) {
204 f.t.Helper()
205 f.dir.Set(subject, role)
206 f.refreshed()
207 if got := f.freshSignIn(subject); got.Code != http.StatusSeeOther {
208 f.t.Fatalf("sign-in of %s = %d %s", subject, got.Code, got.Body.String())
209 }
210}
211
212// refreshed steps the roster clock past the refresh point and refreshes,
213// so the next request sees the directory's current list.
214func (f *teamFixture) refreshed() {
215 f.t.Helper()
216 f.clock.Step(roster.RefreshAfter + time.Second)
217 if err := f.app.team.Refresh(context.Background()); err != nil {
218 f.t.Fatalf("roster refresh: %v", err)
219 }
220}
221
222// expired takes the directory down and steps past the lease: Unknown.
223func (f *teamFixture) expired() {
224 f.dir.SetDown(true)
225 f.clock.Step(roster.MaximumAge + time.Second)
226}
227
228// renewed brings the directory back and refreshes.
229func (f *teamFixture) renewed() {
230 f.t.Helper()
231 f.dir.SetDown(false)
232 f.refreshed()
233}
234
235// localSession puts a local (magic link) session for address in the jar,
236// as a sign-in the owners list admitted would.
237func (f *teamFixture) localSession(address string) {
238 f.t.Helper()
239 w := httptest.NewRecorder()
240 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
241 if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil {
242 f.t.Fatal(err)
243 }
244 for _, c := range w.Result().Cookies() {
245 f.cookies[c.Name] = c
246 }
247}
248
249// sessionNow is the session the jar's cookie currently resolves to.
250func (f *teamFixture) sessionNow() (sessions.Session, bool) {
251 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
252 for _, c := range f.cookies {
253 r.AddCookie(c)
254 }
255 return f.app.home.sessions.From(r)
256}
257
258// ingest stores a memoria-owned document directly, as the instance's own
259// work (a systemWrite): no request's standing is involved.
260func (f *teamFixture) ingest(key, title, body string) int64 {
261 f.t.Helper()
262 id, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "upload", Key: key, Title: title, Body: body})
263 if err != nil {
264 f.t.Fatal(err)
265 }
266 return id
267}
268
269// count is SELECT COUNT(*) FROM table.
270func (f *teamFixture) count(table string) int {
271 f.t.Helper()
272 var n int
273 if err := f.d.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil {
274 f.t.Fatal(err)
275 }
276 return n
277}
278
279// asMember is a context carrying a Member's Access for subject, as
280// requireSession would put on a request: for the store-level tests.
281func (f *teamFixture) asMember(subject string) context.Context {
282 f.t.Helper()
283 acc := f.app.team.Access(context.Background(), subject)
284 if acc.State() != roster.Member {
285 f.t.Fatalf("%s is not a member now", subject)
286 }
287 return teammode.WithAccess(context.Background(), acc)
288}
289