oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "context"
5 "encoding/json"
6 "net"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "github.com/keymaildev/signin"
16)
17
18// keymailStub is a federation server good enough to drive the whole
19// Keymail upgrade end to end: classification, the authorize redirect and
20// the token exchange.
21//
22// It exists because the Keymail path had NO test at all. Everything
23// about it was asserted in comments — that the Gate covers it, that the
24// pending cookie is cleared on read, that its attributes are
25// load-bearing — and a review proved each of those claims survivable by
26// mutation precisely because nothing ever drove the path.
27type keymailStub struct {
28 srv *httptest.Server
29 host string
30 address string
31 // authTime is what the server reports as the moment an
32 // authenticator gesture happened. Zero means "no gesture", which
33 // callers must treat as the weaker of the two methods.
34 authTime time.Time
35 // reauth is what /.well-known/keymail advertises. keymail serve
36 // answers prompt=login with 403 unless it says "reauth": true, so
37 // Home may only ask for a forced gesture when this is set. Set it
38 // before the first classification: the classifier caches it per
39 // domain.
40 reauth bool
41
42 mu sync.Mutex
43 spent map[string]bool
44}
45
46// newKeymailStub wires app.flow to talk to a local federation server for
47// one address's domain.
48func newKeymailStub(t *testing.T, app *testApp, address string) *keymailStub {
49 t.Helper()
50 _, domain, err := signin.SplitAddress(address)
51 if err != nil {
52 t.Fatalf("SplitAddress(%q): %v", address, err)
53 }
54
55 k := &keymailStub{
56 address: address,
57 authTime: time.Now().Truncate(time.Second),
58 spent: map[string]bool{},
59 }
60
61 mux := http.NewServeMux()
62 mux.HandleFunc("/.well-known/keymail", func(w http.ResponseWriter, r *http.Request) {
63 k.mu.Lock()
64 reauth := k.reauth
65 k.mu.Unlock()
66 writeJSON(t, w, map[string]any{"version": "1", "reauth": reauth})
67 })
68 mux.HandleFunc("/api/federation/lookup", func(w http.ResponseWriter, r *http.Request) {
69 // A claimed inbox is a 200; anything else is "not keymail".
70 if r.URL.Query().Get("addr") != strings.ToLower(k.address) {
71 http.Error(w, "no such inbox", http.StatusNotFound)
72 return
73 }
74 writeJSON(t, w, map[string]any{"ok": true})
75 })
76 mux.HandleFunc("/api/oauth/token", func(w http.ResponseWriter, r *http.Request) {
77 // A real federation server redeems an authorization code once,
78 // and once PER CODE — a fresh round trip issues a fresh code.
79 // The stub must model both halves: spending globally made a
80 // second legitimate sign-in fail, and not spending at all let a
81 // replay through. Both versions were written before this
82 // comment.
83 var body struct {
84 Code string `json:"code"`
85 }
86 if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
87 http.Error(w, "bad request", http.StatusBadRequest)
88 return
89 }
90 k.mu.Lock()
91 used := k.spent[body.Code]
92 k.spent[body.Code] = true
93 authTime := k.authTime
94 k.mu.Unlock()
95 if used {
96 http.Error(w, "code already redeemed", http.StatusBadRequest)
97 return
98 }
99 writeJSON(t, w, map[string]any{
100 "access_token": "stub-access-token",
101 "token_type": "bearer",
102 "address": k.address,
103 "auth_time": unixOrZero(authTime),
104 })
105 })
106
107 k.srv = httptest.NewServer(mux)
108 t.Cleanup(k.srv.Close)
109 k.host = strings.TrimPrefix(k.srv.URL, "http://")
110
111 // The delegation record keymail's own dnsFedHost would publish.
112 app.flow.Classifier.Scheme = "http"
113 app.flow.Classifier.LookupTXT = func(_ context.Context, name string) ([]string, error) {
114 if name == "_keymail."+domain {
115 return []string{"v=1 host=" + k.host}, nil
116 }
117 return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true}
118 }
119 // newFlow builds Base as https://<server>; the stub is plain http.
120 app.flow.Keymail = func(server string) *signin.Keymail {
121 return &signin.Keymail{
122 Base: "http://" + server,
123 Origin: Origin,
124 RedirectPath: callbackPath,
125 // Bounded, like the real one. Omitting this left exchanges
126 // on the library's 15s default client, so a stub test would
127 // have passed against an app whose timeout wiring was gone.
128 HTTP: &http.Client{Timeout: classifierTimeout},
129 }
130 }
131 return k
132}
133
134// unixOrZero is what keymail sends: 0 when no gesture backed the
135// approval, never a plausible invented time. time.Time{}.Unix() is a
136// large negative number, which the library would also read as absent,
137// but the stub should say what the server says.
138func unixOrZero(t time.Time) int64 {
139 if t.IsZero() {
140 return 0
141 }
142 return t.Unix()
143}
144
145func writeJSON(t *testing.T, w http.ResponseWriter, v any) {
146 t.Helper()
147 w.Header().Set("Content-Type", "application/json")
148 if err := json.NewEncoder(w).Encode(v); err != nil {
149 t.Errorf("stub encode: %v", err)
150 }
151}
152
153// beginKeymail runs POST /signin for an address the stub claims, and
154// returns the pending cookie and the state the flow sealed into it.
155func beginKeymail(t *testing.T, app *testApp, address string) (*http.Cookie, string) {
156 t.Helper()
157 rec := signIn(t, app, address)
158 loc := doorContinuation(t, rec)
159 if !strings.Contains(loc, "/oauth/authorize") {
160 t.Fatalf("sign-in went to %q, which is not the keymail authorize URL — "+
161 "classification did not take the keymail branch", loc)
162 }
163 if _, sent := app.mailer.last(); sent {
164 t.Fatal("the keymail branch sent a magic link as well")
165 }
166
167 u, err := url.Parse(loc)
168 if err != nil {
169 t.Fatal(err)
170 }
171 state := u.Query().Get("state")
172 if state == "" {
173 t.Fatal("the authorize URL carries no state")
174 }
175
176 var pending *http.Cookie
177 for _, c := range (&http.Response{Header: rec.Header()}).Cookies() {
178 if c.Name == pendingCookie {
179 pending = c
180 }
181 }
182 if pending == nil {
183 t.Fatalf("no %s cookie was set", pendingCookie)
184 }
185 return pending, state
186}
187
188// callback drives GET /signin/callback with the given cookies. The code
189// is a parameter because a real authorization code is single use: two
190// round trips carry two codes, and a replay carries the same one twice.
191func callback(t *testing.T, app *testApp, code, state string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
192 t.Helper()
193 req := httptest.NewRequest(http.MethodGet,
194 callbackPath+"?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), nil)
195 req.Host = credentialHost
196 for _, c := range cookies {
197 if c != nil {
198 req.AddCookie(c)
199 }
200 }
201 w := httptest.NewRecorder()
202 app.Router().ServeHTTP(w, req)
203 return w
204}
205