oficina / home Public

connect: NativeExchange, the native path to a team session (spec §7)

Human

Prompt

Implement the consumer (connect) half of slice A: NativeExchange with states 200/403 unknown/409 choose/503 (spec 2026-11-14 §7, §13).

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

POST /native/oficina-id {assertion, verifier, target?, choice?}: verify with pinned keys and recompute the native nonce from the verifier; read link then Home-only person; with neither, Admit (403 unknown byte-identical, 503, or 409 choose) before any jti; allocate only on choice:"new" with re-resolve; reserve the jti in its own committed transaction, re-resolve, recheck a Home-only person's standing, and mint a home-assertion-native session through the new Config.MintNativeSession. JSON-only, no cookies, refuses Origin/Sec-Fetch-Site; Routes.Middleware lets the path past CSRF. Tests cover the spec §13 exchange gates, including a single-connection pool probe proving no hook or mint runs with the writer held. README documents the wire.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 354c7e94835de245c484ae27492375d1ae0b4e70 parent a1dfdc3
7 files changed, +806 −25
  • connect/README.md +87 −19
  • connect/api.go +8 −0
  • connect/bridge.go +6 −2
  • connect/native.go +222 −0
  • connect/native_test.go +468 −0
  • connect/routes.go +4 −1
  • connect/unlinked_test.go +11 −3

CI cancelled — superseded by a newer push — run details

diff --git a/connect/README.md b/connect/README.md
index da8f01e..6297ca9 100644
--- a/connect/README.md
+++ b/connect/README.md
@@ -89,36 +89,104 @@ request-provided destinations. Keep the existing local plugin callback route.
## Home-only people (team mode)
-`Config.Unlinked` and `Config.HomeOnly` are optional and set together; `New`
-refuses one without the other. Without them nothing above changes. With them, a
-subject with no account link here can still sign in, as an addressless
-person the app creates, which is what team mode needs for a roster member
-who has never had a local account (`home/teammode`,
-`implementation/teammode-package.md`).
+`Config.Admit`, `Config.Unlinked` and `Config.HomeOnly` are optional and set
+together; `New` refuses any one without the others. Without them nothing above
+changes. With them, a roster member with no account link here can still sign
+in, as an addressless person the app creates, which is what team mode needs
+for a member who has never had a local account (`home/teammode`,
+`implementation/teammode-package.md`). Home spec
+`2026-11-14-oficina-id-native.md` §8 governs what follows. No hook is ever
+called with a transaction open: Docs has a single writer connection, and a
+hook waiting on it from inside connect's own transaction would wedge it.
- `HomeOnly(ctx, issuer, subject)` reads, never creates, the person a subject
- was given. Connect asks it after the account link in ordinary resolution: `Resolve`, `ResolveSession` and completion, so the
+ was given. Connect asks it after the account link in ordinary resolution:
+ `Resolve`, `ResolveSession`, completion and the native exchange, so the
same-person rules hold for Home-only people too. It returns `ErrNoPerson`
for none. The person has a positive ID and an empty `Label`; connect
refuses one with a label, because there is no address to give.
It may be asked about any subject linkstore refused, including one that is
not a person ref, so it must not assume the subject's shape.
-- `Unlinked(ctx, issuer, subject)` may create that person. Connect asks it
- only in ordinary completion (never the link flow), only after the
- assertion is verified and consumed, only when the subject has neither a
- link nor a Home-only person, and only when no app session is present. In
- team mode it creates a person only on a current roster Member decision
- whose lease is valid (`teammode.Runtime.AdmitUnlinked`). `ErrNoPerson` is
- answered exactly as an unlinked subject without the hook ("unknown", 403,
- with the resume-linking marker); any other error is a 503.
-- A subject arriving over a live session is never allocated: an unknown one
- is refused as "unknown", and a known one that is not the signed-in person
- is refused as "failed", leaving that session in place. Every cookie shape
- check stays connect's.
+- `Admit(ctx, issuer, subject)` is the roster decision, and it comes first:
+ asked only for a verified subject with neither a link nor a Home-only person,
+ and only when no app session is present, it allocates nothing. `nil` is a
+ Member (`teammode.Runtime.AdmitUnlinked`), `ErrNoPerson` a non-member, any
+ other error "cannot decide now". It must never ask whether the team has
+ local or email accounts.
+- **A non-member** gets today's "unknown" answer byte for byte (403, with the
+ resume-linking marker), the same as an instance without the hooks. **An
+ unavailable roster** is a 503. **A Member** gets a sealed, single-use,
+ ten-minute choice proof bound to the browser by `__Host-oficina-home-choice`
+ (linkstore migration 0003) and a 303 to `ChoosePath`,
+ `/account/home/choose`. Nothing is created yet, so a guest's local account
+ never blocks a new member's first sign-in.
+- Mount `Bridge.ChoosePage` at `GET` and `Bridge.ChoosePost` at `POST`
+ `/account/home/choose`, outside the session guards and inside the app's
+ CSRF middleware. Render state `"choose"` with your own template from
+ `ChoiceFor(r)` (the form's action and token) and the `choose_*` strings:
+ title "Welcome to the team", and two buttons that POST `choice=connect` or
+ `choice=new` with the token. The token is an HMAC of the proof cookie and
+ the POST requires this exact `Origin`.
+ - "Connect my existing account" consumes the proof and goes to
+ `/signin/local` with the resume-linking marker, then slice 1's linking.
+ - "I'm new here — continue with Oficina ID" refuses while any app session
+ is present; otherwise it consumes the proof in its own short
+ transaction, re-checks the link and `Admit` with none open, allocates
+ through `Unlinked`, resolves again and mints. The person lands on `/`.
+- `Unlinked(ctx, issuer, subject)` may create that person, and is asked only
+ after a Member's explicit "I'm new here" (the choose POST, or a native
+ `choice:"new"`). It opens its own writer transaction and re-checks before
+ it creates. Whatever it answers, connect resolves the subject again: a
+ person found then (a racing choice made one) is used; otherwise
+ `ErrNoPerson` is "unknown" and any other error a 503.
+- A subject arriving over a live session is never allocated and no proof is
+ issued: an unknown one is refused as "unknown", and a known one that is not
+ the signed-in person is refused as "failed", leaving that session in
+ place. Every cookie shape check stays connect's.
`Bridge.Linked` knows nothing of Home-only people, so an app should not offer
"Connect your Oficina account" to one: there is no local account to connect.
+## Native apps: NativeExchange
+
+A native app holding an Oficina ID grant asks Home for an assertion for this
+origin (`POST https://id.oficina.works/native/v1/assert {aud, challenge}`)
+and trades it here, with no browser, for a session. Set
+`Config.MintNativeSession` (store the session, return its cookie value, set
+no cookie) and mount `Bridge.NativeExchange` at `POST /native/oficina-id`
+(`NativeExchangePath`). `Routes.Middleware` lets that one path past the CSRF
+check: the exchange itself refuses any request carrying `Origin` or
+`Sec-Fetch-Site`, any query, and anything but `application/json`.
+
+The request is `{"assertion", "verifier", "target"?, "choice"?}`. The
+verifier is 32 random bytes; Home sets the assertion's nonce from its
+challenge, and the exchange recomputes it (`handoff.NativeChallenge`,
+`handoff.NativeNonce`; the derivation and a test vector are in
+`handoff/native.go`). Answers are JSON `{"state": …}`, `no-store`, with no
+cookies:
+
+| Status | state | Meaning |
+|---|---|---|
+| 200 | `ok` | `name` (the session cookie), `value`, `expires_at` (unix, 7 days), `target` echoed if sent |
+| 400 | `invalid` | malformed request |
+| 401 | `failed` | assertion not accepted (signature, audience, expiry, verifier, already used): get a fresh one |
+| 403 | `unknown` | no person here and none may be made; identical for every such subject and instance |
+| 409 | `choose` | a roster Member with no person here: offer both routes; send `choice:"new"` only from "I'm new here" |
+| 503 | `unavailable` | try again shortly |
+
+"Connect my existing account" in the app opens `<origin>/account/home` in the
+default browser. The exchange writes the assertion's `jti` only once it is
+about to mint, in its own committed transaction (`handoff.Store.Reserve`); a
+`jti` burned with no session (a crash, or the final recheck refusing) costs
+the app one fresh assertion.
+
+The session's method is `NativeMethod`, `home-assertion-native`. Every check
+on a Home sign-in uses `IsHomeDerived(method)`, true for `HomeMethod`,
+`NativeMethod` and `NativeWebMethod`. `Expired` refuses a native or
+native-web session more than seven days after its `At`, absolute; an app that
+resolves sessions itself rather than through `ResolveSession` must refuse
+what it refuses. The app re-mints after a day and on any 401.
+
## Moving existing links onto connect
An app that already links Home identities in its own table (Docs'
diff --git a/connect/api.go b/connect/api.go
index fc601d2..3a40903 100644
--- a/connect/api.go
+++ b/connect/api.go
@@ -124,6 +124,14 @@ type Config struct {
// A HomeOnly person has a positive ID and an empty Label: there is no
// address to give, and connect refuses a Home-only person with one.
HomeOnly func(ctx context.Context, issuer, subject string) (Person, error)
+
+ // MintNativeSession is optional and turns NativeExchange on. It stores
+ // a session for s (Method NativeMethod, the assertion's AuthTime) and
+ // returns its cookie value, which the app's native client then sends
+ // as SessionCookie. It must set no cookie, and it is called with no
+ // transaction open. connect refuses the session NativeLifetime after
+ // its At (Expired), so the store must record At at creation.
+ MintNativeSession func(ctx context.Context, s Session) (string, error)
}
// ErrNoPerson is what a Config.Unlinked or Config.HomeOnly hook returns for
diff --git a/connect/bridge.go b/connect/bridge.go
index 8f54642..19f815e 100644
--- a/connect/bridge.go
+++ b/connect/bridge.go
@@ -26,6 +26,8 @@ type Bridge struct {
namespace string
keyHash [32]byte
links *linkstore.Store
+ exchange *handoff.Store
+ mintNative func(context.Context, Session) (string, error)
ordinary, fresh *handoff.Consumer
now func() time.Time
returnPath func(*http.Request) string
@@ -72,7 +74,7 @@ func New(c Config) (*Bridge, error) {
if now == nil {
now = time.Now
}
- b := &Bridge{namespace: c.Namespace, keyHash: sha256.Sum256(c.DEK), origin: c.Origin, issuer: c.Issuer, sessionCookie: c.SessionCookie, links: linker, now: now, returnPath: c.ReturnPath, readSession: c.ReadSession, mintSession: c.MintHomeSession, localPerson: c.LookupLocalSession, render: c.Render, unlinked: c.Unlinked, homeOnly: c.HomeOnly, admit: c.Admit, formKey: formKey(c.DEK, c.Origin)}
+ b := &Bridge{namespace: c.Namespace, keyHash: sha256.Sum256(c.DEK), origin: c.Origin, issuer: c.Issuer, sessionCookie: c.SessionCookie, links: linker, now: now, returnPath: c.ReturnPath, readSession: c.ReadSession, mintSession: c.MintHomeSession, localPerson: c.LookupLocalSession, render: c.Render, unlinked: c.Unlinked, homeOnly: c.HomeOnly, admit: c.Admit, formKey: formKey(c.DEK, c.Origin), exchange: exchange, mintNative: c.MintNativeSession}
cfg := handoff.ConsumerConfig{Store: exchange, ConsumerID: c.ConsumerID, Complete: b.complete, Fail: b.fail, Now: func() time.Time { return b.now() }, CurrentSubject: func(r *http.Request) string {
result, _ := r.Context().Value(homeFinishKey{}).(*homeFinishResult)
if result != nil && result.session != nil && IsHomeDerived(result.session.Method) {
@@ -301,9 +303,11 @@ func (b *Bridge) localBinding(r *http.Request) (linkstore.Local, Person, error)
token, _, _ := homeCookie(r, b.sessionCookie)
return linkstore.Local{PersonID: person.ID, SessionToken: token, AuthTime: at}, person, nil
}
+func (b *Bridge) host() string { return strings.TrimPrefix(b.origin, "https://") }
+
func (b *Bridge) guard(w http.ResponseWriter, r *http.Request, method, path string) bool {
w.Header().Set("Cache-Control", "no-store")
- if r.Host != strings.TrimPrefix(b.origin, "https://") || r.URL.Path != path {
+ if r.Host != b.host() || r.URL.Path != path {
b.fail(w, r, http.StatusNotFound)
return false
}
diff --git a/connect/native.go b/connect/native.go
new file mode 100644
index 0000000..b097e3d
--- /dev/null
+++ b/connect/native.go
@@ -0,0 +1,222 @@
+package connect
+
+import (
+ "crypto/subtle"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
+ json "github.com/go-json-experiment/json"
+)
+
+// NativeExchangePath is where a native app trades a Home assertion for a
+// session on this instance (Home spec 2026-11-14-oficina-id-native.md §7,
+// step 2). Mount Bridge.NativeExchange at POST, outside the app's CSRF
+// middleware (Routes.Middleware lets it through): it refuses any request a
+// browser could make, and reads and sets no cookies.
+const NativeExchangePath = "/native/oficina-id"
+
+// The answer states. Every answer is a JSON object with "state", served
+// no-store with no cookies:
+//
+// 200 ok {"state":"ok","name":<cookie name>,"value":<session>,"expires_at":<unix>}
+// (and "target" echoed when the request carried one)
+// 400 invalid the request is malformed; do not retry it as is
+// 401 failed the assertion was not accepted (bad, expired, wrong
+// audience or verifier, or already used): fetch a fresh
+// assertion and try once more
+// 403 unknown no person here, and none may be made; identical for
+// every such subject, and on an instance without the hooks
+// 409 choose a roster Member with no person here: offer "Connect my
+// existing account" and "I'm new here", and send
+// choice:"new" only from the second
+// 503 unavailable try again shortly
+const (
+ nativeOK = "ok"
+ nativeInvalid = "invalid"
+ nativeFailed = "failed"
+ nativeUnknown = "unknown"
+ nativeChoose = "choose"
+ nativeUnavailable = "unavailable"
+)
+
+var nativeStatus = map[string]int{
+ nativeInvalid: http.StatusBadRequest, nativeFailed: http.StatusUnauthorized,
+ nativeUnknown: http.StatusForbidden, nativeChoose: http.StatusConflict,
+ nativeUnavailable: http.StatusServiceUnavailable,
+}
+
+type nativeRequest struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ Target string `json:"target,omitempty"`
+ Choice string `json:"choice,omitempty"`
+}
+
+type nativeSession struct {
+ State string `json:"state"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ ExpiresAt int64 `json:"expires_at"`
+ Target string `json:"target,omitempty"`
+}
+
+func nativeAnswer(w http.ResponseWriter, state string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(nativeStatus[state])
+ w.Write([]byte(`{"state":"` + state + `"}`))
+}
+
+// NativeExchange is POST /native/oficina-id, {assertion, verifier,
+// target?, choice?}. It runs the spec's five steps in order, and holds no
+// transaction across any hook or the mint:
+//
+// 1. Verify the assertion (pinned keys, exact issuer and audience) and
+// recompute the native nonce from the verifier.
+// 2. Resolve the link, then the Home-only person, writing nothing.
+// 3. With neither, ask Admit: a non-member is "unknown", an unavailable
+// roster 503, a Member without choice:"new" 409 "choose". All three
+// return before any jti is written.
+// 4. A Member with choice:"new" is allocated through Unlinked, then
+// resolved again; nobody found is "unknown" (or 503).
+// 5. Reserve the jti in its own committed transaction, then resolve
+// again, recheck a Home-only person's admission, and mint a
+// NativeMethod session through MintNativeSession.
+//
+// A reserved jti that ends in no session costs the client one fresh
+// assertion; a jti is never reserved twice. choice is ignored for a subject
+// who already has a person here. Without MintNativeSession it is 404.
+func (b *Bridge) NativeExchange(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if b.mintNative == nil || r.Host != b.host() || r.URL.Path != NativeExchangePath {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNotFound)
+ w.Write([]byte(`{"state":"not_found"}`))
+ return
+ }
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ w.Write([]byte(`{"state":"method_not_allowed"}`))
+ return
+ }
+ // No browser makes this request: refuse anything carrying a browser's
+ // provenance, which also means no form or fetch from any page can.
+ if r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 {
+ nativeAnswer(w, nativeInvalid)
+ return
+ }
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || media != "application/json" {
+ nativeAnswer(w, nativeInvalid)
+ return
+ }
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024))
+ if err != nil {
+ nativeAnswer(w, nativeInvalid)
+ return
+ }
+ var in nativeRequest
+ if json.Unmarshal(body, &in, json.RejectUnknownMembers(true)) != nil || in.Assertion == "" || len(in.Assertion) > 8192 || (in.Choice != "" && in.Choice != "new") || (in.Target != "" && !handoff.SafePath(in.Target)) {
+ nativeAnswer(w, nativeInvalid)
+ return
+ }
+ challenge, ok := handoff.NativeChallenge(in.Verifier)
+ if !ok {
+ nativeAnswer(w, nativeInvalid)
+ return
+ }
+
+ // 1. Verify, and accept only the native nonce for this verifier.
+ claims, err := b.exchange.Verify(in.Assertion, b.now())
+ if err != nil {
+ nativeAnswer(w, nativeFailed)
+ return
+ }
+ nonce, _ := handoff.NativeNonce(challenge)
+ if subtle.ConstantTimeCompare([]byte(nonce), []byte(claims.Nonce)) != 1 {
+ nativeAnswer(w, nativeFailed)
+ return
+ }
+ ctx := r.Context()
+ subject := claims.Subject
+
+ // 2. Read the link, then the Home-only person.
+ _, err = b.Resolve(ctx, subject)
+ if errors.Is(err, linkstore.ErrRefused) {
+ // 3. Decide: the roster, with nothing allocated and no jti kept.
+ if b.admit == nil {
+ nativeAnswer(w, nativeUnknown)
+ return
+ }
+ switch decision := b.admit(ctx, b.issuer, subject); {
+ case errors.Is(decision, ErrNoPerson):
+ nativeAnswer(w, nativeUnknown)
+ return
+ case decision != nil:
+ nativeAnswer(w, nativeUnavailable)
+ return
+ case in.Choice != "new":
+ nativeAnswer(w, nativeChoose)
+ return
+ }
+ // 4. Allocate, on the Member's explicit choice.
+ _, err = b.allocate(ctx, subject)
+ }
+ switch {
+ case errors.Is(err, linkstore.ErrRefused):
+ nativeAnswer(w, nativeUnknown)
+ return
+ case err != nil:
+ nativeAnswer(w, nativeUnavailable)
+ return
+ }
+
+ // 5. Reserve, then resolve again, recheck and mint.
+ if _, err := b.exchange.Reserve(ctx, in.Assertion, b.now()); err != nil {
+ if errors.Is(err, handoff.ErrRefused) {
+ nativeAnswer(w, nativeFailed)
+ } else {
+ nativeAnswer(w, nativeUnavailable)
+ }
+ return
+ }
+ person, err := b.Resolve(ctx, subject)
+ if err == nil && person.Label == "" && b.admit != nil {
+ // A Home-only person's standing is the roster's alone; a linked
+ // account's admission was rechecked by LookupPerson in Resolve.
+ switch decision := b.admit(ctx, b.issuer, subject); {
+ case errors.Is(decision, ErrNoPerson):
+ err = linkstore.ErrRefused
+ case decision != nil:
+ err = linkstore.ErrStorage
+ }
+ }
+ switch {
+ case errors.Is(err, linkstore.ErrRefused):
+ nativeAnswer(w, nativeUnknown)
+ return
+ case err != nil:
+ nativeAnswer(w, nativeUnavailable)
+ return
+ }
+ minted := b.now()
+ value, err := b.mintNative(ctx, Session{Subject: subject, Method: NativeMethod, AuthTime: time.Unix(claims.AuthTime, 0)})
+ if err != nil || value == "" {
+ nativeAnswer(w, nativeUnavailable)
+ return
+ }
+ out, err := json.Marshal(nativeSession{State: nativeOK, Name: b.sessionCookie, Value: value, ExpiresAt: minted.Add(NativeLifetime).Unix(), Target: in.Target})
+ if err != nil {
+ nativeAnswer(w, nativeUnavailable)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ w.Write(out)
+}
diff --git a/connect/native_test.go b/connect/native_test.go
new file mode 100644
index 0000000..cc0a2aa
--- /dev/null
+++ b/connect/native_test.go
@@ -0,0 +1,468 @@
+package connect
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ json "github.com/go-json-experiment/json"
+)
+
+// newNativeFixture is a bridge with NativeExchange on, with the team hooks
+// when team is set (h is nil otherwise).
+func newNativeFixture(t *testing.T, team bool) (*bridgeFixture, *homeOnlyHooks) {
+ t.Helper()
+ var h *homeOnlyHooks
+ if team {
+ h = &homeOnlyHooks{}
+ }
+ f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
+ if h != nil {
+ h.install(f, c)
+ }
+ c.MintNativeSession = func(_ context.Context, s Session) (string, error) { return f.sessions.Mint(s) }
+ })
+ if h != nil {
+ f.b.rememberUnknown = func(http.ResponseWriter) { h.remember++ }
+ }
+ return f, h
+}
+
+func newVerifier(t *testing.T) string {
+ t.Helper()
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ t.Fatal(err)
+ }
+ return base64.RawURLEncoding.EncodeToString(raw)
+}
+
+// nativeAssertion is what Home's assert returns for verifier's challenge.
+func (f *bridgeFixture) nativeAssertion(t *testing.T, subject, verifier string) string {
+ t.Helper()
+ challenge, ok := handoff.NativeChallenge(verifier)
+ if !ok {
+ t.Fatal("verifier")
+ }
+ nonce, _ := handoff.NativeNonce(challenge)
+ return f.signed(t, subject, nonce, bridgeOrigin)
+}
+
+func (f *bridgeFixture) signed(t *testing.T, subject, nonce, audience string) string {
+ t.Helper()
+ now := time.Now().Unix()
+ id, err := assertion.RandomID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: audience, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now - 600})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return token
+}
+
+func nativeRequestFor(t *testing.T, body any) *http.Request {
+ t.Helper()
+ raw, ok := body.(string)
+ if !ok {
+ b, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw = string(b)
+ }
+ r := httptest.NewRequest(http.MethodPost, bridgeOrigin+NativeExchangePath, strings.NewReader(raw))
+ r.Header.Set("Content-Type", "application/json")
+ return r
+}
+
+func (f *bridgeFixture) exchange(t *testing.T, r *http.Request) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ f.b.NativeExchange(w, r)
+ if len(w.Result().Cookies()) != 0 {
+ t.Fatal("the native exchange set a cookie")
+ }
+ if w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/json" {
+ t.Fatalf("headers %v", w.Header())
+ }
+ return w
+}
+
+func (f *bridgeFixture) post(t *testing.T, subject string, extra map[string]string) *httptest.ResponseRecorder {
+ t.Helper()
+ verifier := newVerifier(t)
+ body := map[string]string{"assertion": f.nativeAssertion(t, subject, verifier), "verifier": verifier}
+ for k, v := range extra {
+ body[k] = v
+ }
+ return f.exchange(t, nativeRequestFor(t, body))
+}
+
+func (f *bridgeFixture) replayRows(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := f.db.QueryRow("SELECT COUNT(*) FROM oficina_handoff_replay").Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func wantState(t *testing.T, w *httptest.ResponseRecorder, code int, state string) {
+ t.Helper()
+ if w.Code != code || w.Body.String() != `{"state":"`+state+`"}` {
+ t.Fatalf("got %d %s, want %d %s", w.Code, w.Body.String(), code, state)
+ }
+}
+
+// signedSession reads the session an ok answer carries.
+func (f *bridgeFixture) signedSession(t *testing.T, w *httptest.ResponseRecorder) (Session, *http.Cookie) {
+ t.Helper()
+ if w.Code != 200 {
+ t.Fatalf("exchange=%d %s", w.Code, w.Body.String())
+ }
+ var out struct {
+ State string `json:"state"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ Target string `json:"target"`
+ ExpiresAt int64 `json:"expires_at"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.State != "ok" || out.Name != f.b.sessionCookie || out.Value == "" {
+ t.Fatalf("answer %s: %v", w.Body.String(), err)
+ }
+ if d := time.Until(time.Unix(out.ExpiresAt, 0)); d < NativeLifetime-time.Minute || d > NativeLifetime {
+ t.Fatalf("expires_at in %v", d)
+ }
+ cookie := &http.Cookie{Name: out.Name, Value: out.Value}
+ s, ok := f.sessions.From(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}))
+ if !ok {
+ t.Fatal("no session behind the answer")
+ }
+ return s, cookie
+}
+
+func TestNativeExchangeSignsInALinkedPerson(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
+ f.link(t, local, "pr_linked")
+ // choice is ignored for a subject who already has a person here.
+ w := f.post(t, "pr_linked", map[string]string{"choice": "new"})
+ s, cookie := f.signedSession(t, w)
+ if s.Method != NativeMethod || s.Subject != "pr_linked" || time.Since(s.AuthTime) < 9*time.Minute {
+ t.Fatalf("session %+v", s)
+ }
+ p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}))
+ if err != nil || p.Label != "one@example.com" {
+ t.Fatal(p, err)
+ }
+ if h.admitted != 0 || h.unlinked != 0 || f.replayRows(t) != 2 {
+ t.Fatalf("admitted=%d unlinked=%d replay=%d", h.admitted, h.unlinked, f.replayRows(t))
+ }
+}
+
+func TestNativeExchangeWithoutHooksSignsInLinkedPeople(t *testing.T) {
+ f, _ := newNativeFixture(t, false)
+ local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
+ f.link(t, local, "pr_linked")
+ f.signedSession(t, f.post(t, "pr_linked", nil))
+ wantState(t, f.post(t, "pr_stranger", nil), 403, "unknown")
+}
+
+// A Member with no person here: 409 with no choice, and nothing allocated
+// or burned; choice:"new" allocates once.
+func TestNativeMemberChooses(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ wantState(t, f.post(t, "pr_member", nil), 409, "choose")
+ if h.count(t) != 0 || h.unlinked != 0 || f.replayRows(t) != 0 {
+ t.Fatalf("409 allocated %d, unlinked %d, replay %d", h.count(t), h.unlinked, f.replayRows(t))
+ }
+ s, _ := f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"}))
+ if s.Method != NativeMethod || h.count(t) != 1 || h.unlinked != 1 || f.replayRows(t) != 1 {
+ t.Fatalf("new: %+v people=%d unlinked=%d", s, h.count(t), h.unlinked)
+ }
+ // Next time the person is found: no choice needed, nothing allocated.
+ f.signedSession(t, f.post(t, "pr_member", nil))
+ if h.count(t) != 1 || h.unlinked != 1 {
+ t.Fatal("allocated again")
+ }
+}
+
+// Non-members, with or without choice, and instances without the hooks all
+// get the same 403: status, body and headers.
+func TestNativeUnknownIsByteIdentical(t *testing.T) {
+ team, h := newNativeFixture(t, true)
+ h.admission = ErrNoPerson
+ plain, _ := newNativeFixture(t, false)
+ answers := []*httptest.ResponseRecorder{
+ team.post(t, "pr_stranger", nil),
+ team.post(t, "pr_other", map[string]string{"choice": "new"}),
+ plain.post(t, "pr_stranger", nil),
+ plain.post(t, "pr_other", map[string]string{"choice": "new"}),
+ }
+ for i, w := range answers {
+ wantState(t, w, 403, "unknown")
+ if shape(w.Header()) != shape(answers[0].Header()) {
+ t.Fatalf("answer %d headers differ:\n%s\n%s", i, shape(w.Header()), shape(answers[0].Header()))
+ }
+ }
+ if h.count(t) != 0 || h.unlinked != 0 || team.replayRows(t) != 0 || plain.replayRows(t) != 0 {
+ t.Fatal("a non-member allocated or burned something")
+ }
+}
+
+func TestNativeRosterUnavailableIs503(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ h.admission = errors.New("roster unknown")
+ wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), 503, "unavailable")
+ if h.count(t) != 0 || f.replayRows(t) != 0 {
+ t.Fatal("undecided allocated or burned")
+ }
+}
+
+// Unlinked refusing after the roster said Member: re-resolve, then 403 or
+// 503, with no jti kept.
+func TestNativeAllocationRefusedAfterMember(t *testing.T) {
+ for _, c := range []struct {
+ decision error
+ code int
+ state string
+ }{{ErrNoPerson, 403, "unknown"}, {errors.New("disk"), 503, "unavailable"}} {
+ f, h := newNativeFixture(t, true)
+ h.decision = c.decision
+ wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), c.code, c.state)
+ if f.replayRows(t) != 0 || h.unlinked != 1 {
+ t.Fatalf("%v: replay=%d unlinked=%d", c.decision, f.replayRows(t), h.unlinked)
+ }
+ }
+}
+
+// The admission recheck after the reservation: a Home-only person the
+// roster no longer lists gets the unknown answer.
+func TestNativeRechecksAHomeOnlyPersonsStanding(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"}))
+ h.admission = ErrNoPerson
+ wantState(t, f.post(t, "pr_member", nil), 403, "unknown")
+ h.admission = errors.New("roster unknown")
+ wantState(t, f.post(t, "pr_member", nil), 503, "unavailable")
+}
+
+func TestNativeExchangeRefusesTheWrongAssertion(t *testing.T) {
+ f, _ := newNativeFixture(t, true)
+ local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute))
+ f.link(t, local, "pr_linked")
+ before := f.replayRows(t)
+ verifier := newVerifier(t)
+ good := f.nativeAssertion(t, "pr_linked", verifier)
+ webNonce, _ := assertion.RandomID()
+ for name, body := range map[string]map[string]string{
+ "another verifier": {"assertion": good, "verifier": newVerifier(t)},
+ "a browser nonce": {"assertion": f.signed(t, "pr_linked", webNonce, bridgeOrigin), "verifier": verifier},
+ "another audience": {"assertion": f.nativeAssertionFor(t, "pr_linked", verifier, "https://red.docs.oficina.works"), "verifier": verifier},
+ "a corrupted token": {"assertion": good[:len(good)-2] + "AA", "verifier": verifier},
+ "a stranger's token": {"assertion": strings.Repeat("x", 200), "verifier": verifier},
+ } {
+ t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed") })
+ }
+ if f.replayRows(t) != before {
+ t.Fatal("a refused assertion burned a jti")
+ }
+ ok := map[string]string{"assertion": good, "verifier": verifier}
+ f.signedSession(t, f.exchange(t, nativeRequestFor(t, ok)))
+ wantState(t, f.exchange(t, nativeRequestFor(t, ok)), 401, "failed")
+}
+
+func (f *bridgeFixture) nativeAssertionFor(t *testing.T, subject, verifier, audience string) string {
+ t.Helper()
+ challenge, _ := handoff.NativeChallenge(verifier)
+ nonce, _ := handoff.NativeNonce(challenge)
+ return f.signed(t, subject, nonce, audience)
+}
+
+func TestNativeExchangeRefusesBrowsersAndMalformedRequests(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ verifier := newVerifier(t)
+ token := f.nativeAssertion(t, "pr_member", verifier)
+ good := `{"assertion":"` + token + `","verifier":"` + verifier + `"}`
+ for name, adjust := range map[string]func(*http.Request){
+ "Origin": func(r *http.Request) { r.Header.Set("Origin", bridgeOrigin) },
+ "Sec-Fetch-Site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") },
+ "form": func(r *http.Request) { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") },
+ "text": func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") },
+ "query": func(r *http.Request) { r.URL.RawQuery = "x=1" },
+ } {
+ r := nativeRequestFor(t, good)
+ adjust(r)
+ t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, r), 400, "invalid") })
+ }
+ for name, body := range map[string]string{
+ "unknown field": `{"assertion":"` + token + `","verifier":"` + verifier + `","extra":1}`,
+ "duplicate field": `{"assertion":"` + token + `","assertion":"` + token + `","verifier":"` + verifier + `"}`,
+ "trailing value": good + `{}`,
+ "bad verifier": `{"assertion":"` + token + `","verifier":"short"}`,
+ "bad choice": `{"assertion":"` + token + `","verifier":"` + verifier + `","choice":"old"}`,
+ "foreign target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"//evil.example/"}`,
+ "auth target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"/auth/start"}`,
+ "no assertion": `{"verifier":"` + verifier + `"}`,
+ "huge": `{"assertion":"` + strings.Repeat("a", 13*1024) + `","verifier":"` + verifier + `"}`,
+ } {
+ t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 400, "invalid") })
+ }
+ get := httptest.NewRecorder()
+ f.b.NativeExchange(get, httptest.NewRequest(http.MethodGet, bridgeOrigin+NativeExchangePath, nil))
+ if get.Code != 405 || get.Header().Get("Allow") != "POST" {
+ t.Fatalf("GET=%d", get.Code)
+ }
+ if h.admitted != 0 || f.replayRows(t) != 0 {
+ t.Fatal("a refused request reached the roster or burned a jti")
+ }
+}
+
+func TestNativeExchangeEchoesAValidTarget(t *testing.T) {
+ f, _ := newNativeFixture(t, true)
+ w := f.post(t, "pr_member", map[string]string{"choice": "new", "target": "/d/abc?view=1"})
+ f.signedSession(t, w)
+ if !bytes.Contains(w.Body.Bytes(), []byte(`"target":"/d/abc?view=1"`)) {
+ t.Fatal(w.Body.String())
+ }
+}
+
+func TestNativeExchangeIsOffWithoutAMint(t *testing.T) {
+ f, _ := newHomeOnlyFixture(t)
+ w := httptest.NewRecorder()
+ f.b.NativeExchange(w, nativeRequestFor(t, `{}`))
+ if w.Code != 404 {
+ t.Fatalf("exchange without MintNativeSession=%d", w.Code)
+ }
+}
+
+// A jti burned with no session (the mint failed after the reservation) is
+// not usable again; the client's fresh assertion is.
+func TestNativeBurnedJTIIsRetriedWithAFreshAssertion(t *testing.T) {
+ failing := true
+ h := &homeOnlyHooks{}
+ f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
+ h.install(f, c)
+ c.MintNativeSession = func(_ context.Context, s Session) (string, error) {
+ if failing {
+ return "", errors.New("disk")
+ }
+ return f.sessions.Mint(s)
+ }
+ })
+ verifier := newVerifier(t)
+ body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"}
+ wantState(t, f.exchange(t, nativeRequestFor(t, body)), 503, "unavailable")
+ failing = false
+ wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed")
+ f.signedSession(t, f.post(t, "pr_member", nil))
+ if h.count(t) != 1 {
+ t.Fatal("the retry allocated again")
+ }
+}
+
+// Two exchanges choosing "new" for one subject at once make one person.
+func TestNativeConcurrentChoicesMakeOnePerson(t *testing.T) {
+ f, h := newNativeFixture(t, true)
+ var mu sync.Mutex
+ inner := f.b.mintNative
+ f.b.mintNative = func(ctx context.Context, s Session) (string, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ return inner(ctx, s)
+ }
+ h.db.SetMaxOpenConns(4)
+ codes := make(chan int, 4)
+ var wg sync.WaitGroup
+ for range 4 {
+ verifier := newVerifier(t)
+ body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"}
+ r := nativeRequestFor(t, body)
+ wg.Go(func() {
+ w := httptest.NewRecorder()
+ f.b.NativeExchange(w, r)
+ codes <- w.Code
+ })
+ }
+ wg.Wait()
+ close(codes)
+ for c := range codes {
+ if c != 200 {
+ t.Fatalf("a concurrent choice answered %d", c)
+ }
+ }
+ if h.count(t) != 1 {
+ t.Fatalf("%d people", h.count(t))
+ }
+}
+
+// No hook and no mint is ever called with connect holding the writer. On a
+// single-connection pool (Docs' writer), each hook needs the connection; a
+// transaction held across it would make the hook wait, and it fails the
+// test after a second instead of wedging the pool.
+func TestNoHookRunsWithTheWriterHeld(t *testing.T) {
+ var mu sync.Mutex
+ var held []string
+ var probe func(string)
+ h := &homeOnlyHooks{}
+ f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) {
+ h.install(f, c)
+ f.db.SetMaxOpenConns(1)
+ probe = func(name string) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if _, err := f.db.ExecContext(ctx, "UPDATE home_link_clock SET high_water = high_water WHERE id = 1"); err != nil {
+ mu.Lock()
+ held = append(held, name)
+ mu.Unlock()
+ }
+ }
+ admit, unlinked, homeOnly, mint := c.Admit, c.Unlinked, c.HomeOnly, c.MintHomeSession
+ c.Admit = func(ctx context.Context, i, s string) error { probe("Admit"); return admit(ctx, i, s) }
+ c.Unlinked = func(ctx context.Context, i, s string) (Person, error) { probe("Unlinked"); return unlinked(ctx, i, s) }
+ c.HomeOnly = func(ctx context.Context, i, s string) (Person, error) { probe("HomeOnly"); return homeOnly(ctx, i, s) }
+ c.MintHomeSession = func(w http.ResponseWriter, r *http.Request, s Session) error {
+ probe("MintHomeSession")
+ return mint(w, r, s)
+ }
+ c.MintNativeSession = func(_ context.Context, s Session) (string, error) {
+ probe("MintNativeSession")
+ return f.sessions.Mint(s)
+ }
+ })
+ // The probe does notice a held writer.
+ tx, err := f.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ probe("self-check")
+ tx.Rollback()
+ if len(held) != 1 {
+ t.Fatal("the probe cannot see a held writer")
+ }
+ held = nil
+ // The browser path: finish, the choose page, "I'm new here".
+ f.signInNew(t, "pr_browser")
+ // The native path: 409, then choice "new", then a known person.
+ wantState(t, f.post(t, "pr_native", nil), 409, "choose")
+ f.signedSession(t, f.post(t, "pr_native", map[string]string{"choice": "new"}))
+ f.signedSession(t, f.post(t, "pr_native", nil))
+ if h.admitted == 0 || h.unlinked != 2 || h.homeOnly == 0 {
+ t.Fatalf("hooks not exercised: admit=%d unlinked=%d homeOnly=%d", h.admitted, h.unlinked, h.homeOnly)
+ }
+ if len(held) != 0 {
+ t.Fatalf("called with the writer held: %v", held)
+ }
+}
diff --git a/connect/routes.go b/connect/routes.go
index be81f15..24feb5a 100644
--- a/connect/routes.go
+++ b/connect/routes.go
@@ -73,7 +73,10 @@ func (h *Routes) Middleware(next http.Handler) http.Handler {
http.NotFound(w, r)
return
}
- if r.Method == http.MethodPost && r.URL.Path == handoff.CallbackPath {
+ // The assertion callback verifies its browser-bound assertion, and
+ // the native exchange refuses anything a browser sends; neither
+ // can pass a same-origin check, and neither needs one.
+ if r.Method == http.MethodPost && (r.URL.Path == handoff.CallbackPath || r.URL.Path == NativeExchangePath) {
next.ServeHTTP(w, r)
return
}
diff --git a/connect/unlinked_test.go b/connect/unlinked_test.go
index d2e301f..6e13403 100644
--- a/connect/unlinked_test.go
+++ b/connect/unlinked_test.go
@@ -28,6 +28,14 @@ type homeOnlyHooks struct {
unlinked int
homeOnly int
remember int
+ // mu guards the counters when a test races requests.
+ mu sync.Mutex
+}
+
+func (h *homeOnlyHooks) tally(n *int) {
+ h.mu.Lock()
+ *n++
+ h.mu.Unlock()
}
func (h *homeOnlyHooks) install(f *bridgeFixture, c *Config) {
@@ -36,7 +44,7 @@ func (h *homeOnlyHooks) install(f *bridgeFixture, c *Config) {
panic(err)
}
c.HomeOnly = func(ctx context.Context, issuer, subject string) (Person, error) {
- h.homeOnly++
+ h.tally(&h.homeOnly)
if h.lookupErr != nil {
return Person{}, h.lookupErr
}
@@ -49,11 +57,11 @@ func (h *homeOnlyHooks) install(f *bridgeFixture, c *Config) {
return p, err
}
c.Admit = func(ctx context.Context, issuer, subject string) error {
- h.admitted++
+ h.tally(&h.admitted)
return h.admission
}
c.Unlinked = func(ctx context.Context, issuer, subject string) (Person, error) {
- h.unlinked++
+ h.tally(&h.unlinked)
if h.decision != nil {
return Person{}, h.decision
}