oficina / fichas Public

Smart door: Fable's three findings (fichas #9)

1. keepableReturn judges the path as a browser resolves it: backslashes
   are slashes and dot segments go (path.Clean), so /./signed-out,
   /x/../signed-out, %2e forms and dot-segment forms of /signin and
   /auth/* are refused. A refused value is refused whole, never rewritten.
   TestKeepableReturn gains the cases.
2. The landing checks the kept page too (landingReturn, on /auth/verify
   and /auth/callback): the request's own return_to is never read, and
   the kept cookie only when there is exactly one and it passes
   keepableReturn; otherwise it is cleared and the landing is "/". Tests
   for tampered cookies, duplicates, posted return_to (single, duplicate,
   over a cookie); the cookie's lifetime is pinned to the link's, since
   rastrillo's cookie carries no issue time to expire on. The comment
   block says what each end does and what it does not.
3. Keymail continuation coverage, end to end: a Keymail owner through
   Begin to /signin?continue=<id> and the Continue step on the one-way
   door (the override), under the served CSP, with a loopback resolver
   and transport standing in for DNS and the Keymail server. Plus: a
   continuation id without its cookie, another id, or a URL links
   nowhere; a non-Keymail address passes through to Sent with a link.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 97071b6e78511485e2f3c99d7610de7c30df234c parent 3c47583
5 files changed, +414 −35
  • internal/fichas/app.go +5 −3
  • internal/fichas/signin.go +65 −13
  • internal/fichas/signin_door_test.go +37 −19
  • internal/fichastest/signin_door_keymail_test.go +233 −0
  • internal/fichastest/signin_door_return_test.go +74 −0

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/fichastest/
=== fmt ===
=== test ===
go test ./...
?   	amadan.net/oficina/fichas/cmd/fichas	[no test files]
ok  	amadan.net/oficina/fichas/internal/fichas	2.344s
?   	amadan.net/oficina/fichas/internal/fichas/icons	[no test files]
ok  	amadan.net/oficina/fichas/internal/fichas/locale	0.009s
ok  	amadan.net/oficina/fichas/internal/fichas/seal	(cached)
ok  	amadan.net/oficina/fichas/internal/fichastest	2.621s
?   	amadan.net/oficina/fichas/scripts/mockups	[no test files]
?   	amadan.net/oficina/fichas/scripts/preview	[no test files]
?   	amadan.net/oficina/fichas/scripts/writeestilo	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/internal/fichas/app.go b/internal/fichas/app.go
index ffa2f5c..83a5d18 100644
--- a/internal/fichas/app.go
+++ b/internal/fichas/app.go
@@ -93,10 +93,12 @@ func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error
// which with the screen on keeps a Keymail continuation on the door
// (?continue=) so form-action 'self' stays strict.
r.Post(beginPath, a.beginReturn(a.beginGuard(a.authBegin)))
- r.Get("/auth/callback", a.authCallback)
+ // The two landings: the kept page is checked again here
+ // (landingReturn), as at Begin.
+ r.Get("/auth/callback", a.landingReturn(a.authCallback))
// The emailed link: GET draws the confirm door, POST spends the token.
- r.Get("/auth/verify", a.authVerify)
- r.Post("/auth/verify", a.authVerify)
+ r.Get("/auth/verify", a.landingReturn(a.authVerify))
+ r.Post("/auth/verify", a.landingReturn(a.authVerify))
// "Use a different email", and "Forget me on this device".
r.Post(signinForgetPath, a.forget)
r.Post("/signout", a.signout)
diff --git a/internal/fichas/signin.go b/internal/fichas/signin.go
index 0802638..316b37f 100644
--- a/internal/fichas/signin.go
+++ b/internal/fichas/signin.go
@@ -23,6 +23,7 @@ import (
"html"
"net/http"
"net/url"
+ "path"
"strings"
"amadan.net/oficina/estilo.git/chrome"
@@ -264,21 +265,30 @@ func (rw *rewriteLocation) Write(b []byte) (int, error) { return rw.ResponseWrit
// The return memory (shared-chrome spec §9.4) is rastrillo's own: a
// signed-out page request goes to /signin?return_to=<the page>, the door
// posts it to Begin, and Begin keeps it in a host-only cookie across the
-// mail or Keymail round trip. Its protections, which Docs', Sheets',
-// Slides', Calendar's, Calls' and Memoria's reviews asked of each app's
-// own, are rastrillo's here, and Fichas adds the rest:
+// mail or Keymail round trip, which the landing reads back. Fichas adds
+// a check at each end, so what Begin keeps and what a landing reads pass
+// the same test (keepableReturn), and rastrillo supplies the rest:
//
-// - a post without return_to forgets the kept page (rastrillo's
-// keepReturnTo, AnswerAsSent included, so owner and stranger alike);
-// - every landing that mints a session spends it, admitted or not
-// (rastrillo's admit: the emailed link's POST and the Keymail
-// callback, the only two ways Fichas mints a session);
+// - at Begin (beginReturn): a body that does not parse, or a page that
+// is no page to come back to (/signed-out, the door, auth's own
+// routes, dot segments included), keeps nothing, and a post without
+// return_to forgets the kept page (rastrillo's keepReturnTo,
+// AnswerAsSent included, so owner and stranger alike);
+// - at the landing (landingReturn, on /auth/verify and /auth/callback,
+// the only two ways Fichas mints a session): the request's own
+// return_to is never read, and the kept page is read only when there
+// is exactly one cookie and it passes keepableReturn; otherwise it is
+// cleared and the landing is "/";
+// - every landing spends it, admitted or not (rastrillo's admit);
// - Sign out clears it (rastrillo's Signout), and so does Forget
// (forget, above);
-// - a body that does not parse, or a page that is no page to come back
-// to (/signed-out, the door, auth's own routes), keeps nothing
-// (beginReturn);
// - there is no /signin/local to overwrite it.
+//
+// What this does not do: tell an expired cookie from a live one.
+// rastrillo's cookie is the bare path with no issue time, so its
+// lifetime is the browser's Max-Age, which Begin sets to the emailed
+// link's own (15 minutes); a cookie a browser sends past it is one
+// somebody wrote by hand, and still passes keepableReturn or not.
// beginReturn is POST /auth/begin, outermost: Begin keeps no page it
// should not. A body that fails to parse keeps none at all: Go leaves
@@ -305,6 +315,12 @@ func (a *app) beginReturn(next http.HandlerFunc) http.HandlerFunc {
// sign-in may land on: a same-origin path, and not the signed-out page
// ("You’re signed out" straight after signing in), the door, or auth's
// own routes, with or without a query.
+//
+// The path is judged as a browser would resolve it: backslashes are
+// slashes and dot segments are removed (path.Clean), so /./signed-out,
+// /x/../signed-out and /x\..\signin are refused like the pages they
+// name (Fable on fichas #9). A refused value is refused whole, never
+// rewritten to its cleaned form.
func keepableReturn(to string) bool {
if to == "" || !strings.HasPrefix(to, "/") || strings.HasPrefix(to, "//") || strings.HasPrefix(to, "/\\") {
return false
@@ -313,8 +329,44 @@ func keepableReturn(to string) bool {
if err != nil || u.Scheme != "" || u.Host != "" {
return false
}
- p := u.Path
- return p != signedOutPath && p != signinPath && !strings.HasPrefix(p, signinPath+"/") && !strings.HasPrefix(p, "/auth/")
+ p := path.Clean(strings.ReplaceAll(u.Path, "\\", "/"))
+ return p != signedOutPath && p != signinPath && !strings.HasPrefix(p, signinPath+"/") &&
+ p != "/auth" && !strings.HasPrefix(p, "/auth/")
+}
+
+// landingReturn wraps a landing that may mint a session (/auth/verify,
+// /auth/callback): rastrillo's admit lands on the request's own
+// return_to, else the kept one. The request's own is never Fichas' page
+// to land on: no door posts one there, so it comes off the form and the
+// query, duplicates and all. The kept one is read only when the browser
+// sends exactly one cookie and its page passes keepableReturn; any other
+// is cleared on this response and hidden from admit, so the landing is
+// "/". A cookie is a request header like any other.
+func (a *app) landingReturn(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ if r.PostForm != nil {
+ r.PostForm.Del("return_to")
+ }
+ if r.Form != nil {
+ r.Form.Del("return_to")
+ }
+ name := a.returnCookieName()
+ var kept []string
+ for _, c := range r.Cookies() {
+ if c.Name == name {
+ kept = append(kept, c.Value)
+ }
+ }
+ if len(kept) > 0 {
+ to, err := url.QueryUnescape(kept[0])
+ if len(kept) != 1 || err != nil || !keepableReturn(to) {
+ a.forgetReturn(w, r)
+ r = withoutCookie(r, name)
+ }
+ }
+ next(w, r)
+ }
}
// returnCookieName is rastrillo auth's kept-page cookie: rastrillo_return_to,
diff --git a/internal/fichas/signin_door_test.go b/internal/fichas/signin_door_test.go
index d8ef69f..a7bcfd5 100644
--- a/internal/fichas/signin_door_test.go
+++ b/internal/fichas/signin_door_test.go
@@ -52,25 +52,43 @@ func TestTheDoorJudgesOnlyWebSignins(t *testing.T) {
// What a fresh sign-in may land on.
func TestKeepableReturn(t *testing.T) {
for to, want := range map[string]bool{
- "/": true,
- "/cards/new": true,
- "/t/abc?sort=name": true,
- "": false,
- "cards": false,
- "//evil.example/": false,
- "/\\evil.example": false,
- "https://evil.ex/": false,
- "/signed-out": false,
- "/signed-out?x=1": false,
- "/signin": false,
- "/signin?ways=1": false,
- "/signin/forget": false,
- "/auth/verify": false,
- "/signed-outward": true,
- "/signinsheet": true,
- "/authors": true,
- "/%zz": false,
- "javascript:alert1": false,
+ "/": true,
+ "/cards/new": true,
+ "/t/abc?sort=name": true,
+ "": false,
+ "cards": false,
+ "//evil.example/": false,
+ "/\\evil.example": false,
+ "https://evil.ex/": false,
+ "/signed-out": false,
+ "/signed-out?x=1": false,
+ "/signin": false,
+ "/signin?ways=1": false,
+ "/signin/forget": false,
+ "/auth/verify": false,
+ "/signed-outward": true,
+ "/signinsheet": true,
+ "/authors": true,
+ "/%zz": false,
+ // Dot segments and backslashes, as a browser resolves them
+ // (Fable on fichas #9).
+ "/./signed-out": false,
+ "/x/../signed-out": false,
+ "/x/../signed-out?a=1": false,
+ "/x/./../signed-out/": false,
+ "/%2e/signed-out": false,
+ "/x/%2e%2e/signed-out": false,
+ "/x\\..\\signed-out": false,
+ "/./signin": false,
+ "/x/../signin/forget": false,
+ "/cards/../signin?ways=1": false,
+ "/./auth/verify": false,
+ "/x/../auth/callback": false,
+ "/x/../auth": false,
+ "/cards/./new": true,
+ "/t/x/../t_customer": true,
+ "/x/../cards/new": true,
+ "javascript:alert1": false,
} {
if got := keepableReturn(to); got != want {
t.Errorf("keepableReturn(%q) = %v, want %v", to, got, want)
diff --git a/internal/fichastest/signin_door_keymail_test.go b/internal/fichastest/signin_door_keymail_test.go
new file mode 100644
index 0000000..a1bb614
--- /dev/null
+++ b/internal/fichastest/signin_door_keymail_test.go
@@ -0,0 +1,233 @@
+package fichastest
+
+// The Keymail continuation, driven from the outside: an owner whose
+// address Keymail claims posts to Begin, which keeps the sign-in on the
+// door (/signin?continue=<id>) instead of a 303 off-site that the CSP's
+// form-action 'self' would refuse. These replace auth_navigation_test.go,
+// whose wrapper rastrillo's screen made unnecessary.
+//
+// Nothing here leaves the machine: the classifier's DNS lookup goes to a
+// resolver on loopback that answers "no such name" (so the domain is its
+// own Keymail server, as keymail's protocol says), and its HTTPS probes go
+// to a transport that answers for kmail.test. Both are process globals,
+// swapped for the test and put back.
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/url"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ fichas "amadan.net/oficina/fichas/internal/fichas"
+ "amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/db"
+)
+
+const (
+ keymailOwner = "km@kmail.test" // Keymail claims it
+ plainOwner = "pl@plain.test" // a domain that is not Keymail
+ keymailHost = "kmail.test" // its own server: no _keymail delegation
+)
+
+// fakeKeymail answers the classifier's probes: kmail.test is a Keymail
+// server that claims every address; any other host has no well-known.
+type fakeKeymail struct{ probes atomic.Int32 }
+
+func (f *fakeKeymail) RoundTrip(r *http.Request) (*http.Response, error) {
+ f.probes.Add(1)
+ status, body := http.StatusNotFound, "{}"
+ if r.URL.Host == keymailHost {
+ switch r.URL.Path {
+ case "/.well-known/keymail":
+ status, body = http.StatusOK, `{"version":"1"}`
+ case "/api/federation/lookup":
+ status = http.StatusOK
+ }
+ }
+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil
+}
+
+// withFakeKeymail swaps the resolver and the default transport for the
+// test's length.
+func withFakeKeymail(t *testing.T) *fakeKeymail {
+ t.Helper()
+ pc, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { pc.Close() })
+ go func() {
+ buf := make([]byte, 1500)
+ for {
+ n, from, err := pc.ReadFrom(buf)
+ if err != nil {
+ return
+ }
+ if n < 12 {
+ continue
+ }
+ // The query back as the answer: a response (QR), recursion
+ // available, NXDOMAIN, nothing answered.
+ resp := append([]byte(nil), buf[:n]...)
+ resp[2] = 0x80 | (resp[2] & 0x01)
+ resp[3] = 0x80 | 0x03
+ pc.WriteTo(resp, from)
+ }
+ }()
+ resolver, transport := net.DefaultResolver, http.DefaultTransport
+ net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, "udp", pc.LocalAddr().String())
+ }}
+ fake := &fakeKeymail{}
+ http.DefaultTransport = fake
+ t.Cleanup(func() { net.DefaultResolver, http.DefaultTransport = resolver, transport })
+ return fake
+}
+
+// keymailApp is the app as main.go wires it, owned by keymailOwner and
+// plainOwner.
+func keymailApp(t *testing.T) (*http.ServeMux, *capturingMailer) {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
+ if err != nil {
+ t.Fatalf("db.Open: %v", err)
+ }
+ t.Cleanup(func() { d.Close() })
+ cfg := testConfig(t)
+ cfg.Owners = []string{keymailOwner, plainOwner}
+ mux, app, err := fichas.App(d, cfg, logger)
+ if err != nil {
+ t.Fatalf("App: %v", err)
+ }
+ m := &capturingMailer{}
+ au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: m}, logger, app)
+ if err != nil {
+ t.Fatalf("NewAuth: %v", err)
+ }
+ app.UseAuth(au)
+ return mux, m
+}
+
+var metaRefresh = regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]+)">`)
+
+// A Keymail address: Begin keeps the sign-in on the door, and the
+// Continue step navigates on by itself (a meta refresh, no script) and by
+// its link, to exactly the authorize URL for this origin, on the one-way
+// door (its link a pill), with no-referrer and no-store, under the CSP
+// the app is served with, whose form-action stays 'self'.
+func TestAKeymailAddressContinuesOnTheDoor(t *testing.T) {
+ fake := withFakeKeymail(t)
+ mux, m := keymailApp(t)
+ served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: mux, ErrorPage: fichas.ErrorPage})
+ if err != nil {
+ t.Fatalf("rastrillo.Handler: %v", err)
+ }
+ t.Cleanup(func() { closeDB() })
+
+ b := newBrowser()
+ begin := b.post(t, served, "/auth/begin", url.Values{"address": {keymailOwner}})
+ loc := begin.Header().Get("Location")
+ if begin.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?continue=") {
+ t.Fatalf("Begin for a Keymail address: %d to %q, want the door's continuation (probes: %d)", begin.Code, loc, fake.probes.Load())
+ }
+ if len(m.sent) != 0 {
+ t.Error("a Keymail address was mailed a link")
+ }
+
+ page := b.get(t, served, loc)
+ if page.Code != http.StatusOK {
+ t.Fatalf("GET %s: %d", loc, page.Code)
+ }
+ body := page.Body.String()
+ if got := titleOf(body); got != "Taking you to Keymail to sign in to Fichas" {
+ t.Errorf("title %q", got)
+ }
+ if !strings.Contains(body, `<div rst-signin-door="one-way">`) {
+ t.Errorf("the Continue step is not on the one-way door, so its link is no pill:\n%s", body)
+ }
+ refresh := metaRefresh.FindStringSubmatch(body)
+ if refresh == nil {
+ t.Fatalf("no meta refresh on the Continue step:\n%s", body)
+ }
+ dest, err := url.Parse(strings.ReplaceAll(refresh[1], "&amp;", "&"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := dest.Query()
+ if dest.Scheme != "https" || dest.Host != keymailHost || dest.Path != "/oauth/authorize" ||
+ q.Get("client_id") != testOrigin || q.Get("redirect_uri") != testOrigin+"/auth/callback" ||
+ q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("code_challenge") == "" {
+ t.Errorf("the continuation goes to %s, not this origin's Keymail authorize URL", dest)
+ }
+ if !strings.Contains(body, `<a rst-btn="primary block" href="`+refresh[1]+`">Continue to Keymail</a>`) {
+ t.Errorf("no Continue to Keymail link to the same URL:\n%s", body)
+ }
+ if page.Header().Get("Referrer-Policy") != "no-referrer" || page.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("Referrer-Policy %q, Cache-Control %q", page.Header().Get("Referrer-Policy"), page.Header().Get("Cache-Control"))
+ }
+ csp := page.Header().Get("Content-Security-Policy")
+ if !strings.Contains(csp, "form-action 'self'") || strings.Contains(csp, keymailHost) {
+ t.Errorf("the served CSP %q was widened for Keymail", csp)
+ }
+ if strings.Contains(body, "<script>") {
+ t.Error("the Continue step needs an inline script")
+ }
+}
+
+// The continuation is only ever the one this browser's sealed cookie
+// holds: an id without the cookie, a cookie another browser holds, or a
+// URL in its place draws the door with "That link has expired", never a
+// link anywhere. (The field keeps the address this browser typed: that is
+// its own attempt, not the continuation.)
+func TestTheContinuationGoesNowhereItWasNotSent(t *testing.T) {
+ withFakeKeymail(t)
+ h, _ := keymailApp(t)
+ b := newBrowser()
+ loc := b.post(t, h, "/auth/begin", url.Values{"address": {keymailOwner}}).Header().Get("Location")
+ if !strings.HasPrefix(loc, "/signin?continue=") {
+ t.Fatalf("Begin answered %q", loc)
+ }
+ for name, target := range map[string]string{
+ "no cookie": loc,
+ "a URL for id": "/signin?continue=" + url.QueryEscape("https://evil.example/oauth/authorize"),
+ "another id": "/signin?continue=AAAAAAAAAAAAAAAAAAAAAA",
+ } {
+ jar := newBrowser()
+ if name != "no cookie" {
+ jar = b
+ }
+ body := jar.get(t, h, target).Body.String()
+ if strings.Contains(body, "http-equiv=\"refresh\"") || strings.Contains(body, "evil.example") || strings.Contains(body, "/oauth/authorize") || strings.Contains(body, "Continue to Keymail") {
+ t.Errorf("%s: the door links somewhere:\n%s", name, body)
+ }
+ if !strings.Contains(body, "That link has expired or was already used. Send a new one.") {
+ t.Errorf("%s: the door does not say the continuation is gone", name)
+ }
+ }
+}
+
+// An address Keymail does not claim passes straight through: Begin mails
+// a link and answers Sent on the door, with no continuation.
+func TestANonKeymailAddressIsSentALink(t *testing.T) {
+ fake := withFakeKeymail(t)
+ h, m := keymailApp(t)
+ rec := post(t, h, "/auth/begin", url.Values{"address": {plainOwner}})
+ if loc := rec.Header().Get("Location"); rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?sent=1&attempt=") {
+ t.Errorf("Begin for a plain address: %d to %q, want Sent", rec.Code, loc)
+ }
+ if fake.probes.Load() == 0 {
+ t.Error("the classifier was never asked: this test proves nothing")
+ }
+ if mail := m.last(t); !strings.HasPrefix(mail, plainOwner+"\n") || !linkToken.MatchString(mail) {
+ t.Errorf("no link mailed:\n%s", mail)
+ }
+}
diff --git a/internal/fichastest/signin_door_return_test.go b/internal/fichastest/signin_door_return_test.go
index 824a533..cdf28b9 100644
--- a/internal/fichastest/signin_door_return_test.go
+++ b/internal/fichastest/signin_door_return_test.go
@@ -7,6 +7,7 @@ package fichastest
import (
"net/http"
+ "net/http/httptest"
"net/url"
"strings"
"testing"
@@ -127,3 +128,76 @@ func TestForgetAndSignOutClearTheKeptPage(t *testing.T) {
t.Error("Sign out kept the page")
}
}
+
+// The landing reads the kept page back only when it passes the same test
+// Begin's does: a cookie edited by hand, one past its time, or two of
+// them, and a return_to posted to the landing itself, each land on "/"
+// (Fable on fichas #9). The cookie is cleared on that same response.
+func TestTheLandingTrustsNoPageItWasNotKept(t *testing.T) {
+ for name, c := range map[string]struct {
+ cookies []string
+ posted []string
+ }{
+ "tampered: signed-out": {cookies: []string{url.QueryEscape("/signed-out")}},
+ "tampered: dot segments": {cookies: []string{url.QueryEscape("/x/../signed-out")}},
+ "tampered: the door": {cookies: []string{url.QueryEscape("/./signin")}},
+ "tampered: another site": {cookies: []string{url.QueryEscape("//evil.example/")}},
+ "tampered: not escaped": {cookies: []string{"%zz"}},
+ "duplicate cookies": {cookies: []string{url.QueryEscape("/cards/new"), url.QueryEscape("/t/t_customer")}},
+ "posted: signed-out": {posted: []string{"/signed-out"}},
+ "posted: a page": {posted: []string{"/cards/new"}},
+ "posted: duplicate": {posted: []string{"/cards/new", "/cards/new"}},
+ "posted over a kept cookie": {cookies: []string{url.QueryEscape("/signed-out")}, posted: []string{"/cards/new"}},
+ } {
+ h, m, _ := wiredApp(t)
+ b := newBrowser()
+ tok := linkFor(t, h, b, m, TestOwner, nil)
+ form := url.Values{"token": {tok}, "return_to": c.posted}
+ req := httptest.NewRequest(http.MethodPost, "/auth/verify", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", testOrigin)
+ b.send(req)
+ for _, v := range c.cookies {
+ req.AddCookie(&http.Cookie{Name: returnCookie, Value: v})
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/" {
+ t.Errorf("%s: %d to %q, want 303 to /", name, rec.Code, rec.Header().Get("Location"))
+ }
+ if len(c.cookies) > 0 && !clears(rec, returnCookie) {
+ t.Errorf("%s: the landing did not clear the kept page", name)
+ }
+ }
+}
+
+// An expired cookie: rastrillo's kept page carries no issue time, so its
+// lifetime is the Max-Age Begin gives it, the emailed link's own, after
+// which a browser stops sending it. A cookie sent past that is one
+// written by hand, and is judged as above.
+func TestTheKeptPageLivesNoLongerThanItsLink(t *testing.T) {
+ h, _, _ := wiredApp(t)
+ rec := post(t, h, "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}, "return_to": {"/cards/new"}})
+ var kept *http.Cookie
+ for _, c := range rec.Result().Cookies() {
+ if c.Name == returnCookie {
+ kept = c
+ }
+ }
+ if kept == nil {
+ t.Fatal("Begin kept no page")
+ }
+ if kept.MaxAge <= 0 || kept.MaxAge > 900 || !kept.HttpOnly || kept.Path != "/" {
+ t.Errorf("kept page cookie: Max-Age %d, HttpOnly %v, Path %q; want at most the link's 15 minutes, HttpOnly, /", kept.MaxAge, kept.HttpOnly, kept.Path)
+ }
+}
+
+// clears reports whether rec sets name to nothing.
+func clears(rec *httptest.ResponseRecorder, name string) bool {
+ for _, c := range rec.Result().Cookies() {
+ if c.Name == name && (c.MaxAge < 0 || c.Value == "") {
+ return true
+ }
+ }
+ return false
+}