oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 "crypto/sha256"
6 "database/sql"
7 "encoding/base64"
8 "encoding/json"
9 "net/http"
10 "net/http/httptest"
11 "path/filepath"
12 "strings"
13 "testing"
14
15 access "amadan.net/oficina/agent-access.git"
16 "amadan.net/oficina/agent-access.git/client"
17 "amadan.net/oficina/agent-access.git/grant"
18 "github.com/modelcontextprotocol/go-sdk/mcp"
19 "golang.org/x/oauth2"
20)
21
22type agentCredentials struct{ value client.Credentials }
23
24func (m *agentCredentials) Load() (client.Credentials, error) { return m.value, nil }
25func (m *agentCredentials) Save(v client.Credentials) error { m.value = v; return nil }
26func (m *agentCredentials) Delete() error { m.value = client.Credentials{}; return nil }
27
28type agentBearer struct {
29 base http.RoundTripper
30 token string
31}
32
33func (b agentBearer) RoundTrip(r *http.Request) (*http.Response, error) {
34 copy := r.Clone(r.Context())
35 copy.Header.Set("Authorization", "Bearer "+b.token)
36 return b.base.RoundTrip(copy)
37}
38
39// This fixture crosses real HTTPS boundaries from the shared CLI/MCP gateway
40// into Docs' real handlers, linked identity, sealed collaborative content.
41// The signed Home/browser/PKCE flow is exercised in the connection module.
42func TestAgentGatewayToRealDocs(t *testing.T) {
43 ctx := t.Context()
44 var appHandler, httpHandler http.Handler
45 appServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) }))
46 defer appServer.Close()
47 issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpHandler.ServeHTTP(w, r) }))
48 defer issuer.Close()
49 f := newDocAgentFixture(t, issuer.URL)
50 p := f.p
51 input, _ := json.Marshal(initialAgentInput())
52 database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "grants.db"))
53 if err != nil {
54 t.Fatal(err)
55 }
56 defer database.Close()
57 database.SetMaxOpenConns(1)
58 store, err := grant.NewStore(ctx, database)
59 if err != nil {
60 t.Fatal(err)
61 }
62 teams := func(context.Context, string) ([]grant.Team, error) {
63 return []grant.Team{{ID: "blue", Name: "Blue"}}, nil
64 }
65 grants, err := grant.NewServer(grant.Config{IdentityIssuer: bridgeIssuer, Origin: issuer.URL, Resource: issuer.URL + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []grant.Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, Scopes: map[string]string{"docs:read": "Read documents", "docs:write": "Create documents"}, Subject: func(*http.Request) string { return "" }, Teams: teams, ResourceTeams: func(ctx context.Context, subject, resource string) ([]grant.Team, error) {
66 if resource != appServer.URL+"/api/v1" {
67 return nil, nil
68 }
69 return teams(ctx, subject)
70 }, SignInPath: "/signin"})
71 if err != nil {
72 t.Fatal(err)
73 }
74 remote, err := access.NewRemoteVerifier(issuer.URL, appServer.URL+"/api/v1", bridgeIssuer)
75 if err != nil {
76 t.Fatal(err)
77 }
78 remote.Client.Transport = issuer.Client().Transport
79 f.a.origin = appServer.URL
80 appHandler, err = f.a.httpHandler(remote)
81 if err != nil {
82 t.Fatal(err)
83 }
84 contracts, err := AgentContracts()
85 if err != nil {
86 t.Fatal(err)
87 }
88 gateway, err := access.Gateway([]access.Route{{Team: "blue", Resource: appServer.URL + "/api/v1", Operations: contracts}}, store, appServer.Client().Transport)
89 if err != nil {
90 t.Fatal(err)
91 }
92 serviceMux := http.NewServeMux()
93 serviceMux.Handle("/mcp", gateway.MCP(grants))
94 serviceMux.Handle("/api/v1/operations", gateway.HTTP(grants))
95 serviceMux.Handle("/api/v1/operations/", gateway.HTTP(grants))
96 serviceMux.Handle("/", grants.Handler())
97 httpHandler = serviceMux
98 verifier := oauth2.GenerateVerifier()
99 challenge := sha256.Sum256([]byte(verifier))
100 redirect := "http://127.0.0.1:43210/callback"
101 code, err := store.CreateCode(ctx, grant.Grant{Subject: p.Subject, ClientID: client.ClientID, Teams: p.Teams, Scopes: p.Scopes}, grant.Code{Redirect: redirect, Challenge: base64.RawURLEncoding.EncodeToString(challenge[:]), Resource: issuer.URL + "/mcp"})
102 if err != nil {
103 t.Fatal(err)
104 }
105 token, err := store.Exchange(ctx, code, client.ClientID, redirect, issuer.URL+"/mcp", verifier)
106 if err != nil {
107 t.Fatal(err)
108 }
109 credentials := &agentCredentials{client.Credentials{Server: issuer.URL, Resource: issuer.URL + "/mcp", TokenEndpoint: issuer.URL + "/oauth/token", Token: &oauth2.Token{AccessToken: token.AccessToken, TokenType: "Bearer"}}}
110 cli := client.New(credentials)
111 cli.HTTP = issuer.Client()
112 result, err := cli.Call(ctx, "docs_create", json.RawMessage(input))
113 if err != nil {
114 t.Fatal(err)
115 }
116 encoded, _ := json.Marshal(result)
117 var document agentCreated
118 if json.Unmarshal(encoded, &document) != nil || document.ID == "" {
119 t.Fatal("invalid document receipt")
120 }
121 mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Docs integration", Version: "1"}, nil)
122 session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: issuer.URL + "/mcp", HTTPClient: &http.Client{Transport: agentBearer{issuer.Client().Transport, token.AccessToken}}}, nil)
123 if err != nil {
124 t.Fatal(err)
125 }
126 defer session.Close()
127 retry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: json.RawMessage(input)})
128 if err != nil || retry.IsError {
129 t.Fatal("MCP retry", retry, err)
130 }
131 search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_get", Arguments: map[string]any{"team": "blue", "id": document.ID}})
132 if err != nil || search.IsError {
133 t.Fatal("MCP search", search, err)
134 }
135 text, _ := json.Marshal(search.Content)
136 if !strings.Contains(string(text), "PRIVATE_INITIAL_BODY_7f39") {
137 t.Fatal("MCP could not read created document")
138 }
139 edit := editAgentInput(agentBody{agentDocument: document.agentDocument, Revision: document.Revision})
140 editJSON, _ := json.Marshal(edit)
141 edited, err := cli.Call(ctx, "docs_update", editJSON)
142 if err != nil {
143 t.Fatal("CLI edit", err)
144 }
145 editedJSON, _ := json.Marshal(edited)
146 var ack agentUpdated
147 if json.Unmarshal(editedJSON, &ack) != nil || ack.Revision != "2" {
148 t.Fatal("edit receipt", string(editedJSON))
149 }
150 editRetry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_update", Arguments: edit})
151 if err != nil || editRetry.IsError {
152 t.Fatal("MCP edit retry", editRetry, err)
153 }
154 getJSON, _ := json.Marshal(map[string]any{"team": "blue", "id": document.ID})
155 readAfter, err := cli.Call(ctx, "docs_get", getJSON)
156 if err != nil {
157 t.Fatal(err)
158 }
159 afterJSON, _ := json.Marshal(readAfter)
160 if !strings.Contains(string(afterJSON), "EDITED_PRIVATE_BODY") {
161 t.Fatal("edit not readable", string(afterJSON))
162 }
163
164 var count int
165 if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
166 t.Fatal("transport retry duplicated document", count, err)
167 }
168 if err = cli.Logout(ctx); err != nil {
169 t.Fatal(err)
170 }
171 if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: initialAgentInput()}); err == nil {
172 t.Fatal("MCP survived CLI revocation")
173 }
174 if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
175 t.Fatal("revoked call wrote document", count, err)
176 }
177}
178