Merge branch 'assistant-oficina' into main
Merge assistant-oficina: the Assistant reads and writes Oficina apps An Oficina provider through oficina-connect, a connect card, and a consent flow Base finishes with the person's bearer. Off until EQUIPO_OFICINA_CONNECT_* are set. Reviewed (Astra), copy approved (arfnqquz6wks4vdyxptv6ditju), CI passed; Paul approved.
30 files changed,
+3,138
−17
.rastrillo/budgets.txt+3 −3docs/api/equipo-v1.md+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+11 −0internal/equipo/app.go+18 −0internal/equipo/assist/http.go+4 −0internal/equipo/assist/oficina.go+225 −0internal/equipo/assist/oficina_test.go+269 −0internal/equipo/assist/operation.go+3 −0internal/equipo/assist/registry.go+60 −4internal/equipo/chat/assistant_http.go+44 −0internal/equipo/chat/assistant_tools.go+1 −1internal/equipo/chat/connect.go+96 −0internal/equipo/chat/http.go+9 −0internal/equipo/chat/lane.go+3 −0internal/equipo/chat_wiring.go+31 −5internal/equipo/config.go+23 −0internal/equipo/copy.go+22 −0internal/equipo/migrations/0089_oficina_connections.sql+4 −0internal/equipo/migrations/schema.sql+1 −0internal/equipo/models.go+3 −1internal/equipo/oficina/connect.go+554 −0internal/equipo/oficina/connect_test.go+495 −0internal/equipo/oficina/oficinatest/fake.go+375 −0internal/equipo/oficina_connect.go+324 −0internal/equipo/staging_mail_test.go+26 −0internal/equipo/store.go+7 −0internal/plan3test/plan3_release_test.go+3 −1internal/thintest/assistant.go+21 −0internal/thintest/assistant_oficina_contract_test.go+498 −0internal/thintest/instance.go+4 −1
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 01c3c075..0ac14367 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 20601 - Shared web rendering: project correction chips and destination forms beside Roster. Measured 20601 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 30035 - Transactional authority and dispatch stay together; job stop after a failed merge or publish. Measured 30035 source lines. |
| +size internal/equipo/chat 30187 - Transactional authority and dispatch stay together; confirmation, fenced moves, notebook learning, Oficina connect and job stops. Measured 30187 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 - 30294 Shared instance harness: placement consent, restart proof, settled job states and responsive browser contracts. Measured 30294 test lines. |
| +size internal/thintest - 30792 Shared instance harness: placement consent, restart proof, preserved context, settled job states, responsive browser and Oficina connection contracts. Measured 30792 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 e0b28e40..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. 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 53548822..89c67da9 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6678,6 +6678,17 @@ records remain unchanged. |
| | `placement.observed` | Observed by Equipo | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| | `placement.forget` | Remove correction | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| | `placement.abandon_help` | You can abandon this move to keep the task here without restarting work. | Project placement | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15) | |
| +| `assistant.connect.oficina` | Connect your Oficina apps | Assistant connect card: its question, raised when the person asks for something the Oficina apps do before connecting them (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `assistant.connect.oficina_link` | Connect | Assistant connect card: the label of its one link, which starts connecting (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `oficina.connect.title` | Oficina apps | the page after connecting or disconnecting the Oficina apps: its title (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `oficina.connect.connected` | Your Oficina apps are connected. You can close this page and carry on in your conversation. | the page once the Oficina apps are connected (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `oficina.connect.denied` | Your Oficina apps were not connected. You can connect them later from your conversation. | the page when the person did not allow the connection (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `oficina.connect.expired` | This took too long or was already used. Use the card in your conversation to try again. | the page when the consent is too old, used, or not this person's (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `oficina.connect.unavailable` | Oficina could not be reached. Try again in a minute. | the page when oficina-connect cannot be reached (oficina, 2026-11-16) | Runtime; COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, 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 APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `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 APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `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 APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| +| `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 APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) | |
| ## Task 21 |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 4a06d0bb..888aedbf 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -3,6 +3,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/chat" |
| "amadan.net/oficina/equipo/internal/equipo/notifications" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| "context" |
| "encoding/json" |
| @@ -170,6 +171,14 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| store.chatExecution, store.chatTestPeople, store.chatOrigin, store.chatAssistantHosts = cfg.ExecutionEnabled, cfg.TestPeople, cfg.Origin, cfg.AssistantHosts |
| // What the Assistant's provider calls could not do, by call id only. |
| store.Chat().SetLogger(logger) |
| + if cfg.OficinaConnectOrigin != "" { |
| + // The Oficina apps, through oficina-connect. |
| + if store.oficina, err = oficina.New(cfg.oficinaConfig(), oficinaStore{store}, oficinaSealer{store}); err != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return nil, errors.New(copyOficinaConfig) |
| + } |
| + store.Chat().SetOperations(store.assistRegistry(logger)) |
| + } |
| if err := store.Bootstrap(context.Background(), cfg.Owners); err != nil { |
| return nil, err |
| } |
| @@ -251,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) |
| @@ -306,6 +319,11 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/conversation/cards/{id}/visibility", a.chatCardVisibility) |
| r.Post("/conversation/cards/{id}/reply", a.chatCardReply) |
| r.Post("/conversation/turns/{id}/stop", a.chatTurnStop) |
| + if store.oficina != nil { |
| + r.Get(oficinaStartPath, a.oficinaStart) |
| + r.Get(oficinaDonePath, a.oficinaDone) |
| + r.Post(oficinaDisconnectPath, a.oficinaDisconnect) |
| + } |
| r.Get("/jobs", a.jobsPage) |
| r.Get("/jobs/{id}", a.jobPage) |
| r.Post("/jobs/{id}/messages", a.jobSend) |
diff --git a/internal/equipo/assist/http.go b/internal/equipo/assist/http.go| index c3dc801c..c9c61835 100644 |
| --- a/internal/equipo/assist/http.go |
| +++ b/internal/equipo/assist/http.go |
| @@ -27,6 +27,10 @@ type httpProvider struct { |
| // 20 seconds and reads at most 256 KiB. When host reports not ok it makes no |
| // request. A nil client means a default one. |
| func NewHTTPProvider(name string, host func(ctx context.Context, person string) (origin, token string, ok bool, err error), client *http.Client) Provider { |
| + return newHTTPProvider(name, host, client) |
| +} |
| + |
| +func newHTTPProvider(name string, host func(ctx context.Context, person string) (origin, token string, ok bool, err error), client *http.Client) *httpProvider { |
| c := http.Client{} |
| if client != nil { |
| c = *client |
diff --git a/internal/equipo/assist/oficina.go b/internal/equipo/assist/oficina.go| new file mode 100644 |
| index 00000000..4472a1ff |
| --- /dev/null |
| +++ b/internal/equipo/assist/oficina.go |
| @@ -0,0 +1,225 @@ |
| +package assist |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "slices" |
| + "strings" |
| +) |
| + |
| +// Connection is a person's connection to oficina-connect: where it is |
| +// and a current access token (not ok when the person has none), and |
| +// Rejected, told when connect refused a token so the next Host gets a |
| +// fresh one. |
| +type Connection interface { |
| + Host(ctx context.Context, person string) (origin, token string, ok bool, err error) |
| + Rejected(person string) |
| +} |
| + |
| +// Hinter is a provider with something to say in look while the person |
| +// has not connected it: ok when query is something it could do. |
| +type Hinter interface { |
| + Hint(query string) (text string, ok bool) |
| +} |
| + |
| +// 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." |
| + |
| +// oficinaWords are what the Oficina apps do, for matching look's query |
| +// while nothing is listed. |
| +var oficinaWords = []string{"oficina", "calendar", "event", "meeting", "schedule", "free", "busy", "agenda", "doc", "document", "write", "sheet", "spreadsheet", "table", "slide", "deck", "presentation", "note", "memoria", "call", "video"} |
| + |
| +// oficinaProvider is the Oficina apps through oficina-connect: one |
| +// provider for every app the person's connection reaches. It speaks the |
| +// HTTP provider's contract to connect's own /api/v1, and adds what |
| +// agent-access leaves to the client: the app (from the scope), the |
| +// client_id key (agent-access's idempotency convention) and the team. |
| +type oficinaProvider struct { |
| + http *httpProvider |
| + conn Connection |
| +} |
| + |
| +// NewOficinaProvider is the provider for the Oficina apps behind conn. |
| +// Only here is a write's client_id inferred as its key (clientIDKeyed): |
| +// other HTTP providers keep needing an explicit one. |
| +func NewOficinaProvider(name string, conn Connection, client *http.Client) Provider { |
| + return &oficinaProvider{http: newHTTPProvider(name, conn.Host, client), conn: conn} |
| +} |
| + |
| +func (p *oficinaProvider) Name() string { return p.http.name } |
| + |
| +// again makes call, and once more when connect refused the token. |
| +func again[T any](p *oficinaProvider, person string, call func() (T, error)) (T, error) { |
| + out, err := call() |
| + var f Failure |
| + if errors.As(err, &f) && f.Code == "unauthenticated" { |
| + p.conn.Rejected(person) |
| + out, err = call() |
| + } |
| + return out, err |
| +} |
| + |
| +func (p *oficinaProvider) List(ctx context.Context, person string) ([]Operation, error) { |
| + ops, err := again(p, person, func() ([]Operation, error) { return p.http.List(ctx, person) }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + teams, err := p.teams(ctx, person) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for i := range ops { |
| + op := &ops[i] |
| + if op.App == "" { |
| + op.App = appOf(op.Scope) |
| + } |
| + op.KeyField, op.Teams = "", nil |
| + if clientIDKeyed(*op) { |
| + op.KeyField = "client_id" |
| + op.Input = schemaWithout(op.Input, "client_id", true) |
| + } |
| + if schemaRequires(op.Input, "team") { |
| + if len(teams) == 1 { |
| + op.Input = schemaWithout(op.Input, "team", false) |
| + } else if len(teams) > 1 { |
| + op.Teams = teams |
| + } |
| + } |
| + } |
| + return ops, nil |
| +} |
| + |
| +// Invoke fills the team when the model gave none and the connection |
| +// has exactly one; with more, the model must choose, and nothing is sent. |
| +func (p *oficinaProvider) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) { |
| + fields := map[string]json.RawMessage{} |
| + if t := strings.TrimSpace(string(input)); t != "" && t != "null" { |
| + if err := json.Unmarshal(input, &fields); err != nil { |
| + return nil, Failure{Code: "invalid_input", Message: "The input must be a JSON object."} |
| + } |
| + } |
| + if _, has := fields["team"]; !has { |
| + teams, err := p.teams(ctx, person) |
| + if err != nil { |
| + return nil, err |
| + } |
| + switch len(teams) { |
| + case 0: |
| + case 1: |
| + fields["team"], _ = json.Marshal(teams[0]) |
| + default: |
| + return nil, Failure{Code: "team_needed", Message: "Choose the team for this in team: one of " + strings.Join(teams, ", ") + "."} |
| + } |
| + } |
| + in, err := json.Marshal(fields) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return again(p, person, func() (json.RawMessage, error) { return p.http.Invoke(ctx, person, operation, in, key) }) |
| +} |
| + |
| +// teams are the connection's teams, as connect reports them. |
| +func (p *oficinaProvider) teams(ctx context.Context, person string) ([]string, error) { |
| + body, err := again(p, person, func() ([]byte, error) { |
| + return p.http.do(ctx, person, http.MethodGet, "/api/v1/connection", nil, "", maxBody) |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var c struct { |
| + Teams []string `json:"teams"` |
| + } |
| + if err := json.Unmarshal(body, &c); err != nil { |
| + return nil, Failure{Code: "bad_response", Message: "The provider's connection was not understood."} |
| + } |
| + return c.Teams, nil |
| +} |
| + |
| +// Hint is the provider's line while the person is not connected: for an |
| +// empty query, or one about something the apps do. |
| +func (p *oficinaProvider) Hint(query string) (string, bool) { |
| + q := strings.ToLower(strings.TrimSpace(query)) |
| + if q == "" { |
| + return oficinaHint, true |
| + } |
| + for _, w := range oficinaWords { |
| + if strings.Contains(q, w) || len(q) >= 3 && strings.Contains(w, q) { |
| + return oficinaHint, true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// appOf is an app's name from an operation's scope: "calendar:write" is |
| +// Calendar. |
| +func appOf(scope string) string { |
| + app, _, _ := strings.Cut(scope, ":") |
| + if app == "" { |
| + return "" |
| + } |
| + return strings.ToUpper(app[:1]) + app[1:] |
| +} |
| + |
| +// schema is the part of a JSON Schema object the inference reads. |
| +type schema struct { |
| + Required []string `json:"required"` |
| + Properties map[string]json.RawMessage `json:"properties"` |
| +} |
| + |
| +// clientIDKeyed: agent-access's idempotency convention, read from the |
| +// descriptor: an idempotent write whose input requires client_id, a |
| +// string that holds a UUID (format uuid, or at most 36 characters, the |
| +// length the apps declare). |
| +func clientIDKeyed(op Operation) bool { |
| + if op.ReadOnly || !op.Idempotent { |
| + return false |
| + } |
| + var s schema |
| + if json.Unmarshal(op.Input, &s) != nil || !slices.Contains(s.Required, "client_id") { |
| + return false |
| + } |
| + var prop struct { |
| + Type string `json:"type"` |
| + Format string `json:"format"` |
| + MaxLength *int `json:"maxLength"` |
| + } |
| + if json.Unmarshal(s.Properties["client_id"], &prop) != nil || prop.Type != "string" { |
| + return false |
| + } |
| + return prop.Format == "uuid" || prop.MaxLength != nil && *prop.MaxLength == 36 |
| +} |
| + |
| +func schemaRequires(raw json.RawMessage, field string) bool { |
| + var s schema |
| + return json.Unmarshal(raw, &s) == nil && slices.Contains(s.Required, field) |
| +} |
| + |
| +// schemaWithout is raw with field no longer required, and, with drop, |
| +// no longer a property either: what the instance fills in itself. Raw |
| +// it cannot read is returned as it is. |
| +func schemaWithout(raw json.RawMessage, field string, drop bool) json.RawMessage { |
| + var s map[string]json.RawMessage |
| + if json.Unmarshal(raw, &s) != nil { |
| + return raw |
| + } |
| + var required []string |
| + if json.Unmarshal(s["required"], &required) == nil && s["required"] != nil { |
| + required = slices.DeleteFunc(required, func(r string) bool { return r == field }) |
| + s["required"], _ = json.Marshal(required) |
| + } |
| + if drop { |
| + var props map[string]json.RawMessage |
| + if json.Unmarshal(s["properties"], &props) == nil && props != nil { |
| + delete(props, field) |
| + s["properties"], _ = json.Marshal(props) |
| + } |
| + } |
| + out, err := json.Marshal(s) |
| + if err != nil { |
| + return raw |
| + } |
| + return out |
| +} |
diff --git a/internal/equipo/assist/oficina_test.go b/internal/equipo/assist/oficina_test.go| new file mode 100644 |
| index 00000000..1a6432c5 |
| --- /dev/null |
| +++ b/internal/equipo/assist/oficina_test.go |
| @@ -0,0 +1,269 @@ |
| +package assist |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| +) |
| + |
| +// conn is a Connection with one token, or none. |
| +type conn struct { |
| + mu sync.Mutex |
| + origin string |
| + tokens []string // handed out in turn; the last one repeats |
| + rejected int |
| + none bool |
| +} |
| + |
| +func (c *conn) Host(context.Context, string) (string, string, bool, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.none { |
| + return "", "", false, nil |
| + } |
| + tok := c.tokens[0] |
| + if len(c.tokens) > 1 { |
| + c.tokens = c.tokens[1:] |
| + } |
| + return c.origin, tok, true, nil |
| +} |
| + |
| +func (c *conn) Rejected(string) { |
| + c.mu.Lock() |
| + c.rejected++ |
| + c.mu.Unlock() |
| +} |
| + |
| +func oficinaRig(t *testing.T, teams ...string) (*oficinatest.Connect, *conn, *Registry) { |
| + t.Helper() |
| + fake := oficinatest.Start(t) |
| + c := &conn{origin: fake.URL, tokens: []string{fake.Grant(teams...)}} |
| + return fake, c, NewRegistry(NewOficinaProvider("oficina", c, nil)) |
| +} |
| + |
| +// TestOficinaKeyedWrites: an agent-access write whose input requires a |
| +// 36-character string client_id is keyed at client_id, and the model is |
| +// not shown the field; a write without one, or not idempotent, stays |
| +// unsupported. The same descriptor from any other HTTP provider keeps |
| +// R4: no key is inferred there. |
| +func TestOficinaKeyedWrites(t *testing.T) { |
| + _, _, r := oficinaRig(t, "acme") |
| + ctx := context.Background() |
| + want := map[string]struct { |
| + key string |
| + run bool |
| + code string |
| + }{ |
| + "calendar_free_busy": {"", true, ""}, |
| + "calendar_create_event": {"client_id", true, ""}, |
| + "docs_append": {"", false, "write_not_supported"}, |
| + "docs_delete": {"client_id", false, "not_yet"}, |
| + "calls_invite": {"client_id", false, "not_yet"}, |
| + } |
| + for name, w := range want { |
| + op, err := r.Describe(ctx, "p", name) |
| + if err != nil { |
| + t.Fatal(name, err) |
| + } |
| + run, code := Decide(op) |
| + if op.KeyField != w.key || run != w.run || code != w.code { |
| + t.Errorf("%s: key %q run %v code %q, want %q %v %q", name, op.KeyField, run, code, w.key, w.run, w.code) |
| + } |
| + if op.App == "" || op.Provider != "oficina" { |
| + t.Errorf("%s: app %q provider %q", name, op.App, op.Provider) |
| + } |
| + if op.KeyField != "" && strings.Contains(string(op.Input), "client_id") { |
| + t.Errorf("%s: the model is shown client_id: %s", name, op.Input) |
| + } |
| + } |
| + if op, _ := r.Describe(ctx, "p", "calendar_create_event"); op.App != "Calendar" { |
| + t.Errorf("app from the scope: %q", op.App) |
| + } |
| + |
| + // Any other HTTP provider: the same descriptors, no key inferred. |
| + fake := oficinatest.Start(t) |
| + tok := fake.Grant("acme") |
| + base := NewRegistry(NewHTTPProvider("base", func(context.Context, string) (string, string, bool, error) { return fake.URL, tok, true, nil }, nil)) |
| + op, err := base.Describe(ctx, "p", "calendar_create_event") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if run, code := Decide(op); op.KeyField != "" || run || code != "write_not_supported" { |
| + t.Errorf("base provider widened: key %q run %v code %q", op.KeyField, run, code) |
| + } |
| +} |
| + |
| +// TestOficinaClientIDKeyed: the inference reads the schema exactly. |
| +func TestOficinaClientIDKeyed(t *testing.T) { |
| + schema := func(prop, required string) json.RawMessage { |
| + return json.RawMessage(`{"type":"object","required":[` + required + `],"properties":{"client_id":` + prop + `}}`) |
| + } |
| + cases := []struct { |
| + name string |
| + op Operation |
| + want bool |
| + }{ |
| + {"length 36", Operation{Idempotent: true, Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, true}, |
| + {"format uuid", Operation{Idempotent: true, Input: schema(`{"type":"string","format":"uuid"}`, `"client_id"`)}, true}, |
| + {"not required", Operation{Idempotent: true, Input: schema(oficinatest.UUIDSchema, ``)}, false}, |
| + {"not idempotent", Operation{Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, false}, |
| + {"read", Operation{ReadOnly: true, Idempotent: true, Input: schema(oficinatest.UUIDSchema, `"client_id"`)}, false}, |
| + {"any string", Operation{Idempotent: true, Input: schema(`{"type":"string"}`, `"client_id"`)}, false}, |
| + {"integer", Operation{Idempotent: true, Input: schema(`{"type":"integer","maxLength":36}`, `"client_id"`)}, false}, |
| + {"no schema", Operation{Idempotent: true}, false}, |
| + } |
| + for _, c := range cases { |
| + if got := clientIDKeyed(c.op); got != c.want { |
| + t.Errorf("%s: %v", c.name, got) |
| + } |
| + } |
| +} |
| + |
| +// TestOficinaInvoke: a write reaches connect with the bearer, the |
| +// person's one team filled in and client_id the UUIDv5 of the ledger |
| +// key, the same on a retry with that key; a read gets no client_id. |
| +func TestOficinaInvoke(t *testing.T) { |
| + fake, c, r := oficinaRig(t, "acme") |
| + ctx := context.Background() |
| + for range 2 { |
| + if _, err := r.Invoke(ctx, "p", "calendar_create_event", json.RawMessage(`{"title":"Lunch","start_local":"2026-11-20T13:00"}`), "turn\x00calendar_create_event\x00h"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"start":"a","end":"b"}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := fake.Calls() |
| + if len(calls) != 3 { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| + key := Key("turn\x00calendar_create_event\x00h") |
| + for _, call := range calls[:2] { |
| + if call.Input["client_id"] != key || call.Input["team"] != "acme" || call.Input["title"] != "Lunch" || call.Bearer != c.tokens[0] { |
| + t.Errorf("write: %+v, want client_id %s", call, key) |
| + } |
| + } |
| + if _, has := calls[2].Input["client_id"]; has || calls[2].Input["team"] != "acme" { |
| + t.Errorf("read: %+v", calls[2]) |
| + } |
| + // The model's own team stands. |
| + if _, err := r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"team":"other","start":"a","end":"b"}`), ""); err == nil { |
| + t.Error("a team outside the connection was accepted") |
| + } |
| + if got := fake.Calls(); got[len(got)-1].Input["team"] != "other" { |
| + t.Errorf("model's team replaced: %+v", got[len(got)-1]) |
| + } |
| +} |
| + |
| +// TestOficinaTeamsToChoose: with more than one team the model is shown |
| +// them in describe and must choose; nothing is sent without a team. |
| +func TestOficinaTeamsToChoose(t *testing.T) { |
| + fake, _, r := oficinaRig(t, "acme", "zeta") |
| + ctx := context.Background() |
| + op, err := r.Describe(ctx, "p", "calendar_free_busy") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(op) |
| + if len(op.Teams) != 2 || !strings.Contains(string(raw), `"teams":["acme","zeta"]`) || !strings.Contains(string(op.Input), `"required":["team"`) { |
| + t.Errorf("describe: %s", raw) |
| + } |
| + _, err = r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"start":"a","end":"b"}`), "") |
| + var f Failure |
| + if !errors.As(err, &f) || f.Code != "team_needed" || !strings.Contains(f.Message, "acme") || !strings.Contains(f.Message, "zeta") { |
| + t.Errorf("no team: %v", err) |
| + } |
| + if n := len(fake.Calls()); n != 0 { |
| + t.Errorf("sent without a team: %d calls", n) |
| + } |
| + if _, err = r.Invoke(ctx, "p", "calendar_free_busy", json.RawMessage(`{"team":"zeta","start":"a","end":"b"}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // One team: required no more, and no list. |
| + _, _, one := oficinaRig(t, "acme") |
| + op, _ = one.Describe(ctx, "p", "calendar_free_busy") |
| + if len(op.Teams) != 0 || strings.Contains(string(op.Input), `"team"]`) || strings.Contains(string(op.Input), `["team"`) { |
| + t.Errorf("one team: teams %v input %s", op.Teams, op.Input) |
| + } |
| +} |
| + |
| +// TestOficinaRefusesDestructiveAndExternal: neither reaches connect. |
| +func TestOficinaRefusesDestructiveAndExternal(t *testing.T) { |
| + fake, _, r := oficinaRig(t, "acme") |
| + for _, name := range []string{"docs_delete", "calls_invite"} { |
| + _, err := r.Invoke(context.Background(), "p", name, json.RawMessage(`{"id":"1","email":"a@b.c"}`), "k") |
| + var f Failure |
| + if !errors.As(err, &f) || f.Code != "not_yet" { |
| + t.Errorf("%s: %v", name, err) |
| + } |
| + } |
| + if n := len(fake.Calls()); n != 0 { |
| + t.Errorf("refused operations reached connect: %d", n) |
| + } |
| +} |
| + |
| +// TestOficinaRejectedTokenRetried: connect refusing the access token |
| +// tells the connection, and the call is made once more with the next. |
| +func TestOficinaRejectedTokenRetried(t *testing.T) { |
| + fake := oficinatest.Start(t) |
| + c := &conn{origin: fake.URL, tokens: []string{"stale-" + strings.Repeat("x", 20), fake.Grant("acme")}} |
| + r := NewRegistry(NewOficinaProvider("oficina", c, nil)) |
| + if _, err := r.Describe(context.Background(), "p", "calendar_free_busy"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.rejected != 1 { |
| + t.Errorf("rejected %d times", c.rejected) |
| + } |
| +} |
| + |
| +// TestOficinaHintWhenNotConnected: look for something an Oficina app |
| +// does, by a person not connected, carries the provider's hint and calls |
| +// the hook once per look; a look for something else does neither. |
| +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 |
| + 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 |
| + out, err := r.Look(ctx, "p", q) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + 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 { |
| + t.Errorf("weather: hint or hook:\n%s %v", out, hooked) |
| + } |
| + |
| + // Connected: no hint, no hook. |
| + _, _, connected := oficinaRig(t, "acme") |
| + 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/operation.go b/internal/equipo/assist/operation.go| index 5613e217..ba875005 100644 |
| --- a/internal/equipo/assist/operation.go |
| +++ b/internal/equipo/assist/operation.go |
| @@ -24,6 +24,9 @@ type Operation struct { |
| App string `json:"app"` |
| Input json.RawMessage `json:"input_schema"` |
| Output json.RawMessage `json:"output_schema"` |
| + // Teams are the teams the model chooses among for the input's team, |
| + // when its provider fills none in itself (the Oficina apps'). |
| + Teams []string `json:"teams,omitempty"` |
| Provider string `json:"-"` |
| // KeyField is where a client idempotency key goes in the input; empty |
diff --git a/internal/equipo/assist/registry.go b/internal/equipo/assist/registry.go| index 4b34dc04..4becc45a 100644 |
| --- a/internal/equipo/assist/registry.go |
| +++ b/internal/equipo/assist/registry.go |
| @@ -3,6 +3,7 @@ package assist |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "strings" |
| "sync" |
| "time" |
| @@ -28,6 +29,26 @@ type Registry struct { |
| mu sync.Mutex |
| cache map[string]map[int]listing // person -> provider index -> list |
| 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) 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. 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() |
| } |
| // NewRegistry returns a registry over providers, listed in the order given. |
| @@ -46,7 +67,13 @@ func (r *Registry) Forget(person string) { |
| // list returns each provider's operations for the person, in provider order. |
| // A provider that fails is left out and its failure is not cached. |
| func (r *Registry) list(ctx context.Context, person string) [][]Operation { |
| - out := make([][]Operation, len(r.providers)) |
| + out, _ := r.listing(ctx, person) |
| + return out |
| +} |
| + |
| +// listing is list with each provider's failure, by index. |
| +func (r *Registry) listing(ctx context.Context, person string) ([][]Operation, []error) { |
| + out, errs := make([][]Operation, len(r.providers)), make([]error, len(r.providers)) |
| for i, p := range r.providers { |
| r.mu.Lock() |
| l, ok := r.cache[person][i] |
| @@ -58,6 +85,7 @@ func (r *Registry) list(ctx context.Context, person string) [][]Operation { |
| } |
| ops, err := p.List(ctx, person) |
| if err != nil { |
| + errs[i] = err |
| continue |
| } |
| for j := range ops { |
| @@ -75,16 +103,33 @@ func (r *Registry) list(ctx context.Context, person string) [][]Operation { |
| r.mu.Unlock() |
| out[i] = ops |
| } |
| - return out |
| + return out, errs |
| } |
| // Look returns model-facing text: one header per app and one line per |
| -// operation, filtered by query when there is one. |
| +// operation, filtered by query when there is one. A provider the person |
| +// has not connected that has a hint for query (Hinter) shows it under |
| +// its name, and OnUnconnected's hook hears of it. |
| func (r *Registry) Look(ctx context.Context, person, query string) (string, error) { |
| q := strings.ToLower(strings.TrimSpace(query)) |
| var b strings.Builder |
| n := 0 |
| - for i, ops := range r.list(ctx, person) { |
| + lists, errs := r.listing(ctx, person) |
| + for i, ops := range lists { |
| + if text, ok := r.hint(i, errs[i], query); ok { |
| + if b.Len() > 0 { |
| + b.WriteByte('\n') |
| + } |
| + r.mu.Lock() |
| + hook := r.unconnected |
| + r.mu.Unlock() |
| + 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 |
| byApp := map[string][]Operation{} |
| for _, op := range ops { |
| @@ -123,6 +168,17 @@ func (r *Registry) Look(ctx context.Context, person, query string) (string, erro |
| return b.String(), nil |
| } |
| +// hint is provider i's hint for query, when its list failed because the |
| +// person has not connected it. |
| +func (r *Registry) hint(i int, err error, query string) (string, bool) { |
| + var f Failure |
| + h, ok := r.providers[i].(Hinter) |
| + if !ok || !errors.As(err, &f) || f.Code != "not_connected" { |
| + return "", false |
| + } |
| + return h.Hint(query) |
| +} |
| + |
| func firstLine(s string) string { |
| s = strings.TrimSpace(s) |
| if i := strings.IndexByte(s, '\n'); i >= 0 { |
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go| index b6b65f93..c9ec1971 100644 |
| --- a/internal/equipo/chat/assistant_http.go |
| +++ b/internal/equipo/chat/assistant_http.go |
| @@ -45,6 +45,50 @@ 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)) |
| + } |
| + 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 |
| +// 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/assistant_tools.go b/internal/equipo/chat/assistant_tools.go| index 01e49d2c..7fb66ae7 100644 |
| --- a/internal/equipo/chat/assistant_tools.go |
| +++ b/internal/equipo/chat/assistant_tools.go |
| @@ -594,7 +594,7 @@ func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.Too |
| } |
| switch row.Name { |
| case wire.ToolLook: |
| - text, err := ops.Look(ctx, row.Person, in.Query) |
| + text, err := ops.Look(withCall(ctx, row), row.Person, in.Query) |
| if err != nil { |
| return s.opFailed(ctx, row.Person, err), false |
| } |
diff --git a/internal/equipo/chat/connect.go b/internal/equipo/chat/connect.go| new file mode 100644 |
| index 00000000..71013587 |
| --- /dev/null |
| +++ b/internal/equipo/chat/connect.go |
| @@ -0,0 +1,96 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// ConnectCard is the Assistant card the instance raises when the person |
| +// asked for something a provider does and has not connected it: the |
| +// question and one link, to start connecting. Provider is kept on the |
| +// card (Name) so it is raised once and settled when they connect. |
| +type ConnectCard struct { |
| + Provider string |
| + Question string |
| + Link wire.CardLink |
| +} |
| + |
| +// 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. |
| +// 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 |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if _, err := t.s.authority.Me(t.db, person); err != nil { |
| + return err |
| + } |
| + if turn != "" { |
| + var kinds []string |
| + if err := t.db.Model(&turnRecord{}).Where("id = ? AND person = ?", turn, person).Pluck("coalesce(kind, '')", &kinds).Error; err != nil { |
| + return err |
| + } |
| + if len(kinds) != 1 || kinds[0] != wire.TurnPerson { |
| + return 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 = n > 0; open { |
| + return nil |
| + } |
| + links, err := json.Marshal([]wire.CardLink{card.Link}) |
| + if err != nil { |
| + return err |
| + } |
| + now := t.now() |
| + c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardConnect, State: wire.CardOpen, TurnID: turn, Question: card.Question, Options: "[]", Links: string(links), Name: card.Provider, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant} |
| + 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. 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 |
| + } |
| + for _, c := range cards { |
| + c.State = wire.CardResolved |
| + if err := t.saveCard(&c); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// connectCardView fills a connect card's link. |
| +func connectCardView(v *wire.AssistantCard, c cardRecord) error { |
| + if c.Links != "" { |
| + if err := json.Unmarshal([]byte(c.Links), &v.Links); err != nil { |
| + return err |
| + } |
| + } |
| + if v.Links == nil { |
| + v.Links = []wire.CardLink{} |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index c20dc444..412d1b5e 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -33,6 +33,15 @@ 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) |
| + // 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/lane.go b/internal/equipo/chat/lane.go| index ac32cf89..2684ba23 100644 |
| --- a/internal/equipo/chat/lane.go |
| +++ b/internal/equipo/chat/lane.go |
| @@ -321,6 +321,9 @@ func (t *txn) assistantCardView(c cardRecord) (wire.AssistantCard, error) { |
| if c.Kind == wire.CardJob { |
| return v, t.jobCardView(&v, c) |
| } |
| + if c.Kind == wire.CardConnect { |
| + return v, connectCardView(&v, c) |
| + } |
| var options []string |
| if c.Options != "" { |
| if err := json.Unmarshal([]byte(c.Options), &options); err != nil { |
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go| index 4640e57a..e7577293 100644 |
| --- a/internal/equipo/chat_wiring.go |
| +++ b/internal/equipo/chat_wiring.go |
| @@ -63,14 +63,36 @@ func (s *Store) Chat() *chat.Store { |
| return false |
| }, |
| }, nil) |
| - // The Assistant's operations: Base's, at the host each person |
| - // registered, then the team's (the hand-off). |
| - c := s.chat.store |
| - c.SetOperations(assist.NewRegistry(assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider())) |
| + s.chat.store.SetOperations(s.assistRegistry(slog.Default())) |
| }) |
| return s.chat.store |
| } |
| +// assistRegistry is the Assistant's operations: Base's, at the host each |
| +// person registered, then the team's (the hand-off), then, with |
| +// oficina-connect configured, the Oficina apps. A look for something |
| +// they do by a person not connected raises the connect card. |
| +func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry { |
| + c := s.chat.store |
| + providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()} |
| + if s.oficina != nil { |
| + providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil)) |
| + } |
| + r := assist.NewRegistry(providers...) |
| + r.OnUnconnected(func(ctx context.Context, person, provider string) bool { |
| + if provider != oficinaProvider { |
| + return false |
| + } |
| + 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 |
| +} |
| + |
| func lowered(in []string) []string { |
| out := make([]string, 0, len(in)) |
| for _, v := range in { |
| @@ -137,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, h.OficinaFinish = s.oficinaConnect, s.oficinaFinish |
| + } |
| + return h |
| } |
| // RunnerStreamHandler is GET /api/runner/stream. Refused runner frames |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index 2febd9db..3ce88767 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/home/connect" |
| "errors" |
| "net" |
| @@ -29,6 +30,14 @@ type Config struct { |
| // host (EQUIPO_ASSISTANT_HOSTS, comma-separated, lowercased): the |
| // Assistant calls no other address. |
| AssistantHosts []string |
| + // OficinaConnectOrigin is oficina-connect's origin |
| + // (EQUIPO_OFICINA_CONNECT_ORIGIN) and OficinaConnectClientID the |
| + // public client it registered for this instance |
| + // (EQUIPO_OFICINA_CONNECT_CLIENT_ID), whose redirect is |
| + // EQUIPO_ORIGIN/oficina/connect/callback. Unset, the Assistant has no |
| + // Oficina apps. |
| + OficinaConnectOrigin string |
| + OficinaConnectClientID string |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| @@ -57,6 +66,9 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| cfg.AssistantHosts = append(cfg.AssistantHosts, origin) |
| } |
| } |
| + if cfg.OficinaConnectOrigin = strings.TrimSpace(getenv("EQUIPO_OFICINA_CONNECT_ORIGIN")); cfg.OficinaConnectOrigin != "" { |
| + cfg.OficinaConnectClientID = strings.TrimSpace(getenv("EQUIPO_OFICINA_CONNECT_CLIENT_ID")) |
| + } |
| for _, suffix := range strings.Split(getenv("EQUIPO_TEST_PEOPLE"), ",") { |
| if suffix = strings.ToLower(strings.TrimSpace(suffix)); suffix != "" { |
| cfg.TestPeople = append(cfg.TestPeople, suffix) |
| @@ -117,9 +129,20 @@ func (cfg Config) validate() error { |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| return errors.New(copyLoggedMailPublic) |
| } |
| + if cfg.OficinaConnectOrigin != "" { |
| + if _, err := oficina.New(cfg.oficinaConfig(), oficinaStore{}, oficinaSealer{}); err != nil { |
| + //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
| + return errors.New(copyOficinaConfig) |
| + } |
| + } |
| return nil |
| } |
| +// oficinaConfig is the oficina-connect client this configuration names. |
| +func (cfg Config) oficinaConfig() oficina.Config { |
| + return oficina.Config{Origin: cfg.OficinaConnectOrigin, ClientID: cfg.OficinaConnectClientID, Redirect: cfg.Origin + oficinaCallbackPath} |
| +} |
| + |
| // Logged sign-in mail is allowed off loopback only for Oficina's staging |
| // app, so the headless suite can sign in. Production origins never are. |
| var stagingMailOrigin = regexp.MustCompile(`^https://equipo-staging(-[a-f0-9]{16})?\.bds\.oncarlos\.com$`) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 5c77ecd6..eb6100a0 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -54,6 +54,13 @@ const ( |
| copyRetriageFailed = "Failed to triage open tasks." // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| ) |
| +// The Oficina apps through oficina-connect: a configuration refused at |
| +// boot, and a connect card that could not be raised (logged). |
| +const ( |
| + copyOficinaConfig = "EQUIPO_OFICINA_CONNECT_ORIGIN must be an HTTPS address, with EQUIPO_OFICINA_CONNECT_CLIENT_ID set." // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + copyOficinaCardFailed = "Could not show the card to connect Oficina apps." // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| +) |
| + |
| // BootLog is the shared diagnostic used by the command entry point. |
| const BootLog = "Equipo could not start." |
| @@ -1644,6 +1651,21 @@ var pageCopy = map[string]string{ |
| "jobs.back": "Back to your conversation", // COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq, unchanged) |
| "jobs.all": "All work from Base", // COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq, unchanged) |
| + // The Assistant's connect card when the person asks for something |
| + // the Oficina apps do before connecting them: the question, and the |
| + // label of its one link, which starts connecting. |
| + "assistant.connect.oficina": "Connect your Oficina apps", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "assistant.connect.oficina_link": "Connect", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + // The page after connecting the Oficina apps (/oficina/connect/...): |
| + // done, refused at the consent page, a consent too old or not this |
| + // person's, the connection service down; and after disconnecting. |
| + "oficina.connect.title": "Oficina apps", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "oficina.connect.connected": "Your Oficina apps are connected. You can close this page and carry on in your conversation.", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "oficina.connect.denied": "Your Oficina apps were not connected. You can connect them later from your conversation.", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "oficina.connect.expired": "This took too long or was already used. Use the card in your conversation to try again.", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "oficina.connect.unavailable": "Oficina could not be reached. Try again in a minute.", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + "oficina.connect.disconnected": "Your Oficina apps are disconnected. Your assistant can no longer use them.", // COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged) |
| + |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.empty |
| "conversation.empty": "Say what you want done. Your coordinator picks the project and tells you, and you can change it.", |
| "conversation.age_minutes": "%d min", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0089_oficina_connections.sql b/internal/equipo/migrations/0089_oficina_connections.sql| new file mode 100644 |
| index 00000000..c6d66587 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0089_oficina_connections.sql |
| @@ -0,0 +1,4 @@ |
| +-- Each person's connection to oficina-connect, the Oficina apps' |
| +-- connection service: their rotating refresh token, sealed with the |
| +-- instance key. Access tokens are never stored. |
| +CREATE TABLE oficina_connections (person text PRIMARY KEY, refresh text, revision integer, created_at datetime, updated_at datetime); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index a76edb4e..29aacb0b 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -710,3 +710,4 @@ ALTER TABLE chat_turns ADD COLUMN create_repo text; |
| ALTER TABLE chat_notebooks ADD COLUMN corrections text; |
| CREATE INDEX chat_task_move ON chat_tasks(creator, move_project) WHERE move_project IS NOT NULL AND move_project <> ''; |
| UPDATE chat_notebooks SET entries = (SELECT json_group_array(json(value)) FROM json_each(chat_notebooks.entries) WHERE NOT (coalesce(json_extract(value, '$.source'), '') = 'own' AND substr(json_extract(value, '$.id'), 1, 2) = 'mv')) WHERE entries IS NOT NULL AND entries <> ''; |
| +CREATE TABLE oficina_connections (person text PRIMARY KEY, refresh text, revision integer, created_at datetime, updated_at datetime); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 2089e253..b9a643c8 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -55,4 +55,6 @@ type projectRequest = setup.ProjectRequest |
| type Specialist = library.Specialist |
| -func init() { Models = append(Models, oficinaid.Models...) } |
| +func init() { |
| + Models = append(append(Models, oficinaid.Models...), &oficinaConnectionRecord{}) |
| +} |
diff --git a/internal/equipo/oficina/connect.go b/internal/equipo/oficina/connect.go| new file mode 100644 |
| index 00000000..87972f13 |
| --- /dev/null |
| +++ b/internal/equipo/oficina/connect.go |
| @@ -0,0 +1,554 @@ |
| +// Package oficina is Equipo's client of oficina-connect, the Oficina |
| +// apps' connection service: a pre-registered public OAuth 2 client with |
| +// S256 PKCE. A person connects once (Start, then Finish at the |
| +// redirect); their rotating refresh token is kept sealed with the |
| +// instance key, their 5-minute access token only in memory. Host gives |
| +// the assist registry's oficina provider a current token; Disconnect |
| +// revokes the connection at connect and forgets it. |
| +package oficina |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// Domain binds a sealed refresh token to its use. |
| +const Domain = "oficina.connect" |
| + |
| +// The audit kinds; their detail is a code, never a token. |
| +const ( |
| + AuditConnect = "oficina.connect" |
| + AuditConnectFailed = "oficina.connect_failed" |
| + AuditRefreshFailed = "oficina.refresh_failed" |
| + AuditDisconnect = "oficina.disconnect" |
| +) |
| + |
| +const ( |
| + // pendingTTL is how long a started consent may take. |
| + pendingTTL = 10 * time.Minute |
| + // maxPending bounds the consents started and not finished. |
| + maxPending = 1000 |
| + // early is how long before its expiry an access token is replaced. |
| + early = 30 * time.Second |
| + timeout = 20 * time.Second |
| + maxAnswer = 64 << 10 |
| +) |
| + |
| +var ( |
| + // ErrExpired: the callback is not one this instance is waiting for |
| + // from this person (unknown, used, too old, another issuer), or |
| + // connect did not accept its code. |
| + ErrExpired = errors.New("oficina: consent expired") |
| + // ErrDenied: the person did not allow the connection. |
| + ErrDenied = errors.New("oficina: consent denied") |
| + // ErrUnavailable: connect could not be reached or answered wrongly. |
| + 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. |
| +type Config struct { |
| + // Origin is oficina-connect's: https, or http on loopback. |
| + Origin string |
| + // ClientID is Equipo's pre-registered public client. |
| + ClientID string |
| + // Redirect is the instance's callback, exactly as registered. |
| + Redirect string |
| + // Client makes the requests (a default one when nil); Now is the |
| + // clock (time.Now when nil). |
| + Client *http.Client |
| + Now func() time.Time |
| +} |
| + |
| +// Store keeps each person's sealed refresh token. Save and Delete audit |
| +// the kind they are given (none when empty) in their own transaction. |
| +type Store interface { |
| + Load(ctx context.Context, person string) (sealed string, err error) |
| + Save(ctx context.Context, person, sealed, audit string) error |
| + Delete(ctx context.Context, person, audit, detail string) error |
| + Audit(ctx context.Context, person, kind, detail string) error |
| +} |
| + |
| +// Sealer seals with the instance key, bound to a domain. |
| +type Sealer interface { |
| + Seal(domain string, v any) (string, error) |
| + 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, 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 |
| +// expires, and the newest refresh token, unsaved when the store did not |
| +// take it (it is saved again before anything else). |
| +type session struct { |
| + access string |
| + expires time.Time |
| + refresh string |
| + unsaved bool |
| +} |
| + |
| +// Connector is the client for every person on the instance. |
| +type Connector struct { |
| + cfg Config |
| + store Store |
| + sealer Sealer |
| + client *http.Client |
| + now func() time.Time |
| + |
| + mu sync.Mutex |
| + pending map[string]pending // sha256 of the state -> who started it |
| + sessions map[string]*session |
| + locks map[string]*sync.Mutex |
| +} |
| + |
| +// New checks cfg and returns its connector. |
| +func New(cfg Config, store Store, sealer Sealer) (*Connector, error) { |
| + if !allowedOrigin(cfg.Origin, false) || cfg.ClientID == "" || !allowedOrigin(cfg.Redirect, true) || store == nil || sealer == nil { |
| + return nil, ErrConfig |
| + } |
| + c := http.Client{} |
| + if cfg.Client != nil { |
| + c = *cfg.Client |
| + } |
| + c.Timeout = timeout |
| + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| + now := cfg.Now |
| + if now == nil { |
| + now = time.Now |
| + } |
| + return &Connector{cfg: cfg, store: store, sealer: sealer, client: &c, now: now, pending: map[string]pending{}, sessions: map[string]*session{}, locks: map[string]*sync.Mutex{}}, nil |
| +} |
| + |
| +// allowedOrigin: an https origin (http only on loopback), with a path |
| +// only when path is allowed. |
| +func allowedOrigin(raw string, path bool) bool { |
| + u, err := url.Parse(raw) |
| + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || !path && u.Path != "" { |
| + return false |
| + } |
| + host := u.Hostname() |
| + ip := net.ParseIP(host) |
| + return u.Scheme == "https" || u.Scheme == "http" && (host == "localhost" || ip != nil && ip.IsLoopback()) |
| +} |
| + |
| +// Origin is connect's origin. |
| +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 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 |
| + } |
| + verifier, state := random(), random() |
| + sum := sha256.Sum256([]byte(verifier)) |
| + now := c.now() |
| + c.mu.Lock() |
| + for k, p := range c.pending { |
| + if !now.Before(p.expires) { |
| + delete(c.pending, k) |
| + } |
| + } |
| + if len(c.pending) >= maxPending { |
| + c.mu.Unlock() |
| + return "", ErrUnavailable |
| + } |
| + 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") |
| + q.Set("client_id", c.cfg.ClientID) |
| + q.Set("redirect_uri", c.cfg.Redirect) |
| + q.Set("scope", strings.Join(scopes, " ")) |
| + q.Set("state", state) |
| + q.Set("code_challenge", base64.RawURLEncoding.EncodeToString(sum[:])) |
| + q.Set("code_challenge_method", "S256") |
| + q.Set("resource", c.resource()) |
| + return c.cfg.Origin + "/oauth/authorize?" + q.Encode(), nil |
| +} |
| + |
| +// scopes are the scopes to ask for, from connect's metadata. |
| +func (c *Connector) scopes(ctx context.Context) ([]string, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.cfg.Origin+"/.well-known/oauth-authorization-server", nil) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + var meta struct { |
| + Scopes []string `json:"scopes_supported"` |
| + } |
| + if status, err := c.do(req, &meta); err != nil || status != http.StatusOK { |
| + return nil, ErrUnavailable |
| + } |
| + out := []string{"offline_access"} |
| + for _, s := range meta.Scopes { |
| + app, kind, ok := strings.Cut(s, ":") |
| + if ok && app != "" && (kind == "read" || kind == "write") && !slices.Contains(out, s) { |
| + out = append(out, s) |
| + } |
| + } |
| + if len(out) == 1 { |
| + return nil, ErrUnavailable |
| + } |
| + return out, nil |
| +} |
| + |
| +// 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] |
| + 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 := 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) |
| + } |
| + 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", code) |
| + form.Set("client_id", c.cfg.ClientID) |
| + form.Set("redirect_uri", c.cfg.Redirect) |
| + form.Set("resource", c.resource()) |
| + form.Set("code_verifier", p.verifier) |
| + lock := c.lock(person) |
| + lock.Lock() |
| + defer lock.Unlock() |
| + tok, err := c.token(ctx, form) |
| + if errors.Is(err, errGrant) { |
| + return c.failed(ctx, person, "invalid_grant", ErrExpired) |
| + } |
| + if err != nil || tok.Refresh == "" { |
| + return c.failed(ctx, person, "unavailable", ErrUnavailable) |
| + } |
| + sealed, err := c.sealer.Seal(Domain, tok.Refresh) |
| + if err != nil { |
| + return err |
| + } |
| + if err := c.store.Save(ctx, person, sealed, AuditConnect); err != nil { |
| + 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 nil |
| +} |
| + |
| +// failed audits a consent that did not finish and returns err. |
| +func (c *Connector) failed(ctx context.Context, person, detail string, err error) error { |
| + if aerr := c.store.Audit(ctx, person, AuditConnectFailed, detail); aerr != nil { |
| + return aerr |
| + } |
| + return err |
| +} |
| + |
| +// Connected says the person has a connection stored. |
| +func (c *Connector) Connected(ctx context.Context, person string) (bool, error) { |
| + sealed, err := c.store.Load(ctx, person) |
| + return sealed != "", err |
| +} |
| + |
| +// Host is connect's origin and a current access token for person: the |
| +// 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() |
| + var s session |
| + known := c.sessions[person] != nil |
| + if known { |
| + s = *c.sessions[person] |
| + } |
| + c.mu.Unlock() |
| + if known && s.unsaved { |
| + if err := c.save(ctx, person, s.refresh); err != nil { |
| + return "", "", false, err |
| + } |
| + c.mu.Lock() |
| + if cur := c.sessions[person]; cur != nil && cur.refresh == s.refresh { |
| + cur.unsaved = false |
| + } |
| + c.mu.Unlock() |
| + } |
| + if known && s.access != "" && c.now().Add(early).Before(s.expires) { |
| + return c.cfg.Origin, s.access, true, nil |
| + } |
| + refresh := "" |
| + if known { |
| + refresh = s.refresh |
| + } else { |
| + sealed, err := c.store.Load(ctx, person) |
| + if err != nil || sealed == "" { |
| + return "", "", false, err |
| + } |
| + if err := c.sealer.Open(Domain, sealed, &refresh); err != nil { |
| + return "", "", false, err |
| + } |
| + } |
| + form := url.Values{} |
| + form.Set("grant_type", "refresh_token") |
| + form.Set("refresh_token", refresh) |
| + form.Set("client_id", c.cfg.ClientID) |
| + form.Set("resource", c.resource()) |
| + tok, err := c.token(ctx, form) |
| + if errors.Is(err, errGrant) { |
| + c.drop(person) |
| + return "", "", false, c.store.Delete(ctx, person, AuditRefreshFailed, "invalid_grant") |
| + } |
| + if err != nil { |
| + if aerr := c.store.Audit(ctx, person, AuditRefreshFailed, "unavailable"); aerr != nil { |
| + return "", "", false, aerr |
| + } |
| + return "", "", false, err |
| + } |
| + if tok.Refresh == "" { |
| + tok.Refresh = refresh |
| + } |
| + next := &session{access: tok.Access, expires: c.now().Add(tok.lifetime()), refresh: tok.Refresh} |
| + c.mu.Lock() |
| + c.sessions[person] = next |
| + c.mu.Unlock() |
| + 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 |
| +} |
| + |
| +func (c *Connector) save(ctx context.Context, person, refresh string) error { |
| + sealed, err := c.sealer.Seal(Domain, refresh) |
| + if err != nil { |
| + return err |
| + } |
| + return c.store.Save(ctx, person, sealed, "") |
| +} |
| + |
| +// Rejected drops the person's access token, which connect refused: the |
| +// next Host refreshes. |
| +func (c *Connector) Rejected(person string) { |
| + c.mu.Lock() |
| + if s := c.sessions[person]; s != nil { |
| + s.access = "" |
| + } |
| + c.mu.Unlock() |
| +} |
| + |
| +// Disconnect revokes the person's connection at connect and forgets it. |
| +// A revocation connect did not confirm is audited as such; the |
| +// connection is forgotten either way. |
| +func (c *Connector) Disconnect(ctx context.Context, person string) error { |
| + lock := c.lock(person) |
| + lock.Lock() |
| + defer lock.Unlock() |
| + refresh := "" |
| + c.mu.Lock() |
| + if s := c.sessions[person]; s != nil { |
| + refresh = s.refresh |
| + } |
| + c.mu.Unlock() |
| + if refresh == "" { |
| + sealed, err := c.store.Load(ctx, person) |
| + if err != nil { |
| + return err |
| + } |
| + if sealed == "" { |
| + return nil |
| + } |
| + if err := c.sealer.Open(Domain, sealed, &refresh); err != nil { |
| + return err |
| + } |
| + } |
| + detail := "" |
| + form := url.Values{} |
| + form.Set("token", refresh) |
| + form.Set("client_id", c.cfg.ClientID) |
| + req, err := c.post(ctx, "/oauth/revoke", form) |
| + if err == nil { |
| + var status int |
| + if status, err = c.do(req, nil); err == nil && status != http.StatusOK { |
| + err = ErrUnavailable |
| + } |
| + } |
| + if err != nil { |
| + detail = "revoke_failed" |
| + } |
| + c.drop(person) |
| + return c.store.Delete(ctx, person, AuditDisconnect, detail) |
| +} |
| + |
| +func (c *Connector) drop(person string) { |
| + c.mu.Lock() |
| + delete(c.sessions, person) |
| + c.mu.Unlock() |
| +} |
| + |
| +func (c *Connector) lock(person string) *sync.Mutex { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + l := c.locks[person] |
| + if l == nil { |
| + l = &sync.Mutex{} |
| + c.locks[person] = l |
| + } |
| + return l |
| +} |
| + |
| +// errGrant: connect refused the code or refresh token (invalid_grant). |
| +var errGrant = errors.New("oficina: invalid grant") |
| + |
| +type tokens struct { |
| + Access string `json:"access_token"` |
| + Type string `json:"token_type"` |
| + ExpiresIn int `json:"expires_in"` |
| + Refresh string `json:"refresh_token"` |
| +} |
| + |
| +func (t tokens) lifetime() time.Duration { return time.Duration(t.ExpiresIn) * time.Second } |
| + |
| +// token posts form to connect's token endpoint. |
| +func (c *Connector) token(ctx context.Context, form url.Values) (tokens, error) { |
| + req, err := c.post(ctx, "/oauth/token", form) |
| + if err != nil { |
| + return tokens{}, ErrUnavailable |
| + } |
| + var raw json.RawMessage |
| + status, err := c.do(req, &raw) |
| + if err != nil { |
| + return tokens{}, ErrUnavailable |
| + } |
| + if status == http.StatusBadRequest { |
| + var e struct { |
| + Error string `json:"error"` |
| + } |
| + if json.Unmarshal(raw, &e) == nil && e.Error == "invalid_grant" { |
| + return tokens{}, errGrant |
| + } |
| + } |
| + var t tokens |
| + if status != http.StatusOK || json.Unmarshal(raw, &t) != nil || t.Access == "" || !strings.EqualFold(t.Type, "bearer") || t.ExpiresIn <= 0 { |
| + return tokens{}, ErrUnavailable |
| + } |
| + return t, nil |
| +} |
| + |
| +func (c *Connector) post(ctx context.Context, path string, form url.Values) (*http.Request, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.Origin+path, strings.NewReader(form.Encode())) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + return req, nil |
| +} |
| + |
| +// do sends req and reads a JSON answer into out (nil: none), at most |
| +// 64 KiB. |
| +func (c *Connector) do(req *http.Request, out any) (int, error) { |
| + req.Header.Set("Accept", "application/json") |
| + resp, err := c.client.Do(req) |
| + if err != nil { |
| + return 0, ErrUnavailable |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer+1)) |
| + if err != nil || len(body) > maxAnswer { |
| + return 0, ErrUnavailable |
| + } |
| + if out != nil && len(body) > 0 && json.Unmarshal(body, out) != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return resp.StatusCode, nil |
| +} |
| + |
| +func random() string { |
| + b := make([]byte, 32) |
| + _, _ = rand.Read(b) |
| + return base64.RawURLEncoding.EncodeToString(b) |
| +} |
| + |
| +func digest(s string) string { |
| + sum := sha256.Sum256([]byte(s)) |
| + return base64.RawURLEncoding.EncodeToString(sum[:]) |
| +} |
diff --git a/internal/equipo/oficina/connect_test.go b/internal/equipo/oficina/connect_test.go| new file mode 100644 |
| index 00000000..2fcd6d04 |
| --- /dev/null |
| +++ b/internal/equipo/oficina/connect_test.go |
| @@ -0,0 +1,495 @@ |
| +package oficina |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// memStore is a Store in memory that records its audit. |
| +type memStore struct { |
| + mu sync.Mutex |
| + sealed map[string]string |
| + audit []string |
| + saves int |
| + fail bool |
| +} |
| + |
| +func (m *memStore) Load(_ context.Context, person string) (string, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.sealed[person], nil |
| +} |
| + |
| +func (m *memStore) Save(_ context.Context, person, sealed, audit string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if m.fail { |
| + return errors.New("disk full") |
| + } |
| + m.sealed[person] = sealed |
| + m.saves++ |
| + if audit != "" { |
| + m.audit = append(m.audit, person+" "+audit) |
| + } |
| + return nil |
| +} |
| + |
| +func (m *memStore) Delete(_ context.Context, person, audit, detail string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + delete(m.sealed, person) |
| + m.audit = append(m.audit, strings.TrimSpace(person+" "+audit+" "+detail)) |
| + return nil |
| +} |
| + |
| +func (m *memStore) Audit(_ context.Context, person, kind, detail string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.audit = append(m.audit, strings.TrimSpace(person+" "+kind+" "+detail)) |
| + return nil |
| +} |
| + |
| +func (m *memStore) audits() string { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return strings.Join(m.audit, "\n") |
| +} |
| + |
| +// sealer seals by encoding with the domain, so a test can open what was |
| +// stored and see it is not the token as it is. |
| +type sealer struct{} |
| + |
| +func (sealer) Seal(domain string, v any) (string, error) { |
| + b, err := json.Marshal(v) |
| + return "sealed:" + base64.RawURLEncoding.EncodeToString(append([]byte(domain+"|"), b...)), err |
| +} |
| + |
| +func (sealer) Open(domain, raw string, v any) error { |
| + b, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(raw, "sealed:")) |
| + if err != nil { |
| + return err |
| + } |
| + rest, ok := strings.CutPrefix(string(b), domain+"|") |
| + if !ok { |
| + return errors.New("wrong domain") |
| + } |
| + return json.Unmarshal([]byte(rest), v) |
| +} |
| + |
| +type clock struct { |
| + mu sync.Mutex |
| + t time.Time |
| +} |
| + |
| +func (c *clock) now() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.t |
| +} |
| + |
| +func (c *clock) add(d time.Duration) { |
| + c.mu.Lock() |
| + c.t = c.t.Add(d) |
| + c.mu.Unlock() |
| +} |
| + |
| +type rig struct { |
| + fake *oficinatest.Connect |
| + store *memStore |
| + clock *clock |
| + c *Connector |
| +} |
| + |
| +const redirect = "https://equipo.example.com/oficina/connect/callback" |
| + |
| +func newRig(t *testing.T) *rig { |
| + t.Helper() |
| + fake := oficinatest.Start(t) |
| + fake.Redirect = redirect |
| + r := &rig{fake: fake, store: &memStore{sealed: map[string]string{}}, clock: &clock{t: time.Now()}} |
| + c, err := New(Config{Origin: fake.URL, ClientID: fake.ClientID, Redirect: redirect, Now: r.clock.now}, r.store, sealer{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.c = c |
| + return r |
| +} |
| + |
| +// consent starts the flow for person and follows connect's consent, |
| +// 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, "https://base.example.com/ask") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + res, err := client.Get(start) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res.Body.Close() |
| + loc, err := url.Parse(res.Header.Get("Location")) |
| + if res.StatusCode != http.StatusSeeOther || err != nil || !strings.HasPrefix(loc.String(), redirect+"?") { |
| + t.Fatalf("consent: %d %q", res.StatusCode, res.Header.Get("Location")) |
| + } |
| + return loc.Query() |
| +} |
| + |
| +func (r *rig) connect(t *testing.T, person string) { |
| + t.Helper() |
| + 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("peek: %+v %v", res, err) |
| + } |
| + if err := r.c.Finish(context.Background(), person, q.Get("state"), q.Get("code")); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// refreshToken is the person's refresh token as stored, opened. |
| +func (r *rig) refreshToken(t *testing.T, person string) string { |
| + t.Helper() |
| + sealed := r.store.sealed[person] |
| + if sealed == "" { |
| + return "" |
| + } |
| + var tok string |
| + if err := (sealer{}).Open(Domain, sealed, &tok); err != nil { |
| + t.Fatal(err) |
| + } |
| + return tok |
| +} |
| + |
| +// TestConnectPKCE: the authorization request is a public client's with |
| +// S256 PKCE for connect's resource, asking for every read and write |
| +// scope connect offers and offline_access, never a share scope. The code |
| +// is exchanged with the verifier (the fake checks it), the refresh token |
| +// 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", "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + u, _ := url.Parse(start) |
| + q := u.Query() |
| + if u.Scheme+"://"+u.Host != r.fake.URL || u.Path != "/oauth/authorize" || q.Get("client_id") != r.fake.ClientID || q.Get("redirect_uri") != redirect || |
| + q.Get("response_type") != "code" || q.Get("code_challenge_method") != "S256" || q.Get("resource") != r.fake.URL+"/mcp" || len(q.Get("state")) < 32 || len(q.Get("code_challenge")) != 43 { |
| + t.Fatalf("authorize: %s", start) |
| + } |
| + scopes := " " + q.Get("scope") + " " |
| + for _, want := range []string{" offline_access ", " calendar:read ", " calendar:write ", " docs:write "} { |
| + if !strings.Contains(scopes, want) { |
| + t.Errorf("scope %q missing: %s", want, scopes) |
| + } |
| + } |
| + if strings.Contains(scopes, "share") { |
| + t.Errorf("a share scope asked for: %s", scopes) |
| + } |
| + |
| + r.connect(t, "ana@example.com") |
| + if ex, _ := r.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| + refresh := r.refreshToken(t, "ana@example.com") |
| + if refresh == "" || strings.Contains(r.store.sealed["ana@example.com"], refresh) { |
| + t.Fatalf("refresh token not stored sealed: %q", r.store.sealed["ana@example.com"]) |
| + } |
| + origin, tok, ok, err := r.c.Host(context.Background(), "ana@example.com") |
| + if err != nil || !ok || origin != r.fake.URL || !r.fake.Live(tok) { |
| + t.Fatalf("host: %q %v %v", origin, ok, err) |
| + } |
| + if _, refreshes := r.fake.Counts(); refreshes != 0 { |
| + t.Errorf("the first access token was not cached: %d refreshes", refreshes) |
| + } |
| + if ok, _ := r.c.Connected(context.Background(), "ana@example.com"); !ok { |
| + t.Error("not connected") |
| + } |
| + if !strings.Contains(r.store.audits(), "ana@example.com oficina.connect") { |
| + t.Errorf("audit: %s", r.store.audits()) |
| + } |
| +} |
| + |
| +// 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") |
| + 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) |
| + } |
| + // 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 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.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.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.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.Peek(ctx, q); !errors.Is(err, ErrDenied) { |
| + t.Errorf("a refusal: %v", err) |
| + } |
| + 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) |
| + } |
| + |
| + // A code the fake refuses stores nothing. |
| + q = r.consent(t, "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") { |
| + t.Errorf("audit: %s", a) |
| + } |
| +} |
| + |
| +// 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). |
| +func TestConnectRefreshRotates(t *testing.T) { |
| + r := newRig(t) |
| + ctx := context.Background() |
| + r.connect(t, "ana@example.com") |
| + first := r.refreshToken(t, "ana@example.com") |
| + _, before, _, _ := r.c.Host(ctx, "ana@example.com") |
| + for i := 1; i <= 3; i++ { |
| + r.clock.add(5 * time.Minute) |
| + _, tok, ok, err := r.c.Host(ctx, "ana@example.com") |
| + if err != nil || !ok || tok == before || !r.fake.Live(tok) { |
| + t.Fatalf("refresh %d: %v %v", i, ok, err) |
| + } |
| + before = tok |
| + if _, n := r.fake.Counts(); n != i { |
| + t.Errorf("refreshes %d, want %d", n, i) |
| + } |
| + } |
| + now := r.refreshToken(t, "ana@example.com") |
| + if now == first || r.fake.Live(first) || !r.fake.Live(now) { |
| + t.Errorf("not rotated: first live %v, now live %v", r.fake.Live(first), r.fake.Live(now)) |
| + } |
| + // Rejected drops the cached access token: the next Host refreshes. |
| + r.c.Rejected("ana@example.com") |
| + if _, tok, ok, _ := r.c.Host(ctx, "ana@example.com"); !ok || tok == before { |
| + t.Error("a rejected token was kept") |
| + } |
| +} |
| + |
| +// TestConnectRefreshOnce: callers at once share one refresh. |
| +func TestConnectRefreshOnce(t *testing.T) { |
| + r := newRig(t) |
| + r.connect(t, "ana@example.com") |
| + r.clock.add(5 * time.Minute) |
| + var wg sync.WaitGroup |
| + for range 10 { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + if _, _, ok, err := r.c.Host(context.Background(), "ana@example.com"); !ok || err != nil { |
| + t.Errorf("host: %v %v", ok, err) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if _, n := r.fake.Counts(); n != 1 { |
| + t.Errorf("refreshes %d", n) |
| + } |
| +} |
| + |
| +// TestConnectRefreshRevoked: a connection revoked at connect is |
| +// forgotten on the next refresh, audited without a token. |
| +func TestConnectRefreshRevoked(t *testing.T) { |
| + r := newRig(t) |
| + ctx := context.Background() |
| + r.connect(t, "ana@example.com") |
| + r.fake.RevokeAll() |
| + r.clock.add(5 * time.Minute) |
| + if _, _, ok, err := r.c.Host(ctx, "ana@example.com"); ok || err != nil { |
| + t.Fatalf("revoked: %v %v", ok, err) |
| + } |
| + if ok, _ := r.c.Connected(ctx, "ana@example.com"); ok || len(r.store.sealed) != 0 { |
| + t.Error("a revoked connection is kept") |
| + } |
| + if a := r.store.audits(); !strings.Contains(a, "ana@example.com oficina.refresh_failed invalid_grant") { |
| + t.Errorf("audit: %s", a) |
| + } |
| +} |
| + |
| +// TestConnectRefreshUnavailable: connect down is an error and keeps the |
| +// connection; a rotated token that could not be stored is still used. |
| +func TestConnectRefreshUnavailable(t *testing.T) { |
| + r := newRig(t) |
| + ctx := context.Background() |
| + r.connect(t, "ana@example.com") |
| + r.fake.Down = true |
| + r.clock.add(5 * time.Minute) |
| + if _, _, _, err := r.c.Host(ctx, "ana@example.com"); err == nil { |
| + t.Fatal("no error with connect down") |
| + } |
| + if ok, _ := r.c.Connected(ctx, "ana@example.com"); !ok { |
| + t.Error("forgotten while connect was down") |
| + } |
| + if a := r.store.audits(); !strings.Contains(a, "oficina.refresh_failed unavailable") { |
| + t.Errorf("audit: %s", a) |
| + } |
| + r.fake.Down = false |
| + r.store.fail = true |
| + if _, _, ok, err := r.c.Host(ctx, "ana@example.com"); ok || err == nil { |
| + t.Errorf("a rotation that could not be stored: %v %v", ok, err) |
| + } |
| + r.store.fail = false |
| + r.c.Rejected("ana@example.com") |
| + if _, tok, ok, err := r.c.Host(ctx, "ana@example.com"); !ok || err != nil || !r.fake.Live(tok) { |
| + t.Fatalf("after the store recovered: %v %v", ok, err) |
| + } |
| + if !r.fake.Live(r.refreshToken(t, "ana@example.com")) { |
| + t.Error("the stored refresh token is not the current one") |
| + } |
| +} |
| + |
| +// TestConnectDisconnect revokes at connect and forgets the connection. |
| +func TestConnectDisconnect(t *testing.T) { |
| + r := newRig(t) |
| + ctx := context.Background() |
| + r.connect(t, "ana@example.com") |
| + refresh := r.refreshToken(t, "ana@example.com") |
| + if err := r.c.Disconnect(ctx, "ana@example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := r.fake.Revoked(); len(got) != 1 || got[0] != refresh || r.fake.Live(refresh) { |
| + t.Errorf("revoked %v", got) |
| + } |
| + if _, _, ok, _ := r.c.Host(ctx, "ana@example.com"); ok || len(r.store.sealed) != 0 { |
| + t.Error("still connected") |
| + } |
| + if a := r.store.audits(); !strings.Contains(a, "ana@example.com oficina.disconnect") { |
| + t.Errorf("audit: %s", a) |
| + } |
| + // Disconnecting with nothing connected changes nothing. |
| + if err := r.c.Disconnect(ctx, "ana@example.com"); err != nil || len(r.fake.Revoked()) != 1 { |
| + t.Errorf("second disconnect: %v %v", err, r.fake.Revoked()) |
| + } |
| + if a := r.store.audits(); strings.Contains(a, refresh) { |
| + t.Errorf("a token in the audit: %s", a) |
| + } |
| +} |
| + |
| +// TestConnectConfig: an origin must be https (http only on loopback), |
| +// with a client id and an https redirect. |
| +func TestConnectConfig(t *testing.T) { |
| + for _, cfg := range []Config{ |
| + {Origin: "http://connect.example.com", ClientID: "c", Redirect: redirect}, |
| + {Origin: "https://connect.example.com/path", ClientID: "c", Redirect: redirect}, |
| + {Origin: "https://connect.example.com", Redirect: redirect}, |
| + {Origin: "https://connect.example.com", ClientID: "c"}, |
| + } { |
| + if _, err := New(cfg, &memStore{}, sealer{}); err == nil { |
| + t.Errorf("accepted %+v", cfg) |
| + } |
| + } |
| + if _, err := New(Config{Origin: "https://connect.example.com", ClientID: "c", Redirect: redirect}, &memStore{}, sealer{}); err != nil { |
| + t.Error(err) |
| + } |
| +} |
diff --git a/internal/equipo/oficina/oficinatest/fake.go b/internal/equipo/oficina/oficinatest/fake.go| new file mode 100644 |
| index 00000000..ef64ea7e |
| --- /dev/null |
| +++ b/internal/equipo/oficina/oficinatest/fake.go |
| @@ -0,0 +1,375 @@ |
| +// Package oficinatest is a fake oficina-connect for tests: the OAuth 2 |
| +// authorization code flow with S256 PKCE for public clients, rotating |
| +// refresh tokens (reusing a consumed one revokes the connection, as |
| +// connect does), revocation, and the operations API behind a bearer. |
| +// It approves every consent itself, for the teams it was given. |
| +package oficinatest |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Operation is a descriptor the fake lists, in agent-access's shape. |
| +type Operation struct { |
| + Name string `json:"name"` |
| + Description string `json:"description"` |
| + Scope string `json:"scope"` |
| + ReadOnly bool `json:"read_only"` |
| + Destructive bool `json:"destructive"` |
| + Idempotent bool `json:"idempotent"` |
| + External bool `json:"external,omitempty"` |
| + Input json.RawMessage `json:"input_schema"` |
| + Output json.RawMessage `json:"output_schema"` |
| +} |
| + |
| +// Call is one operation call the fake answered. |
| +type Call struct { |
| + Name string |
| + Bearer string |
| + Input map[string]any |
| +} |
| + |
| +// UUIDSchema is a required client_id as the apps declare it: a string |
| +// of exactly 36 characters. |
| +const UUIDSchema = `{"type":"string","minLength":36,"maxLength":36}` |
| + |
| +// Operations is the fake's default list: a read, a client_id-keyed |
| +// write, a write without a key, one destructive and one external write. |
| +func Operations() []Operation { |
| + in := func(props string, required ...string) json.RawMessage { |
| + req, _ := json.Marshal(append([]string{"team"}, required...)) |
| + return json.RawMessage(`{"type":"object","additionalProperties":false,"required":` + string(req) + `,"properties":{"team":{"type":"string","maxLength":64}` + props + `}}`) |
| + } |
| + out := json.RawMessage(`{"type":"object"}`) |
| + return []Operation{ |
| + {Name: "calendar_free_busy", Description: "Busy spans in a range.", Scope: "calendar:read", ReadOnly: true, Idempotent: true, Input: in(`,"start":{"type":"string"},"end":{"type":"string"}`, "start", "end"), Output: out}, |
| + {Name: "calendar_create_event", Description: "Create an event. Sends no invitations.", Scope: "calendar:write", Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"title":{"type":"string"},"start_local":{"type":"string"}`, "client_id", "title", "start_local"), Output: out}, |
| + {Name: "docs_append", Description: "Append to a document without a client_id.", Scope: "docs:write", Idempotent: false, Input: in(`,"id":{"type":"string"},"text":{"type":"string"}`, "id", "text"), Output: out}, |
| + {Name: "docs_delete", Description: "Delete a document.", Scope: "docs:write", Destructive: true, Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"id":{"type":"string"}`, "client_id", "id"), Output: out}, |
| + {Name: "calls_invite", Description: "Invite a guest.", Scope: "calls:write", External: true, Idempotent: true, Input: in(`,"client_id":`+UUIDSchema+`,"email":{"type":"string"}`, "client_id", "email"), Output: out}, |
| + } |
| +} |
| + |
| +type grant struct { |
| + teams []string |
| + revoked bool |
| +} |
| + |
| +type code struct { |
| + grant *grant |
| + redirect, resource string |
| + challenge string |
| + expires time.Time |
| +} |
| + |
| +type token struct { |
| + grant *grant |
| + refresh bool |
| + used bool |
| + expires time.Time |
| +} |
| + |
| +// Connect is a running fake oficina-connect. |
| +type Connect struct { |
| + URL string |
| + ClientID string |
| + // Redirect is the client's one registered redirect; empty takes any. |
| + Redirect string |
| + // Teams are what consent selects; Ops what the operations API lists. |
| + Teams []string |
| + Ops []Operation |
| + // AccessTTL is an access token's lifetime (5 minutes by default). |
| + AccessTTL time.Duration |
| + // Deny makes the next consent a refusal. |
| + Deny bool |
| + // Down makes the token endpoint answer 503. |
| + Down bool |
| + // FailNext makes the next operation call answer 503 once it is |
| + // recorded. |
| + FailNext bool |
| + |
| + mu sync.Mutex |
| + codes map[string]*code |
| + tokens map[string]*token |
| + calls []Call |
| + exchanges int |
| + refreshes int |
| + revokes []string |
| + srv *httptest.Server |
| +} |
| + |
| +// Start serves a fake connect on 127.0.0.1 until the test ends. |
| +func Start(t testing.TB) *Connect { |
| + t.Helper() |
| + c := &Connect{ClientID: "8d3f6c1e-7a52-4c1b-9f60-2b7e4d1a9c33", Teams: []string{"acme"}, Ops: Operations(), AccessTTL: 5 * time.Minute, codes: map[string]*code{}, tokens: map[string]*token{}} |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /.well-known/oauth-authorization-server", c.metadata) |
| + mux.HandleFunc("GET /oauth/authorize", c.authorize) |
| + mux.HandleFunc("POST /oauth/token", c.token) |
| + mux.HandleFunc("POST /oauth/revoke", c.revoke) |
| + mux.HandleFunc("GET /api/v1/connection", c.bearer(c.connection)) |
| + mux.HandleFunc("GET /api/v1/operations", c.bearer(c.operations)) |
| + mux.HandleFunc("POST /api/v1/operations/{name}", c.bearer(c.invoke)) |
| + c.srv = httptest.NewServer(mux) |
| + c.URL = c.srv.URL |
| + t.Cleanup(c.srv.Close) |
| + return c |
| +} |
| + |
| +// Resource is the audience every token is for, as connect's /mcp. |
| +func (c *Connect) Resource() string { return c.URL + "/mcp" } |
| + |
| +// Grant mints an access token for teams directly, with no consent. |
| +func (c *Connect) Grant(teams ...string) string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + g := &grant{teams: teams} |
| + access := random() |
| + c.tokens[access] = &token{grant: g, expires: time.Now().Add(c.AccessTTL)} |
| + return access |
| +} |
| + |
| +// Calls are the operation calls the fake answered, oldest first. |
| +func (c *Connect) Calls() []Call { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return slices.Clone(c.calls) |
| +} |
| + |
| +// Counts are the code exchanges and refreshes the fake answered. |
| +func (c *Connect) Counts() (exchanges, refreshes int) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.exchanges, c.refreshes |
| +} |
| + |
| +// Revoked are the tokens revoked through /oauth/revoke. |
| +func (c *Connect) Revoked() []string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return slices.Clone(c.revokes) |
| +} |
| + |
| +// Live says a token is current: known, unexpired, unused and its |
| +// connection not revoked. |
| +func (c *Connect) Live(tok string) bool { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + k, ok := c.tokens[tok] |
| + return ok && !k.used && !k.grant.revoked && time.Now().Before(k.expires) |
| +} |
| + |
| +// RevokeAll revokes every connection, as /connections would. |
| +func (c *Connect) RevokeAll() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + for _, k := range c.tokens { |
| + k.grant.revoked = true |
| + } |
| +} |
| + |
| +// Expire makes every access token expire now. |
| +func (c *Connect) Expire() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + for _, k := range c.tokens { |
| + if !k.refresh { |
| + k.expires = time.Now().Add(-time.Second) |
| + } |
| + } |
| +} |
| + |
| +func (c *Connect) metadata(w http.ResponseWriter, _ *http.Request) { |
| + scopes := []string{"offline_access"} |
| + c.mu.Lock() |
| + for _, op := range c.Ops { |
| + if !slices.Contains(scopes, op.Scope) { |
| + scopes = append(scopes, op.Scope) |
| + } |
| + } |
| + c.mu.Unlock() |
| + scopes = append(scopes, "calls:share") |
| + write(w, 200, map[string]any{"issuer": c.URL, "authorization_endpoint": c.URL + "/oauth/authorize", "token_endpoint": c.URL + "/oauth/token", "revocation_endpoint": c.URL + "/oauth/revoke", "code_challenge_methods_supported": []string{"S256"}, "scopes_supported": scopes}) |
| +} |
| + |
| +func (c *Connect) authorize(w http.ResponseWriter, r *http.Request) { |
| + q := r.URL.Query() |
| + challenge, err := base64.RawURLEncoding.DecodeString(q.Get("code_challenge")) |
| + if q.Get("client_id") != c.ClientID || c.Redirect != "" && q.Get("redirect_uri") != c.Redirect || err != nil || len(challenge) != 32 || |
| + q.Get("code_challenge_method") != "S256" || q.Get("response_type") != "code" || q.Get("resource") != c.Resource() || len(q.Get("state")) < 16 { |
| + fail(w, 400, "invalid_request") |
| + return |
| + } |
| + scopes := strings.Fields(q.Get("scope")) |
| + if len(scopes) == 0 || !slices.Contains(scopes, "offline_access") || slices.Contains(scopes, "calls:share") { |
| + fail(w, 400, "invalid_scope") |
| + return |
| + } |
| + dest, _ := url.Parse(q.Get("redirect_uri")) |
| + v := dest.Query() |
| + v.Set("state", q.Get("state")) |
| + v.Set("iss", c.URL) |
| + c.mu.Lock() |
| + if c.Deny { |
| + c.Deny = false |
| + v.Set("error", "access_denied") |
| + } else { |
| + k := random() |
| + c.codes[k] = &code{grant: &grant{teams: slices.Clone(c.Teams)}, redirect: q.Get("redirect_uri"), resource: q.Get("resource"), challenge: q.Get("code_challenge"), expires: time.Now().Add(2 * time.Minute)} |
| + v.Set("code", k) |
| + } |
| + c.mu.Unlock() |
| + dest.RawQuery = v.Encode() |
| + http.Redirect(w, r, dest.String(), http.StatusSeeOther) |
| +} |
| + |
| +func (c *Connect) token(w http.ResponseWriter, r *http.Request) { |
| + if r.ParseForm() != nil || r.URL.RawQuery != "" { |
| + fail(w, 400, "invalid_request") |
| + return |
| + } |
| + f := r.PostForm |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.Down { |
| + fail(w, 503, "temporarily_unavailable") |
| + return |
| + } |
| + if f.Get("client_id") != c.ClientID { |
| + fail(w, 400, "invalid_client") |
| + return |
| + } |
| + switch f.Get("grant_type") { |
| + case "authorization_code": |
| + c.exchanges++ |
| + k, ok := c.codes[f.Get("code")] |
| + delete(c.codes, f.Get("code")) |
| + sum := sha256.Sum256([]byte(f.Get("code_verifier"))) |
| + if !ok || time.Now().After(k.expires) || k.redirect != f.Get("redirect_uri") || k.resource != f.Get("resource") || len(f.Get("code_verifier")) < 43 || |
| + base64.RawURLEncoding.EncodeToString(sum[:]) != k.challenge { |
| + fail(w, 400, "invalid_grant") |
| + return |
| + } |
| + write(w, 200, c.mint(k.grant)) |
| + case "refresh_token": |
| + c.refreshes++ |
| + k, ok := c.tokens[f.Get("refresh_token")] |
| + if !ok || !k.refresh || k.grant.revoked || f.Get("resource") != c.Resource() { |
| + fail(w, 400, "invalid_grant") |
| + return |
| + } |
| + if k.used { |
| + // Reuse of a consumed refresh token revokes the connection. |
| + k.grant.revoked = true |
| + fail(w, 400, "invalid_grant") |
| + return |
| + } |
| + k.used = true |
| + write(w, 200, c.mint(k.grant)) |
| + default: |
| + fail(w, 400, "unsupported_grant_type") |
| + } |
| +} |
| + |
| +func (c *Connect) mint(g *grant) map[string]any { |
| + access, refresh := random(), random() |
| + c.tokens[access] = &token{grant: g, expires: time.Now().Add(c.AccessTTL)} |
| + c.tokens[refresh] = &token{grant: g, refresh: true, expires: time.Now().Add(30 * 24 * time.Hour)} |
| + return map[string]any{"access_token": access, "token_type": "Bearer", "expires_in": int(c.AccessTTL / time.Second), "refresh_token": refresh, "scope": "offline_access"} |
| +} |
| + |
| +func (c *Connect) revoke(w http.ResponseWriter, r *http.Request) { |
| + if r.ParseForm() != nil || r.PostForm.Get("client_id") != c.ClientID { |
| + fail(w, 400, "invalid_client") |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.revokes = append(c.revokes, r.PostForm.Get("token")) |
| + if k, ok := c.tokens[r.PostForm.Get("token")]; ok { |
| + k.grant.revoked = true |
| + } |
| + w.WriteHeader(200) |
| +} |
| + |
| +func (c *Connect) bearer(next func(http.ResponseWriter, *http.Request, string, *grant)) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| + c.mu.Lock() |
| + k, known := c.tokens[tok] |
| + live := ok && known && !k.refresh && !k.grant.revoked && time.Now().Before(k.expires) |
| + c.mu.Unlock() |
| + if !live { |
| + write(w, 401, map[string]any{"error": map[string]string{"code": "unauthenticated", "message": "Connect to Oficina first."}}) |
| + return |
| + } |
| + next(w, r, tok, k.grant) |
| + } |
| +} |
| + |
| +func (c *Connect) connection(w http.ResponseWriter, _ *http.Request, _ string, g *grant) { |
| + write(w, 200, map[string]any{"teams": g.teams, "scopes": []string{"calendar:read", "calendar:write"}}) |
| +} |
| + |
| +func (c *Connect) operations(w http.ResponseWriter, _ *http.Request, _ string, _ *grant) { |
| + c.mu.Lock() |
| + ops := slices.Clone(c.Ops) |
| + c.mu.Unlock() |
| + write(w, 200, map[string]any{"operations": ops}) |
| +} |
| + |
| +func (c *Connect) invoke(w http.ResponseWriter, r *http.Request, tok string, g *grant) { |
| + if r.Header.Get("Content-Type") != "application/json" { |
| + write(w, 415, map[string]any{"error": map[string]string{"code": "unsupported_media_type", "message": "Send application/json."}}) |
| + return |
| + } |
| + raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| + var in map[string]any |
| + if json.Unmarshal(raw, &in) != nil { |
| + write(w, 422, map[string]any{"error": map[string]string{"code": "invalid", "message": "Send an object."}}) |
| + return |
| + } |
| + c.mu.Lock() |
| + c.calls = append(c.calls, Call{Name: r.PathValue("name"), Bearer: tok, Input: in}) |
| + failed := c.FailNext |
| + c.FailNext = false |
| + c.mu.Unlock() |
| + if failed { |
| + write(w, 503, map[string]any{"error": map[string]string{"code": "unavailable", "message": "The app is unavailable."}}) |
| + return |
| + } |
| + team, _ := in["team"].(string) |
| + if !slices.Contains(g.teams, team) { |
| + write(w, 403, map[string]any{"error": map[string]string{"code": "forbidden", "message": "Select one of this connection's teams."}}) |
| + return |
| + } |
| + write(w, 200, map[string]any{"ok": true, "team": team, "client_id": in["client_id"]}) |
| +} |
| + |
| +func write(w http.ResponseWriter, status int, v any) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(v) |
| +} |
| + |
| +func fail(w http.ResponseWriter, status int, code string) { |
| + write(w, status, map[string]string{"error": code}) |
| +} |
| + |
| +func random() string { |
| + b := make([]byte, 32) |
| + _, _ = rand.Read(b) |
| + return base64.RawURLEncoding.EncodeToString(b) |
| +} |
diff --git a/internal/equipo/oficina_connect.go b/internal/equipo/oficina_connect.go| new file mode 100644 |
| index 00000000..bf9731b3 |
| --- /dev/null |
| +++ b/internal/equipo/oficina_connect.go |
| @@ -0,0 +1,324 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log/slog" |
| + "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" |
| +) |
| + |
| +// The Oficina apps, through oficina-connect (internal/equipo/oficina): |
| +// the provider's name in the Assistant's registry, and the routes a |
| +// person's browser takes to connect (the card's link, then connect's |
| +// redirect back) and to disconnect. |
| +const ( |
| + oficinaProvider = "oficina" |
| + 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: |
| +// their refresh token, sealed with the instance key (domain |
| +// oficina.connect), replaced as connect rotates it. |
| +type oficinaConnectionRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + Refresh string |
| + Revision int64 |
| + CreatedAt time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (oficinaConnectionRecord) TableName() string { return "oficina_connections" } |
| + |
| +// oficinaStore keeps connections in the instance's database. A save |
| +// checks the roster in its transaction; each audit is a code, never a |
| +// token. |
| +type oficinaStore struct{ s *Store } |
| + |
| +func (o oficinaStore) Load(ctx context.Context, person string) (string, error) { |
| + var sealed []string |
| + err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Model(&oficinaConnectionRecord{}).Where("person = ?", normalizeAddress(person)).Pluck("refresh", &sealed).Error |
| + if err != nil || len(sealed) == 0 { |
| + return "", storeError(err) |
| + } |
| + return sealed[0], nil |
| +} |
| + |
| +func (o oficinaStore) Save(ctx context.Context, person, sealed, audit string) error { |
| + person = normalizeAddress(person) |
| + return o.tx(ctx, func(tx *gorm.DB) error { |
| + if _, err := currentRunnerMember(tx, person); err != nil { |
| + return err |
| + } |
| + var r oficinaConnectionRecord |
| + if err := tx.Where("person = ?", person).Limit(1).Find(&r).Error; err != nil { |
| + return err |
| + } |
| + now := time.Now().UTC() |
| + if r.Person == "" { |
| + r = oficinaConnectionRecord{Person: person, CreatedAt: now} |
| + } |
| + r.Refresh, r.Revision, r.UpdatedAt = sealed, r.Revision+1, now |
| + if err := tx.Save(&r).Error; err != nil { |
| + return err |
| + } |
| + if audit == "" { |
| + return nil |
| + } |
| + return appendAudit(tx, Actor{Address: person}, audit, "") |
| + }) |
| +} |
| + |
| +// Delete forgets a connection, a removed member's too. |
| +func (o oficinaStore) Delete(ctx context.Context, person, audit, detail string) error { |
| + person = normalizeAddress(person) |
| + return o.tx(ctx, func(tx *gorm.DB) error { |
| + if err := tx.Where("person = ?", person).Delete(&oficinaConnectionRecord{}).Error; err != nil { |
| + return err |
| + } |
| + return appendAudit(tx, Actor{Address: person}, audit, detail) |
| + }) |
| +} |
| + |
| +func (o oficinaStore) Audit(ctx context.Context, person, kind, detail string) error { |
| + return o.tx(ctx, func(tx *gorm.DB) error { return appendAudit(tx, Actor{Address: person}, kind, detail) }) |
| +} |
| + |
| +func (o oficinaStore) tx(ctx context.Context, fn func(*gorm.DB) error) error { |
| + err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| + if err == nil || errors.Is(err, ErrForbidden) { |
| + return err |
| + } |
| + return storeError(err) |
| +} |
| + |
| +// oficinaSealer seals with the instance key, as device results and |
| +// Base host tokens are (read when used: the key is set after the store). |
| +type oficinaSealer struct{ s *Store } |
| + |
| +func (o oficinaSealer) Seal(domain string, v any) (string, error) { |
| + return o.s.personDevices().Seal(domain, v) |
| +} |
| + |
| +func (o oficinaSealer) Open(domain, raw string, v any) error { |
| + return o.s.personDevices().Open(domain, raw, v) |
| +} |
| + |
| +// 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(), normalizeAddress(id.Address), "") |
| + if err != nil { |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| + return |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + http.Redirect(w, r, dest, http.StatusSeeOther) |
| +} |
| + |
| +// 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") |
| + 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 |
| + } |
| + add := url.Values{} |
| + switch { |
| + case errors.Is(err, oficina.ErrDenied): |
| + add.Set("oficina", "denied") |
| + case errors.Is(err, oficina.ErrExpired): |
| + add.Set("oficina", "expired") |
| + case err != nil: |
| + add.Set("oficina", "unavailable") |
| + default: |
| + add.Set("oficina_state", q.Get("state")) |
| + add.Set("oficina_code", q.Get("code")) |
| + } |
| + dest := res.ReturnTo |
| + if dest == "" { |
| + dest = oficinaDonePath |
| + } |
| + 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: it |
| +// finishes it with the session's person, or shows how it failed. |
| +func (a *application) oficinaDone(w http.ResponseWriter, r *http.Request) { |
| + 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 |
| + } |
| + a.oficinaPage(w, r, http.StatusOK, key) |
| +} |
| + |
| +// oficinaDisconnect revokes the signed-in person's connection at connect |
| +// and forgets it. |
| +func (a *application) oficinaDisconnect(w http.ResponseWriter, r *http.Request) { |
| + id, ok := identity.From(r) |
| + if !ok { |
| + ErrorPage(w, r, http.StatusForbidden, "") |
| + return |
| + } |
| + person := normalizeAddress(id.Address) |
| + if err := a.store.oficina.Disconnect(r.Context(), person); err != nil { |
| + a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| + return |
| + } |
| + a.store.assist.Forget(person) |
| + a.oficinaPage(w, r, http.StatusOK, "oficina.connect.disconnected") |
| +} |
| + |
| +// oficinaPage is a short page saying what happened, under the app's |
| +// chrome. |
| +func (a *application) oficinaPage(w http.ResponseWriter, r *http.Request, status int, key string) { |
| + data, err := a.page(r, "settings") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Title, data.EmptyKey = "oficina.connect.title", key |
| + w.Header().Set("Cache-Control", "no-store") |
| + renderStatus(w, status, "empty", data) |
| +} |
diff --git a/internal/equipo/staging_mail_test.go b/internal/equipo/staging_mail_test.go| index 01e5e347..54e173fb 100644 |
| --- a/internal/equipo/staging_mail_test.go |
| +++ b/internal/equipo/staging_mail_test.go |
| @@ -53,3 +53,29 @@ func TestDatabaseName(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// EQUIPO_OFICINA_CONNECT_ORIGIN is off by default; set, it needs an |
| +// https origin (http on loopback) and EQUIPO_OFICINA_CONNECT_CLIENT_ID, |
| +// and the client's redirect is this instance's callback. |
| +func TestOficinaConnectConfig(t *testing.T) { |
| + env := map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com", "EQUIPO_INSTANCE_KEY": "k", "CARLOS_SMTP_HOST": "smtp.example.com", "CARLOS_SMTP_FROM": "e@example.com", "EQUIPO_OFICINA_CONNECT_CLIENT_ID": "c"} |
| + get := func(k string) string { return env[k] } |
| + if cfg, err := LoadConfig(get); err != nil || cfg.OficinaConnectOrigin != "" || cfg.OficinaConnectClientID != "" { |
| + t.Fatalf("unset: %+v %v", cfg, err) |
| + } |
| + for origin, ok := range map[string]bool{"https://connect.oficina.works": true, "http://connect.oficina.works": false, "https://connect.oficina.works/x": false, "http://127.0.0.1:9": true} { |
| + env["EQUIPO_OFICINA_CONNECT_ORIGIN"] = origin |
| + if _, err := LoadConfig(get); (err == nil) != ok { |
| + t.Errorf("%s: %v", origin, err) |
| + } |
| + } |
| + env["EQUIPO_OFICINA_CONNECT_ORIGIN"], env["EQUIPO_OFICINA_CONNECT_CLIENT_ID"] = "https://connect.oficina.works", "" |
| + if _, err := LoadConfig(get); err == nil { |
| + t.Error("no client id accepted") |
| + } |
| + env["EQUIPO_OFICINA_CONNECT_CLIENT_ID"] = " c " |
| + cfg, err := LoadConfig(get) |
| + if err != nil || cfg.OficinaConnectClientID != "c" || cfg.oficinaConfig().Redirect != "https://equipo.example.com/oficina/connect/callback" { |
| + t.Fatalf("set: %+v %v", cfg.oficinaConfig(), err) |
| + } |
| +} |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 220ec4ae..5c12729b 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -11,7 +11,9 @@ import ( |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| + "amadan.net/oficina/equipo/internal/equipo/assist" |
| "amadan.net/oficina/equipo/internal/equipo/library" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/setup" |
| @@ -79,6 +81,11 @@ type Store struct { |
| chatOrigin string |
| // chatAssistantHosts is EQUIPO_ASSISTANT_HOSTS. |
| chatAssistantHosts []string |
| + // oficina is the oficina-connect client, nil while |
| + // EQUIPO_OFICINA_CONNECT_ORIGIN is unset; assist the Assistant's |
| + // registry, kept to forget a person's lists when they connect. |
| + oficina *oficina.Connector |
| + assist *assist.Registry |
| } |
| type StoreOption func(*Store) |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index b4461ef8..823733bc 100644 |
| --- a/internal/plan3test/plan3_release_test.go |
| +++ b/internal/plan3test/plan3_release_test.go |
| @@ -177,11 +177,13 @@ func plan3CopyInventory(t *testing.T) { |
| approvedAssistant := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-13, copy-review jbltdd2mvwblrz4en6xfhv6d2y, unchanged)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-13, copy-review 64nswfjbrpsw2pezhyi7y3nenq, unchanged)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-13, copy-review c3ipwcupsvwv7rpbj2kdbgrsyy, unchanged)") |
| // Paul's own review of the jobs strings and the API section's job prose. |
| approvedJobs := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq, unchanged)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-14, copy-review cvaxhn3pwgpxhpssj5cgizqtrq)") || strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-14, copy-review mbvzxmewxxgud4ksakdb2m7pye)") |
| + // Paul's own review of the Oficina connection's strings and API sentence. |
| + approvedOficina := strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-16, copy-review arfnqquz6wks4vdyxptv6ditju, unchanged)") |
| acceptedRoster := strings.HasPrefix(key, "roster.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-14)") |
| acceptedPlacement := strings.HasPrefix(key, "placement.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)") |
| acceptedReportActions := slices.Contains([]string{"roster.talk", "roster.round_busy", "roster.round_done", "roster.merge_busy", "roster.merge_done"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-15)") |
| acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key]) |
| - if !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs { |
| + if !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina { |
| t.Fatal("entry has no copy review status or applicable acceptance", key) |
| } |
| } |
diff --git a/internal/thintest/assistant.go b/internal/thintest/assistant.go| index 16f30fd7..5cadb28a 100644 |
| --- a/internal/thintest/assistant.go |
| +++ b/internal/thintest/assistant.go |
| @@ -56,3 +56,24 @@ 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 |
| +} |
| + |
| +// 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| new file mode 100644 |
| index 00000000..c3c509fd |
| --- /dev/null |
| +++ b/internal/thintest/assistant_oficina_contract_test.go |
| @@ -0,0 +1,498 @@ |
| +package thintest |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/oficina/oficinatest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// oficinaRig is an Assistant rig whose instance has oficina-connect |
| +// configured: a fake connect that approves every consent itself. |
| +type oficinaRig struct { |
| + *opsRig |
| + fake *oficinatest.Connect |
| +} |
| + |
| +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) |
| + 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, 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() |
| + 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) |
| + } |
| + 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 |
| +// followed: the status, Location and body. |
| +func (o *oficinaRig) browse(method, raw string) (int, string, string) { |
| + o.t.Helper() |
| + req, _ := http.NewRequest(method, raw, nil) |
| + if strings.HasPrefix(raw, o.inst.URL) { |
| + req.AddCookie(o.inst.Cookie()) |
| + if method == http.MethodPost { |
| + req.Header.Set("Origin", o.inst.URL) |
| + } |
| + } |
| + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + res, err := client.Do(req) |
| + 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) |
| +} |
| + |
| +// consent follows the connect card's link through connect's consent |
| +// and back, as the person's browser does; it returns the last page. |
| +func (o *oficinaRig) consent(start string) string { |
| + o.t.Helper() |
| + status, authorize, _ := o.browse(http.MethodGet, start) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(authorize, o.fake.URL+"/oauth/authorize?") { |
| + o.t.Fatalf("start: %d %q", status, authorize) |
| + } |
| + 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, done, _ := o.anonymous(callback) |
| + 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) |
| + } |
| + return page |
| +} |
| + |
| +// connectCards are the person's connect cards in the Assistant lane. |
| +func (o *oficinaRig) connectCards() []wire.AssistantCard { |
| + o.t.Helper() |
| + snap, err := o.a.Snapshot(o.ctx) |
| + if err != nil { |
| + o.t.Fatal(err) |
| + } |
| + return slices.DeleteFunc(snap.Cards, func(c wire.AssistantCard) bool { return c.Kind != wire.CardConnect }) |
| +} |
| + |
| +// TestContractAssistantOficinaConnectCard: a look for something the |
| +// Oficina apps do, by a person who has not connected them, tells the |
| +// model so and raises one connect card, whose link starts connecting; a |
| +// look for anything else does neither. Connecting (PKCE, checked by the |
| +// fake) settles the card and the apps' operations are listed. |
| +func TestContractAssistantOficinaConnectCard(t *testing.T) { |
| + o := newOficinaRig(t) |
| + o.begin("Put lunch with Ana in my calendar on Friday.") |
| + for _, id := range []string{"l1", "l2"} { |
| + res := o.tool(id, wire.ToolLook, map[string]any{"query": "calendar"}) |
| + if res.IsError || !strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "(oficina)") { |
| + t.Fatalf("look %s: %+v", id, res) |
| + } |
| + } |
| + if res := o.tool("l3", wire.ToolLook, map[string]any{"query": "weather"}); strings.Contains(res.Text, "oficina") { |
| + t.Errorf("weather: %+v", res) |
| + } |
| + cards := o.connectCards() |
| + if len(cards) != 1 { |
| + t.Fatalf("connect cards: %+v", cards) |
| + } |
| + c := cards[0] |
| + 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) |
| + var decoded any |
| + _ = json.Unmarshal(raw, &decoded) |
| + noMachinery(t, "k_none", []string{"/tasks/", "Equipo", "equipo"})("the connect card", decoded, false) |
| + |
| + if status := o.viaBase(); status != "connected" { |
| + t.Errorf("finish: %q", status) |
| + } |
| + if ex, _ := o.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| + cards = o.connectCards() |
| + if len(cards) != 1 || cards[0].State != wire.CardResolved || cards[0].Revision != c.Revision+1 { |
| + t.Errorf("after connecting: %+v", cards) |
| + } |
| + res := o.tool("l4", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + if strings.Contains(res.Text, "not connected") || !strings.Contains(res.Text, "Calendar (oficina)") || !strings.Contains(res.Text, "calendar_create_event") { |
| + t.Errorf("connected look: %+v", res) |
| + } |
| + if n := len(o.connectCards()); n != 1 { |
| + t.Errorf("%d connect cards after connecting", n) |
| + } |
| + |
| + if ex, _ := o.fake.Counts(); ex != 1 { |
| + t.Errorf("exchanges %d", ex) |
| + } |
| +} |
| + |
| +// 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) |
| + 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) |
| + } |
| + 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 ex, _ := o.fake.Counts(); ex != 0 || o.rows("SELECT count(*) FROM oficina_connections") != 0 { |
| + t.Fatalf("exchanged %d", ex) |
| + } |
| + |
| + 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 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") |
| + 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 |
| + 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)"} { |
| + 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 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) |
| + } |
| + } |
| +} |
| + |
| +// 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 |
| +// reach connect with a current bearer (refreshed, rotated, as each |
| +// expires) and the person's one team; the write's client_id is a UUIDv5 |
| +// of its ledger key, the same when a failed call is made again, and a |
| +// repeat is replayed. Destructive, external and unkeyed writes never |
| +// reach connect. Nothing stored or audited carries a token. |
| +func TestContractAssistantOficinaUse(t *testing.T) { |
| + o := newOficinaRig(t) |
| + o.fake.AccessTTL = time.Second |
| + o.begin("Book lunch.") |
| + o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}) |
| + 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"`) { |
| + t.Fatalf("describe: %+v", d) |
| + } |
| + if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "2026-11-20T00:00:00Z", "end": "2026-11-21T00:00:00Z"}); res.IsError || res.Code != "used" { |
| + t.Fatalf("read: %+v", res) |
| + } |
| + o.fake.FailNext = true |
| + lunch := map[string]any{"title": "Lunch with Ana", "start_local": "2026-11-20T13:00"} |
| + if res := o.use("w1", "calendar_create_event", lunch); !res.IsError || res.Code != "unavailable" { |
| + t.Fatalf("failed write: %+v", res) |
| + } |
| + if res := o.use("w2", "calendar_create_event", lunch); res.IsError || res.Code != "used" || res.Replayed { |
| + t.Fatalf("write: %+v", res) |
| + } |
| + if res := o.use("w3", "calendar_create_event", lunch); res.IsError || !res.Replayed { |
| + t.Fatalf("repeat: %+v", res) |
| + } |
| + for op, code := range map[string]string{"docs_delete": "not_yet", "calls_invite": "not_yet", "docs_append": "write_not_supported"} { |
| + if res := o.use("x-"+op, op, map[string]any{"id": "d1", "email": "guest@example.com", "text": "hi"}); !res.IsError || res.Code != code { |
| + t.Errorf("%s: %+v", op, res) |
| + } |
| + } |
| + |
| + calls := o.fake.Calls() |
| + if len(calls) != 3 || calls[0].Name != "calendar_free_busy" || calls[1].Name != "calendar_create_event" || calls[2].Name != "calendar_create_event" { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| + key, _ := calls[1].Input["client_id"].(string) |
| + if !uuidV5.MatchString(key) || calls[2].Input["client_id"] != key { |
| + t.Errorf("client_id %q then %v", key, calls[2].Input["client_id"]) |
| + } |
| + for _, c := range calls { |
| + if c.Input["team"] != "acme" || c.Bearer == "" { |
| + t.Errorf("call %s: %+v", c.Name, c) |
| + } |
| + } |
| + if _, refreshes := o.fake.Counts(); refreshes == 0 { |
| + t.Error("expired access tokens were not refreshed") |
| + } |
| + |
| + // The refresh token is stored sealed; neither it nor any access |
| + // token is in the audit or the logs. |
| + var sealed string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + if o.fake.Live(sealed) { |
| + t.Error("the refresh token is stored as it is") |
| + } |
| + logs := o.inst.Logs() |
| + for _, c := range calls { |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE record_id LIKE ?", "%"+c.Bearer+"%"); n != 0 || strings.Contains(logs, c.Bearer) { |
| + t.Error("an access token in the audit or the logs") |
| + } |
| + } |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.connect' AND actor = ? AND record_id = ''", Owner); n != 1 { |
| + t.Errorf("connect audits %d", n) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaDisconnect: the person's disconnect |
| +// revokes the connection at connect and forgets it; the next look for |
| +// the apps raises a connect card again. |
| +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.viaBase() |
| + if res := o.use("r1", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); res.IsError { |
| + t.Fatalf("read: %+v", res) |
| + } |
| + var sealed string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT refresh FROM oficina_connections WHERE person = ?", Owner).Scan(&sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + status, _, page := o.browse(http.MethodPost, o.inst.URL+"/oficina/connect/disconnect") |
| + if status != http.StatusOK || !strings.Contains(page, "Your Oficina apps are disconnected.") { |
| + t.Fatalf("disconnect: %d %s", status, page) |
| + } |
| + if revoked := o.fake.Revoked(); len(revoked) != 1 || o.fake.Live(revoked[0]) { |
| + t.Errorf("revoked %v", revoked) |
| + } |
| + if n := o.rows("SELECT count(*) FROM oficina_connections"); n != 0 { |
| + t.Errorf("%d connections kept", n) |
| + } |
| + if n := o.rows("SELECT count(*) FROM audit_events WHERE kind = 'oficina.disconnect' AND actor = ?", Owner); n != 1 { |
| + t.Errorf("disconnect audits %d", n) |
| + } |
| + if res := o.tool("l2", wire.ToolLook, map[string]any{"query": "calendar"}); !strings.Contains(res.Text, "not connected") { |
| + t.Errorf("look after disconnecting: %+v", res) |
| + } |
| + if res := o.use("r2", "calendar_free_busy", map[string]any{"start": "a", "end": "b"}); !res.IsError { |
| + t.Errorf("use after disconnecting: %+v", res) |
| + } |
| + cards := o.connectCards() |
| + if len(cards) != 2 || cards[0].State == cards[1].State { |
| + t.Errorf("cards after disconnecting: %+v", cards) |
| + } |
| +} |
| + |
| +// TestContractAssistantOficinaOffByDefault: without |
| +// EQUIPO_OFICINA_CONNECT_ORIGIN nothing changes: no hint, no card, no |
| +// routes. |
| +func TestContractAssistantOficinaOffByDefault(t *testing.T) { |
| + o := newOpsRig(t) |
| + o.begin("Put lunch in my calendar.") |
| + if res := o.tool("l1", wire.ToolLook, map[string]any{"query": "calendar"}); strings.Contains(res.Text, "oficina") { |
| + t.Errorf("look: %+v", res) |
| + } |
| + snap, err := o.a.Snapshot(o.ctx) |
| + 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) |
| + } |
| + for _, path := range []string{"/oficina/connect/start", "/oficina/connect/callback"} { |
| + req, _ := http.NewRequest(http.MethodGet, o.inst.URL+path, nil) |
| + req.AddCookie(o.inst.Cookie()) |
| + res, err := (&http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}).Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res.Body.Close() |
| + if res.StatusCode != http.StatusNotFound { |
| + t.Errorf("%s: %d", path, res.StatusCode) |
| + } |
| + } |
| +} |
| + |
| +// 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) |
| + } |
| +} |
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go| index 3b29571a..134ceb6d 100644 |
| --- a/internal/thintest/instance.go |
| +++ b/internal/thintest/instance.go |
| @@ -58,6 +58,9 @@ type Instance struct { |
| // from the next start (StartInstanceWith, Restart). |
| AssistantHosts []string |
| Providers []assist.Provider |
| + // OficinaConnect and OficinaClientID are |
| + // EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID. |
| + OficinaConnect, OficinaClientID string |
| addr string |
| server *http.Server |
| @@ -126,7 +129,7 @@ func (i *Instance) serve(t testing.TB, l net.Listener) { |
| t.Fatal(err) |
| } |
| s := equipo.NewStore(d) |
| - router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts}, mail.Logged(i.logger), i.logger, s) |
| + router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts, OficinaConnectOrigin: i.OficinaConnect, OficinaConnectClientID: i.OficinaClientID}, mail.Logged(i.logger), i.logger, s) |
| if err != nil { |
| t.Fatal(err) |
| } |