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 browser's default calendar), 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 the guard by putting viewer.go back on the old path: polish-audit/r3/scripts/migrate-calendar-native-red.txt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+280
−0
internal/calendar/native_exchange_test.go+280 −0
diff --git a/internal/calendar/native_exchange_test.go b/internal/calendar/native_exchange_test.go| new file mode 100644 |
| index 0000000..9380e66 |
| --- /dev/null |
| +++ b/internal/calendar/native_exchange_test.go |
| @@ -0,0 +1,280 @@ |
| +package calendar |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// The native sign-in crosses two rastrillo module paths. The app's |
| +// sessions are amadan.net/rastrillo/rastrillo's; 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 (auth's RequireSession), a local sign-in with |
| +// Home configured, and a Home sign-in (both through the Home |
| +// connection's own sessions, the second resolving an opaque subject). |
| + |
| +// nativeRig is one signed-in browser against one app. |
| +type nativeRig struct { |
| + app *App |
| + origin string |
| + browser *http.Cookie |
| +} |
| + |
| +func nativeRigs(t *testing.T) map[string]func(*testing.T) *nativeRig { |
| + return map[string]func(*testing.T) *nativeRig{ |
| + "local, no Home": func(t *testing.T) *nativeRig { |
| + a, err := New(Config{DBPath: filepath.Join(t.TempDir(), "calendar.db"), Env: "development", Origin: TestOrigin, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + return &nativeRig{a, TestOrigin, a.SignInForTest(t, "alice@example.test")} |
| + }, |
| + "local, Home configured": func(t *testing.T) *nativeRig { |
| + f := newHomeRouterFixture(t) |
| + f.local(t) |
| + return &nativeRig{f.app, homeTestOrigin, f.cookies[f.app.home.sessions.CookieName()]} |
| + }, |
| + "Home sign-in": func(t *testing.T) *nativeRig { |
| + f := newHomeRouterFixture(t) |
| + f.local(t) |
| + // The first signed-in page sets the person up; linking needs one. |
| + if w := f.do("GET", "/day/2026-09-10", ""); w.Code != 200 { |
| + t.Fatalf("first page = %d", w.Code) |
| + } |
| + if w := f.do("GET", "/account/home", ""); w.Code != 200 { |
| + t.Fatalf("link page = %d %s", w.Code, w.Body.String()) |
| + } |
| + 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", "")) |
| + if got := homeRedirect(t, f.exchange(t, start, "opaque-home-alice")); got != "/" { |
| + t.Fatalf("Home sign-in landed on %q", got) |
| + } |
| + c := f.cookies[f.app.home.sessions.CookieName()] |
| + 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.app, homeTestOrigin, c} |
| + }, |
| + } |
| +} |
| + |
| +func (n *nativeRig) do(t *testing.T, method, path, body string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest(method, n.origin+path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Origin", n.origin) |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + n.app.mux.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.do(t, "POST", "/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 Calendar app". |
| +func (n *nativeRig) approve(t *testing.T, id string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return n.do(t, "POST", "/native/authorize?id="+id, "", n.browser) |
| +} |
| + |
| +func (n *nativeRig) exchange(t *testing.T, id, verifier string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + return n.do(t, "POST", "/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} |
| +} |
| + |
| +// defaultCalendar is GET /api/native/session with one cookie: the |
| +// status, and whose default calendar it answered with. |
| +func (n *nativeRig) defaultCalendar(t *testing.T, c *http.Cookie) (int, int64) { |
| + t.Helper() |
| + w := n.do(t, "GET", "/api/native/session", "", c) |
| + var s struct { |
| + Default int64 `json:"default_calendar_id"` |
| + } |
| + _ = json.Unmarshal(w.Body.Bytes(), &s) |
| + return w.Code, s.Default |
| +} |
| + |
| +func (n *nativeRig) setExpiry(t *testing.T, token string, at time.Time) { |
| + t.Helper() |
| + res := n.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) { |
| + t.Run(name, func(t *testing.T) { |
| + n := build(t) |
| + code, want := n.defaultCalendar(t, n.browser) |
| + if code != 200 || want == 0 { |
| + t.Fatalf("the browser's own session: GET /api/native/session = %d", code) |
| + } |
| + 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, got := n.defaultCalendar(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 got != want { |
| + t.Fatalf("the minted session is somebody else: default calendar %d, the browser's is %d", got, want) |
| + } |
| + // 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) { |
| + 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.defaultCalendar(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.defaultCalendar(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) { |
| + 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.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) |
| + if w := n.do(t, "POST", "/signout", "", native); w.Code >= 400 { |
| + t.Fatalf("POST /signout with the minted session = %d", w.Code) |
| + } |
| + if code, _ := n.defaultCalendar(t, native); code == 200 { |
| + t.Fatal("a signed-out minted session still reaches the native API") |
| + } |
| + if code, _ := n.defaultCalendar(t, n.browser); code != 200 { |
| + t.Fatalf("signing native out ended the browser's session too: GET /api/native/session = %d", code) |
| + } |
| + }) |
| + } |
| +} |