| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | "log/slog" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "net/url" |
| 14 | "path/filepath" |
| 15 | "regexp" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 21 | "amadan.net/rastrillo/rastrillo/db" |
| 22 | "amadan.net/rastrillo/rastrillo/sessions" |
| 23 | ) |
| 24 | |
| 25 | // The native sign-in crosses two rastrillo module paths. The app reads |
| 26 | // sessions through amadan.net/rastrillo/rastrillo's package (a.sess, and |
| 27 | // auth's and Home's gates); rastrillo/native's server only takes |
| 28 | // github.com/carlosframework/rastrillo's, which native.go builds over the |
| 29 | // same database (the one import TestNoPreMoveRastrillo allows). These |
| 30 | // tests drive the whole exchange through the router, so a change to |
| 31 | // either package's sessions table, cookie name, token hash or time |
| 32 | // layout fails here rather than in the Mac or iPhone app: approval of a |
| 33 | // browser session, the exchange minting a new one, that one being an |
| 34 | // ordinary session to the app, and expiry and revocation holding on |
| 35 | // both sides. |
| 36 | // |
| 37 | // Three shapes, because the app reads a session three ways: a local |
| 38 | // sign-in with no Home, a local sign-in with Home configured, and a Home |
| 39 | // sign-in (an opaque subject the app resolves through its link store). |
| 40 | |
| 41 | // nativeRig is one signed-in browser against one app. |
| 42 | type nativeRig struct { |
| 43 | f *homeRouterFixture |
| 44 | browser *http.Cookie |
| 45 | } |
| 46 | |
| 47 | // newLocalOnlyFixture is newHomeRouterFixture without Home: auth's own |
| 48 | // magic link is the only way in, as on an instance with no MEMORIA_HOME_*. |
| 49 | func newLocalOnlyFixture(t *testing.T) *homeRouterFixture { |
| 50 | t.Helper() |
| 51 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 52 | d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), logger) |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | t.Cleanup(func() { d.Close() }) |
| 57 | cipher, err := seal.New(bytes.Repeat([]byte{6}, 32)) |
| 58 | if err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | mux, a, err := App(d, homeTestOrigin, cipher, logger) |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | t.Cleanup(func() { a.store.ix.Close() }) |
| 66 | a.SetOwners([]string{"alice@example.test"}) |
| 67 | mail := &homeTestMail{} |
| 68 | auth, err := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: mail}, logger, a) |
| 69 | if err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | a.UseAuth(auth) |
| 73 | a.MountAuth(mux, homeTestOrigin) |
| 74 | return &homeRouterFixture{a, mux, nil, mail, map[string]*http.Cookie{}} |
| 75 | } |
| 76 | |
| 77 | func nativeRigs() map[string]func(*testing.T) *nativeRig { |
| 78 | session := func(t *testing.T, f *homeRouterFixture) *http.Cookie { |
| 79 | t.Helper() |
| 80 | for _, c := range f.cookies { |
| 81 | if strings.Contains(c.Name, "session") { |
| 82 | return c |
| 83 | } |
| 84 | } |
| 85 | t.Fatalf("no session cookie in %v", f.cookies) |
| 86 | return nil |
| 87 | } |
| 88 | return map[string]func(*testing.T) *nativeRig{ |
| 89 | "local, no Home": func(t *testing.T) *nativeRig { |
| 90 | f := newLocalOnlyFixture(t) |
| 91 | homeRedirect(t, f.do("POST", "/auth/begin", "address=alice%40example.test&force=1")) |
| 92 | link := regexp.MustCompile(`https://[^\s<>\"]+/auth/verify\?[^\s<>\"]+`).FindString(f.mail.body) |
| 93 | u, err := url.Parse(link) |
| 94 | if err != nil || link == "" { |
| 95 | t.Fatal("no captured verification link") |
| 96 | } |
| 97 | homeRedirect(t, f.openLink(t, u.RequestURI())) |
| 98 | return &nativeRig{f, session(t, f)} |
| 99 | }, |
| 100 | "local, Home configured": func(t *testing.T) *nativeRig { |
| 101 | f := newHomeRouterFixture(t) |
| 102 | f.local(t) |
| 103 | return &nativeRig{f, session(t, f)} |
| 104 | }, |
| 105 | "Home sign-in": func(t *testing.T) *nativeRig { |
| 106 | f := newHomeRouterFixture(t) |
| 107 | f.local(t) |
| 108 | if w := f.do("GET", "/account/home", ""); w.Code != 200 { |
| 109 | t.Fatalf("link page = %d", w.Code) |
| 110 | } |
| 111 | start := homeRedirect(t, f.do("POST", "/account/home", "")) |
| 112 | homeRedirect(t, f.exchange(t, start, "opaque-home-alice")) |
| 113 | homeRedirect(t, f.do("POST", "/account/home/confirm", "")) |
| 114 | f.do("POST", "/signout", "") |
| 115 | start = homeRedirect(t, f.do("GET", "/signin", "")) |
| 116 | homeRedirect(t, f.exchange(t, start, "opaque-home-alice")) |
| 117 | c := session(t, f) |
| 118 | var method string |
| 119 | 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 == "" { |
| 120 | t.Fatalf("the fixture's session is not a Home session: method %q, %v", method, err) |
| 121 | } |
| 122 | return &nativeRig{f, c} |
| 123 | }, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | func (n *nativeRig) post(t *testing.T, path, body string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 128 | t.Helper() |
| 129 | r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body)) |
| 130 | r.Header.Set("Content-Type", "application/json") |
| 131 | r.Header.Set("Origin", homeTestOrigin) |
| 132 | for _, c := range cookies { |
| 133 | r.AddCookie(c) |
| 134 | } |
| 135 | w := httptest.NewRecorder() |
| 136 | n.f.handler.ServeHTTP(w, r) |
| 137 | return w |
| 138 | } |
| 139 | |
| 140 | // request starts a native sign-in and returns its id and verifier. |
| 141 | func (n *nativeRig) request(t *testing.T) (id, verifier string) { |
| 142 | t.Helper() |
| 143 | b := make([]byte, 32) |
| 144 | if _, err := rand.Read(b); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | verifier = base64.RawURLEncoding.EncodeToString(b) |
| 148 | sum := sha256.Sum256([]byte(verifier)) |
| 149 | w := n.post(t, "/native/request", `{"challenge":"`+base64.RawURLEncoding.EncodeToString(sum[:])+`"}`) |
| 150 | var out struct{ ID string } |
| 151 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || out.ID == "" { |
| 152 | t.Fatalf("POST /native/request = %d %q", w.Code, w.Body.String()) |
| 153 | } |
| 154 | return out.ID, verifier |
| 155 | } |
| 156 | |
| 157 | // approve is the signed-in browser pressing "Sign in to Memoria app". |
| 158 | func (n *nativeRig) approve(t *testing.T, id string) *httptest.ResponseRecorder { |
| 159 | t.Helper() |
| 160 | return n.post(t, "/native/authorize?id="+id, "", n.browser) |
| 161 | } |
| 162 | |
| 163 | func (n *nativeRig) exchange(t *testing.T, id, verifier string) *httptest.ResponseRecorder { |
| 164 | t.Helper() |
| 165 | return n.post(t, "/native/exchange", `{"id":"`+id+`","verifier":"`+verifier+`"}`) |
| 166 | } |
| 167 | |
| 168 | // mint runs a whole approved exchange and returns the minted cookie. |
| 169 | func (n *nativeRig) mint(t *testing.T) *http.Cookie { |
| 170 | t.Helper() |
| 171 | id, verifier := n.request(t) |
| 172 | if w := n.approve(t, id); w.Code != 200 { |
| 173 | t.Fatalf("approval = %d", w.Code) |
| 174 | } |
| 175 | w := n.exchange(t, id, verifier) |
| 176 | var minted struct{ Name, Value string } |
| 177 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil { |
| 178 | t.Fatalf("exchange = %d %q", w.Code, w.Body.String()) |
| 179 | } |
| 180 | return &http.Cookie{Name: minted.Name, Value: minted.Value} |
| 181 | } |
| 182 | |
| 183 | // who is the native API's answer to one cookie, and the address the |
| 184 | // index page names for it: the status, and who the app thinks it is. |
| 185 | func (n *nativeRig) who(t *testing.T, c *http.Cookie) (int, bool) { |
| 186 | t.Helper() |
| 187 | r := httptest.NewRequest("GET", homeTestOrigin+"/api/native/session", nil) |
| 188 | r.AddCookie(c) |
| 189 | w := httptest.NewRecorder() |
| 190 | n.f.handler.ServeHTTP(w, r) |
| 191 | if w.Code != 200 { |
| 192 | return w.Code, false |
| 193 | } |
| 194 | r = httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| 195 | r.AddCookie(c) |
| 196 | page := httptest.NewRecorder() |
| 197 | n.f.handler.ServeHTTP(page, r) |
| 198 | return w.Code, page.Code == 200 && strings.Contains(page.Body.String(), "alice@example.test") |
| 199 | } |
| 200 | |
| 201 | func (n *nativeRig) setExpiry(t *testing.T, token string, at time.Time) { |
| 202 | t.Helper() |
| 203 | res := n.f.app.db.G.Exec(`UPDATE sessions SET expires_at = ? WHERE token_hash = ?`, at.UTC().Format(time.RFC3339), sessions.HashToken(token)) |
| 204 | if res.Error != nil || res.RowsAffected != 1 { |
| 205 | t.Fatalf("expire session: %v, %d rows", res.Error, res.RowsAffected) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | func TestNativeExchangeMintsASessionTheAppAccepts(t *testing.T) { |
| 210 | for name, build := range nativeRigs() { |
| 211 | t.Run(name, func(t *testing.T) { |
| 212 | n := build(t) |
| 213 | if code, alice := n.who(t, n.browser); code != 200 || !alice { |
| 214 | t.Fatalf("the browser's own session: GET /api/native/session = %d, names alice: %v", code, alice) |
| 215 | } |
| 216 | id, verifier := n.request(t) |
| 217 | if w := n.exchange(t, id, verifier); w.Code != http.StatusAccepted { |
| 218 | t.Fatalf("exchange before approval = %d, want 202", w.Code) |
| 219 | } |
| 220 | if w := n.approve(t, id); w.Code != 200 || !strings.Contains(w.Body.String(), "is signed in") { |
| 221 | t.Fatalf("approval = %d: %s", w.Code, w.Body.String()) |
| 222 | } |
| 223 | wrong := make([]byte, 32) |
| 224 | _, _ = rand.Read(wrong) |
| 225 | if w := n.exchange(t, id, base64.RawURLEncoding.EncodeToString(wrong)); w.Code != http.StatusNotFound { |
| 226 | t.Fatalf("exchange with the wrong verifier = %d, want 404", w.Code) |
| 227 | } |
| 228 | w := n.exchange(t, id, verifier) |
| 229 | var minted struct{ Name, Value string } |
| 230 | if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &minted) != nil { |
| 231 | t.Fatalf("exchange = %d %q", w.Code, w.Body.String()) |
| 232 | } |
| 233 | // The pre-move package names the cookie the app reads, and |
| 234 | // mints a new token rather than handing back the browser's. |
| 235 | if minted.Name != n.browser.Name { |
| 236 | t.Fatalf("exchange minted cookie %q; the app reads %q", minted.Name, n.browser.Name) |
| 237 | } |
| 238 | if minted.Value == "" || minted.Value == n.browser.Value { |
| 239 | t.Fatal("exchange did not mint a session of its own") |
| 240 | } |
| 241 | // And the app takes it as the same person. |
| 242 | code, alice := n.who(t, &http.Cookie{Name: minted.Name, Value: minted.Value}) |
| 243 | if code != 200 { |
| 244 | t.Fatalf("the app refuses the session native minted: GET /api/native/session = %d", code) |
| 245 | } |
| 246 | if !alice { |
| 247 | t.Fatal("the minted session is somebody else: the index does not name alice") |
| 248 | } |
| 249 | // Spent: the same id never exchanges twice. |
| 250 | if w := n.exchange(t, id, verifier); w.Code != http.StatusNotFound { |
| 251 | t.Fatalf("second exchange = %d, want 404", w.Code) |
| 252 | } |
| 253 | }) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | func TestNativeSessionExpiryHolds(t *testing.T) { |
| 258 | for name, build := range nativeRigs() { |
| 259 | t.Run(name, func(t *testing.T) { |
| 260 | n := build(t) |
| 261 | |
| 262 | // An expired browser session signs nothing in. (The approval |
| 263 | // page records whatever cookie it is shown; the exchange is |
| 264 | // where the session is authenticated, from scratch.) |
| 265 | n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute)) |
| 266 | id, verifier := n.request(t) |
| 267 | n.approve(t, id) |
| 268 | if w := n.exchange(t, id, verifier); w.Code == 200 { |
| 269 | t.Fatal("an expired browser session signed a native app in") |
| 270 | } |
| 271 | |
| 272 | // Approved while live, expired before the exchange: refused. |
| 273 | n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour)) |
| 274 | id, verifier = n.request(t) |
| 275 | n.approve(t, id) |
| 276 | n.setExpiry(t, n.browser.Value, time.Now().Add(-time.Minute)) |
| 277 | if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized { |
| 278 | t.Fatalf("exchange of an expired approval = %d, want 401", w.Code) |
| 279 | } |
| 280 | |
| 281 | // A minted session expires like any other. |
| 282 | n.setExpiry(t, n.browser.Value, time.Now().Add(time.Hour)) |
| 283 | native := n.mint(t) |
| 284 | if code, _ := n.who(t, native); code != 200 { |
| 285 | t.Fatalf("live minted session: GET /api/native/session = %d", code) |
| 286 | } |
| 287 | n.setExpiry(t, native.Value, time.Now().Add(-time.Minute)) |
| 288 | if code, _ := n.who(t, native); code == 200 { |
| 289 | t.Fatal("the app still accepts a minted session past its expiry") |
| 290 | } |
| 291 | }) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | func TestNativeSessionRevocationHolds(t *testing.T) { |
| 296 | for name, build := range nativeRigs() { |
| 297 | t.Run(name, func(t *testing.T) { |
| 298 | // Signing the browser out between approval and exchange |
| 299 | // refuses the exchange. |
| 300 | n := build(t) |
| 301 | id, verifier := n.request(t) |
| 302 | n.approve(t, id) |
| 303 | 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 { |
| 304 | t.Fatalf("revoke the browser's session: %v", res.Error) |
| 305 | } |
| 306 | if w := n.exchange(t, id, verifier); w.Code != http.StatusUnauthorized { |
| 307 | t.Fatalf("exchange after the browser signed out = %d, want 401", w.Code) |
| 308 | } |
| 309 | |
| 310 | // The app signing out a minted session (the app's own |
| 311 | // sessions package, deleting a row the pre-move package |
| 312 | // wrote) ends it, and leaves the browser's alone. |
| 313 | n = build(t) |
| 314 | native := n.mint(t) |
| 315 | r := httptest.NewRequest("POST", homeTestOrigin+"/signout", nil) |
| 316 | r.Header.Set("Origin", homeTestOrigin) |
| 317 | r.AddCookie(native) |
| 318 | w := httptest.NewRecorder() |
| 319 | n.f.handler.ServeHTTP(w, r) |
| 320 | if w.Code >= 400 { |
| 321 | t.Fatalf("POST /signout with the minted session = %d", w.Code) |
| 322 | } |
| 323 | if code, _ := n.who(t, native); code == 200 { |
| 324 | t.Fatal("a signed-out minted session still reaches the native API") |
| 325 | } |
| 326 | if code, _ := n.who(t, n.browser); code != 200 { |
| 327 | t.Fatalf("signing native out ended the browser's session too: GET /api/native/session = %d", code) |
| 328 | } |
| 329 | }) |
| 330 | } |
| 331 | } |
| 332 | |