Add the Oficina provider and an oficina-connect OAuth client
assist.NewOficinaProvider speaks connect's /api/v1 for every Oficina app a person's connection reaches. It names each operation's app from its scope, keys an idempotent write at client_id when the input schema requires a 36-character (or format uuid) string client_id, and hides that field from the model; no other HTTP provider infers a key, so R4 holds there. The team comes from GET /api/v1/connection: filled in when there is exactly one, listed in describe when there are several (team_needed until the model picks one). Destructive and external writes stay not_yet. A refused bearer is dropped and the call made once more. While a person is not connected, look shows the provider's hint for queries about what the apps do and tells the registry's OnUnconnected hook. internal/equipo/oficina is the public client with S256 PKCE: Start asks for every read and write scope connect offers plus offline_access (never a share scope); Finish takes only a state the same person started, unused, under ten minutes old and from connect's issuer. The refresh token is stored sealed (domain oficina.connect) and rotated under a per-person lock; a rotation the store did not take is kept in memory and saved first next time. invalid_grant forgets the connection; Disconnect revokes at connect and forgets it. Access tokens live in memory only. Audits carry codes, never tokens. oficinatest is a fake connect for tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,826
−4
internal/equipo/assist/http.go+4 −0internal/equipo/assist/oficina.go+225 −0internal/equipo/assist/oficina_test.go+260 −0internal/equipo/assist/operation.go+3 −0internal/equipo/assist/registry.go+50 −4internal/equipo/oficina/connect.go+491 −0internal/equipo/oficina/connect_test.go+418 −0internal/equipo/oficina/oficinatest/fake.go+375 −0
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..da033197 |
| --- /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. They now have a card to connect; tell them to use it, then try again." |
| + |
| +// 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..89e8ffd8 |
| --- /dev/null |
| +++ b/internal/equipo/assist/oficina_test.go |
| @@ -0,0 +1,260 @@ |
| +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 |
| + r.OnUnconnected(func(_ context.Context, person, provider string) { hooked = append(hooked, person+"/"+provider) }) |
| + 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") { |
| + t.Errorf("%q: no hint:\n%s", q, out) |
| + } |
| + if len(hooked) != 1 || hooked[0] != "p/oficina" { |
| + t.Errorf("%q: hook %v", q, hooked) |
| + } |
| + } |
| + 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) { hooked = append(hooked, "x") }) |
| + 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..4ae347ad 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,17 @@ 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) |
| +} |
| + |
| +// OnUnconnected sets what look tells when it shows a provider's hint: the |
| +// person asked for something it does and has not connected it. |
| +func (r *Registry) OnUnconnected(f func(ctx context.Context, person, provider string)) { |
| + r.mu.Lock() |
| + r.unconnected = f |
| + r.mu.Unlock() |
| } |
| // NewRegistry returns a registry over providers, listed in the order given. |
| @@ -46,7 +58,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 +76,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 +94,32 @@ 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') |
| + } |
| + b.WriteString(r.providers[i].Name() + " (" + r.providers[i].Name() + ")\n" + text) |
| + r.mu.Lock() |
| + hook := r.unconnected |
| + r.mu.Unlock() |
| + if hook != nil { |
| + hook(ctx, person, r.providers[i].Name()) |
| + } |
| + continue |
| + } |
| var apps []string |
| byApp := map[string][]Operation{} |
| for _, op := range ops { |
| @@ -123,6 +158,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/oficina/connect.go b/internal/equipo/oficina/connect.go| new file mode 100644 |
| index 00000000..dc65d9fe |
| --- /dev/null |
| +++ b/internal/equipo/oficina/connect.go |
| @@ -0,0 +1,491 @@ |
| +// 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") |
| +) |
| + |
| +// 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 |
| +} |
| + |
| +type pending struct { |
| + person, verifier string |
| + expires time.Time |
| +} |
| + |
| +// 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 scopes are every read and write scope connect offers, and |
| +// offline_access; never a share scope. |
| +func (c *Connector) Start(ctx context.Context, person string) (string, error) { |
| + 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, 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 |
| +} |
| + |
| +// Finish completes person's consent from the callback's query: the |
| +// state must be one they started, unused and current, from connect. The |
| +// refresh token is stored sealed; the access token kept in memory. |
| +func (c *Connector) Finish(ctx context.Context, person string, q url.Values) error { |
| + key := digest(q.Get("state")) |
| + c.mu.Lock() |
| + p, ok := c.pending[key] |
| + delete(c.pending, key) |
| + c.mu.Unlock() |
| + if !ok || p.person != person || !c.now().Before(p.expires) || q.Get("iss") != c.cfg.Origin { |
| + return c.failed(ctx, person, "state", ErrExpired) |
| + } |
| + if q.Get("error") != "" { |
| + return c.failed(ctx, person, "access_denied", ErrDenied) |
| + } |
| + form := url.Values{} |
| + form.Set("grant_type", "authorization_code") |
| + form.Set("code", q.Get("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). |
| +func (c *Connector) Host(ctx context.Context, person string) (origin, token string, ok bool, err error) { |
| + lock := c.lock(person) |
| + lock.Lock() |
| + defer lock.Unlock() |
| + c.mu.Lock() |
| + s := c.sessions[person] |
| + c.mu.Unlock() |
| + if s != nil && s.unsaved { |
| + if err := c.save(ctx, person, s.refresh); err != nil { |
| + return "", "", false, err |
| + } |
| + s.unsaved = false |
| + } |
| + if s != nil && s.access != "" && c.now().Add(early).Before(s.expires) { |
| + return c.cfg.Origin, s.access, true, nil |
| + } |
| + refresh := "" |
| + if s != nil { |
| + 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. |
| + next.unsaved = true |
| + 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..01f5cc79 |
| --- /dev/null |
| +++ b/internal/equipo/oficina/connect_test.go |
| @@ -0,0 +1,418 @@ |
| +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) |
| + 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() |
| + if err := r.c.Finish(context.Background(), person, r.consent(t, person)); 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()) |
| + } |
| +} |
| + |
| +// TestConnectStateIsThePersons: a callback's state is one use, for the |
| +// person who started it, from connect itself; a refusal stores nothing. |
| +func TestConnectStateIsThePersons(t *testing.T) { |
| + r := newRig(t) |
| + ctx := context.Background() |
| + q := r.consent(t, "ana@example.com") |
| + if err := r.c.Finish(ctx, "bo@example.com", q); !errors.Is(err, ErrExpired) { |
| + t.Errorf("another person's state: %v", err) |
| + } |
| + if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| + t.Errorf("a state tried by another person stays usable: %v", err) |
| + } |
| + |
| + q = r.consent(t, "ana@example.com") |
| + q.Set("iss", "https://elsewhere.example.com") |
| + if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| + t.Errorf("another issuer: %v", err) |
| + } |
| + |
| + q = r.consent(t, "ana@example.com") |
| + r.clock.add(11 * time.Minute) |
| + if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) { |
| + t.Errorf("an old state: %v", err) |
| + } |
| + |
| + r.fake.Deny = true |
| + q = r.consent(t, "ana@example.com") |
| + if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrDenied) { |
| + t.Errorf("a refusal: %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, "oficina.connect_failed access_denied") || !strings.Contains(a, "oficina.connect_failed state") { |
| + t.Errorf("audit: %s", a) |
| + } |
| + |
| + // A code the fake refuses (a verifier it does not match) stores nothing. |
| + q = r.consent(t, "ana@example.com") |
| + q.Set("code", "not-the-code") |
| + if err := r.c.Finish(ctx, "ana@example.com", q); !errors.Is(err, ErrExpired) || len(r.store.sealed) != 0 { |
| + 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) |
| + } |
| +} |
| + |
| +// 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) |
| +} |