oficina / memoria Public

Smart door review fixes (Fable on #49)

1. /auth/finish and POST /account/home/choose spend the page a local
   sign-in kept, on the response that mints the session (spentOnMint),
   as every landing does. Answers that go on to the choice or, for
   "Connect my existing account", to the email-only door mint nothing
   and keep it. Tests for both routes, the choice both ways.
2. TestAnUndecidedGateIsNoRefusal asserts the retryable no-store 503 on
   GET /api/native/session and POST /api/native/search outside team
   mode.
3. TestAStrangersBeginIsAnOwnersSent compares equal-length addresses
   down to each cookie's Max-Age, flags and value length, plain, as a
   step-up, with expect=keymail, and from a browser already holding an
   attempt.
4. A removed session at /signin?err=expired, ?reauth=1, ?force=1 and
   ?sent=1 is ended there and the door drawn; Sent says nothing (as
   Calendar found), the others say the removal.
5. homeUnavailable sends Retry-After, as teamUnavailable does.
6. beginGuard's comment names response time as a fourth residual.

Each fix was seen to fail its test when reverted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e19e6ac568893ed36eb7f2c53a1ba47c27c28c51 parent ac7b108
7 files changed, +217 −40
  • internal/memoria/app.go +4 −2
  • internal/memoria/auth.go +9 −2
  • internal/memoria/home.go +3 −0
  • internal/memoria/return.go +30 −0
  • internal/memoria/signin_door_refusal_test.go +46 −0
  • internal/memoria/signin_door_return_test.go +53 −0
  • internal/memoria/signin_door_states_test.go +72 −36

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/memoria/ ./internal/memoriatest/
=== fmt ===
=== test ===
go test ./...
?   	amadan.net/oficina/memoria/cmd/memoria	[no test files]
?   	amadan.net/oficina/memoria/cmd/memoria-contract	[no test files]
ok  	amadan.net/oficina/memoria/internal/memoria	12.565s
ok  	amadan.net/oficina/memoria/internal/memoria/chunk	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/fact	(cached)
?   	amadan.net/oficina/memoria/internal/memoria/icons	[no test files]
ok  	amadan.net/oficina/memoria/internal/memoria/index	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/notion	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/provider	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/query	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/seal	(cached)
ok  	amadan.net/oficina/memoria/internal/memoria/sibling	(cached)
?   	amadan.net/oficina/memoria/internal/memoria/teamstate	[no test files]
ok  	amadan.net/oficina/memoria/internal/memoriatest	5.043s
?   	amadan.net/oficina/memoria/scripts/writeestilo	[no test files]
?   	amadan.net/oficina/memoria/tools/bench	[no test files]
?   	amadan.net/oficina/memoria/tools/drive	[no test files]
?   	amadan.net/oficina/memoria/tools/seed	[no test files]
?   	amadan.net/oficina/memoria/tools/vendorassets	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/internal/memoria/app.go b/internal/memoria/app.go
index 20cf144..52859b6 100644
--- a/internal/memoria/app.go
+++ b/internal/memoria/app.go
@@ -172,7 +172,7 @@ func AppWith(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, e
a.routeNotFound(w, r)
return
}
- a.home.bridge.ChoosePost(w, r)
+ a.spentOnMint(a.home.bridge.ChoosePost)(w, r)
})
// Where Sign out lands, standalone and with Home alike: connect's
// SignedOut with Home (which puts the Forget path on the page),
@@ -316,7 +316,9 @@ func (a *app) MountAuth(mux *http.ServeMux, origin string) {
r.Post("/signout", a.homeSignout)
r.Get("/auth/start", a.home.bridge.Start)
r.Post("/auth/assertion", a.home.bridge.Callback)
- r.Get("/auth/finish", a.home.bridge.Finish)
+ // A finished exchange spends a page a local sign-in kept, as every
+ // landing does (spentOnMint).
+ r.Get("/auth/finish", a.spentOnMint(a.home.bridge.Finish))
r.Get("/auth/local/complete", a.landedAfter(a.localComplete))
}
mux.Handle("/auth/", r)
diff --git a/internal/memoria/auth.go b/internal/memoria/auth.go
index bf1e5af..1a677e9 100644
--- a/internal/memoria/auth.go
+++ b/internal/memoria/auth.go
@@ -52,7 +52,7 @@ const beginPath = "/auth/begin"
// since the dial only confirms the instance exists while an oracle
// confirms who owns it.
//
-// THREE RESIDUALS, and the second one means the sentence above is an aim
+// FOUR RESIDUALS, and the second one means the sentence above is an aim
// rather than an achievement. Stated here because an earlier version of
// this comment claimed the guard was not an oracle, and it is one.
//
@@ -78,7 +78,14 @@ const beginPath = "/auth/begin"
// it is listed because "no dial" and "no outbound anything" are not
// the same claim.
//
-// All three are narrower than the status quo, where the dial happens for
+// 4. **Response time.** An owner's answer waits for the classifier's
+// dial and the mailer inside Begin; a stranger's is answered here at
+// once. The two answers are the same bytes (AnswerAsSent), but how
+// long they take is not, and nothing here pads one to match the
+// other. Closing it needs the same upstream reordering as 2, or the
+// mail sent after the response as Calls does (signin_mail.go).
+//
+// All four are narrower than the status quo, where the dial happens for
// every address at every domain, and all three close when the upstream
// fix lands.
func (a *app) beginGuard(origin string, next http.HandlerFunc) http.HandlerFunc {
diff --git a/internal/memoria/home.go b/internal/memoria/home.go
index 0c943a7..b2c5598 100644
--- a/internal/memoria/home.go
+++ b/internal/memoria/home.go
@@ -3,10 +3,12 @@ package memoria
import (
"context"
"net/http"
+ "strconv"
"time"
"amadan.net/oficina/home/connect"
"amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/roster"
"amadan.net/rastrillo/rastrillo/csrf"
"amadan.net/rastrillo/rastrillo/migrate"
"amadan.net/rastrillo/rastrillo/sessions"
@@ -114,6 +116,7 @@ func (a *app) homeMiddleware(origin string) func(http.Handler) http.Handler {
// session (signin_admission.go).
func (a *app) homeUnavailable(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Retry-After", strconv.Itoa(int(roster.RetryAfter/time.Second)))
a.errorPage(w, r, http.StatusServiceUnavailable, kindStatus, "")
}
diff --git a/internal/memoria/return.go b/internal/memoria/return.go
index 0fd46a2..ca4d91f 100644
--- a/internal/memoria/return.go
+++ b/internal/memoria/return.go
@@ -355,6 +355,36 @@ func (a *app) landedAfter(complete http.HandlerFunc) http.HandlerFunc {
}
}
+// spentOnMint wraps a Home route that may finish a sign-in without a
+// local landing (connect's /auth/finish, and the member choice's POST):
+// when its answer mints a session, the page a local sign-in kept is
+// spent on that same response, as every landing spends it (Fable on
+// oficina/memoria #49). An answer that sends the browser on to the
+// choice, or "Connect my existing account" to the email-only door, mints
+// no session, so it keeps the page: that sign-in is not over, and still
+// needs it. (A Location check for those two was written and deleted: no
+// minting answer goes there, so it could not fail.)
+func (a *app) spentOnMint(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ result := &bufferedResponse{header: make(http.Header)}
+ next(result, r)
+ if a.auth != nil && mintsSession(result.header, a.sessionCookie()) {
+ a.forgetReturn(result)
+ }
+ result.replay(w)
+ }
+}
+
+// mintsSession reports whether h sets the named session cookie to a value.
+func mintsSession(h http.Header, name string) bool {
+ for _, c := range (&http.Response{Header: h}).Cookies() {
+ if c.Name == name && c.MaxAge >= 0 && c.Value != "" {
+ return true
+ }
+ }
+ return false
+}
+
// rewriteLocation swaps one Location for another at the last moment a
// header is still settable. to == "" leaves it alone.
type rewriteLocation struct {
diff --git a/internal/memoria/signin_door_refusal_test.go b/internal/memoria/signin_door_refusal_test.go
index 81e041f..f036f53 100644
--- a/internal/memoria/signin_door_refusal_test.go
+++ b/internal/memoria/signin_door_refusal_test.go
@@ -225,6 +225,22 @@ func TestAnUndecidedGateIsNoRefusal(t *testing.T) {
if rec := f.send(page); rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("a page with identity storage down = %d %q %q, want a no-store 503", rec.Code, rec.Header().Get("Cache-Control"), rec.Header().Get("Location"))
}
+ // The native apps' API too, as plain text, the same retryable no-store
+ // 503 (a deliberate change: outside team mode this was a 404).
+ for _, c := range []struct{ method, path, body string }{
+ {http.MethodGet, "/api/native/session", ""},
+ {http.MethodPost, "/api/native/search", `{"query":"plan"}`},
+ } {
+ r := httptest.NewRequest(c.method, homeTestOrigin+c.path, strings.NewReader(c.body))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Origin", homeTestOrigin)
+ for _, ck := range f.cookies {
+ r.AddCookie(ck)
+ }
+ if rec := f.send(r); rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Cache-Control") != "no-store" || rec.Header().Get("Retry-After") == "" {
+ t.Fatalf("%s %s with identity storage down = %d %q, Retry-After %q; want a retryable no-store 503", c.method, c.path, rec.Code, rec.Header().Get("Cache-Control"), rec.Header().Get("Retry-After"))
+ }
+ }
if !f.liveSession(session) {
t.Fatal("a 503 ended the session")
}
@@ -305,3 +321,33 @@ func TestTheDoorJudgesWebSessionsOnly(t *testing.T) {
})
}
}
+
+// A removed owner's session on any of the door's states (a problem, a
+// step-up, a failed Keymail, Sent) is ended there too, and the door is
+// drawn, not a loop. The removal is said on each, except Sent, which
+// rastrillo draws as Sent with no app problem (as Calendar found): the
+// session is still ended there (Calendar's gap tests, Fable on #49).
+func TestARemovedSessionOnTheDoorsStates(t *testing.T) {
+ for _, path := range []string{"/signin?err=expired", "/signin?reauth=1", "/signin?force=1", "/signin?sent=1"} {
+ t.Run(path, func(t *testing.T) {
+ doorModes(t, func(t *testing.T, f *homeRouterFixture) {
+ f.session(t, "alice@example.test", "magiclink", time.Now())
+ session := f.sessionCookie().Value
+ f.app.SetOwners([]string{"someone-else@example.test"})
+ rec := f.get(path)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("GET %s for a removed session = %d %q", path, rec.Code, rec.Header().Get("Location"))
+ }
+ if !clears(rec, f.app.sessionCookie()) || f.liveSession(session) {
+ t.Fatalf("GET %s kept a removed session", path)
+ }
+ if says := strings.Contains(rec.Body.String(), signinRemoved); says != (path != "/signin?sent=1") {
+ t.Errorf("GET %s says the removal: %v", path, says)
+ }
+ if again := f.get("/signin"); again.Code != http.StatusOK || strings.Contains(again.Body.String(), signinRemoved) {
+ t.Fatalf("the next /signin: %d", again.Code)
+ }
+ })
+ })
+ }
+}
diff --git a/internal/memoria/signin_door_return_test.go b/internal/memoria/signin_door_return_test.go
index 0361e5f..72a68ca 100644
--- a/internal/memoria/signin_door_return_test.go
+++ b/internal/memoria/signin_door_return_test.go
@@ -13,6 +13,8 @@ import (
"strings"
"testing"
"time"
+
+ "amadan.net/oficina/home/connect"
)
// The door's form posts return_to; Begin never sees it; the sign-in lands
@@ -248,3 +250,54 @@ func TestTheLinkStepUpStaysLocalEndToEnd(t *testing.T) {
t.Fatalf("the link page after the step-up = %d", w.Code)
}
}
+
+// A finished Oficina ID exchange (/auth/finish) and the member choice's
+// "I'm new here" spend a page a local sign-in kept, on the response that
+// mints the session, as every landing does; an answer that sends the
+// browser on to the choice, or "Connect my existing account" to the
+// email-only door, keeps it (Fable on #49, finding 1).
+func TestAFinishedExchangeSpendsTheKeptPage(t *testing.T) {
+ f := newHomeRouterFixture(t)
+ f.link(t)
+ f.signOut(t)
+ f.cookies = map[string]*http.Cookie{}
+ f.get("/signin/local?return_to=%2Fconnectors")
+ if f.returnPath() != "/connectors" {
+ t.Fatalf("nothing kept: %q", f.returnPath())
+ }
+ fin := f.oficinaSignin(t, "/signin/oficina", "opaque-home-alice")
+ if fin.Code != http.StatusSeeOther || !sets(fin, f.app.sessionCookie()) || !clears(fin, f.app.returnCookieName()) {
+ t.Fatalf("/auth/finish = %d, mints %v, clears %v; want the kept page spent with the session", fin.Code, sets(fin, f.app.sessionCookie()), clears(fin, f.app.returnCookieName()))
+ }
+ if f.returnPath() != "" {
+ t.Fatalf("the kept page survived the exchange: %q", f.returnPath())
+ }
+}
+
+func TestTeamTheChoiceSpendsTheKeptPageOnlyWhenItSignsIn(t *testing.T) {
+ for _, c := range []struct {
+ choice string
+ spent bool
+ }{{"new", true}, {"connect", false}} {
+ t.Run(c.choice, func(t *testing.T) {
+ f := newTeamFixture(t, "carol@example.test")
+ subject := teamSubject('k')
+ f.dir.Set(subject, "member")
+ f.refreshed()
+ f.cookies = map[string]*http.Cookie{}
+ f.get("/signin/local?return_to=%2Fconnectors")
+ fin := f.signInChoosing(subject)
+ redirectsTo(t, fin, connect.ChoosePath)
+ if clears(fin, f.app.returnCookieName()) || f.returnPath() != "/connectors" {
+ t.Fatal("/auth/finish spent the kept page on its way to the choice")
+ }
+ w := f.choose(c.choice)
+ if got := clears(w, f.app.returnCookieName()); got != c.spent {
+ t.Fatalf("choice %s: clears the kept page %v, want %v (%d %q)", c.choice, got, c.spent, w.Code, w.Header().Get("Location"))
+ }
+ if (f.returnPath() == "") != c.spent {
+ t.Fatalf("choice %s: memory now %q", c.choice, f.returnPath())
+ }
+ })
+ }
+}
diff --git a/internal/memoria/signin_door_states_test.go b/internal/memoria/signin_door_states_test.go
index 7807ed8..1ff873c 100644
--- a/internal/memoria/signin_door_states_test.go
+++ b/internal/memoria/signin_door_states_test.go
@@ -4,6 +4,7 @@ package memoria
// "Routes, and every state the door must answer"), with Home and without.
import (
+ "fmt"
"net/http"
"net/url"
"strings"
@@ -176,43 +177,78 @@ func TestAnEmailSigninThroughTheDoor(t *testing.T) {
})
}
-// A stranger's post is answered exactly as an owner's is: the same status,
-// the same Sent (attempt id aside), the same cookies set, and nothing
-// mailed (beginGuard's AnswerAsSent, gate 33).
+// A stranger's post is answered exactly as an owner's is (beginGuard's
+// AnswerAsSent, gate 33): for addresses of the same length, the same
+// status, the same Sent (attempt id aside, of the same length), the same
+// cookies with the same Max-Age, flags and value lengths, and nothing
+// mailed. Plain, as a step-up, as the remembered-Keymail one-tap
+// (expect=keymail), and from a browser that already holds an attempt.
func TestAStrangersBeginIsAnOwnersSent(t *testing.T) {
- doorModes(t, func(t *testing.T, f *homeRouterFixture) {
- answer := func(address string) (int, string, []string) {
- br := f.fresh()
- rec := br.do(http.MethodPost, "/auth/begin", url.Values{"address": {address}, "force": {"1"}, "return_to": {"/connectors"}}.Encode())
- var names []string
- for _, c := range rec.Result().Cookies() {
- names = append(names, c.Name)
- }
- u, _ := url.Parse(rec.Header().Get("Location"))
- q := u.Query()
- if q.Get("attempt") == "" {
- t.Errorf("%s: Sent carries no attempt: %q", address, rec.Header().Get("Location"))
- }
- q.Del("attempt")
- u.RawQuery = q.Encode()
- return rec.Code, u.String(), names
- }
- f.mail.body = ""
- sc, sl, sn := answer("stranger@elsewhere.test")
- if f.mail.body != "" {
- t.Fatal("a link was mailed to a stranger")
- }
- oc, ol, on := answer("alice@example.test")
- if f.mail.body == "" {
- t.Fatal("no link was mailed to the owner, so the comparison proves nothing")
- }
- if sc != oc || sl != ol || strings.Join(sn, ",") != strings.Join(on, ",") {
- t.Fatalf("a stranger is answered %d %q %v, an owner %d %q %v", sc, sl, sn, oc, ol, on)
- }
- if ol != "/signin?return_to=%2Fconnectors&sent=1" {
- t.Fatalf("Sent = %q, want the door's Sent with the page", ol)
- }
- })
+ type cookieShape struct {
+ Name, Path string
+ MaxAge, ValueLen int
+ Secure, HTTPOnly bool
+ SameSite http.SameSite
+ }
+ type answer struct {
+ Code int
+ Location string
+ Cookies []cookieShape
+ }
+ const owner, stranger = "alice@example.test", "zzzzz@example.test"
+ for _, c := range []struct {
+ name string
+ extra url.Values
+ before bool
+ }{
+ {"plain", nil, false},
+ {"a step-up", url.Values{"reauth": {"1"}}, false},
+ {"expect=keymail", url.Values{"expect": {"keymail"}}, false},
+ {"an attempt already held", nil, true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ doorModes(t, func(t *testing.T, f *homeRouterFixture) {
+ post := func(address string) answer {
+ br := f.fresh()
+ form := url.Values{"address": {address}, "force": {"1"}, "return_to": {"/connectors"}}
+ for k, v := range c.extra {
+ form[k] = v
+ }
+ if c.before {
+ br.do(http.MethodPost, "/auth/begin", form.Encode())
+ }
+ rec := br.do(http.MethodPost, "/auth/begin", form.Encode())
+ u, _ := url.Parse(rec.Header().Get("Location"))
+ q := u.Query()
+ if q.Get("attempt") == "" {
+ t.Errorf("%s: Sent carries no attempt: %q", address, rec.Header().Get("Location"))
+ }
+ q.Set("attempt", strings.Repeat("x", len(q.Get("attempt"))))
+ u.RawQuery = q.Encode()
+ a := answer{Code: rec.Code, Location: u.String()}
+ for _, ck := range rec.Result().Cookies() {
+ a.Cookies = append(a.Cookies, cookieShape{ck.Name, ck.Path, ck.MaxAge, len(ck.Value), ck.Secure, ck.HttpOnly, ck.SameSite})
+ }
+ return a
+ }
+ f.mail.body = ""
+ s := post(stranger)
+ if f.mail.body != "" {
+ t.Fatal("a link was mailed to a stranger")
+ }
+ o := post(owner)
+ if f.mail.body == "" {
+ t.Fatal("no link was mailed to the owner, so the comparison proves nothing")
+ }
+ if fmt.Sprint(s) != fmt.Sprint(o) {
+ t.Fatalf("a stranger is answered\n%+v\nan owner\n%+v", s, o)
+ }
+ if u, _ := url.Parse(o.Location); u.Path != "/signin" || u.Query().Get("sent") != "1" || u.Query().Get("return_to") != "/connectors" {
+ t.Fatalf("Sent = %q, want the door's Sent with the page", o.Location)
+ }
+ })
+ })
+ }
}
// The guard's own answer to a malformed address is Begin's shape: err,