oficina / agent-access Public

Clone
git clone https://amadan.net/oficina/agent-access

Plain git — no account needed to clone.

Download this file

1package agentaccess_test
2
3import (
4 access "amadan.net/oficina/agent-access.git"
5 "amadan.net/oficina/agent-access.git/client"
6 "context"
7 "crypto/tls"
8 "encoding/json"
9 "errors"
10 "github.com/modelcontextprotocol/go-sdk/mcp"
11 "golang.org/x/oauth2"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "os"
16 "path/filepath"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21)
22
23type interopCredentials struct{ revoked bool }
24
25func (c *interopCredentials) Downstream(context.Context, access.Principal, string, string, []string) (string, error) {
26 if c.revoked {
27 return "", access.Fail("unauthenticated", "Revoked")
28 }
29 return "fixture", nil
30}
31
32type interopStore struct{ c client.Credentials }
33
34func (s *interopStore) Load() (client.Credentials, error) { return s.c, nil }
35func (s *interopStore) Save(c client.Credentials) error { s.c = c; return nil }
36func (s *interopStore) Delete() error { return nil }
37
38type interopTransport struct {
39 base http.RoundTripper
40 dest map[string]string
41 mu sync.Mutex
42 drop string
43}
44
45func (t *interopTransport) RoundTrip(r *http.Request) (*http.Response, error) {
46 copy := r.Clone(r.Context())
47 target, ok := t.dest[r.URL.Scheme+"://"+r.URL.Host]
48 if !ok {
49 return nil, errors.New("unregistered fixture destination")
50 }
51 u, _ := url.Parse(target)
52 copy.URL.Scheme = u.Scheme
53 copy.URL.Host = u.Host
54 copy.Header.Set("Authorization", "Bearer fixture")
55 resp, err := t.base.RoundTrip(copy)
56 t.mu.Lock()
57 defer t.mu.Unlock()
58 if err == nil && t.drop != "" && strings.HasSuffix(r.URL.Path, "/"+t.drop) {
59 t.drop = ""
60 resp.Body.Close()
61 return nil, errors.New("lost committed response")
62 }
63 return resp, err
64}
65func TestSuiteSchedulingInterop(t *testing.T) {
66 dir := os.Getenv("OFICINA_INTEROP_DIR")
67 if dir == "" {
68 t.Skip("run scripts/suite-interop.py with the three app worktrees")
69 }
70 p := access.Principal{Subject: "opaque-home-alice", Client: "oficina-interop", Grant: "interop-grant", Teams: []string{"acme"}, Scopes: []string{"docs:read", "docs:write", "calls:read", "calls:write", "calendar:read", "calendar:write"}}
71 transport := &interopTransport{base: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, dest: map[string]string{}} // Private ephemeral test TLS only.
72 defer transport.base.(*http.Transport).CloseIdleConnections()
73 var routes []access.Route
74 var calendarID int64
75 for _, app := range []string{"docs", "calls", "calendar"} {
76 var fixture struct {
77 URL, Origin string
78 CalendarID int64 `json:"calendar_id"`
79 }
80 b, err := os.ReadFile(filepath.Join(dir, app+".json"))
81 if err != nil || json.Unmarshal(b, &fixture) != nil || fixture.Origin == "" {
82 t.Fatalf("%s fixture metadata: %v %s", app, err, b)
83 }
84 transport.dest[fixture.Origin] = fixture.URL
85 req, _ := http.NewRequestWithContext(t.Context(), "GET", fixture.Origin+"/api/v1/operations", nil)
86 resp, err := (&http.Client{Transport: transport}).Do(req)
87 if err != nil {
88 t.Fatal(err)
89 }
90 var contracts struct{ Operations []access.Operation }
91 err = json.NewDecoder(resp.Body).Decode(&contracts)
92 resp.Body.Close()
93 if err != nil || resp.StatusCode != 200 || len(contracts.Operations) == 0 {
94 t.Fatal(app, resp.StatusCode, err)
95 }
96 routes = append(routes, access.Route{Team: "acme", Resource: fixture.Origin + "/api/v1", Operations: contracts.Operations})
97 if app == "calendar" {
98 calendarID = fixture.CalendarID
99 }
100 }
101 credentials := &interopCredentials{}
102 gateway, err := access.Gateway(routes, credentials, transport)
103 if err != nil {
104 t.Fatal(err)
105 }
106 verify := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil })
107 server := httptest.NewTLSServer(gateway.HTTPGuarded(verify, verify, gateway.ScheduleResponseGuard))
108 defer server.Close()
109 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)}}})
110 cli.HTTP = server.Client()
111 args := map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "title": "Interop review", "calendar_id": calendarID, "start": "2026-11-02T10:00:00Z", "end": "2026-11-02T11:00:00Z", "tz": "Europe/Dublin", "notes": "Review shipped changes", "agenda": map[string]any{"title": "Review agenda", "blocks": []any{map[string]any{"type": "paragraph", "text": "Check the shared workflow"}}}}
112 raw, _ := json.Marshal(args)
113 transport.drop = "calendar_create_event"
114 first, err := cli.Call(t.Context(), "calls_schedule", raw)
115 if err != nil || first.(map[string]any)["status"] != "partial" {
116 t.Fatal("lost-response partial", first, err)
117 }
118 // A fresh gateway, fresh MCP server and unchanged app stores model restarting
119 // the stateless connection process. Every app must replay its durable receipt.
120 restarted, err := access.Gateway(routes, credentials, transport)
121 if err != nil {
122 t.Fatal(err)
123 }
124 mcpServer := httptest.NewTLSServer(restarted.MCP(verify))
125 defer mcpServer.Close()
126 mcpTransport := &interopTransport{base: mcpServer.Client().Transport, dest: map[string]string{mcpServer.URL: mcpServer.URL}}
127 session, err := mcp.NewClient(&mcp.Implementation{Name: "suite-interop", Version: "1"}, nil).Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: mcpServer.URL, HTTPClient: &http.Client{Transport: mcpTransport}}, nil)
128 if err != nil {
129 t.Fatal(err)
130 }
131 defer session.Close()
132 result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "calls_schedule", Arguments: args})
133 if err != nil || result.IsError {
134 t.Fatal("MCP resume", result, err)
135 }
136 var out struct {
137 Status string
138 Steps []struct {
139 Name string
140 Resource access.ResourceReference
141 }
142 InvitationsSent bool `json:"invitations_sent"`
143 }
144 b, _ := json.Marshal(result.StructuredContent)
145 if json.Unmarshal(b, &out) != nil || out.Status != "complete" || len(out.Steps) != 3 || out.InvitationsSent {
146 t.Fatal(string(b))
147 }
148 refs := map[string]access.ResourceReference{}
149 for _, s := range out.Steps {
150 refs[s.Name] = s.Resource
151 }
152 get := func(name string, in map[string]any) map[string]any {
153 t.Helper()
154 raw, _ := json.Marshal(in)
155 value, err := restarted.Call(t.Context(), p, name, raw)
156 if err != nil {
157 t.Fatal(name, err)
158 }
159 return value.(map[string]any)
160 }
161 doc := get("docs_get", map[string]any{"team": "acme", "id": refs["agenda"].ID})
162 text, _ := json.Marshal(doc)
163 if !strings.Contains(string(text), "Check the shared workflow") {
164 t.Fatal("agenda content missing", string(text))
165 }
166 eventID := json.Number(refs["event"].ID)
167 event := get("calendar_get_event", map[string]any{"team": "acme", "id": eventID})
168 text, _ = json.Marshal(event)
169 for _, name := range []string{"agenda", "meeting"} {
170 if !strings.Contains(string(text), refs[name].URL) {
171 t.Fatal("cross-app reference missing", name, string(text))
172 }
173 }
174 again, err := cli.Call(t.Context(), "calls_schedule", raw)
175 if err != nil {
176 t.Fatal(err)
177 }
178 a, _ := json.Marshal(again)
179 if string(a) != string(b) {
180 t.Fatal("transport replay changed result", string(a), string(b))
181 }
182 args["notes"] = "different request"
183 changed, _ := json.Marshal(args)
184 if _, err = cli.Call(t.Context(), "calls_schedule", changed); access.SafeFailure(err).Code != "conflict" {
185 t.Fatal("changed retry accepted", err)
186 }
187 credentials.revoked = true
188 if _, err = restarted.Call(t.Context(), p, "calls_schedule", raw); access.SafeFailure(err).Code != "unauthenticated" {
189 t.Fatal("revoked workflow accepted", err)
190 }
191 t.Log("Real Docs/Calls/Calendar stores: HTTPS CLI partial, lost committed Calendar response, fresh-gateway MCP resume, readable linked resources, exact replay, changed request conflict, revocation all passed")
192}
193