Let Base start the Oficina consent; guard sessions and card settling
Review round 1 (Astra), all four findings:
1. Connecting no longer needs Equipo. POST /api/v1/assistant/oficina/
connect {return_to} (person bearer only) returns connect's consent
address; return_to must be on an EQUIPO_ASSISTANT_HOSTS origin (422
invalid_input otherwise). The state is 256 random bits kept server-side
with the person, PKCE verifier and return address: one use, ten
minutes, connect's issuer. The callback is outside the member session:
it finishes by state alone and redirects to return_to with
oficina=connected|denied|expired|unavailable (Referrer-Policy
no-referrer); an unknown or replayed state gets plain text, no Equipo
page. The card's link is rel "oficina_connect", pointing at the
person's Base host /ask/oficina/connect (Equipo's own start when they
have no host). The session start remains for people in Equipo, ending
on /oficina/connect/done.
2. Connector session fields are read and written only under c.mu; Host
works from a copy. TestConnectHostRejectedRace (run with -race) catches
the old unguarded read.
3. SettleConnect checks the roster in its transaction
(TestContractAssistantOficinaSettleChecksRoster).
4. RaiseConnect reports whether a card is open, and look only tells
the model about a card when there is one.
API doc sentence and its inventory row updated (pending review).
Budgets re-measured: internal/equipo 20970, internal/equipo/chat 30133,
internal/thintest 30514 test lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+502
−113
.rastrillo/budgets.txt+3 −3docs/api/equipo-v1.md+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+1 −1internal/equipo/app.go+5 −1internal/equipo/assist/oficina.go+1 −1internal/equipo/assist/oficina_test.go+12 −3internal/equipo/assist/registry.go+16 −6internal/equipo/chat/assistant_http.go+22 −0internal/equipo/chat/connect.go+12 −6internal/equipo/chat/http.go+4 −0internal/equipo/chat_wiring.go+10 −5internal/equipo/oficina/connect.go+54 −23internal/equipo/oficina/connect_test.go+72 −23internal/equipo/oficina_connect.go+107 −25internal/thintest/assistant.go+11 −0internal/thintest/assistant_oficina_contract_test.go+171 −15
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index c2d6eb42..93955dbf 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 20879 - Shared web rendering: project correction chips and destination forms beside Roster; the Oficina connection routes and store. Measured 20879 source lines. |
| +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/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 30101 - Transactional authority and dispatch stay together; project confirmation, fenced moves, notebook learning and connect cards. Measured 30101 source lines. |
| +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. |
| 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 - 30358 Shared instance harness: placement consent, restart proof, preserved context, responsive browser and Oficina connection contracts. Measured 30358 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. |
| 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 bb64e111..1e02148a 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. 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` 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: |
| ```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 fc4d1483..698ed5fa 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. | 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` 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 | |
| ## Task 21 |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index fe025645..888aedbf 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -260,6 +260,10 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| } else { |
| a.Post("/signout", a.auth.Signout) |
| } |
| + if store.oficina != nil { |
| + // connect's redirect back: the state, not a session, says whose. |
| + a.Get(oficinaCallbackPath, a.oficinaCallback) |
| + } |
| ih := a.invitationHandler() |
| a.Get("/invites/{id}", ih.Page) |
| a.Post("/invites/{id}/accept", ih.Accept) |
| @@ -317,7 +321,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/conversation/turns/{id}/stop", a.chatTurnStop) |
| if store.oficina != nil { |
| r.Get(oficinaStartPath, a.oficinaStart) |
| - r.Get(oficinaCallbackPath, a.oficinaCallback) |
| + r.Get(oficinaDonePath, a.oficinaDone) |
| r.Post(oficinaDisconnectPath, a.oficinaDisconnect) |
| } |
| r.Get("/jobs", a.jobsPage) |
diff --git a/internal/equipo/assist/oficina.go b/internal/equipo/assist/oficina.go| index da033197..4472a1ff 100644 |
| --- a/internal/equipo/assist/oficina.go |
| +++ b/internal/equipo/assist/oficina.go |
| @@ -26,7 +26,7 @@ type Hinter interface { |
| // oficinaHint is look's model-facing line for the Oficina apps while the |
| // person has not connected them. |
| -const oficinaHint = "- not connected: once the person connects their Oficina apps you can use Calendar, Docs, Sheets, Slides, Memoria notes and Calls for them. They now have a card to connect; tell them to use it, then try again." |
| +const oficinaHint = "- not connected: once the person connects their Oficina apps you can use Calendar, Docs, Sheets, Slides, Memoria notes and Calls for them." |
| // oficinaWords are what the Oficina apps do, for matching look's query |
| // while nothing is listed. |
diff --git a/internal/equipo/assist/oficina_test.go b/internal/equipo/assist/oficina_test.go| index 89e8ffd8..1a6432c5 100644 |
| --- a/internal/equipo/assist/oficina_test.go |
| +++ b/internal/equipo/assist/oficina_test.go |
| @@ -229,7 +229,11 @@ func TestOficinaHintWhenNotConnected(t *testing.T) { |
| c := &conn{none: true} |
| r := NewRegistry(&fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_weather", App: "Weather", ReadOnly: true}}}}, NewOficinaProvider("oficina", c, nil)) |
| var hooked []string |
| - r.OnUnconnected(func(_ context.Context, person, provider string) { hooked = append(hooked, person+"/"+provider) }) |
| + raised := true |
| + r.OnUnconnected(func(_ context.Context, person, provider string) bool { |
| + hooked = append(hooked, person+"/"+provider) |
| + return raised |
| + }) |
| ctx := context.Background() |
| for _, q := range []string{"", "calendar", "Docs", "meeting"} { |
| hooked = nil |
| @@ -237,13 +241,18 @@ func TestOficinaHintWhenNotConnected(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if !strings.Contains(out, "(oficina)") || !strings.Contains(out, "not connected") { |
| + if !strings.Contains(out, "(oficina)") || !strings.Contains(out, "not connected") || !strings.Contains(out, "now have a card") { |
| t.Errorf("%q: no hint:\n%s", q, out) |
| } |
| if len(hooked) != 1 || hooked[0] != "p/oficina" { |
| t.Errorf("%q: hook %v", q, hooked) |
| } |
| } |
| + // No card raised: the model is not told there is one. |
| + raised = false |
| + if out, _ := r.Look(ctx, "p", "calendar"); strings.Contains(out, "card") || !strings.Contains(out, "needs connecting") { |
| + t.Errorf("no card:\n%s", out) |
| + } |
| hooked = nil |
| out, _ := r.Look(ctx, "p", "weather") |
| if strings.Contains(out, "oficina") || len(hooked) != 0 { |
| @@ -252,7 +261,7 @@ func TestOficinaHintWhenNotConnected(t *testing.T) { |
| // Connected: no hint, no hook. |
| _, _, connected := oficinaRig(t, "acme") |
| - connected.OnUnconnected(func(context.Context, string, string) { hooked = append(hooked, "x") }) |
| + connected.OnUnconnected(func(context.Context, string, string) bool { hooked = append(hooked, "x"); return true }) |
| out, _ = connected.Look(ctx, "p", "calendar") |
| if strings.Contains(out, "not connected") || !strings.Contains(out, "calendar_free_busy") || len(hooked) != 0 { |
| t.Errorf("connected look:\n%s %v", out, hooked) |
diff --git a/internal/equipo/assist/registry.go b/internal/equipo/assist/registry.go| index 4ae347ad..4becc45a 100644 |
| --- a/internal/equipo/assist/registry.go |
| +++ b/internal/equipo/assist/registry.go |
| @@ -31,12 +31,21 @@ type Registry struct { |
| gen map[string]uint64 // person -> times Forget has run |
| // unconnected is told when look showed a provider's hint |
| // (OnUnconnected). |
| - unconnected func(ctx context.Context, person, provider string) |
| + unconnected func(ctx context.Context, person, provider string) bool |
| } |
| +// The end of a hint's line in look: the person has a card to connect |
| +// the provider (the hook said so), or not. |
| +const ( |
| + hintCard = " They now have a card to connect it; tell them to use it, then try again." |
| + hintNoCard = " Tell them it needs connecting first." |
| +) |
| + |
| // OnUnconnected sets what look tells when it shows a provider's hint: the |
| -// person asked for something it does and has not connected it. |
| -func (r *Registry) OnUnconnected(f func(ctx context.Context, person, provider string)) { |
| +// person asked for something it does and has not connected it. f says |
| +// whether the person now has a card to connect it; look tells the model |
| +// only what f reports. |
| +func (r *Registry) OnUnconnected(f func(ctx context.Context, person, provider string) bool) { |
| r.mu.Lock() |
| r.unconnected = f |
| r.mu.Unlock() |
| @@ -111,13 +120,14 @@ func (r *Registry) Look(ctx context.Context, person, query string) (string, erro |
| if b.Len() > 0 { |
| b.WriteByte('\n') |
| } |
| - b.WriteString(r.providers[i].Name() + " (" + r.providers[i].Name() + ")\n" + text) |
| r.mu.Lock() |
| hook := r.unconnected |
| r.mu.Unlock() |
| - if hook != nil { |
| - hook(ctx, person, r.providers[i].Name()) |
| + end := hintNoCard |
| + if hook != nil && hook(ctx, person, r.providers[i].Name()) { |
| + end = hintCard |
| } |
| + b.WriteString(r.providers[i].Name() + " (" + r.providers[i].Name() + ")\n" + text + end) |
| continue |
| } |
| var apps []string |
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go| index b6b65f93..64cba9c3 100644 |
| --- a/internal/equipo/chat/assistant_http.go |
| +++ b/internal/equipo/chat/assistant_http.go |
| @@ -45,6 +45,28 @@ func (h *HTTP) MountAssistant(r chi.Router) { |
| r.Put("/host", h.bearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| h.assistantHost(w, r, p, lane) |
| })) |
| + if h.OficinaConnect != nil { |
| + r.Post("/oficina/connect", h.bearer(h.oficinaConnect)) |
| + } |
| +} |
| + |
| +// oficinaConnect is POST oficina/connect {return_to}: 200 {url}, the |
| +// address of connect's consent page for the person, whose browser comes |
| +// back to return_to (on an allowed Base origin, or 422 invalid_input). |
| +func (h *HTTP) oficinaConnect(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in struct { |
| + ReturnTo string `json:"return_to"` |
| + } |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + url, err := h.OficinaConnect(r.Context(), p.Address, in.ReturnTo) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, 200, map[string]string{"url": url}) |
| } |
| // warmAssistant asks the person's runner to warm their Assistant: Base |
diff --git a/internal/equipo/chat/connect.go b/internal/equipo/chat/connect.go| index df4d7cef..71013587 100644 |
| --- a/internal/equipo/chat/connect.go |
| +++ b/internal/equipo/chat/connect.go |
| @@ -20,12 +20,13 @@ type ConnectCard struct { |
| // RaiseConnect shows the person card in the Assistant lane, unless one |
| // for the same provider is open. Raised from a call (look's), it belongs |
| // to the call's turn, and only a turn the person started raises one. |
| -func (s *Store) RaiseConnect(ctx context.Context, person string, card ConnectCard) error { |
| +// open says the person has an open card for the provider now. |
| +func (s *Store) RaiseConnect(ctx context.Context, person string, card ConnectCard) (open bool, err error) { |
| turn := "" |
| if row, ok := callFrom(ctx); ok { |
| turn = row.TurnID |
| } |
| - return s.tx(ctx, func(t *txn) error { |
| + err = s.tx(ctx, func(t *txn) error { |
| if _, err := t.s.authority.Me(t.db, person); err != nil { |
| return err |
| } |
| @@ -38,11 +39,11 @@ func (s *Store) RaiseConnect(ctx context.Context, person string, card ConnectCar |
| return nil |
| } |
| } |
| - var open int64 |
| - if err := t.db.Model(&cardRecord{}).Where("person = ? AND lane = ? AND kind = ? AND name = ? AND state = ?", person, wire.LaneAssistant, wire.CardConnect, card.Provider, wire.CardOpen).Count(&open).Error; err != nil { |
| + var n int64 |
| + if err := t.db.Model(&cardRecord{}).Where("person = ? AND lane = ? AND kind = ? AND name = ? AND state = ?", person, wire.LaneAssistant, wire.CardConnect, card.Provider, wire.CardOpen).Count(&n).Error; err != nil { |
| return err |
| } |
| - if open > 0 { |
| + if open = n > 0; open { |
| return nil |
| } |
| links, err := json.Marshal([]wire.CardLink{card.Link}) |
| @@ -54,14 +55,19 @@ func (s *Store) RaiseConnect(ctx context.Context, person string, card ConnectCar |
| if err := t.db.Create(&c).Error; err != nil { |
| return err |
| } |
| + open = true |
| return t.cardEvent(c) |
| }) |
| + return open && err == nil, err |
| } |
| // SettleConnect resolves the person's open connect cards for provider: |
| -// they connected it. |
| +// they connected it. A person no longer on the roster settles nothing. |
| func (s *Store) SettleConnect(ctx context.Context, person, provider string) error { |
| return s.tx(ctx, func(t *txn) error { |
| + if _, err := t.s.authority.Me(t.db, person); err != nil { |
| + return err |
| + } |
| var cards []cardRecord |
| if err := t.db.Where("person = ? AND lane = ? AND kind = ? AND name = ? AND state = ?", person, wire.LaneAssistant, wire.CardConnect, provider, wire.CardOpen).Find(&cards).Error; err != nil { |
| return err |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index c20dc444..e7579485 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -33,6 +33,10 @@ type HTTP struct { |
| // thin task routes share three paths with them and hand over requests |
| // that are not for a thin task until the slice 7 sweep. |
| Old map[string]http.Handler |
| + // OficinaConnect starts the person's consent to connect their Oficina |
| + // 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) |
| } |
| // 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 e38b4645..36cceedc 100644 |
| --- a/internal/equipo/chat_wiring.go |
| +++ b/internal/equipo/chat_wiring.go |
| @@ -79,14 +79,15 @@ func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry { |
| providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil)) |
| } |
| r := assist.NewRegistry(providers...) |
| - r.OnUnconnected(func(ctx context.Context, person, provider string) { |
| + r.OnUnconnected(func(ctx context.Context, person, provider string) bool { |
| if provider != oficinaProvider { |
| - return |
| + return false |
| } |
| - card := chat.ConnectCard{Provider: oficinaProvider, Question: copyText("assistant.connect.oficina"), Link: wire.CardLink{Label: copyText("assistant.connect.oficina_link"), URL: s.chatOrigin + oficinaStartPath}} |
| - if err := c.RaiseConnect(ctx, person, card); err != nil { |
| + open, err := c.RaiseConnect(ctx, person, chat.ConnectCard{Provider: oficinaProvider, Question: copyText("assistant.connect.oficina"), Link: s.oficinaLink(ctx, person)}) |
| + if err != nil { |
| logger.Warn(copyOficinaCardFailed, "err", err) |
| } |
| + return open |
| }) |
| s.assist = r |
| return r |
| @@ -158,13 +159,17 @@ func runnerRole(tx *gorm.DB, id string) (string, error) { |
| } |
| func (s *Store) chatHTTP(authenticate func(*http.Request) (personapi.PersonPrincipal, error), failure func(http.ResponseWriter, *http.Request, error)) *chat.HTTP { |
| - return &chat.HTTP{Store: s.Chat(), Authenticate: authenticate, Failure: failure, AuthenticateRunner: func(ctx context.Context, token string) (chat.RunnerPrincipal, error) { |
| + h := &chat.HTTP{Store: s.Chat(), Authenticate: authenticate, Failure: failure, AuthenticateRunner: func(ctx context.Context, token string) (chat.RunnerPrincipal, error) { |
| p, err := s.AuthenticateRunner(ctx, token) |
| if err != nil { |
| return chat.RunnerPrincipal{}, err |
| } |
| return chat.RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, nil |
| }} |
| + if s.oficina != nil { |
| + h.OficinaConnect = s.oficinaConnect |
| + } |
| + return h |
| } |
| // RunnerStreamHandler is GET /api/runner/stream. Refused runner frames |
diff --git a/internal/equipo/oficina/connect.go b/internal/equipo/oficina/connect.go| index dc65d9fe..cef3e88b 100644 |
| --- a/internal/equipo/oficina/connect.go |
| +++ b/internal/equipo/oficina/connect.go |
| @@ -88,9 +88,18 @@ type Sealer interface { |
| Open(domain, raw string, v any) error |
| } |
| +// pending is a consent started and not finished: who it is for, the |
| +// PKCE verifier (never sent until the exchange) and where to send the |
| +// browser after. |
| type pending struct { |
| - person, verifier string |
| - expires time.Time |
| + person, verifier, returnTo string |
| + expires time.Time |
| +} |
| + |
| +// Result is whose consent a callback finished, and where its browser |
| +// goes next ("" for none given at Start). |
| +type Result struct { |
| + Person, ReturnTo string |
| } |
| // session is a person's tokens in memory: the access token until it |
| @@ -153,9 +162,11 @@ func (c *Connector) Origin() string { return c.cfg.Origin } |
| func (c *Connector) resource() string { return c.cfg.Origin + "/mcp" } |
| // Start begins a consent for person: the address to send their browser |
| -// to. The scopes are every read and write scope connect offers, and |
| -// offline_access; never a share scope. |
| -func (c *Connector) Start(ctx context.Context, person string) (string, error) { |
| +// to. The state it carries is 256 random bits, kept here with person, |
| +// the verifier and returnTo (the caller checks it): one use, ten |
| +// minutes. The scopes are every read and write scope connect offers, |
| +// and offline_access; never a share scope. |
| +func (c *Connector) Start(ctx context.Context, person, returnTo string) (string, error) { |
| scopes, err := c.scopes(ctx) |
| if err != nil { |
| return "", err |
| @@ -173,7 +184,7 @@ func (c *Connector) Start(ctx context.Context, person string) (string, error) { |
| c.mu.Unlock() |
| return "", ErrUnavailable |
| } |
| - c.pending[digest(state)] = pending{person: person, verifier: verifier, expires: now.Add(pendingTTL)} |
| + c.pending[digest(state)] = pending{person: person, verifier: verifier, returnTo: returnTo, expires: now.Add(pendingTTL)} |
| c.mu.Unlock() |
| q := url.Values{} |
| q.Set("response_type", "code") |
| @@ -212,20 +223,26 @@ func (c *Connector) scopes(ctx context.Context) ([]string, error) { |
| return out, nil |
| } |
| -// Finish completes person's consent from the callback's query: the |
| -// state must be one they started, unused and current, from connect. The |
| -// refresh token is stored sealed; the access token kept in memory. |
| -func (c *Connector) Finish(ctx context.Context, person string, q url.Values) error { |
| +// 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) { |
| key := digest(q.Get("state")) |
| c.mu.Lock() |
| p, ok := c.pending[key] |
| delete(c.pending, key) |
| c.mu.Unlock() |
| - if !ok || p.person != person || !c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin { |
| - return c.failed(ctx, person, "state", ErrExpired) |
| + 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) |
| } |
| if q.Get("error") != "" { |
| - return c.failed(ctx, person, "access_denied", ErrDenied) |
| + return res, c.failed(ctx, person, "access_denied", ErrDenied) |
| } |
| form := url.Values{} |
| form.Set("grant_type", "authorization_code") |
| @@ -239,22 +256,22 @@ func (c *Connector) Finish(ctx context.Context, person string, q url.Values) err |
| defer lock.Unlock() |
| tok, err := c.token(ctx, form) |
| if errors.Is(err, errGrant) { |
| - return c.failed(ctx, person, "invalid_grant", ErrExpired) |
| + return res, c.failed(ctx, person, "invalid_grant", ErrExpired) |
| } |
| if err != nil || tok.Refresh == "" { |
| - return c.failed(ctx, person, "unavailable", ErrUnavailable) |
| + return res, c.failed(ctx, person, "unavailable", ErrUnavailable) |
| } |
| sealed, err := c.sealer.Seal(Domain, tok.Refresh) |
| if err != nil { |
| - return err |
| + return res, err |
| } |
| if err := c.store.Save(ctx, person, sealed, AuditConnect); err != nil { |
| - return err |
| + return res, err |
| } |
| c.mu.Lock() |
| c.sessions[person] = &session{access: tok.Access, expires: c.now().Add(tok.lifetime()), refresh: tok.Refresh} |
| c.mu.Unlock() |
| - return nil |
| + return res, nil |
| } |
| // failed audits a consent that did not finish and returns err. |
| @@ -275,24 +292,36 @@ func (c *Connector) Connected(ctx context.Context, person string) (bool, error) |
| // one in memory until it nearly expires, then a refreshed one, the |
| // rotated refresh token stored first. Not ok when the person has no |
| // connection, or connect no longer accepts it (then it is forgotten). |
| +// |
| +// The per-person lock makes one refresh at a time; a session's fields |
| +// are read and written only under c.mu (Rejected takes only that), so |
| +// Host works from a copy. |
| func (c *Connector) Host(ctx context.Context, person string) (origin, token string, ok bool, err error) { |
| lock := c.lock(person) |
| lock.Lock() |
| defer lock.Unlock() |
| c.mu.Lock() |
| - s := c.sessions[person] |
| + var s session |
| + known := c.sessions[person] != nil |
| + if known { |
| + s = *c.sessions[person] |
| + } |
| c.mu.Unlock() |
| - if s != nil && s.unsaved { |
| + if known && s.unsaved { |
| if err := c.save(ctx, person, s.refresh); err != nil { |
| return "", "", false, err |
| } |
| - s.unsaved = false |
| + c.mu.Lock() |
| + if cur := c.sessions[person]; cur != nil && cur.refresh == s.refresh { |
| + cur.unsaved = false |
| + } |
| + c.mu.Unlock() |
| } |
| - if s != nil && s.access != "" && c.now().Add(early).Before(s.expires) { |
| + if known && s.access != "" && c.now().Add(early).Before(s.expires) { |
| return c.cfg.Origin, s.access, true, nil |
| } |
| refresh := "" |
| - if s != nil { |
| + if known { |
| refresh = s.refresh |
| } else { |
| sealed, err := c.store.Load(ctx, person) |
| @@ -329,7 +358,9 @@ func (c *Connector) Host(ctx context.Context, person string) (origin, token stri |
| if err := c.save(ctx, person, tok.Refresh); err != nil { |
| // Kept in memory, the consumed token is never sent again; |
| // saving is tried again first thing next time. |
| + c.mu.Lock() |
| next.unsaved = true |
| + c.mu.Unlock() |
| return "", "", false, err |
| } |
| return c.cfg.Origin, tok.Access, true, nil |
diff --git a/internal/equipo/oficina/connect_test.go b/internal/equipo/oficina/connect_test.go| index 01f5cc79..510e0854 100644 |
| --- a/internal/equipo/oficina/connect_test.go |
| +++ b/internal/equipo/oficina/connect_test.go |
| @@ -133,7 +133,7 @@ func newRig(t *testing.T) *rig { |
| // which approves itself, to the callback's query. |
| func (r *rig) consent(t *testing.T, person string) url.Values { |
| t.Helper() |
| - start, err := r.c.Start(context.Background(), person) |
| + start, err := r.c.Start(context.Background(), person, "https://base.example.com/ask") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -152,8 +152,9 @@ func (r *rig) consent(t *testing.T, person string) url.Values { |
| func (r *rig) connect(t *testing.T, person string) { |
| t.Helper() |
| - if err := r.c.Finish(context.Background(), person, r.consent(t, person)); err != nil { |
| - t.Fatal(err) |
| + res, err := r.c.Finish(context.Background(), r.consent(t, person)) |
| + if err != nil || res.Person != person || res.ReturnTo != "https://base.example.com/ask" { |
| + t.Fatalf("finish: %+v %v", res, err) |
| } |
| } |
| @@ -178,7 +179,7 @@ func (r *rig) refreshToken(t *testing.T, person string) string { |
| // stored sealed and the access token used. |
| func TestConnectPKCE(t *testing.T) { |
| r := newRig(t) |
| - start, err := r.c.Start(context.Background(), "ana@example.com") |
| + start, err := r.c.Start(context.Background(), "ana@example.com", "") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -221,47 +222,56 @@ func TestConnectPKCE(t *testing.T) { |
| } |
| } |
| -// TestConnectStateIsThePersons: a callback's state is one use, for the |
| -// person who started it, from connect itself; a refusal stores nothing. |
| -func TestConnectStateIsThePersons(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. |
| +func TestConnectState(t *testing.T) { |
| r := newRig(t) |
| ctx := context.Background() |
| q := r.consent(t, "ana@example.com") |
| - if err := r.c.Finish(ctx, "bo@example.com", q); !errors.Is(err, ErrExpired) { |
| - t.Errorf("another person's state: %v", err) |
| + used := url.Values{} |
| + for k, v := range q { |
| + used[k] = v |
| + } |
| + if res, err := r.c.Finish(ctx, q); err != nil || res.Person != "ana@example.com" { |
| + t.Fatalf("finish: %+v %v", res, err) |
| } |
| - if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| - t.Errorf("a state tried by another person stays usable: %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) |
| + } |
| + 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 != "" { |
| + t.Errorf("a state never issued: %+v %v", res, err) |
| } |
| - q = r.consent(t, "ana@example.com") |
| + q = r.consent(t, "bo@example.com") |
| q.Set("iss", "https://elsewhere.example.com") |
| - if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| - t.Errorf("another issuer: %v", err) |
| + if res, err := r.c.Finish(ctx, q); !errors.Is(err, ErrExpired) || res.Person != "bo@example.com" || res.ReturnTo == "" { |
| + t.Errorf("another issuer: %+v %v", res, err) |
| } |
| - q = r.consent(t, "ana@example.com") |
| + q = r.consent(t, "bo@example.com") |
| r.clock.add(11 * time.Minute) |
| - if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| + if _, err := r.c.Finish(ctx, q); !errors.Is(err, ErrExpired) { |
| t.Errorf("an old state: %v", err) |
| } |
| r.fake.Deny = true |
| - q = r.consent(t, "ana@example.com") |
| - if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrDenied) { |
| + q = r.consent(t, "bo@example.com") |
| + if _, err := r.c.Finish(ctx, q); !errors.Is(err, ErrDenied) { |
| t.Errorf("a refusal: %v", err) |
| } |
| - if ex, _ := r.fake.Counts(); ex != 0 || len(r.store.sealed) != 0 { |
| + if ex, _ := r.fake.Counts(); ex != 1 || r.store.sealed["bo@example.com"] != "" { |
| t.Errorf("exchanged %d, stored %v", ex, r.store.sealed) |
| } |
| - if a := r.store.audits(); !strings.Contains(a, "oficina.connect_failed access_denied") || !strings.Contains(a, "oficina.connect_failed state") { |
| + 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) |
| } |
| - // A code the fake refuses (a verifier it does not match) stores nothing. |
| - q = r.consent(t, "ana@example.com") |
| + // 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, "ana@example.com", q); !errors.Is(err, ErrExpired) || len(r.store.sealed) != 0 { |
| + if _, err := r.c.Finish(ctx, q); !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") { |
| @@ -269,6 +279,45 @@ func TestConnectStateIsThePersons(t *testing.T) { |
| } |
| } |
| +// TestConnectHostRejectedRace: Rejected while Host runs never makes Host |
| +// answer ok without a token (run with -race). |
| +func TestConnectHostRejectedRace(t *testing.T) { |
| + r := newRig(t) |
| + r.connect(t, "ana@example.com") |
| + done := make(chan struct{}) |
| + var rejecting sync.WaitGroup |
| + for range 4 { |
| + rejecting.Add(1) |
| + go func() { |
| + defer rejecting.Done() |
| + for { |
| + select { |
| + case <-done: |
| + return |
| + default: |
| + r.c.Rejected("ana@example.com") |
| + } |
| + } |
| + }() |
| + } |
| + var hosts sync.WaitGroup |
| + for range 4 { |
| + hosts.Add(1) |
| + go func() { |
| + defer hosts.Done() |
| + for range 200 { |
| + if _, tok, ok, err := r.c.Host(context.Background(), "ana@example.com"); err != nil || !ok || tok == "" { |
| + t.Errorf("host: %q %v %v", tok, ok, err) |
| + return |
| + } |
| + } |
| + }() |
| + } |
| + hosts.Wait() |
| + close(done) |
| + rejecting.Wait() |
| +} |
| + |
| // TestConnectRefreshRotates: an expired access token is refreshed, the |
| // rotated refresh token replaces the stored one, and the consumed one is |
| // never sent again (connect would revoke the connection). |
diff --git a/internal/equipo/oficina_connect.go b/internal/equipo/oficina_connect.go| index 677fabfb..8613ad76 100644 |
| --- a/internal/equipo/oficina_connect.go |
| +++ b/internal/equipo/oficina_connect.go |
| @@ -3,11 +3,17 @@ package equipo |
| import ( |
| "context" |
| "errors" |
| + "net" |
| "net/http" |
| + "net/url" |
| + "slices" |
| + "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| "amadan.net/oficina/equipo/internal/equipo/identity" |
| "amadan.net/oficina/equipo/internal/equipo/oficina" |
| + "amadan.net/oficina/equipo/internal/wire" |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| ) |
| @@ -21,6 +27,7 @@ const ( |
| oficinaStartPath = "/oficina/connect/start" |
| oficinaCallbackPath = "/oficina/connect/callback" |
| oficinaDisconnectPath = "/oficina/connect/disconnect" |
| + oficinaDonePath = "/oficina/connect/done" |
| ) |
| // oficinaConnectionRecord is a person's connection to oficina-connect: |
| @@ -110,16 +117,71 @@ func (o oficinaSealer) Open(domain, raw string, v any) error { |
| return o.s.personDevices().Open(domain, raw, v) |
| } |
| -// oficinaStart sends the signed-in person to connect's consent page. |
| +// oficinaLinkRel marks the connect card's link: Base resolves it |
| +// through POST /api/v1/assistant/oficina/connect (baseConnectPath on the |
| +// person's Base host); with no host registered it is the instance's own |
| +// start, for a person who uses Equipo directly. |
| +const ( |
| + oficinaLinkRel = "oficina_connect" |
| + baseConnectPath = "/ask/oficina/connect" |
| +) |
| + |
| +// oficinaResults are where a consent ended, as the callback reports it |
| +// (oficina=<result> on the return address) and the page shows it. |
| +var oficinaResults = map[string]string{"connected": "oficina.connect.connected", "denied": "oficina.connect.denied", "expired": "oficina.connect.expired", "unavailable": "oficina.connect.unavailable"} |
| + |
| +// oficinaLink is the connect card's one link for person. |
| +func (s *Store) oficinaLink(ctx context.Context, person string) wire.CardLink { |
| + link := wire.CardLink{Label: copyText("assistant.connect.oficina_link"), URL: s.chatOrigin + oficinaStartPath, Rel: oficinaLinkRel} |
| + if origin, _, ok, err := s.Chat().Host(ctx, person); err == nil && ok { |
| + link.URL = origin + baseConnectPath |
| + } |
| + return link |
| +} |
| + |
| +// oficinaConnect starts person's consent for the person API: their |
| +// browser comes back to returnTo, which must be on an allowed Base |
| +// origin. |
| +func (s *Store) oficinaConnect(ctx context.Context, person, returnTo string) (string, error) { |
| + if !s.oficinaReturn(returnTo) { |
| + return "", chat.ErrInvalid |
| + } |
| + dest, err := s.oficina.Start(ctx, normalizeAddress(person), returnTo) |
| + if err != nil { |
| + return "", chat.ErrUnavailable |
| + } |
| + return dest, nil |
| +} |
| + |
| +// oficinaReturn: an absolute https address (http only on loopback), with |
| +// no user or fragment, on an origin in EQUIPO_ASSISTANT_HOSTS. |
| +func (s *Store) oficinaReturn(raw string) bool { |
| + if raw == "" || len(raw) > 2048 || strings.ContainsAny(raw, " \t\r\n\\") { |
| + return false |
| + } |
| + u, err := url.Parse(raw) |
| + if err != nil || u.User != nil || u.Opaque != "" || u.Fragment != "" || u.Hostname() == "" { |
| + return false |
| + } |
| + scheme, host := strings.ToLower(u.Scheme), strings.ToLower(u.Hostname()) |
| + ip := net.ParseIP(host) |
| + if scheme != "https" && (scheme != "http" || host != "localhost" && (ip == nil || !ip.IsLoopback())) { |
| + return false |
| + } |
| + return slices.Contains(lowered(s.chatAssistantHosts), scheme+"://"+strings.ToLower(u.Host)) |
| +} |
| + |
| +// oficinaStart sends the signed-in person to connect's consent page, for |
| +// a person who connects from Equipo itself. |
| func (a *application) oficinaStart(w http.ResponseWriter, r *http.Request) { |
| id, ok := identity.From(r) |
| if !ok { |
| ErrorPage(w, r, http.StatusForbidden, "") |
| return |
| } |
| - dest, err := a.store.oficina.Start(r.Context(), id.Address) |
| + dest, err := a.store.oficina.Start(r.Context(), normalizeAddress(id.Address), "") |
| if err != nil { |
| - a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| return |
| } |
| w.Header().Set("Cache-Control", "no-store") |
| @@ -127,35 +189,55 @@ func (a *application) oficinaStart(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, dest, http.StatusSeeOther) |
| } |
| -// oficinaCallback is connect's redirect back: the same signed-in person |
| -// finishes the consent they started. Connected, their lists are read |
| -// afresh and their connect card is settled. |
| +// 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. |
| func (a *application) oficinaCallback(w http.ResponseWriter, r *http.Request) { |
| - id, ok := identity.From(r) |
| - if !ok { |
| - ErrorPage(w, r, http.StatusForbidden, "") |
| + 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()) |
| + if res.Person == "" { |
| + // Nobody's: plain words, not an Equipo page. |
| + http.Error(w, copyText(oficinaResults["expired"]), http.StatusBadRequest) |
| return |
| } |
| - person := normalizeAddress(id.Address) |
| - switch err := a.store.oficina.Finish(r.Context(), person, r.URL.Query()); { |
| + result := "connected" |
| + switch { |
| case errors.Is(err, oficina.ErrDenied): |
| - a.oficinaPage(w, r, http.StatusOK, "oficina.connect.denied") |
| - return |
| + result = "denied" |
| case errors.Is(err, oficina.ErrExpired): |
| - a.oficinaPage(w, r, http.StatusBadRequest, "oficina.connect.expired") |
| - return |
| - case errors.Is(err, ErrForbidden): |
| - ErrorPage(w, r, http.StatusForbidden, "") |
| - return |
| + result = "expired" |
| case err != nil: |
| - a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| - return |
| + result = "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) |
| + } |
| } |
| - a.store.assist.Forget(person) |
| - if err := a.store.Chat().SettleConnect(r.Context(), person, oficinaProvider); err != nil { |
| - a.logger.Warn(copyOficinaCardFailed, "err", err) |
| + 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() |
| + } |
| + http.Redirect(w, r, dest, http.StatusSeeOther) |
| +} |
| + |
| +// oficinaDone is the Equipo page after a consent started in Equipo. |
| +func (a *application) oficinaDone(w http.ResponseWriter, r *http.Request) { |
| + key, ok := oficinaResults[r.URL.Query().Get("result")] |
| + if !ok { |
| + ErrorPage(w, r, http.StatusNotFound, "") |
| + return |
| } |
| - a.oficinaPage(w, r, http.StatusOK, "oficina.connect.connected") |
| + a.oficinaPage(w, r, http.StatusOK, key) |
| } |
| // oficinaDisconnect revokes the signed-in person's connection at connect |
| @@ -168,7 +250,7 @@ func (a *application) oficinaDisconnect(w http.ResponseWriter, r *http.Request) |
| } |
| person := normalizeAddress(id.Address) |
| if err := a.store.oficina.Disconnect(r.Context(), person); err != nil { |
| - a.oficinaPage(w, r, http.StatusServiceUnavailable, "oficina.connect.unavailable") |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| return |
| } |
| a.store.assist.Forget(person) |
diff --git a/internal/thintest/assistant.go b/internal/thintest/assistant.go| index 16f30fd7..581e8930 100644 |
| --- a/internal/thintest/assistant.go |
| +++ b/internal/thintest/assistant.go |
| @@ -56,3 +56,14 @@ func (a *AssistantClient) Open(ctx context.Context, after int64) (*Stream, error |
| func (a *AssistantClient) PutHost(ctx context.Context, origin, token string) (out wire.AssistantHost, err error) { |
| return out, a.c.do(ctx, http.MethodPut, assistantPath+"/host", wire.AssistantHost{Origin: origin, Token: token}, &out) |
| } |
| + |
| +// OficinaConnect is POST /api/v1/assistant/oficina/connect: the address |
| +// of connect's consent page for this person, whose browser comes back to |
| +// returnTo. |
| +func (a *AssistantClient) OficinaConnect(ctx context.Context, returnTo string) (string, error) { |
| + var out struct { |
| + URL string `json:"url"` |
| + } |
| + err := a.c.do(ctx, http.MethodPost, assistantPath+"/oficina/connect", map[string]string{"return_to": returnTo}, &out) |
| + return out.URL, err |
| +} |
diff --git a/internal/thintest/assistant_oficina_contract_test.go b/internal/thintest/assistant_oficina_contract_test.go| index 0ed36232..8bd7ef4f 100644 |
| --- a/internal/thintest/assistant_oficina_contract_test.go |
| +++ b/internal/thintest/assistant_oficina_contract_test.go |
| @@ -2,6 +2,7 @@ package thintest |
| import ( |
| "encoding/json" |
| + "errors" |
| "io" |
| "net/http" |
| "net/url" |
| @@ -10,6 +11,7 @@ import ( |
| "testing" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -23,12 +25,51 @@ type oficinaRig struct { |
| func newOficinaRig(t *testing.T) *oficinaRig { |
| fake := oficinatest.Start(t) |
| + base := StartFakeBase(t) |
| r := newRigWith(t, func(i *Instance) { |
| + i.AssistantHosts = []string{base.Origin} |
| i.OficinaConnect, i.OficinaClientID = fake.URL, fake.ClientID |
| fake.Redirect = i.URL + "/oficina/connect/callback" |
| }) |
| runner := r.dialAt(wire.ProtocolAssistant) |
| - return &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: runner}, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} |
| + o := &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: runner}, base: base, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} |
| + o.connect(base.Token) |
| + return o |
| +} |
| + |
| +// 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. |
| +func (o *oficinaRig) viaBase() string { |
| + o.t.Helper() |
| + authorize, err := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask?open=1") |
| + if err != nil || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") { |
| + o.t.Fatalf("start: %q %v", authorize, err) |
| + } |
| + status, callback, _ := o.browse(http.MethodGet, authorize) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(callback, o.inst.URL+"/oficina/connect/callback?") { |
| + o.t.Fatalf("consent: %d %q", status, callback) |
| + } |
| + status, back, _ := o.anonymous(callback) |
| + if status != http.StatusSeeOther { |
| + o.t.Fatalf("callback: %d %q", status, back) |
| + } |
| + return back |
| +} |
| + |
| +// anonymous is a GET with no session at all. |
| +func (o *oficinaRig) anonymous(raw string) (int, string, string) { |
| + o.t.Helper() |
| + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + res, err := client.Get(raw) |
| + if err != nil { |
| + o.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + body, _ := io.ReadAll(res.Body) |
| + return res.StatusCode, res.Header.Get("Location"), string(body) |
| } |
| // browse is one browser request with the owner's session, redirects not |
| @@ -64,9 +105,13 @@ func (o *oficinaRig) consent(start string) string { |
| if status != http.StatusSeeOther || !strings.HasPrefix(callback, o.inst.URL+"/oficina/connect/callback?") { |
| o.t.Fatalf("consent: %d %q", status, callback) |
| } |
| - status, _, page := o.browse(http.MethodGet, callback) |
| + status, done, _ := o.anonymous(callback) |
| + if status != http.StatusSeeOther || done != "/oficina/connect/done?result=connected" { |
| + o.t.Fatalf("callback: %d %q", status, done) |
| + } |
| + status, _, page := o.browse(http.MethodGet, o.inst.URL+done) |
| if status != http.StatusOK { |
| - o.t.Fatalf("callback: %d %s", status, page) |
| + o.t.Fatalf("done: %d %s", status, page) |
| } |
| return page |
| } |
| @@ -103,8 +148,7 @@ func TestContractAssistantOficinaConnectCard(t *testing.T) { |
| t.Fatalf("connect cards: %+v", cards) |
| } |
| c := cards[0] |
| - start := o.inst.URL + "/oficina/connect/start" |
| - if c.State != wire.CardOpen || c.Question != "Connect your Oficina apps" || len(c.Links) != 1 || c.Links[0].URL != start || c.Links[0].Label != "Connect" || c.Options == nil { |
| + if c.State != wire.CardOpen || c.Question != "Connect your Oficina apps" || len(c.Links) != 1 || c.Links[0].URL != o.base.Origin+"/ask/oficina/connect" || c.Links[0].Rel != "oficina_connect" || c.Links[0].Label != "Connect" || c.Options == nil { |
| t.Fatalf("card: %+v", c) |
| } |
| raw, _ := json.Marshal(c) |
| @@ -112,9 +156,8 @@ func TestContractAssistantOficinaConnectCard(t *testing.T) { |
| _ = json.Unmarshal(raw, &decoded) |
| noMachinery(t, "k_none", []string{"/tasks/", "Equipo", "equipo"})("the connect card", decoded, false) |
| - page := o.consent(c.Links[0].URL) |
| - if !strings.Contains(page, "Your Oficina apps are connected.") { |
| - t.Errorf("page: %s", page) |
| + if back := o.viaBase(); back != o.base.Origin+"/ask?oficina=connected&open=1" { |
| + t.Errorf("back to Base: %q", back) |
| } |
| if ex, _ := o.fake.Counts(); ex != 1 { |
| t.Errorf("exchanges %d", ex) |
| @@ -131,15 +174,91 @@ func TestContractAssistantOficinaConnectCard(t *testing.T) { |
| t.Errorf("%d connect cards after connecting", n) |
| } |
| - // A callback replayed, or one this person never started, connects |
| - // nothing. |
| - status, _, page := o.browse(http.MethodGet, o.inst.URL+"/oficina/connect/callback?state=nope&code=x&iss="+url.QueryEscape(o.fake.URL)) |
| - if status != http.StatusBadRequest || !strings.Contains(page, "try again") { |
| - t.Errorf("unknown state: %d %s", status, page) |
| + if ex, _ := o.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| +} |
| + |
| +// 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. |
| +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) |
| + } |
| + _, 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) |
| + } |
| + if status, back, page := o.anonymous(callback); status != http.StatusBadRequest || back != "" || strings.Contains(page, "rst-shell") { |
| + t.Errorf("replayed: %d %q", status, back) |
| + } |
| + 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 != "" { |
| + 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) |
| + u, _ := url.Parse(callback) |
| + q := u.Query() |
| + q.Set("iss", "https://elsewhere.example.com") |
| + u.RawQuery = q.Encode() |
| + if _, back, _ := o.anonymous(u.String()); back != o.base.Origin+"/ask?oficina=expired" { |
| + 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" { |
| + 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) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaFromEquipo: a person who uses Equipo |
| +// directly connects through its own start, behind their session, and |
| +// lands on Equipo's page; with no Base host the card links there. |
| +func TestContractAssistantOficinaFromEquipo(t *testing.T) { |
| + fake := oficinatest.Start(t) |
| + r := newRigWith(t, func(i *Instance) { |
| + i.OficinaConnect, i.OficinaClientID = fake.URL, fake.ClientID |
| + fake.Redirect = i.URL + "/oficina/connect/callback" |
| + }) |
| + o := &oficinaRig{opsRig: &opsRig{toolRig: &toolRig{rig: r, runner: r.dialAt(wire.ProtocolAssistant)}, a: r.client.Assistant(), protocol: wire.ProtocolAssistant}, fake: fake} |
| + o.begin("Put lunch in my calendar.") |
| + o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + link := o.connectCards()[0].Links[0] |
| + if link.URL != o.inst.URL+"/oficina/connect/start" || link.Rel != "oficina_connect" { |
| + t.Fatalf("link: %+v", link) |
| + } |
| + if page := o.consent(link.URL); !strings.Contains(page, "Your Oficina apps are connected.") { |
| + t.Errorf("page: %s", page) |
| + } |
| + if _, to, _ := o.anonymous(o.inst.URL + "/oficina/connect/start"); strings.HasPrefix(to, fake.URL) { |
| + t.Error("start without a session") |
| + } |
| } |
| // TestContractAssistantOficinaUse: through use, a read and a write |
| @@ -153,7 +272,7 @@ func TestContractAssistantOficinaUse(t *testing.T) { |
| o.fake.AccessTTL = time.Second |
| o.begin("Book lunch.") |
| o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| - o.consent(o.connectCards()[0].Links[0].URL) |
| + o.viaBase() |
| d := o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "calendar_create_event"}) |
| if d.IsError || strings.Contains(d.Text, "client_id") || strings.Contains(d.Text, `"teams"`) { |
| @@ -223,7 +342,7 @@ func TestContractAssistantOficinaDisconnect(t *testing.T) { |
| o := newOficinaRig(t) |
| o.begin("What is on Friday?") |
| o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| - o.consent(o.connectCards()[0].Links[0].URL) |
| + o.viaBase() |
| if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); res.IsError { |
| t.Fatalf("read: %+v", res) |
| } |
| @@ -270,6 +389,10 @@ func TestContractAssistantOficinaOffByDefault(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + var s *ErrStatus |
| + if _, err := o.a.OficinaConnect(o.ctx, o.base.Origin+"/ask"); !errors.As(err, &s) || s.Status/100 == 2 { |
| + t.Errorf("connect API: %v", err) |
| + } |
| if slices.ContainsFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind == wire.CardConnect }) { |
| t.Errorf("a connect card: %+v", snap.Cards) |
| } |
| @@ -286,3 +409,36 @@ func TestContractAssistantOficinaOffByDefault(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestContractAssistantOficinaSettleChecksRoster: a person removed from |
| +// the roster has their connect card settled by nothing, in the same |
| +// transaction that would settle it. |
| +func TestContractAssistantOficinaSettleChecksRoster(t *testing.T) { |
| + o := newOficinaRig(t) |
| + ana := o.other("ana@example.com") |
| + ana.begin("Put lunch in my calendar.") |
| + ana.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + state := func() string { |
| + var s string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_cards WHERE person = ? AND kind = ?", "ana@example.com", wire.CardConnect).Scan(&s); err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| + } |
| + if state() != wire.CardOpen { |
| + t.Fatal("no open card") |
| + } |
| + m, err := o.inst.Store.Member(o.ctx, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.inst.Store.SetMember(o.ctx, equipo.Actor{Address: Owner}, "ana@example.com", equipo.RoleOwner, false, m.Revision); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.inst.Store.Chat().SettleConnect(o.ctx, "ana@example.com", "oficina"); err == nil { |
| + t.Error("settled for a removed member") |
| + } |
| + if s := state(); s != wire.CardOpen { |
| + t.Errorf("card %s", s) |
| + } |
| +} |