oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1package memoriatest
2
3import (
4 "context"
5 "encoding/binary"
6 "encoding/json"
7 "fmt"
8 "html"
9 "io"
10 "log/slog"
11 "net"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "path/filepath"
16 "regexp"
17 "strings"
18 stdsync "sync"
19 "testing"
20 "time"
21
22 "amadan.net/rastrillo/rastrillo/db"
23
24 "amadan.net/oficina/memoria/internal/memoria"
25)
26
27// fakeKeymail answers the two probes signin's classifier makes of a
28// Keymail server — /.well-known/keymail and /api/federation/lookup — for
29// one host, and the token exchange for the codes approve hands out, and
30// 404s everything else. It stands in for http.DefaultTransport, which the
31// classifier's and the callback's clients fall back to.
32type fakeKeymail struct {
33 host string
34 mu stdsync.Mutex
35 hits []string
36 codes map[string]string
37}
38
39// approve is Keymail's consent screen saying yes for address: the code
40// the browser carries back to /auth/callback.
41func (f *fakeKeymail) approve(address string) string {
42 f.mu.Lock()
43 defer f.mu.Unlock()
44 if f.codes == nil {
45 f.codes = map[string]string{}
46 }
47 code := fmt.Sprintf("code-%d", len(f.codes)+1)
48 f.codes[code] = address
49 return code
50}
51
52func (f *fakeKeymail) RoundTrip(r *http.Request) (*http.Response, error) {
53 f.mu.Lock()
54 f.hits = append(f.hits, r.URL.Host+r.URL.Path)
55 f.mu.Unlock()
56 body, code := `{}`, http.StatusNotFound
57 if r.URL.Host == f.host {
58 switch r.URL.Path {
59 case "/.well-known/keymail":
60 body, code = `{"version":"1"}`, http.StatusOK
61 case "/api/federation/lookup":
62 code = http.StatusOK
63 case "/api/oauth/token":
64 var in map[string]string
65 _ = json.NewDecoder(r.Body).Decode(&in)
66 f.mu.Lock()
67 address, ok := f.codes[in["code"]]
68 delete(f.codes, in["code"])
69 f.mu.Unlock()
70 body, code = `{"error":"invalid_grant"}`, http.StatusBadRequest
71 if ok && r.Method == http.MethodPost {
72 out, _ := json.Marshal(map[string]any{
73 "access_token": "synthetic", "token_type": "bearer",
74 "address": address, "auth_time": time.Now().Unix(),
75 })
76 body, code = string(out), http.StatusOK
77 }
78 }
79 }
80 return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body)),
81 Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil
82}
83
84// nxdomainResolver answers every DNS query NXDOMAIN — "this domain
85// publishes no _keymail delegation" — which signin's classifier reads as
86// "the domain itself is the Keymail candidate". Go's resolver speaks
87// length-prefixed DNS over any conn that is not a PacketConn, which a
88// net.Pipe is not.
89func nxdomainResolver() *net.Resolver {
90 return &net.Resolver{PreferGo: true, Dial: func(context.Context, string, string) (net.Conn, error) {
91 client, server := net.Pipe()
92 go func() {
93 defer server.Close()
94 for {
95 var n [2]byte
96 if _, err := io.ReadFull(server, n[:]); err != nil {
97 return
98 }
99 q := make([]byte, binary.BigEndian.Uint16(n[:]))
100 if _, err := io.ReadFull(server, q); err != nil || len(q) < 12 {
101 return
102 }
103 // Header plus the question, and nothing after it.
104 i := 12
105 for i < len(q) && q[i] != 0 {
106 i += int(q[i]) + 1
107 }
108 i += 5 // the root label, QTYPE, QCLASS
109 if i > len(q) {
110 return
111 }
112 resp := append([]byte(nil), q[:i]...)
113 rd := binary.BigEndian.Uint16(q[2:4]) & 0x0100
114 binary.BigEndian.PutUint16(resp[2:4], 0x8000|0x0400|rd|0x0080|3) // QR AA RD RA, NXDOMAIN
115 binary.BigEndian.PutUint16(resp[4:6], 1)
116 for _, off := range []int{6, 8, 10} {
117 binary.BigEndian.PutUint16(resp[off:off+2], 0)
118 }
119 binary.BigEndian.PutUint16(n[:], uint16(len(resp)))
120 if _, err := server.Write(append(n[:], resp...)); err != nil {
121 return
122 }
123 }
124 }()
125 return client, nil
126 }}
127}
128
129// keymailSigninApp is the real app with the real sign-in wired, whose
130// owner's domain resolves — through the fakes above — to a Keymail server.
131func keymailSigninApp(t *testing.T) (http.Handler, *fakeKeymail) {
132 t.Helper()
133 km := &fakeKeymail{host: "example.test"}
134 return keymailSigninAppWith(t, filepath.Join(t.TempDir(), "app.db"), []string{dialTestOwner}, km), km
135}
136
137// keymailSigninAppWith is keymailSigninApp over a given database and
138// owners list and Keymail fake: two apps over one database share the
139// pending state, so a sign-in begun under one owners list can come back
140// under another.
141func keymailSigninAppWith(t *testing.T, dbPath string, owners []string, km *fakeKeymail) http.Handler {
142 t.Helper()
143 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
144 d, err := db.Open(dbPath, logger)
145 if err != nil {
146 t.Fatal(err)
147 }
148 t.Cleanup(func() { d.Close() })
149 mux, a, err := memoria.App(d, testOrigin, testDEK(t), logger)
150 if err != nil {
151 t.Fatal(err)
152 }
153 au, err := memoria.NewAuth(d.Writer(), memoria.AuthEnv{
154 Origin: testOrigin, InstanceKey: "signin-keymail-instance-key",
155 Owners: owners, Mailer: &stubMailer{},
156 // Listed, so rastrillo's keymail client sends through
157 // http.DefaultTransport, which is km below (AuthEnv says why).
158 KeymailServers: []string{km.host},
159 }, logger, a)
160 if err != nil {
161 t.Fatal(err)
162 }
163 a.UseAuth(au)
164 a.SetOwners(owners)
165 a.MountAuth(mux, testOrigin)
166
167 prevT, prevR := http.DefaultTransport, net.DefaultResolver
168 http.DefaultTransport, net.DefaultResolver = km, nxdomainResolver()
169 t.Cleanup(func() { http.DefaultTransport, net.DefaultResolver = prevT, prevR })
170 return mux
171}
172
173// **Signing in with a Keymail address must be able to leave the page.**
174//
175// Begin used to answer a Keymail address with 303 to the server's
176// /oauth/authorize, and memoria's CSP says form-action 'self', which
177// browsers enforce across a form submission's WHOLE redirect chain. Safari
178// refused the redirect and the sign-in button spun forever (2026-09-29,
179// memoria.oficina.works). Since the smart door, rastrillo's SigninScreen
180// answers the POST with a same-origin 303 to the door's continuation
181// (/signin?continue=<id>), and that page's meta refresh, which is a
182// navigation and not a form submission, goes on to Keymail.
183//
184// Through rastrillo's REAL Begin and the REAL mounted route: the classifier
185// is only faked at the network, so what is asserted is what production
186// sends.
187func TestAKeymailSigninCanLeaveThePage(t *testing.T) {
188 h, km := keymailSigninApp(t)
189 c := newClient(t, h)
190 rr := c.do(http.MethodPost, testOrigin+"/auth/begin", url.Values{"address": {dialTestOwner}})
191
192 // Presence: the classifier really took the Keymail path. Without this,
193 // a redirect below could be the magic link's Sent and prove nothing.
194 if !contains(km.hits, "example.test/api/federation/lookup") {
195 t.Fatalf("the classifier never reached the Keymail probes (hits %v); this proves nothing", km.hits)
196 }
197 next, err := url.Parse(rr.Header().Get("Location"))
198 if rr.Code != http.StatusSeeOther || err != nil || next.Host != "" || next.Path != "/signin" || next.Query().Get("continue") == "" {
199 t.Fatalf("POST /auth/begin = %d %q, want a same-origin 303 to the door's continuation", rr.Code, rr.Header().Get("Location"))
200 }
201 // Begin's pending cookie must be set, or the callback cannot match the
202 // flow it started.
203 if !strings.Contains(strings.Join(rr.Header().Values("Set-Cookie"), "\n"), "rastrillo_pending") {
204 t.Errorf("no pending cookie: %q", rr.Header().Values("Set-Cookie"))
205 }
206
207 page := c.get(testOrigin + next.String())
208 if page.Code != http.StatusOK {
209 t.Fatalf("GET %s = %d, want the continuation", next, page.Code)
210 }
211 body := page.Body.String()
212 // The continuation navigates to the authorize URL Begin chose, for THIS
213 // origin and callback.
214 if !strings.Contains(body, `http-equiv="refresh"`) {
215 t.Fatalf("no meta refresh in the continuation page:\n%s", body)
216 }
217 for _, want := range []string{
218 "https://example.test/oauth/authorize",
219 "client_id=" + url.QueryEscape(testOrigin),
220 "redirect_uri=" + url.QueryEscape(testOrigin+"/auth/callback"),
221 "code_challenge_method=S256",
222 } {
223 if !strings.Contains(strings.ReplaceAll(body, "&amp;", "&"), want) {
224 t.Errorf("continuation page lacks %q", want)
225 }
226 }
227 if got := page.Header().Get("Cache-Control"); got != "no-store" {
228 t.Errorf("Cache-Control = %q, want no-store: the page carries a one-time PKCE state", got)
229 }
230 // Rendered as Memoria's door: the layout, its bar, the door, and
231 // rastrillo's tab title for the state. (No footer: it is a sign-in
232 // page, and the footer is said only to somebody signed in.)
233 for _, want := range []string{"<header estilo-bar", "estilo-door", "<title>Signing in to Memoria</title>"} {
234 if !strings.Contains(body, want) {
235 t.Errorf("the continuation page lacks %q", want)
236 }
237 }
238 if strings.Contains(body, "<footer") {
239 t.Error("the continuation page carries the signed-in footer")
240 }
241}
242
243// And the paths that must NOT change: a non-owner still gets the guard's
244// same-origin redirect with no dial (gate 33's ground), and an address with
245// no Keymail still gets the magic link's same-origin redirect, untouched.
246func TestSigninPathsThatDoNotLeaveAreUnchanged(t *testing.T) {
247 h, km := keymailSigninApp(t)
248
249 rr := beginSignin(t, h, "stranger@elsewhere.test")
250 if rr.Code != http.StatusSeeOther || !sentLocation(rr.Header().Get("Location")) {
251 t.Errorf("non-owner: %d %q, want 303 to Begin's Sent", rr.Code, rr.Header().Get("Location"))
252 }
253 if len(km.hits) != 0 {
254 t.Errorf("a non-owner's sign-in reached the network: %v", km.hits)
255 }
256
257 // An owner whose domain has no Keymail (the fake 404s other hosts).
258 km.host = "nowhere.invalid"
259 rr = beginSignin(t, h, dialTestOwner)
260 if rr.Code != http.StatusSeeOther || !strings.HasPrefix(rr.Header().Get("Location"), "/") {
261 t.Errorf("magic-link path: %d %q, want a same-origin 303", rr.Code, rr.Header().Get("Location"))
262 }
263}
264
265// authorizeHref is the authorize URL a continuation page carries: the
266// door's Continue link (rastrillo's words; it never names Keymail).
267var authorizeHref = regexp.MustCompile(`href="(https://example\.test/oauth/authorize\?[^"]+)"`)
268
269// A Keymail sign-in that comes back verified for an address Admit refuses
270// is the door, in auth's own 403, through the Refused hook (app.refused):
271// not rastrillo's bare text, not a redirect to a query anybody could
272// type, and no session. beginGuard refuses a non-owner before Begin
273// (gate 33), so the refusal is reached the way the magic link's is: the
274// address is an owner when the sign-in starts and is not one when it
275// comes back. The admitted half runs first, through the same continuation
276// page, and its session opens the index — or the refusal proves nothing.
277func TestKeymailRefusalIsTheDoor(t *testing.T) {
278 km := &fakeKeymail{host: "example.test"}
279 dbPath := filepath.Join(t.TempDir(), "app.db")
280 h := keymailSigninAppWith(t, dbPath, []string{dialTestOwner}, km)
281
282 // begin starts a Keymail sign-in on h and returns the browser that
283 // carries it and the callback Keymail would send it to.
284 begin := func() (*client, string) {
285 t.Helper()
286 c := newClient(t, h)
287 rr := c.do(http.MethodPost, testOrigin+"/auth/begin", url.Values{"address": {dialTestOwner}})
288 page := c.get(testOrigin + location(t, rr))
289 m := authorizeHref.FindStringSubmatch(page.Body.String())
290 if page.Code != http.StatusOK || m == nil {
291 t.Fatalf("POST /auth/begin went to %d with no Keymail continuation:\n%s", page.Code, page.Body.String())
292 }
293 u, err := url.Parse(html.UnescapeString(m[1]))
294 if err != nil {
295 t.Fatal(err)
296 }
297 return c, testOrigin + "/auth/callback?" + url.Values{"state": {u.Query().Get("state")}, "code": {km.approve(dialTestOwner)}}.Encode()
298 }
299
300 c, callback := begin()
301 cb := c.get(callback)
302 if cb.Code != http.StatusSeeOther || !sessionSet(cb) {
303 t.Fatalf("admitted Keymail callback = %d (session %v), want 303 and a session:\n%s", cb.Code, sessionSet(cb), cb.Body.String())
304 }
305 dest := cb.Header().Get("Location")
306 for i := 0; i < 3 && dest != "/"; i++ {
307 dest = location(t, c.get(testOrigin+dest))
308 }
309 if got := c.get(testOrigin + "/"); dest != "/" || got.Code != http.StatusOK || !strings.Contains(got.Body.String(), "estilo-account") {
310 t.Fatalf("the Keymail session did not open the index (landed %q, GET / = %d)", dest, got.Code)
311 }
312
313 // Begun as an owner; back after the owner was removed.
314 c, callback = begin()
315 c.h = keymailSigninAppWith(t, dbPath, []string{"someone-else@example.test"}, km)
316 cb = c.get(callback)
317 if cb.Code != http.StatusForbidden || cb.Header().Get("Location") != "" || sessionSet(cb) {
318 t.Fatalf("refused Keymail callback = %d %q (session %v), want 403 and the door itself", cb.Code, cb.Header().Get("Location"), sessionSet(cb))
319 }
320 door := html.UnescapeString(cb.Body.String())
321 for _, want := range []string{"estilo-door", `name="address"`, "That email can’t sign in to Memoria. Use a different email, or ask whoever runs this team to add it."} {
322 if !strings.Contains(door, want) {
323 t.Errorf("the refusal door lacks %q:\n%s", want, door)
324 }
325 }
326 if strings.Contains(door, "verified but not admitted") {
327 t.Error("the refusal is still rastrillo's bare text")
328 }
329 // The sentence means "you proved this address and it is not
330 // admitted": nobody may summon it by typing a URL.
331 if spoof := html.UnescapeString(newClient(t, h).get(testOrigin + "/signin?err=refused").Body.String()); strings.Contains(spoof, "can’t sign in to Memoria") {
332 t.Error("anybody can show the refusal by visiting /signin?err=refused")
333 }
334}
335
336func contains(xs []string, want string) bool {
337 for _, x := range xs {
338 if x == want {
339 return true
340 }
341 }
342 return false
343}
344
345var _ = httptest.NewRecorder
346