package webtest import ( "bytes" "crypto/rand" "encoding/base64" "encoding/json" "net/http" "net/url" "strings" "testing" "time" "amadan.net/oficina/home/connect" "amadan.net/oficina/home/handoff" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/rastrillo/rastrillo/sessions" ) // The native app's Oficina ID session (Home spec 2026-11-14-oficina-id-native.md // ยง7): connect's NativeMethod, minted without a browser and handed to the // app, which sends it as the session cookie with Origin set to Base's own. // sessionCookie is the name of Base's session cookie at homeOrigin. const sessionCookie = "__Host-rastrillo_session" // storedSession writes a session row as rastrillo's store would have, // created at, and returns a browser carrying its cookie. It stands in for a // session minted some time ago. func (a *testApp) storedSession(subject, method string, at time.Time) *testApp { a.t.Helper() token, hash, err := sessions.NewToken() if err != nil { a.t.Fatal(err) } if _, err := a.DB.Exec(`INSERT INTO sessions (token_hash, subject, method, auth_time, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`, 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 { a.t.Fatal(err) } return a.withSession(token) } // withSession is a fresh browser that holds only the session token, as the // native app does: it sends the cookie itself. func (a *testApp) withSession(token string) *testApp { a.t.Helper() b := a.newBrowser() u, _ := url.Parse(homeOrigin + "/") b.client.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: token, Path: "/", Secure: true, HttpOnly: true}}) return b } // nativeGet is a GET as the native app makes it: the cookie, Origin and // Accept: application/json, and no Sec-Fetch-Site. func (a *testApp) nativeGet(target string) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodGet, a.base+target, nil) req.Header.Set("Origin", homeOrigin) req.Header.Set("Accept", "application/json") return a.do(req) } // nativePost is a JSON POST as the native app makes it. func (a *testApp) nativePost(target, body string) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Origin", homeOrigin) req.Header.Set("Accept", "application/json") return a.do(req) } func TestNativeSessionIsAMember(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") b := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-time.Hour)) if r := b.get("/"); r.Code != 200 { t.Fatalf("native session, GET /: %d %q", r.Code, r.Location()) } if r := b.get("/settings"); r.Code != 200 || !strings.Contains(r.Body, ownerAddress) { t.Fatalf("native session, GET /settings: %d", r.Code) } // A subject with no link names nobody. if r := a.storedSession("subject-stranger", connect.NativeMethod, time.Now()).get("/"); r.Code != http.StatusForbidden { t.Errorf("unlinked native session, GET /: %d", r.Code) } } // Seven days after it was minted, however recently used, the native session // opens nothing (connect.Expired): the app mints a new one long before. func TestNativeSessionExpiresAfterSevenDays(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") if r := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime+time.Minute)).get("/"); r.Code != 200 { t.Fatalf("a native session just short of seven days: %d", r.Code) } old := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime-time.Second)) for _, p := range []string{"/", "/settings"} { if r := old.get(p); r.Code == 200 { t.Errorf("a native session past seven days, GET %s: %d", p, r.Code) } } // A browser Home session of the same age is the store's to expire. if r := a.storedSession("subject-owner", connect.HomeMethod, time.Now().Add(-connect.NativeLifetime-time.Hour)).get("/"); r.Code != 200 { t.Errorf("a browser Oficina session of eight days: %d", r.Code) } } // A passkey is filed under the session's subject; for every Home-derived // session that is the Oficina account, so none may add one. func TestOwnSignInOnlyRefusesNativeSessions(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") b := a.storedSession("subject-owner", connect.NativeMethod, time.Now()) if r := b.nativePost("/passkey/register/begin", "{}"); r.Code != http.StatusForbidden { t.Errorf("register from a native session: %d", r.Code) } // Settings offers no passkey to a native session, and lists the // member's own by address. if body := b.get("/settings").Body; strings.Contains(body, "data-passkey-add") { t.Errorf("settings offers a passkey to a native session") } } // nativeAnswer is POST /native/oficina-id's JSON answer. type nativeAnswer struct { State string `json:"state"` Name string `json:"name"` Value string `json:"value"` ExpiresAt int64 `json:"expires_at"` } // nativeAssertion is what id.oficina gives the native app for Base: an // assertion for subject whose nonce is derived from verifier's challenge. func (a *testApp) nativeAssertion(subject, audience string) (token, verifier string) { a.t.Helper() raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { a.t.Fatal(err) } verifier = base64.RawURLEncoding.EncodeToString(raw) challenge, _ := handoff.NativeChallenge(verifier) nonce, _ := handoff.NativeNonce(challenge) now := time.Now().Unix() jti, err := assertion.RandomID() if err != nil { a.t.Fatal(err) } token, err = assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: audience, Subject: subject, KeyID: homeKeyID, ID: jti, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - 60}) if err != nil { a.t.Fatal(err) } return token, verifier } // nativeExchange posts what the native app posts: JSON, no Origin, no // Sec-Fetch-Site, no cookies. func (a *testApp) nativeExchange(subject string) (Resp, nativeAnswer) { a.t.Helper() token, verifier := a.nativeAssertion(subject, homeOrigin) body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") r := a.newBrowser().do(req) if len(r.Header.Values("Set-Cookie")) != 0 { a.t.Fatalf("the native exchange set a cookie: %q", r.Header.Values("Set-Cookie")) } var answer nativeAnswer if err := json.Unmarshal([]byte(r.Body), &answer); err != nil { a.t.Fatalf("exchange answer %d %q: %v", r.Code, r.Body, err) } return r, answer } // nativeSignIn is a linked member's native app, signed in: a browser that // holds only the minted session. func (a *testApp) nativeSignIn(subject string) *testApp { a.t.Helper() r, answer := a.nativeExchange(subject) if r.Code != 200 || answer.State != "ok" { a.t.Fatalf("native exchange: %d %s", r.Code, r.Body) } return a.withSession(answer.Value) } func TestNativeExchangeMintsASession(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") r, answer := a.nativeExchange("subject-owner") if r.Code != 200 || answer.State != "ok" || answer.Name != sessionCookie || answer.Value == "" { t.Fatalf("exchange: %d %s", r.Code, r.Body) } if want := time.Now().Add(connect.NativeLifetime).Unix(); answer.ExpiresAt < want-60 || answer.ExpiresAt > want+60 { t.Errorf("expires_at %d, want about %d", answer.ExpiresAt, want) } if r.Header.Get("Cache-Control") != "no-store" { t.Errorf("Cache-Control %q", r.Header.Get("Cache-Control")) } var method string if err := a.DB.QueryRow(`SELECT method FROM sessions WHERE token_hash = ?`, sessions.HashToken(answer.Value)).Scan(&method); err != nil || method != connect.NativeMethod { t.Fatalf("stored session method %q, %v", method, err) } if home := a.withSession(answer.Value).get("/"); home.Code != 200 { t.Fatalf("the minted session, GET /: %d %q", home.Code, home.Location()) } if me := a.withSession(answer.Value).nativeGet("/api/v1/me"); me.Code != 200 || !strings.Contains(me.Body, ownerAddress) { t.Fatalf("the minted session, GET /api/v1/me: %d %s", me.Code, me.Body) } } func TestNativeExchangeUnknownPerson(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") r, _ := a.nativeExchange("subject-stranger") if r.Code != http.StatusForbidden || r.Body != `{"state":"unknown"}` { t.Fatalf("unlinked subject: %d %s", r.Code, r.Body) } } // The exchange is not a browser route: a request carrying a browser's // Origin or Sec-Fetch-Site is refused by the exchange itself. func TestNativeExchangeRefusesBrowsers(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") for _, h := range [][2]string{{"Origin", homeOrigin}, {"Origin", "https://evil.test"}, {"Sec-Fetch-Site", "same-origin"}} { token, verifier := a.nativeAssertion("subject-owner", homeOrigin) body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set(h[0], h[1]) if r := a.newBrowser().do(req); r.Code != http.StatusBadRequest || r.Body != `{"state":"invalid"}` { t.Errorf("with %s: %s: %d %s", h[0], h[1], r.Code, r.Body) } } // An assertion for another audience is not accepted. token, verifier := a.nativeAssertion("subject-owner", "https://docs.acme.test") body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier}) req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") if r := a.newBrowser().do(req); r.Code != http.StatusUnauthorized { t.Errorf("another audience: %d %s", r.Code, r.Body) } } // POST /signout is the native app's sign-out: it ends the session it // carries, whatever its method, and nothing else. func TestSignoutEndsTheNativeSession(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") app := a.nativeSignIn("subject-owner") other := a.nativeSignIn("subject-owner") if r := app.nativePost("/signout", "{}"); r.Code != http.StatusNoContent { t.Fatalf("native signout: %d %q", r.Code, r.Body) } if r := app.get("/"); r.Code == 200 { t.Fatalf("the signed-out native session still opens Home") } if r := other.get("/"); r.Code != 200 { t.Errorf("another device's session ended too: %d", r.Code) } // From another site it is refused, as every POST is. if r := other.postFrom("https://evil.test", "/signout", nil); r.Code != http.StatusForbidden { t.Errorf("cross-site signout: %d", r.Code) } // A browser form lands on the signed-out page. a.signedInOwner() if r := a.post("/signout", nil); r.Code != http.StatusSeeOther || r.Location() != "/signed-out" { t.Errorf("browser signout: %d %q", r.Code, r.Location()) } if r := a.get("/"); r.Code == 200 { t.Errorf("the browser session survived /signout") } }