oficina / base Public

Mount the native Oficina ID exchange and POST /signout

With Oficina ID on, Base mounts connect's NativeExchange at
POST /native/oficina-id and mints a NativeMethod session for a linked
member through sessions.Mint (no cookie; the value is in the answer, with
expires_at seven days on). Admit, Unlinked and HomeOnly stay unset, so an
unlinked subject is connect's 403 unknown, as on the web.

POST /signout is the native kit's sign-out: it ends the session the
request carries and nothing else, answering 204 to JSON and a 303 to
/signed-out to a form. It sits inside the CSRF check; the kit sends
Base's Origin. /native/web/end is not mounted (Home slice D).

make ci: 16 packages ran, 0 failed; test step 7.8s of 60s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3a8e6309a8ca2165de0af5cb013f70ec58e654c0 parent c9c963f
3 files changed, +189 −0
  • internal/web/app.go +28 −0
  • internal/web/oficina.go +7 −0
  • internal/webtest/native_test.go +154 −0
diff --git a/internal/web/app.go b/internal/web/app.go
index d1f5439..e621f39 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -10,6 +10,7 @@ import (
"html/template"
"io/fs"
"log/slog"
+ "mime"
"net/http"
"strings"
"time"
@@ -176,6 +177,11 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Get("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
r.Post("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
r.Post("/auth/signout", o.routes.Signout)
+ // The native app's Oficina ID exchange. connect's Middleware lets
+ // this one path past the CSRF check: it refuses anything a browser
+ // sends, and reads and sets no cookies.
+ r.Post(connect.NativeExchangePath, o.bridge.NativeExchange)
+ r.Post("/signout", a.signout)
} else {
r.Get("/signin", a.signin)
r.Post("/auth/begin", a.auth.Begin)
@@ -317,6 +323,28 @@ func ownSignInOnly(next http.Handler) http.Handler {
})
}
+// signout is POST /signout, the native app's sign-out: it ends the session
+// the request carries, whatever its method, and nothing else (Oficina's own
+// sign-out is the app's to do). The app hears 204; a browser form goes to
+// the signed-out page. It is mounted with Oficina ID on, inside the CSRF
+// check like every POST, which the app passes by sending Base's Origin.
+func (a *app) signout(w http.ResponseWriter, r *http.Request) {
+ a.sess.SignOut(w, r)
+ w.Header().Set("Cache-Control", "no-store")
+ if wantsJSON(r) || isJSONBody(r) {
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ http.Redirect(w, r, "/signed-out", http.StatusSeeOther)
+}
+
+// isJSONBody reports whether the request's body is JSON, as the native kit
+// sends it.
+func isJSONBody(r *http.Request) bool {
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ return err == nil && media == "application/json"
+}
+
// signedInAt is when the request's session signed in: the credential's own
// verification time when the sign-in method records one (Keymail, and
// Oficina ID, which records when the person last proved who they are at
diff --git a/internal/web/oficina.go b/internal/web/oficina.go
index 97d77f9..c602275 100644
--- a/internal/web/oficina.go
+++ b/internal/web/oficina.go
@@ -72,6 +72,13 @@ func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
Render: a.oficinaPage,
MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error {
return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
+ },
+ // The native app's session (connect.NativeExchange, method
+ // NativeMethod): the same store and cookie name, minted without a
+ // cookie and handed back in the answer. The store records when it
+ // was made (At), which is what ends it after seven days.
+ MintNativeSession: func(_ context.Context, s connect.Session) (string, error) {
+ return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
}}
b, err := connect.New(cfg)
if err != nil {
diff --git a/internal/webtest/native_test.go b/internal/webtest/native_test.go
index 42d3440..cb3d474 100644
--- a/internal/webtest/native_test.go
+++ b/internal/webtest/native_test.go
@@ -1,6 +1,10 @@
package webtest
import (
+ "bytes"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
"net/http"
"net/url"
"strings"
@@ -8,6 +12,8 @@ import (
"time"
"amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/assertion"
"amadan.net/rastrillo/rastrillo/sessions"
)
@@ -105,3 +111,151 @@ func TestOwnSignInOnlyRefusesNativeSessions(t *testing.T) {
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())
+ }
+}
+
+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")
+ }
+}