Read an operation's team and destination in one place

Registry.Call authorized the exact key "team", while the gateway's Invoke
decoded the same input with encoding/json, which matches keys without
regard to case. Duplicate detection treats "team" and "TEAM" as different
keys, so {"team":"B","TEAM":"A"} was authorized for B and routed to A
wherever a contract allowed the extra field.

operationTeam is now the only reader of the team, and Call, Invoke, the
HTTP response check and the scheduler's response guard all use it. Any
other top-level spelling of "team" is refused as invalid before a token
is minted or an app is called. The gateway's destination lookup is one
function too. Valid calls are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4e27e9e9faa5c5e7c241ff1a4a943a6ed9eecce6 parent a9810cf
5 files changed, +286 −12
  • gateway.go +10 −7
  • http_guarded.go +2 −3
  • operation.go +31 −1
  • schedule_guard.go +5 −1
  • team_arg_test.go +238 −0

CI passed — run details

CI log
=== ci ===
go vet ./...
go test -race ./...
ok  	amadan.net/oficina/agent-access.git	2.267s
ok  	amadan.net/oficina/agent-access.git/client	1.048s
?   	amadan.net/oficina/agent-access.git/cmd/oficina	[no test files]
ok  	amadan.net/oficina/agent-access.git/cmd/oficina-connect	5.620s
ok  	amadan.net/oficina/agent-access.git/connection	1.364s
ok  	amadan.net/oficina/agent-access.git/grant	1.794s
diff --git a/gateway.go b/gateway.go
index 2faf883..643381a 100644
--- a/gateway.go
+++ b/gateway.go
@@ -52,30 +52,33 @@ 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
+ }
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))
for _, contract := range contracts {
op := contract
op.Available = func(p Principal) bool {
for _, team := range p.Teams {
- if _, ok := destinations[coordinate{team, op.Name}]; ok {
+ if _, ok := destination(team, op.Name); ok {
return true
}
}
return false
}
op.Invoke = func(ctx context.Context, p Principal, input json.RawMessage) (any, error) {
- var args struct {
- Team string `json:"team"`
- }
- if json.Unmarshal(input, &args) != nil {
+ team, err := operationTeam(input)
+ if err != nil {
return nil, Fail("invalid", "Invalid operation input.")
}
- resource, exists := destinations[coordinate{args.Team, op.Name}]
+ resource, exists := destination(team, op.Name)
if !exists {
return nil, Fail("not_found", "This app operation is unavailable for the selected team.")
}
- token, err := credentials.Downstream(ctx, p, resource, args.Team, []string{op.Scope})
+ token, err := credentials.Downstream(ctx, p, resource, team, []string{op.Scope})
if err != nil {
if f := SafeFailure(err); f.Code == "unavailable" || f.Code == "forbidden" {
return nil, f
diff --git a/http_guarded.go b/http_guarded.go
index ee41b39..2a93148 100644
--- a/http_guarded.go
+++ b/http_guarded.go
@@ -32,9 +32,8 @@ func (registry *Registry) HTTPGuarded(initial, recheck Verifier, guard ResponseG
}
var team string
if name != "" {
- var input map[string]any
- _ = DecodeJSON(raw, &input)
- team, _ = input["team"].(string)
+ // An unreadable team stays empty, which no connection allows.
+ team, _ = operationTeam(raw)
}
check := func(ctx context.Context) error {
fresh, err := recheck.Verify(ctx, token)
diff --git a/operation.go b/operation.go
index f387cd4..f4d3acc 100644
--- a/operation.go
+++ b/operation.go
@@ -8,6 +8,7 @@ import (
"fmt"
"regexp"
"sort"
+ "strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
@@ -149,7 +150,10 @@ func (r *Registry) Call(ctx context.Context, p Principal, name string, raw json.
if DecodeJSON(raw, &input) != nil || input == nil {
return nil, Fail("invalid", "Send a JSON object.")
}
- team, _ := input["team"].(string)
+ team, err := teamOf(input)
+ if err != nil {
+ return nil, Fail("invalid", "Send one JSON object with unique field names.")
+ }
if !p.Allows(team, entry.op.Scope) {
return nil, Fail("forbidden", "This connection does not allow that team and operation.")
}
@@ -174,6 +178,32 @@ func (r *Registry) Call(ctx context.Context, p Principal, name string, raw json.
return value, nil
}
+var errAmbiguousTeam = errors.New("ambiguous operation team")
+
+// operationTeam is the one reader of an operation's team. Authorization,
+// routing and the checks before a response is sent all use it, so they cannot
+// settle on different teams for the same input.
+func operationTeam(raw json.RawMessage) (string, error) {
+ var input map[string]any // DecodeJSON refuses duplicate keys.
+ if DecodeJSON(raw, &input) != nil || input == nil {
+ return "", errAmbiguousTeam
+ }
+ return teamOf(input)
+}
+
+// teamOf reads the exact key "team". encoding/json matches keys without regard
+// to case, and duplicate detection does not, so any other spelling is refused
+// rather than left for a later decoder to prefer.
+func teamOf(input map[string]any) (string, error) {
+ for key := range input {
+ if key != "team" && strings.EqualFold(key, "team") {
+ return "", errAmbiguousTeam
+ }
+ }
+ team, _ := input["team"].(string)
+ return team, nil
+}
+
// Contracts are self-contained. Schema compilation must never fetch URLs or
// read local files supplied through a reference in a deployment contract.
type localSchemas struct{}
diff --git a/schedule_guard.go b/schedule_guard.go
index 849df71..8bcaee3 100644
--- a/schedule_guard.go
+++ b/schedule_guard.go
@@ -11,13 +11,17 @@ func (r *Registry) ScheduleResponseGuard(ctx context.Context, p Principal, name
if name != "calls_schedule" {
return nil
}
+ team, err := operationTeam(raw)
+ if err != nil {
+ return Fail("unavailable", "Workflow provenance is unavailable.")
+ }
if r.schedule == nil {
return Fail("unavailable", "Scheduling is unavailable.")
}
var in scheduleInput
var out scheduleResult
body, err := json.Marshal(result)
- if err != nil || len(body) > 65535 || json.Unmarshal(raw, &in) != nil || json.Unmarshal(body, &out) != nil || out.Team != in.Team || out.ClientID != in.ClientID {
+ if err != nil || len(body) > 65535 || json.Unmarshal(raw, &in) != nil || json.Unmarshal(body, &out) != nil || in.Team != team || out.Team != team || out.ClientID != in.ClientID {
return Fail("unavailable", "Workflow provenance is unavailable.")
}
return r.schedule.revalidate(ctx, p, in, out)
diff --git a/team_arg_test.go b/team_arg_test.go
new file mode 100644
index 0000000..5c214a0
--- /dev/null
+++ b/team_arg_test.go
@@ -0,0 +1,238 @@
+package agentaccess
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// permissiveNote has no additionalProperties:false, so a stray key reaches
+// the routing code instead of being refused by the schema.
+func permissiveNote() Operation {
+ return Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write",
+ Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"},"title":{"type":"string"}},"required":["title"]}`),
+ Output: json.RawMessage(`{"type":"object"}`)}
+}
+
+// teamArgFixture is a real Gateway in front of one TLS app per routed team.
+type teamArgFixture struct {
+ gateway *Registry
+ credentials *testCredentials
+ mu sync.Mutex
+ hits []string
+ bodies []string
+}
+
+func (f *teamArgFixture) reached() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string{}, f.hits...)
+}
+
+func newTeamArgFixture(t *testing.T, teams ...string) *teamArgFixture {
+ t.Helper()
+ f := &teamArgFixture{credentials: &testCredentials{}}
+ mux := http.NewServeMux()
+ s := httptest.NewTLSServer(mux)
+ t.Cleanup(s.Close)
+ routes := []Route{}
+ for _, team := range teams {
+ routes = append(routes, Route{Team: team, Resource: "https://" + team + ".test/api/v1", Operations: []Operation{permissiveNote()}})
+ mux.HandleFunc("POST /"+team+"/api/v1/operations/notes_create", func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ f.mu.Lock()
+ f.hits, f.bodies = append(f.hits, team), append(f.bodies, string(body))
+ f.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{}`))
+ })
+ }
+ base := s.Client().Transport
+ rewrite := roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ out := r.Clone(r.Context())
+ team := strings.TrimSuffix(r.URL.Hostname(), ".test")
+ out.URL.Scheme, out.URL.Host = "https", strings.TrimPrefix(s.URL, "https://")
+ out.URL.Path = "/" + team + r.URL.Path
+ return base.RoundTrip(out)
+ })
+ gateway, err := Gateway(routes, f.credentials, rewrite)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.gateway = gateway
+ return f
+}
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func teamArgPrincipal(teams ...string) Principal {
+ return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: teams, Scopes: []string{"notes:write"}}
+}
+
+// Every spelling encoding/json would fold onto "team", in both orders, with
+// the same value and with another team's.
+var ambiguousTeamInputs = []string{
+ `{"team":"acme","TEAM":"other","title":"x"}`,
+ `{"TEAM":"other","team":"acme","title":"x"}`,
+ `{"team":"other","TEAM":"acme","title":"x"}`,
+ `{"team":"acme","Team":"other","title":"x"}`,
+ `{"team":"acme","tEAM":"other","title":"x"}`,
+ `{"team":"acme","teaM":"other","title":"x"}`,
+ `{"team":"acme","TEAM":"acme","title":"x"}`,
+ `{"TEAM":"acme","title":"x"}`,
+ `{"team":"acme","team":"other","title":"x"}`,
+}
+
+func TestAmbiguousTeamIsRefusedBeforeAnyApp(t *testing.T) {
+ for _, raw := range ambiguousTeamInputs {
+ t.Run(raw, func(t *testing.T) {
+ f := newTeamArgFixture(t, "acme", "other")
+ _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw))
+ if err == nil || SafeFailure(err).Code != "invalid" {
+ t.Fatalf("want invalid, got %v", err)
+ }
+ if f.credentials.calls != 0 || len(f.reached()) != 0 {
+ t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached())
+ }
+ })
+ }
+}
+
+func TestAmbiguousTeamIsRefusedOverHTTPAndMCP(t *testing.T) {
+ const raw = `{"team":"acme","TEAM":"other","title":"x"}`
+ 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))
+ defer api.Close()
+ req, _ := http.NewRequest("POST", api.URL+"/api/v1/operations/notes_create", strings.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test")
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := api.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 422 {
+ t.Fatalf("HTTP status %d", resp.StatusCode)
+ }
+
+ server := httptest.NewServer(f.gateway.MCP(verify))
+ defer server.Close()
+ client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil)
+ session, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: server.URL, HTTPClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ out := r.Clone(r.Context())
+ out.Header.Set("Authorization", "Bearer test")
+ return http.DefaultTransport.RoundTrip(out)
+ })}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer session.Close()
+ result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(raw)})
+ if err == nil && !result.IsError {
+ t.Fatal("MCP accepted an ambiguous team")
+ }
+ if f.credentials.calls != 0 || len(f.reached()) != 0 {
+ t.Fatalf("reached minting (%d) or an app (%v)", f.credentials.calls, f.reached())
+ }
+}
+
+// Only one team has routes, as in production today.
+func TestSingleRoutedTeamCannotBeCrossed(t *testing.T) {
+ for _, tc := range []struct {
+ raw string
+ teams []string
+ }{
+ {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk"}},
+ {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk"}},
+ {`{"team":"Xy","TEAM":"Uk","title":"x"}`, []string{"Uk", "Xy"}},
+ {`{"team":"Uk","TEAM":"Xy","title":"x"}`, []string{"Uk", "Xy"}},
+ } {
+ t.Run(tc.raw, func(t *testing.T) {
+ f := newTeamArgFixture(t, "Uk")
+ if _, err := f.gateway.Call(t.Context(), teamArgPrincipal(tc.teams...), "notes_create", json.RawMessage(tc.raw)); err == nil {
+ t.Fatal("accepted")
+ }
+ if len(f.reached()) != 0 {
+ t.Fatalf("reached %v", f.reached())
+ }
+ })
+ }
+}
+
+// What must keep working: the named team, unrelated fields, and a nested key
+// that happens to be spelled TEAM.
+func TestUnambiguousCallsRouteToTheNamedTeam(t *testing.T) {
+ for _, raw := range []string{
+ `{"team":"other","title":"x"}`,
+ `{"team":"other","title":"x","teammate":"y"}`,
+ `{"team":"other","title":"x","meta":{"TEAM":"acme"}}`,
+ } {
+ t.Run(raw, func(t *testing.T) {
+ f := newTeamArgFixture(t, "acme", "other")
+ if _, err := f.gateway.Call(t.Context(), teamArgPrincipal("acme", "other"), "notes_create", json.RawMessage(raw)); err != nil {
+ t.Fatal(err)
+ }
+ if got := f.reached(); len(got) != 1 || got[0] != "other" || f.credentials.team != "other" {
+ t.Fatalf("routed to %v, minted for %q", got, f.credentials.team)
+ }
+ if f.bodies[0] != raw {
+ t.Fatalf("body changed: %s", f.bodies[0])
+ }
+ })
+ }
+}
+
+func TestOperationTeamIsTheExactKey(t *testing.T) {
+ for _, tc := range []struct {
+ raw, team string
+ bad bool
+ }{
+ {raw: `{"team":"acme"}`, team: "acme"},
+ {raw: `{"title":"x"}`},
+ {raw: `{"team":7}`},
+ {raw: `{"team":"acme","meta":{"TEAM":"other"}}`, team: "acme"},
+ {raw: `{"team":"acme","TEAM":"other"}`, bad: true},
+ {raw: `{"Team":"acme"}`, bad: true},
+ {raw: `{"team":"acme","team":"other"}`, bad: true},
+ {raw: `[]`, bad: true},
+ {raw: `null`, bad: true},
+ } {
+ team, err := operationTeam(json.RawMessage(tc.raw))
+ if (err != nil) != tc.bad || team != tc.team {
+ t.Errorf("%s: team %q, err %v", tc.raw, team, err)
+ }
+ }
+}
+
+// The scheduler's response check reads the team the same way.
+func TestScheduleGuardRefusesAnAmbiguousTeam(t *testing.T) {
+ r, err := NewRegistry()
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = r.ScheduleResponseGuard(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)
+ }
+}
+
+// Invoke holds the same line on its own, whatever reaches it.
+func TestInvokeRefusesAnAmbiguousTeam(t *testing.T) {
+ f := newTeamArgFixture(t, "acme", "other")
+ invoke := f.gateway.operations["notes_create"].op.Invoke
+ _, err := invoke(t.Context(), teamArgPrincipal("acme", "other"), json.RawMessage(`{"team":"acme","TEAM":"other","title":"x"}`))
+ if err == nil || SafeFailure(err).Code != "invalid" || f.credentials.calls != 0 || len(f.reached()) != 0 {
+ t.Fatalf("got %v, minted %d, reached %v", err, f.credentials.calls, f.reached())
+ }
+}