oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package consumer
2
3import (
4 "context"
5 "crypto/tls"
6 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "io"
10 "log/slog"
11 "net"
12 "net/http"
13 "net/http/cookiejar"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "github.com/go-chi/chi/v5"
23
24 "amadan.net/rastrillo/rastrillo/assertion"
25 "amadan.net/rastrillo/rastrillo/budget"
26 "amadan.net/rastrillo/rastrillo/crypto"
27 "amadan.net/rastrillo/rastrillo/csrf"
28 "amadan.net/rastrillo/rastrillo/db"
29 "amadan.net/rastrillo/rastrillo/dbtest"
30 "amadan.net/rastrillo/rastrillo/migrate"
31 "amadan.net/rastrillo/rastrillo/sessions"
32
33 "amadan.net/oficina/base/internal/config"
34 "amadan.net/oficina/base/internal/install"
35)
36
37const (
38 issuerOrigin = "https://base.test"
39 appOrigin = "https://acme-scratchpad.test"
40 appID = "scratchpad"
41)
42
43var schema = dbtest.FromSet(migrate.Merge(sessions.Schema, Schema))
44
45func TestMain(m *testing.M) {
46 code := budget.Main(m)
47 schema.Remove()
48 os.Exit(code)
49}
50
51// clock is a settable time shared by the consumer and the session store.
52type clock struct {
53 mu sync.Mutex
54 t time.Time
55}
56
57func (c *clock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
58func (c *clock) Add(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) }
59
60type testApp struct {
61 t *testing.T
62 key *crypto.Keypair
63 kid string
64 clock *clock
65 addr string
66 db *db.DB
67 logs *logBuffer
68}
69
70// logBuffer collects what the consumer logs, so tests can read it and
71// expected warnings do not print.
72type logBuffer struct {
73 mu sync.Mutex
74 b strings.Builder
75}
76
77func (l *logBuffer) Write(p []byte) (int, error) {
78 l.mu.Lock()
79 defer l.mu.Unlock()
80 return l.b.Write(p)
81}
82
83func (l *logBuffer) String() string { l.mu.Lock(); defer l.mu.Unlock(); return l.b.String() }
84
85// newApp serves a consumer over TLS, configured from exactly the variables
86// Base writes at install time, with one guarded page that prints Person.
87func newApp(t *testing.T) *testApp {
88 t.Helper()
89 key, err := crypto.Generate()
90 if err != nil {
91 t.Fatal(err)
92 }
93 vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin)
94 cfg, err := Load(func(k string) string { return vars[k] })
95 if err != nil {
96 t.Fatalf("Load: %v", err)
97 }
98 clk := &clock{t: time.Now()}
99 cfg.now = clk.Now
100 logs := &logBuffer{}
101 cfg.Logger = slog.New(slog.NewTextHandler(logs, nil))
102 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
103 d, err := db.Open(schema.Path(t), logger)
104 if err != nil {
105 t.Fatal(err)
106 }
107 t.Cleanup(func() { d.Close() })
108 sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: appOrigin, SigninPath: StartPath, Logger: logger, Now: clk.Now})
109 if err != nil {
110 t.Fatal(err)
111 }
112 r := chi.NewRouter()
113 r.Use(csrf.Protect(appOrigin, csrf.Exempt(AssertionPath)))
114 Mount(r, d.Writer(), cfg, sess)
115 page := func(w http.ResponseWriter, r *http.Request) {
116 sub, name, base, ok := Person(r)
117 if !ok {
118 http.Error(w, "no person", http.StatusInternalServerError)
119 return
120 }
121 fmt.Fprintf(w, "Signed in as %s, %s (%s)", name, base, sub)
122 }
123 r.With(Require).Get("/", page)
124 r.With(Require).Get("/notes", page)
125 r.With(Require).Post("/", page)
126 srv := httptest.NewTLSServer(r) // 127.0.0.1 only
127 t.Cleanup(srv.Close)
128 kid, _ := install.KeySet(key)
129 return &testApp{t: t, key: key, kid: kid, clock: clk, addr: srv.Listener.Addr().String(), db: d, logs: logs}
130}
131
132type resp struct {
133 Code int
134 Header http.Header
135 Body string
136}
137
138func (r resp) Location() string { return r.Header.Get("Location") }
139
140// cookie returns the Set-Cookie for name, if the response set one.
141func (r resp) cookie(name string) (*http.Cookie, bool) {
142 for _, c := range (&http.Response{Header: r.Header}).Cookies() {
143 if c.Name == name {
144 return c, true
145 }
146 }
147 return nil, false
148}
149
150// browser is one cookie jar talking to the app at appOrigin.
151type browser struct {
152 a *testApp
153 jar *cookiejar.Jar
154 client *http.Client
155}
156
157func (a *testApp) browser() *browser {
158 jar, _ := cookiejar.New(nil)
159 tr := &http.Transport{
160 DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
161 return (&net.Dialer{}).DialContext(ctx, network, a.addr)
162 },
163 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate
164 }
165 a.t.Cleanup(tr.CloseIdleConnections)
166 return &browser{a: a, jar: jar, client: &http.Client{Jar: jar, Transport: tr,
167 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
168}
169
170func (b *browser) do(req *http.Request) resp {
171 b.a.t.Helper()
172 res, err := b.client.Do(req)
173 if err != nil {
174 b.a.t.Fatal(err)
175 }
176 defer res.Body.Close()
177 raw, _ := io.ReadAll(res.Body)
178 return resp{res.StatusCode, res.Header, string(raw)}
179}
180
181func (b *browser) get(path string) resp {
182 b.a.t.Helper()
183 req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil)
184 return b.do(req)
185}
186
187// post sends a form with the given Origin headers (none if empty).
188func (b *browser) post(path string, form url.Values, origins ...string) resp {
189 b.a.t.Helper()
190 req, _ := http.NewRequest(http.MethodPost, appOrigin+path, strings.NewReader(form.Encode()))
191 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
192 for _, o := range origins {
193 req.Header.Add("Origin", o)
194 }
195 return b.do(req)
196}
197
198// postAssertion is Base's handoff form arriving with Base's Origin.
199func (b *browser) postAssertion(token string) resp {
200 b.a.t.Helper()
201 return b.post(AssertionPath, url.Values{"assertion": {token}}, issuerOrigin)
202}
203
204// start begins a sign-in and returns the nonce the browser was sent to Base with.
205func (b *browser) start(returnTo string) string {
206 b.a.t.Helper()
207 r := b.get(StartPath + "?" + url.Values{"return_to": {returnTo}}.Encode())
208 if r.Code != http.StatusSeeOther {
209 b.a.t.Fatalf("start: %d %s", r.Code, r.Body)
210 }
211 u, err := url.Parse(r.Location())
212 if err != nil || u.Scheme+"://"+u.Host != issuerOrigin || u.Path != "/authorize" {
213 b.a.t.Fatalf("start redirected to %q", r.Location())
214 }
215 q := u.Query()
216 if len(q) != 2 || q.Get("consumer") != appID || len(q.Get("nonce")) != 22 {
217 b.a.t.Fatalf("authorize query %q", u.RawQuery)
218 }
219 return q.Get("nonce")
220}
221
222type person struct{ sub, name, email, base string }
223
224var paul = person{"member-paul", "Paul", "paul@acme.test", "Acme Ltd"}
225
226// sign issues an assertion as Base would, at the app's current clock.
227// edit may change the claims before signing.
228func (a *testApp) sign(nonce string, p person, edit func(*assertion.Claims)) string {
229 a.t.Helper()
230 jti, err := assertion.RandomID()
231 if err != nil {
232 a.t.Fatal(err)
233 }
234 ext, _ := json.Marshal(map[string]string{"name": p.name, "email": p.email, "base": p.base})
235 iat := a.clock.Now().Unix()
236 c := assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, Subject: p.sub, KeyID: a.kid,
237 ID: jti, Nonce: nonce, IssuedAt: iat, ExpiresAt: iat + 120, AuthTime: iat, Ext: ext}
238 if edit != nil {
239 edit(&c)
240 }
241 token, err := assertion.Sign(a.key, c)
242 if err != nil {
243 a.t.Fatalf("sign: %v", err)
244 }
245 return token
246}
247
248// signIn runs the whole handoff for p and checks it lands on returnTo.
249func (b *browser) signIn(p person, returnTo string) {
250 b.a.t.Helper()
251 n := b.start(returnTo)
252 if r := b.postAssertion(b.a.sign(n, p, nil)); r.Code != http.StatusSeeOther || r.Location() != FinishPath {
253 b.a.t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body)
254 }
255 if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != returnTo {
256 b.a.t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body)
257 }
258}
259
260// signedOut checks the browser has no session: the guarded page sends it to start.
261func (b *browser) signedOut() {
262 b.a.t.Helper()
263 if r := b.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Location(), StartPath) {
264 b.a.t.Fatalf("want no session, got %d %q %s", r.Code, r.Location(), r.Body)
265 }
266}
267
268func checkCookie(t *testing.T, r resp, name string, maxAge int) {
269 t.Helper()
270 c, ok := r.cookie(name)
271 if !ok {
272 t.Fatalf("no %s cookie set; headers %v", name, r.Header["Set-Cookie"])
273 }
274 if !c.Secure || !c.HttpOnly || c.Path != "/" || c.Domain != "" || c.SameSite != http.SameSiteLaxMode || c.MaxAge != maxAge {
275 t.Errorf("%s cookie: %+v", name, c)
276 }
277}
278
279func TestHandoffSignsIn(t *testing.T) {
280 a := newApp(t)
281 b := a.browser()
282 if r := b.get("/notes?x=1"); r.Code != http.StatusSeeOther || r.Location() != StartPath+"?return_to=%2Fnotes%3Fx%3D1" {
283 t.Fatalf("guarded page: %d %q", r.Code, r.Location())
284 }
285
286 r := b.get(StartPath + "?return_to=%2Fnotes%3Fx%3D1")
287 if r.Code != http.StatusSeeOther {
288 t.Fatalf("start: %d %s", r.Code, r.Body)
289 }
290 checkCookie(t, r, "__Host-base-pending", 600)
291 if got := r.Header.Get("Cache-Control"); got != "no-store" {
292 t.Errorf("start Cache-Control %q", got)
293 }
294 u, _ := url.Parse(r.Location())
295 n := u.Query().Get("nonce")
296 if c, _ := r.cookie("__Host-base-pending"); c != nil && strings.Contains(c.Value, n) {
297 t.Errorf("the pending cookie carries the nonce itself; it must be an independent secret")
298 }
299
300 r = b.postAssertion(a.sign(n, paul, nil))
301 if r.Code != http.StatusSeeOther || r.Location() != FinishPath {
302 t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body)
303 }
304 checkCookie(t, r, "__Host-base-inbox", 120)
305
306 r = b.get(FinishPath)
307 if r.Code != http.StatusSeeOther || r.Location() != "/notes?x=1" {
308 t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body)
309 }
310 checkCookie(t, r, "__Host-rastrillo_session", int((30 * 24 * time.Hour).Seconds()))
311 for _, name := range []string{"__Host-base-pending", "__Host-base-inbox"} {
312 if c, ok := r.cookie(name); !ok || c.MaxAge >= 0 {
313 t.Errorf("finish did not clear %s: %+v", name, c)
314 }
315 }
316
317 if r := b.get("/notes?x=1"); r.Code != 200 || r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
318 t.Fatalf("signed-in page: %d %q", r.Code, r.Body)
319 }
320}
321
322func TestAssertionReplayRefused(t *testing.T) {
323 a := newApp(t)
324 b := a.browser()
325 n := b.start("/")
326 token := a.sign(n, paul, nil)
327 // A second browser holding a copy of the same pending cookie, as a thief
328 // who took both the cookie and the assertion would.
329 thief := a.browser()
330 u, _ := url.Parse(appOrigin)
331 thief.jar.SetCookies(u, b.jar.Cookies(u))
332
333 if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
334 t.Fatalf("first post: %d %s", r.Code, r.Body)
335 }
336 if r := b.get(FinishPath); r.Code != http.StatusSeeOther {
337 t.Fatalf("first finish: %d %s", r.Code, r.Body)
338 }
339
340 r := thief.postAssertion(token)
341 if r.Code == http.StatusSeeOther {
342 t.Fatalf("second post of the same assertion was accepted: %q", r.Location())
343 }
344 if _, ok := r.cookie("__Host-base-inbox"); ok {
345 t.Errorf("a refused assertion set an inbox cookie")
346 }
347 if r := thief.get(FinishPath); r.Code == http.StatusSeeOther {
348 t.Fatalf("finish after replay: %q", r.Location())
349 }
350 thief.signedOut()
351
352 // The same browser posting it again gets nothing either.
353 if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
354 t.Fatalf("same browser replay accepted")
355 }
356}
357
358func TestAssertionReplayRefusedBeforeFinish(t *testing.T) {
359 a := newApp(t)
360 b := a.browser()
361 token := a.sign(b.start("/"), paul, nil)
362 if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
363 t.Fatalf("first post: %d", r.Code)
364 }
365 // Still in the inbox, not yet finished: a second post is refused.
366 if r := a.browser().postAssertion(token); r.Code == http.StatusSeeOther {
367 t.Fatalf("second post while the first waits in the inbox was accepted")
368 }
369}
370
371func TestAssertionExpiredRefused(t *testing.T) {
372 t.Run("posted late", func(t *testing.T) {
373 a := newApp(t)
374 b := a.browser()
375 token := a.sign(b.start("/"), paul, nil)
376 a.clock.Add(121 * time.Second)
377 if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
378 t.Fatalf("expired assertion accepted")
379 }
380 b.get(FinishPath)
381 b.signedOut()
382 })
383 t.Run("finished late", func(t *testing.T) {
384 a := newApp(t)
385 b := a.browser()
386 token := a.sign(b.start("/"), paul, nil)
387 a.clock.Add(60 * time.Second)
388 if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
389 t.Fatalf("post within lifetime: %d %s", r.Code, r.Body)
390 }
391 a.clock.Add(61 * time.Second) // iat + 121
392 if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
393 t.Fatalf("finish after expiry accepted: %q", r.Location())
394 }
395 b.signedOut()
396 })
397 t.Run("pending expired", func(t *testing.T) {
398 a := newApp(t)
399 b := a.browser()
400 n := b.start("/")
401 a.clock.Add(601 * time.Second)
402 if r := b.postAssertion(a.sign(n, paul, nil)); r.Code != http.StatusSeeOther {
403 t.Fatalf("post: %d", r.Code)
404 }
405 if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
406 t.Fatalf("finish after the pending request expired was accepted")
407 }
408 b.signedOut()
409 })
410}
411
412func TestAssertionWrongOriginRefused(t *testing.T) {
413 a := newApp(t)
414 for name, origins := range map[string][]string{
415 "other site": {"https://evil.test"},
416 "suffix": {"https://base.test.evil.test"},
417 "plain http": {"http://base.test"},
418 "trailing slash": {"https://base.test/"},
419 "null": {"null"},
420 "missing": nil,
421 "the app itself": {appOrigin},
422 "two headers": {issuerOrigin, "https://evil.test"},
423 } {
424 t.Run(name, func(t *testing.T) {
425 b := a.browser()
426 token := a.sign(b.start("/"), paul, nil)
427 r := b.post(AssertionPath, url.Values{"assertion": {token}}, origins...)
428 if r.Code != http.StatusForbidden {
429 t.Fatalf("Origin %q: %d %q, want 403", origins, r.Code, r.Location())
430 }
431 if _, ok := r.cookie("__Host-base-inbox"); ok {
432 t.Errorf("refused post set an inbox cookie")
433 }
434 b.get(FinishPath)
435 b.signedOut()
436 })
437 }
438}
439
440func TestAssertionForAnotherAudienceRefused(t *testing.T) {
441 a := newApp(t)
442 for name, edit := range map[string]func(*assertion.Claims){
443 "another app": func(c *assertion.Claims) { c.Audience = "https://acme-welcome.test" },
444 "another issuer": func(c *assertion.Claims) { c.Issuer = "https://other-base.test" },
445 } {
446 t.Run(name, func(t *testing.T) {
447 b := a.browser()
448 if r := b.postAssertion(a.sign(b.start("/"), paul, edit)); r.Code == http.StatusSeeOther {
449 t.Fatalf("assertion accepted")
450 }
451 b.get(FinishPath)
452 b.signedOut()
453 })
454 }
455 t.Run("another key", func(t *testing.T) {
456 b := a.browser()
457 other, _ := crypto.Generate()
458 forged := &testApp{t: t, key: other, kid: a.kid, clock: a.clock}
459 token := forged.sign(b.start("/"), paul, nil)
460 if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
461 t.Fatalf("assertion signed by another key accepted")
462 }
463 })
464}
465
466func TestNonceFromAnotherTabRefused(t *testing.T) {
467 a := newApp(t)
468 b := a.browser()
469 first := b.start("/")
470 second := b.start("/") // a second tab replaces the first's pending request
471 if first == second {
472 t.Fatal("two starts gave one nonce")
473 }
474 if r := b.postAssertion(a.sign(first, paul, nil)); r.Code != http.StatusSeeOther {
475 t.Fatalf("post: %d", r.Code)
476 }
477 if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
478 t.Fatalf("assertion for the replaced request finished: %q", r.Location())
479 }
480 b.signedOut()
481}
482
483func TestLoginCSRFRefused(t *testing.T) {
484 a := newApp(t)
485 mallory := person{"member-mallory", "Mallory", "m@evil.test", "Evil"}
486 // In each scenario the attacker gets a fresh assertion for themselves in
487 // their own browser, and makes the victim's browser deliver it, with and
488 // without a sign-in of the victim's own in flight.
489 for _, pending := range []bool{false, true} {
490 attacker := a.browser()
491 token := a.sign(attacker.start("/"), mallory, nil)
492 victim := a.browser()
493 if pending {
494 victim.start("/")
495 }
496 // Even with Base's Origin (the strongest an attacker could manage),
497 // a valid, unused assertion is accepted into the inbox...
498 if r := victim.postAssertion(token); r.Code != http.StatusSeeOther || r.Location() != FinishPath {
499 t.Fatalf("victim (pending=%v): post %d %q, want 303 to %s", pending, r.Code, r.Location(), FinishPath)
500 }
501 // ...but finishing is refused: it is bound to the attacker's browser.
502 if r := victim.get(FinishPath); r.Code != http.StatusBadRequest {
503 t.Fatalf("victim (pending=%v): finish %d %q, want 400", pending, r.Code, r.Location())
504 }
505 victim.signedOut()
506 }
507}
508
509func TestStartRefusesOffsiteReturn(t *testing.T) {
510 a := newApp(t)
511 for _, to := range []string{
512 "", "//evil.test/", "https://evil.test/", "/\\evil.test", "\\\\evil.test", "/\t/evil.test",
513 "evil.test", "/a\r\nSet-Cookie: x=1", "/a#frag", "/auth/finish", "/auth/start?return_to=/", "/./auth/finish",
514 "/%2e%2e/auth/finish", "javascript:alert(1)",
515 } {
516 b := a.browser()
517 r := b.get(StartPath + "?" + url.Values{"return_to": {to}}.Encode())
518 if r.Code == http.StatusSeeOther {
519 t.Errorf("return_to %q accepted, redirect %q", to, r.Location())
520 }
521 if _, ok := r.cookie("__Host-base-pending"); ok {
522 t.Errorf("return_to %q set a pending cookie", to)
523 }
524 }
525 // Extra or repeated parameters are refused too.
526 for _, q := range []string{"return_to=/&return_to=/x", "return_to=/&nonce=abc"} {
527 if r := a.browser().get(StartPath + "?" + q); r.Code == http.StatusSeeOther {
528 t.Errorf("start?%s accepted", q)
529 }
530 }
531 // No return_to means Home.
532 b := a.browser()
533 r := b.get(StartPath)
534 if r.Code != http.StatusSeeOther {
535 t.Fatalf("bare start: %d", r.Code)
536 }
537}
538
539func TestStartWithoutReturnLandsHome(t *testing.T) {
540 a := newApp(t)
541 b := a.browser()
542 r := b.get(StartPath)
543 u, _ := url.Parse(r.Location())
544 b.postAssertion(a.sign(u.Query().Get("nonce"), paul, nil))
545 if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != "/" {
546 t.Fatalf("finish: %d %q", r.Code, r.Location())
547 }
548}
549
550func TestRequire(t *testing.T) {
551 a := newApp(t)
552 b := a.browser()
553 if r := b.post("/", url.Values{}, appOrigin); r.Code != http.StatusForbidden {
554 t.Errorf("signed-out POST: %d, want 403", r.Code)
555 }
556 b.signIn(paul, "/")
557 if r := b.post("/", url.Values{}, appOrigin); r.Code != 200 {
558 t.Errorf("signed-in POST: %d %s", r.Code, r.Body)
559 }
560}
561
562func TestSecondPersonSeesThemselves(t *testing.T) {
563 a := newApp(t)
564 one, two := a.browser(), a.browser()
565 one.signIn(paul, "/")
566 ana := person{"member-ana", "", "ana@acme.test", "Acme Ltd"}
567 two.signIn(ana, "/")
568 if r := one.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
569 t.Errorf("one: %q", r.Body)
570 }
571 // No name yet: the email stands in.
572 if r := two.get("/"); r.Body != "Signed in as ana@acme.test, Acme Ltd (member-ana)" {
573 t.Errorf("two: %q", r.Body)
574 }
575}
576
577func TestFinishRefusesAnotherSubjectOverALiveSession(t *testing.T) {
578 a := newApp(t)
579 b := a.browser()
580 b.signIn(paul, "/")
581 n := b.start("/")
582 b.postAssertion(a.sign(n, person{"member-ana", "Ana", "ana@acme.test", "Acme Ltd"}, nil))
583 if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
584 t.Fatalf("a live session was swapped for another person")
585 }
586 if r := b.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
587 t.Errorf("after refused swap: %d %q", r.Code, r.Body)
588 }
589}
590
591func TestLoad(t *testing.T) {
592 key, _ := crypto.Generate()
593 good := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin)
594 cfg, err := Load(func(k string) string { return good[k] })
595 if err != nil {
596 t.Fatal(err)
597 }
598 if cfg.Origin != appOrigin || cfg.Issuer != issuerOrigin || cfg.ConsumerID != appID || cfg.Verifier == nil {
599 t.Errorf("cfg: %+v", cfg)
600 }
601 keysJSON := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
602 for name, change := range map[string][2]string{
603 "no origin": {"BASE_APP_ORIGIN", ""},
604 "http origin": {"BASE_APP_ORIGIN", "http://acme-scratchpad.test"},
605 "no issuer": {"BASE_APP_ISSUER", ""},
606 "issuer is origin": {"BASE_APP_ISSUER", appOrigin},
607 "no consumer": {"BASE_APP_CONSUMER_ID", ""},
608 "bad consumer": {"BASE_APP_CONSUMER_ID", "scratch pad"},
609 "no keys": {"BASE_APP_KEYS", ""},
610 "keys not base64": {"BASE_APP_KEYS", "!!"},
611 "keys not JSON": {"BASE_APP_KEYS", keysJSON("nope")},
612 "empty key set": {"BASE_APP_KEYS", keysJSON("{}")},
613 "key not base64": {"BASE_APP_KEYS", keysJSON(`{"abc":"!!"}`)},
614 "key wrong length": {"BASE_APP_KEYS", keysJSON(`{"abc":"AAAA"}`)},
615 "origin with path": {"BASE_APP_ORIGIN", appOrigin + "/x"},
616 "issuer with slash": {"BASE_APP_ISSUER", issuerOrigin + "/"},
617 } {
618 t.Run(name, func(t *testing.T) {
619 _, err := Load(func(k string) string {
620 if k == change[0] {
621 return change[1]
622 }
623 return good[k]
624 })
625 if err == nil {
626 t.Fatalf("Load accepted %s=%q", change[0], change[1])
627 }
628 })
629 }
630}
631
632func TestClockSteppedBackRefused(t *testing.T) {
633 a := newApp(t)
634 b := a.browser()
635 b.start("/")
636 a.clock.Add(-31 * time.Second)
637 if r := b.get(StartPath); r.Code != http.StatusServiceUnavailable {
638 t.Fatalf("start with the clock 31 s behind: %d, want 503", r.Code)
639 }
640 a.clock.Add(2 * time.Second) // within the tolerance again
641 if r := b.get(StartPath); r.Code != http.StatusSeeOther {
642 t.Fatalf("start with the clock 29 s behind: %d", r.Code)
643 }
644}
645
646func TestHandoffRefusesAnotherHost(t *testing.T) {
647 a := newApp(t)
648 b := a.browser()
649 for _, path := range []string{StartPath, FinishPath} {
650 req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil)
651 req.Host = "acme-scratchpad.test.evil.test"
652 if r := b.do(req); r.Code != http.StatusNotFound {
653 t.Errorf("%s on another host: %d, want 404", path, r.Code)
654 }
655 }
656}
657
658func TestConsumerLogsToTheCallersLogger(t *testing.T) {
659 a := newApp(t)
660 b := a.browser()
661 token := a.sign(b.start("/"), paul, nil)
662 b.postAssertion(token)
663 a.browser().postAssertion(token) // a replay, which is logged
664 if got := a.logs.String(); !strings.Contains(got, "consumer: assertion replayed") {
665 t.Fatalf("the replay warning did not reach Config.Logger; it logged:\n%s", got)
666 }
667}
668
669func TestStorageErrorKeepsItsCause(t *testing.T) {
670 a := newApp(t)
671 b := a.browser()
672 a.db.Close()
673 if r := b.get(StartPath); r.Code != http.StatusServiceUnavailable {
674 t.Fatalf("start with the database closed: %d, want 503", r.Code)
675 }
676 got := a.logs.String()
677 for _, want := range []string{"consumer: storage", "begin transaction", "database is closed"} {
678 if !strings.Contains(got, want) {
679 t.Errorf("log lacks %q:\n%s", want, got)
680 }
681 }
682}
683
684// Finding 7 (R30): an app's own sign-out ends its session for good, and
685// then a different person can sign in on that browser.
686func TestSignOutEndsTheAppSession(t *testing.T) {
687 a := newApp(t)
688 b := a.browser()
689 b.signIn(paul, "/")
690 if r := b.post(SignOutPath, url.Values{}, "https://evil.test"); r.Code != http.StatusForbidden {
691 t.Fatalf("cross-origin sign-out: %d, want 403", r.Code)
692 }
693 if r := b.get("/"); r.Code != 200 {
694 t.Fatalf("a refused sign-out signed out: %d", r.Code)
695 }
696 // A copy of the session cookie, as a second tab or a thief would hold.
697 u, _ := url.Parse(appOrigin)
698 stolen := b.client.Jar.Cookies(u)
699 // Same origin: a 303 off this origin would break the form's redirect
700 // chain on the app's CSP form-action 'self'.
701 r := b.post(SignOutPath, url.Values{}, appOrigin)
702 if r.Code != http.StatusSeeOther || r.Location() != SignedOutPath {
703 t.Fatalf("sign-out: %d %q %s", r.Code, r.Location(), r.Body)
704 }
705 page := b.get(SignedOutPath)
706 if page.Code != 200 || page.Header.Get("Cache-Control") != "no-store" {
707 t.Fatalf("signed-out page: %d %q", page.Code, page.Header.Get("Cache-Control"))
708 }
709 for _, want := range []string{`<a class="btn" href="/">Sign in again</a>`, `href="` + issuerOrigin + `/">Back to Home</a>`, `<a class="wordmark" href="` + issuerOrigin + `/">base</a>`} {
710 if !strings.Contains(page.Body, want) {
711 t.Errorf("signed-out page lacks %q:\n%s", want, page.Body)
712 }
713 }
714 b.signedOut()
715 replay := a.browser()
716 replay.client.Jar.SetCookies(u, stolen)
717 replay.signedOut()
718 // Base now vouches for someone else on this browser; they get in as
719 // themselves.
720 ana := person{"member-ana", "Ana", "ana@acme.test", "Acme Ltd"}
721 b.signIn(ana, "/")
722 if r := b.get("/"); r.Body != "Signed in as Ana, Acme Ltd (member-ana)" {
723 t.Errorf("after signing out and in again: %q", r.Body)
724 }
725 if r := b.get(SignOutPath); r.Code != http.StatusMethodNotAllowed {
726 t.Errorf("GET sign-out: %d, want 405", r.Code)
727 }
728}
729