oficina / agent-access Public
Route provisioned teams from Home's directory
A team Alta provisions needed a hand edit of connect's config and a restart. With the new team_contracts_from key, a static team's routes become the operation contracts for provisioned teams, and Home's directory says where each team's apps are. A team gets a route only for a live app at exactly https://<label>.<app>.oficina.works. Authority stays with Home: minting and app introspection re-read the directory for that team and resource. GuardResponse now rechecks the exact resource before a provisioned result is sent, over HTTP and MCP, so an app retired mid-call returns nothing. A team named in routes never takes a provisioned route, and without the key behaviour is unchanged. A bad catalog refuses to start.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+1,170
−24
README.md+23 −1cmd/oficina-connect/main_test.go+12 −0connection/directory.go+62 −5connection/server.go+10 −3connection/team_routes_test.go+557 −0gateway.go+25 −6grant/server.go+12 −0grant/team_routes_test.go+73 −0mcp.go+1 −1operation.go+4 −0schedule_guard.go+13 −2schedule_interop_test.go+1 −1schedule_test.go+3 −3team_arg_test.go+2 −2team_routes.go+118 −0team_routes_test.go+254 −0
CI passed — run details
CI log
=== ci === go vet ./... go test -race ./... ok amadan.net/oficina/agent-access.git 2.300s ok amadan.net/oficina/agent-access.git/client 1.049s ? amadan.net/oficina/agent-access.git/cmd/oficina [no test files] ok amadan.net/oficina/agent-access.git/cmd/oficina-connect 5.667s ok amadan.net/oficina/agent-access.git/connection 4.330s ok amadan.net/oficina/agent-access.git/grant 1.827s
diff --git a/README.md b/README.md| index 6ee5c9d..1cc992d 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -62,7 +62,8 @@ Configuration fields are `origin`, `home_issuer`, `consumer_id`, `home_keys` |
| `routes`. A route binds `team`, `resource` (the app HTTPS origin plus `/api/v1`), |
| and `operations` (the app's exported operation descriptors). Routes are operator |
| configuration, never tool arguments. Only current Home membership and live app |
| -destinations matching those configured routes are eligible. Configure the Home |
| +destinations matching those configured routes are eligible, apart from the teams |
| +described under "Teams Alta provisions". Configure the Home |
| consumer with this origin and the `/auth/assertion` callback. Require an existing |
| admitted local app account linked to Home; the service does not provision one. |
| @@ -93,6 +94,27 @@ never persists operation payloads or results. App implementations retain their |
| own content storage, permissions and retry receipts. JSON validation preserves |
| large integer IDs and decimal bounds and cannot fetch external schema references. |
| +### Teams Alta provisions |
| + |
| +Set `team_contracts_from` to a static team, such as `"team_contracts_from": "Uk"`, and |
| +teams Alta provisions need no route of their own. That team's routes become the operation |
| +contracts for every provisioned team, so each must be one app's canonical resource |
| +(`https://<app>.oficina.works/api/v1`, for Docs, Sheets, Slides, Calendar, Calls or |
| +Memoria). Anything else stops the service from starting. |
| + |
| +Home's directory then decides where a provisioned team's calls go. A team gets a route for |
| +each live app whose origin is exactly `https://<label>.<app>.oficina.works`. Connect reads |
| +that on every request, so an app stops being reachable as soon as Home stops listing it, |
| +including a result already on its way back. A team named in `routes` is never routed this |
| +way. Without the key, only `routes` apply. |
| + |
| +Three limits: |
| + |
| +- A person's connection covers the teams they approved, so a new team means connecting again. |
| +- `calls_schedule` stays with teams named in `routes`. A provisioned team uses the Docs, Calls |
| + and Calendar operations directly. |
| +- An older build refuses a config containing this key, so deploy the build first. |
| + |
| ## Rastrillo convergence |
| The agent on `docs-t1` confirmed explicit descriptors, shared policy checks and |
diff --git a/cmd/oficina-connect/main_test.go b/cmd/oficina-connect/main_test.go| index de6aced..833d9b5 100644 |
| --- a/cmd/oficina-connect/main_test.go |
| +++ b/cmd/oficina-connect/main_test.go |
| @@ -346,3 +346,15 @@ func TestServingOptionsOwnershipAndDeadlines(t *testing.T) { |
| t.Fatal("consent endpoints must not enable speculative loads") |
| } |
| } |
| + |
| +func TestConfigReadsTeamContractsFrom(t *testing.T) { |
| + t.Setenv("OFICINA_CONNECT_DEK", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32))) |
| + cfg, err := loadConfig(syntheticConfig(t)) |
| + if err != nil || cfg.TeamContractsFrom != "" { |
| + t.Fatalf("without the key: %q %v", cfg.TeamContractsFrom, err) |
| + } |
| + raw := bytes.Replace(syntheticConfig(t), []byte(`"routes"`), []byte(`"team_contracts_from": "test", "routes"`), 1) |
| + if cfg, err = loadConfig(raw); err != nil || cfg.TeamContractsFrom != "test" { |
| + t.Fatalf("with the key: %q %v", cfg.TeamContractsFrom, err) |
| + } |
| +} |
diff --git a/connection/directory.go b/connection/directory.go| index d99edf4..27724b0 100644 |
| --- a/connection/directory.go |
| +++ b/connection/directory.go |
| @@ -82,12 +82,53 @@ type credentials struct { |
| directory *Directory |
| store *grant.Store |
| routes []access.Route |
| + // static names every team with a configured route; teamApps is the apps a |
| + // provisioned team can be routed to. |
| + static map[string]bool |
| + teamApps map[string]bool |
| +} |
| + |
| +func newCredentials(directory *Directory, store *grant.Store, routes []access.Route, catalog map[string]string) *credentials { |
| + c := &credentials{directory: directory, store: store, routes: routes, static: map[string]bool{}, teamApps: map[string]bool{}} |
| + for _, route := range routes { |
| + c.static[route.Team] = true |
| + } |
| + for _, app := range catalog { |
| + c.teamApps[app] = true |
| + } |
| + return c |
| } |
| func (c *credentials) teams(ctx context.Context, subject string) ([]grant.Team, error) { |
| return c.resourceTeams(ctx, subject, "") |
| } |
| +// teamRoutes is app to resource for a provisioned team, from Home's current |
| +// answer. A row outside the canonical pattern gets no route; a team whose apps |
| +// do not share one label gets none at all. |
| +func (c *credentials) teamRoutes(team DirectoryTeam) map[string]string { |
| + if c.static[team.ID] { |
| + return nil |
| + } |
| + routes := map[string]string{} |
| + teamLabel := "" |
| + for _, app := range team.Apps { |
| + if !c.teamApps[app.App] { |
| + continue |
| + } |
| + resource, label, ok := access.TeamResource(app.App, app.Origin) |
| + if !ok { |
| + continue |
| + } |
| + if teamLabel != "" && label != teamLabel { |
| + return nil |
| + } |
| + teamLabel = label |
| + routes[app.App] = resource |
| + } |
| + return routes |
| +} |
| + |
| func (c *credentials) resourceTeams(ctx context.Context, subject, resource string) ([]grant.Team, error) { |
| teams, err := c.directory.Lookup(ctx, subject) |
| if err != nil { |
| @@ -103,21 +144,37 @@ func (c *credentials) resourceTeams(ctx context.Context, subject, resource strin |
| } |
| } |
| } |
| + routes := c.teamRoutes(team) |
| + for _, route := range routes { |
| + if resource == "" || resource == route { |
| + found = true |
| + } |
| + } |
| if found { |
| - out = append(out, grant.Team{ID: team.ID, Name: team.Name}) |
| + out = append(out, grant.Team{ID: team.ID, Name: team.Name, Routes: routes}) |
| } |
| } |
| return out, nil |
| } |
| -func (c *credentials) Downstream(ctx context.Context, p access.Principal, resource, team string, scopes []string) (string, error) { |
| + |
| +// CheckRoute answers from Home's current directory whether team owns resource |
| +// for this person. It mints nothing. |
| +func (c *credentials) CheckRoute(ctx context.Context, p access.Principal, resource, team string) error { |
| teams, err := c.resourceTeams(ctx, p.Subject, resource) |
| if err != nil { |
| - return "", err |
| + return err |
| } |
| for _, entry := range teams { |
| if entry.ID == team { |
| - return c.store.Downstream(ctx, p, resource, team, scopes) |
| + return nil |
| } |
| } |
| - return "", access.Fail("forbidden", "The app is no longer available to this team.") |
| + return access.Fail("forbidden", "The app is no longer available to this team.") |
| +} |
| + |
| +func (c *credentials) Downstream(ctx context.Context, p access.Principal, resource, team string, scopes []string) (string, error) { |
| + if err := c.CheckRoute(ctx, p, resource, team); err != nil { |
| + return "", err |
| + } |
| + return c.store.Downstream(ctx, p, resource, team, scopes) |
| } |
diff --git a/connection/server.go b/connection/server.go| index d893dfe..8df3677 100644 |
| --- a/connection/server.go |
| +++ b/connection/server.go |
| @@ -32,6 +32,9 @@ type Config struct { |
| Directory string `json:"directory"` |
| Clients []grant.Client `json:"clients"` |
| Routes []access.Route `json:"routes"` |
| + // TeamContractsFrom names the static team whose routes are the operation |
| + // contracts for teams Alta provisions. Empty leaves only the static routes. |
| + TeamContractsFrom string `json:"team_contracts_from,omitempty"` |
| // Secrets come from deployment secret configuration, never the config file. |
| DEK []byte `json:"-"` |
| DirectoryToken string `json:"-"` |
| @@ -111,8 +114,12 @@ func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Serve |
| if err = store.Sweep(ctx); err != nil { |
| return nil, err |
| } |
| - provider := &credentials{directory, store, cfg.Routes} |
| - registry, err := access.Gateway(cfg.Routes, provider, cfg.Transport) |
| + catalog, err := access.TeamCatalog(cfg.Routes, cfg.TeamContractsFrom) |
| + if err != nil { |
| + return nil, err |
| + } |
| + provider := newCredentials(directory, store, cfg.Routes, catalog) |
| + registry, err := access.TeamGateway(cfg.Routes, catalog, provider, cfg.Transport) |
| if err != nil { |
| return nil, err |
| } |
| @@ -144,7 +151,7 @@ func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Serve |
| return nil, err |
| } |
| mux.Handle("/mcp", grants.ResourceHandler(mcpHandler)) |
| - api := registry.HTTPGuarded(grants, grants, registry.ScheduleResponseGuard) |
| + api := registry.HTTPGuarded(grants, grants, registry.GuardResponse) |
| mux.Handle("/api/v1/connection", grants.ResourceHandler(api)) |
| mux.Handle("/api/v1/operations", grants.ResourceHandler(api)) |
| mux.Handle("/api/v1/operations/", grants.ResourceHandler(api)) |
diff --git a/connection/team_routes_test.go b/connection/team_routes_test.go| new file mode 100644 |
| index 0000000..29af767 |
| --- /dev/null |
| +++ b/connection/team_routes_test.go |
| @@ -0,0 +1,557 @@ |
| +package connection |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/agent-access.git/client" |
| + "amadan.net/oficina/agent-access.git/grant" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "github.com/modelcontextprotocol/go-sdk/mcp" |
| +) |
| + |
| +const ( |
| + teamSubject = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + teamService = "https://connect.example.test" |
| + teamRedirect = "http://127.0.0.1:1/callback" |
| + appMarker = "app_result_marker_5d1c" |
| +) |
| + |
| +type teamFixture struct { |
| + t *testing.T |
| + server *Server |
| + store *grant.Store |
| + http *http.Client |
| + base http.RoundTripper |
| + |
| + mu sync.Mutex |
| + teams []DirectoryTeam |
| + lookups int |
| + onLookup func(int) |
| + hits []string |
| + bearers []string |
| + introspect []int |
| + introBody []string |
| + afterApp func() |
| + body string |
| +} |
| + |
| +type teamTransport struct { |
| + base http.RoundTripper |
| + service, app string |
| +} |
| + |
| +func (x teamTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + target := "" |
| + switch { |
| + case r.URL.Host == strings.TrimPrefix(teamService, "https://"): |
| + target = x.service |
| + case strings.HasSuffix(r.URL.Hostname(), ".oficina.works"): |
| + target = x.app |
| + default: |
| + return x.base.RoundTrip(r) |
| + } |
| + out := r.Clone(r.Context()) |
| + out.Host = r.URL.Host |
| + out.URL.Host = strings.TrimPrefix(target, "https://") |
| + return x.base.RoundTrip(out) |
| +} |
| + |
| +func teamOperation(name, scope string) access.Operation { |
| + return access.Operation{Name: name, Description: "Team operation", Scope: scope, ReadOnly: true, |
| + Input: json.RawMessage(`{"type":"object","required":["team"],"properties":{"team":{"type":"string"}},"additionalProperties":false}`), |
| + Output: json.RawMessage(`{"type":"object"}`)} |
| +} |
| + |
| +func ukRoutes() []access.Route { |
| + return []access.Route{ |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []access.Operation{teamOperation("docs_list", "docs:read")}}, |
| + {Team: "Uk", Resource: "https://calendar.oficina.works/api/v1", Operations: []access.Operation{teamOperation("calendar_list", "calendar:read")}}, |
| + } |
| +} |
| + |
| +func provisioned(id, label string, apps ...string) DirectoryTeam { |
| + team := DirectoryTeam{ID: id, Name: "Team " + id, Apps: []DirectoryApp{}} |
| + for _, app := range apps { |
| + team.Apps = append(team.Apps, DirectoryApp{App: app, Origin: "https://" + label + "." + app + ".oficina.works"}) |
| + } |
| + return team |
| +} |
| + |
| +func ukTeam() DirectoryTeam { |
| + return DirectoryTeam{ID: "Uk", Name: "Oficina", Apps: []DirectoryApp{{App: "docs", Origin: "https://docs.oficina.works"}, {App: "calendar", Origin: "https://calendar.oficina.works"}}} |
| +} |
| + |
| +func newTeamFixture(t *testing.T, contractsFrom string, teams ...DirectoryTeam) *teamFixture { |
| + t.Helper() |
| + f := &teamFixture{t: t, teams: teams, body: `{"marker":"` + appMarker + `"}`} |
| + const token = "service-token-7141d52840e349fe878ae3054a1a1ab5" |
| + directory := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.mu.Lock() |
| + f.lookups++ |
| + n := f.lookups |
| + hook := f.onLookup |
| + f.mu.Unlock() |
| + if hook != nil { |
| + hook(n) |
| + } |
| + f.mu.Lock() |
| + out := append([]DirectoryTeam{}, f.teams...) |
| + f.mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + _ = json.NewEncoder(w).Encode(map[string]any{"teams": out}) |
| + })) |
| + t.Cleanup(directory.Close) |
| + var serviceHandler http.Handler |
| + service := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { serviceHandler.ServeHTTP(w, r) })) |
| + t.Cleanup(service.Close) |
| + f.base = service.Client().Transport |
| + var transport http.RoundTripper |
| + app := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + bearer := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") |
| + raw, _ := json.Marshal(map[string]string{"resource": "https://" + r.Host + "/api/v1"}) |
| + check, _ := http.NewRequest("POST", teamService+"/api/v1/credential", bytes.NewReader(raw)) |
| + check.Header.Set("Authorization", "Bearer "+bearer) |
| + check.Header.Set("Content-Type", "application/json") |
| + status, text := 0, "" |
| + if resp, err := (&http.Client{Transport: transport}).Do(check); err == nil { |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + status, text = resp.StatusCode, string(b) |
| + } |
| + f.mu.Lock() |
| + f.hits = append(f.hits, r.Host) |
| + f.bearers = append(f.bearers, bearer) |
| + f.introspect = append(f.introspect, status) |
| + f.introBody = append(f.introBody, text) |
| + after, body := f.afterApp, f.body |
| + f.mu.Unlock() |
| + if after != nil { |
| + after() |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + _, _ = io.WriteString(w, body) |
| + })) |
| + t.Cleanup(app.Close) |
| + transport = teamTransport{f.base, service.URL, app.URL} |
| + f.http = &http.Client{Transport: transport} |
| + key, err := family.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + d, err := db.Open(filepath.Join(t.TempDir(), "connect.db"), slog.New(slog.DiscardHandler)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + server, err := New(t.Context(), Config{Origin: teamService, HomeIssuer: "https://id.example.test", ConsumerID: "connect", HomeKeys: map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}, Directory: directory.URL, DirectoryToken: token, DEK: []byte(strings.Repeat("d", 32)), Transport: transport, Routes: ukRoutes(), TeamContractsFrom: contractsFrom}, d, slog.New(slog.DiscardHandler)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + serviceHandler = server.Handler |
| + f.server, f.store = server, server.Grants |
| + return f |
| +} |
| + |
| +func (f *teamFixture) setTeams(teams ...DirectoryTeam) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.teams = teams |
| +} |
| + |
| +func (f *teamFixture) reached() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]string{}, f.hits...) |
| +} |
| + |
| +func (f *teamFixture) token(teams ...string) string { |
| + f.t.Helper() |
| + verifier := strings.Repeat("v", 43) |
| + sum := sha256.Sum256([]byte(verifier)) |
| + resource := teamService + "/mcp" |
| + code, err := f.store.CreateCode(f.t.Context(), grant.Grant{Subject: teamSubject, ClientID: client.ClientID, Teams: teams, Scopes: []string{"docs:read", "calendar:read"}}, grant.Code{Redirect: teamRedirect, Challenge: base64.RawURLEncoding.EncodeToString(sum[:]), Resource: resource}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + out, err := f.store.Exchange(f.t.Context(), code, client.ClientID, teamRedirect, resource, verifier) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return out.AccessToken |
| +} |
| + |
| +func (f *teamFixture) call(token, op, team string) (int, string, error) { |
| + f.t.Helper() |
| + req, _ := http.NewRequest("POST", teamService+"/api/v1/operations/"+op, strings.NewReader(`{"team":"`+team+`"}`)) |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := f.http.Do(req) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(resp.Body) |
| + return resp.StatusCode, string(body), err |
| +} |
| + |
| +func (f *teamFixture) operations(token string) []string { |
| + f.t.Helper() |
| + req, _ := http.NewRequest("GET", teamService+"/api/v1/operations", nil) |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + resp, err := f.http.Do(req) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + var out struct { |
| + Operations []struct { |
| + Name string `json:"name"` |
| + } `json:"operations"` |
| + } |
| + if resp.StatusCode != 200 || json.NewDecoder(resp.Body).Decode(&out) != nil { |
| + f.t.Fatalf("operations status %d", resp.StatusCode) |
| + } |
| + names := []string{} |
| + for _, op := range out.Operations { |
| + names = append(names, op.Name) |
| + } |
| + slices.Sort(names) |
| + return names |
| +} |
| + |
| +func (f *teamFixture) introspect1(bearer, resource string) int { |
| + f.t.Helper() |
| + raw, _ := json.Marshal(map[string]string{"resource": resource}) |
| + req, _ := http.NewRequest("POST", teamService+"/api/v1/credential", bytes.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer "+bearer) |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := f.http.Do(req) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + return resp.StatusCode |
| +} |
| + |
| +func TestProvisionedTeamReachesOnlyItsHomeOrigin(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", ukTeam(), provisioned("Tm1", "acme", "docs"), provisioned("Tm2", "beta", "docs", "calendar")) |
| + token := f.token("Tm1") |
| + if got := f.operations(token); !slices.Equal(got, []string{"docs_list"}) { |
| + t.Fatalf("listed %v", got) |
| + } |
| + status, body, err := f.call(token, "docs_list", "Tm1") |
| + if err != nil || status != 200 || !strings.Contains(body, appMarker) { |
| + t.Fatalf("call %d %s %v", status, body, err) |
| + } |
| + if got := f.reached(); !slices.Equal(got, []string{"acme.docs.oficina.works"}) { |
| + t.Fatalf("reached %v", got) |
| + } |
| + if f.introspect[0] != 200 { |
| + t.Fatalf("the app could not verify its token: %d", f.introspect[0]) |
| + } |
| + if status, _, _ := f.call(token, "calendar_list", "Tm1"); status == 200 { |
| + t.Fatal("an app the team does not have was routed") |
| + } |
| + if status, _, _ := f.call(token, "docs_list", "Tm2"); status == 200 { |
| + t.Fatal("a team outside the grant was routed") |
| + } |
| + if got := f.reached(); len(got) != 1 { |
| + t.Fatalf("reached %v", got) |
| + } |
| +} |
| + |
| +func TestATeamIsOfferedOnlyOnceAnAppIsLive(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", provisioned("Tm1", "acme")) |
| + token := f.token("Tm1") |
| + if status, _, _ := f.call(token, "docs_list", "Tm1"); status != 401 { |
| + t.Fatalf("a team with nothing live answered %d", status) |
| + } |
| + f.setTeams(provisioned("Tm1", "acme", "docs")) |
| + if status, body, _ := f.call(token, "docs_list", "Tm1"); status != 200 { |
| + t.Fatalf("activated team %d %s", status, body) |
| + } |
| + f.setTeams(provisioned("Tm1", "acme")) |
| + if status, _, _ := f.call(token, "docs_list", "Tm1"); status != 401 { |
| + t.Fatalf("a retired team answered %d", status) |
| + } |
| + if got := f.reached(); len(got) != 1 { |
| + t.Fatalf("reached %v", got) |
| + } |
| +} |
| + |
| +func TestRetiringAnAppEndsItsLiveTokens(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", provisioned("Tm1", "acme", "docs", "calendar")) |
| + token := f.token("Tm1") |
| + if status, _, _ := f.call(token, "docs_list", "Tm1"); status != 200 { |
| + t.Fatal(status) |
| + } |
| + resource := "https://acme.docs.oficina.works/api/v1" |
| + if got := f.introspect1(f.bearers[0], resource); got != 200 { |
| + t.Fatalf("live token %d", got) |
| + } |
| + f.setTeams(provisioned("Tm1", "acme", "calendar")) |
| + if got := f.introspect1(f.bearers[0], resource); got != 401 { |
| + t.Fatalf("retired app's token answered %d", got) |
| + } |
| + if status, _, _ := f.call(token, "docs_list", "Tm1"); status == 200 { |
| + t.Fatal("retired app was routed") |
| + } |
| + if status, _, _ := f.call(token, "calendar_list", "Tm1"); status != 200 { |
| + t.Fatal("the team's other app went too", status) |
| + } |
| +} |
| + |
| +func TestHomeOriginsOutsideThePatternGetNoRoute(t *testing.T) { |
| + for _, origin := range []string{ |
| + "https://evil.example.test", |
| + "https://acme.docs.oficina.works:8443", |
| + "https://a.b.docs.oficina.works", |
| + "https://acme.calendar.oficina.works", |
| + "https://oficina.docs.oficina.works", |
| + "https://xn--a1.docs.oficina.works", |
| + "https://docs.oficina.works", |
| + "https://acme.docs.oficina.works.evil.test", |
| + "https://ACME.docs.oficina.works", |
| + } { |
| + t.Run(origin, func(t *testing.T) { |
| + bad := DirectoryTeam{ID: "Tm1", Name: "Bad", Apps: []DirectoryApp{{App: "docs", Origin: origin}}} |
| + f := newTeamFixture(t, "Uk", ukTeam(), bad) |
| + if status, _, _ := f.call(f.token("Tm1"), "docs_list", "Tm1"); status != 401 { |
| + t.Fatalf("answered %d", status) |
| + } |
| + if got := f.reached(); len(got) != 0 { |
| + t.Fatalf("reached %v", got) |
| + } |
| + if status, body, _ := f.call(f.token("Uk"), "docs_list", "Uk"); status != 200 { |
| + t.Fatalf("a bad row disturbed Uk: %d %s", status, body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestATeamWithTwoLabelsGetsNoRoutes(t *testing.T) { |
| + mixed := DirectoryTeam{ID: "Tm1", Name: "Mixed", Apps: []DirectoryApp{{App: "docs", Origin: "https://acme.docs.oficina.works"}, {App: "calendar", Origin: "https://beta.calendar.oficina.works"}}} |
| + f := newTeamFixture(t, "Uk", mixed) |
| + if status, _, _ := f.call(f.token("Tm1"), "docs_list", "Tm1"); status != 401 { |
| + t.Fatalf("answered %d", status) |
| + } |
| +} |
| + |
| +func TestAnotherTeamsResourceIsRefused(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", provisioned("Tm1", "acme", "docs"), provisioned("Tm2", "beta", "docs")) |
| + token := f.token("Tm1", "Tm2") |
| + p, err := f.server.Grants.Verify(t.Context(), token, teamService+"/mcp") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + beta := "https://beta.docs.oficina.works/api/v1" |
| + // A token minted for Tm1 against Tm2's app fails the app's online check. |
| + crossed, err := f.store.Downstream(t.Context(), p, beta, "Tm1", []string{"docs:read"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.introspect1(crossed, beta); got != 401 { |
| + t.Fatalf("crossed token answered %d", got) |
| + } |
| + own, err := f.store.Downstream(t.Context(), p, beta, "Tm2", []string{"docs:read"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.introspect1(own, beta); got != 200 { |
| + t.Fatalf("own token answered %d", got) |
| + } |
| +} |
| + |
| +func TestResultIsNotSentOnceTheAppIsGone(t *testing.T) { |
| + both := func() []DirectoryTeam { |
| + return []DirectoryTeam{provisioned("Tm1", "acme", "docs", "calendar"), provisioned("Tm2", "beta", "docs")} |
| + } |
| + retire := func(f *teamFixture) func() { |
| + return func() { |
| + f.setTeams(provisioned("Tm1", "acme", "calendar"), provisioned("Tm2", "beta", "docs")) |
| + } |
| + } |
| + t.Run("http", func(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", both()...) |
| + token := f.token("Tm1", "Tm2") |
| + f.afterApp = retire(f) |
| + status, body, _ := f.call(token, "docs_list", "Tm1") |
| + if status != 403 || strings.Contains(body, appMarker) { |
| + t.Fatalf("sent %d %s", status, body) |
| + } |
| + if got := f.reached(); !slices.Equal(got, []string{"acme.docs.oficina.works"}) { |
| + t.Fatalf("reached %v", got) |
| + } |
| + f.afterApp = nil |
| + if status, body, _ := f.call(token, "docs_list", "Tm2"); status != 200 || !strings.Contains(body, appMarker) { |
| + t.Fatalf("the team that kept the app: %d %s", status, body) |
| + } |
| + }) |
| + t.Run("mcp", func(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", both()...) |
| + token := f.token("Tm1", "Tm2") |
| + session, err := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil).Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: teamService + "/mcp", HTTPClient: &http.Client{Transport: bearerTransport{f.http.Transport, token}}}, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer session.Close() |
| + f.afterApp = retire(f) |
| + result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "docs_list", Arguments: map[string]any{"team": "Tm1"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + text, _ := json.Marshal(result) |
| + if !result.IsError || strings.Contains(string(text), appMarker) { |
| + t.Fatalf("sent %s", text) |
| + } |
| + f.afterApp = nil |
| + result, err = session.CallTool(t.Context(), &mcp.CallToolParams{Name: "docs_list", Arguments: map[string]any{"team": "Tm2"}}) |
| + if err != nil || result.IsError { |
| + t.Fatalf("the team that kept the app: %v %v", result, err) |
| + } |
| + }) |
| +} |
| + |
| +func TestRetirementBetweenChunksStopsTheResponse(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", provisioned("Tm1", "acme", "docs", "calendar")) |
| + token := f.token("Tm1") |
| + f.body = `{"marker":"` + strings.Repeat("x", 300<<10) + `"}` |
| + f.afterApp = func() { |
| + f.mu.Lock() |
| + start := f.lookups |
| + f.onLookup = func(n int) { |
| + // Each check reads Home twice: the first two checks pass. |
| + if n > start+4 { |
| + f.setTeams(provisioned("Tm1", "acme", "calendar")) |
| + } |
| + } |
| + f.mu.Unlock() |
| + } |
| + status, body, err := f.call(token, "docs_list", "Tm1") |
| + if status != 200 { |
| + t.Fatalf("the response never started: %d", status) |
| + } |
| + if err == nil && len(body) >= 300<<10 { |
| + t.Fatalf("the whole result was sent: %d bytes", len(body)) |
| + } |
| +} |
| + |
| +func TestUkIsUnchangedByTheCatalog(t *testing.T) { |
| + type outcome struct { |
| + operations []string |
| + reached []string |
| + status int |
| + lookups int |
| + } |
| + run := func(contractsFrom string) outcome { |
| + // Home lists a provisioned-looking origin under the static team: it |
| + // must still get only its configured routes. |
| + uk := DirectoryTeam{ID: "Uk", Name: "Oficina", Apps: []DirectoryApp{{App: "docs", Origin: "https://docs.oficina.works"}, {App: "calendar", Origin: "https://acme.calendar.oficina.works"}}} |
| + f := newTeamFixture(t, contractsFrom, uk) |
| + token := f.token("Uk") |
| + out := outcome{operations: f.operations(token)} |
| + status, _, _ := f.call(token, "docs_list", "Uk") |
| + out.status = status |
| + if status, _, _ := f.call(token, "calendar_list", "Uk"); status == 200 { |
| + t.Fatal("Uk took a provisioned route") |
| + } |
| + out.reached = f.reached() |
| + f.mu.Lock() |
| + out.lookups = f.lookups |
| + f.mu.Unlock() |
| + return out |
| + } |
| + without, with := run(""), run("Uk") |
| + if !slices.Equal(without.operations, []string{"calendar_list", "docs_list"}) || !slices.Equal(without.reached, []string{"docs.oficina.works"}) || without.status != 200 { |
| + t.Fatalf("baseline changed: %+v", without) |
| + } |
| + if !slices.Equal(with.operations, without.operations) || !slices.Equal(with.reached, without.reached) || with.status != without.status || with.lookups != without.lookups { |
| + t.Fatalf("with the catalog %+v, without %+v", with, without) |
| + } |
| +} |
| + |
| +func TestWithoutTheKeyAProvisionedTeamGetsNothing(t *testing.T) { |
| + f := newTeamFixture(t, "", ukTeam(), provisioned("Tm1", "acme", "docs")) |
| + if status, _, _ := f.call(f.token("Tm1"), "docs_list", "Tm1"); status != 401 { |
| + t.Fatalf("answered %d", status) |
| + } |
| + if got := f.reached(); len(got) != 0 { |
| + t.Fatalf("reached %v", got) |
| + } |
| +} |
| + |
| +func TestABadCatalogRefusesToStart(t *testing.T) { |
| + key, _ := family.Generate() |
| + for name, cfg := range map[string]struct { |
| + from string |
| + routes []access.Route |
| + }{ |
| + "unknown team": {"Nope", ukRoutes()}, |
| + "not canonical": {"St", []access.Route{{Team: "St", Resource: "https://static.example.test/api/v1", Operations: []access.Operation{teamOperation("docs_list", "docs:read")}}}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + d, err := db.Open(filepath.Join(t.TempDir(), "connect.db"), slog.New(slog.DiscardHandler)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + _, err = New(context.Background(), Config{Origin: teamService, HomeIssuer: "https://id.example.test", ConsumerID: "connect", HomeKeys: map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}, Directory: "https://directory.example.test", DirectoryToken: strings.Repeat("t", 40), DEK: []byte(strings.Repeat("d", 32)), Routes: cfg.routes, TeamContractsFrom: cfg.from}, d, slog.New(slog.DiscardHandler)) |
| + if err == nil { |
| + t.Fatal("started") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRoutesNeverLeaveTheService(t *testing.T) { |
| + f := newTeamFixture(t, "Uk", provisioned("Tm1", "acme", "docs", "calendar")) |
| + if status, _, _ := f.call(f.token("Tm1"), "docs_list", "Tm1"); status != 200 { |
| + t.Fatal(status) |
| + } |
| + if got := f.introBody[0]; strings.Contains(got, "acme.calendar") || strings.Contains(strings.ToLower(got), "routes") { |
| + t.Fatalf("introspection carried routes: %s", got) |
| + } |
| +} |
| + |
| +// A static team is held to its configured routes even when Home lists it at an |
| +// origin that would suit a provisioned team. |
| +func TestAStaticTeamNeverGainsAProvisionedOrigin(t *testing.T) { |
| + uk := DirectoryTeam{ID: "Uk", Name: "Oficina", Apps: []DirectoryApp{{App: "calendar", Origin: "https://acme.calendar.oficina.works"}}} |
| + f := newTeamFixture(t, "Uk", uk) |
| + token := f.token("Uk") |
| + if status, _, _ := f.call(token, "calendar_list", "Uk"); status != 401 { |
| + t.Fatalf("answered %d", status) |
| + } |
| + f.setTeams(ukTeam(), uk) |
| + p, err := f.store.Verify(t.Context(), token, teamService+"/mcp") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.setTeams(uk) |
| + resource := "https://acme.calendar.oficina.works/api/v1" |
| + minted, err := f.store.Downstream(t.Context(), p, resource, "Uk", []string{"calendar:read"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.introspect1(minted, resource); got != 401 { |
| + t.Fatalf("introspection answered %d", got) |
| + } |
| + if got := f.reached(); len(got) != 0 { |
| + t.Fatalf("reached %v", got) |
| + } |
| +} |
diff --git a/gateway.go b/gateway.go| index 643381a..87cfd4e 100644 |
| --- a/gateway.go |
| +++ b/gateway.go |
| @@ -27,9 +27,19 @@ type CredentialProvider interface { |
| // Gateway forwards the selected operation to its configured app with a fresh, |
| // audience-bound credential. It stores no content and never follows redirects. |
| func Gateway(routes []Route, credentials CredentialProvider, transport http.RoundTripper) (*Registry, error) { |
| + return TeamGateway(routes, nil, credentials, transport) |
| +} |
| + |
| +// TeamGateway is Gateway with a catalog of operation name to app: the operations |
| +// a provisioned team may use, at the resource Home states for it on each request. |
| +func TeamGateway(routes []Route, catalog map[string]string, credentials CredentialProvider, transport http.RoundTripper) (*Registry, error) { |
| if credentials == nil || len(routes) == 0 { |
| return nil, errors.New("gateway needs routes and a credential provider") |
| } |
| + checker, _ := credentials.(RouteChecker) |
| + if len(catalog) > 0 && checker == nil { |
| + return nil, errors.New("a team catalog needs a provider that can recheck routes") |
| + } |
| type coordinate struct{ team, name string } |
| destinations := map[coordinate]string{} |
| contracts := map[string]Operation{} |
| @@ -52,10 +62,17 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun |
| destinations[key] = route.Resource |
| } |
| } |
| - // destination is the one reader of where a team's operation goes. |
| - destination := func(team, name string) (string, bool) { |
| - resource, ok := destinations[coordinate{team, name}] |
| - return resource, ok |
| + for name := range catalog { |
| + if _, exists := contracts[name]; !exists { |
| + return nil, errors.New("team catalog names an unrouted operation") |
| + } |
| + } |
| + router := &teamRouter{static: map[string]map[string]string{}, catalog: catalog, checker: checker} |
| + for key, resource := range destinations { |
| + if router.static[key.team] == nil { |
| + router.static[key.team] = map[string]string{} |
| + } |
| + router.static[key.team][key.name] = resource |
| } |
| httpClient := &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| operations := make([]Operation, 0, len(contracts)) |
| @@ -63,7 +80,7 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun |
| op := contract |
| op.Available = func(p Principal) bool { |
| for _, team := range p.Teams { |
| - if _, ok := destination(team, op.Name); ok { |
| + if _, _, ok := router.resolve(p, team, op.Name); ok { |
| return true |
| } |
| } |
| @@ -74,7 +91,7 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun |
| if err != nil { |
| return nil, Fail("invalid", "Invalid operation input.") |
| } |
| - resource, exists := destination(team, op.Name) |
| + resource, _, exists := router.resolve(p, team, op.Name) |
| if !exists { |
| return nil, Fail("not_found", "This app operation is unavailable for the selected team.") |
| } |
| @@ -115,6 +132,7 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun |
| if err != nil { |
| return nil, err |
| } |
| + base.router = router |
| schedule := &scheduler{registry: base, credentials: credentials, routes: map[string]map[string]string{}} |
| for key, resource := range destinations { |
| if schedule.routes[key.team] == nil { |
| @@ -137,6 +155,7 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun |
| return nil, err |
| } |
| out.schedule = schedule |
| + out.router = router |
| return out, nil |
| } |
| return base, nil |
diff --git a/grant/server.go b/grant/server.go| index b80f86a..9ba7be1 100644 |
| --- a/grant/server.go |
| +++ b/grant/server.go |
| @@ -30,6 +30,8 @@ type Client struct { |
| type Team struct { |
| ID string `json:"id"` |
| Name string `json:"name"` |
| + // Routes is app to resource for a provisioned team, as Home states it now. |
| + Routes map[string]string `json:"-"` |
| } |
| type Config struct { |
| // IdentityIssuer is the fixed Home namespace; it is not the grant Origin. |
| @@ -471,13 +473,23 @@ func (s *Server) Verify(ctx context.Context, token string) (access.Principal, er |
| return access.Principal{}, access.Fail("unavailable", "Authorization is temporarily unavailable.") |
| } |
| allowed := map[string]bool{} |
| + routes := map[string]map[string]string{} |
| for _, team := range teams { |
| allowed[team.ID] = true |
| + if len(team.Routes) > 0 { |
| + routes[team.ID] = team.Routes |
| + } |
| } |
| filtered := []string{} |
| for _, team := range p.Teams { |
| if allowed[team] { |
| filtered = append(filtered, team) |
| + if routes[team] != nil { |
| + if p.Routes == nil { |
| + p.Routes = map[string]map[string]string{} |
| + } |
| + p.Routes[team] = routes[team] |
| + } |
| } |
| } |
| p.Teams = filtered |
diff --git a/grant/team_routes_test.go b/grant/team_routes_test.go| new file mode 100644 |
| index 0000000..ce19886 |
| --- /dev/null |
| +++ b/grant/team_routes_test.go |
| @@ -0,0 +1,73 @@ |
| +package grant |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/agent-access.git/client" |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +// Verify carries routes only for teams this connection was granted and Home |
| +// still lists. |
| +func TestVerifyCarriesRoutesOnlyForGrantedTeams(t *testing.T) { |
| + ctx := context.Background() |
| + raw, err := sql.Open("sqlite", "file:"+t.TempDir()+"/grant.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer raw.Close() |
| + store, err := NewStore(ctx, raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + const origin = "https://connect.example.test" |
| + listed := []Team{ |
| + {ID: "Tm1", Name: "One", Routes: map[string]string{"docs": "https://one.docs.oficina.works/api/v1"}}, |
| + {ID: "Tm2", Name: "Two", Routes: map[string]string{"docs": "https://two.docs.oficina.works/api/v1"}}, |
| + {ID: "Uk", Name: "Static"}, |
| + } |
| + s, err := NewServer(Config{IdentityIssuer: "https://home.example.test", Origin: origin, Resource: origin + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []Client{{ID: client.ClientID, Name: "CLI", Loopback: true}}, Scopes: map[string]string{"docs:read": "Read"}, SignInPath: "/auth/start", |
| + Subject: func(*http.Request) string { return "" }, |
| + Teams: func(context.Context, string) ([]Team, error) { return listed, nil }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + const verifier = "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" |
| + token := grantedToken(t, store, origin+"/mcp", verifier, []string{"Tm1", "Uk"}) |
| + p, err := s.Verify(ctx, token) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(p.Routes) != 1 || p.Routes["Tm1"]["docs"] != "https://one.docs.oficina.works/api/v1" { |
| + t.Fatalf("routes %v", p.Routes) |
| + } |
| + listed = listed[1:] |
| + p, err = s.Verify(ctx, token) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(p.Routes) != 0 { |
| + t.Fatalf("a team Home stopped listing kept its routes: %v", p.Routes) |
| + } |
| +} |
| + |
| +func grantedToken(t *testing.T, store *Store, resource, verifier string, teams []string) string { |
| + t.Helper() |
| + const redirect = "http://127.0.0.1:1/callback" |
| + sum := sha256.Sum256([]byte(verifier)) |
| + code, err := store.CreateCode(context.Background(), Grant{Subject: "person", ClientID: client.ClientID, Teams: teams, Scopes: []string{"docs:read"}}, Code{Redirect: redirect, Challenge: base64.RawURLEncoding.EncodeToString(sum[:]), Resource: resource}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out, err := store.Exchange(context.Background(), code, client.ClientID, redirect, resource, verifier) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return out.AccessToken |
| +} |
diff --git a/mcp.go b/mcp.go| index 7bf80e9..ebd1c64 100644 |
| --- a/mcp.go |
| +++ b/mcp.go |
| @@ -29,7 +29,7 @@ func (r *Registry) MCPServer(p Principal) *mcp.Server { |
| if err != nil { |
| return nil, err |
| } |
| - if err := r.ScheduleResponseGuard(ctx, p, op.Name, req.Params.Arguments, result); err != nil { |
| + if err := r.GuardResponse(ctx, p, op.Name, req.Params.Arguments, result); err != nil { |
| f := SafeFailure(err) |
| return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: f.Error()}}}, nil |
| } |
diff --git a/operation.go b/operation.go| index f4d3acc..4d1db4e 100644 |
| --- a/operation.go |
| +++ b/operation.go |
| @@ -22,6 +22,9 @@ type Principal struct { |
| Grant string `json:"grant"` |
| Teams []string `json:"teams"` |
| Scopes []string `json:"scopes"` |
| + // Routes is team, then app, to the resource Home states for this request. |
| + // The connection service sets it after verifying; it never leaves the process. |
| + Routes map[string]map[string]string `json:"-"` |
| } |
| func (p Principal) Allows(team, scope string) bool { |
| @@ -71,6 +74,7 @@ type compiled struct { |
| type Registry struct { |
| operations map[string]compiled |
| schedule *scheduler |
| + router *teamRouter |
| } |
| var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) |
diff --git a/schedule_guard.go b/schedule_guard.go| index 8bcaee3..89d4117 100644 |
| --- a/schedule_guard.go |
| +++ b/schedule_guard.go |
| @@ -5,9 +5,20 @@ import ( |
| "encoding/json" |
| ) |
| -// ScheduleResponseGuard performs only current reads and credential checks. |
| +// GuardResponse runs before a result is sent, over HTTP and MCP. A provisioned |
| +// team's call is rechecked against the exact resource it used. |
| +func (r *Registry) GuardResponse(ctx context.Context, p Principal, name string, raw json.RawMessage, result any) error { |
| + if r.router != nil { |
| + if err := r.router.recheck(ctx, p, name, raw); err != nil { |
| + return err |
| + } |
| + } |
| + return r.scheduleResponseGuard(ctx, p, name, raw, result) |
| +} |
| + |
| +// scheduleResponseGuard performs only current reads and credential checks. |
| // Other operations keep their own app-owned emission authorization. |
| -func (r *Registry) ScheduleResponseGuard(ctx context.Context, p Principal, name string, raw json.RawMessage, result any) error { |
| +func (r *Registry) scheduleResponseGuard(ctx context.Context, p Principal, name string, raw json.RawMessage, result any) error { |
| if name != "calls_schedule" { |
| return nil |
| } |
diff --git a/schedule_interop_test.go b/schedule_interop_test.go| index 904db61..d99593c 100644 |
| --- a/schedule_interop_test.go |
| +++ b/schedule_interop_test.go |
| @@ -104,7 +104,7 @@ func TestSuiteSchedulingInterop(t *testing.T) { |
| t.Fatal(err) |
| } |
| verify := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }) |
| - server := httptest.NewTLSServer(gateway.HTTPGuarded(verify, verify, gateway.ScheduleResponseGuard)) |
| + server := httptest.NewTLSServer(gateway.HTTPGuarded(verify, verify, gateway.GuardResponse)) |
| defer server.Close() |
| cli := client.New(&interopStore{client.Credentials{Server: server.URL, Resource: server.URL + "/mcp", TokenEndpoint: server.URL + "/token", Token: &oauth2.Token{AccessToken: "fixture", Expiry: time.Now().Add(time.Hour)}}}) |
| cli.HTTP = server.Client() |
diff --git a/schedule_test.go b/schedule_test.go| index 27b3d54..e2cf4c7 100644 |
| --- a/schedule_test.go |
| +++ b/schedule_test.go |
| @@ -198,7 +198,7 @@ func TestScheduleResumeLostResponsesAndGatewayRestart(t *testing.T) { |
| before := h.reads |
| r := h.gateway(t) |
| raw, _ := json.Marshal(scheduleArgs()) |
| - if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, second); err != nil || h.reads != before+3 { |
| + if err = r.GuardResponse(t.Context(), h.p, "calls_schedule", raw, second); err != nil || h.reads != before+3 { |
| t.Fatal("guard not pure reads", err, h.reads) |
| } |
| changed := scheduleArgs() |
| @@ -237,7 +237,7 @@ func TestScheduleAuthorityAndProvenance(t *testing.T) { |
| } |
| h.objects = map[string]map[string]any{} |
| raw, _ := json.Marshal(scheduleArgs()) |
| - if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); SafeFailure(err).Code != "not_found" { |
| + if err = r.GuardResponse(t.Context(), h.p, "calls_schedule", raw, out); SafeFailure(err).Code != "not_found" { |
| t.Fatal("deleted resource emitted", err) |
| } |
| return |
| @@ -344,7 +344,7 @@ func TestScheduleReferencesCannotEscapeMemberRoutes(t *testing.T) { |
| } |
| out.Steps[0].Resource.URL = "https://foreign.test/d/ghjkmnpqrs" |
| raw, _ := json.Marshal(scheduleArgs()) |
| - if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); err == nil { |
| + if err = r.GuardResponse(t.Context(), h.p, "calls_schedule", raw, out); err == nil { |
| t.Fatal("guard accepted substituted URL") |
| } |
| } |
diff --git a/team_arg_test.go b/team_arg_test.go| index 5c214a0..0eed62b 100644 |
| --- a/team_arg_test.go |
| +++ b/team_arg_test.go |
| @@ -112,7 +112,7 @@ func TestAmbiguousTeamIsRefusedOverHTTPAndMCP(t *testing.T) { |
| f := newTeamArgFixture(t, "acme", "other") |
| verify := VerifyFunc(func(context.Context, string) (Principal, error) { return teamArgPrincipal("acme", "other"), nil }) |
| - api := httptest.NewServer(f.gateway.HTTPGuarded(verify, verify, f.gateway.ScheduleResponseGuard)) |
| + api := httptest.NewServer(f.gateway.HTTPGuarded(verify, verify, f.gateway.GuardResponse)) |
| defer api.Close() |
| req, _ := http.NewRequest("POST", api.URL+"/api/v1/operations/notes_create", strings.NewReader(raw)) |
| req.Header.Set("Authorization", "Bearer test") |
| @@ -221,7 +221,7 @@ func TestScheduleGuardRefusesAnAmbiguousTeam(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - err = r.ScheduleResponseGuard(t.Context(), teamArgPrincipal("acme"), "calls_schedule", json.RawMessage(`{"team":"acme","TEAM":"other"}`), map[string]any{}) |
| + err = r.GuardResponse(t.Context(), teamArgPrincipal("acme"), "calls_schedule", json.RawMessage(`{"team":"acme","TEAM":"other"}`), map[string]any{}) |
| if f := SafeFailure(err); f.Code != "unavailable" || !strings.Contains(f.Message, "provenance") { |
| t.Fatalf("got %v", err) |
| } |
diff --git a/team_routes.go b/team_routes.go| new file mode 100644 |
| index 0000000..1f585bf |
| --- /dev/null |
| +++ b/team_routes.go |
| @@ -0,0 +1,118 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "regexp" |
| + "slices" |
| + "strings" |
| +) |
| + |
| +// teamApps is the closed list of apps a provisioned team can be routed to. |
| +var teamApps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} |
| + |
| +// teamOrigin is the one shape of a provisioned team's app. The label rule is |
| +// Alta's: Home admits more, and anything Alta did not create gets no route. |
| +var teamOrigin = regexp.MustCompile(`^https://([a-z][a-z0-9-]{1,30}[a-z0-9])\.([a-z]+)\.oficina\.works$`) |
| + |
| +// contractResource is the shape of a route that may supply a contract. |
| +var contractResource = regexp.MustCompile(`^https://([a-z]+)\.oficina\.works/api/v1$`) |
| + |
| +// RouteChecker answers whether a team owns a resource for this person now. It |
| +// must read current facts and must not mint or store anything. |
| +type RouteChecker interface { |
| + CheckRoute(ctx context.Context, p Principal, resource, team string) error |
| +} |
| + |
| +// TeamResource returns the resource for an app origin Home stated, when the |
| +// origin is exactly https://<label>.<app>.oficina.works. |
| +func TeamResource(app, origin string) (resource, label string, ok bool) { |
| + match := teamOrigin.FindStringSubmatch(origin) |
| + if match == nil || match[2] != app || !slices.Contains(teamApps, app) { |
| + return "", "", false |
| + } |
| + label = match[1] |
| + if label == "oficina" || strings.Contains(label, "--") { |
| + return "", "", false |
| + } |
| + return origin + "/api/v1", label, true |
| +} |
| + |
| +// TeamCatalog maps each operation of a static team's routes to its app, for |
| +// use with provisioned teams. An empty team means no catalog. Any route that is |
| +// not one app's canonical resource refuses the whole catalog. |
| +func TeamCatalog(routes []Route, team string) (map[string]string, error) { |
| + if team == "" { |
| + return nil, nil |
| + } |
| + catalog := map[string]string{} |
| + apps := map[string]bool{} |
| + for _, route := range routes { |
| + if route.Team != team { |
| + continue |
| + } |
| + match := contractResource.FindStringSubmatch(route.Resource) |
| + if match == nil || !slices.Contains(teamApps, match[1]) || apps[match[1]] { |
| + return nil, errors.New("team contracts need one canonical route per app") |
| + } |
| + apps[match[1]] = true |
| + for _, op := range route.Operations { |
| + if _, exists := catalog[op.Name]; exists { |
| + return nil, errors.New("team contracts repeat an operation") |
| + } |
| + catalog[op.Name] = match[1] |
| + } |
| + } |
| + if len(catalog) == 0 { |
| + return nil, errors.New("team contracts name a team without routes") |
| + } |
| + return catalog, nil |
| +} |
| + |
| +// teamRouter is the one reader of where an operation goes. |
| +type teamRouter struct { |
| + static map[string]map[string]string // team, operation -> configured resource |
| + catalog map[string]string // operation -> app |
| + checker RouteChecker |
| +} |
| + |
| +// resolve answers the destination of one team's operation. A team with any |
| +// configured route is static and never takes a provisioned route. |
| +func (t *teamRouter) resolve(p Principal, team, name string) (resource string, provisioned, ok bool) { |
| + if routes, static := t.static[team]; static { |
| + resource, ok = routes[name] |
| + return resource, false, ok |
| + } |
| + app, ok := t.catalog[name] |
| + if !ok { |
| + return "", false, false |
| + } |
| + resource = p.Routes[team][app] |
| + origin, cut := strings.CutSuffix(resource, "/api/v1") |
| + if !cut { |
| + return "", false, false |
| + } |
| + if _, _, ok = TeamResource(app, origin); !ok { |
| + return "", false, false |
| + } |
| + return resource, true, true |
| +} |
| + |
| +// recheck refuses a provisioned result whose team no longer owns the resource |
| +// the call used. Static teams and operations outside the catalog pass through. |
| +func (t *teamRouter) recheck(ctx context.Context, p Principal, name string, raw json.RawMessage) error { |
| + if _, listed := t.catalog[name]; !listed { |
| + return nil |
| + } |
| + // An unreadable team stays empty, and the empty team has no route. |
| + team, _ := operationTeam(raw) |
| + resource, provisioned, ok := t.resolve(p, team, name) |
| + if !ok { |
| + return Fail("forbidden", "Connection access changed.") |
| + } |
| + if !provisioned { |
| + return nil |
| + } |
| + return t.checker.CheckRoute(ctx, p, resource, team) |
| +} |
diff --git a/team_routes_test.go b/team_routes_test.go| new file mode 100644 |
| index 0000000..ec76f42 |
| --- /dev/null |
| +++ b/team_routes_test.go |
| @@ -0,0 +1,254 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +type checkingCredentials struct { |
| + testCredentials |
| + checks []string |
| + refuse bool |
| +} |
| + |
| +func (c *checkingCredentials) CheckRoute(_ context.Context, _ Principal, resource, team string) error { |
| + c.checks = append(c.checks, team+" "+resource) |
| + if c.refuse { |
| + return Fail("forbidden", "The app is no longer available to this team.") |
| + } |
| + return nil |
| +} |
| + |
| +func TestTeamResourceIsTheCanonicalPatternOnly(t *testing.T) { |
| + good, label, ok := TeamResource("docs", "https://acme-2.docs.oficina.works") |
| + if !ok || good != "https://acme-2.docs.oficina.works/api/v1" || label != "acme-2" { |
| + t.Fatal(good, label, ok) |
| + } |
| + for _, tc := range [][2]string{ |
| + {"docs", "https://docs.oficina.works"}, |
| + {"docs", "https://oficina.docs.oficina.works"}, |
| + {"docs", "https://acme.calendar.oficina.works"}, |
| + {"docs", "https://a.b.docs.oficina.works"}, |
| + {"docs", "https://acme.docs.oficina.works:8443"}, |
| + {"docs", "https://acme.docs.oficina.works/"}, |
| + {"docs", "https://acme.docs.oficina.works.evil.test"}, |
| + {"docs", "https://acme.docs.evil.test"}, |
| + {"docs", "http://acme.docs.oficina.works"}, |
| + {"docs", "https://ACME.docs.oficina.works"}, |
| + {"docs", "https://xn--a1.docs.oficina.works"}, |
| + {"docs", "https://ab.docs.oficina.works"}, |
| + {"docs", "https://-acme.docs.oficina.works"}, |
| + {"docs", "https://acme-.docs.oficina.works"}, |
| + {"docs", "https://" + strings.Repeat("a", 33) + ".docs.oficina.works"}, |
| + {"fichas", "https://acme.fichas.oficina.works"}, |
| + {"", "https://acme..oficina.works"}, |
| + } { |
| + if resource, _, ok := TeamResource(tc[0], tc[1]); ok { |
| + t.Errorf("%s %s admitted as %s", tc[0], tc[1], resource) |
| + } |
| + } |
| +} |
| + |
| +func catalogOp(name string) Operation { |
| + return Operation{Name: name, Description: "An operation", Scope: "notes:write", |
| + Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"}},"required":["team"],"additionalProperties":false}`), |
| + Output: json.RawMessage(`{"type":"object"}`)} |
| +} |
| + |
| +func TestTeamCatalogComesFromCanonicalRoutes(t *testing.T) { |
| + routes := []Route{ |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("docs_list")}}, |
| + {Team: "Uk", Resource: "https://calendar.oficina.works/api/v1", Operations: []Operation{catalogOp("calendar_list")}}, |
| + {Team: "St", Resource: "https://other.example.test/api/v1", Operations: []Operation{catalogOp("other_list")}}, |
| + } |
| + got, err := TeamCatalog(routes, "Uk") |
| + if err != nil || len(got) != 2 || got["docs_list"] != "docs" || got["calendar_list"] != "calendar" { |
| + t.Fatal(got, err) |
| + } |
| + if got, err := TeamCatalog(routes, ""); err != nil || got != nil { |
| + t.Fatal("no team must mean no catalog", got, err) |
| + } |
| + for name, tc := range map[string]struct { |
| + routes []Route |
| + team string |
| + }{ |
| + "unknown team": {routes, "Nope"}, |
| + "not canonical": {routes, "St"}, |
| + "unknown app": {[]Route{{Team: "Uk", Resource: "https://fichas.oficina.works/api/v1", Operations: []Operation{catalogOp("f")}}}, "Uk"}, |
| + "provisioned": {[]Route{{Team: "Uk", Resource: "https://acme.docs.oficina.works/api/v1", Operations: []Operation{catalogOp("f")}}}, "Uk"}, |
| + "app twice": {[]Route{ |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("a")}}, |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("b")}}}, "Uk"}, |
| + "operation twice": {[]Route{ |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("a")}}, |
| + {Team: "Uk", Resource: "https://sheets.oficina.works/api/v1", Operations: []Operation{catalogOp("a")}}}, "Uk"}, |
| + } { |
| + if got, err := TeamCatalog(tc.routes, tc.team); err == nil { |
| + t.Errorf("%s: accepted %v", name, got) |
| + } |
| + } |
| +} |
| + |
| +type teamGatewayFixture struct { |
| + gateway *Registry |
| + credentials *checkingCredentials |
| + mu sync.Mutex |
| + hosts []string |
| +} |
| + |
| +func (f *teamGatewayFixture) reached() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]string{}, f.hosts...) |
| +} |
| + |
| +func newTeamGateway(t *testing.T) *teamGatewayFixture { |
| + t.Helper() |
| + f := &teamGatewayFixture{credentials: &checkingCredentials{}} |
| + routes := []Route{ |
| + {Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("docs_list")}}, |
| + {Team: "Uk", Resource: "https://calendar.oficina.works/api/v1", Operations: []Operation{catalogOp("calendar_list")}}, |
| + {Team: "St", Resource: "https://static.example.test/api/v1", Operations: []Operation{catalogOp("docs_list")}}, |
| + } |
| + catalog := map[string]string{"docs_list": "docs", "calendar_list": "calendar"} |
| + transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| + f.mu.Lock() |
| + f.hosts = append(f.hosts, r.URL.Host) |
| + f.mu.Unlock() |
| + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{}`)), Request: r}, nil |
| + }) |
| + gateway, err := TeamGateway(routes, catalog, f.credentials, transport) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.gateway = gateway |
| + return f |
| +} |
| + |
| +func routed(teams []string, routes map[string]map[string]string) Principal { |
| + return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: teams, Scopes: []string{"notes:write"}, Routes: routes} |
| +} |
| + |
| +const acmeDocs = "https://acme.docs.oficina.works/api/v1" |
| + |
| +func TestProvisionedRouteGoesToTheResourceHomeStated(t *testing.T) { |
| + f := newTeamGateway(t) |
| + p := routed([]string{"Tm", "Uk"}, map[string]map[string]string{"Tm": {"docs": acmeDocs}}) |
| + if _, err := f.gateway.Call(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Tm"}`)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.reached(); len(got) != 1 || got[0] != "acme.docs.oficina.works" || f.credentials.resource != acmeDocs || f.credentials.team != "Tm" { |
| + t.Fatalf("reached %v, minted %s for %s", got, f.credentials.resource, f.credentials.team) |
| + } |
| + if _, err := f.gateway.Call(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Uk"}`)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.reached(); got[1] != "docs.oficina.works" { |
| + t.Fatalf("Uk went to %v", got) |
| + } |
| +} |
| + |
| +func TestProvisionedOperationsAreListedPerLiveApp(t *testing.T) { |
| + f := newTeamGateway(t) |
| + names := func(p Principal) string { |
| + out := []string{} |
| + for _, op := range f.gateway.List(p) { |
| + out = append(out, op.Name) |
| + } |
| + return strings.Join(out, ",") |
| + } |
| + if got := names(routed([]string{"Tm"}, map[string]map[string]string{"Tm": {"docs": acmeDocs}})); got != "docs_list" { |
| + t.Fatalf("listed %q", got) |
| + } |
| + if got := names(routed([]string{"Tm"}, nil)); got != "" { |
| + t.Fatalf("no route listed %q", got) |
| + } |
| + if got := names(routed([]string{"Other"}, map[string]map[string]string{"Tm": {"docs": acmeDocs}})); got != "" { |
| + t.Fatalf("another team's route listed %q", got) |
| + } |
| +} |
| + |
| +func TestRoutesTheGatewayMustNotUse(t *testing.T) { |
| + for name, tc := range map[string]struct { |
| + team, op string |
| + routes map[string]map[string]string |
| + }{ |
| + "no route": {"Tm", "docs_list", nil}, |
| + "another team's": {"Tm", "docs_list", map[string]map[string]string{"Tb": {"docs": acmeDocs}}}, |
| + "another app's": {"Tm", "calendar_list", map[string]map[string]string{"Tm": {"docs": acmeDocs}}}, |
| + "outside pattern": {"Tm", "docs_list", map[string]map[string]string{"Tm": {"docs": "https://evil.example.test/api/v1"}}}, |
| + "wrong app's host": {"Tm", "docs_list", map[string]map[string]string{"Tm": {"docs": "https://acme.calendar.oficina.works/api/v1"}}}, |
| + "origin only": {"Tm", "docs_list", map[string]map[string]string{"Tm": {"docs": "https://acme.docs.oficina.works"}}}, |
| + "static team": {"St", "calendar_list", map[string]map[string]string{"St": {"calendar": "https://acme.calendar.oficina.works/api/v1"}}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + f := newTeamGateway(t) |
| + p := routed([]string{tc.team, "Uk"}, tc.routes) |
| + _, err := f.gateway.Call(t.Context(), p, tc.op, json.RawMessage(`{"team":"`+tc.team+`"}`)) |
| + if err == nil || f.credentials.calls != 0 || len(f.reached()) != 0 { |
| + t.Fatalf("got %v, minted %d, reached %v", err, f.credentials.calls, f.reached()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGuardRechecksTheExactProvisionedRoute(t *testing.T) { |
| + f := newTeamGateway(t) |
| + p := routed([]string{"Tm", "Uk"}, map[string]map[string]string{"Tm": {"docs": acmeDocs}}) |
| + if err := f.gateway.GuardResponse(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Tm"}`), map[string]any{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.credentials.checks) != 1 || f.credentials.checks[0] != "Tm "+acmeDocs { |
| + t.Fatalf("checked %v", f.credentials.checks) |
| + } |
| + f.credentials.refuse = true |
| + if err := f.gateway.GuardResponse(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Tm"}`), map[string]any{}); SafeFailure(err).Code != "forbidden" { |
| + t.Fatalf("refusal lost: %v", err) |
| + } |
| + if err := f.gateway.GuardResponse(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Tm","TEAM":"Uk"}`), map[string]any{}); err == nil { |
| + t.Fatal("ambiguous team passed the guard") |
| + } |
| + if err := f.gateway.GuardResponse(t.Context(), routed([]string{"Tm"}, nil), "docs_list", json.RawMessage(`{"team":"Tm"}`), map[string]any{}); err == nil { |
| + t.Fatal("a route that is gone passed the guard") |
| + } |
| +} |
| + |
| +func TestGuardLeavesStaticTeamsAlone(t *testing.T) { |
| + f := newTeamGateway(t) |
| + f.credentials.refuse = true |
| + p := routed([]string{"Uk"}, nil) |
| + if err := f.gateway.GuardResponse(t.Context(), p, "docs_list", json.RawMessage(`{"team":"Uk"}`), map[string]any{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.gateway.GuardResponse(t.Context(), p, "", nil, map[string]any{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.credentials.checks) != 0 { |
| + t.Fatalf("static team made checks: %v", f.credentials.checks) |
| + } |
| +} |
| + |
| +func TestCatalogNeedsAProviderThatCanRecheck(t *testing.T) { |
| + routes := []Route{{Team: "Uk", Resource: "https://docs.oficina.works/api/v1", Operations: []Operation{catalogOp("docs_list")}}} |
| + if _, err := TeamGateway(routes, map[string]string{"docs_list": "docs"}, &testCredentials{}, http.DefaultTransport); err == nil { |
| + t.Fatal("started without a way to recheck provisioned routes") |
| + } |
| + if _, err := TeamGateway(routes, map[string]string{"nope": "docs"}, &checkingCredentials{}, http.DefaultTransport); err == nil { |
| + t.Fatal("catalog named an operation no route carries") |
| + } |
| + if _, err := TeamGateway(routes, nil, &testCredentials{}, http.DefaultTransport); err != nil { |
| + t.Fatal("static routes need no recheck", err) |
| + } |
| +} |
| + |
| +func TestPrincipalRoutesAreNeverSerialised(t *testing.T) { |
| + raw, err := json.Marshal(routed([]string{"Tm"}, map[string]map[string]string{"Tm": {"docs": acmeDocs}})) |
| + if err != nil || strings.Contains(string(raw), "acme") || strings.Contains(strings.ToLower(string(raw)), "routes") { |
| + t.Fatalf("%s %v", raw, err) |
| + } |
| +} |