oficina / equipo Public

Finish Oficina consent with the person's bearer, not the callback

Fix round 2: consent fixation. Someone could start a consent for
themselves and get another person to approve it, attaching that
person's Oficina apps to the first person's Assistant.

The callback no longer exchanges anything. Peek checks the state
(issued, current, connect's issuer, allowed) without using it up, and
the browser goes to the stored return_to with oficina_state and
oficina_code (or oficina=denied|expired|unavailable), no-store and
Referrer-Policy no-referrer. Base then calls POST /api/v1/assistant/
oficina/connect/finish {state, code} with the person's bearer: the
state is used up on any attempt, a consent started by someone else is
403 forbidden (and nobody can finish it after), and otherwise the code
is exchanged with the server-side PKCE verifier and saved; 200
{status: connected|denied|expired|unavailable}. A consent started in
Equipo is handed to /oficina/connect/done, which finishes it with the
session's person.

Tests: the callback alone saves nothing; another person's bearer is
refused and burns the state; replayed finish and callback are refused
(TestConnectState, TestContractAssistantOficinaCallbackState,
TestContractAssistantOficinaFromEquipo). API doc sentence and its
inventory row updated (pending review). Budgets re-measured:
internal/equipo 21023, internal/equipo/chat 30160, internal/thintest
30568 test lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 86f836c817fa62127a9e5c2849b80eda5cd30a2b parent 4052e5b
11 files changed, +307 −103
  • .rastrillo/budgets.txt +3 −3
  • docs/api/equipo-v1.md +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −1
  • internal/equipo/chat/assistant_http.go +22 −0
  • internal/equipo/chat/http.go +5 −0
  • internal/equipo/chat_wiring.go +1 −1
  • internal/equipo/oficina/connect.go +50 −18
  • internal/equipo/oficina/connect_test.go +48 −20
  • internal/equipo/oficina_connect.go +78 −25
  • internal/thintest/assistant.go +10 −0
  • internal/thintest/assistant_oficina_contract_test.go +88 −34

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 93955dbf..8f5a57a4 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 20970 - Shared web rendering: project correction chips and destination forms beside Roster; the Oficina connection routes, store and Base-driven consent. Measured 20970 source lines.
+size internal/equipo 21023 - Shared web rendering: project correction chips and destination forms beside Roster; the Oficina connection routes, store and Base-driven consent. Measured 21023 source lines.
size internal/wire 6447 - Shared protocol types and Encode; 25 adds placement choices and notebook corrections. Measured 6447 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 30133 - Transactional authority and dispatch stay together; project confirmation, fenced moves, notebook learning, connect cards and the connect route. Measured 30133 source lines.
+size internal/equipo/chat 30160 - Transactional authority and dispatch stay together; project confirmation, fenced moves, notebook learning, connect cards and the connect and finish routes. Measured 30160 source lines.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 11062 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11062 test lines.
-size internal/thintest - 30514 Shared instance harness: placement consent, restart proof, preserved context, responsive browser and Oficina connection contracts. Measured 30514 test lines.
+size internal/thintest - 30568 Shared instance harness: placement consent, restart proof, preserved context, responsive browser and Oficina connection contracts. Measured 30568 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation.
diff --git a/docs/api/equipo-v1.md b/docs/api/equipo-v1.md
index 1e02148a..c958ee45 100644
--- a/docs/api/equipo-v1.md
+++ b/docs/api/equipo-v1.md
@@ -94,7 +94,7 @@ When a turn that answers you starts, a `glance` event may come first: one short
A message has `role` `person` or `assistant`. A turn's `kind` is empty when it answers you, and `team_update` when the Assistant tells you, on its own, what the team did with something you asked for. A `team_update` turn may end with no message: its state is `replied` and its `reply_id` is empty. Cancel a turn in flight with `POST /api/v1/assistant/turns/{id}/cancel` and an empty JSON object. The answer is `202` with the turn's `attempt`, or `409 turn_ended` once the turn has ended.
-A card has `id`, `revision`, `kind`, `state`, `question`, `options`, `links` and `result`. Its kind is `question`, `confirm`, `outcome`, `connect` or `job`. A `job` card has states of its own, below; any other card is `open`, `answered` or `resolved`. `options` and `links` are always arrays, never null. A link has `label` and `url`, and may have `rel`: `rel: "equipo"` marks a link to the job's page in Equipo. A `connect` card asks you to connect something the Assistant needs, such as your Oficina apps: it has no options and one link, which you open in your browser to connect. It is answered by connecting, not through the API, and is `resolved` once you have. The Oficina apps' card link has `rel: "oficina_connect"`: call `POST /api/v1/assistant/oficina/connect` with `{"return_to":"<address on your origin>"}` and send the browser to the `url` it returns. The return address must be on an origin in `EQUIPO_ASSISTANT_HOSTS`, or the answer is `422 invalid_input`. After the consent page the browser comes back to it with `oficina` set to `connected`, `denied`, `expired` or `unavailable`. Answer an open card with `POST /api/v1/assistant/cards/{id}/answer`, one option's `value` and the card's revision:
+A card has `id`, `revision`, `kind`, `state`, `question`, `options`, `links` and `result`. Its kind is `question`, `confirm`, `outcome`, `connect` or `job`. A `job` card has states of its own, below; any other card is `open`, `answered` or `resolved`. `options` and `links` are always arrays, never null. A link has `label` and `url`, and may have `rel`: `rel: "equipo"` marks a link to the job's page in Equipo. A `connect` card asks you to connect something the Assistant needs, such as your Oficina apps: it has no options and one link, which you open in your browser to connect. It is answered by connecting, not through the API, and is `resolved` once you have. The Oficina apps' card link has `rel: "oficina_connect"`: call `POST /api/v1/assistant/oficina/connect` with `{"return_to":"<address on your origin>"}` and send the browser to the `url` it returns. The return address must be on an origin in `EQUIPO_ASSISTANT_HOSTS`, or the answer is `422 invalid_input`. After the consent page the browser comes back to it with `oficina_state` and `oficina_code`, which you pass to `POST /api/v1/assistant/oficina/connect/finish` as `{"state":"…","code":"…"}` with the same person's bearer, within two minutes. The answer is `200` with `status` `connected`, `denied`, `expired` or `unavailable`, or `403 forbidden` when the consent was started by someone else. When the consent fails, the browser comes back with `oficina` set to `denied`, `expired` or `unavailable` instead. Answer an open card with `POST /api/v1/assistant/cards/{id}/answer`, one option's `value` and the card's revision:
```json
{"choice":"Yes","revision":2}
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 698ed5fa..18c4f0c4 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -6688,7 +6688,7 @@ records remain unchanged.
| `oficina.connect.disconnected` | Your Oficina apps are disconnected. Your assistant can no longer use them. | the page after disconnecting the Oficina apps (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED |
| `copyOficinaConfig` | EQUIPO_OFICINA_CONNECT_ORIGIN must be an HTTPS address, with EQUIPO_OFICINA_CONNECT_CLIENT_ID set. | boot error for a refused oficina-connect configuration (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED |
| `copyOficinaCardFailed` | Could not show the card to connect Oficina apps. | log line when the connect card could not be raised (oficina, 2026-11-16) | Runtime; COPY REVIEW REQUIRED |
-| `docs/api/equipo-v1.md / Talk to the Assistant: connect cards` | A `connect` card asks you to connect something the Assistant needs, such as your Oficina apps: it has no options and one link, which you open in your browser to connect. It is answered by connecting, not through the API, and is `resolved` once you have. The Oficina apps' card link has `rel: "oficina_connect"`: call `POST /api/v1/assistant/oficina/connect` with `{"return_to":"<address on your origin>"}` and send the browser to the `url` it returns. The return address must be on an origin in `EQUIPO_ASSISTANT_HOSTS`, or the answer is `422 invalid_input`. After the consent page the browser comes back to it with `oficina` set to `connected`, `denied`, `expired` or `unavailable`. | API doc: the new sentence on connect cards in the card paragraph (oficina, 2026-11-16) | API; COPY REVIEW REQUIRED |
+| `docs/api/equipo-v1.md / Talk to the Assistant: connect cards` | A `connect` card asks you to connect something the Assistant needs, such as your Oficina apps: it has no options and one link, which you open in your browser to connect. It is answered by connecting, not through the API, and is `resolved` once you have. The Oficina apps' card link has `rel: "oficina_connect"`: call `POST /api/v1/assistant/oficina/connect` with `{"return_to":"<address on your origin>"}` and send the browser to the `url` it returns. The return address must be on an origin in `EQUIPO_ASSISTANT_HOSTS`, or the answer is `422 invalid_input`. After the consent page the browser comes back to it with `oficina_state` and `oficina_code`, which you pass to `POST /api/v1/assistant/oficina/connect/finish` as `{"state":"…","code":"…"}` with the same person's bearer, within two minutes. The answer is `200` with `status` `connected`, `denied`, `expired` or `unavailable`, or `403 forbidden` when the consent was started by someone else. When the consent fails, the browser comes back with `oficina` set to `denied`, `expired` or `unavailable` instead. | API doc: the new sentence on connect cards in the card paragraph (oficina, 2026-11-16) | API; COPY REVIEW REQUIRED |
## Task 21
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go
index 64cba9c3..c9ec1971 100644
--- a/internal/equipo/chat/assistant_http.go
+++ b/internal/equipo/chat/assistant_http.go
@@ -48,6 +48,28 @@ func (h *HTTP) MountAssistant(r chi.Router) {
if h.OficinaConnect != nil {
r.Post("/oficina/connect", h.bearer(h.oficinaConnect))
}
+ if h.OficinaFinish != nil {
+ r.Post("/oficina/connect/finish", h.bearer(h.oficinaFinish))
+ }
+}
+
+// oficinaFinish is POST oficina/connect/finish {state, code}: 200
+// {status}, or 403 forbidden when the consent was another person's.
+func (h *HTTP) oficinaFinish(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in struct {
+ State string `json:"state"`
+ Code string `json:"code"`
+ }
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ status, err := h.OficinaFinish(r.Context(), p.Address, in.State, in.Code)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, 200, map[string]string{"status": status})
}
// oficinaConnect is POST oficina/connect {return_to}: 200 {url}, the
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index e7579485..412d1b5e 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -37,6 +37,11 @@ type HTTP struct {
// apps, their browser coming back to returnTo after: the address to
// send it to. Nil when the instance has no oficina-connect.
OficinaConnect func(ctx context.Context, person, returnTo string) (string, error)
+ // OficinaFinish finishes the person's consent with the state and code
+ // connect's callback handed back: a status (connected, denied,
+ // expired, unavailable), or ErrForbidden when the consent was another
+ // person's.
+ OficinaFinish func(ctx context.Context, person, state, code string) (string, error)
}
// thinOr serves thin when it applies to the request, else the earlier
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 36cceedc..e7577293 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -167,7 +167,7 @@ func (s *Store) chatHTTP(authenticate func(*http.Request) (personapi.PersonPrinc
return chat.RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, nil
}}
if s.oficina != nil {
- h.OficinaConnect = s.oficinaConnect
+ h.OficinaConnect, h.OficinaFinish = s.oficinaConnect, s.oficinaFinish
}
return h
}
diff --git a/internal/equipo/oficina/connect.go b/internal/equipo/oficina/connect.go
index cef3e88b..87972f13 100644
--- a/internal/equipo/oficina/connect.go
+++ b/internal/equipo/oficina/connect.go
@@ -57,6 +57,9 @@ var (
ErrUnavailable = errors.New("oficina: connect unavailable")
// ErrConfig: the configuration is incomplete or not allowed.
ErrConfig = errors.New("oficina: invalid configuration")
+ // ErrNotYours: the consent was started for another person. Its
+ // state is used up all the same.
+ ErrNotYours = errors.New("oficina: consent not this person's")
)
// Config is the client as connect registered it.
@@ -223,30 +226,59 @@ func (c *Connector) scopes(ctx context.Context) ([]string, error) {
return out, nil
}
-// Finish completes a consent from the callback's query, with no session:
-// the state alone says whose it is, and must be one Start issued, unused
-// and current, from connect's issuer. An unknown state finishes nobody's
-// (Result empty). The refresh token is stored sealed; the access token
-// kept in memory.
-func (c *Connector) Finish(ctx context.Context, q url.Values) (Result, error) {
+// Peek checks the callback's query without finishing anything: the state
+// must be one Start issued, current, from connect's issuer, and the
+// consent allowed. An unknown state is nobody's (Result empty). A state
+// that fails is used up; one that passes stays for Finish, which a
+// proven person (bearer or session) calls with it and the code. The
+// callback alone never exchanges the code: whoever's browser brings it
+// back, only the person who started the consent can finish it.
+func (c *Connector) Peek(ctx context.Context, q url.Values) (Result, error) {
key := digest(q.Get("state"))
c.mu.Lock()
p, ok := c.pending[key]
- delete(c.pending, key)
+ failed := ok && (!c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin || q.Get("error") != "" || q.Get("code") == "")
+ if failed {
+ delete(c.pending, key)
+ }
c.mu.Unlock()
if !ok {
return Result{}, ErrExpired
}
- res, person := Result{Person: p.person, ReturnTo: p.returnTo}, p.person
- if !c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin {
- return res, c.failed(ctx, person, "state", ErrExpired)
+ res := Result{Person: p.person, ReturnTo: p.returnTo}
+ switch {
+ case !c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin:
+ return res, c.failed(ctx, p.person, "state", ErrExpired)
+ case q.Get("error") != "":
+ return res, c.failed(ctx, p.person, "access_denied", ErrDenied)
+ case q.Get("code") == "":
+ return res, c.failed(ctx, p.person, "state", ErrExpired)
}
- if q.Get("error") != "" {
- return res, c.failed(ctx, person, "access_denied", ErrDenied)
+ return res, nil
+}
+
+// Finish completes person's consent: the state is used up whatever
+// happens, must be one Start issued for this person (ErrNotYours) and
+// current; then the code is exchanged with its PKCE verifier. The
+// refresh token is stored sealed; the access token kept in memory.
+func (c *Connector) Finish(ctx context.Context, person, state, code string) error {
+ key := digest(state)
+ c.mu.Lock()
+ p, ok := c.pending[key]
+ delete(c.pending, key)
+ c.mu.Unlock()
+ if !ok {
+ return ErrExpired
+ }
+ if p.person != person {
+ return c.failed(ctx, person, "not_theirs", ErrNotYours)
+ }
+ if !c.now().Before(p.expires) {
+ return c.failed(ctx, person, "state", ErrExpired)
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
- form.Set("code", q.Get("code"))
+ form.Set("code", code)
form.Set("client_id", c.cfg.ClientID)
form.Set("redirect_uri", c.cfg.Redirect)
form.Set("resource", c.resource())
@@ -256,22 +288,22 @@ func (c *Connector) Finish(ctx context.Context, q url.Values) (Result, error) {
defer lock.Unlock()
tok, err := c.token(ctx, form)
if errors.Is(err, errGrant) {
- return res, c.failed(ctx, person, "invalid_grant", ErrExpired)
+ return c.failed(ctx, person, "invalid_grant", ErrExpired)
}
if err != nil || tok.Refresh == "" {
- return res, c.failed(ctx, person, "unavailable", ErrUnavailable)
+ return c.failed(ctx, person, "unavailable", ErrUnavailable)
}
sealed, err := c.sealer.Seal(Domain, tok.Refresh)
if err != nil {
- return res, err
+ return err
}
if err := c.store.Save(ctx, person, sealed, AuditConnect); err != nil {
- return res, err
+ return err
}
c.mu.Lock()
c.sessions[person] = &session{access: tok.Access, expires: c.now().Add(tok.lifetime()), refresh: tok.Refresh}
c.mu.Unlock()
- return res, nil
+ return nil
}
// failed audits a consent that did not finish and returns err.
diff --git a/internal/equipo/oficina/connect_test.go b/internal/equipo/oficina/connect_test.go
index 510e0854..2fcd6d04 100644
--- a/internal/equipo/oficina/connect_test.go
+++ b/internal/equipo/oficina/connect_test.go
@@ -152,9 +152,13 @@ func (r *rig) consent(t *testing.T, person string) url.Values {
func (r *rig) connect(t *testing.T, person string) {
t.Helper()
- res, err := r.c.Finish(context.Background(), r.consent(t, person))
+ q := r.consent(t, person)
+ res, err := r.c.Peek(context.Background(), q)
if err != nil || res.Person != person || res.ReturnTo != "https://base.example.com/ask" {
- t.Fatalf("finish: %+v %v", res, err)
+ t.Fatalf("peek: %+v %v", res, err)
+ }
+ if err := r.c.Finish(context.Background(), person, q.Get("state"), q.Get("code")); err != nil {
+ t.Fatal(err)
}
}
@@ -222,47 +226,72 @@ func TestConnectPKCE(t *testing.T) {
}
}
-// TestConnectState: a callback needs no session: its state says whose
-// consent it finishes. A state is one use, ten minutes, from connect's
-// issuer; one never issued finishes nobody's. A refusal stores nothing.
+// TestConnectState: the callback's check (Peek) needs a state Start
+// issued, current, from connect's issuer, and exchanges nothing; only
+// the person who started the consent can finish it, once.
func TestConnectState(t *testing.T) {
r := newRig(t)
ctx := context.Background()
q := r.consent(t, "ana@example.com")
- used := url.Values{}
- for k, v := range q {
- used[k] = v
+ for range 2 {
+ if res, err := r.c.Peek(ctx, q); err != nil || res.Person != "ana@example.com" {
+ t.Fatalf("peek: %+v %v", res, err)
+ }
+ }
+ if ex, _ := r.fake.Counts(); ex != 0 || len(r.store.sealed) != 0 {
+ t.Fatalf("the callback's check exchanged %d, stored %v", ex, r.store.sealed)
}
- if res, err := r.c.Finish(ctx, q); err != nil || res.Person != "ana@example.com" {
- t.Fatalf("finish: %+v %v", res, err)
+ // Another person's bearer: refused, and the state is used up.
+ if err := r.c.Finish(ctx, "bo@example.com", q.Get("state"), q.Get("code")); !errors.Is(err, ErrNotYours) {
+ t.Errorf("another person: %v", err)
}
- if res, err := r.c.Finish(ctx, used); !errors.Is(err, ErrExpired) || res.Person != "" {
- t.Errorf("a replayed state: %+v %v", res, err)
+ if err := r.c.Finish(ctx, "ana@example.com", q.Get("state"), q.Get("code")); !errors.Is(err, ErrExpired) {
+ t.Errorf("after another person tried: %v", err)
+ }
+ if ex, _ := r.fake.Counts(); ex != 0 || len(r.store.sealed) != 0 {
+ t.Errorf("exchanged %d, stored %v", ex, r.store.sealed)
+ }
+ if a := r.store.audits(); !strings.Contains(a, "bo@example.com oficina.connect_failed not_theirs") {
+ t.Errorf("audit: %s", a)
+ }
+
+ q = r.consent(t, "ana@example.com")
+ if err := r.c.Finish(ctx, "ana@example.com", q.Get("state"), q.Get("code")); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.c.Finish(ctx, "ana@example.com", q.Get("state"), q.Get("code")); !errors.Is(err, ErrExpired) {
+ t.Errorf("a replayed finish: %v", err)
+ }
+ if res, err := r.c.Peek(ctx, q); !errors.Is(err, ErrExpired) || res.Person != "" {
+ t.Errorf("a used state: %+v %v", res, err)
}
forged := url.Values{"state": {random()}, "code": {"x"}, "iss": {r.fake.URL}}
- if res, err := r.c.Finish(ctx, forged); !errors.Is(err, ErrExpired) || res.Person != "" {
+ if res, err := r.c.Peek(ctx, forged); !errors.Is(err, ErrExpired) || res.Person != "" {
t.Errorf("a state never issued: %+v %v", res, err)
}
q = r.consent(t, "bo@example.com")
q.Set("iss", "https://elsewhere.example.com")
- if res, err := r.c.Finish(ctx, q); !errors.Is(err, ErrExpired) || res.Person != "bo@example.com" || res.ReturnTo == "" {
+ if res, err := r.c.Peek(ctx, q); !errors.Is(err, ErrExpired) || res.Person != "bo@example.com" || res.ReturnTo == "" {
t.Errorf("another issuer: %+v %v", res, err)
}
+ if err := r.c.Finish(ctx, "bo@example.com", q.Get("state"), q.Get("code")); !errors.Is(err, ErrExpired) {
+ t.Errorf("a state that failed the check: %v", err)
+ }
q = r.consent(t, "bo@example.com")
r.clock.add(11 * time.Minute)
- if _, err := r.c.Finish(ctx, q); !errors.Is(err, ErrExpired) {
+ if _, err := r.c.Peek(ctx, q); !errors.Is(err, ErrExpired) {
t.Errorf("an old state: %v", err)
}
r.fake.Deny = true
q = r.consent(t, "bo@example.com")
- if _, err := r.c.Finish(ctx, q); !errors.Is(err, ErrDenied) {
+ if _, err := r.c.Peek(ctx, q); !errors.Is(err, ErrDenied) {
t.Errorf("a refusal: %v", err)
}
- if ex, _ := r.fake.Counts(); ex != 1 || r.store.sealed["bo@example.com"] != "" {
- t.Errorf("exchanged %d, stored %v", ex, r.store.sealed)
+ if r.store.sealed["bo@example.com"] != "" {
+ t.Errorf("stored %v", r.store.sealed)
}
if a := r.store.audits(); !strings.Contains(a, "bo@example.com oficina.connect_failed access_denied") || !strings.Contains(a, "bo@example.com oficina.connect_failed state") {
t.Errorf("audit: %s", a)
@@ -270,8 +299,7 @@ func TestConnectState(t *testing.T) {
// A code the fake refuses stores nothing.
q = r.consent(t, "bo@example.com")
- q.Set("code", "not-the-code")
- if _, err := r.c.Finish(ctx, q); !errors.Is(err, ErrExpired) || r.store.sealed["bo@example.com"] != "" {
+ if err := r.c.Finish(ctx, "bo@example.com", q.Get("state"), "not-the-code"); !errors.Is(err, ErrExpired) || r.store.sealed["bo@example.com"] != "" {
t.Errorf("a bad code: %v %v", err, r.store.sealed)
}
if a := r.store.audits(); !strings.Contains(a, "oficina.connect_failed invalid_grant") {
diff --git a/internal/equipo/oficina_connect.go b/internal/equipo/oficina_connect.go
index 8613ad76..bf9731b3 100644
--- a/internal/equipo/oficina_connect.go
+++ b/internal/equipo/oficina_connect.go
@@ -3,6 +3,7 @@ package equipo
import (
"context"
"errors"
+ "log/slog"
"net"
"net/http"
"net/url"
@@ -189,50 +190,102 @@ func (a *application) oficinaStart(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, dest, http.StatusSeeOther)
}
-// oficinaCallback is connect's redirect back. It needs no session: the
-// state says whose consent it is (one use, ten minutes, kept here with
-// the PKCE verifier). Connected, the person's lists are read afresh and
-// their connect card settled. The browser goes to the return address
-// Base gave, with oficina=<result>, or to the Equipo page for a consent
-// started there; a state never issued, used or unknown goes nowhere.
+// oficinaFinish finishes person's consent with the state and code the
+// callback handed back (the person API, for Base): its status, or
+// chat.ErrForbidden when the consent was another person's.
+func (s *Store) oficinaFinish(ctx context.Context, person, state, code string) (string, error) {
+ if state == "" || code == "" || len(state) > 512 || len(code) > 512 {
+ return "", chat.ErrInvalid
+ }
+ return s.oficinaFinished(ctx, normalizeAddress(person), s.oficina.Finish(ctx, normalizeAddress(person), state, code))
+}
+
+// oficinaFinished is a finished consent's status. Connected, the
+// person's lists are read afresh and their connect card settled.
+func (s *Store) oficinaFinished(ctx context.Context, person string, err error) (string, error) {
+ switch {
+ case errors.Is(err, oficina.ErrNotYours):
+ return "", chat.ErrForbidden
+ case errors.Is(err, oficina.ErrDenied):
+ return "denied", nil
+ case errors.Is(err, oficina.ErrExpired):
+ return "expired", nil
+ case err != nil:
+ return "unavailable", nil
+ }
+ s.assist.Forget(person)
+ if err := s.Chat().SettleConnect(ctx, person, oficinaProvider); err != nil {
+ slog.Warn(copyOficinaCardFailed, "err", err)
+ }
+ return "connected", nil
+}
+
+// oficinaCallback is connect's redirect back. It needs no session and
+// finishes nothing: it checks the state (Peek) and hands the state and
+// code on to where the consent started, for the person to finish with
+// proof of who they are. For Base that is the return address it gave
+// (oficina_state and oficina_code, or oficina=<result> when the consent
+// failed), and Base finishes with the person's bearer; for a consent
+// started in Equipo, the done page, which finishes with the session. A
+// browser that brings back someone else's consent cannot finish it. A
+// state never issued, used or unknown goes nowhere.
func (a *application) oficinaCallback(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
// The code is in this address: never in a Referer.
w.Header().Set("Referrer-Policy", "no-referrer")
- res, err := a.store.oficina.Finish(r.Context(), r.URL.Query())
+ q := r.URL.Query()
+ res, err := a.store.oficina.Peek(r.Context(), q)
if res.Person == "" {
// Nobody's: plain words, not an Equipo page.
http.Error(w, copyText(oficinaResults["expired"]), http.StatusBadRequest)
return
}
- result := "connected"
+ add := url.Values{}
switch {
case errors.Is(err, oficina.ErrDenied):
- result = "denied"
+ add.Set("oficina", "denied")
case errors.Is(err, oficina.ErrExpired):
- result = "expired"
+ add.Set("oficina", "expired")
case err != nil:
- result = "unavailable"
+ add.Set("oficina", "unavailable")
default:
- a.store.assist.Forget(res.Person)
- if err := a.store.Chat().SettleConnect(r.Context(), res.Person, oficinaProvider); err != nil {
- a.logger.Warn(copyOficinaCardFailed, "err", err)
- }
+ add.Set("oficina_state", q.Get("state"))
+ add.Set("oficina_code", q.Get("code"))
}
- dest := oficinaDonePath + "?result=" + result
- if res.ReturnTo != "" {
- u, _ := url.Parse(res.ReturnTo)
- q := u.Query()
- q.Set("oficina", result)
- u.RawQuery = q.Encode()
- dest = u.String()
+ dest := res.ReturnTo
+ if dest == "" {
+ dest = oficinaDonePath
}
- http.Redirect(w, r, dest, http.StatusSeeOther)
+ u, _ := url.Parse(dest)
+ v := u.Query()
+ for k := range add {
+ v.Set(k, add.Get(k))
+ }
+ u.RawQuery = v.Encode()
+ http.Redirect(w, r, u.String(), http.StatusSeeOther)
}
-// oficinaDone is the Equipo page after a consent started in Equipo.
+// oficinaDone is the Equipo page after a consent started in Equipo: it
+// finishes it with the session's person, or shows how it failed.
func (a *application) oficinaDone(w http.ResponseWriter, r *http.Request) {
- key, ok := oficinaResults[r.URL.Query().Get("result")]
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ q := r.URL.Query()
+ result := q.Get("oficina")
+ if state := q.Get("oficina_state"); state != "" {
+ id, ok := identity.From(r)
+ if !ok {
+ ErrorPage(w, r, http.StatusForbidden, "")
+ return
+ }
+ person := normalizeAddress(id.Address)
+ var err error
+ if result, err = a.store.oficinaFinished(r.Context(), person, a.store.oficina.Finish(r.Context(), person, state, q.Get("oficina_code"))); err != nil {
+ ErrorPage(w, r, http.StatusForbidden, "")
+ return
+ }
+ }
+ key, ok := oficinaResults[result]
if !ok {
ErrorPage(w, r, http.StatusNotFound, "")
return
diff --git a/internal/thintest/assistant.go b/internal/thintest/assistant.go
index 581e8930..5cadb28a 100644
--- a/internal/thintest/assistant.go
+++ b/internal/thintest/assistant.go
@@ -67,3 +67,13 @@ func (a *AssistantClient) OficinaConnect(ctx context.Context, returnTo string) (
err := a.c.do(ctx, http.MethodPost, assistantPath+"/oficina/connect", map[string]string{"return_to": returnTo}, &out)
return out.URL, err
}
+
+// OficinaFinish is POST /api/v1/assistant/oficina/connect/finish: the
+// person finishes the consent connect's callback handed back.
+func (a *AssistantClient) OficinaFinish(ctx context.Context, state, code string) (string, error) {
+ var out struct {
+ Status string `json:"status"`
+ }
+ err := a.c.do(ctx, http.MethodPost, assistantPath+"/oficina/connect/finish", map[string]string{"state": state, "code": code}, &out)
+ return out.Status, err
+}
diff --git a/internal/thintest/assistant_oficina_contract_test.go b/internal/thintest/assistant_oficina_contract_test.go
index 8bd7ef4f..c3c509fd 100644
--- a/internal/thintest/assistant_oficina_contract_test.go
+++ b/internal/thintest/assistant_oficina_contract_test.go
@@ -40,11 +40,42 @@ func newOficinaRig(t *testing.T) *oficinaRig {
// viaBase connects as Base does it: the card's link is Base's route,
// which asks the person API for connect's address with the person's
// bearer and sends the browser there; connect's consent comes back to
-// the instance's callback, with no Equipo session, and on to Base's
-// return address. It returns where the browser ends.
+// the instance's callback, with no Equipo session, which hands the state
+// and code on to Base's return address, saving nothing; Base finishes
+// with the person's bearer. It returns the finish's status.
func (o *oficinaRig) viaBase() string {
o.t.Helper()
- authorize, err := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask?open=1")
+ state, code := o.handBack(o.base.Origin + "/ask?open=1")
+ if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 {
+ o.t.Fatalf("the callback saved %d connections", n)
+ }
+ status, err := o.a.OficinaFinish(o.ctx, state, code)
+ if err != nil {
+ o.t.Fatalf("finish: %v", err)
+ }
+ return status
+}
+
+// handBack starts a consent for returnTo and follows it through
+// connect and the callback: the state and code the callback hands back.
+func (o *oficinaRig) handBack(returnTo string) (state, code string) {
+ o.t.Helper()
+ back := o.callback(returnTo)
+ u, err := url.Parse(back)
+ if err != nil || !strings.HasPrefix(back, strings.SplitN(returnTo, "?", 2)[0]+"?") || u.Query().Get("oficina_state") == "" || u.Query().Get("oficina_code") == "" {
+ o.t.Fatalf("handed back: %q", back)
+ }
+ if ex, _ := o.fake.Counts(); ex != 0 {
+ o.t.Fatalf("the callback exchanged the code")
+ }
+ return u.Query().Get("oficina_state"), u.Query().Get("oficina_code")
+}
+
+// callback starts a consent for returnTo and follows it to where the
+// callback sends the browser, with no session.
+func (o *oficinaRig) callback(returnTo string) string {
+ o.t.Helper()
+ authorize, err := o.a.OficinaConnect(o.ctx, returnTo)
if err != nil || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") {
o.t.Fatalf("start: %q %v", authorize, err)
}
@@ -106,9 +137,16 @@ func (o *oficinaRig) consent(start string) string {
o.t.Fatalf("consent: %d %q", status, callback)
}
status, done, _ := o.anonymous(callback)
- if status != http.StatusSeeOther || done != "/oficina/connect/done?result=connected" {
+ if status != http.StatusSeeOther || !strings.HasPrefix(done, "/oficina/connect/done?") || !strings.Contains(done, "oficina_state=") {
o.t.Fatalf("callback: %d %q", status, done)
}
+ // Without the session that started it, nothing is finished.
+ if _, to, _ := o.anonymous(o.inst.URL + done); strings.HasPrefix(to, "/oficina") {
+ o.t.Fatalf("done without a session: %q", to)
+ }
+ if ex, _ := o.fake.Counts(); ex != 0 {
+ o.t.Fatal("finished without the session")
+ }
status, _, page := o.browse(http.MethodGet, o.inst.URL+done)
if status != http.StatusOK {
o.t.Fatalf("done: %d %s", status, page)
@@ -156,8 +194,8 @@ func TestContractAssistantOficinaConnectCard(t *testing.T) {
_ = json.Unmarshal(raw, &decoded)
noMachinery(t, "k_none", []string{"/tasks/", "Equipo", "equipo"})("the connect card", decoded, false)
- if back := o.viaBase(); back != o.base.Origin+"/ask?oficina=connected&open=1" {
- t.Errorf("back to Base: %q", back)
+ if status := o.viaBase(); status != "connected" {
+ t.Errorf("finish: %q", status)
}
if ex, _ := o.fake.Counts(); ex != 1 {
t.Errorf("exchanges %d", ex)
@@ -179,34 +217,51 @@ func TestContractAssistantOficinaConnectCard(t *testing.T) {
}
}
-// TestContractAssistantOficinaCallbackState: the callback needs no
-// session, and only a state the instance issued finishes anything: once,
-// from connect's issuer. A replayed or forged state connects nothing
-// and goes nowhere; connect's consent refused goes back to Base saying
-// so. The return address must be on an allowed Base origin.
+// TestContractAssistantOficinaCallbackState (consent fixation): the
+// callback needs no session and saves nothing; it hands the state and
+// code back to Base. Only the person who started the consent finishes
+// it, once, with their bearer: another person's bearer is refused (403)
+// and uses the state up. A forged or finished state goes nowhere;
+// connect's consent refused, or from another issuer, goes back to Base
+// saying so. The return address must be on an allowed Base origin.
func TestContractAssistantOficinaCallbackState(t *testing.T) {
o := newOficinaRig(t)
- authorize, err := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask")
- if err != nil {
- t.Fatal(err)
+ ana := o.other("ana@example.com")
+ state, code := o.handBack(o.base.Origin + "/ask")
+ if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 {
+ t.Fatalf("the callback saved %d connections", n)
}
- _, callback, _ := o.browse(http.MethodGet, authorize)
- if status, back, _ := o.anonymous(callback); status != http.StatusSeeOther || back != o.base.Origin+"/ask?oficina=connected" {
- t.Fatalf("callback: %d %q", status, back)
+ var s *ErrStatus
+ if _, err := ana.a.OficinaFinish(o.ctx, state, code); !errors.As(err, &s) || s.Status != http.StatusForbidden || strings.Contains(string(s.Body), Owner) {
+ t.Fatalf("another person's finish: %v", err)
+ }
+ if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" {
+ t.Errorf("after another person tried: %q %v", status, err)
}
- if status, back, page := o.anonymous(callback); status != http.StatusBadRequest || back != "" || strings.Contains(page, "rst-shell") {
- t.Errorf("replayed: %d %q", status, back)
+ if ex, _ := o.fake.Counts(); ex != 0 || o.rows("SELECT count(*) FROM oficina_connections") != 0 {
+ t.Fatalf("exchanged %d", ex)
}
- if status, back, _ := o.anonymous(o.inst.URL + "/oficina/connect/callback?state=" + strings.Repeat("A", 43) + "&code=x&iss=" + url.QueryEscape(o.fake.URL)); status != http.StatusBadRequest || back != "" {
+
+ state, code = o.handBack(o.base.Origin + "/ask")
+ if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "connected" {
+ t.Fatalf("finish: %q %v", status, err)
+ }
+ if status, err := o.a.OficinaFinish(o.ctx, state, code); err != nil || status != "expired" {
+ t.Errorf("replayed finish: %q %v", status, err)
+ }
+ if status, _, _ := o.anonymous(o.inst.URL + "/oficina/connect/callback?state=" + url.QueryEscape(state) + "&code=" + url.QueryEscape(code) + "&iss=" + url.QueryEscape(o.fake.URL)); status != http.StatusBadRequest {
+ t.Errorf("a finished state's callback: %d", status)
+ }
+ if status, back, page := o.anonymous(o.inst.URL + "/oficina/connect/callback?state=" + strings.Repeat("A", 43) + "&code=x&iss=" + url.QueryEscape(o.fake.URL)); status != http.StatusBadRequest || back != "" || strings.Contains(page, "rst-shell") {
t.Errorf("forged: %d %q", status, back)
}
if ex, _ := o.fake.Counts(); ex != 1 {
t.Errorf("exchanges %d", ex)
}
- // Another issuer: not connected, and Base hears it expired.
- authorize, _ = o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask")
- _, callback, _ = o.browse(http.MethodGet, authorize)
+ // Another issuer: not handed on, and Base hears it expired.
+ authorize, _ := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask")
+ _, callback, _ := o.browse(http.MethodGet, authorize)
u, _ := url.Parse(callback)
q := u.Query()
q.Set("iss", "https://elsewhere.example.com")
@@ -215,25 +270,24 @@ func TestContractAssistantOficinaCallbackState(t *testing.T) {
t.Errorf("another issuer: %q", back)
}
o.fake.Deny = true
- authorize, _ = o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask")
- _, callback, _ = o.browse(http.MethodGet, authorize)
- if _, back, _ := o.anonymous(callback); back != o.base.Origin+"/ask?oficina=denied" {
+ if back := o.callback(o.base.Origin + "/ask"); back != o.base.Origin+"/ask?oficina=denied" {
t.Errorf("denied: %q", back)
}
for _, bad := range []string{"https://evil.example.com/ask", strings.Replace(o.base.Origin, "127.0.0.1", "localhost", 1) + "/ask", "/ask", o.base.Origin + "/ask#x", "", "javascript:alert(1)"} {
- var s *ErrStatus
if _, err := o.a.OficinaConnect(o.ctx, bad); !errors.As(err, &s) || s.Status != 422 {
t.Errorf("return to %q: %v", bad, err)
}
}
- // A cookie is not the bearer this route takes.
- req, _ := http.NewRequest(http.MethodPost, o.inst.URL+"/api/v1/assistant/oficina/connect", strings.NewReader(`{"return_to":"`+o.base.Origin+`/ask"}`))
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Origin", o.inst.URL)
- req.AddCookie(o.inst.Cookie())
- if res, err := http.DefaultClient.Do(req); err != nil || res.StatusCode/100 == 2 {
- t.Errorf("cookie accepted: %v %v", res.StatusCode, err)
+ // A cookie is not the bearer these routes take.
+ for _, path := range []string{"/api/v1/assistant/oficina/connect", "/api/v1/assistant/oficina/connect/finish"} {
+ req, _ := http.NewRequest(http.MethodPost, o.inst.URL+path, strings.NewReader(`{"return_to":"`+o.base.Origin+`/ask"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Origin", o.inst.URL)
+ req.AddCookie(o.inst.Cookie())
+ if res, err := http.DefaultClient.Do(req); err != nil || res.StatusCode/100 == 2 {
+ t.Errorf("%s: cookie accepted: %v", path, err)
+ }
}
}