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 "html"
5 "net/http"
6 "net/http/httptest"
7 "net/url"
8 "regexp"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/home/internal/home/sealtest"
14 "amadan.net/rastrillo/rastrillo/assertion"
15)
16
17// The fresh step-up through Keymail (implementation/fresh-assertion.md,
18// "Keymail step-up"). A fresh intent may take the Keymail door only
19// when the server can be told to demand a new gesture (prompt=login,
20// advertised as "reauth": true) and only counts when the gesture time
21// Keymail reports is inside the window. Everything else is the email
22// link, as before.
23
24const freshKeymailAddress = "person@keymail.invalid"
25
26// freshSignInForm walks a fresh, unauthenticated intent to the sign-in
27// form the way a browser does, and returns the intent and the
28// navigation cookie that carries /authorize/resume.
29func freshSignInForm(t *testing.T, p exchangePair, session *http.Cookie) (intent, navigation *http.Cookie) {
30 t.Helper()
31 _, intent = p.startFresh(t, session)
32 resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
33 if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" {
34 t.Fatal("fresh intent did not ask for sign-in", resume.Code, resume.Header().Get("Location"))
35 }
36 form := exchangeRequest(p.credential.App, "GET", Origin+resume.Header().Get("Location"), "", nil, intent, session)
37 return intent, namedCookie(t, form, returnCookie)
38}
39
40// freshBegin POSTs the address under a fresh intent. It forgets earlier
41// mail first, so what the mailer holds afterwards is this begin's.
42func freshBegin(t *testing.T, p exchangePair, path, address string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
43 t.Helper()
44 p.credential.mailer.mu.Lock()
45 p.credential.mailer.sent = nil
46 p.credential.mailer.mu.Unlock()
47 return exchangeRequest(p.credential.App, "POST", Origin+path, Origin, url.Values{"address": {address}}, cookies...)
48}
49
50// keymailContinuation returns the authorize URL a begin handed the
51// browser, the pending cookie and the sealed state; it fails the test
52// if the begin did anything else, mail included.
53func keymailContinuation(t *testing.T, p exchangePair, begin *httptest.ResponseRecorder) (*url.URL, *http.Cookie) {
54 t.Helper()
55 if begin.Code != 200 {
56 t.Fatal("fresh Keymail begin did not continue to Keymail", begin.Code, begin.Header().Get("Location"))
57 }
58 to := doorContinuation(t, begin)
59 if !strings.Contains(to, "/oauth/authorize?") {
60 t.Fatal("fresh Keymail begin did not continue to Keymail", to)
61 }
62 if _, sent := p.credential.mailer.last(); sent {
63 t.Fatal("fresh Keymail begin also sent mail")
64 }
65 u, err := url.Parse(to)
66 if err != nil {
67 t.Fatal(err)
68 }
69 return u, namedCookie(t, begin, pendingCookie)
70}
71
72func TestFreshIntentStartsKeymailWithForcedLogin(t *testing.T) {
73 p := newExchangePair(t)
74 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
75 stub.reauth = true
76 intent, navigation := freshSignInForm(t, p, nil)
77
78 u, _ := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation))
79 if got := u.Query()["prompt"]; len(got) != 1 || got[0] != "login" {
80 t.Fatalf("fresh Keymail authorize URL carries prompt=%q, want exactly login", got)
81 }
82}
83
84func TestFreshKeymailGestureYieldsAssertionWithKeymailAuthTime(t *testing.T) {
85 p := newExchangePair(t)
86 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
87 stub.reauth = true
88 intent, navigation := freshSignInForm(t, p, nil)
89
90 u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation))
91 // The simulated gesture happens after the link transaction starts.
92 stub.mu.Lock()
93 stub.authTime = time.Now().Truncate(time.Second)
94 stub.mu.Unlock()
95 back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation)
96 if back.Code != 303 || back.Header().Get("Location") != "/authorize/resume" || sessionCookie(back) == nil {
97 t.Fatal("fresh Keymail gesture was not credited", back.Code, back.Header().Get("Location"))
98 }
99 token, _ := p.mint(t, intent, sessionCookie(back))
100 verifier, err := assertion.NewVerifier(Origin, directoryOrigin, p.credential.runtime.keys)
101 if err != nil {
102 t.Fatal(err)
103 }
104 claims, err := verifier.Verify(token, time.Now())
105 if err != nil {
106 t.Fatal(err)
107 }
108 if claims.AuthTime != stub.authTime.Unix() {
109 t.Fatalf("assertion auth_time=%d, want Keymail's %d", claims.AuthTime, stub.authTime.Unix())
110 }
111}
112
113// A gesture Keymail did not report (zero), one older than the window,
114// and one from the future must not become a session in a fresh flow.
115// Each falls back to the email link with the intent intact, and that
116// link — taken through the form a browser would actually submit —
117// completes the step-up.
118//
119// Zero is the case with teeth: resume reads a zero AuthTime as the
120// session's At, which is the callback's own clock, so without the
121// callback's check a standing Keymail approval would pass as fresh.
122func TestFreshKeymailWithoutAFreshGestureFallsBackToEmail(t *testing.T) {
123 for name, at := range map[string]func() time.Time{
124 "zero": func() time.Time { return time.Time{} },
125 "stale": func() time.Time { return time.Now().Add(-301 * time.Second) },
126 "hour": func() time.Time { return time.Now().Add(-time.Hour) },
127 "future": func() time.Time { return time.Now().Add(5 * time.Second) },
128 "far": func() time.Time { return time.Now().Add(time.Hour) },
129 } {
130 t.Run(name, func(t *testing.T) {
131 p := newExchangePair(t)
132 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
133 stub.reauth = true
134 stub.authTime = at()
135 intent, navigation := freshSignInForm(t, p, nil)
136
137 u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation))
138 back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation)
139 if back.Code != 303 || back.Header().Get("Location") != "/signin?force=1" || sessionCookie(back) != nil {
140 t.Fatal("Keymail approval without a fresh gesture was credited", back.Code, back.Header().Get("Location"))
141 }
142 if intentCleared(back) {
143 t.Fatal("fallback discarded the assertion intent")
144 }
145
146 // The form the fallback renders must itself carry the
147 // override: the browser submits its action, not the URL it
148 // was reached by.
149 form := exchangeRequest(p.credential.App, "GET", Origin+"/signin?force=1", "", nil, intent, navigation)
150 if form.Code != 200 {
151 t.Fatal("fallback form", form.Code)
152 }
153 if c := intentFrom(form); c != nil {
154 navigation = c
155 }
156 sent := freshBegin(t, p, formAction(t, form), freshKeymailAddress, intent, navigation)
157 if sent.Code != 303 || sent.Header().Get("Location") != "/signin/sent" {
158 t.Fatal("fallback did not email", sent.Code)
159 }
160 verified := exchangeRequest(p.credential.App, "POST", Origin+linkPath, Origin, url.Values{"token": {capturedLink(t, p.credential)}}, intent, navigation)
161 if verified.Code != 303 || verified.Header().Get("Location") != "/authorize/resume" {
162 t.Fatal("email fallback lost the step-up continuation", verified.Code)
163 }
164 p.mint(t, intent, sessionCookie(verified))
165 })
166 }
167}
168
169// formAction is the sign-in form's own action, which is what a browser
170// submits — not the URL that rendered the form. Tests that POST to a URL
171// of their own choosing are how the ordinary fallback's lost override
172// survived.
173func formAction(t *testing.T, r *httptest.ResponseRecorder) string {
174 t.Helper()
175 m := regexp.MustCompile(`<form rst-signin-form method="post" action="([^"]*)"`).FindStringSubmatch(r.Body.String())
176 if len(m) != 2 {
177 t.Fatal("no sign-in form")
178 }
179 return html.UnescapeString(m[1])
180}
181
182func intentCleared(r *httptest.ResponseRecorder) bool {
183 for _, c := range r.Result().Cookies() {
184 if c.Name == assertionIntentCookie {
185 return true
186 }
187 }
188 return false
189}
190
191func TestFreshKeymailWithoutReauthStillEmails(t *testing.T) {
192 p := newExchangePair(t)
193 newKeymailStub(t, p.credential, freshKeymailAddress) // reauth: false
194 intent, navigation := freshSignInForm(t, p, nil)
195 begin := freshBegin(t, p, "/signin", freshKeymailAddress, intent, navigation)
196 if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" {
197 t.Fatal("fresh flow took Keymail on a server that cannot force a gesture", begin.Code)
198 }
199 if m, sent := p.credential.mailer.last(); !sent || m.To != freshKeymailAddress {
200 t.Fatal("no email was sent")
201 }
202}
203
204func TestFreshNonKeymailAddressEmails(t *testing.T) {
205 p := newExchangePair(t)
206 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
207 stub.reauth = true
208 const other = "nobody@keymail.invalid" // the stub's lookup answers 404
209 intent, navigation := freshSignInForm(t, p, nil)
210 begin := freshBegin(t, p, "/signin", other, intent, navigation)
211 if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" {
212 t.Fatal("non-Keymail address did not get email", begin.Code)
213 }
214 if m, sent := p.credential.mailer.last(); !sent || m.To != other {
215 t.Fatal("no email was sent")
216 }
217}
218
219// The ordinary path keeps what it had: Keymail, and whatever prompt the
220// library's own classification chose, with no new check on the return.
221func TestOrdinaryKeymailIgnoresGestureTime(t *testing.T) {
222 p := newExchangePair(t)
223 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
224 stub.reauth = true
225 stub.authTime = time.Time{}
226 _, intent := p.start(t)
227 pending, state := beginKeymail(t, p.credential, freshKeymailAddress)
228 back := callback(t, p.credential, "code-1", state, pending, intent)
229 if sessionCookie(back) == nil {
230 t.Fatal("ordinary Keymail sign-in now depends on gesture time", back.Code, back.Header().Get("Location"))
231 }
232}
233
234func TestFreshKeymailCannotSwitchSubject(t *testing.T) {
235 p := newExchangePair(t)
236 original := signInFully(t, p.credential, sealtest.CanaryAddress)
237 backdateCredential(t, p, time.Now().Add(-time.Hour))
238 stub := newKeymailStub(t, p.credential, freshKeymailAddress)
239 stub.reauth = true
240 intent, navigation := freshSignInForm(t, p, original)
241
242 u, pending := keymailContinuation(t, p, freshBegin(t, p, "/signin", freshKeymailAddress, intent, original, navigation))
243 back := callback(t, p.credential, "code-1", u.Query().Get("state"), pending, intent, navigation)
244 other := sessionCookie(back)
245 if other == nil || back.Header().Get("Location") != "/authorize/resume" {
246 t.Fatal("fresh Keymail sign-in did not complete", back.Code)
247 }
248 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, other)
249 if r.Code != 400 || strings.Contains(r.Body.String(), `name="assertion"`) {
250 t.Fatal("a different person's fresh Keymail gesture satisfied the original step-up", r.Code)
251 }
252}
253
254// The ordinary Keymail fallback, driven as a browser drives it: a failed
255// return lands on /signin?force=1, and the person submits the form that
256// page renders. The override has to be in that form's action, or the
257// next attempt classifies again and goes straight back to Keymail.
258func TestOrdinaryKeymailFallbackFormEmails(t *testing.T) {
259 app := newTestApp(t)
260 newKeymailStub(t, app, freshKeymailAddress)
261 pending, _ := beginKeymail(t, app, freshKeymailAddress)
262 back := callback(t, app, "code-1", "invalid-state", pending)
263 if back.Header().Get("Location") != "/signin?force=1" || sessionCookie(back) != nil {
264 t.Fatal("failed Keymail return did not fall back", back.Code)
265 }
266 form := returnRequest(app, "GET", back.Header().Get("Location"), nil)
267 sent := returnRequest(app, "POST", formAction(t, form), url.Values{"address": {freshKeymailAddress}})
268 if sent.Code != 303 || sent.Header().Get("Location") != "/signin/sent" {
269 t.Fatal("the fallback form went back to Keymail instead of emailing", sent.Code)
270 }
271 if m, ok := app.mailer.last(); !ok || m.To != freshKeymailAddress {
272 t.Fatal("no email was sent")
273 }
274 // And the plain form stays plain.
275 if got := formAction(t, returnRequest(app, "GET", "/signin", nil)); got != "/signin" {
276 t.Fatalf("plain form action=%q", got)
277 }
278}
279
280// A Keymail session that reported no gesture time has nothing a step-up
281// can credit: its At is when Home minted it, not when the person did
282// anything. It must not pass a later fresh intent just for being new.
283// The control is the same flow with a reported gesture, which passes.
284func TestKeymailSessionWithoutGestureTimeIsNotFresh(t *testing.T) {
285 for name, gesture := range map[string]bool{"no gesture": false, "gesture": true} {
286 t.Run(name, func(t *testing.T) {
287 p := newExchangePair(t)
288 stub := newKeymailStub(t, p.credential, freshKeymailAddress) // reauth: false
289 if !gesture {
290 stub.authTime = time.Time{}
291 }
292 pending, state := beginKeymail(t, p.credential, freshKeymailAddress)
293 session := sessionCookie(callback(t, p.credential, "code-1", state, pending))
294 if session == nil {
295 t.Fatal("ordinary Keymail sign-in failed")
296 }
297 _, intent := p.startFresh(t, session)
298 resume := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
299 if resume.Code != 303 || resume.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume" || strings.Contains(resume.Body.String(), `name="assertion"`) {
300 t.Fatal("a Keymail session with no gesture time satisfied a step-up", resume.Code)
301 }
302 form := exchangeRequest(p.credential.App, "GET", Origin+resume.Header().Get("Location"), "", nil, intent, session)
303 navigation := namedCookie(t, form, returnCookie)
304 begin := freshBegin(t, p, formAction(t, form), freshKeymailAddress, intent, session, navigation)
305 if begin.Code != 303 || begin.Header().Get("Location") != "/signin/sent" {
306 t.Fatal("step-up did not fall back to email", begin.Code)
307 }
308 })
309 }
310}
311
312// An error re-render of the form must keep the override too. Each of
313// these renders the form again, and the person resubmits that form: if
314// its action is plain /signin, the retry goes back to Keymail.
315func TestForcedFormErrorsKeepTheOverride(t *testing.T) {
316 t.Run("bad address", func(t *testing.T) {
317 app := newTestApp(t)
318 newKeymailStub(t, app, freshKeymailAddress)
319 bad := returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"person@localhost"}})
320 if bad.Code != 400 {
321 t.Fatal("single-label domain accepted", bad.Code)
322 }
323 retry := returnRequest(app, "POST", formAction(t, bad), url.Values{"address": {freshKeymailAddress}})
324 if retry.Code != 303 || retry.Header().Get("Location") != "/signin/sent" {
325 t.Fatal("retry after an error went back to Keymail", retry.Code)
326 }
327 })
328 t.Run("rate limited", func(t *testing.T) {
329 app := newTestApp(t)
330 var last *httptest.ResponseRecorder
331 for range 6 {
332 last = returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"person@example.invalid"}})
333 }
334 if last.Code != 429 {
335 t.Fatal("address budget not reached", last.Code)
336 }
337 if got := formAction(t, last); got != "/signin?force=1" {
338 t.Fatalf("rate-limited form action=%q", got)
339 }
340 })
341 t.Run("plain stays plain", func(t *testing.T) {
342 app := newTestApp(t)
343 bad := returnRequest(app, "POST", "/signin", url.Values{"address": {"person@localhost"}})
344 if got := formAction(t, bad); got != "/signin" {
345 t.Fatalf("plain error form action=%q", got)
346 }
347 })
348}
349