oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1package memoria
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 Memoria's own operation handlers, linked identity, sealer and index.
41// The signed Home/browser/PKCE flow is exercised in the connection module.
42func TestAgentGatewayToRealMemoria(t *testing.T) {
43 f, p := linkedAgentFixture(t)
44 ctx := t.Context()
45 var appHandler, httpHandler http.Handler
46 appServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) }))
47 defer appServer.Close()
48 issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpHandler.ServeHTTP(w, r) }))
49 defer issuer.Close()
50 database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "grants.db"))
51 if err != nil {
52 t.Fatal(err)
53 }
54 defer database.Close()
55 database.SetMaxOpenConns(1)
56 store, err := grant.NewStore(ctx, database)
57 if err != nil {
58 t.Fatal(err)
59 }
60 teams := func(context.Context, string) ([]grant.Team, error) {
61 return []grant.Team{{ID: "acme", Name: "Acme"}}, nil
62 }
63 grants, err := grant.NewServer(grant.Config{IdentityIssuer: homeTestIssuer, 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{"notes:read": "Read notes", "notes:write": "Create notes"}, Subject: func(*http.Request) string { return "" }, Teams: teams, ResourceTeams: func(ctx context.Context, subject, resource string) ([]grant.Team, error) {
64 if resource != appServer.URL+"/api/v1" {
65 return nil, nil
66 }
67 return teams(ctx, subject)
68 }, SignInPath: "/signin"})
69 if err != nil {
70 t.Fatal(err)
71 }
72 remote, err := access.NewRemoteVerifier(issuer.URL, appServer.URL+"/api/v1", homeTestIssuer)
73 if err != nil {
74 t.Fatal(err)
75 }
76 remote.Client.Transport = issuer.Client().Transport
77 mux := http.NewServeMux()
78 if err = f.app.mountAgentAccess(mux, issuer.URL, "acme", remote); err != nil {
79 t.Fatal(err)
80 }
81 appHandler = mux
82 contracts, err := AgentContracts()
83 if err != nil {
84 t.Fatal(err)
85 }
86 gateway, err := access.Gateway([]access.Route{{Team: "acme", Resource: appServer.URL + "/api/v1", Operations: contracts}}, store, appServer.Client().Transport)
87 if err != nil {
88 t.Fatal(err)
89 }
90 serviceMux := http.NewServeMux()
91 serviceMux.Handle("/mcp", gateway.MCP(grants))
92 serviceMux.Handle("/api/v1/operations", gateway.HTTP(grants))
93 serviceMux.Handle("/api/v1/operations/", gateway.HTTP(grants))
94 serviceMux.Handle("/", grants.Handler())
95 httpHandler = serviceMux
96 verifier := oauth2.GenerateVerifier()
97 challenge := sha256.Sum256([]byte(verifier))
98 redirect := "http://127.0.0.1:43210/callback"
99 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"})
100 if err != nil {
101 t.Fatal(err)
102 }
103 token, err := store.Exchange(ctx, code, client.ClientID, redirect, issuer.URL+"/mcp", verifier)
104 if err != nil {
105 t.Fatal(err)
106 }
107 credentials := &agentCredentials{client.Credentials{Server: issuer.URL, Resource: issuer.URL + "/mcp", TokenEndpoint: issuer.URL + "/oauth/token", Token: &oauth2.Token{AccessToken: token.AccessToken, TokenType: "Bearer"}}}
108 cli := client.New(credentials)
109 cli.HTTP = issuer.Client()
110 result, err := cli.Call(ctx, "notes_create", json.RawMessage(agentNoteInput))
111 if err != nil {
112 t.Fatal(err)
113 }
114 encoded, _ := json.Marshal(result)
115 var note agentNoteResult
116 if json.Unmarshal(encoded, &note) != nil || note.ID <= 0 {
117 t.Fatal("invalid note receipt")
118 }
119 mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Memoria integration", Version: "1"}, nil)
120 session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: issuer.URL + "/mcp", HTTPClient: &http.Client{Transport: agentBearer{issuer.Client().Transport, token.AccessToken}}}, nil)
121 if err != nil {
122 t.Fatal(err)
123 }
124 defer session.Close()
125 retry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(agentNoteInput)})
126 if err != nil || retry.IsError {
127 t.Fatal("MCP retry", retry, err)
128 }
129 search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_search", Arguments: map[string]any{"team": "acme", "query": "nebula"}})
130 if err != nil || search.IsError {
131 t.Fatal("MCP search", search, err)
132 }
133 text, _ := json.Marshal(search.Content)
134 if !strings.Contains(string(text), agentTitleCanary) {
135 t.Fatal("MCP could not see created note")
136 }
137 var count int
138 if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
139 t.Fatal("transport retry duplicated note", count, err)
140 }
141 assertAgentContentSealed(t, f)
142 if err = cli.Logout(ctx); err != nil {
143 t.Fatal(err)
144 }
145 if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: json.RawMessage(strings.Replace(agentNoteInput, "a8d99147", "b8d99147", 1))}); err == nil {
146 t.Fatal("MCP survived CLI revocation")
147 }
148 if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
149 t.Fatal("revoked call wrote note", count, err)
150 }
151}
152