oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package connect
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/base64"
8 "errors"
9 "net/http"
10 "net/http/httptest"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/home/handoff"
17 "amadan.net/rastrillo/rastrillo/assertion"
18 json "github.com/go-json-experiment/json"
19)
20
21// newNativeFixture is a bridge with NativeExchange on, with the team hooks
22// when team is set (h is nil otherwise).
23func newNativeFixture(t *testing.T, team bool) (*bridgeFixture, *homeOnlyHooks) {
24 t.Helper()
25 var h *homeOnlyHooks
26 if team {
27 h = &homeOnlyHooks{}
28 }
29 f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
30 if h != nil {
31 h.install(f, c)
32 }
33 c.MintNativeSession = func(_ context.Context, s Session) (string, error) { return f.sessions.Mint(s) }
34 })
35 if h != nil {
36 f.b.rememberUnknown = func(http.ResponseWriter) { h.remember++ }
37 }
38 return f, h
39}
40
41func newVerifier(t *testing.T) string {
42 t.Helper()
43 raw := make([]byte, 32)
44 if _, err := rand.Read(raw); err != nil {
45 t.Fatal(err)
46 }
47 return base64.RawURLEncoding.EncodeToString(raw)
48}
49
50// nativeAssertion is what Home's assert returns for verifier's challenge.
51func (f *bridgeFixture) nativeAssertion(t *testing.T, subject, verifier string) string {
52 t.Helper()
53 challenge, ok := handoff.NativeChallenge(verifier)
54 if !ok {
55 t.Fatal("verifier")
56 }
57 nonce, _ := handoff.NativeNonce(challenge)
58 return f.signed(t, subject, nonce, bridgeOrigin)
59}
60
61func (f *bridgeFixture) signed(t *testing.T, subject, nonce, audience string) string {
62 t.Helper()
63 now := time.Now().Unix()
64 id, err := assertion.RandomID()
65 if err != nil {
66 t.Fatal(err)
67 }
68 token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: audience, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now - 600})
69 if err != nil {
70 t.Fatal(err)
71 }
72 return token
73}
74
75func nativeRequestFor(t *testing.T, body any) *http.Request {
76 t.Helper()
77 raw, ok := body.(string)
78 if !ok {
79 b, err := json.Marshal(body)
80 if err != nil {
81 t.Fatal(err)
82 }
83 raw = string(b)
84 }
85 r := httptest.NewRequest(http.MethodPost, bridgeOrigin+NativeExchangePath, strings.NewReader(raw))
86 r.Header.Set("Content-Type", "application/json")
87 return r
88}
89
90func (f *bridgeFixture) exchange(t *testing.T, r *http.Request) *httptest.ResponseRecorder {
91 t.Helper()
92 w := httptest.NewRecorder()
93 f.b.NativeExchange(w, r)
94 if len(w.Result().Cookies()) != 0 {
95 t.Fatal("the native exchange set a cookie")
96 }
97 if w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/json" {
98 t.Fatalf("headers %v", w.Header())
99 }
100 return w
101}
102
103func (f *bridgeFixture) post(t *testing.T, subject string, extra map[string]string) *httptest.ResponseRecorder {
104 t.Helper()
105 verifier := newVerifier(t)
106 body := map[string]string{"assertion": f.nativeAssertion(t, subject, verifier), "verifier": verifier}
107 for k, v := range extra {
108 body[k] = v
109 }
110 return f.exchange(t, nativeRequestFor(t, body))
111}
112
113func (f *bridgeFixture) replayRows(t *testing.T) int {
114 t.Helper()
115 var n int
116 if err := f.db.QueryRow("SELECT COUNT(*) FROM oficina_handoff_replay").Scan(&n); err != nil {
117 t.Fatal(err)
118 }
119 return n
120}
121
122func wantState(t *testing.T, w *httptest.ResponseRecorder, code int, state string) {
123 t.Helper()
124 if w.Code != code || w.Body.String() != `{"state":"`+state+`"}` {
125 t.Fatalf("got %d %s, want %d %s", w.Code, w.Body.String(), code, state)
126 }
127}
128
129// signedSession reads the session an ok answer carries.
130func (f *bridgeFixture) signedSession(t *testing.T, w *httptest.ResponseRecorder) (Session, *http.Cookie) {
131 t.Helper()
132 if w.Code != 200 {
133 t.Fatalf("exchange=%d %s", w.Code, w.Body.String())
134 }
135 var out struct {
136 State string `json:"state"`
137 Name string `json:"name"`
138 Value string `json:"value"`
139 Target string `json:"target"`
140 ExpiresAt int64 `json:"expires_at"`
141 }
142 if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.State != "ok" || out.Name != f.b.sessionCookie || out.Value == "" {
143 t.Fatalf("answer %s: %v", w.Body.String(), err)
144 }
145 if d := time.Until(time.Unix(out.ExpiresAt, 0)); d < NativeLifetime-time.Minute || d > NativeLifetime {
146 t.Fatalf("expires_at in %v", d)
147 }
148 cookie := &http.Cookie{Name: out.Name, Value: out.Value}
149 s, ok := f.sessions.From(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}))
150 if !ok {
151 t.Fatal("no session behind the answer")
152 }
153 return s, cookie
154}
155
156func TestNativeExchangeSignsInALinkedPerson(t *testing.T) {
157 f, h := newNativeFixture(t, true)
158 local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
159 f.link(t, local, "pr_linked")
160 // choice is ignored for a subject who already has a person here.
161 w := f.post(t, "pr_linked", map[string]string{"choice": "new"})
162 s, cookie := f.signedSession(t, w)
163 if s.Method != NativeMethod || s.Subject != "pr_linked" || time.Since(s.AuthTime) < 9*time.Minute {
164 t.Fatalf("session %+v", s)
165 }
166 p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}))
167 if err != nil || p.Label != "one@example.com" {
168 t.Fatal(p, err)
169 }
170 if h.admitted != 0 || h.unlinked != 0 || f.replayRows(t) != 2 {
171 t.Fatalf("admitted=%d unlinked=%d replay=%d", h.admitted, h.unlinked, f.replayRows(t))
172 }
173}
174
175func TestNativeExchangeWithoutHooksSignsInLinkedPeople(t *testing.T) {
176 f, _ := newNativeFixture(t, false)
177 local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
178 f.link(t, local, "pr_linked")
179 f.signedSession(t, f.post(t, "pr_linked", nil))
180 wantState(t, f.post(t, "pr_stranger", nil), 403, "unknown")
181}
182
183// A Member with no person here: 409 with no choice, and nothing allocated
184// or burned; choice:"new" allocates once.
185func TestNativeMemberChooses(t *testing.T) {
186 f, h := newNativeFixture(t, true)
187 wantState(t, f.post(t, "pr_member", nil), 409, "choose")
188 if h.count(t) != 0 || h.unlinked != 0 || f.replayRows(t) != 0 {
189 t.Fatalf("409 allocated %d, unlinked %d, replay %d", h.count(t), h.unlinked, f.replayRows(t))
190 }
191 s, _ := f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"}))
192 if s.Method != NativeMethod || h.count(t) != 1 || h.unlinked != 1 || f.replayRows(t) != 1 {
193 t.Fatalf("new: %+v people=%d unlinked=%d", s, h.count(t), h.unlinked)
194 }
195 // Next time the person is found: no choice needed, nothing allocated.
196 f.signedSession(t, f.post(t, "pr_member", nil))
197 if h.count(t) != 1 || h.unlinked != 1 {
198 t.Fatal("allocated again")
199 }
200}
201
202// Non-members, with or without choice, and instances without the hooks all
203// get the same 403: status, body and headers.
204func TestNativeUnknownIsByteIdentical(t *testing.T) {
205 team, h := newNativeFixture(t, true)
206 h.admission = ErrNoPerson
207 plain, _ := newNativeFixture(t, false)
208 answers := []*httptest.ResponseRecorder{
209 team.post(t, "pr_stranger", nil),
210 team.post(t, "pr_other", map[string]string{"choice": "new"}),
211 plain.post(t, "pr_stranger", nil),
212 plain.post(t, "pr_other", map[string]string{"choice": "new"}),
213 }
214 for i, w := range answers {
215 wantState(t, w, 403, "unknown")
216 if shape(w.Header()) != shape(answers[0].Header()) {
217 t.Fatalf("answer %d headers differ:\n%s\n%s", i, shape(w.Header()), shape(answers[0].Header()))
218 }
219 }
220 if h.count(t) != 0 || h.unlinked != 0 || team.replayRows(t) != 0 || plain.replayRows(t) != 0 {
221 t.Fatal("a non-member allocated or burned something")
222 }
223}
224
225func TestNativeRosterUnavailableIs503(t *testing.T) {
226 f, h := newNativeFixture(t, true)
227 h.admission = errors.New("roster unknown")
228 wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), 503, "unavailable")
229 if h.count(t) != 0 || f.replayRows(t) != 0 {
230 t.Fatal("undecided allocated or burned")
231 }
232}
233
234// Unlinked refusing after the roster said Member: re-resolve, then 403 or
235// 503, with no jti kept.
236func TestNativeAllocationRefusedAfterMember(t *testing.T) {
237 for _, c := range []struct {
238 decision error
239 code int
240 state string
241 }{{ErrNoPerson, 403, "unknown"}, {errors.New("disk"), 503, "unavailable"}} {
242 f, h := newNativeFixture(t, true)
243 h.decision = c.decision
244 wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), c.code, c.state)
245 if f.replayRows(t) != 0 || h.unlinked != 1 {
246 t.Fatalf("%v: replay=%d unlinked=%d", c.decision, f.replayRows(t), h.unlinked)
247 }
248 }
249}
250
251// The admission recheck after the reservation: a Home-only person the
252// roster no longer lists gets the unknown answer.
253func TestNativeRechecksAHomeOnlyPersonsStanding(t *testing.T) {
254 f, h := newNativeFixture(t, true)
255 f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"}))
256 h.admission = ErrNoPerson
257 wantState(t, f.post(t, "pr_member", nil), 403, "unknown")
258 h.admission = errors.New("roster unknown")
259 wantState(t, f.post(t, "pr_member", nil), 503, "unavailable")
260}
261
262func TestNativeExchangeRefusesTheWrongAssertion(t *testing.T) {
263 f, _ := newNativeFixture(t, true)
264 local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
265 f.link(t, local, "pr_linked")
266 before := f.replayRows(t)
267 verifier := newVerifier(t)
268 good := f.nativeAssertion(t, "pr_linked", verifier)
269 webNonce, _ := assertion.RandomID()
270 for name, body := range map[string]map[string]string{
271 "another verifier": {"assertion": good, "verifier": newVerifier(t)},
272 "a browser nonce": {"assertion": f.signed(t, "pr_linked", webNonce, bridgeOrigin), "verifier": verifier},
273 "another audience": {"assertion": f.nativeAssertionFor(t, "pr_linked", verifier, "https://red.docs.oficina.works"), "verifier": verifier},
274 "a corrupted token": {"assertion": corrupt(good), "verifier": verifier},
275 "a stranger's token": {"assertion": strings.Repeat("x", 200), "verifier": verifier},
276 } {
277 t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed") })
278 }
279 if f.replayRows(t) != before {
280 t.Fatal("a refused assertion burned a jti")
281 }
282 ok := map[string]string{"assertion": good, "verifier": verifier}
283 f.signedSession(t, f.exchange(t, nativeRequestFor(t, ok)))
284 wantState(t, f.exchange(t, nativeRequestFor(t, ok)), 401, "failed")
285}
286
287// corrupt changes one character inside the token's signature, always to a
288// different one: a middle character carries six full bits, so the decoded
289// signature differs whatever the original was.
290func corrupt(token string) string {
291 i := len(token) - 10
292 c := byte('A')
293 if token[i] == 'A' {
294 c = 'B'
295 }
296 return token[:i] + string(c) + token[i+1:]
297}
298
299func (f *bridgeFixture) nativeAssertionFor(t *testing.T, subject, verifier, audience string) string {
300 t.Helper()
301 challenge, _ := handoff.NativeChallenge(verifier)
302 nonce, _ := handoff.NativeNonce(challenge)
303 return f.signed(t, subject, nonce, audience)
304}
305
306func TestNativeExchangeRefusesBrowsersAndMalformedRequests(t *testing.T) {
307 f, h := newNativeFixture(t, true)
308 verifier := newVerifier(t)
309 token := f.nativeAssertion(t, "pr_member", verifier)
310 good := `{"assertion":"` + token + `","verifier":"` + verifier + `"}`
311 for name, adjust := range map[string]func(*http.Request){
312 "Origin": func(r *http.Request) { r.Header.Set("Origin", bridgeOrigin) },
313 "Sec-Fetch-Site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") },
314 "form": func(r *http.Request) { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") },
315 "text": func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") },
316 "query": func(r *http.Request) { r.URL.RawQuery = "x=1" },
317 } {
318 r := nativeRequestFor(t, good)
319 adjust(r)
320 t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, r), 400, "invalid") })
321 }
322 for name, body := range map[string]string{
323 "unknown field": `{"assertion":"` + token + `","verifier":"` + verifier + `","extra":1}`,
324 "duplicate field": `{"assertion":"` + token + `","assertion":"` + token + `","verifier":"` + verifier + `"}`,
325 "trailing value": good + `{}`,
326 "bad verifier": `{"assertion":"` + token + `","verifier":"short"}`,
327 "bad choice": `{"assertion":"` + token + `","verifier":"` + verifier + `","choice":"old"}`,
328 "foreign target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"//evil.example/"}`,
329 "auth target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"/auth/start"}`,
330 "no assertion": `{"verifier":"` + verifier + `"}`,
331 "huge": `{"assertion":"` + strings.Repeat("a", 13*1024) + `","verifier":"` + verifier + `"}`,
332 } {
333 t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 400, "invalid") })
334 }
335 get := httptest.NewRecorder()
336 f.b.NativeExchange(get, httptest.NewRequest(http.MethodGet, bridgeOrigin+NativeExchangePath, nil))
337 if get.Code != 405 || get.Header().Get("Allow") != "POST" {
338 t.Fatalf("GET=%d", get.Code)
339 }
340 if h.admitted != 0 || f.replayRows(t) != 0 {
341 t.Fatal("a refused request reached the roster or burned a jti")
342 }
343}
344
345func TestNativeExchangeEchoesAValidTarget(t *testing.T) {
346 f, _ := newNativeFixture(t, true)
347 w := f.post(t, "pr_member", map[string]string{"choice": "new", "target": "/d/abc?view=1"})
348 f.signedSession(t, w)
349 if !bytes.Contains(w.Body.Bytes(), []byte(`"target":"/d/abc?view=1"`)) {
350 t.Fatal(w.Body.String())
351 }
352}
353
354func TestNativeExchangeIsOffWithoutAMint(t *testing.T) {
355 f, _ := newHomeOnlyFixture(t)
356 w := httptest.NewRecorder()
357 f.b.NativeExchange(w, nativeRequestFor(t, `{}`))
358 if w.Code != 404 {
359 t.Fatalf("exchange without MintNativeSession=%d", w.Code)
360 }
361}
362
363// A jti burned with no session (the mint failed after the reservation) is
364// not usable again; the client's fresh assertion is.
365func TestNativeBurnedJTIIsRetriedWithAFreshAssertion(t *testing.T) {
366 failing := true
367 h := &homeOnlyHooks{}
368 f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
369 h.install(f, c)
370 c.MintNativeSession = func(_ context.Context, s Session) (string, error) {
371 if failing {
372 return "", errors.New("disk")
373 }
374 return f.sessions.Mint(s)
375 }
376 })
377 verifier := newVerifier(t)
378 body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"}
379 wantState(t, f.exchange(t, nativeRequestFor(t, body)), 503, "unavailable")
380 failing = false
381 wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed")
382 f.signedSession(t, f.post(t, "pr_member", nil))
383 if h.count(t) != 1 {
384 t.Fatal("the retry allocated again")
385 }
386}
387
388// Two exchanges choosing "new" for one subject at once make one person.
389func TestNativeConcurrentChoicesMakeOnePerson(t *testing.T) {
390 f, h := newNativeFixture(t, true)
391 var mu sync.Mutex
392 inner := f.b.mintNative
393 f.b.mintNative = func(ctx context.Context, s Session) (string, error) {
394 mu.Lock()
395 defer mu.Unlock()
396 return inner(ctx, s)
397 }
398 h.db.SetMaxOpenConns(4)
399 codes := make(chan int, 4)
400 var wg sync.WaitGroup
401 for range 4 {
402 verifier := newVerifier(t)
403 body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"}
404 r := nativeRequestFor(t, body)
405 wg.Go(func() {
406 w := httptest.NewRecorder()
407 f.b.NativeExchange(w, r)
408 codes <- w.Code
409 })
410 }
411 wg.Wait()
412 close(codes)
413 for c := range codes {
414 if c != 200 {
415 t.Fatalf("a concurrent choice answered %d", c)
416 }
417 }
418 if h.count(t) != 1 {
419 t.Fatalf("%d people", h.count(t))
420 }
421}
422
423// No hook and no mint is ever called with connect holding the writer. On a
424// single-connection pool (Docs' writer), each hook needs the connection; a
425// transaction held across it would make the hook wait forever. The probe
426// waits a second instead, and a hook that finds the writer held fails the
427// test there and then, before it or anything after it touches the pool.
428// Every hook runs on the test goroutine (the handlers are called directly),
429// so Fatalf is safe here.
430func TestNoHookRunsWithTheWriterHeld(t *testing.T) {
431 var probe func(string) bool
432 h := &homeOnlyHooks{}
433 f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
434 h.install(f, c)
435 f.db.SetMaxOpenConns(1)
436 probe = func(string) bool {
437 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
438 defer cancel()
439 _, err := f.db.ExecContext(ctx, "UPDATE home_link_clock SET high_water = high_water WHERE id = 1")
440 return err != nil
441 }
442 free := func(name string) {
443 if probe(name) {
444 t.Fatalf("called with the writer held: [%s]", name)
445 }
446 }
447 admit, unlinked, homeOnly, mint := c.Admit, c.Unlinked, c.HomeOnly, c.MintHomeSession
448 c.Admit = func(ctx context.Context, i, s string) error { free("Admit"); return admit(ctx, i, s) }
449 c.Unlinked = func(ctx context.Context, i, s string) (Person, error) { free("Unlinked"); return unlinked(ctx, i, s) }
450 c.HomeOnly = func(ctx context.Context, i, s string) (Person, error) { free("HomeOnly"); return homeOnly(ctx, i, s) }
451 c.MintHomeSession = func(w http.ResponseWriter, r *http.Request, s Session) error {
452 free("MintHomeSession")
453 return mint(w, r, s)
454 }
455 c.MintNativeSession = func(_ context.Context, s Session) (string, error) {
456 free("MintNativeSession")
457 return f.sessions.Mint(s)
458 }
459 })
460 // The probe does notice a held writer.
461 tx, err := f.db.Begin()
462 if err != nil {
463 t.Fatal(err)
464 }
465 seen := probe("self-check")
466 tx.Rollback()
467 if !seen {
468 t.Fatal("the probe cannot see a held writer")
469 }
470 // The browser path: finish, the choose page, "I'm new here"; then a
471 // known person's finish (HomeOnly and MintHomeSession in complete).
472 f.signInNew(t, "pr_browser")
473 if w := f.finishAs(t, "pr_browser", nil); w.Code != 303 || w.Header().Get("Location") != "/next" {
474 t.Fatalf("known person's finish=%d %q", w.Code, w.Header().Get("Location"))
475 }
476 // The native path: 409, then choice "new", then a known person.
477 wantState(t, f.post(t, "pr_native", nil), 409, "choose")
478 f.signedSession(t, f.post(t, "pr_native", map[string]string{"choice": "new"}))
479 f.signedSession(t, f.post(t, "pr_native", nil))
480 if h.admitted == 0 || h.unlinked != 2 || h.homeOnly == 0 {
481 t.Fatalf("hooks not exercised: admit=%d unlinked=%d homeOnly=%d", h.admitted, h.unlinked, h.homeOnly)
482 }
483}
484