oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "html"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "regexp"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/home/connect"
18 "amadan.net/oficina/home/handoff"
19 "amadan.net/oficina/home/roster"
20 "amadan.net/oficina/home/teammode"
21 "amadan.net/oficina/home/teammode/teammodetest"
22 "amadan.net/rastrillo/rastrillo/assertion"
23 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
24 "amadan.net/rastrillo/rastrillo/db"
25 "amadan.net/rastrillo/rastrillo/sessions"
26)
27
28// Team mode's fixture: Home configured exactly as homeFixture does, and
29// home/teammode's test directory (teammodetest) answering the roster in
30// memory from a member list a test can change or take down, with a
31// roster clock a test can step past the lease.
32
33const (
34 teamTestIssuer = "https://home.example.com"
35 teamTestConsumer = "slides-test"
36)
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// homeFixture configures them, the test directory and team, Slides, and
43// the test origin.
44func teamTestBindings() roster.Bindings {
45 b := teammodetest.Bindings("slides", teamTestConsumer, homeTestOrigin)
46 b.Issuer = teamTestIssuer
47 return b
48}
49
50type teamFixture struct {
51 t *testing.T
52 mux *http.ServeMux
53 a *app
54 d *db.DB
55 key *assertioncrypto.Keypair
56 dir *teammodetest.Directory
57 clock *teammodetest.Clock
58 cfg *teammode.Config
59 jar map[string]*http.Cookie
60}
61
62// teamConfigFor builds a Config for a team-mode instance on bindings b,
63// over d: Home as homeFixture has it, the record signed for b, and the
64// test directory and clock. allowed is SLIDES_ALLOWED_ADDRESSES, which in
65// team mode only admits local sign-in; none is Alta's shape.
66func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, allowed ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) {
67 t.Helper()
68 tcfg, dir := teammodetest.Provision(t, b)
69 clock := teammodetest.NewClock()
70 raw, _ := json.Marshal(map[string]string{"test": base64.StdEncoding.EncodeToString(key.SignPub())})
71 cfg := Config{KeymailServers: testKeymailServers, Mailer: &homeTestMail{}, Env: EnvDevelopment, Origin: homeTestOrigin, Logger: quietLogger(), AllowedAddresses: allowed,
72 Home: &connect.Credentials{Issuer: teamTestIssuer, ConsumerID: teamTestConsumer, KeysBase64: base64.StdEncoding.EncodeToString(raw), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{8}, 32))},
73 Team: tcfg, teamTransport: dir, teamClock: clock}
74 return cfg, dir, clock
75}
76
77func newTeamFixture(t *testing.T, allowed ...string) *teamFixture {
78 t.Helper()
79 key, err := assertioncrypto.Generate()
80 if err != nil {
81 t.Fatal(err)
82 }
83 d := testDB(t)
84 cfg, dir, clock := teamConfigFor(t, teamTestBindings(), key, allowed...)
85 mux, a, err := New(d, cfg)
86 if err != nil {
87 t.Fatalf("New in team mode: %v", err)
88 }
89 t.Cleanup(func() { a.Close() })
90 return &teamFixture{t: t, mux: mux, a: a, d: d, key: key, dir: dir, clock: clock, cfg: cfg.Team, jar: map[string]*http.Cookie{}}
91}
92
93// do runs one request with the jar's cookies and keeps what it sets.
94// origin, when set, is sent as Origin (a same-origin form POST).
95func (f *teamFixture) do(method, path, body, contentType, origin string) *httptest.ResponseRecorder {
96 r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body))
97 if origin != "" {
98 r.Header.Set("Origin", origin)
99 r.Header.Set("Sec-Fetch-Site", "same-origin")
100 }
101 if contentType != "" {
102 r.Header.Set("Content-Type", contentType)
103 }
104 r.Header.Set("Accept", "text/html")
105 for _, c := range f.jar {
106 r.AddCookie(c)
107 }
108 w := httptest.NewRecorder()
109 f.mux.ServeHTTP(w, r)
110 for _, c := range w.Result().Cookies() {
111 if c.MaxAge < 0 {
112 delete(f.jar, c.Name)
113 } else {
114 f.jar[c.Name] = c
115 }
116 }
117 return w
118}
119
120func (f *teamFixture) get(path string) *httptest.ResponseRecorder {
121 return f.do("GET", path, "", "", "")
122}
123
124func (f *teamFixture) post(path string, form url.Values) *httptest.ResponseRecorder {
125 return f.do("POST", path, form.Encode(), "application/x-www-form-urlencoded", homeTestOrigin)
126}
127
128// signInHome runs a full Home exchange for subject — start, a signed
129// assertion, callback, finish — keeping whatever is already in the jar
130// (a live local session, say), and returns the finish response.
131//
132// A roster Member with no account here yet is asked to choose (Home spec
133// 2026-11-14-oficina-id-native.md §8); signInHome answers "I'm new here",
134// as a new member would, and returns that answer. signInHomeChoosing
135// stops at the choice.
136func (f *teamFixture) signInHome(subject string) *httptest.ResponseRecorder {
137 f.t.Helper()
138 fin := f.signInHomeChoosing(subject)
139 if fin.Code != http.StatusSeeOther || fin.Header().Get("Location") != connect.ChoosePath {
140 return fin
141 }
142 return f.choose("new")
143}
144
145// choose reads the choice page's form token and posts choice with it.
146func (f *teamFixture) choose(choice string) *httptest.ResponseRecorder {
147 f.t.Helper()
148 page := f.get(connect.ChoosePath)
149 if page.Code != http.StatusOK {
150 f.t.Fatalf("choose page = %d %s", page.Code, page.Body.String())
151 }
152 m := regexp.MustCompile(`name="token" value="([^"]+)"`).FindStringSubmatch(page.Body.String())
153 if m == nil {
154 f.t.Fatalf("choose page has no form token: %s", page.Body.String())
155 }
156 return f.post(connect.ChoosePath, url.Values{"choice": {choice}, "token": {html.UnescapeString(m[1])}})
157}
158
159// signInHomeChoosing is signInHome, stopping at the member choice.
160func (f *teamFixture) signInHomeChoosing(subject string) *httptest.ResponseRecorder {
161 f.t.Helper()
162 start := f.get(handoff.StartPath)
163 if start.Code != http.StatusSeeOther {
164 f.t.Fatalf("start = %d %s", start.Code, start.Body.String())
165 }
166 target, err := url.Parse(start.Header().Get("Location"))
167 if err != nil {
168 f.t.Fatal(err)
169 }
170 id, _ := assertion.RandomID()
171 now := time.Now().Unix()
172 token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: teamTestIssuer, Audience: homeTestOrigin, Subject: subject, KeyID: "test", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now})
173 if err != nil {
174 f.t.Fatal(err)
175 }
176 callback := f.do("POST", handoff.CallbackPath, url.Values{"assertion": {token}}.Encode(), "application/x-www-form-urlencoded", teamTestIssuer)
177 if callback.Code != http.StatusSeeOther {
178 f.t.Fatalf("callback = %d %s", callback.Code, callback.Body.String())
179 }
180 return f.get(handoff.FinishPath)
181}
182
183// freshHomeSignIn is signInHome from an empty jar.
184func (f *teamFixture) freshHomeSignIn(subject string) *httptest.ResponseRecorder {
185 f.jar = map[string]*http.Cookie{}
186 return f.signInHome(subject)
187}
188
189// member adds subject to the roster with role, refreshes, and signs them
190// in with Home from an empty jar, failing unless they got a session.
191func (f *teamFixture) member(subject, role string) User {
192 f.t.Helper()
193 f.dir.Set(subject, role)
194 f.refreshed()
195 finish := f.freshHomeSignIn(subject)
196 if finish.Code != http.StatusSeeOther {
197 f.t.Fatalf("sign-in of %s = %d %s", subject, finish.Code, finish.Body.String())
198 }
199 return f.userFor(subject)
200}
201
202// userFor is the user a Home subject signs in as.
203func (f *teamFixture) userFor(subject string) User {
204 f.t.Helper()
205 p, err := f.a.home.Resolve(context.Background(), subject)
206 if err != nil {
207 f.t.Fatalf("resolve %s: %v", subject, err)
208 }
209 var u User
210 if err := f.d.G.Take(&u, p.ID).Error; err != nil {
211 f.t.Fatal(err)
212 }
213 return u
214}
215
216// localSession puts a local (magic link) session for address in the jar,
217// as a sign-in the allowlist admitted would.
218func (f *teamFixture) localSession(address string) {
219 f.t.Helper()
220 w := httptest.NewRecorder()
221 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
222 if err := f.a.homeSessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil {
223 f.t.Fatal(err)
224 }
225 for _, c := range w.Result().Cookies() {
226 f.jar[c.Name] = c
227 }
228}
229
230// refreshed steps the roster clock past the refresh point and waits for
231// the refresh, so the next request sees the directory's current list.
232func (f *teamFixture) refreshed() {
233 f.t.Helper()
234 f.clock.Step(roster.RefreshAfter + time.Second)
235 if err := f.a.team.Refresh(context.Background()); err != nil {
236 f.t.Fatalf("roster refresh: %v", err)
237 }
238}
239
240// expired takes the directory down and steps past the lease: Unknown.
241func (f *teamFixture) expired() {
242 f.dir.SetDown(true)
243 f.clock.Step(roster.MaximumAge + time.Second)
244}
245
246// deck makes a deck owned by u directly (no request), on rung, with its
247// opening ops, and returns it.
248func (f *teamFixture) deck(u User, title, rung string) Deck {
249 f.t.Helper()
250 ctx := context.Background()
251 d, err := f.a.createDeckRow(ctx, u, title, defaultTheme, nil)
252 if err != nil {
253 f.t.Fatal(err)
254 }
255 ops, err := openingOps(title, defaultTheme)
256 if err != nil {
257 f.t.Fatal(err)
258 }
259 if err := f.a.editDeck(ctx, &d, actorFor(u), ops, nil, nil); err != nil {
260 f.t.Fatal(err)
261 }
262 if rung != rungPrivate {
263 if err := f.d.G.Model(&Deck{}).Where("id = ?", d.ID).Update("rung", rung).Error; err != nil {
264 f.t.Fatal(err)
265 }
266 d.Rung = rung
267 }
268 return d
269}
270
271// grant names u on d, given by somebody else.
272func (f *teamFixture) grant(d Deck, u User, by User) {
273 f.t.Helper()
274 if err := f.d.G.Create(&DeckGrant{DeckID: d.ID, UserID: u.ID, Actor: actorFor(by), CreatedAt: time.Now().UTC()}).Error; err != nil {
275 f.t.Fatal(err)
276 }
277}
278
279// localUser makes a users row for address, as a first local sign-in does.
280func (f *teamFixture) localUser(address string) User {
281 f.t.Helper()
282 u, _, err := ensureUser(context.Background(), f.d.G, address)
283 if err != nil {
284 f.t.Fatal(err)
285 }
286 return u
287}
288