oficina / agent-access Public
Add shared Oficina operations with HTTP and MCP adapters
Keep validation and team/scope authorization at the operation boundary so transport replacement cannot change access. Use stateless MCP requests to recheck revoked connections.
10 files changed,
+577
−0
.amadan/ci.d/10-ci+3 −0Makefile+8 −0README.md+25 −0go.mod+18 −0go.sum+24 −0http.go+92 −0json.go+71 −0mcp.go+37 −0operation.go+161 −0operation_test.go+138 −0
diff --git a/.amadan/ci.d/10-ci b/.amadan/ci.d/10-ci| new file mode 100755 |
| index 0000000..4dfd829 |
| --- /dev/null |
| +++ b/.amadan/ci.d/10-ci |
| @@ -0,0 +1,3 @@ |
| +#!/bin/sh |
| +set -eu |
| +make ci |
diff --git a/Makefile b/Makefile| new file mode 100644 |
| index 0000000..f12bf8f |
| --- /dev/null |
| +++ b/Makefile |
| @@ -0,0 +1,8 @@ |
| +.PHONY: ci test vet fmt-check |
| +ci: fmt-check vet test |
| +fmt-check: |
| + @test -z "$$(gofmt -l $$(find . -name '*.go' -not -path './vendor/*'))" |
| +vet: |
| + go vet ./... |
| +test: |
| + go test -race ./... |
diff --git a/README.md b/README.md| new file mode 100644 |
| index 0000000..4b609f5 |
| --- /dev/null |
| +++ b/README.md |
| @@ -0,0 +1,25 @@ |
| +# Oficina agent access |
| + |
| +One operation contract for Oficina HTTP APIs, the `oficina` CLI, and MCP. |
| +The transport and credential interfaces are independent of the app operations |
| +so they can be replaced by Rastrillo implementations later. |
| + |
| +Status: implementation in progress. The shared registry, HTTP and MCP adapters |
| +exist. Browser authorization, app integration and the CLI are not yet complete. |
| +No production endpoint is deployed. |
| + |
| +Each request supplies a verified person, client, grant, selected teams and |
| +scopes. The registry rejects unauthorized team/scope combinations before calling |
| +an app, validates inputs and outputs, and returns bounded JSON. The app remains |
| +responsible for current local admission, resource access, data storage and edit |
| +semantics. MCP uses the official Go SDK, with stateless requests to avoid retaining |
| +one person's authorization in another request. |
| + |
| +Run `make ci` for formatting, vet, and tests. Integration tests drive the same |
| +operation through HTTP and MCP and verify that grant revocation prevents writes |
| +through an already connected MCP client. |
| + |
| +[Rastrillo coordination](https://amadan.net/rastrillo/rastrillo/-/discussion/116). |
| +The JSON API framework landed at Rastrillo `2e833dd`; its MCP and OAuth packages |
| +are separate ongoing work. This module will not wait on them, per Paul's |
| +2026-10-24 direction. |
diff --git a/go.mod b/go.mod| new file mode 100644 |
| index 0000000..4f4f286 |
| --- /dev/null |
| +++ b/go.mod |
| @@ -0,0 +1,18 @@ |
| +module amadan.net/oficina/agent-access |
| + |
| +go 1.25.0 |
| + |
| +require ( |
| + github.com/google/jsonschema-go v0.4.3 |
| + github.com/modelcontextprotocol/go-sdk v1.7.0 |
| +) |
| + |
| +require ( |
| + github.com/segmentio/asm v1.1.3 // indirect |
| + github.com/segmentio/encoding v0.5.4 // indirect |
| + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect |
| + golang.org/x/oauth2 v0.35.0 // indirect |
| + golang.org/x/sync v0.20.0 // indirect |
| + golang.org/x/sys v0.41.0 // indirect |
| + golang.org/x/time v0.15.0 // indirect |
| +) |
diff --git a/go.sum b/go.sum| new file mode 100644 |
| index 0000000..f93aba1 |
| --- /dev/null |
| +++ b/go.sum |
| @@ -0,0 +1,24 @@ |
| +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= |
| +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= |
| +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= |
| +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= |
| +github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0= |
| +github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= |
| +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= |
| +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= |
| +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= |
| +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= |
| +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= |
| +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= |
| +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= |
| +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= |
| +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= |
| +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= |
| +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= |
| +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= |
| +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= |
| +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= |
| +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= |
diff --git a/http.go b/http.go| new file mode 100644 |
| index 0000000..4088296 |
| --- /dev/null |
| +++ b/http.go |
| @@ -0,0 +1,92 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +type Verifier interface { |
| + Verify(context.Context, string) (Principal, error) |
| +} |
| +type VerifyFunc func(context.Context, string) (Principal, error) |
| + |
| +func (v VerifyFunc) Verify(ctx context.Context, token string) (Principal, error) { |
| + return v(ctx, token) |
| +} |
| + |
| +type principalKey struct{} |
| + |
| +func principalFrom(ctx context.Context) Principal { |
| + p, _ := ctx.Value(principalKey{}).(Principal) |
| + return p |
| +} |
| + |
| +func Authenticate(v Verifier, next http.Handler) http.Handler { |
| + if v == nil { |
| + panic("agentaccess: verifier is required") |
| + } |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + parts := strings.Fields(r.Header.Get("Authorization")) |
| + if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| + w.Header().Set("WWW-Authenticate", "Bearer") |
| + writeFailure(w, Fail("unauthenticated", "Connect to Oficina first.")) |
| + return |
| + } |
| + p, err := v.Verify(r.Context(), parts[1]) |
| + if err != nil { |
| + writeFailure(w, err) |
| + return |
| + } |
| + if p.Subject == "" { |
| + writeFailure(w, Fail("unauthenticated", "Connect to Oficina first.")) |
| + return |
| + } |
| + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), principalKey{}, p))) |
| + }) |
| +} |
| +func (registry *Registry) HTTP(v Verifier) http.Handler { |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /api/v1/operations", func(w http.ResponseWriter, r *http.Request) { |
| + writeJSON(w, 200, map[string]any{"operations": registry.List(principalFrom(r.Context()))}) |
| + }) |
| + mux.HandleFunc("POST /api/v1/operations/{name}", func(w http.ResponseWriter, r *http.Request) { |
| + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || media != "application/json" { |
| + writeFailure(w, Fail("unsupported_media_type", "Send application/json.")) |
| + return |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(r.Body, MaxPayload+1)) |
| + if err != nil { |
| + writeFailure(w, Fail("invalid", "Could not read the request.")) |
| + return |
| + } |
| + result, err := registry.Call(r.Context(), principalFrom(r.Context()), r.PathValue("name"), raw) |
| + if err != nil { |
| + writeFailure(w, err) |
| + return |
| + } |
| + writeJSON(w, 200, result) |
| + }) |
| + return Authenticate(v, mux) |
| +} |
| +func writeJSON(w http.ResponseWriter, status int, value any) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(value) |
| +} |
| +func writeFailure(w http.ResponseWriter, err error) { |
| + f := SafeFailure(err) |
| + status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "conflict": 409, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503, "rate_limited": 429}[f.Code] |
| + if status == 0 { |
| + status = 500 |
| + } |
| + if status == 401 { |
| + w.Header().Set("WWW-Authenticate", "Bearer") |
| + } |
| + writeJSON(w, status, map[string]any{"error": f}) |
| +} |
diff --git a/json.go b/json.go| new file mode 100644 |
| index 0000000..400f8c4 |
| --- /dev/null |
| +++ b/json.go |
| @@ -0,0 +1,71 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| +) |
| + |
| +// Reject duplicate keys before different adapters or validators can disagree |
| +// about which value determines a team, destination or write argument. |
| +func UniqueJSON(raw []byte) error { |
| + d := json.NewDecoder(bytes.NewReader(raw)) |
| + d.UseNumber() |
| + var walk func(int) error |
| + walk = func(depth int) error { |
| + if depth > 64 { |
| + return errors.New("JSON nesting limit") |
| + } |
| + tok, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + delim, ok := tok.(json.Delim) |
| + if !ok { |
| + return nil |
| + } |
| + switch delim { |
| + case '{': |
| + seen := map[string]bool{} |
| + for d.More() { |
| + k, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + key, ok := k.(string) |
| + if !ok || seen[key] { |
| + return errors.New("duplicate key") |
| + } |
| + seen[key] = true |
| + if err := walk(depth + 1); err != nil { |
| + return err |
| + } |
| + } |
| + tok, err = d.Token() |
| + if err != nil || tok != json.Delim('}') { |
| + return errors.New("invalid object") |
| + } |
| + case '[': |
| + for d.More() { |
| + if err := walk(depth + 1); err != nil { |
| + return err |
| + } |
| + } |
| + tok, err = d.Token() |
| + if err != nil || tok != json.Delim(']') { |
| + return errors.New("invalid array") |
| + } |
| + default: |
| + return errors.New("unexpected delimiter") |
| + } |
| + return nil |
| + } |
| + if err := walk(0); err != nil { |
| + return err |
| + } |
| + if _, err := d.Token(); err != io.EOF { |
| + return errors.New("trailing JSON") |
| + } |
| + return nil |
| +} |
diff --git a/mcp.go b/mcp.go| new file mode 100644 |
| index 0000000..5b02b18 |
| --- /dev/null |
| +++ b/mcp.go |
| @@ -0,0 +1,37 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + |
| + "github.com/modelcontextprotocol/go-sdk/mcp" |
| +) |
| + |
| +// MCPServer keeps the operation registry independent of the SDK. Replacing this |
| +// adapter with Rastrillo must not change domain handlers or authorization. |
| +func (r *Registry) MCPServer(p Principal) *mcp.Server { |
| + server := mcp.NewServer(&mcp.Implementation{Name: "oficina", Version: "0.1.0"}, nil) |
| + for _, op := range r.List(p) { |
| + destructive := op.Destructive |
| + server.AddTool(&mcp.Tool{Name: op.Name, Description: op.Description, InputSchema: op.Input, OutputSchema: op.Output, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: op.ReadOnly, DestructiveHint: &destructive, IdempotentHint: op.Idempotent}}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { |
| + result, err := r.Call(ctx, p, op.Name, req.Params.Arguments) |
| + if err != nil { |
| + f := SafeFailure(err) |
| + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: f.Error()}}}, nil |
| + } |
| + raw, err := json.Marshal(result) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &mcp.CallToolResult{StructuredContent: result, Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil |
| + }) |
| + } |
| + return server |
| +} |
| +func (r *Registry) MCP(v Verifier) http.Handler { |
| + // A fresh stateless server receives the verified principal on every request. |
| + // A session established by one identity cannot retain another one's tools. |
| + handler := mcp.NewStreamableHTTPHandler(func(req *http.Request) *mcp.Server { return r.MCPServer(principalFrom(req.Context())) }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) |
| + return Authenticate(v, handler) |
| +} |
diff --git a/operation.go b/operation.go| new file mode 100644 |
| index 0000000..f37c818 |
| --- /dev/null |
| +++ b/operation.go |
| @@ -0,0 +1,161 @@ |
| +// Package agentaccess defines Oficina operations independently of any transport. |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "regexp" |
| + "sort" |
| + |
| + "github.com/google/jsonschema-go/jsonschema" |
| +) |
| + |
| +const MaxPayload = 2 << 20 |
| + |
| +// Principal is supplied by a verifier, never decoded from operation arguments. |
| +type Principal struct { |
| + Subject string |
| + Client string |
| + Grant string |
| + Teams []string |
| + Scopes []string |
| +} |
| + |
| +func (p Principal) Allows(team, scope string) bool { |
| + return p.Subject != "" && contains(p.Teams, team) && contains(p.Scopes, scope) |
| +} |
| +func contains(xs []string, x string) bool { |
| + for _, s := range xs { |
| + if s == x { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +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"` |
| + Input json.RawMessage `json:"input_schema"` |
| + Output json.RawMessage `json:"output_schema"` |
| + Invoke func(context.Context, Principal, json.RawMessage) (any, error) `json:"-"` |
| +} |
| + |
| +type Failure struct { |
| + Code string `json:"code"` |
| + Message string `json:"message"` |
| +} |
| + |
| +func (f Failure) Error() string { return f.Code + ": " + f.Message } |
| +func Fail(code, message string) error { return Failure{code, message} } |
| +func SafeFailure(err error) Failure { |
| + var f Failure |
| + if errors.As(err, &f) { |
| + return f |
| + } |
| + return Failure{"internal", "The operation could not be completed."} |
| +} |
| + |
| +type compiled struct { |
| + op Operation |
| + input, output *jsonschema.Resolved |
| +} |
| +type Registry struct{ operations map[string]compiled } |
| + |
| +var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) |
| + |
| +func NewRegistry(operations ...Operation) (*Registry, error) { |
| + r := &Registry{operations: map[string]compiled{}} |
| + for _, op := range operations { |
| + if !namePattern.MatchString(op.Name) || op.Scope == "" || op.Description == "" || op.Invoke == nil { |
| + return nil, fmt.Errorf("invalid operation registration: %s", op.Name) |
| + } |
| + if _, ok := r.operations[op.Name]; ok { |
| + return nil, fmt.Errorf("duplicate operation: %s", op.Name) |
| + } |
| + parse := func(raw json.RawMessage) (*jsonschema.Resolved, error) { |
| + var s jsonschema.Schema |
| + if err := json.Unmarshal(raw, &s); err != nil { |
| + return nil, err |
| + } |
| + if s.Type != "object" { |
| + return nil, errors.New("operation schema must describe an object") |
| + } |
| + return s.Resolve(nil) |
| + } |
| + in, err := parse(op.Input) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s input: %w", op.Name, err) |
| + } |
| + out, err := parse(op.Output) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s output: %w", op.Name, err) |
| + } |
| + op.Input = append(json.RawMessage(nil), op.Input...) |
| + op.Output = append(json.RawMessage(nil), op.Output...) |
| + r.operations[op.Name] = compiled{op, in, out} |
| + } |
| + return r, nil |
| +} |
| +func (r *Registry) List(p Principal) []Operation { |
| + out := []Operation{} |
| + if p.Subject == "" || len(p.Teams) == 0 { |
| + return out |
| + } |
| + for _, entry := range r.operations { |
| + if contains(p.Scopes, entry.op.Scope) { |
| + o := entry.op |
| + o.Invoke = nil |
| + o.Input = append(json.RawMessage(nil), o.Input...) |
| + o.Output = append(json.RawMessage(nil), o.Output...) |
| + out = append(out, o) |
| + } |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) |
| + return out |
| +} |
| +func (r *Registry) Call(ctx context.Context, p Principal, name string, raw json.RawMessage) (any, error) { |
| + if p.Subject == "" { |
| + return nil, Fail("unauthenticated", "Connect to Oficina first.") |
| + } |
| + entry, ok := r.operations[name] |
| + if !ok { |
| + return nil, Fail("not_found", "This operation is unavailable.") |
| + } |
| + if len(raw) > MaxPayload { |
| + return nil, Fail("too_large", "The operation input is too large.") |
| + } |
| + if err := UniqueJSON(raw); err != nil { |
| + return nil, Fail("invalid", "Send one JSON object with unique field names.") |
| + } |
| + var input map[string]any |
| + if json.Unmarshal(raw, &input) != nil || input == nil { |
| + return nil, Fail("invalid", "Send a JSON object.") |
| + } |
| + team, _ := input["team"].(string) |
| + if !p.Allows(team, entry.op.Scope) { |
| + return nil, Fail("forbidden", "This connection does not allow that team and operation.") |
| + } |
| + if entry.input.Validate(input) != nil { |
| + return nil, Fail("invalid", "The input does not match the operation schema.") |
| + } |
| + result, err := entry.op.Invoke(ctx, p, raw) |
| + if err != nil { |
| + return nil, SafeFailure(err) |
| + } |
| + encoded, err := json.Marshal(result) |
| + if err != nil || len(encoded) > MaxPayload { |
| + return nil, Fail("internal", "The operation returned an invalid or oversized result.") |
| + } |
| + var value any |
| + if json.Unmarshal(encoded, &value) != nil || entry.output.Validate(value) != nil { |
| + return nil, Fail("internal", "The operation result does not match its schema.") |
| + } |
| + return value, nil |
| +} |
diff --git a/operation_test.go b/operation_test.go| new file mode 100644 |
| index 0000000..6688d73 |
| --- /dev/null |
| +++ b/operation_test.go |
| @@ -0,0 +1,138 @@ |
| +package agentaccess |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/modelcontextprotocol/go-sdk/mcp" |
| +) |
| + |
| +func testRegistry(t *testing.T, count *atomic.Int32) *Registry { |
| + t.Helper() |
| + r, err := NewRegistry(Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"},"title":{"type":"string","minLength":1}},"required":["team","title"],"additionalProperties":false}`), Output: json.RawMessage(`{"type":"object","properties":{"id":{"type":"integer"}},"required":["id"],"additionalProperties":false}`), Invoke: func(context.Context, Principal, json.RawMessage) (any, error) { |
| + count.Add(1) |
| + return map[string]int{"id": 42}, nil |
| + }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| +} |
| +func principal() Principal { |
| + return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: []string{"acme"}, Scopes: []string{"notes:write"}} |
| +} |
| +func TestAuthorizationAndValidationPrecedeMutation(t *testing.T) { |
| + var count atomic.Int32 |
| + r := testRegistry(t, &count) |
| + cases := []struct { |
| + name string |
| + p Principal |
| + raw string |
| + code string |
| + }{ |
| + {"anonymous", Principal{}, `{"team":"acme","title":"x"}`, "unauthenticated"}, |
| + {"other team", principal(), `{"team":"elsewhere","title":"x"}`, "forbidden"}, |
| + {"read only", Principal{Subject: "person", Teams: []string{"acme"}, Scopes: []string{"notes:read"}}, `{"team":"acme","title":"x"}`, "forbidden"}, |
| + {"unknown input", principal(), `{"team":"acme","title":"x","subject":"someone"}`, "invalid"}, |
| + {"duplicate team", principal(), `{"team":"elsewhere","team":"acme","title":"x"}`, "invalid"}, |
| + {"empty title", principal(), `{"team":"acme","title":""}`, "invalid"}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + _, err := r.Call(context.Background(), tc.p, "notes_create", []byte(tc.raw)) |
| + if err == nil || SafeFailure(err).Code != tc.code { |
| + t.Fatalf("got %v", err) |
| + } |
| + if count.Load() != 0 { |
| + t.Fatal("unauthorized mutation") |
| + } |
| + }) |
| + } |
| + _, err := r.Call(context.Background(), principal(), "notes_create", []byte(`{"team":"acme","title":"x"}`)) |
| + if err != nil || count.Load() != 1 { |
| + t.Fatalf("valid call: %v, %d", err, count.Load()) |
| + } |
| +} |
| +func TestHTTPAndMCPUseSameOperationAndRecheckRevocation(t *testing.T) { |
| + var count atomic.Int32 |
| + var revoked atomic.Bool |
| + r := testRegistry(t, &count) |
| + verify := VerifyFunc(func(_ context.Context, token string) (Principal, error) { |
| + if token != "test" || revoked.Load() { |
| + return Principal{}, Fail("unauthenticated", "Connection revoked.") |
| + } |
| + return principal(), nil |
| + }) |
| + mux := http.NewServeMux() |
| + mux.Handle("/api/", r.HTTP(verify)) |
| + mux.Handle("/mcp", r.MCP(verify)) |
| + server := httptest.NewServer(mux) |
| + defer server.Close() |
| + doHTTP := func() int { |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_create", strings.NewReader(`{"team":"acme","title":"x"}`)) |
| + req.Header.Set("Authorization", "Bearer test") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := server.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + io.Copy(io.Discard, resp.Body) |
| + return resp.StatusCode |
| + } |
| + if code := doHTTP(); code != 200 { |
| + t.Fatalf("HTTP %d", code) |
| + } |
| + client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil) |
| + session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{Endpoint: server.URL + "/mcp", HTTPClient: &http.Client{Transport: headerTransport{base: http.DefaultTransport}}}, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer session.Close() |
| + tools, err := session.ListTools(context.Background(), nil) |
| + if err != nil || len(tools.Tools) != 1 { |
| + t.Fatalf("tools %v %v", tools, err) |
| + } |
| + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "notes_create", Arguments: map[string]any{"team": "acme", "title": "x"}}) |
| + if err != nil || result.IsError { |
| + t.Fatalf("MCP call: %v %v", result, err) |
| + } |
| + if count.Load() != 2 { |
| + t.Fatalf("calls %d", count.Load()) |
| + } |
| + revoked.Store(true) |
| + if code := doHTTP(); code != 401 { |
| + t.Fatalf("revoked HTTP %d", code) |
| + } |
| + _, err = session.CallTool(context.Background(), &mcp.CallToolParams{Name: "notes_create", Arguments: map[string]any{"team": "acme", "title": "x"}}) |
| + if err == nil { |
| + t.Fatal("revoked MCP accepted") |
| + } |
| + if count.Load() != 2 { |
| + t.Fatal("revoked call mutated") |
| + } |
| +} |
| + |
| +type headerTransport struct{ base http.RoundTripper } |
| + |
| +func (h headerTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| + r := req.Clone(req.Context()) |
| + r.Header.Set("Authorization", "Bearer test") |
| + return h.base.RoundTrip(r) |
| +} |
| +func TestUniqueJSON(t *testing.T) { |
| + for _, raw := range []string{`{"x":{"a":1,"a":2}}`, `{"x":1} {}`, `[1,`, strings.Repeat("[", 66) + "0" + strings.Repeat("]", 66)} { |
| + if UniqueJSON([]byte(raw)) == nil { |
| + t.Fatalf("accepted %s", raw) |
| + } |
| + } |
| + if err := UniqueJSON([]byte(`{"x":[1,{"a":2}]}`)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |