connect: Admit first, and members choose (spec §8, browser path)
Human
Prompt
Implement the consumer (connect) half of slice A: Admit with the member choice on the browser path and the choose page (spec 2026-11-14 §8).
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
New Config.Admit (set with Unlinked and HomeOnly, or none) takes the roster decision for a subject with no person, allocating nothing. Non-members get today's unknown answer byte for byte; an unavailable roster stays 503; a Member gets a sealed, single-use, browser-bound ten-minute choice proof (linkstore migration 0003) and a 303 to /account/home/choose. ChoosePage/ChoosePost: form token is an HMAC of the proof cookie plus an exact same-origin Origin; 'connect' consumes the proof and resumes linking via /signin/local; 'new' refuses with any app session, consumes the proof in its own transaction, rechecks Admit and the link with none open, allocates through Unlinked, re-resolves and mints, landing on /.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+869
−82
connect/api.go+30 −16connect/bridge.go+32 −10connect/choose.go+208 −0connect/linkstore/choice.go+157 −0connect/linkstore/choice_test.go+86 −0connect/linkstore/migrations/0003_choice_proofs.sql+6 −0connect/linkstore/store_test.go+1 −1connect/resolve_on_test.go+1 −3connect/unlinked_test.go+342 −52connect/view.go+6 −0
diff --git a/connect/api.go b/connect/api.go| index 43798a8..fc601d2 100644 |
| --- a/connect/api.go |
| +++ b/connect/api.go |
| @@ -84,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 |
diff --git a/connect/bridge.go b/connect/bridge.go| index 3c0fd9b..8f54642 100644 |
| --- a/connect/bridge.go |
| +++ b/connect/bridge.go |
| @@ -34,6 +34,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 +53,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,7 +72,7 @@ func New(c Config) (*Bridge, error) { |
| if now == nil { |
| now = time.Now |
| } |
| - b := &Bridge{namespace: c.Namespace, keyHash: sha256.Sum256(c.DEK), origin: c.Origin, issuer: c.Issuer, sessionCookie: c.SessionCookie, links: linker, now: now, returnPath: c.ReturnPath, readSession: c.ReadSession, mintSession: c.MintHomeSession, localPerson: c.LookupLocalSession, render: c.Render, unlinked: c.Unlinked, homeOnly: c.HomeOnly} |
| + 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)} |
| cfg := handoff.ConsumerConfig{Store: exchange, ConsumerID: c.ConsumerID, Complete: b.complete, Fail: b.fail, Now: func() time.Time { return b.now() }, CurrentSubject: func(r *http.Request) string { |
| result, _ := r.Context().Value(homeFinishKey{}).(*homeFinishResult) |
| if result != nil && result.session != nil && IsHomeDerived(result.session.Method) { |
| @@ -181,6 +184,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 +226,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 { |
diff --git a/connect/choose.go b/connect/choose.go| new file mode 100644 |
| index 0000000..8ebd952 |
| --- /dev/null |
| +++ b/connect/choose.go |
| @@ -0,0 +1,208 @@ |
| +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()) |
| + setHomeCookie(w, homeChoiceCookie, "", -1) |
| + switch { |
| + case errors.Is(err, linkstore.ErrRefused): |
| + b.fail(w, r, http.StatusForbidden) |
| + return |
| + case err != nil: |
| + b.fail(w, r, http.StatusServiceUnavailable) |
| + return |
| + } |
| + 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/linkstore/choice.go b/connect/linkstore/choice.go| new file mode 100644 |
| index 0000000..d7dc606 |
| --- /dev/null |
| +++ b/connect/linkstore/choice.go |
| @@ -0,0 +1,157 @@ |
| +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 |
| +} |
| + |
| +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..ccacfff |
| --- /dev/null |
| +++ b/connect/linkstore/choice_test.go |
| @@ -0,0 +1,86 @@ |
| +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) |
| + } |
| +} |
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_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/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/unlinked_test.go b/connect/unlinked_test.go| index 99ba7ba..d2e301f 100644 |
| --- a/connect/unlinked_test.go |
| +++ b/connect/unlinked_test.go |
| @@ -6,20 +6,25 @@ 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 |
| @@ -43,6 +48,10 @@ 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.admitted++ |
| + return h.admission |
| + } |
| c.Unlinked = func(ctx context.Context, issuer, subject string) (Person, error) { |
| h.unlinked++ |
| if h.decision != nil { |
| @@ -84,35 +93,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 +187,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 +463,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 +511,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 +532,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 +547,11 @@ 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.count(t) != 0 { |
| - t.Fatal("a malformed cookie reached Unlinked") |
| + if h.unlinked != 0 || h.admitted != 0 || h.count(t) != 0 { |
| + t.Fatal("a malformed cookie reached a team hook") |
| } |
| } |
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", |
| } |