package consumer
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/go-chi/chi/v5"
"amadan.net/rastrillo/rastrillo/assertion"
"amadan.net/rastrillo/rastrillo/budget"
"amadan.net/rastrillo/rastrillo/crypto"
"amadan.net/rastrillo/rastrillo/csrf"
"amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/dbtest"
"amadan.net/rastrillo/rastrillo/migrate"
"amadan.net/rastrillo/rastrillo/sessions"
"amadan.net/oficina/base/internal/config"
"amadan.net/oficina/base/internal/install"
)
const (
issuerOrigin = "https://base.test"
appOrigin = "https://acme-scratchpad.test"
appID = "scratchpad"
)
var schema = dbtest.FromSet(migrate.Merge(sessions.Schema, Schema))
func TestMain(m *testing.M) {
code := budget.Main(m)
schema.Remove()
os.Exit(code)
}
// clock is a settable time shared by the consumer and the session store.
type clock struct {
mu sync.Mutex
t time.Time
}
func (c *clock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *clock) Add(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) }
type testApp struct {
t *testing.T
key *crypto.Keypair
kid string
clock *clock
addr string
db *db.DB
logs *logBuffer
}
// logBuffer collects what the consumer logs, so tests can read it and
// expected warnings do not print.
type logBuffer struct {
mu sync.Mutex
b strings.Builder
}
func (l *logBuffer) Write(p []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
return l.b.Write(p)
}
func (l *logBuffer) String() string { l.mu.Lock(); defer l.mu.Unlock(); return l.b.String() }
// newApp serves a consumer over TLS, configured from exactly the variables
// Base writes at install time, with one guarded page that prints Person.
func newApp(t *testing.T) *testApp {
t.Helper()
key, err := crypto.Generate()
if err != nil {
t.Fatal(err)
}
vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin)
cfg, err := Load(func(k string) string { return vars[k] })
if err != nil {
t.Fatalf("Load: %v", err)
}
clk := &clock{t: time.Now()}
cfg.now = clk.Now
logs := &logBuffer{}
cfg.Logger = slog.New(slog.NewTextHandler(logs, nil))
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(schema.Path(t), logger)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: appOrigin, SigninPath: StartPath, Logger: logger, Now: clk.Now})
if err != nil {
t.Fatal(err)
}
r := chi.NewRouter()
r.Use(csrf.Protect(appOrigin, csrf.Exempt(AssertionPath)))
Mount(r, d.Writer(), cfg, sess)
page := func(w http.ResponseWriter, r *http.Request) {
sub, name, base, ok := Person(r)
if !ok {
http.Error(w, "no person", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Signed in as %s, %s (%s)", name, base, sub)
}
r.With(Require).Get("/", page)
r.With(Require).Get("/notes", page)
r.With(Require).Post("/", page)
srv := httptest.NewTLSServer(r) // 127.0.0.1 only
t.Cleanup(srv.Close)
kid, _ := install.KeySet(key)
return &testApp{t: t, key: key, kid: kid, clock: clk, addr: srv.Listener.Addr().String(), db: d, logs: logs}
}
type resp struct {
Code int
Header http.Header
Body string
}
func (r resp) Location() string { return r.Header.Get("Location") }
// cookie returns the Set-Cookie for name, if the response set one.
func (r resp) cookie(name string) (*http.Cookie, bool) {
for _, c := range (&http.Response{Header: r.Header}).Cookies() {
if c.Name == name {
return c, true
}
}
return nil, false
}
// browser is one cookie jar talking to the app at appOrigin.
type browser struct {
a *testApp
jar *cookiejar.Jar
client *http.Client
}
func (a *testApp) browser() *browser {
jar, _ := cookiejar.New(nil)
tr := &http.Transport{
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, a.addr)
},
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate
}
a.t.Cleanup(tr.CloseIdleConnections)
return &browser{a: a, jar: jar, client: &http.Client{Jar: jar, Transport: tr,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
}
func (b *browser) do(req *http.Request) resp {
b.a.t.Helper()
res, err := b.client.Do(req)
if err != nil {
b.a.t.Fatal(err)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
return resp{res.StatusCode, res.Header, string(raw)}
}
func (b *browser) get(path string) resp {
b.a.t.Helper()
req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil)
return b.do(req)
}
// post sends a form with the given Origin headers (none if empty).
func (b *browser) post(path string, form url.Values, origins ...string) resp {
b.a.t.Helper()
req, _ := http.NewRequest(http.MethodPost, appOrigin+path, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, o := range origins {
req.Header.Add("Origin", o)
}
return b.do(req)
}
// postAssertion is Base's handoff form arriving with Base's Origin.
func (b *browser) postAssertion(token string) resp {
b.a.t.Helper()
return b.post(AssertionPath, url.Values{"assertion": {token}}, issuerOrigin)
}
// start begins a sign-in and returns the nonce the browser was sent to Base with.
func (b *browser) start(returnTo string) string {
b.a.t.Helper()
r := b.get(StartPath + "?" + url.Values{"return_to": {returnTo}}.Encode())
if r.Code != http.StatusSeeOther {
b.a.t.Fatalf("start: %d %s", r.Code, r.Body)
}
u, err := url.Parse(r.Location())
if err != nil || u.Scheme+"://"+u.Host != issuerOrigin || u.Path != "/authorize" {
b.a.t.Fatalf("start redirected to %q", r.Location())
}
q := u.Query()
if len(q) != 2 || q.Get("consumer") != appID || len(q.Get("nonce")) != 22 {
b.a.t.Fatalf("authorize query %q", u.RawQuery)
}
return q.Get("nonce")
}
type person struct{ sub, name, email, base string }
var paul = person{"member-paul", "Paul", "paul@acme.test", "Acme Ltd"}
// sign issues an assertion as Base would, at the app's current clock.
// edit may change the claims before signing.
func (a *testApp) sign(nonce string, p person, edit func(*assertion.Claims)) string {
a.t.Helper()
jti, err := assertion.RandomID()
if err != nil {
a.t.Fatal(err)
}
ext, _ := json.Marshal(map[string]string{"name": p.name, "email": p.email, "base": p.base})
iat := a.clock.Now().Unix()
c := assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, Subject: p.sub, KeyID: a.kid,
ID: jti, Nonce: nonce, IssuedAt: iat, ExpiresAt: iat + 120, AuthTime: iat, Ext: ext}
if edit != nil {
edit(&c)
}
token, err := assertion.Sign(a.key, c)
if err != nil {
a.t.Fatalf("sign: %v", err)
}
return token
}
// signIn runs the whole handoff for p and checks it lands on returnTo.
func (b *browser) signIn(p person, returnTo string) {
b.a.t.Helper()
n := b.start(returnTo)
if r := b.postAssertion(b.a.sign(n, p, nil)); r.Code != http.StatusSeeOther || r.Location() != FinishPath {
b.a.t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body)
}
if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != returnTo {
b.a.t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body)
}
}
// signedOut checks the browser has no session: the guarded page sends it to start.
func (b *browser) signedOut() {
b.a.t.Helper()
if r := b.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Location(), StartPath) {
b.a.t.Fatalf("want no session, got %d %q %s", r.Code, r.Location(), r.Body)
}
}
func checkCookie(t *testing.T, r resp, name string, maxAge int) {
t.Helper()
c, ok := r.cookie(name)
if !ok {
t.Fatalf("no %s cookie set; headers %v", name, r.Header["Set-Cookie"])
}
if !c.Secure || !c.HttpOnly || c.Path != "/" || c.Domain != "" || c.SameSite != http.SameSiteLaxMode || c.MaxAge != maxAge {
t.Errorf("%s cookie: %+v", name, c)
}
}
func TestHandoffSignsIn(t *testing.T) {
a := newApp(t)
b := a.browser()
if r := b.get("/notes?x=1"); r.Code != http.StatusSeeOther || r.Location() != StartPath+"?return_to=%2Fnotes%3Fx%3D1" {
t.Fatalf("guarded page: %d %q", r.Code, r.Location())
}
r := b.get(StartPath + "?return_to=%2Fnotes%3Fx%3D1")
if r.Code != http.StatusSeeOther {
t.Fatalf("start: %d %s", r.Code, r.Body)
}
checkCookie(t, r, "__Host-base-pending", 600)
if got := r.Header.Get("Cache-Control"); got != "no-store" {
t.Errorf("start Cache-Control %q", got)
}
u, _ := url.Parse(r.Location())
n := u.Query().Get("nonce")
if c, _ := r.cookie("__Host-base-pending"); c != nil && strings.Contains(c.Value, n) {
t.Errorf("the pending cookie carries the nonce itself; it must be an independent secret")
}
r = b.postAssertion(a.sign(n, paul, nil))
if r.Code != http.StatusSeeOther || r.Location() != FinishPath {
t.Fatalf("assertion: %d %q %s", r.Code, r.Location(), r.Body)
}
checkCookie(t, r, "__Host-base-inbox", 120)
r = b.get(FinishPath)
if r.Code != http.StatusSeeOther || r.Location() != "/notes?x=1" {
t.Fatalf("finish: %d %q %s", r.Code, r.Location(), r.Body)
}
checkCookie(t, r, "__Host-rastrillo_session", int((30 * 24 * time.Hour).Seconds()))
for _, name := range []string{"__Host-base-pending", "__Host-base-inbox"} {
if c, ok := r.cookie(name); !ok || c.MaxAge >= 0 {
t.Errorf("finish did not clear %s: %+v", name, c)
}
}
if r := b.get("/notes?x=1"); r.Code != 200 || r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
t.Fatalf("signed-in page: %d %q", r.Code, r.Body)
}
}
func TestAssertionReplayRefused(t *testing.T) {
a := newApp(t)
b := a.browser()
n := b.start("/")
token := a.sign(n, paul, nil)
// A second browser holding a copy of the same pending cookie, as a thief
// who took both the cookie and the assertion would.
thief := a.browser()
u, _ := url.Parse(appOrigin)
thief.jar.SetCookies(u, b.jar.Cookies(u))
if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
t.Fatalf("first post: %d %s", r.Code, r.Body)
}
if r := b.get(FinishPath); r.Code != http.StatusSeeOther {
t.Fatalf("first finish: %d %s", r.Code, r.Body)
}
r := thief.postAssertion(token)
if r.Code == http.StatusSeeOther {
t.Fatalf("second post of the same assertion was accepted: %q", r.Location())
}
if _, ok := r.cookie("__Host-base-inbox"); ok {
t.Errorf("a refused assertion set an inbox cookie")
}
if r := thief.get(FinishPath); r.Code == http.StatusSeeOther {
t.Fatalf("finish after replay: %q", r.Location())
}
thief.signedOut()
// The same browser posting it again gets nothing either.
if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
t.Fatalf("same browser replay accepted")
}
}
func TestAssertionReplayRefusedBeforeFinish(t *testing.T) {
a := newApp(t)
b := a.browser()
token := a.sign(b.start("/"), paul, nil)
if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
t.Fatalf("first post: %d", r.Code)
}
// Still in the inbox, not yet finished: a second post is refused.
if r := a.browser().postAssertion(token); r.Code == http.StatusSeeOther {
t.Fatalf("second post while the first waits in the inbox was accepted")
}
}
func TestAssertionExpiredRefused(t *testing.T) {
t.Run("posted late", func(t *testing.T) {
a := newApp(t)
b := a.browser()
token := a.sign(b.start("/"), paul, nil)
a.clock.Add(121 * time.Second)
if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
t.Fatalf("expired assertion accepted")
}
b.get(FinishPath)
b.signedOut()
})
t.Run("finished late", func(t *testing.T) {
a := newApp(t)
b := a.browser()
token := a.sign(b.start("/"), paul, nil)
a.clock.Add(60 * time.Second)
if r := b.postAssertion(token); r.Code != http.StatusSeeOther {
t.Fatalf("post within lifetime: %d %s", r.Code, r.Body)
}
a.clock.Add(61 * time.Second) // iat + 121
if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
t.Fatalf("finish after expiry accepted: %q", r.Location())
}
b.signedOut()
})
t.Run("pending expired", func(t *testing.T) {
a := newApp(t)
b := a.browser()
n := b.start("/")
a.clock.Add(601 * time.Second)
if r := b.postAssertion(a.sign(n, paul, nil)); r.Code != http.StatusSeeOther {
t.Fatalf("post: %d", r.Code)
}
if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
t.Fatalf("finish after the pending request expired was accepted")
}
b.signedOut()
})
}
func TestAssertionWrongOriginRefused(t *testing.T) {
a := newApp(t)
for name, origins := range map[string][]string{
"other site": {"https://evil.test"},
"suffix": {"https://base.test.evil.test"},
"plain http": {"http://base.test"},
"trailing slash": {"https://base.test/"},
"null": {"null"},
"missing": nil,
"the app itself": {appOrigin},
"two headers": {issuerOrigin, "https://evil.test"},
} {
t.Run(name, func(t *testing.T) {
b := a.browser()
token := a.sign(b.start("/"), paul, nil)
r := b.post(AssertionPath, url.Values{"assertion": {token}}, origins...)
if r.Code != http.StatusForbidden {
t.Fatalf("Origin %q: %d %q, want 403", origins, r.Code, r.Location())
}
if _, ok := r.cookie("__Host-base-inbox"); ok {
t.Errorf("refused post set an inbox cookie")
}
b.get(FinishPath)
b.signedOut()
})
}
}
func TestAssertionForAnotherAudienceRefused(t *testing.T) {
a := newApp(t)
for name, edit := range map[string]func(*assertion.Claims){
"another app": func(c *assertion.Claims) { c.Audience = "https://acme-welcome.test" },
"another issuer": func(c *assertion.Claims) { c.Issuer = "https://other-base.test" },
} {
t.Run(name, func(t *testing.T) {
b := a.browser()
if r := b.postAssertion(a.sign(b.start("/"), paul, edit)); r.Code == http.StatusSeeOther {
t.Fatalf("assertion accepted")
}
b.get(FinishPath)
b.signedOut()
})
}
t.Run("another key", func(t *testing.T) {
b := a.browser()
other, _ := crypto.Generate()
forged := &testApp{t: t, key: other, kid: a.kid, clock: a.clock}
token := forged.sign(b.start("/"), paul, nil)
if r := b.postAssertion(token); r.Code == http.StatusSeeOther {
t.Fatalf("assertion signed by another key accepted")
}
})
}
func TestNonceFromAnotherTabRefused(t *testing.T) {
a := newApp(t)
b := a.browser()
first := b.start("/")
second := b.start("/") // a second tab replaces the first's pending request
if first == second {
t.Fatal("two starts gave one nonce")
}
if r := b.postAssertion(a.sign(first, paul, nil)); r.Code != http.StatusSeeOther {
t.Fatalf("post: %d", r.Code)
}
if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
t.Fatalf("assertion for the replaced request finished: %q", r.Location())
}
b.signedOut()
}
func TestLoginCSRFRefused(t *testing.T) {
a := newApp(t)
mallory := person{"member-mallory", "Mallory", "m@evil.test", "Evil"}
// In each scenario the attacker gets a fresh assertion for themselves in
// their own browser, and makes the victim's browser deliver it, with and
// without a sign-in of the victim's own in flight.
for _, pending := range []bool{false, true} {
attacker := a.browser()
token := a.sign(attacker.start("/"), mallory, nil)
victim := a.browser()
if pending {
victim.start("/")
}
// Even with Base's Origin (the strongest an attacker could manage),
// a valid, unused assertion is accepted into the inbox...
if r := victim.postAssertion(token); r.Code != http.StatusSeeOther || r.Location() != FinishPath {
t.Fatalf("victim (pending=%v): post %d %q, want 303 to %s", pending, r.Code, r.Location(), FinishPath)
}
// ...but finishing is refused: it is bound to the attacker's browser.
if r := victim.get(FinishPath); r.Code != http.StatusBadRequest {
t.Fatalf("victim (pending=%v): finish %d %q, want 400", pending, r.Code, r.Location())
}
victim.signedOut()
}
}
func TestStartRefusesOffsiteReturn(t *testing.T) {
a := newApp(t)
for _, to := range []string{
"", "//evil.test/", "https://evil.test/", "/\\evil.test", "\\\\evil.test", "/\t/evil.test",
"evil.test", "/a\r\nSet-Cookie: x=1", "/a#frag", "/auth/finish", "/auth/start?return_to=/", "/./auth/finish",
"/%2e%2e/auth/finish", "javascript:alert(1)",
} {
b := a.browser()
r := b.get(StartPath + "?" + url.Values{"return_to": {to}}.Encode())
if r.Code == http.StatusSeeOther {
t.Errorf("return_to %q accepted, redirect %q", to, r.Location())
}
if _, ok := r.cookie("__Host-base-pending"); ok {
t.Errorf("return_to %q set a pending cookie", to)
}
}
// Extra or repeated parameters are refused too.
for _, q := range []string{"return_to=/&return_to=/x", "return_to=/&nonce=abc"} {
if r := a.browser().get(StartPath + "?" + q); r.Code == http.StatusSeeOther {
t.Errorf("start?%s accepted", q)
}
}
// No return_to means Home.
b := a.browser()
r := b.get(StartPath)
if r.Code != http.StatusSeeOther {
t.Fatalf("bare start: %d", r.Code)
}
}
func TestStartWithoutReturnLandsHome(t *testing.T) {
a := newApp(t)
b := a.browser()
r := b.get(StartPath)
u, _ := url.Parse(r.Location())
b.postAssertion(a.sign(u.Query().Get("nonce"), paul, nil))
if r := b.get(FinishPath); r.Code != http.StatusSeeOther || r.Location() != "/" {
t.Fatalf("finish: %d %q", r.Code, r.Location())
}
}
func TestRequire(t *testing.T) {
a := newApp(t)
b := a.browser()
if r := b.post("/", url.Values{}, appOrigin); r.Code != http.StatusForbidden {
t.Errorf("signed-out POST: %d, want 403", r.Code)
}
b.signIn(paul, "/")
if r := b.post("/", url.Values{}, appOrigin); r.Code != 200 {
t.Errorf("signed-in POST: %d %s", r.Code, r.Body)
}
}
func TestSecondPersonSeesThemselves(t *testing.T) {
a := newApp(t)
one, two := a.browser(), a.browser()
one.signIn(paul, "/")
ana := person{"member-ana", "", "ana@acme.test", "Acme Ltd"}
two.signIn(ana, "/")
if r := one.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
t.Errorf("one: %q", r.Body)
}
// No name yet: the email stands in.
if r := two.get("/"); r.Body != "Signed in as ana@acme.test, Acme Ltd (member-ana)" {
t.Errorf("two: %q", r.Body)
}
}
func TestFinishRefusesAnotherSubjectOverALiveSession(t *testing.T) {
a := newApp(t)
b := a.browser()
b.signIn(paul, "/")
n := b.start("/")
b.postAssertion(a.sign(n, person{"member-ana", "Ana", "ana@acme.test", "Acme Ltd"}, nil))
if r := b.get(FinishPath); r.Code == http.StatusSeeOther {
t.Fatalf("a live session was swapped for another person")
}
if r := b.get("/"); r.Body != "Signed in as Paul, Acme Ltd (member-paul)" {
t.Errorf("after refused swap: %d %q", r.Code, r.Body)
}
}
func TestLoad(t *testing.T) {
key, _ := crypto.Generate()
good := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, appID, appOrigin)
cfg, err := Load(func(k string) string { return good[k] })
if err != nil {
t.Fatal(err)
}
if cfg.Origin != appOrigin || cfg.Issuer != issuerOrigin || cfg.ConsumerID != appID || cfg.Verifier == nil {
t.Errorf("cfg: %+v", cfg)
}
keysJSON := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
for name, change := range map[string][2]string{
"no origin": {"BASE_APP_ORIGIN", ""},
"http origin": {"BASE_APP_ORIGIN", "http://acme-scratchpad.test"},
"no issuer": {"BASE_APP_ISSUER", ""},
"issuer is origin": {"BASE_APP_ISSUER", appOrigin},
"no consumer": {"BASE_APP_CONSUMER_ID", ""},
"bad consumer": {"BASE_APP_CONSUMER_ID", "scratch pad"},
"no keys": {"BASE_APP_KEYS", ""},
"keys not base64": {"BASE_APP_KEYS", "!!"},
"keys not JSON": {"BASE_APP_KEYS", keysJSON("nope")},
"empty key set": {"BASE_APP_KEYS", keysJSON("{}")},
"key not base64": {"BASE_APP_KEYS", keysJSON(`{"abc":"!!"}`)},
"key wrong length": {"BASE_APP_KEYS", keysJSON(`{"abc":"AAAA"}`)},
"origin with path": {"BASE_APP_ORIGIN", appOrigin + "/x"},
"issuer with slash": {"BASE_APP_ISSUER", issuerOrigin + "/"},
} {
t.Run(name, func(t *testing.T) {
_, err := Load(func(k string) string {
if k == change[0] {
return change[1]
}
return good[k]
})
if err == nil {
t.Fatalf("Load accepted %s=%q", change[0], change[1])
}
})
}
}
func TestClockSteppedBackRefused(t *testing.T) {
a := newApp(t)
b := a.browser()
b.start("/")
a.clock.Add(-31 * time.Second)
if r := b.get(StartPath); r.Code != http.StatusServiceUnavailable {
t.Fatalf("start with the clock 31 s behind: %d, want 503", r.Code)
}
a.clock.Add(2 * time.Second) // within the tolerance again
if r := b.get(StartPath); r.Code != http.StatusSeeOther {
t.Fatalf("start with the clock 29 s behind: %d", r.Code)
}
}
func TestHandoffRefusesAnotherHost(t *testing.T) {
a := newApp(t)
b := a.browser()
for _, path := range []string{StartPath, FinishPath} {
req, _ := http.NewRequest(http.MethodGet, appOrigin+path, nil)
req.Host = "acme-scratchpad.test.evil.test"
if r := b.do(req); r.Code != http.StatusNotFound {
t.Errorf("%s on another host: %d, want 404", path, r.Code)
}
}
}
func TestConsumerLogsToTheCallersLogger(t *testing.T) {
a := newApp(t)
b := a.browser()
token := a.sign(b.start("/"), paul, nil)
b.postAssertion(token)
a.browser().postAssertion(token) // a replay, which is logged
if got := a.logs.String(); !strings.Contains(got, "consumer: assertion replayed") {
t.Fatalf("the replay warning did not reach Config.Logger; it logged:\n%s", got)
}
}
func TestStorageErrorKeepsItsCause(t *testing.T) {
a := newApp(t)
b := a.browser()
a.db.Close()
if r := b.get(StartPath); r.Code != http.StatusServiceUnavailable {
t.Fatalf("start with the database closed: %d, want 503", r.Code)
}
got := a.logs.String()
for _, want := range []string{"consumer: storage", "begin transaction", "database is closed"} {
if !strings.Contains(got, want) {
t.Errorf("log lacks %q:\n%s", want, got)
}
}
}
// Finding 7 (R30): an app's own sign-out ends its session for good, and
// then a different person can sign in on that browser.
func TestSignOutEndsTheAppSession(t *testing.T) {
a := newApp(t)
b := a.browser()
b.signIn(paul, "/")
if r := b.post(SignOutPath, url.Values{}, "https://evil.test"); r.Code != http.StatusForbidden {
t.Fatalf("cross-origin sign-out: %d, want 403", r.Code)
}
if r := b.get("/"); r.Code != 200 {
t.Fatalf("a refused sign-out signed out: %d", r.Code)
}
// A copy of the session cookie, as a second tab or a thief would hold.
u, _ := url.Parse(appOrigin)
stolen := b.client.Jar.Cookies(u)
// Same origin: a 303 off this origin would break the form's redirect
// chain on the app's CSP form-action 'self'.
r := b.post(SignOutPath, url.Values{}, appOrigin)
if r.Code != http.StatusSeeOther || r.Location() != SignedOutPath {
t.Fatalf("sign-out: %d %q %s", r.Code, r.Location(), r.Body)
}
page := b.get(SignedOutPath)
if page.Code != 200 || page.Header.Get("Cache-Control") != "no-store" {
t.Fatalf("signed-out page: %d %q", page.Code, page.Header.Get("Cache-Control"))
}
for _, want := range []string{`Sign in again`, `href="` + issuerOrigin + `/">Back to Home`, `base`} {
if !strings.Contains(page.Body, want) {
t.Errorf("signed-out page lacks %q:\n%s", want, page.Body)
}
}
b.signedOut()
replay := a.browser()
replay.client.Jar.SetCookies(u, stolen)
replay.signedOut()
// Base now vouches for someone else on this browser; they get in as
// themselves.
ana := person{"member-ana", "Ana", "ana@acme.test", "Acme Ltd"}
b.signIn(ana, "/")
if r := b.get("/"); r.Body != "Signed in as Ana, Acme Ltd (member-ana)" {
t.Errorf("after signing out and in again: %q", r.Body)
}
if r := b.get(SignOutPath); r.Code != http.StatusMethodNotAllowed {
t.Errorf("GET sign-out: %d, want 405", r.Code)
}
}