| 1 | package webtest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/rand" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/home/connect" |
| 15 | "amadan.net/oficina/home/handoff" |
| 16 | "amadan.net/rastrillo/rastrillo/assertion" |
| 17 | "amadan.net/rastrillo/rastrillo/sessions" |
| 18 | ) |
| 19 | |
| 20 | // The native app's Oficina ID session (Home spec 2026-11-14-oficina-id-native.md |
| 21 | // §7): connect's NativeMethod, minted without a browser and handed to the |
| 22 | // app, which sends it as the session cookie with Origin set to Base's own. |
| 23 | |
| 24 | // sessionCookie is the name of Base's session cookie at homeOrigin. |
| 25 | const sessionCookie = "__Host-rastrillo_session" |
| 26 | |
| 27 | // storedSession writes a session row as rastrillo's store would have, |
| 28 | // created at, and returns a browser carrying its cookie. It stands in for a |
| 29 | // session minted some time ago. |
| 30 | func (a *testApp) storedSession(subject, method string, at time.Time) *testApp { |
| 31 | a.t.Helper() |
| 32 | token, hash, err := sessions.NewToken() |
| 33 | if err != nil { |
| 34 | a.t.Fatal(err) |
| 35 | } |
| 36 | if _, err := a.DB.Exec(`INSERT INTO sessions (token_hash, subject, method, auth_time, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`, |
| 37 | hash, subject, method, at.UTC().Format(time.RFC3339), at.UTC().Format(time.RFC3339), time.Now().Add(30*24*time.Hour).UTC().Format(time.RFC3339)); err != nil { |
| 38 | a.t.Fatal(err) |
| 39 | } |
| 40 | return a.withSession(token) |
| 41 | } |
| 42 | |
| 43 | // withSession is a fresh browser that holds only the session token, as the |
| 44 | // native app does: it sends the cookie itself. |
| 45 | func (a *testApp) withSession(token string) *testApp { |
| 46 | a.t.Helper() |
| 47 | b := a.newBrowser() |
| 48 | u, _ := url.Parse(homeOrigin + "/") |
| 49 | b.client.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: token, Path: "/", Secure: true, HttpOnly: true}}) |
| 50 | return b |
| 51 | } |
| 52 | |
| 53 | // nativeGet is a GET as the native app makes it: the cookie, Origin and |
| 54 | // Accept: application/json, and no Sec-Fetch-Site. |
| 55 | func (a *testApp) nativeGet(target string) Resp { |
| 56 | a.t.Helper() |
| 57 | req, _ := http.NewRequest(http.MethodGet, a.base+target, nil) |
| 58 | req.Header.Set("Origin", homeOrigin) |
| 59 | req.Header.Set("Accept", "application/json") |
| 60 | return a.do(req) |
| 61 | } |
| 62 | |
| 63 | // nativePost is a JSON POST as the native app makes it. |
| 64 | func (a *testApp) nativePost(target, body string) Resp { |
| 65 | a.t.Helper() |
| 66 | req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(body)) |
| 67 | req.Header.Set("Content-Type", "application/json") |
| 68 | req.Header.Set("Origin", homeOrigin) |
| 69 | req.Header.Set("Accept", "application/json") |
| 70 | return a.do(req) |
| 71 | } |
| 72 | |
| 73 | func TestNativeSessionIsAMember(t *testing.T) { |
| 74 | a := newHomeApp(t) |
| 75 | a.link(ownerAddress, "subject-owner") |
| 76 | b := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-time.Hour)) |
| 77 | if r := b.get("/"); r.Code != 200 { |
| 78 | t.Fatalf("native session, GET /: %d %q", r.Code, r.Location()) |
| 79 | } |
| 80 | if r := b.get("/settings"); r.Code != 200 || !strings.Contains(r.Body, ownerAddress) { |
| 81 | t.Fatalf("native session, GET /settings: %d", r.Code) |
| 82 | } |
| 83 | // A subject with no link names nobody. |
| 84 | if r := a.storedSession("subject-stranger", connect.NativeMethod, time.Now()).get("/"); r.Code != http.StatusForbidden { |
| 85 | t.Errorf("unlinked native session, GET /: %d", r.Code) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // Seven days after it was minted, however recently used, the native session |
| 90 | // opens nothing (connect.Expired): the app mints a new one long before. |
| 91 | func TestNativeSessionExpiresAfterSevenDays(t *testing.T) { |
| 92 | a := newHomeApp(t) |
| 93 | a.link(ownerAddress, "subject-owner") |
| 94 | if r := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime+time.Minute)).get("/"); r.Code != 200 { |
| 95 | t.Fatalf("a native session just short of seven days: %d", r.Code) |
| 96 | } |
| 97 | old := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime-time.Second)) |
| 98 | for _, p := range []string{"/", "/settings"} { |
| 99 | if r := old.get(p); r.Code == 200 { |
| 100 | t.Errorf("a native session past seven days, GET %s: %d", p, r.Code) |
| 101 | } |
| 102 | } |
| 103 | // A browser Home session of the same age is the store's to expire. |
| 104 | if r := a.storedSession("subject-owner", connect.HomeMethod, time.Now().Add(-connect.NativeLifetime-time.Hour)).get("/"); r.Code != 200 { |
| 105 | t.Errorf("a browser Oficina session of eight days: %d", r.Code) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // A passkey is filed under the session's subject; for every Home-derived |
| 110 | // session that is the Oficina account, so none may add one. |
| 111 | func TestOwnSignInOnlyRefusesNativeSessions(t *testing.T) { |
| 112 | a := newHomeApp(t) |
| 113 | a.link(ownerAddress, "subject-owner") |
| 114 | b := a.storedSession("subject-owner", connect.NativeMethod, time.Now()) |
| 115 | if r := b.nativePost("/passkey/register/begin", "{}"); r.Code != http.StatusForbidden { |
| 116 | t.Errorf("register from a native session: %d", r.Code) |
| 117 | } |
| 118 | // Settings offers no passkey to a native session, and lists the |
| 119 | // member's own by address. |
| 120 | if body := b.get("/settings").Body; strings.Contains(body, "data-passkey-add") { |
| 121 | t.Errorf("settings offers a passkey to a native session") |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // nativeAnswer is POST /native/oficina-id's JSON answer. |
| 126 | type nativeAnswer struct { |
| 127 | State string `json:"state"` |
| 128 | Name string `json:"name"` |
| 129 | Value string `json:"value"` |
| 130 | ExpiresAt int64 `json:"expires_at"` |
| 131 | } |
| 132 | |
| 133 | // nativeAssertion is what id.oficina gives the native app for Base: an |
| 134 | // assertion for subject whose nonce is derived from verifier's challenge. |
| 135 | func (a *testApp) nativeAssertion(subject, audience string) (token, verifier string) { |
| 136 | a.t.Helper() |
| 137 | raw := make([]byte, 32) |
| 138 | if _, err := rand.Read(raw); err != nil { |
| 139 | a.t.Fatal(err) |
| 140 | } |
| 141 | verifier = base64.RawURLEncoding.EncodeToString(raw) |
| 142 | challenge, _ := handoff.NativeChallenge(verifier) |
| 143 | nonce, _ := handoff.NativeNonce(challenge) |
| 144 | now := time.Now().Unix() |
| 145 | jti, err := assertion.RandomID() |
| 146 | if err != nil { |
| 147 | a.t.Fatal(err) |
| 148 | } |
| 149 | token, err = assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: audience, Subject: subject, |
| 150 | KeyID: homeKeyID, ID: jti, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - 60}) |
| 151 | if err != nil { |
| 152 | a.t.Fatal(err) |
| 153 | } |
| 154 | return token, verifier |
| 155 | } |
| 156 | |
| 157 | // nativeExchange posts what the native app posts: JSON, no Origin, no |
| 158 | // Sec-Fetch-Site, no cookies. |
| 159 | func (a *testApp) nativeExchange(subject string) (Resp, nativeAnswer) { |
| 160 | a.t.Helper() |
| 161 | token, verifier := a.nativeAssertion(subject, homeOrigin) |
| 162 | body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) |
| 163 | req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) |
| 164 | req.Header.Set("Content-Type", "application/json") |
| 165 | r := a.newBrowser().do(req) |
| 166 | if len(r.Header.Values("Set-Cookie")) != 0 { |
| 167 | a.t.Fatalf("the native exchange set a cookie: %q", r.Header.Values("Set-Cookie")) |
| 168 | } |
| 169 | var answer nativeAnswer |
| 170 | if err := json.Unmarshal([]byte(r.Body), &answer); err != nil { |
| 171 | a.t.Fatalf("exchange answer %d %q: %v", r.Code, r.Body, err) |
| 172 | } |
| 173 | return r, answer |
| 174 | } |
| 175 | |
| 176 | // nativeSignIn is a linked member's native app, signed in: a browser that |
| 177 | // holds only the minted session. |
| 178 | func (a *testApp) nativeSignIn(subject string) *testApp { |
| 179 | a.t.Helper() |
| 180 | r, answer := a.nativeExchange(subject) |
| 181 | if r.Code != 200 || answer.State != "ok" { |
| 182 | a.t.Fatalf("native exchange: %d %s", r.Code, r.Body) |
| 183 | } |
| 184 | return a.withSession(answer.Value) |
| 185 | } |
| 186 | |
| 187 | func TestNativeExchangeMintsASession(t *testing.T) { |
| 188 | a := newHomeApp(t) |
| 189 | a.link(ownerAddress, "subject-owner") |
| 190 | r, answer := a.nativeExchange("subject-owner") |
| 191 | if r.Code != 200 || answer.State != "ok" || answer.Name != sessionCookie || answer.Value == "" { |
| 192 | t.Fatalf("exchange: %d %s", r.Code, r.Body) |
| 193 | } |
| 194 | if want := time.Now().Add(connect.NativeLifetime).Unix(); answer.ExpiresAt < want-60 || answer.ExpiresAt > want+60 { |
| 195 | t.Errorf("expires_at %d, want about %d", answer.ExpiresAt, want) |
| 196 | } |
| 197 | if r.Header.Get("Cache-Control") != "no-store" { |
| 198 | t.Errorf("Cache-Control %q", r.Header.Get("Cache-Control")) |
| 199 | } |
| 200 | var method string |
| 201 | if err := a.DB.QueryRow(`SELECT method FROM sessions WHERE token_hash = ?`, sessions.HashToken(answer.Value)).Scan(&method); err != nil || method != connect.NativeMethod { |
| 202 | t.Fatalf("stored session method %q, %v", method, err) |
| 203 | } |
| 204 | if home := a.withSession(answer.Value).get("/"); home.Code != 200 { |
| 205 | t.Fatalf("the minted session, GET /: %d %q", home.Code, home.Location()) |
| 206 | } |
| 207 | if me := a.withSession(answer.Value).nativeGet("/api/v1/me"); me.Code != 200 || !strings.Contains(me.Body, ownerAddress) { |
| 208 | t.Fatalf("the minted session, GET /api/v1/me: %d %s", me.Code, me.Body) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | func TestNativeExchangeUnknownPerson(t *testing.T) { |
| 213 | a := newHomeApp(t) |
| 214 | a.link(ownerAddress, "subject-owner") |
| 215 | r, _ := a.nativeExchange("subject-stranger") |
| 216 | if r.Code != http.StatusForbidden || r.Body != `{"state":"unknown"}` { |
| 217 | t.Fatalf("unlinked subject: %d %s", r.Code, r.Body) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // The exchange is not a browser route: a request carrying a browser's |
| 222 | // Origin or Sec-Fetch-Site is refused by the exchange itself. |
| 223 | func TestNativeExchangeRefusesBrowsers(t *testing.T) { |
| 224 | a := newHomeApp(t) |
| 225 | a.link(ownerAddress, "subject-owner") |
| 226 | for _, h := range [][2]string{{"Origin", homeOrigin}, {"Origin", "https://evil.test"}, {"Sec-Fetch-Site", "same-origin"}} { |
| 227 | token, verifier := a.nativeAssertion("subject-owner", homeOrigin) |
| 228 | body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) |
| 229 | req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) |
| 230 | req.Header.Set("Content-Type", "application/json") |
| 231 | req.Header.Set(h[0], h[1]) |
| 232 | if r := a.newBrowser().do(req); r.Code != http.StatusBadRequest || r.Body != `{"state":"invalid"}` { |
| 233 | t.Errorf("with %s: %s: %d %s", h[0], h[1], r.Code, r.Body) |
| 234 | } |
| 235 | } |
| 236 | // An assertion for another audience is not accepted. |
| 237 | token, verifier := a.nativeAssertion("subject-owner", "https://docs.acme.test") |
| 238 | body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) |
| 239 | req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) |
| 240 | req.Header.Set("Content-Type", "application/json") |
| 241 | if r := a.newBrowser().do(req); r.Code != http.StatusUnauthorized { |
| 242 | t.Errorf("another audience: %d %s", r.Code, r.Body) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | // POST /signout is the native app's sign-out: it ends the session it |
| 247 | // carries, whatever its method, and nothing else. |
| 248 | func TestSignoutEndsTheNativeSession(t *testing.T) { |
| 249 | a := newHomeApp(t) |
| 250 | a.link(ownerAddress, "subject-owner") |
| 251 | app := a.nativeSignIn("subject-owner") |
| 252 | other := a.nativeSignIn("subject-owner") |
| 253 | if r := app.nativePost("/signout", "{}"); r.Code != http.StatusNoContent { |
| 254 | t.Fatalf("native signout: %d %q", r.Code, r.Body) |
| 255 | } |
| 256 | if r := app.get("/"); r.Code == 200 { |
| 257 | t.Fatalf("the signed-out native session still opens Home") |
| 258 | } |
| 259 | if r := other.get("/"); r.Code != 200 { |
| 260 | t.Errorf("another device's session ended too: %d", r.Code) |
| 261 | } |
| 262 | // From another site it is refused, as every POST is. |
| 263 | if r := other.postFrom("https://evil.test", "/signout", nil); r.Code != http.StatusForbidden { |
| 264 | t.Errorf("cross-site signout: %d", r.Code) |
| 265 | } |
| 266 | // A browser form lands on the signed-out page. |
| 267 | a.signedInOwner() |
| 268 | if r := a.post("/signout", nil); r.Code != http.StatusSeeOther || r.Location() != "/signed-out" { |
| 269 | t.Errorf("browser signout: %d %q", r.Code, r.Location()) |
| 270 | } |
| 271 | if r := a.get("/"); r.Code == 200 { |
| 272 | t.Errorf("the browser session survived /signout") |
| 273 | } |
| 274 | } |
| 275 | |