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 "amadan.net/oficina/home/handoff"
5 "amadan.net/rastrillo/rastrillo/assertion"
6 "amadan.net/rastrillo/rastrillo/sessions"
7 "encoding/base64"
8 "encoding/json"
9 "github.com/keymaildev/signin"
10 "html"
11 "net/http"
12 "net/http/httptest"
13 "net/url"
14 "regexp"
15 "strings"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/home/internal/home/sealtest"
20 "amadan.net/rastrillo/rastrillo/migrate"
21)
22
23func TestIDLinkAlwaysRequiresNewGesture(t *testing.T) {
24 p := newExchangePair(t)
25 session := signInFully(t, p.credential, sealtest.CanaryAddress)
26 _, intent := p.startFresh(t, session)
27 for _, method := range []string{"GET", "POST"} {
28 r := exchangeRequest(p.credential.App, method, Origin+"/authorize/resume", Origin, nil, intent, session)
29 if r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") {
30 t.Fatalf("%s reused existing session: %d", method, r.Code)
31 }
32 }
33}
34
35// TestIDStraightIn is Paul's straight-in ruling (2026-11-20; slice 1
36// spec, Assertion and browser exchange, step 2): with an id.* session
37// and no forced authentication, the GET that lands on /authorize/resume
38// mints and renders the form-POST delivery itself, with no Continue page.
39// The assertion rides only the form body: never the URL, a redirect or a
40// log line.
41func TestIDStraightIn(t *testing.T) {
42 p := newExchangePair(t)
43 session := signInFully(t, p.credential, sealtest.CanaryAddress)
44 pending, intent := p.start(t)
45 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
46 body := r.Body.String()
47 m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(body)
48 if r.Code != 200 || len(m) != 2 {
49 t.Fatal("GET did not go straight in", r.Code)
50 }
51 token := html.UnescapeString(m[1])
52 if strings.Contains(body, `action="/authorize/resume"`) || strings.Contains(body, "Continue to the app") {
53 t.Fatal("the Continue page is still drawn")
54 }
55 // The delivery is the hop: auto-submit, with Continue for script-off.
56 for _, want := range []string{`action="` + directoryOrigin + handoff.CallbackPath + `"`, `data-assertion-handoff`, `<button type="submit" rst-btn="primary" estilo-signin-action>Continue</button>`, versioned("/static/assertion.js")} {
57 if !strings.Contains(body, want) {
58 t.Fatalf("delivery lacks %q", want)
59 }
60 }
61 if r.Header().Get("Cache-Control") != "no-store" || r.Header().Get("Referrer-Policy") != "strict-origin-when-cross-origin" || r.Header().Get("Location") != "" {
62 t.Fatal("delivery headers changed", r.Header())
63 }
64 cleared := false
65 for _, c := range r.Result().Cookies() {
66 cleared = cleared || (c.Name == assertionIntentCookie && c.MaxAge < 0)
67 }
68 if !cleared {
69 t.Fatal("intent survived the mint")
70 }
71 for _, h := range r.Header().Values("Set-Cookie") {
72 if strings.Contains(h, token) {
73 t.Fatal("assertion in a cookie")
74 }
75 }
76 if strings.Contains(p.logs.String(), token) || strings.Contains(p.logs.String(), sealtest.CanaryAddress) {
77 t.Fatal("assertion or address in the logs")
78 }
79 // And it finishes: the app's callback takes it.
80 if p.finish(t, token, pending) == nil {
81 t.Fatal("no app session")
82 }
83 // The POST still mints, for a Continue page left open in a tab, and
84 // still behind csrf.Protect.
85 _, again := p.start(t)
86 if bad := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", "https://evil.invalid", url.Values{}, again, session); bad.Code != 403 {
87 t.Fatal("POST lacks CSRF protection", bad.Code)
88 }
89 if good := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, url.Values{}, again, session); good.Code != 200 || !strings.Contains(good.Body.String(), `name="assertion"`) {
90 t.Fatal("POST did not mint", good.Code)
91 }
92}
93
94// TestIDStraightInForeignNonceRefusedAtFinish: an assertion the
95// straight-in GET minted for a nonce that is not this browser's pending
96// one (another browser's, or one made up and sent to /authorize) never
97// signs this browser in at the app: the app's finish refuses it.
98func TestIDStraightInForeignNonceRefusedAtFinish(t *testing.T) {
99 p := newExchangePair(t)
100 session := signInFully(t, p.credential, sealtest.CanaryAddress)
101 pending, _ := p.start(t)
102 _, otherIntent := p.start(t)
103 junk := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?consumer=directory&nonce="+base64.RawURLEncoding.EncodeToString(make([]byte, 16)), "", nil, session)
104 if junk.Code != http.StatusSeeOther {
105 t.Fatal("junk authorize", junk.Code)
106 }
107 for name, intent := range map[string]*http.Cookie{"another browser's nonce": otherIntent, "a made-up nonce": namedCookie(t, junk, assertionIntentCookie)} {
108 t.Run(name, func(t *testing.T) {
109 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
110 m := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(r.Body.String())
111 if r.Code != 200 || len(m) != 2 {
112 t.Fatal("no straight-in mint", r.Code)
113 }
114 callback := exchangeRequest(p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, url.Values{"assertion": {html.UnescapeString(m[1])}})
115 if sessionCookie(callback) != nil {
116 t.Fatal("the callback minted a session")
117 }
118 cookies := []*http.Cookie{pending}
119 for _, c := range callback.Result().Cookies() {
120 if c.Name == "__Host-oficina-assertion-inbox" && c.Value != "" {
121 cookies = append(cookies, c)
122 }
123 }
124 finish := exchangeRequest(p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, cookies...)
125 if sessionCookie(finish) != nil || finish.Header().Get("Location") == "/?team=blue" {
126 t.Fatal("a foreign nonce signed this browser in", finish.Code)
127 }
128 })
129 }
130}
131
132// TestIDStraightInMintsOnlyForANavigation: the minting GET refuses a
133// prefetch or prerender, and anything a browser says is not a top-level
134// document navigation; a browser that sends no Sec-Fetch headers is
135// judged on the purpose headers alone.
136func TestIDStraightInMintsOnlyForANavigation(t *testing.T) {
137 p := newExchangePair(t)
138 session := signInFully(t, p.credential, sealtest.CanaryAddress)
139 _, intent := p.start(t)
140 navigate := map[string]string{"Sec-Fetch-Mode": "navigate", "Sec-Fetch-Dest": "document", "Sec-Fetch-Site": "cross-site"}
141 with := func(base map[string]string, k, v string) map[string]string {
142 out := map[string]string{}
143 for a, b := range base {
144 out[a] = b
145 }
146 if v == "" {
147 delete(out, k)
148 } else {
149 out[k] = v
150 }
151 return out
152 }
153 get := func(headers map[string]string) *httptest.ResponseRecorder {
154 r := httptest.NewRequest("GET", Origin+"/authorize/resume", nil)
155 r.AddCookie(intent)
156 r.AddCookie(session)
157 for k, v := range headers {
158 r.Header.Set(k, v)
159 }
160 w := httptest.NewRecorder()
161 p.credential.Router().ServeHTTP(w, r)
162 return w
163 }
164 for name, headers := range map[string]map[string]string{
165 "prefetch": with(navigate, "Sec-Purpose", "prefetch"),
166 "prerender": with(navigate, "Sec-Purpose", "prefetch;prerender"),
167 "legacy prefetch": {"Purpose": "prefetch"},
168 "fetch()": with(with(navigate, "Sec-Fetch-Mode", "cors"), "Sec-Fetch-Dest", "empty"),
169 "no-cors": with(with(navigate, "Sec-Fetch-Mode", "no-cors"), "Sec-Fetch-Dest", "image"),
170 "iframe": with(navigate, "Sec-Fetch-Dest", "iframe"),
171 "mode without dest": with(navigate, "Sec-Fetch-Dest", ""),
172 "dest without mode": with(navigate, "Sec-Fetch-Mode", ""),
173 } {
174 if r := get(headers); r.Code == 200 || strings.Contains(r.Body.String(), `name="assertion"`) {
175 t.Errorf("%s minted: %d", name, r.Code)
176 }
177 }
178 for name, headers := range map[string]map[string]string{"navigation": navigate, "no Sec-Fetch headers": {}} {
179 if r := get(headers); r.Code != 200 || !strings.Contains(r.Body.String(), `name="assertion"`) {
180 t.Errorf("%s did not mint: %d", name, r.Code)
181 }
182 }
183}
184
185// TestIDStraightInWithoutSessionIsTheDoor: no id.* session, no mint; the
186// sign-in door, coming back to the resume.
187func TestIDStraightInWithoutSessionIsTheDoor(t *testing.T) {
188 p := newExchangePair(t)
189 _, intent := p.start(t)
190 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent)
191 if r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header().Get("Location"), "/signin") || strings.Contains(r.Body.String(), `name="assertion"`) {
192 t.Fatal("no session did not go to the door", r.Code, r.Header().Get("Location"))
193 }
194}
195
196// TestIDStraightInNeverSkipsForcedAuthentication: a link or a step-up
197// (max_age=300) on a standing session, however recent, still goes to the
198// door for a new gesture; after that gesture the GET goes straight in.
199func TestIDStraightInNeverSkipsForcedAuthentication(t *testing.T) {
200 p := newExchangePair(t)
201 session := signInFully(t, p.credential, sealtest.CanaryAddress)
202 _, intent := p.startFresh(t, session)
203 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, session)
204 if r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") || strings.Contains(r.Body.String(), `name="assertion"`) {
205 t.Fatal("forced authentication was skipped", r.Code)
206 }
207 fresh := signInFully(t, p.credential, sealtest.CanaryAddress)
208 if after := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, fresh); after.Code != 200 || !strings.Contains(after.Body.String(), `name="assertion"`) {
209 t.Fatal("a fresh gesture did not go straight in", after.Code)
210 }
211}
212
213func TestIDRevokedCachedSessionCannotMint(t *testing.T) {
214 p := newExchangePair(t)
215 s := signInFully(t, p.credential, sealtest.CanaryAddress)
216 _, intent := p.start(t)
217 r := httptest.NewRequest("POST", Origin+"/authorize/resume", nil)
218 r.AddCookie(s)
219 r.AddCookie(intent)
220 w := httptest.NewRecorder()
221 p.credential.sessions.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
222 if _, err := p.credential.db.Writer().Exec("DELETE FROM sessions"); err != nil {
223 t.Fatal(err)
224 }
225 p.credential.handleAssertion(w, r)
226 })).ServeHTTP(w, r)
227 if strings.Contains(w.Body.String(), `name="assertion"`) {
228 t.Fatal("cached revoked session minted an assertion")
229 }
230}
231
232func TestIDLegacyRuntimeAppliesIdentitySchema(t *testing.T) {
233 d, err := migrate.Replay(t.Context(), (Runtime{}).ServingSchema().All())
234 if err != nil {
235 t.Fatal(err)
236 }
237 defer d.Close()
238 if _, err = d.Exec("UPDATE home_id_clock SET high_water=1 WHERE id=1"); err != nil {
239 t.Fatal("legacy runtime cannot serve identity handlers", err)
240 }
241 a := newTestApp(t)
242 signInFully(t, a, sealtest.CanaryAddress)
243}
244
245func TestIDLinkRejectsProofBeforeTransactionStart(t *testing.T) {
246 p := newExchangePair(t)
247 old := signInFully(t, p.credential, sealtest.CanaryAddress)
248 _, intent := p.startFresh(t, old)
249 current := signInFully(t, p.credential, sealtest.CanaryAddress)
250 if _, err := p.credential.db.Writer().Exec("UPDATE sessions SET auth_time=? WHERE token_hash=?", time.Now().Add(-30*time.Second).UTC().Format(time.RFC3339), sessions.HashToken(current.Value)); err != nil {
251 t.Fatal(err)
252 }
253 r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, current)
254 if r.Code != 303 || !strings.HasPrefix(r.Header().Get("Location"), "/signin?") {
255 t.Fatal("otherwise fresh proof predating link start was accepted")
256 }
257}
258
259func TestIDLinkRejectsPassiveMintedSession(t *testing.T) {
260 p := newExchangePair(t)
261 _, intent := p.startFresh(t, nil)
262 s := signInFully(t, p.credential, sealtest.CanaryAddress)
263 p.credential.db.Writer().Exec("UPDATE sessions SET method='keymail',auth_time=''")
264 r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, s)
265 if r.Code != 303 {
266 t.Fatal("passive newly minted session satisfied linking")
267 }
268}
269
270func TestIDClosedAuthorize(t *testing.T) {
271 p := newExchangePair(t)
272 nonce, _ := assertion.RandomID()
273 base := "consumer=directory&nonce=" + nonce
274 for _, query := range []string{base + "&consumer=directory", base + "&nonce=" + nonce, base + "&unexpected=1", "consumer=unknown&nonce=" + nonce, "consumer=directory&nonce=bad", base + "&max_age=301", base + "&max_age=300&max_age=300"} {
275 r := exchangeRequest(p.credential.App, "GET", Origin+"/authorize?"+query, "", nil)
276 if r.Code != 400 || len(r.Result().Cookies()) != 0 {
277 t.Fatal("ambiguous authorize accepted")
278 }
279 }
280}
281func TestIDAllSensitivePostsRequireOrigin(t *testing.T) {
282 p := newExchangePair(t)
283 for _, path := range []string{"/authorize/resume", "/passkey/direct/begin", "/passkey/direct/finish", "/passkey/register/begin", "/passkey/register/finish", "/passkey/signin/begin", "/passkey/signin/finish", "/passkey/signin/recovery", "/passkey/replace/begin", "/passkey/replace/finish", "/passkey/codes", "/passkey/notice"} {
284 r := exchangeRequest(p.credential.App, "POST", Origin+path, "https://evil.invalid", url.Values{})
285 if r.Code != 403 {
286 t.Fatal("cross-origin mutation admitted", path, r.Code)
287 }
288 }
289}
290
291func TestIDEmailMintPreservesVerificationTime(t *testing.T) {
292 a := newTestApp(t)
293 verified := time.Now().Add(-2 * time.Minute).UTC().Truncate(time.Second)
294 r := httptest.NewRequest("POST", Origin+linkPath, nil)
295 w := httptest.NewRecorder()
296 a.completeSignIn(w, r, signin.Identity{Address: sealtest.CanaryAddress, Method: signin.MethodMagicLink, At: verified})
297 c := sessionCookie(w)
298 if c == nil {
299 t.Fatal("email completion failed")
300 }
301 r.AddCookie(c)
302 s, ok := a.sessions.From(r)
303 if !ok || !s.AuthTime.Equal(verified) {
304 t.Fatal("email verification time was replaced with mint time")
305 }
306}
307
308func TestIDFreshIntentRequiresStartTime(t *testing.T) {
309 p := newExchangePair(t)
310 _, cookie := p.startFresh(t, nil)
311 req := httptest.NewRequest("GET", Origin+"/authorize/resume", nil)
312 req.AddCookie(cookie)
313 intent, ok := p.credential.readAssertionIntent(req, time.Now())
314 if !ok {
315 t.Fatal("fixture intent")
316 }
317 intent.Started = 0
318 raw, _ := json.Marshal(intent)
319 sealed, err := p.credential.secrets.Sealer.Seal("assertion.intent", raw)
320 if err != nil {
321 t.Fatal(err)
322 }
323 cookie.Value = base64.RawURLEncoding.EncodeToString(sealed)
324 session := signInFully(t, p.credential, sealtest.CanaryAddress)
325 r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, cookie, session)
326 if r.Code != 400 {
327 t.Fatal("old freshness intent without transaction start was accepted", r.Code)
328 }
329}
330
331func TestIDEmailInAnotherBrowserCannotFinishOriginalHandoff(t *testing.T) {
332 p := newExchangePair(t)
333 _, intent := p.start(t)
334 form := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume", "", nil, intent)
335 navigation := namedCookie(t, form, returnCookie)
336 exchangeRequest(p.credential.App, "POST", Origin+"/signin", Origin, url.Values{"address": {sealtest.CanaryAddress}}, intent, navigation)
337 other := redeem(t, p.credential, capturedLink(t, p.credential))
338 if sessionCookie(other) == nil || other.Header().Get("Location") != "/" {
339 t.Fatal("other browser inherited original handoff")
340 }
341 original := exchangeRequest(p.credential.App, "GET", Origin+"/authorize/resume", "", nil, intent, navigation)
342 if original.Code != 303 || !strings.HasPrefix(original.Header().Get("Location"), "/signin") {
343 t.Fatal("original browser acquired another browser's authentication")
344 }
345 var n int
346 if err := p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&n); err != nil || n != 0 {
347 t.Fatal("other-browser email minted an app session")
348 }
349}
350