oficina / memoria Public

Test the native sign-in across both rastrillo sessions packages

native.go hands rastrillo/native's server an old-path sessions handle,
while the app reads sessions with the new one. native_exchange_test.go
runs the exchange through the router in all three shapes the app reads
a session (local with no Home, local with Home configured, a Home
sign-in):

- Exchange: 202 before approval, 404 for a wrong verifier, a new token
  under the cookie name the app reads, the same person (the index names
  alice), and no second exchange.
- Expiry: an expired browser session signs nothing in, an approval that
  expires before the exchange gets 401, and a minted session expires.
- Revocation: a browser signing out between approval and exchange gets
  401, and /signout ends a minted session and leaves the browser's.

Shown red by mutating native.go (an http origin, sessions minted
already expired), and both new guards by breaking what they guard:
polish-audit/r3/scripts/migrate-memoria-native-red.txt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev f85212011d5c1d2df0a0fdb0162b3dc9ce21c17b parent a1e6708
1 file changed, +331 −0
  • internal/memoria/native_exchange_test.go +331 −0
diff --git a/internal/memoria/native_exchange_test.go b/internal/memoria/native_exchange_test.go
new file mode 100644
index 0000000..22a3d83
--- /dev/null
+++ b/internal/memoria/native_exchange_test.go
@@ -0,0 +1,331 @@
+package memoria
+
+import (
+ "bytes"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/memoria/internal/memoria/seal"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+// The native sign-in crosses two rastrillo module paths. The app reads
+// sessions through amadan.net/rastrillo/rastrillo's package (a.sess, and
+// auth's and Home's gates); rastrillo/native's server only takes
+// github.com/carlosframework/rastrillo's, which native.go builds over the
+// same database (the one import TestNoPreMoveRastrillo allows). These
+// tests drive the whole exchange through the router, so a change to
+// either package's sessions table, cookie name, token hash or time
+// layout fails here rather than in the Mac or iPhone app: approval of a
+// browser session, the exchange minting a new one, that one being an
+// ordinary session to the app, and expiry and revocation holding on
+// both sides.
+//
+// Three shapes, because the app reads a session three ways: a local
+// sign-in with no Home, a local sign-in with Home configured, and a Home
+// sign-in (an opaque subject the app resolves through its link store).
+
+// nativeRig is one signed-in browser against one app.
+type nativeRig struct {
+ f *homeRouterFixture
+ browser *http.Cookie
+}
+
+// newLocalOnlyFixture is newHomeRouterFixture without Home: auth's own
+// magic link is the only way in, as on an instance with no MEMORIA_HOME_*.
+func newLocalOnlyFixture(t *testing.T) *homeRouterFixture {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ cipher, err := seal.New(bytes.Repeat([]byte{6}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ mux, a, err := App(d, homeTestOrigin, cipher, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { a.store.ix.Close() })
+ a.SetOwners([]string{"alice@example.test"})
+ mail := &homeTestMail{}
+ auth, err := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: mail}, logger, a.Admit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.UseAuth(auth)
+ a.MountAuth(mux, homeTestOrigin)
+ return &homeRouterFixture{a, mux, nil, mail, map[string]*http.Cookie{}}
+}
+
+func nativeRigs() map[string]func(*testing.T) *nativeRig {
+ session := func(t *testing.T, f *homeRouterFixture) *http.Cookie {
+ t.Helper()
+ for _, c := range f.cookies {
+ if strings.Contains(c.Name, "session") {
+ return c
+ }
+ }
+ t.Fatalf("no session cookie in %v", f.cookies)
+ return nil
+ }
+ return map[string]func(*testing.T) *nativeRig{
+ "local, no Home": func(t *testing.T) *nativeRig {
+ f := newLocalOnlyFixture(t)
+ homeRedirect(t, f.do("POST", "/auth/begin", "address=alice%40example.test&force=1"))
+ link := regexp.MustCompile(`https://[^\s<>\"]+/auth/verify\?[^\s<>\"]+`).FindString(f.mail.body)
+ u, err := url.Parse(link)
+ if err != nil || link == "" {
+ t.Fatal("no captured verification link")
+ }
+ homeRedirect(t, f.do("GET", u.RequestURI(), ""))
+ return &nativeRig{f, session(t, f)}
+ },
+ "local, Home configured": func(t *testing.T) *nativeRig {
+ f := newHomeRouterFixture(t)
+ f.local(t)
+ return &nativeRig{f, session(t, f)}
+ },
+ "Home sign-in": func(t *testing.T) *nativeRig {
+ f := newHomeRouterFixture(t)
+ f.local(t)
+ if w := f.do("GET", "/account/home", ""); w.Code != 200 {
+ t.Fatalf("link page = %d", w.Code)
+ }
+ start := homeRedirect(t, f.do("POST", "/account/home", ""))
+ homeRedirect(t, f.exchange(t, start, "opaque-home-alice"))
+ homeRedirect(t, f.do("POST", "/account/home/confirm", ""))
+ f.do("POST", "/signout", "")
+ start = homeRedirect(t, f.do("GET", "/signin", ""))
+ homeRedirect(t, f.exchange(t, start, "opaque-home-alice"))
+ c := session(t, f)
+ var method string
+ if err := f.app.db.G.Raw(`SELECT method FROM sessions WHERE token_hash = ?`, sessions.HashToken(c.Value)).Scan(&method).Error; err != nil || method == "magiclink" || method == "" {
+ t.Fatalf("the fixture's session is not a Home session: method %q, %v", method, err)
+ }
+ return &nativeRig{f, c}
+ },
+ }
+}
+
+func (n *nativeRig) post(t *testing.T, path, body string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Origin", homeTestOrigin)
+ for _, c := range cookies {
+ r.AddCookie(c)
+ }
+ w := httptest.NewRecorder()
+ n.f.handler.ServeHTTP(w, r)
+ return w
+}
+
+// request starts a native sign-in and returns its id and verifier.
+func (n *nativeRig) request(t *testing.T) (id, verifier string) {
+ t.Helper()
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ t.Fatal(err)
+ }
+ verifier = base64.RawURLEncoding.EncodeToString(b)
+ sum := sha256.Sum256([]byte(verifier))
+ w := n.post(t, "/native/request", `{"challenge":"`+base64.RawURLEncoding.EncodeToString(sum[:])+`"}`)
+ var out struct{ ID string }
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.ID == "" {
+ t.Fatalf("POST /native/request = %d %q", w.Code, w.Body.String())
+ }
+ return out.ID, verifier
+}
+
+// approve is the signed-in browser pressing "Sign in to Memoria app".
+func (n *nativeRig) approve(t *testing.T, id string) *httptest.ResponseRecorder {
+ t.Helper()
+ return n.post(t, "/native/authorize?id="+id, "", n.browser)
+}
+
+func (n *nativeRig) exchange(t *testing.T, id, verifier string) *httptest.ResponseRecorder {
+ t.Helper()
+ return n.post(t, "/native/exchange", `{"id":"`+id+`","verifier":"`+verifier+`"}`)
+}
+
+// mint runs a whole approved exchange and returns the minted cookie.
+func (n *nativeRig) mint(t *testing.T) *http.Cookie {
+ t.Helper()
+ id, verifier := n.request(t)
+ if w := n.approve(t, id); w.Code != 200 {
+ t.Fatalf("approval = %d", w.Code)
+ }
+ w := n.exchange(t, id, verifier)
+ var minted struct{ Name, Value string }
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil {
+ t.Fatalf("exchange = %d %q", w.Code, w.Body.String())
+ }
+ return &http.Cookie{Name: minted.Name, Value: minted.Value}
+}
+
+// who is the native API's answer to one cookie, and the address the
+// index page names for it: the status, and who the app thinks it is.
+func (n *nativeRig) who(t *testing.T, c *http.Cookie) (int, bool) {
+ t.Helper()
+ r := httptest.NewRequest("GET", homeTestOrigin+"/api/native/session", nil)
+ r.AddCookie(c)
+ w := httptest.NewRecorder()
+ n.f.handler.ServeHTTP(w, r)
+ if w.Code != 200 {
+ return w.Code, false
+ }
+ r = httptest.NewRequest("GET", homeTestOrigin+"/", nil)
+ r.AddCookie(c)
+ page := httptest.NewRecorder()
+ n.f.handler.ServeHTTP(page, r)
+ return w.Code, page.Code == 200 && strings.Contains(page.Body.String(), "alice@example.test")
+}
+
+func (n *nativeRig) setExpiry(t *testing.T, token string, at time.Time) {
+ t.Helper()
+ res := n.f.app.db.G.Exec(`UPDATE sessions SET expires_at = ? WHERE token_hash = ?`, at.UTC().Format(time.RFC3339), sessions.HashToken(token))
+ if res.Error != nil || res.RowsAffected != 1 {
+ t.Fatalf("expire session: %v, %d rows", res.Error, res.RowsAffected)
+ }
+}
+
+func TestNativeExchangeMintsASessionTheAppAccepts(t *testing.T) {
+ for name, build := range nativeRigs() {
+ t.Run(name, func(t *testing.T) {
+ n := build(t)
+ if code, alice := n.who(t, n.browser); code != 200 || !alice {
+ t.Fatalf("the browser's own session: GET /api/native/session = %d, names alice: %v", code, alice)
+ }
+ id, verifier := n.request(t)
+ if w := n.exchange(t, id, verifier); w.Code != http.StatusAccepted {
+ t.Fatalf("exchange before approval = %d, want 202", w.Code)
+ }
+ if w := n.approve(t, id); w.Code != 200 || !strings.Contains(w.Body.String(), "is signed in") {
+ t.Fatalf("approval = %d: %s", w.Code, w.Body.String())
+ }
+ wrong := make([]byte, 32)
+ _, _ = rand.Read(wrong)
+ if w := n.exchange(t, id, base64.RawURLEncoding.EncodeToString(wrong)); w.Code != http.StatusNotFound {
+ t.Fatalf("exchange with the wrong verifier = %d, want 404", w.Code)
+ }
+ w := n.exchange(t, id, verifier)
+ var minted struct{ Name, Value string }
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil {
+ t.Fatalf("exchange = %d %q", w.Code, w.Body.String())
+ }
+ // The pre-move package names the cookie the app reads, and
+ // mints a new token rather than handing back the browser's.
+ if minted.Name != n.browser.Name {
+ t.Fatalf("exchange minted cookie %q; the app reads %q", minted.Name, n.browser.Name)
+ }
+ if minted.Value == "" || minted.Value == n.browser.Value {
+ t.Fatal("exchange did not mint a session of its own")
+ }
+ // And the app takes it as the same person.
+ code, alice := n.who(t, &http.Cookie{Name: minted.Name, Value: minted.Value})
+ if code != 200 {
+ t.Fatalf("the app refuses the session native minted: GET /api/native/session = %d", code)
+ }
+ if !alice {
+ t.Fatal("the minted session is somebody else: the index does not name alice")
+ }
+ // Spent: the same id never exchanges twice.
+ if w := n.exchange(t, id, verifier); w.Code != http.StatusNotFound {
+ t.Fatalf("second exchange = %d, want 404", w.Code)
+ }
+ })
+ }
+}
+
+func TestNativeSessionExpiryHolds(t *testing.T) {
+ for name, build := range nativeRigs() {
+ t.Run(name, func(t *testing.T) {
+ n := build(t)
+
+ // An expired browser session signs nothing in. (The approval
+ // page records whatever cookie it is shown; the exchange is
+ // where the session is authenticated, from scratch.)
+ n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute))
+ id, verifier := n.request(t)
+ n.approve(t, id)
+ if w := n.exchange(t, id, verifier); w.Code == 200 {
+ t.Fatal("an expired browser session signed a native app in")
+ }
+
+ // Approved while live, expired before the exchange: refused.
+ n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour))
+ id, verifier = n.request(t)
+ n.approve(t, id)
+ n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute))
+ if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized {
+ t.Fatalf("exchange of an expired approval = %d, want 401", w.Code)
+ }
+
+ // A minted session expires like any other.
+ n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour))
+ native := n.mint(t)
+ if code, _ := n.who(t, native); code != 200 {
+ t.Fatalf("live minted session: GET /api/native/session = %d", code)
+ }
+ n.setExpiry(t, native.Value, time.Now().Add(-time.Minute))
+ if code, _ := n.who(t, native); code == 200 {
+ t.Fatal("the app still accepts a minted session past its expiry")
+ }
+ })
+ }
+}
+
+func TestNativeSessionRevocationHolds(t *testing.T) {
+ for name, build := range nativeRigs() {
+ t.Run(name, func(t *testing.T) {
+ // Signing the browser out between approval and exchange
+ // refuses the exchange.
+ n := build(t)
+ id, verifier := n.request(t)
+ n.approve(t, id)
+ if res := n.f.app.db.G.Exec(`DELETE FROM sessions WHERE token_hash = ?`, sessions.HashToken(n.browser.Value)); res.Error != nil || res.RowsAffected != 1 {
+ t.Fatalf("revoke the browser's session: %v", res.Error)
+ }
+ if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized {
+ t.Fatalf("exchange after the browser signed out = %d, want 401", w.Code)
+ }
+
+ // The app signing out a minted session (the app's own
+ // sessions package, deleting a row the pre-move package
+ // wrote) ends it, and leaves the browser's alone.
+ n = build(t)
+ native := n.mint(t)
+ r := httptest.NewRequest("POST", homeTestOrigin+"/signout", nil)
+ r.Header.Set("Origin", homeTestOrigin)
+ r.AddCookie(native)
+ w := httptest.NewRecorder()
+ n.f.handler.ServeHTTP(w, r)
+ if w.Code >= 400 {
+ t.Fatalf("POST /signout with the minted session = %d", w.Code)
+ }
+ if code, _ := n.who(t, native); code == 200 {
+ t.Fatal("a signed-out minted session still reaches the native API")
+ }
+ if code, _ := n.who(t, n.browser); code != 200 {
+ t.Fatalf("signing native out ended the browser's session too: GET /api/native/session = %d", code)
+ }
+ })
+ }
+}