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 "html"
6 "io"
7 "log/slog"
8 "net/http"
9 "net/http/httptest"
10 "net/url"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/home/connect"
18 "amadan.net/oficina/memoria/internal/memoria/seal"
19 rauth "amadan.net/rastrillo/rastrillo/auth"
20 "amadan.net/rastrillo/rastrillo/db"
21 "amadan.net/rastrillo/rastrillo/lastsignin"
22 "amadan.net/rastrillo/rastrillo/sessions"
23)
24
25// The smart door's test helpers (signin_door_*_test.go), and the way the
26// older Home tests now reach the exchange: through the door's own
27// "Continue with Oficina ID" (GET /signin draws the door; it no longer
28// hops to Home).
29
30// federatedRe is rastrillo's one-way door's "Continue with {name}" button
31// (ui partials/signin.html, the federated door): a primary link.
32var federatedRe = regexp.MustCompile(`<a rst-btn="primary block" href="([^"]+)"[^>]*>.*?Continue with Oficina ID`)
33
34// oficinaHrefOn is the "Continue with Oficina ID" href on a door page, or
35// "" when the door offers none.
36func oficinaHrefOn(page string) string {
37 m := federatedRe.FindStringSubmatch(page)
38 if m == nil {
39 return ""
40 }
41 return html.UnescapeString(m[1])
42}
43
44// chooserOficinaRe is the chooser's Oficina ID row: a link to the door's
45// own one-option screen for Oficina ID (?way=oficina).
46var chooserOficinaRe = regexp.MustCompile(`<a rst-btn="block" href="(/signin\?[^"]*way=oficina[^"]*)"`)
47
48// oficina opens the door at path (GET /signin, with its return_to), taps
49// Continue with Oficina ID, and returns where that sent the browser: the
50// start of the Home exchange (/auth/start…). When this browser last signed
51// in another way, the door's one way is that one, so it goes by Other ways
52// to sign in, as a person would. It fails unless path drew the door and
53// the door, or its chooser, offered Oficina ID.
54func (f *homeRouterFixture) oficina(t *testing.T, path string) string {
55 t.Helper()
56 door := f.do("GET", path, "")
57 if door.Code != http.StatusOK {
58 t.Fatalf("GET %s = %d, want the door", path, door.Code)
59 }
60 href, seen := oficinaHrefOn(door.Body.String()), door.Body.String()
61 if href == "" {
62 ways := path + "?ways=1"
63 if strings.Contains(path, "?") {
64 ways = path + "&ways=1"
65 }
66 chooser := f.do("GET", ways, "")
67 seen = chooser.Body.String()
68 if m := chooserOficinaRe.FindStringSubmatch(chooser.Body.String()); m != nil {
69 screen := f.do("GET", html.UnescapeString(m[1]), "")
70 seen = screen.Body.String()
71 href = oficinaHrefOn(seen)
72 }
73 }
74 if href == "" {
75 t.Fatalf("GET %s: neither the door nor its chooser offers Oficina ID:\n%s", path, seen)
76 }
77 u, err := url.Parse(href)
78 if err != nil || u.Path != "/signin/oficina" {
79 t.Fatalf("Continue with Oficina ID goes to %q, want /signin/oficina", href)
80 }
81 return homeRedirect(t, f.do("GET", href, ""))
82}
83
84// newStandaloneDoor is homeRouterFixture's browser on an instance without
85// Home: email is the only way in, and alice@example.test the one owner.
86// The origin is https, so the door's __Host- cookies behave as in
87// production.
88func newStandaloneDoor(t *testing.T) *homeRouterFixture {
89 t.Helper()
90 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
91 d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), logger)
92 if err != nil {
93 t.Fatal(err)
94 }
95 t.Cleanup(func() { d.Close() })
96 cipher, err := seal.New(bytes.Repeat([]byte{6}, 32))
97 if err != nil {
98 t.Fatal(err)
99 }
100 mux, a, err := App(d, homeTestOrigin, cipher, logger)
101 if err != nil {
102 t.Fatal(err)
103 }
104 t.Cleanup(func() { a.store.ix.Close() })
105 a.SetOwners([]string{"alice@example.test"})
106 mail := &homeTestMail{}
107 auth, err := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: mail}, logger, a)
108 if err != nil {
109 t.Fatal(err)
110 }
111 a.UseAuth(auth)
112 a.MountAuth(mux, homeTestOrigin)
113 return &homeRouterFixture{a, mux, nil, mail, map[string]*http.Cookie{}}
114}
115
116// doorModes runs fn once with Home and once without.
117func doorModes(t *testing.T, fn func(t *testing.T, f *homeRouterFixture)) {
118 t.Run("home", func(t *testing.T) { fn(t, newHomeRouterFixture(t)) })
119 t.Run("standalone", func(t *testing.T) { fn(t, newStandaloneDoor(t)) })
120}
121
122// fresh is another browser on f's app: the same instance, an empty jar.
123func (f *homeRouterFixture) fresh() *homeRouterFixture {
124 return &homeRouterFixture{f.app, f.handler, f.key, f.mail, map[string]*http.Cookie{}}
125}
126
127// get is do("GET", path, "").
128func (f *homeRouterFixture) get(path string) *httptest.ResponseRecorder {
129 return f.do(http.MethodGet, path, "")
130}
131
132// remember gives the browser a remembered way in, sealed by Memoria's own
133// jar, as rastrillo would have after a sign-in.
134func (f *homeRouterFixture) remember(t *testing.T, rec lastsignin.Record) {
135 t.Helper()
136 w := httptest.NewRecorder()
137 f.app.auth.RememberJar().Remember(w, rec)
138 cookies := w.Result().Cookies()
139 if len(cookies) != 1 {
140 t.Fatalf("the jar refused %+v", rec)
141 }
142 f.cookies[cookies[0].Name] = cookies[0]
143}
144
145// remembered is the browser's remembered way in, read by Memoria's jar.
146func (f *homeRouterFixture) remembered() (lastsignin.Record, lastsignin.ReadResult) {
147 return f.app.auth.RememberJar().Read(f.jarRequest())
148}
149
150// returnPath is the page the browser's return memory holds, "" for none.
151func (f *homeRouterFixture) returnPath() string {
152 p, _ := f.app.rememberedReturn(f.jarRequest())
153 return p
154}
155
156func (f *homeRouterFixture) jarRequest() *http.Request {
157 r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil)
158 for _, c := range f.cookies {
159 r.AddCookie(c)
160 }
161 return r
162}
163
164// session puts a session for subject, signed in by method, in the jar, as
165// a finished sign-in would, verified at authTime.
166func (f *homeRouterFixture) session(t *testing.T, subject, method string, authTime time.Time) {
167 t.Helper()
168 w := httptest.NewRecorder()
169 if err := f.app.sess.SignIn(w, httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil), sessions.Session{Subject: subject, Method: method, AuthTime: authTime}); err != nil {
170 t.Fatal(err)
171 }
172 for _, c := range w.Result().Cookies() {
173 f.cookies[c.Name] = c
174 }
175}
176
177// sessionCookie is the session cookie in the jar, or nil.
178func (f *homeRouterFixture) sessionCookie() *http.Cookie {
179 return f.cookies[f.app.sessionCookie()]
180}
181
182// liveSession reports whether value is a session cookie that still
183// resolves.
184func (f *homeRouterFixture) liveSession(value string) bool {
185 r := httptest.NewRequest(http.MethodGet, homeTestOrigin+"/", nil)
186 r.AddCookie(&http.Cookie{Name: f.app.sessionCookie(), Value: value})
187 _, ok := f.app.sess.From(r)
188 return ok
189}
190
191// signinLink is the emailed sign-in link in the last mail.
192var signinLink = regexp.MustCompile(`https://[^\s<>"]+/auth/verify\?[^\s<>"]+`)
193
194// emailSignin signs the browser in by the emailed link, posting form to
195// Begin as the door's form does (force=1, so the classifier dials no DNS
196// in a test), and returns where it lands once the landing has settled.
197func (f *homeRouterFixture) emailSignin(t *testing.T, form url.Values) string {
198 t.Helper()
199 f.mail.body = ""
200 if !form.Has("force") {
201 form.Set("force", "1")
202 }
203 if w := f.do(http.MethodPost, "/auth/begin", form.Encode()); w.Code != http.StatusSeeOther {
204 t.Fatalf("POST /auth/begin: %d", w.Code)
205 }
206 link := signinLink.FindString(f.mail.body)
207 if link == "" {
208 t.Fatal("no sign-in link mailed")
209 }
210 u, err := url.Parse(link)
211 if err != nil {
212 t.Fatal(err)
213 }
214 next := homeRedirect(t, f.openLink(t, u.RequestURI()))
215 for range 4 {
216 if next != "/auth/local/complete" && next != landedPath {
217 return next
218 }
219 next = homeRedirect(t, f.get(next))
220 }
221 t.Fatalf("the landing never settled: %q", next)
222 return ""
223}
224
225// link gives alice@example.test a local account linked to the Oficina
226// subject opaque-home-alice, and signs the browser in afresh through
227// Continue with Oficina ID, as she would from then on: a Home session,
228// with Oficina ID remembered.
229func (f *homeRouterFixture) link(t *testing.T) {
230 t.Helper()
231 f.local(t)
232 homeRedirect(t, f.linkFromMenu(t, "opaque-home-alice"))
233 f.cookies = map[string]*http.Cookie{}
234 start := homeRedirect(t, f.get("/signin/oficina"))
235 if got := homeRedirect(t, f.exchange(t, start, "opaque-home-alice")); got != "/" {
236 t.Fatalf("the Oficina sign-in landed on %q", got)
237 }
238 if s, ok := f.app.sess.From(f.jarRequest()); !ok || s.Method != connect.HomeMethod {
239 t.Fatalf("after the Oficina sign-in the session is %+v", s)
240 }
241}
242
243// redirectsTo fails unless rec is a 303 to want.
244func redirectsTo(t *testing.T, rec *httptest.ResponseRecorder, want string) {
245 t.Helper()
246 if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != want {
247 t.Fatalf("got %d %q, want 303 %q", rec.Code, rec.Header().Get("Location"), want)
248 }
249}
250
251// door is the sign-in card's own content: rastrillo's section inside
252// estilo-signin-screen, unescaped, followed by its text alone (the markup
253// taken out, so "Continue as <bdi>x</bdi>" reads "Continue as x").
254func door(t *testing.T, body string) string {
255 t.Helper()
256 start := strings.Index(body, "<div estilo-signin-screen>")
257 if start < 0 {
258 t.Fatalf("no estilo-signin-screen:\n%s", body)
259 }
260 end := strings.Index(body[start:], "</section>")
261 card := html.UnescapeString(body[start : start+end])
262 return card + "\n" + regexp.MustCompile(`<[^>]*>`).ReplaceAllString(card, "")
263}
264
265// titleOf is the page's <title>, unescaped.
266func titleOf(t *testing.T, body string) string {
267 t.Helper()
268 m := regexp.MustCompile(`<title>([^<]*)</title>`).FindStringSubmatch(body)
269 if m == nil {
270 t.Fatalf("no <title>:\n%s", body)
271 }
272 return html.UnescapeString(m[1])
273}
274
275// clears reports whether rec clears the named cookie.
276func clears(rec *httptest.ResponseRecorder, name string) bool {
277 for _, c := range rec.Result().Cookies() {
278 if c.Name == name && c.MaxAge < 0 {
279 return true
280 }
281 }
282 return false
283}
284
285// sets reports whether rec sets the named cookie to a value.
286func sets(rec *httptest.ResponseRecorder, name string) bool {
287 for _, c := range rec.Result().Cookies() {
288 if c.Name == name && c.MaxAge >= 0 && c.Value != "" {
289 return true
290 }
291 }
292 return false
293}
294
295// What the door's markup says, for the tests to look for.
296const (
297 oficinaButton = "Continue with Oficina ID"
298 otherWays = "Other ways to sign in"
299 emailField = `id="rst-signin-email" name="address"`
300 appProblem = `id="rst-signin-app-problem"`
301)
302
303// rauthIdentity is a verified address, as auth hands its Refused hook.
304func rauthIdentity(address string) rauth.Identity { return rauth.Identity{Address: address} }
305