Merge remote-tracking branch 'origin/main' into feat/oficina-id-native-a
21 files changed,
+2,097
−121
connect/README.md+87 −19connect/api.go+80 −16connect/bridge.go+42 −13connect/choose.go+210 −0connect/derived_test.go+77 −0connect/go.mod+1 −1connect/go.sum+4 −0connect/linkstore/choice.go+169 −0connect/linkstore/choice_test.go+101 −0connect/linkstore/migrations/0003_choice_proofs.sql+6 −0connect/linkstore/store.go+4 −2connect/linkstore/store_test.go+1 −1connect/native.go+227 −0connect/native_test.go+471 −0connect/resolve_on_test.go+1 −3connect/routes.go+18 −11connect/routes_test.go+7 −2connect/unlinked_test.go+368 −53connect/view.go+6 −0handoff/native.go+116 −0handoff/native_test.go+101 −0
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 ad33166..8dbd217 100644 |
| --- a/connect/api.go |
| +++ b/connect/api.go |
| @@ -14,6 +14,46 @@ import ( |
| const HomeMethod = "home-assertion" |
| +// NativeMethod is a session minted by NativeExchange for a native app, from |
| +// an assertion Home made for a device grant (Home spec |
| +// 2026-11-14-oficina-id-native.md §7). NativeWebMethod is the browser |
| +// session "Open on the web" mints (§12, slice D); connect does not mint it |
| +// yet, but resolves and ages it like any Home-derived session. |
| +const ( |
| + NativeMethod = "home-assertion-native" |
| + NativeWebMethod = "home-native-web" |
| +) |
| + |
| +// NativeLifetime is how long after its creation (Session.At) connect accepts |
| +// a NativeMethod or NativeWebMethod session: absolute, never sliding (Paul, |
| +// 2026-11-14). The app re-mints after a day and on any 401; this bounds what |
| +// an offline device keeps after its grant is revoked. |
| +const NativeLifetime = 7 * 24 * time.Hour |
| + |
| +// IsHomeDerived reports whether a session method names a person by their |
| +// Home subject: a browser sign-in through Home, a native exchange, or a |
| +// native-to-web handoff. Every check that used to compare a method with |
| +// HomeMethod asks this instead, so the three are one kind of session. |
| +func IsHomeDerived(method string) bool { |
| + switch method { |
| + case HomeMethod, NativeMethod, NativeWebMethod: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// Expired reports whether connect refuses a session by its age: a native or |
| +// native-web session more than NativeLifetime after its At, or one with no |
| +// At at all (fail closed). Browser and local sessions keep the session |
| +// store's own expiry. Apps that resolve sessions themselves, rather than |
| +// through ResolveSession, must refuse what this refuses. |
| +func Expired(s Session, now time.Time) bool { |
| + if s.Method != NativeMethod && s.Method != NativeWebMethod { |
| + return false |
| + } |
| + return s.At.IsZero() || s.At.After(now.Add(time.Minute)) || now.Sub(s.At) > NativeLifetime |
| +} |
| + |
| // Session times must come from the verified stored session, never request or last-seen time. |
| // AuthTime is the method verification time; At is immutable session creation time. |
| type Session struct { |
| @@ -44,23 +84,37 @@ type Config struct { |
| ReturnPath func(*http.Request) string |
| Now func() time.Time |
| - // Unlinked and HomeOnly are optional and set together, or not at all; |
| - // New refuses one without the other. With both nil, connect behaves |
| - // exactly as it always has: an ordinary sign-in whose subject has no |
| - // account link here is refused with the "unknown" page and the |
| - // resume-linking marker. They exist for team mode (home/teammode), |
| - // where a roster member who has never had a local account must be able |
| - // to enter on their Home identity alone, as an addressless person. |
| + // Admit, Unlinked and HomeOnly are optional and set together, or not |
| + // at all; New refuses any one without the others. With all three nil, |
| + // connect behaves exactly as it always has: an ordinary sign-in whose |
| + // subject has no account link here is refused with the "unknown" page |
| + // and the resume-linking marker. They exist for team mode |
| + // (home/teammode), where a roster member who has never had a local |
| + // account must be able to enter on their Home identity alone, as an |
| + // addressless person. No hook is ever called with a transaction open. |
| // |
| - // Unlinked is asked only during ordinary completion (never the link |
| - // flow), only after the assertion has been verified and consumed, only |
| - // for a subject with neither an account link nor a HomeOnly person, and |
| - // only when no app session is present. It may create a person, and must |
| - // do so only on a current decision that the subject may enter (in team |
| - // mode: a roster Member decision whose lease is valid). It returns |
| - // ErrNoPerson for a subject that may not enter, which connect answers |
| - // exactly as it answers an unlinked subject without the hook; any |
| - // other error is "cannot decide now", a 503. |
| + // Admit is the roster decision, and it comes first (Home spec |
| + // 2026-11-14-oficina-id-native.md §8): asked only for a verified |
| + // subject with neither an account link nor a HomeOnly person, it |
| + // allocates nothing. nil means a roster Member (in team mode, a Member |
| + // decision whose lease is valid: teammode.Runtime.AdmitUnlinked); |
| + // ErrNoPerson means a non-member, answered exactly as an unlinked |
| + // subject on an instance without the hooks; any other error is "cannot |
| + // decide now", a 503. A Member is not allocated: they are asked whether |
| + // they already have an account here (the choose page, or 409 "choose" |
| + // natively), so a guest's local account never blocks a new member. |
| + // It must never ask whether the team has local or email accounts. |
| + Admit func(ctx context.Context, issuer, subject string) error |
| + // Unlinked may create the Home-only person for a subject. Connect asks |
| + // it only after a Member chose "I'm new here" (the choose POST, or a |
| + // native exchange with choice "new"), never in the link flow, never |
| + // with an app session present, and only after re-checking Admit and |
| + // that the subject still has no person. It must re-check before it |
| + // creates, open its own writer transaction, and create only on a |
| + // current decision that the subject may enter. ErrNoPerson or any |
| + // other error makes connect resolve the subject again: a person found |
| + // then (a racing choice made one) is used; otherwise ErrNoPerson is |
| + // "unknown" and any other error a 503. |
| Unlinked func(ctx context.Context, issuer, subject string) (Person, error) |
| // HomeOnly reads, never creates, the person Unlinked gave a subject; |
| // ErrNoPerson when there is none. Connect asks it after the account |
| @@ -70,6 +124,16 @@ 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, and its |
| + // own lifetime must be at least NativeLifetime: the answer promises the |
| + // app expires_at = now + NativeLifetime. |
| + 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 e35e5f5..c0f5a2b 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 |
| @@ -34,6 +36,9 @@ type Bridge struct { |
| localPerson func(context.Context, Session) (Person, error) |
| render func(http.ResponseWriter, *http.Request, string, string, int) |
| unlinked, homeOnly func(context.Context, string, string) (Person, error) |
| + admit func(context.Context, string, string) error |
| + // formKey binds the choose page's form token to its proof cookie. |
| + formKey []byte |
| // rememberUnknown is set by NewRoutes: an assertion with no link here |
| // leaves the sealed navigation marker that resumes linking after the |
| // person signs in locally. |
| @@ -50,7 +55,7 @@ type homeFinishResult struct { |
| // Both subsystem schemas must be migrated before construction. The consumers |
| // share one replay store; choosing a different Finish cannot weaken freshness. |
| func New(c Config) (*Bridge, error) { |
| - if c.DB == nil || c.ReadSession == nil || c.MintHomeSession == nil || c.LookupLocalSession == nil || c.LookupPerson == nil || c.Render == nil || !validSessionCookie(c.SessionCookie) || (c.Unlinked == nil) != (c.HomeOnly == nil) { |
| + if c.DB == nil || c.ReadSession == nil || c.MintHomeSession == nil || c.LookupLocalSession == nil || c.LookupPerson == nil || c.Render == nil || !validSessionCookie(c.SessionCookie) || (c.Unlinked == nil) != (c.HomeOnly == nil) || (c.Admit == nil) != (c.HomeOnly == nil) { |
| return nil, errHomeBridge |
| } |
| sealer, err := seal.New(c.DEK, c.Namespace) |
| @@ -69,10 +74,10 @@ 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} |
| + 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 && result.session.Method == HomeMethod { |
| + if result != nil && result.session != nil && IsHomeDerived(result.session.Method) && !Expired(*result.session, b.now()) { |
| return result.session.Subject |
| } |
| return "" |
| @@ -181,6 +186,13 @@ func (b *Bridge) fail(w http.ResponseWriter, r *http.Request, status int) { |
| if result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult); ok && result.state != "" { |
| state, status = result.state, result.status |
| } |
| + if state == "choose" { |
| + // A Member with no link: the proof cookie is set; the page asks. |
| + // The return path stays with the exchange, so after a choice the |
| + // person lands on "/". |
| + http.Redirect(w, r, ChoosePath, http.StatusSeeOther) |
| + return |
| + } |
| b.render(w, r, state, "", status) |
| } |
| func rejectHome(r *http.Request, state string, status int) error { |
| @@ -216,14 +228,26 @@ func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims asserti |
| if claims.Issuer == b.issuer { |
| arriving, err = b.Resolve(r.Context(), claims.Subject) |
| } |
| - if errors.Is(err, linkstore.ErrRefused) && b.unlinked != nil && result.session == nil && claims.Issuer == b.issuer { |
| - // Nobody is signed in here and the subject has no person: the one |
| - // place a person may be created from a Home subject alone. With a |
| - // session present the arrival is refused below as unknown, before |
| - // anything is allocated, whoever that session belongs to. |
| - // ErrStorage ("cannot decide now") falls through to errHomeBridge, |
| - // which the exchange answers 503. |
| - arriving, err = homeOnlyPerson(b.unlinked(r.Context(), claims.Issuer, claims.Subject)) |
| + if errors.Is(err, linkstore.ErrRefused) && b.admit != nil && result.session == nil && claims.Issuer == b.issuer { |
| + // Nobody is signed in here and the subject has no person: take the |
| + // roster decision, which allocates nothing. With a session present |
| + // the arrival is refused below as unknown, before Admit and with |
| + // no proof issued, whoever that session belongs to. A non-member |
| + // falls through to exactly the unknown answer an instance without |
| + // the hooks gives. A Member gets a single-use choice proof and the |
| + // choose page; nothing is created until they choose. "Cannot |
| + // decide now" is errHomeBridge, which the exchange answers 503. |
| + switch decision := b.admit(r.Context(), claims.Issuer, claims.Subject); { |
| + case decision == nil: |
| + secret, err := b.links.StartChoice(r.Context(), linkstore.Choice{Subject: claims.Subject, AuthTime: time.Unix(claims.AuthTime, 0)}, b.now()) |
| + if err != nil { |
| + return errHomeBridge |
| + } |
| + setHomeCookie(w, homeChoiceCookie, secret, choiceCookieLifetime) |
| + return rejectHome(r, "choose", http.StatusSeeOther) |
| + case !errors.Is(decision, ErrNoPerson): |
| + return errHomeBridge |
| + } |
| } |
| if errors.Is(err, linkstore.ErrRefused) { |
| if b.rememberUnknown != nil { |
| @@ -248,7 +272,10 @@ func (b *Bridge) complete(w http.ResponseWriter, r *http.Request, claims asserti |
| // existingPerson never creates a person or samples, even during ordinary SSO. |
| func (b *Bridge) existingPerson(r *http.Request, session Session) (Person, error) { |
| - if session.Method == HomeMethod { |
| + if IsHomeDerived(session.Method) { |
| + if Expired(session, b.now()) { |
| + return Person{}, errIdentityRefused |
| + } |
| return b.Resolve(r.Context(), session.Subject) |
| } |
| if session.Method != "magiclink" && session.Method != "keymail" { |
| @@ -276,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/choose.go b/connect/choose.go| new file mode 100644 |
| index 0000000..b905394 |
| --- /dev/null |
| +++ b/connect/choose.go |
| @@ -0,0 +1,210 @@ |
| +package connect |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "net/url" |
| + |
| + "amadan.net/oficina/home/connect/linkstore" |
| +) |
| + |
| +// ChoosePath is the member choice page (Home spec |
| +// 2026-11-14-oficina-id-native.md §8). Mount ChoosePage at GET and |
| +// ChoosePost at POST, outside the session guards: the person choosing has |
| +// no session here. ChoosePost is an ordinary same-origin form, so it stays |
| +// inside the app's CSRF middleware as well as checking Origin itself. |
| +const ChoosePath = "/account/home/choose" |
| + |
| +const homeChoiceCookie = "__Host-oficina-home-choice" |
| +const choiceCookieLifetime = 600 |
| + |
| +// ChoicePage is the choose page's form: both buttons POST Action with the |
| +// field "choice" ("connect" or "new") and the hidden field "token". |
| +type ChoicePage struct { |
| + Action, Token string |
| +} |
| + |
| +type choiceKey struct{} |
| + |
| +// ChoiceFor is the form for the choose page being rendered: Render is |
| +// called with state "choose" and a request carrying it. The labels are the |
| +// app's ("choose_title", "choose_body", "choose_connect_action" and |
| +// "choose_new_action" in English). |
| +func ChoiceFor(r *http.Request) (ChoicePage, bool) { |
| + p, ok := r.Context().Value(choiceKey{}).(ChoicePage) |
| + return p, ok |
| +} |
| + |
| +// formKey is the choice form's HMAC key, derived from the storage key and |
| +// bound to this origin, so a token is good for one proof on one instance. |
| +func formKey(dek []byte, origin string) []byte { |
| + m := hmac.New(sha256.New, dek) |
| + m.Write([]byte("oficina-connect/choice-form/v1\x00" + origin)) |
| + return m.Sum(nil) |
| +} |
| + |
| +func (b *Bridge) choiceToken(secret string) string { |
| + m := hmac.New(sha256.New, b.formKey) |
| + m.Write([]byte(secret)) |
| + return base64.RawURLEncoding.EncodeToString(m.Sum(nil)) |
| +} |
| + |
| +// ChoosePage is GET /account/home/choose: "Welcome to the team", with |
| +// "Connect my existing account" and "I'm new here — continue with Oficina |
| +// ID". It consumes nothing; it needs the live, browser-bound proof that a |
| +// Member's finish left. |
| +func (b *Bridge) ChoosePage(w http.ResponseWriter, r *http.Request) { |
| + if !b.guard(w, r, http.MethodGet, ChoosePath) { |
| + return |
| + } |
| + if b.admit == nil { |
| + b.fail(w, r, http.StatusNotFound) |
| + return |
| + } |
| + secret, present, ok := homeCookie(r, homeChoiceCookie) |
| + if !present || !ok { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + switch err := b.links.ChoiceLive(r.Context(), secret, b.now()); { |
| + case errors.Is(err, linkstore.ErrRefused): |
| + setHomeCookie(w, homeChoiceCookie, "", -1) |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + case err != nil: |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + page := ChoicePage{Action: ChoosePath, Token: b.choiceToken(secret)} |
| + b.render(w, r.WithContext(context.WithValue(r.Context(), choiceKey{}, page)), "choose", "", http.StatusOK) |
| +} |
| + |
| +// ChoosePost is the choice. Its form token is an HMAC of the proof cookie |
| +// and it requires this exact origin in Origin. "connect" consumes the proof |
| +// and goes to local sign-in with the link-resuming marker, so the person |
| +// lands on slice 1's linking. "new" refuses while any app session is |
| +// present; otherwise it consumes the proof in its own short transaction |
| +// and then, with no transaction open, re-checks Admit and that the subject |
| +// still has no person, allocates through Unlinked, resolves and mints. A |
| +// consumed proof that yields no session means signing in again. |
| +func (b *Bridge) ChoosePost(w http.ResponseWriter, r *http.Request) { |
| + if !b.guard(w, r, http.MethodPost, ChoosePath) { |
| + return |
| + } |
| + if b.admit == nil { |
| + b.fail(w, r, http.StatusNotFound) |
| + return |
| + } |
| + origins := r.Header.Values("Origin") |
| + if len(origins) != 1 || origins[0] != b.origin { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || media != "application/x-www-form-urlencoded" { |
| + b.fail(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1024)) |
| + if err != nil { |
| + b.fail(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + form, err := url.ParseQuery(string(body)) |
| + if err != nil || len(form) != 2 || len(form["choice"]) != 1 || len(form["token"]) != 1 { |
| + b.fail(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + secret, present, ok := homeCookie(r, homeChoiceCookie) |
| + if !present || !ok || !hmac.Equal([]byte(form["token"][0]), []byte(b.choiceToken(secret))) { |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + choice := form["choice"][0] |
| + if choice != "connect" && choice != "new" { |
| + b.fail(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + if choice == "new" && cookieCount(r, b.sessionCookie) != 0 { |
| + // Allocation is reachable only with no app session at all, as at |
| + // finish; the proof stays for a choice made without one. |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + } |
| + taken, err := b.links.TakeChoice(r.Context(), secret, b.now()) |
| + switch { |
| + case errors.Is(err, linkstore.ErrRefused): |
| + setHomeCookie(w, homeChoiceCookie, "", -1) |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + case err != nil: |
| + // Nothing was consumed: the same proof may be tried again. |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + setHomeCookie(w, homeChoiceCookie, "", -1) |
| + if choice == "connect" { |
| + if b.rememberUnknown != nil { |
| + b.rememberUnknown(w) |
| + } |
| + http.Redirect(w, r, "/signin/local", http.StatusSeeOther) |
| + return |
| + } |
| + person, err := b.chooseNew(r.Context(), taken.Subject) |
| + if errors.Is(err, linkstore.ErrRefused) { |
| + if b.rememberUnknown != nil { |
| + b.rememberUnknown(w) |
| + } |
| + b.render(w, r, "unknown", "", http.StatusForbidden) |
| + return |
| + } |
| + if err != nil || person.ID <= 0 { |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + if err := b.mintSession(w, r, Session{Subject: taken.Subject, Method: HomeMethod, AuthTime: taken.AuthTime}); err != nil { |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + http.Redirect(w, r, "/", http.StatusSeeOther) |
| +} |
| + |
| +// chooseNew is "I'm new here" for a subject, after its proof or its native |
| +// request: a person found now (a link or a racing choice) is used as is; |
| +// otherwise Admit again, then allocate. ErrRefused is "unknown", ErrStorage |
| +// "cannot decide now". It holds no transaction across any hook. |
| +func (b *Bridge) chooseNew(ctx context.Context, subject string) (Person, error) { |
| + if p, err := b.Resolve(ctx, subject); !errors.Is(err, linkstore.ErrRefused) { |
| + return p, err |
| + } |
| + switch err := b.admit(ctx, b.issuer, subject); { |
| + case errors.Is(err, ErrNoPerson): |
| + return Person{}, linkstore.ErrRefused |
| + case err != nil: |
| + return Person{}, linkstore.ErrStorage |
| + } |
| + return b.allocate(ctx, subject) |
| +} |
| + |
| +// allocate is Unlinked followed by a fresh resolution (spec §7 step 4): the |
| +// person is whoever the subject resolves to afterwards, so a hook that |
| +// refused because a racing choice created the person still signs this one |
| +// in, and a refusal with nobody found is "unknown", or "cannot decide now" |
| +// when either step could not read. |
| +func (b *Bridge) allocate(ctx context.Context, subject string) (Person, error) { |
| + _, hookErr := homeOnlyPerson(b.unlinked(ctx, b.issuer, subject)) |
| + p, err := b.Resolve(ctx, subject) |
| + switch { |
| + case err == nil: |
| + return p, nil |
| + case errors.Is(hookErr, linkstore.ErrStorage) || errors.Is(err, linkstore.ErrStorage): |
| + return Person{}, linkstore.ErrStorage |
| + } |
| + return Person{}, linkstore.ErrRefused |
| +} |
diff --git a/connect/derived_test.go b/connect/derived_test.go| new file mode 100644 |
| index 0000000..8b68ff4 |
| --- /dev/null |
| +++ b/connect/derived_test.go |
| @@ -0,0 +1,77 @@ |
| +package connect |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestIsHomeDerivedIsExactlyTheThreeHomeMethods(t *testing.T) { |
| + for method, want := range map[string]bool{ |
| + HomeMethod: true, NativeMethod: true, NativeWebMethod: true, |
| + "magiclink": false, "keymail": false, "guest": false, "": false, |
| + "home-assertion-native ": false, "Home-Assertion": false, |
| + } { |
| + if IsHomeDerived(method) != want { |
| + t.Errorf("IsHomeDerived(%q) = %v", method, !want) |
| + } |
| + } |
| +} |
| + |
| +func TestExpiredIsSevenDaysAbsoluteForNativeSessions(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + for _, c := range []struct { |
| + method string |
| + at time.Time |
| + want bool |
| + }{ |
| + {NativeMethod, now.Add(-NativeLifetime), false}, |
| + {NativeMethod, now.Add(-NativeLifetime - time.Second), true}, |
| + {NativeWebMethod, now.Add(-NativeLifetime - time.Second), true}, |
| + {NativeMethod, time.Time{}, true}, |
| + {NativeMethod, now.Add(time.Hour), true}, |
| + // A browser or local session keeps the session store's own expiry. |
| + {HomeMethod, now.Add(-30 * 24 * time.Hour), false}, |
| + {"magiclink", time.Time{}, false}, |
| + } { |
| + if got := Expired(Session{Subject: "pr_x", Method: c.method, At: c.at}, now); got != c.want { |
| + t.Errorf("Expired(%s, at %v) = %v", c.method, now.Sub(c.at), got) |
| + } |
| + } |
| +} |
| + |
| +// A native session resolves, signs in and holds the same-person rules like a |
| +// Home one, until seven days after it was minted, however recently used. |
| +func TestNativeSessionResolvesUntilSevenDays(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + if _, err := h.db.Exec("INSERT INTO home_only(issuer,subject) VALUES(?,?)", bridgeIssuer, "pr_member"); err != nil { |
| + t.Fatal(err) |
| + } |
| + token, err := f.sessions.Mint(Session{Subject: "pr_member", Method: NativeMethod, AuthTime: time.Now().Add(-time.Minute)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cookie := &http.Cookie{Name: f.b.sessionCookie, Value: token} |
| + if p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie})); err != nil || p.ID <= 1000 { |
| + t.Fatalf("native session did not resolve: %+v %v", p, err) |
| + } |
| + routes := f.routes(t) |
| + w := httptest.NewRecorder() |
| + routes.Signin(w, bridgeRequest(http.MethodGet, "/signin?return_to=%2Fd%2Fx", []*http.Cookie{cookie})) |
| + if w.Code != 303 || w.Header().Get("Location") != "/d/x" { |
| + t.Fatalf("a live native session is not signed in: %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + |
| + s := f.sessions.values[token] |
| + s.At = time.Now().Add(-NativeLifetime - time.Minute) |
| + f.sessions.values[token] = s |
| + if _, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie})); err == nil { |
| + t.Fatal("a native session resolved after seven days") |
| + } |
| + w = httptest.NewRecorder() |
| + routes.Signin(w, bridgeRequest(http.MethodGet, "/signin?return_to=%2Fd%2Fx", []*http.Cookie{cookie})) |
| + if w.Header().Get("Location") == "/d/x" { |
| + t.Fatal("an expired native session counted as signed in") |
| + } |
| +} |
diff --git a/connect/go.mod b/connect/go.mod| index 7d92eac..a17cd5e 100644 |
| --- a/connect/go.mod |
| +++ b/connect/go.mod |
| @@ -4,7 +4,7 @@ go 1.25.0 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| - amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| + amadan.net/oficina/home/handoff v0.0.0-20261114103055-d11246af8c07 |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd |
| github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| modernc.org/sqlite v1.55.0 |
diff --git a/connect/go.sum b/connect/go.sum| index 067fbd4..6d07edf 100644 |
| --- a/connect/go.sum |
| +++ b/connect/go.sum |
| @@ -2,6 +2,10 @@ amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114095655-c43a9100faf0 h1:DTpsiobE852SQDorghPVYRIrDI9DA5r/8BHNosBCM54= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114095655-c43a9100faf0/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114103055-d11246af8c07 h1:F/cCmhmNZONlrdWt9AD5O3BjpLqIUeRDYDLvYrpST+o= |
| +amadan.net/oficina/home/handoff v0.0.0-20261114103055-d11246af8c07/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc= |
| amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE= |
| github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= |
diff --git a/connect/linkstore/choice.go b/connect/linkstore/choice.go| new file mode 100644 |
| index 0000000..8e07a4f |
| --- /dev/null |
| +++ b/connect/linkstore/choice.go |
| @@ -0,0 +1,169 @@ |
| +package linkstore |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "time" |
| +) |
| + |
| +// Choice is what a member's choice proof holds (Home spec |
| +// 2026-11-14-oficina-id-native.md §8): the subject and authentication time |
| +// of an already verified and consumed assertion whose subject had neither a |
| +// link nor a Home-only person here, and whom the roster called a Member. |
| +// It is bound to one browser by its secret, lives ten minutes, and is |
| +// single-use: TakeChoice deletes it before reading it. |
| +type Choice struct { |
| + Subject string |
| + AuthTime time.Time |
| +} |
| + |
| +type choiceProof struct { |
| + Version int `json:"v"` |
| + Issuer string `json:"issuer"` |
| + Subject string `json:"subject"` |
| + AuthTime int64 `json:"auth"` |
| + Expires int64 `json:"expires"` |
| +} |
| + |
| +const choiceLifetime = 600 |
| +const maxChoices = 10000 |
| + |
| +func (s *Store) choicePurpose(id string) string { |
| + return "identity-choice/v1/" + id + "/" + s.origin |
| +} |
| + |
| +// StartChoice stores a sealed choice proof and returns its browser secret. |
| +// Only the hash of the secret enters the database. At capacity the oldest |
| +// proof is evicted: losing one costs that person a fresh sign-in. |
| +func (s *Store) StartChoice(ctx context.Context, c Choice, now time.Time) (string, error) { |
| + if !validSubject(c.Subject) || c.AuthTime.Unix() <= 0 { |
| + return "", ErrRefused |
| + } |
| + secret, err := newSecret() |
| + if err != nil { |
| + return "", err |
| + } |
| + id := hash(secret) |
| + tx, high, err := s.begin(ctx, now) |
| + if err != nil { |
| + return "", err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, "DELETE FROM home_choice_proofs WHERE expires_at <= ?", high); err != nil { |
| + return "", ErrStorage |
| + } |
| + var count int |
| + if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_choice_proofs").Scan(&count); err != nil { |
| + return "", ErrStorage |
| + } |
| + if count >= maxChoices { |
| + if _, err = tx.ExecContext(ctx, "DELETE FROM home_choice_proofs WHERE id_hash IN (SELECT id_hash FROM home_choice_proofs ORDER BY expires_at, id_hash LIMIT ?)", count-maxChoices+1); err != nil { |
| + return "", ErrStorage |
| + } |
| + } |
| + p := choiceProof{Version: 1, Issuer: s.issuer, Subject: c.Subject, AuthTime: c.AuthTime.Unix(), Expires: high + choiceLifetime} |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return "", ErrStorage |
| + } |
| + sealed, err := s.seal.Seal(s.choicePurpose(id), raw) |
| + if err != nil { |
| + return "", ErrStorage |
| + } |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO home_choice_proofs (id_hash, expires_at, payload) VALUES (?, ?, ?)", id, p.Expires, sealed); err != nil { |
| + return "", ErrStorage |
| + } |
| + if err = commit(tx); err != nil { |
| + return "", err |
| + } |
| + return secret, nil |
| +} |
| + |
| +// ChoiceLive reports whether secret names a live proof, consuming nothing: |
| +// the choose page's GET. ErrRefused for none, ErrStorage when unreadable. |
| +func (s *Store) ChoiceLive(ctx context.Context, secret string, now time.Time) error { |
| + id, ok := secretHash(secret) |
| + if !ok { |
| + return ErrRefused |
| + } |
| + var expires int64 |
| + var raw []byte |
| + err := s.db.QueryRowContext(ctx, "SELECT expires_at, payload FROM home_choice_proofs WHERE id_hash = ?", id).Scan(&expires, &raw) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrRefused |
| + } |
| + if err != nil { |
| + return ErrStorage |
| + } |
| + _, err = s.openChoice(id, expires, raw, now.Unix()) |
| + return err |
| +} |
| + |
| +// TakeChoice consumes a proof in its own short transaction, deleting it |
| +// before interpreting it and committing either way, so a proof is used at |
| +// most once even when two choices race: one gets the Choice, the other |
| +// ErrRefused. The caller acts on the Choice with no transaction open. |
| +func (s *Store) TakeChoice(ctx context.Context, secret string, now time.Time) (Choice, error) { |
| + id, ok := secretHash(secret) |
| + if !ok { |
| + return Choice{}, ErrRefused |
| + } |
| + tx, high, err := s.begin(ctx, now) |
| + if err != nil { |
| + return Choice{}, err |
| + } |
| + defer tx.Rollback() |
| + var expires int64 |
| + var raw []byte |
| + err = tx.QueryRowContext(ctx, "DELETE FROM home_choice_proofs WHERE id_hash = ? RETURNING expires_at, payload", id).Scan(&expires, &raw) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return Choice{}, refuse(tx) |
| + } |
| + if err != nil { |
| + return Choice{}, ErrStorage |
| + } |
| + c, err := s.openChoice(id, expires, raw, high) |
| + if err != nil { |
| + return Choice{}, refuse(tx) |
| + } |
| + if err = commit(tx); err != nil { |
| + return Choice{}, err |
| + } |
| + return c, nil |
| +} |
| + |
| +// DropChoice deletes a proof by its secret, consuming it unused: sign-out. |
| +func (s *Store) DropChoice(ctx context.Context, secret string) error { |
| + id, ok := secretHash(secret) |
| + if !ok { |
| + return ErrRefused |
| + } |
| + if _, err := s.db.ExecContext(ctx, "DELETE FROM home_choice_proofs WHERE id_hash = ?", id); err != nil { |
| + return ErrStorage |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Store) openChoice(id string, expires int64, raw []byte, now int64) (Choice, error) { |
| + if len(raw) > 4096 || expires <= now { |
| + return Choice{}, ErrRefused |
| + } |
| + opened, err := s.seal.Open(s.choicePurpose(id), raw) |
| + if err != nil { |
| + return Choice{}, ErrRefused |
| + } |
| + var p choiceProof |
| + dec := json.NewDecoder(bytes.NewReader(opened)) |
| + dec.DisallowUnknownFields() |
| + if dec.Decode(&p) != nil || dec.Decode(new(any)) != io.EOF { |
| + return Choice{}, ErrRefused |
| + } |
| + if p.Version != 1 || p.Issuer != s.issuer || p.Expires != expires || !validSubject(p.Subject) || p.AuthTime <= 0 { |
| + return Choice{}, ErrRefused |
| + } |
| + return Choice{Subject: p.Subject, AuthTime: time.Unix(p.AuthTime, 0)}, nil |
| +} |
diff --git a/connect/linkstore/choice_test.go b/connect/linkstore/choice_test.go| new file mode 100644 |
| index 0000000..e11830b |
| --- /dev/null |
| +++ b/connect/linkstore/choice_test.go |
| @@ -0,0 +1,101 @@ |
| +package linkstore |
| + |
| +import ( |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestChoiceProofIsSingleUse(t *testing.T) { |
| + s, _ := fixture(t) |
| + secret, err := s.StartChoice(ctx, Choice{Subject: "pr_member", AuthTime: testNow.Add(-time.Minute)}, testNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The page's check consumes nothing. |
| + for range 2 { |
| + if err := s.ChoiceLive(ctx, secret, testNow); err != nil { |
| + t.Fatal("live proof refused", err) |
| + } |
| + } |
| + c, err := s.TakeChoice(ctx, secret, testNow) |
| + if err != nil || c.Subject != "pr_member" || !c.AuthTime.Equal(testNow.Add(-time.Minute)) { |
| + t.Fatalf("take: %+v %v", c, err) |
| + } |
| + if _, err := s.TakeChoice(ctx, secret, testNow); err != ErrRefused { |
| + t.Fatal("proof used twice", err) |
| + } |
| + if err := s.ChoiceLive(ctx, secret, testNow); err != ErrRefused { |
| + t.Fatal("a used proof is still live", err) |
| + } |
| +} |
| + |
| +func TestChoiceProofExpiresInTenMinutes(t *testing.T) { |
| + s, _ := fixture(t) |
| + secret, err := s.StartChoice(ctx, Choice{Subject: "pr_member", AuthTime: testNow}, testNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + later := testNow.Add(10 * time.Minute) |
| + if err := s.ChoiceLive(ctx, secret, later); err != ErrRefused { |
| + t.Fatal("expired proof live", err) |
| + } |
| + if _, err := s.TakeChoice(ctx, secret, later); err != ErrRefused { |
| + t.Fatal("expired proof taken", err) |
| + } |
| +} |
| + |
| +func TestChoiceProofRefusesForeignSecrets(t *testing.T) { |
| + s, _ := fixture(t) |
| + if _, err := s.StartChoice(ctx, Choice{Subject: "pr_member", AuthTime: testNow}, testNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, bad := range []string{"", "short", local(1).SessionToken, "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"} { |
| + if _, err := s.TakeChoice(ctx, bad, testNow); err != ErrRefused { |
| + t.Errorf("took %q: %v", bad, err) |
| + } |
| + } |
| + if _, err := s.StartChoice(ctx, Choice{Subject: "bad subject", AuthTime: testNow}, testNow); err != ErrRefused { |
| + t.Fatal("stored an invalid subject", err) |
| + } |
| +} |
| + |
| +// Two choices racing for one proof: exactly one gets it. |
| +func TestChoiceProofRaceHasOneWinner(t *testing.T) { |
| + s, _ := fixture(t) |
| + secret, err := s.StartChoice(ctx, Choice{Subject: "pr_member", AuthTime: testNow}, testNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var wg sync.WaitGroup |
| + var mu sync.Mutex |
| + won := 0 |
| + for range 8 { |
| + wg.Go(func() { |
| + if _, err := s.TakeChoice(ctx, secret, testNow); err == nil { |
| + mu.Lock() |
| + won++ |
| + mu.Unlock() |
| + } |
| + }) |
| + } |
| + wg.Wait() |
| + if won != 1 { |
| + t.Fatalf("%d winners", won) |
| + } |
| +} |
| + |
| +// Sweep, at boot and inside every link flow, drops expired proofs. |
| +func TestSweepDropsExpiredChoiceProofs(t *testing.T) { |
| + s, _ := fixture(t) |
| + if _, err := s.StartChoice(ctx, Choice{Subject: "pr_member", AuthTime: testNow}, testNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.Sweep(ctx, testNow.Add(11*time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var n int |
| + if err := s.db.QueryRow("SELECT COUNT(*) FROM home_choice_proofs").Scan(&n); err != nil || n != 0 { |
| + t.Fatal("expired proof kept", n, err) |
| + } |
| +} |
diff --git a/connect/linkstore/migrations/0003_choice_proofs.sql b/connect/linkstore/migrations/0003_choice_proofs.sql| new file mode 100644 |
| index 0000000..84a6044 |
| --- /dev/null |
| +++ b/connect/linkstore/migrations/0003_choice_proofs.sql |
| @@ -0,0 +1,6 @@ |
| +CREATE TABLE home_choice_proofs ( |
| + id_hash TEXT PRIMARY KEY NOT NULL, |
| + expires_at INTEGER NOT NULL, |
| + payload BLOB NOT NULL |
| +); |
| +CREATE INDEX home_choice_proofs_expiry ON home_choice_proofs(expires_at); |
diff --git a/connect/linkstore/store.go b/connect/linkstore/store.go| index 5036cc0..9f8eb79 100644 |
| --- a/connect/linkstore/store.go |
| +++ b/connect/linkstore/store.go |
| @@ -158,8 +158,10 @@ func commit(tx *sql.Tx) error { |
| return nil |
| } |
| func sweep(ctx context.Context, tx *sql.Tx, high int64) error { |
| - if _, err := tx.ExecContext(ctx, "DELETE FROM home_link_flows WHERE expires_at <= ?", high); err != nil { |
| - return ErrStorage |
| + for _, table := range []string{"home_link_flows", "home_choice_proofs"} { |
| + if _, err := tx.ExecContext(ctx, "DELETE FROM "+table+" WHERE expires_at <= ?", high); err != nil { |
| + return ErrStorage |
| + } |
| } |
| return nil |
| } |
diff --git a/connect/linkstore/store_test.go b/connect/linkstore/store_test.go| index f965b76..076e57b 100644 |
| --- a/connect/linkstore/store_test.go |
| +++ b/connect/linkstore/store_test.go |
| @@ -36,7 +36,7 @@ func fixture(t *testing.T) (*Store, string) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - for _, name := range []string{"0001_links.sql", "0002_person_binding.sql"} { |
| + for _, name := range []string{"0001_links.sql", "0002_person_binding.sql", "0003_choice_proofs.sql"} { |
| migration, err := migrations.ReadFile("migrations/" + name) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/connect/native.go b/connect/native.go| new file mode 100644 |
| index 0000000..bb0fe2d |
| --- /dev/null |
| +++ b/connect/native.go |
| @@ -0,0 +1,227 @@ |
| +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 |
| + } |
| + // Known and accepted (Fable, 2026-11-14 review; recorded in the spec): |
| + // an instance cannot tell this assertion from a browser one that |
| + // /authorize minted with a caller-chosen nonce equal to a native nonce. |
| + // Only the subject's own browser can do that, for itself, so it grants |
| + // nothing the person does not already have. |
| + 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..a6bd4a6 |
| --- /dev/null |
| +++ b/connect/native_test.go |
| @@ -0,0 +1,471 @@ |
| +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 forever. The probe |
| +// waits a second instead, and a hook that finds the writer held fails the |
| +// test there and then, before it or anything after it touches the pool. |
| +// Every hook runs on the test goroutine (the handlers are called directly), |
| +// so Fatalf is safe here. |
| +func TestNoHookRunsWithTheWriterHeld(t *testing.T) { |
| + var probe func(string) bool |
| + h := &homeOnlyHooks{} |
| + f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) { |
| + h.install(f, c) |
| + f.db.SetMaxOpenConns(1) |
| + probe = func(string) bool { |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| + defer cancel() |
| + _, err := f.db.ExecContext(ctx, "UPDATE home_link_clock SET high_water = high_water WHERE id = 1") |
| + return err != nil |
| + } |
| + free := func(name string) { |
| + if probe(name) { |
| + t.Fatalf("called with the writer held: [%s]", name) |
| + } |
| + } |
| + admit, unlinked, homeOnly, mint := c.Admit, c.Unlinked, c.HomeOnly, c.MintHomeSession |
| + c.Admit = func(ctx context.Context, i, s string) error { free("Admit"); return admit(ctx, i, s) } |
| + c.Unlinked = func(ctx context.Context, i, s string) (Person, error) { free("Unlinked"); return unlinked(ctx, i, s) } |
| + c.HomeOnly = func(ctx context.Context, i, s string) (Person, error) { free("HomeOnly"); return homeOnly(ctx, i, s) } |
| + c.MintHomeSession = func(w http.ResponseWriter, r *http.Request, s Session) error { |
| + free("MintHomeSession") |
| + return mint(w, r, s) |
| + } |
| + c.MintNativeSession = func(_ context.Context, s Session) (string, error) { |
| + free("MintNativeSession") |
| + return f.sessions.Mint(s) |
| + } |
| + }) |
| + // The probe does notice a held writer. |
| + tx, err := f.db.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seen := probe("self-check") |
| + tx.Rollback() |
| + if !seen { |
| + t.Fatal("the probe cannot see a held writer") |
| + } |
| + // The browser path: finish, the choose page, "I'm new here"; then a |
| + // known person's finish (HomeOnly and MintHomeSession in complete). |
| + f.signInNew(t, "pr_browser") |
| + if w := f.finishAs(t, "pr_browser", nil); w.Code != 303 || w.Header().Get("Location") != "/next" { |
| + t.Fatalf("known person's finish=%d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + // 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) |
| + } |
| +} |
diff --git a/connect/resolve_on_test.go b/connect/resolve_on_test.go| index 7195b51..0d27303 100644 |
| --- a/connect/resolve_on_test.go |
| +++ b/connect/resolve_on_test.go |
| @@ -44,9 +44,7 @@ func TestResolveOnAdoptedLinkUsesHeldWriter(t *testing.T) { |
| func TestResolveOnNeverEscapesToHomeOnlyHook(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| - if w := f.finishAs(t, "pr_member", nil); w.Code != 303 { |
| - t.Fatalf("ordinary Home-only sign-in failed: %d", w.Code) |
| - } |
| + f.signInNew(t, "pr_member") |
| if p, err := f.b.Resolve(t.Context(), "pr_member"); err != nil || p.ID <= 1000 || p.Label != "" { |
| t.Fatal("ordinary Resolve lost Home-only support", p, err) |
| } |
diff --git a/connect/routes.go b/connect/routes.go| index a3ef883..42eb5b1 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 |
| } |
| @@ -131,11 +134,11 @@ func (h *Routes) Signin(w http.ResponseWriter, r *http.Request) { |
| // signedIn reports a live, signed-in app session: exactly one session |
| // cookie, which ReadSession resolves to a person who signed in, through |
| -// Home (HomeMethod) or a local link (magiclink, keymail). An ambiguous |
| -// pair or a revoked cookie is not one, and neither is any other method: |
| -// Calls' anonymous per-meeting guests ("guest") are sessions but not |
| -// sign-ins, and sending one to the root instead of the exchange ends on a |
| -// 404 (the #74 review, finding 3). An unknown method falls back to the |
| +// Home (IsHomeDerived and not Expired) or a local link (magiclink, |
| +// keymail). An ambiguous pair or a revoked cookie is not one, and neither |
| +// is any other method: Calls' anonymous per-meeting guests ("guest") are |
| +// sessions but not sign-ins, and sending one to the root instead of the |
| +// exchange ends on a 404 (the #74 review, finding 3). An unknown method falls back to the |
| // exchange, which is what /signin did before this check existed. |
| func (h *Routes) signedIn(r *http.Request) bool { |
| if cookieCount(r, h.cfg.SessionCookie) != 1 { |
| @@ -145,11 +148,10 @@ func (h *Routes) signedIn(r *http.Request) bool { |
| if err != nil || s == nil || s.Subject == "" { |
| return false |
| } |
| - switch s.Method { |
| - case HomeMethod, "magiclink", "keymail": |
| - return true |
| + if IsHomeDerived(s.Method) { |
| + return !Expired(*s, h.bridge.now()) |
| } |
| - return false |
| + return s.Method == "magiclink" || s.Method == "keymail" |
| } |
| func (h *Routes) SignedOut(w http.ResponseWriter, r *http.Request) { |
| @@ -209,7 +211,12 @@ func (h *Routes) ConfirmPost(w http.ResponseWriter, r *http.Request) { |
| // here, as before. |
| func (h *Routes) Signout(w http.ResponseWriter, r *http.Request) { |
| h.cfg.SignOut(w, r) |
| - for _, name := range []string{homeInitCookie, homeProofCookie, localLinkNavigationCookie, homeReturnCookie, "__Host-oficina-assertion-pending", "__Host-oficina-assertion-inbox"} { |
| + // A pending member choice ends with the browser's sign-out: its row, |
| + // not only its cookie. Best effort; the proof expires in ten minutes. |
| + if secret, present, ok := homeCookie(r, homeChoiceCookie); present && ok && h.bridge.links != nil { |
| + _ = h.bridge.links.DropChoice(r.Context(), secret) |
| + } |
| + for _, name := range []string{homeInitCookie, homeProofCookie, homeChoiceCookie, localLinkNavigationCookie, homeReturnCookie, "__Host-oficina-assertion-pending", "__Host-oficina-assertion-inbox"} { |
| localNavigationCookie(w, name, "", -1) |
| } |
| w.Header().Set("Cache-Control", "no-store") |
diff --git a/connect/routes_test.go b/connect/routes_test.go| index 2c7fc26..9b0b27d 100644 |
| --- a/connect/routes_test.go |
| +++ b/connect/routes_test.go |
| @@ -107,13 +107,18 @@ func assertSignoutCleared(t *testing.T, w *httptest.ResponseRecorder) { |
| if w.Header().Get("Cache-Control") != "no-store" { |
| t.Fatal("sign-out cacheable") |
| } |
| - if len(w.Result().Cookies()) != 6 { |
| + if len(w.Result().Cookies()) != 7 { |
| t.Fatal("handoff pointers left behind") |
| } |
| + choice := false |
| for _, c := range w.Result().Cookies() { |
| if c.MaxAge != -1 || !c.Secure || !c.HttpOnly { |
| t.Fatal("cookie not cleared safely") |
| } |
| + choice = choice || c.Name == homeChoiceCookie |
| + } |
| + if !choice { |
| + t.Fatal("a pending member choice survived sign-out") |
| } |
| } |
| @@ -124,7 +129,7 @@ func assertSignoutCleared(t *testing.T, w *httptest.ResponseRecorder) { |
| func TestSigninWhenAlreadySignedIn(t *testing.T) { |
| _, n := navigationFixture(t) |
| locals := 0 |
| - h := &Routes{bridge: &Bridge{render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { w.WriteHeader(status) }}, navigation: n, cfg: RoutesConfig{Origin: navigationOrigin, SessionCookie: "__Host-rastrillo_session", ReadSession: func(r *http.Request) (*Session, error) { |
| + h := &Routes{bridge: &Bridge{now: time.Now, render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { w.WriteHeader(status) }}, navigation: n, cfg: RoutesConfig{Origin: navigationOrigin, SessionCookie: "__Host-rastrillo_session", ReadSession: func(r *http.Request) (*Session, error) { |
| c, err := r.Cookie("__Host-rastrillo_session") |
| if err != nil || (c.Value != "verified" && c.Value != "guest") { |
| return nil, nil |
diff --git a/connect/unlinked_test.go b/connect/unlinked_test.go| index 99ba7ba..df10bda 100644 |
| --- a/connect/unlinked_test.go |
| +++ b/connect/unlinked_test.go |
| @@ -6,23 +6,36 @@ import ( |
| "errors" |
| "net/http" |
| "net/http/httptest" |
| + "net/url" |
| + "slices" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| ) |
| // homeOnlyHooks is a team-mode app in miniature: a Home-only person table, |
| -// and a decision a test sets (admit, refuse, or cannot decide). It counts |
| -// how often each hook is asked, so a test can prove when connect does not |
| -// ask at all. |
| +// a roster decision and an allocation decision a test sets (admit, refuse, |
| +// or cannot decide). It counts how often each hook is asked, so a test can |
| +// prove when connect does not ask at all. |
| type homeOnlyHooks struct { |
| db *sql.DB |
| - decision error // nil admits; ErrNoPerson refuses; anything else is unavailable |
| + admission error // Admit: nil is a Member; ErrNoPerson a non-member; anything else unavailable |
| + decision error // Unlinked: nil allocates; anything else is returned as is |
| label string |
| lookupErr error |
| + admitted int |
| 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) { |
| @@ -31,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 |
| } |
| @@ -43,8 +56,12 @@ func (h *homeOnlyHooks) install(f *bridgeFixture, c *Config) { |
| p.Label = h.label |
| return p, err |
| } |
| + c.Admit = func(ctx context.Context, issuer, subject string) error { |
| + 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 |
| } |
| @@ -84,35 +101,89 @@ func (f *bridgeFixture) finishAs(t *testing.T, subject string, cookies []*http.C |
| return w |
| } |
| -func TestUnlinkedHooksAreAPair(t *testing.T) { |
| +// choose follows a finish that answered "choose": the page, then the POST. |
| +// It returns the page's response and the POST's. |
| +func (f *bridgeFixture) choose(t *testing.T, finish *httptest.ResponseRecorder, choice string, cookies []*http.Cookie) (*httptest.ResponseRecorder, *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if finish.Code != 303 || finish.Header().Get("Location") != ChoosePath { |
| + t.Fatalf("finish=%d %q, want the choose page", finish.Code, finish.Header().Get("Location")) |
| + } |
| + proof := bridgeCookie(t, finish, homeChoiceCookie) |
| + cookies = append(append([]*http.Cookie{}, cookies...), proof) |
| + page := httptest.NewRecorder() |
| + f.b.ChoosePage(page, bridgeRequest(http.MethodGet, ChoosePath, cookies)) |
| + if page.Code != 200 || page.Body.String() != "choose" { |
| + t.Fatalf("choose page=%d %q", page.Code, page.Body.String()) |
| + } |
| + return page, f.choosePost(t, choice, f.b.choiceToken(proof.Value), cookies) |
| +} |
| + |
| +func (f *bridgeFixture) choosePost(t *testing.T, choice, token string, cookies []*http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + form := url.Values{"choice": {choice}, "token": {token}} |
| + r := httptest.NewRequest(http.MethodPost, bridgeOrigin+ChoosePath, strings.NewReader(form.Encode())) |
| + r.Header.Set("Origin", bridgeOrigin) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + f.b.ChoosePost(w, r) |
| + return w |
| +} |
| + |
| +// signInNew is a Member's first sign-in: finish, then "I'm new here". It |
| +// returns the session cookie. |
| +func (f *bridgeFixture) signInNew(t *testing.T, subject string) *http.Cookie { |
| + t.Helper() |
| + _, w := f.choose(t, f.finishAs(t, subject, nil), "new", nil) |
| + if w.Code != 303 || w.Header().Get("Location") != "/" { |
| + t.Fatalf("choose new=%d %q body=%s", w.Code, w.Header().Get("Location"), w.Body.String()) |
| + } |
| + return bridgeCookie(t, w, f.b.sessionCookie) |
| +} |
| + |
| +func TestTeamHooksAreATrio(t *testing.T) { |
| hook := func(context.Context, string, string) (Person, error) { return Person{}, ErrNoPerson } |
| + admit := func(context.Context, string, string) error { return ErrNoPerson } |
| newBridgeFixtureWith(t, func(_ *bridgeFixture, c *Config) { |
| for name, adjust := range map[string]func(*Config){ |
| - "unlinked only": func(c *Config) { c.Unlinked = hook }, |
| - "home-only only": func(c *Config) { c.HomeOnly = hook }, |
| + "unlinked only": func(c *Config) { c.Unlinked = hook }, |
| + "home-only only": func(c *Config) { c.HomeOnly = hook }, |
| + "admit only": func(c *Config) { c.Admit = admit }, |
| + "no admit": func(c *Config) { c.Unlinked, c.HomeOnly = hook, hook }, |
| + "no unlinked": func(c *Config) { c.Admit, c.HomeOnly = admit, hook }, |
| + "no home-only only": func(c *Config) { c.Admit, c.Unlinked = admit, hook }, |
| } { |
| one := *c |
| adjust(&one) |
| if _, err := New(one); err == nil { |
| - t.Errorf("%s: New accepted one hook without the other", name) |
| + t.Errorf("%s: New accepted an incomplete set of team hooks", name) |
| } |
| } |
| - both := *c |
| - both.Unlinked, both.HomeOnly = hook, hook |
| - if _, err := New(both); err != nil { |
| - t.Errorf("New refused both hooks: %v", err) |
| + all := *c |
| + all.Admit, all.Unlinked, all.HomeOnly = admit, hook, hook |
| + if _, err := New(all); err != nil { |
| + t.Errorf("New refused all three hooks: %v", err) |
| } |
| }) |
| } |
| -func TestUnlinkedMemberSignsInAsAHomeOnlyPerson(t *testing.T) { |
| +// A Member with no link is asked, not allocated: the finish leaves a proof |
| +// and the choose page, and "I'm new here" makes the Home-only person. |
| +func TestMemberChoosesNewAndSignsInAsAHomeOnlyPerson(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| - w := f.finishAs(t, "pr_member", nil) |
| - if w.Code != 303 || w.Header().Get("Location") != "/next" { |
| - t.Fatalf("finish=%d %q body=%s", w.Code, w.Header().Get("Location"), w.Body.String()) |
| + finish := f.finishAs(t, "pr_member", nil) |
| + bridgeNoSession(t, f.b, finish) |
| + if h.admitted != 1 || h.unlinked != 0 || h.count(t) != 0 || h.remember != 0 { |
| + t.Fatalf("finish admitted=%d unlinked=%d people=%d remember=%d", h.admitted, h.unlinked, h.count(t), h.remember) |
| + } |
| + _, w := f.choose(t, finish, "new", nil) |
| + if w.Code != 303 || w.Header().Get("Location") != "/" { |
| + t.Fatalf("choose new=%d %q", w.Code, w.Header().Get("Location")) |
| } |
| - if h.unlinked != 1 || h.count(t) != 1 { |
| - t.Fatalf("unlinked asked %d times, %d people", h.unlinked, h.count(t)) |
| + if h.unlinked != 1 || h.count(t) != 1 || h.admitted != 2 { |
| + t.Fatalf("unlinked=%d people=%d admitted=%d", h.unlinked, h.count(t), h.admitted) |
| } |
| cookie := bridgeCookie(t, w, f.b.sessionCookie) |
| r := bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}) |
| @@ -124,60 +195,273 @@ func TestUnlinkedMemberSignsInAsAHomeOnlyPerson(t *testing.T) { |
| if err != nil || p.ID <= 1000 || p.Label != "" { |
| t.Fatalf("ResolveSession %+v %v", p, err) |
| } |
| - // A second sign-in is the same person, found without asking Unlinked. |
| + // A second sign-in is the same person, straight through: no roster |
| + // decision, no choice, no allocation. |
| again := f.finishAs(t, "pr_member", nil) |
| - if again.Code != 303 || h.unlinked != 1 || h.count(t) != 1 { |
| - t.Fatalf("second sign-in=%d unlinked=%d people=%d", again.Code, h.unlinked, h.count(t)) |
| + if again.Code != 303 || again.Header().Get("Location") != "/next" || h.unlinked != 1 || h.admitted != 2 || h.count(t) != 1 { |
| + t.Fatalf("second sign-in=%d %q unlinked=%d admitted=%d", again.Code, again.Header().Get("Location"), h.unlinked, h.admitted) |
| } |
| if p2, err := f.b.Resolve(context.Background(), "pr_member"); err != nil || p2.ID != p.ID { |
| t.Fatal("Resolve does not find the Home-only person", err) |
| } |
| - // Signed in as that person, the same subject arriving again is fine. |
| own := f.finishAs(t, "pr_member", []*http.Cookie{cookie}) |
| if own.Code != 303 || h.unlinked != 1 { |
| t.Fatalf("same person over own session=%d", own.Code) |
| } |
| } |
| -func TestUnlinkedRefusalIsConnectsUnknown(t *testing.T) { |
| +// "Connect my existing account" spends the proof and goes to local sign-in |
| +// with the link-resuming marker; the spent proof cannot then say "new". |
| +func TestChooseConnectConsumesTheProof(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + finish := f.finishAs(t, "pr_member", nil) |
| + proof := bridgeCookie(t, finish, homeChoiceCookie) |
| + _, w := f.choose(t, finish, "connect", nil) |
| + if w.Code != 303 || w.Header().Get("Location") != "/signin/local" || h.remember != 1 { |
| + t.Fatalf("connect=%d %q remember=%d", w.Code, w.Header().Get("Location"), h.remember) |
| + } |
| + bridgeNoSession(t, f.b, w) |
| + if again := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); again.Code != 403 { |
| + t.Fatalf("spent proof chose new: %d", again.Code) |
| + } |
| + if h.unlinked != 0 || h.count(t) != 0 { |
| + t.Fatal("connect allocated a person") |
| + } |
| +} |
| + |
| +// The POST that allocates refuses while any app session is present, and |
| +// leaves the proof for a choice made without one. |
| +func TestChooseNewRefusedWithAnAppSession(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + finish := f.finishAs(t, "pr_member", nil) |
| + proof := bridgeCookie(t, finish, homeChoiceCookie) |
| + local := f.local(t, "guest@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| + w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof, local}) |
| + if w.Code != 403 || h.unlinked != 0 || h.count(t) != 0 { |
| + t.Fatalf("new over a session=%d unlinked=%d", w.Code, h.unlinked) |
| + } |
| + bridgeNoSession(t, f.b, w) |
| + if ok := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); ok.Code != 303 { |
| + t.Fatalf("proof did not survive the refusal: %d", ok.Code) |
| + } |
| +} |
| + |
| +// The form token is bound to its proof cookie, and the POST to this origin. |
| +func TestChooseFormIsBoundToItsProof(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + mine := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) |
| + other := bridgeCookie(t, f.finishAs(t, "pr_other", nil), homeChoiceCookie) |
| + for name, w := range map[string]*httptest.ResponseRecorder{ |
| + "another proof's token": f.choosePost(t, "new", f.b.choiceToken(other.Value), []*http.Cookie{mine}), |
| + "no token": f.choosePost(t, "new", "", []*http.Cookie{mine}), |
| + "no proof": f.choosePost(t, "new", f.b.choiceToken(mine.Value), nil), |
| + "unknown choice": f.choosePost(t, "both", f.b.choiceToken(mine.Value), []*http.Cookie{mine}), |
| + } { |
| + if w.Code == 303 { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + bridgeNoSession(t, f.b, w) |
| + } |
| + for _, origin := range []string{"", "null", "https://evil.example", bridgeIssuer} { |
| + form := url.Values{"choice": {"new"}, "token": {f.b.choiceToken(mine.Value)}} |
| + r := httptest.NewRequest(http.MethodPost, bridgeOrigin+ChoosePath, strings.NewReader(form.Encode())) |
| + if origin != "" { |
| + r.Header.Set("Origin", origin) |
| + } |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.AddCookie(mine) |
| + w := httptest.NewRecorder() |
| + f.b.ChoosePost(w, r) |
| + if w.Code != 403 { |
| + t.Errorf("Origin %q: %d", origin, w.Code) |
| + } |
| + } |
| + if h.unlinked != 0 || h.count(t) != 0 { |
| + t.Fatal("a forged choice allocated") |
| + } |
| + // The proof survived every refusal. |
| + if w := f.choosePost(t, "new", f.b.choiceToken(mine.Value), []*http.Cookie{mine}); w.Code != 303 { |
| + t.Fatalf("genuine choice=%d", w.Code) |
| + } |
| +} |
| + |
| +func TestChoosePageNeedsALiveProof(t *testing.T) { |
| + f, _ := newHomeOnlyFixture(t) |
| + for name, cookies := range map[string][]*http.Cookie{ |
| + "none": nil, |
| + "malformed": {{Name: homeChoiceCookie, Value: "bad"}}, |
| + "unknown": {{Name: homeChoiceCookie, Value: strings.Repeat("A", 43)}}, |
| + } { |
| + w := httptest.NewRecorder() |
| + f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, cookies)) |
| + if w.Code != 403 || w.Body.String() != "failed" { |
| + t.Errorf("%s: %d %q", name, w.Code, w.Body.String()) |
| + } |
| + } |
| + proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) |
| + f.b.now = func() time.Time { return time.Now().Add(11 * time.Minute) } |
| + w := httptest.NewRecorder() |
| + f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, []*http.Cookie{proof})) |
| + if w.Code != 403 { |
| + t.Fatalf("expired proof page=%d", w.Code) |
| + } |
| +} |
| + |
| +// Without the hooks there is no choice to make. |
| +func TestChooseWithoutHooksIsNotFound(t *testing.T) { |
| + f := newBridgeFixture(t) |
| + w := httptest.NewRecorder() |
| + f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, nil)) |
| + if w.Code != 404 { |
| + t.Fatalf("page=%d", w.Code) |
| + } |
| +} |
| + |
| +// Two "I'm new here" POSTs racing on one proof make one person. |
| +func TestChooseRaceMakesOnePerson(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) |
| + token := f.b.choiceToken(proof.Value) |
| + codes := make(chan int, 4) |
| + var wg sync.WaitGroup |
| + for range 4 { |
| + wg.Go(func() { codes <- f.choosePost(t, "new", token, []*http.Cookie{proof}).Code }) |
| + } |
| + wg.Wait() |
| + close(codes) |
| + minted := 0 |
| + for c := range codes { |
| + if c == 303 { |
| + minted++ |
| + } |
| + } |
| + if minted != 1 || h.count(t) != 1 { |
| + t.Fatalf("minted=%d people=%d", minted, h.count(t)) |
| + } |
| +} |
| + |
| +// Unlinked refusing after the roster said Member: resolve again. Nobody |
| +// found is unknown, an error is a 503, and a person made meanwhile (a |
| +// racing choice) is signed in. |
| +func TestChooseNewReResolvesAfterUnlinkedRefuses(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + decision error |
| + existing bool |
| + code int |
| + body string |
| + }{ |
| + {"refused, nobody", ErrNoPerson, false, 403, "unknown"}, |
| + {"error, nobody", errors.New("disk"), false, 503, "failed"}, |
| + {"refused, made meanwhile", ErrNoPerson, true, 303, ""}, |
| + {"error, made meanwhile", errors.New("disk"), true, 303, ""}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + finish := f.finishAs(t, "pr_member", nil) |
| + proof := bridgeCookie(t, finish, homeChoiceCookie) |
| + h.decision = c.decision |
| + if c.existing { |
| + // The person appears between the re-check and Unlinked. |
| + inner := f.b.unlinked |
| + f.b.unlinked = func(ctx context.Context, issuer, subject string) (Person, error) { |
| + if _, err := h.db.Exec("INSERT INTO home_only(issuer,subject) VALUES(?,?)", issuer, subject); err != nil { |
| + t.Fatal(err) |
| + } |
| + return inner(ctx, issuer, subject) |
| + } |
| + } |
| + w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}) |
| + if w.Code != c.code || (c.body != "" && w.Body.String() != c.body) { |
| + t.Fatalf("%d %q", w.Code, w.Body.String()) |
| + } |
| + if c.code != 303 { |
| + bridgeNoSession(t, f.b, w) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestNonMemberIsConnectsUnknown(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| - h.decision = ErrNoPerson |
| + h.admission = ErrNoPerson |
| w := f.finishAs(t, "pr_stranger", nil) |
| if w.Code != 403 || w.Body.String() != "unknown" || h.remember != 1 { |
| t.Fatalf("refused=%d %q remember=%d", w.Code, w.Body.String(), h.remember) |
| } |
| bridgeNoSession(t, f.b, w) |
| - if h.count(t) != 0 { |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == homeChoiceCookie { |
| + t.Fatal("a non-member got a choice proof") |
| + } |
| + } |
| + if h.count(t) != 0 || h.unlinked != 0 { |
| t.Fatal("refusal allocated a person") |
| } |
| } |
| -func TestUnlinkedUndecidedIsRetryable(t *testing.T) { |
| +// The answer to a non-member is the answer an instance without the hooks |
| +// gives, status, body and headers alike; only the freshly sealed marker |
| +// cookie's value differs. |
| +func TestNonMemberAnswerIsByteIdenticalToNoHooks(t *testing.T) { |
| + plain := newBridgeFixture(t) |
| + plain.routes(t) |
| + team, h := newHomeOnlyFixture(t) |
| + team.routes(t) |
| + h.admission = ErrNoPerson |
| + a := plain.finishAs(t, "pr_stranger", nil) |
| + b := team.finishAs(t, "pr_stranger", nil) |
| + if a.Code != b.Code || a.Body.String() != b.Body.String() { |
| + t.Fatalf("status/body differ: %d %q vs %d %q", a.Code, a.Body.String(), b.Code, b.Body.String()) |
| + } |
| + if shape(a.Header()) != shape(b.Header()) { |
| + t.Fatalf("headers differ:\n%s\n%s", shape(a.Header()), shape(b.Header())) |
| + } |
| +} |
| + |
| +// shape is a header set with cookie values elided. |
| +func shape(h http.Header) string { |
| + var lines []string |
| + for k, vs := range h { |
| + for _, v := range vs { |
| + if k == "Set-Cookie" { |
| + name, rest, _ := strings.Cut(v, "=") |
| + _, attrs, _ := strings.Cut(rest, ";") |
| + v = name + "=…;" + attrs |
| + } |
| + lines = append(lines, k+": "+v) |
| + } |
| + } |
| + slices.Sort(lines) |
| + return strings.Join(lines, "\n") |
| +} |
| + |
| +func TestRosterUnavailableIsRetryable(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| - h.decision = errors.New("roster unknown") |
| + h.admission = errors.New("roster unknown") |
| w := f.finishAs(t, "pr_member", nil) |
| if w.Code != 503 || w.Body.String() != "failed" || h.remember != 0 { |
| t.Fatalf("undecided=%d %q remember=%d", w.Code, w.Body.String(), h.remember) |
| } |
| bridgeNoSession(t, f.b, w) |
| - if h.count(t) != 0 { |
| + if h.count(t) != 0 || h.unlinked != 0 { |
| t.Fatal("undecided allocated a person") |
| } |
| - h.decision = nil |
| + h.admission = nil |
| h.lookupErr = errors.New("disk") |
| w = f.finishAs(t, "pr_member", nil) |
| - if w.Code != 503 || h.unlinked != 1 { |
| - t.Fatalf("unreadable Home-only store=%d unlinked=%d", w.Code, h.unlinked) |
| + if w.Code != 503 || h.admitted != 1 { |
| + t.Fatalf("unreadable Home-only store=%d admitted=%d", w.Code, h.admitted) |
| } |
| bridgeNoSession(t, f.b, w) |
| } |
| // An addressless person is the contract: a hook handing back a label (an |
| // address) is refused, never minted. |
| -func TestUnlinkedPersonWithAnAddressIsRefused(t *testing.T) { |
| +func TestHomeOnlyPersonWithAnAddressIsRefused(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| h.label = "someone@example.com" |
| - w := f.finishAs(t, "pr_member", nil) |
| + _, w := f.choose(t, f.finishAs(t, "pr_member", nil), "new", nil) |
| if w.Code != 403 || w.Body.String() != "unknown" { |
| t.Fatalf("labelled Home-only person=%d %q", w.Code, w.Body.String()) |
| } |
| @@ -187,26 +471,40 @@ func TestUnlinkedPersonWithAnAddressIsRefused(t *testing.T) { |
| } |
| } |
| -// Somebody already signed in: an unknown arrival is refused before anything |
| -// is allocated, and Unlinked is never asked. |
| -func TestUnlinkedNeverAskedOverALiveSession(t *testing.T) { |
| +// Somebody already signed in: an unknown arrival is refused before the |
| +// roster is asked and before any proof is issued. |
| +func TestAdmitNeverAskedOverALiveSession(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| local := f.local(t, "x@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| w := f.finishAs(t, "pr_member", []*http.Cookie{local}) |
| - if w.Code != 403 || h.unlinked != 0 || h.count(t) != 0 { |
| - t.Fatalf("arrival over a live session=%d unlinked=%d people=%d", w.Code, h.unlinked, h.count(t)) |
| + if w.Code != 403 || w.Body.String() != "unknown" || h.remember != 1 || h.admitted != 0 || h.unlinked != 0 || h.count(t) != 0 { |
| + t.Fatalf("arrival over a live session=%d %q admitted=%d unlinked=%d", w.Code, w.Body.String(), h.admitted, h.unlinked) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == homeChoiceCookie { |
| + t.Fatal("a proof was issued over a live session") |
| + } |
| } |
| bridgeNoSession(t, f.b, w) |
| } |
| +// A guest's local account never blocks a new member's first sign-in: |
| +// the roster decides, not whether local accounts exist. |
| +func TestGuestLocalAccountNeverBlocksANewMember(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + f.local(t, "guest@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| + f.signInNew(t, "pr_member") |
| + if h.count(t) != 1 { |
| + t.Fatal("member was not admitted beside a guest's local account") |
| + } |
| +} |
| + |
| // Connect's same-person rule holds for Home-only people: a known Home-only |
| // member arriving over somebody else's live session is 403, and that |
| // session survives. |
| func TestKnownHomeOnlyArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| - if w := f.finishAs(t, "pr_member", nil); w.Code != 303 { |
| - t.Fatalf("allocate=%d", w.Code) |
| - } |
| + f.signInNew(t, "pr_member") |
| local := f.local(t, "x@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| w := f.finishAs(t, "pr_member", []*http.Cookie{local}) |
| if w.Code != 403 || w.Body.String() != "failed" { |
| @@ -221,19 +519,19 @@ func TestKnownHomeOnlyArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| } |
| } |
| -// A linked subject is the linked account: HomeOnly is not consulted and |
| -// nothing is allocated, and the link flow never reaches Unlinked. |
| +// A linked subject is the linked account: no hook decides anything, and |
| +// the link flow never reaches them. |
| func TestLinkedSubjectNeverReachesTheHooks(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| f.link(t, local, "pr_linked") |
| - if h.unlinked != 0 { |
| - t.Fatal("the link flow asked Unlinked") |
| + if h.unlinked != 0 || h.admitted != 0 { |
| + t.Fatal("the link flow asked a team hook") |
| } |
| before := h.homeOnly |
| w := f.finishAs(t, "pr_linked", nil) |
| - if w.Code != 303 || h.unlinked != 0 || h.homeOnly != before || h.count(t) != 0 { |
| - t.Fatalf("linked sign-in=%d unlinked=%d homeOnly=%d", w.Code, h.unlinked, h.homeOnly-before) |
| + if w.Code != 303 || h.unlinked != 0 || h.admitted != 0 || h.homeOnly != before || h.count(t) != 0 { |
| + t.Fatalf("linked sign-in=%d unlinked=%d admitted=%d homeOnly=%d", w.Code, h.unlinked, h.admitted, h.homeOnly-before) |
| } |
| p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{bridgeCookie(t, w, f.b.sessionCookie)})) |
| if err != nil || p.Label != "one@example.com" { |
| @@ -242,8 +540,8 @@ func TestLinkedSubjectNeverReachesTheHooks(t *testing.T) { |
| } |
| // Malformed cookies are still connect's refusals with the hooks set: the |
| -// shape checks are shared, and none reaches Unlinked. |
| -func TestUnlinkedKeepsConnectsCookieChecks(t *testing.T) { |
| +// shape checks are shared, and none reaches a team hook. |
| +func TestTeamHooksKeepConnectsCookieChecks(t *testing.T) { |
| f, h := newHomeOnlyFixture(t) |
| pending, nonce := f.start(t, nil, "/") |
| inbox := f.callback(t, "pr_member", nonce, time.Now().Add(-time.Minute)) |
| @@ -257,11 +555,28 @@ func TestUnlinkedKeepsConnectsCookieChecks(t *testing.T) { |
| w := httptest.NewRecorder() |
| f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", append(cookies, pending, inbox))) |
| if w.Code == 303 { |
| - t.Fatalf("%s: minted", name) |
| + t.Fatalf("%s: answered %q", name, w.Header().Get("Location")) |
| } |
| bridgeNoSession(t, f.b, w) |
| } |
| + if h.unlinked != 0 || h.admitted != 0 || h.count(t) != 0 { |
| + t.Fatal("a malformed cookie reached a team hook") |
| + } |
| +} |
| + |
| +// Signing out ends a pending choice: the proof row goes, not just the cookie. |
| +func TestSignoutDropsAPendingChoice(t *testing.T) { |
| + f, h := newHomeOnlyFixture(t) |
| + routes := f.routes(t) |
| + proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) |
| + r := httptest.NewRequest(http.MethodPost, bridgeOrigin+"/signout", nil) |
| + r.AddCookie(proof) |
| + routes.Signout(httptest.NewRecorder(), r) |
| + // The browser kept a copy of the cookie: it chooses nothing. |
| + if w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); w.Code != 403 { |
| + t.Fatalf("choice after sign-out=%d", w.Code) |
| + } |
| if h.unlinked != 0 || h.count(t) != 0 { |
| - t.Fatal("a malformed cookie reached Unlinked") |
| + t.Fatal("a signed-out choice allocated") |
| } |
| } |
diff --git a/connect/view.go b/connect/view.go| index d4bcfb8..611c4aa 100644 |
| --- a/connect/view.go |
| +++ b/connect/view.go |
| @@ -70,10 +70,16 @@ func Page(state, label string, translate ...func(string) string) PageData { |
| // address, so the Oficina account cannot be named, only the local one. |
| // The unknown state says what signing in will do, because it now does it: |
| // local sign-in resumes the link (localLinkNavigation.Complete). |
| +// |
| +// The choose_* strings are the member choice page (Home spec |
| +// 2026-11-14-oficina-id-native.md §8), which Page does not draw: its two |
| +// buttons carry ChoiceFor's token, so the app renders it with its own |
| +// template from ChoiceFor and these labels. |
| var English = map[string]string{ |
| "signedout_title": "You’re signed out", "signedout_body": "You can sign in again with your Oficina account.", "signedout_action": "Sign in", |
| "start_title": "Connect your Oficina account", "start_body": "Use your Oficina account to sign in to this account. Your content and sharing settings stay as they are.", "start_action": "Connect", "cancel_action": "Back", |
| "confirm_title": "Connect these two accounts?", "confirm_body": "Your Oficina account is confirmed. Connect it to the account below, and you can sign in to that account with Oficina from now on.", "confirm_action": "Connect accounts", |
| "unknown_title": "Oficina account not connected", "unknown_body": "Sign in to your existing account once to connect it to your Oficina account.", "local_action": "Sign in to your existing account", |
| + "choose_title": "Welcome to the team", "choose_body": "Do you already have an account here that signs in with email? Connect it, and your Oficina ID will open it from now on. If you’re new here, continue with Oficina ID.", "choose_connect_action": "Connect my existing account", "choose_new_action": "I’m new here — continue with Oficina ID", |
| "failed_title": "Could not connect accounts", "failed_body": "Return to the app and start again.", "success_title": "Accounts connected", "success_body": "You can now use your Oficina account to sign in to this account.", "documents_action": "Back to the app", "menu_action": "Connect your Oficina account", |
| } |
diff --git a/handoff/native.go b/handoff/native.go| new file mode 100644 |
| index 0000000..889eb6a |
| --- /dev/null |
| +++ b/handoff/native.go |
| @@ -0,0 +1,116 @@ |
| +package handoff |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/assertion" |
| +) |
| + |
| +// The native slice (Home spec 2026-11-14-oficina-id-native.md §7) has no |
| +// browser and so no pending row: a native client proves it requested an |
| +// assertion by holding the verifier behind the challenge it gave Home, and |
| +// Home, not the client, sets the nonce from that challenge. These two |
| +// functions are the whole derivation. Home's assert and every instance's |
| +// NativeExchange use them, so the two sides cannot drift apart. |
| +// |
| +// On the wire every value is unpadded base64url: |
| +// |
| +// verifier = 32 random bytes (43 characters) |
| +// challenge = SHA-256(the verifier's 43 ASCII characters) |
| +// (43 characters) |
| +// nonce = SHA-256("oficina-id/native/v1" || 0x00 || challenge's 32 bytes)[:16] |
| +// (22 characters) |
| +// |
| +// The challenge hashes the verifier string, not its decoded bytes: that is |
| +// the S256 convention rastrillo/native's /native/exchange already uses, and |
| +// the one the Swift client implements. The nonce is cut to 16 bytes because |
| +// an assertion nonce is exactly that (rastrillo assertion: 22 characters of |
| +// 16 bytes). |
| +const nativeNonceContext = "oficina-id/native/v1\x00" |
| + |
| +// NativeChallenge is the challenge for a native verifier, or false unless |
| +// the verifier is the canonical encoding of exactly 32 bytes. |
| +func NativeChallenge(verifier string) (string, bool) { |
| + if _, ok := decode32(verifier); !ok { |
| + return "", false |
| + } |
| + sum := sha256.Sum256([]byte(verifier)) |
| + return base64.RawURLEncoding.EncodeToString(sum[:]), true |
| +} |
| + |
| +// NativeNonce is the nonce Home sets on a native assertion for challenge, |
| +// or false unless the challenge is the canonical encoding of 32 bytes. |
| +// Nothing else may produce a native nonce: a caller-chosen nonce is a |
| +// browser's (/authorize), and NativeExchange accepts only this one. |
| +func NativeNonce(challenge string) (string, bool) { |
| + raw, ok := decode32(challenge) |
| + if !ok { |
| + return "", false |
| + } |
| + sum := sha256.Sum256(append([]byte(nativeNonceContext), raw...)) |
| + return base64.RawURLEncoding.EncodeToString(sum[:16]), true |
| +} |
| + |
| +func decode32(s string) ([]byte, bool) { |
| + if len(s) != 43 { |
| + return nil, false |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(s) |
| + return raw, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == s |
| +} |
| + |
| +// Verify checks an assertion against this store's pinned keys, issuer and |
| +// audience at now. It consumes and writes nothing: a native exchange |
| +// verifies first and reserves the jti only once it has decided to mint. |
| +func (s *Store) Verify(token string, now time.Time) (assertion.Claims, error) { |
| + claims, err := s.verifier.Verify(token, now) |
| + if err != nil { |
| + return assertion.Claims{}, ErrRefused |
| + } |
| + return claims, nil |
| +} |
| + |
| +// Reserve burns an assertion's (iss, jti) in its own short transaction and |
| +// commits before returning, so no caller can hold the writer across it. |
| +// It re-verifies the token, and refuses one whose jti is already reserved |
| +// or is waiting in a browser's inbox. A reserved jti that then produces no |
| +// session costs only a fresh assertion; a jti is never reserved twice, so |
| +// replay stays impossible (the native slice's accepted non-atomicity). |
| +func (s *Store) Reserve(ctx context.Context, token string, now time.Time) (assertion.Claims, error) { |
| + zero := assertion.Claims{} |
| + claims, err := s.Verify(token, now) |
| + if err != nil { |
| + return zero, err |
| + } |
| + tx, _, _, err := s.begin(ctx, now) |
| + if err != nil { |
| + return zero, err |
| + } |
| + defer tx.Rollback() |
| + jti := jtiHash(claims) |
| + var waiting int |
| + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM oficina_handoff_inbox WHERE jti_hash=?`, jti).Scan(&waiting); err != nil { |
| + return zero, ErrStorage |
| + } |
| + if waiting != 0 { |
| + return zero, ErrRefused |
| + } |
| + result, err := tx.ExecContext(ctx, `INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING`, jti, claims.ExpiresAt) |
| + if err != nil { |
| + return zero, ErrStorage |
| + } |
| + rows, err := result.RowsAffected() |
| + if err != nil { |
| + return zero, ErrStorage |
| + } |
| + if rows != 1 { |
| + return zero, ErrRefused |
| + } |
| + if tx.Commit() != nil { |
| + return zero, ErrStorage |
| + } |
| + return claims, nil |
| +} |
diff --git a/handoff/native_test.go b/handoff/native_test.go| new file mode 100644 |
| index 0000000..7f57c29 |
| --- /dev/null |
| +++ b/handoff/native_test.go |
| @@ -0,0 +1,101 @@ |
| +package handoff |
| + |
| +import ( |
| + "context" |
| + "testing" |
| +) |
| + |
| +// A fixed vector, so Home's assert, every instance and the Swift client can |
| +// each check their derivation against the same bytes (verifier = the |
| +// encoding of 0x00..0x1f; the challenge hashes that 43-character string). |
| +func TestNativeNonceVector(t *testing.T) { |
| + const verifier = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" |
| + challenge, ok := NativeChallenge(verifier) |
| + if !ok || challenge != "6oZqdX5MOLq_qBJ8vppAnT4fk6AP8UiP9zX8-Rev_9A" { |
| + t.Fatalf("challenge %q %v", challenge, ok) |
| + } |
| + nonce, ok := NativeNonce(challenge) |
| + if !ok || nonce != "ZVVVj2zbBfhkAIwAOKNylg" || !ValidNonce(nonce) { |
| + t.Fatalf("nonce %q %v", nonce, ok) |
| + } |
| +} |
| + |
| +func TestNativeDerivationRefusesNonCanonicalInput(t *testing.T) { |
| + for _, bad := range []string{ |
| + "", |
| + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", // padded |
| + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh", // 31 bytes |
| + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh9", // non-canonical last character |
| + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh+", // standard alphabet |
| + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8\n", // trailing newline |
| + } { |
| + if _, ok := NativeChallenge(bad); ok { |
| + t.Errorf("NativeChallenge accepted %q", bad) |
| + } |
| + if _, ok := NativeNonce(bad); ok { |
| + t.Errorf("NativeNonce accepted %q", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestVerifyConsumesNothing(t *testing.T) { |
| + f := fresh(t) |
| + token := f.token(t, "ZVVVj2zbBfhkAIwAOKNylg") |
| + for range 2 { |
| + if c, err := f.s.Verify(token, f.now); err != nil || c.Nonce != "ZVVVj2zbBfhkAIwAOKNylg" { |
| + t.Fatal(c, err) |
| + } |
| + } |
| + if count(t, f.db, "oficina_handoff_replay") != 0 { |
| + t.Fatal("Verify wrote a replay row") |
| + } |
| + if _, err := f.s.Verify(token, f.now.Add(10*60e9)); err != ErrRefused { |
| + t.Fatal("expired assertion verified", err) |
| + } |
| +} |
| + |
| +func TestReserveOnceAcrossRestart(t *testing.T) { |
| + f := fresh(t) |
| + ctx := context.Background() |
| + token := f.token(t, "ZVVVj2zbBfhkAIwAOKNylg") |
| + if c, err := f.s.Reserve(ctx, token, f.now); err != nil || c.Subject != "person_123" { |
| + t.Fatal(c, err) |
| + } |
| + if _, err := f.s.Reserve(ctx, token, f.now); err != ErrRefused { |
| + t.Fatal("reserved twice", err) |
| + } |
| + // A new Store over the same database is a restarted process. |
| + again, err := NewStore(f.db, f.s.sealer, f.s.issuer, f.s.audience, map[string][]byte{"k1": f.k.SignPub()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := again.Reserve(ctx, token, f.now); err != ErrRefused { |
| + t.Fatal("reserved again after a restart", err) |
| + } |
| + // And the browser path refuses what the native path reserved. |
| + if _, err := f.s.Receive(ctx, token, f.now); err != ErrRefused { |
| + t.Fatal("browser received a reserved assertion", err) |
| + } |
| +} |
| + |
| +func TestReserveRefusesAWaitingBrowserReceipt(t *testing.T) { |
| + f := fresh(t) |
| + _, nonce := f.pending(t) |
| + token := f.token(t, nonce) |
| + if _, err := f.s.Receive(context.Background(), token, f.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.s.Reserve(context.Background(), token, f.now); err != ErrRefused { |
| + t.Fatal("reserved an assertion waiting in a browser inbox", err) |
| + } |
| +} |
| + |
| +func TestReserveRefusesAnInvalidToken(t *testing.T) { |
| + f := fresh(t) |
| + if _, err := f.s.Reserve(context.Background(), "not-a-token", f.now); err != ErrRefused { |
| + t.Fatal(err) |
| + } |
| + if count(t, f.db, "oficina_handoff_replay") != 0 { |
| + t.Fatal("an invalid token wrote a replay row") |
| + } |
| +} |