| 1 | package connection |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "html" |
| 9 | "io" |
| 10 | "log/slog" |
| 11 | "net/http" |
| 12 | "net/http/cookiejar" |
| 13 | "net/http/httptest" |
| 14 | "net/url" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "regexp" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "sync/atomic" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | access "amadan.net/oficina/agent-access.git" |
| 25 | "amadan.net/oficina/agent-access.git/client" |
| 26 | "amadan.net/rastrillo/rastrillo/assertion" |
| 27 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 28 | "amadan.net/rastrillo/rastrillo/db" |
| 29 | "github.com/modelcontextprotocol/go-sdk/mcp" |
| 30 | ) |
| 31 | |
| 32 | type memoryCredentials struct{ value client.Credentials } |
| 33 | |
| 34 | func (m *memoryCredentials) Load() (client.Credentials, error) { return m.value, nil } |
| 35 | func (m *memoryCredentials) Save(value client.Credentials) error { m.value = value; return nil } |
| 36 | func (m *memoryCredentials) Delete() error { m.value = client.Credentials{}; return nil } |
| 37 | |
| 38 | type bearerTransport struct { |
| 39 | base http.RoundTripper |
| 40 | token string |
| 41 | } |
| 42 | |
| 43 | func (b bearerTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 44 | copy := r.Clone(r.Context()) |
| 45 | copy.Header.Set("Authorization", "Bearer "+b.token) |
| 46 | return b.base.RoundTrip(copy) |
| 47 | } |
| 48 | |
| 49 | func TestHomeBrowserConsentToHTTPMCPAndLogout(t *testing.T) { |
| 50 | ctx := t.Context() |
| 51 | logs := &lockedLog{} |
| 52 | logger := slog.New(slog.NewTextHandler(logs, nil)) |
| 53 | key, err := family.Generate() |
| 54 | if err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | const subject = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| 58 | const home = "https://id.example.test" |
| 59 | const serviceOrigin = "https://connect.example.test" |
| 60 | const inputCanary = "input_canary_910838cbe00b4f5db045" |
| 61 | const outputCanary = "result_canary_c004907156a142f2a8f9" |
| 62 | var calls atomic.Int32 |
| 63 | var admitted atomic.Bool |
| 64 | admitted.Store(true) |
| 65 | var appLive atomic.Bool |
| 66 | appLive.Store(true) |
| 67 | appRegistry, err := access.NewRegistry(access.Operation{Name: "notes_create", Description: "Create a note", Scope: "notes:write", Idempotent: true, |
| 68 | Input: json.RawMessage(`{"type":"object","required":["team","title"],"properties":{"team":{"type":"string"},"title":{"type":"string"}},"additionalProperties":false}`), |
| 69 | Output: json.RawMessage(`{"type":"object","required":["id"],"properties":{"id":{"type":"integer"},"marker":{"type":"string"}}}`), |
| 70 | Invoke: func(_ context.Context, p access.Principal, _ json.RawMessage) (any, error) { |
| 71 | if p.Subject != subject || p.Client != client.ClientID || len(p.Teams) != 1 || p.Teams[0] != "acme" || len(p.Scopes) != 1 || p.Scopes[0] != "notes:write" { |
| 72 | t.Error("identity or attenuation changed") |
| 73 | } |
| 74 | calls.Add(1) |
| 75 | return map[string]any{"id": int64(9007199254740993), "marker": outputCanary}, nil |
| 76 | }}) |
| 77 | if err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | var appHandler http.Handler |
| 81 | app := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) })) |
| 82 | defer app.Close() |
| 83 | const serviceToken = "service-token-7141d52840e349fe878ae3054a1a1ab5" |
| 84 | directory := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 85 | if r.Method != "POST" || r.URL.Path != "/api/agent/directory" || r.Header.Get("Authorization") != "Bearer "+serviceToken { |
| 86 | t.Error("invalid directory request") |
| 87 | w.WriteHeader(401) |
| 88 | return |
| 89 | } |
| 90 | var in struct { |
| 91 | Subject string `json:"subject"` |
| 92 | } |
| 93 | if json.NewDecoder(r.Body).Decode(&in) != nil || in.Subject != subject { |
| 94 | t.Error("unverified subject sent to directory") |
| 95 | w.WriteHeader(400) |
| 96 | return |
| 97 | } |
| 98 | teams := []DirectoryTeam{} |
| 99 | if admitted.Load() { |
| 100 | apps := []DirectoryApp{{App: "retained", Origin: "https://retained.example.test"}} |
| 101 | if appLive.Load() { |
| 102 | apps = append(apps, DirectoryApp{App: "memoria", Origin: app.URL}) |
| 103 | } |
| 104 | teams = append(teams, DirectoryTeam{ID: "acme", Name: "Acme", Apps: apps}) |
| 105 | } |
| 106 | w.Header().Set("Content-Type", "application/json") |
| 107 | json.NewEncoder(w).Encode(map[string]any{"teams": teams}) |
| 108 | })) |
| 109 | defer directory.Close() |
| 110 | var serviceHandler http.Handler |
| 111 | service := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { serviceHandler.ServeHTTP(w, r) })) |
| 112 | defer service.Close() |
| 113 | transport := originTransport{service.Client().Transport, serviceOrigin, service.URL} |
| 114 | databaseDir := t.TempDir() |
| 115 | d, err := db.Open(filepath.Join(databaseDir, "connect.db"), logger) |
| 116 | if err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | defer d.Close() |
| 120 | contracts := appRegistry.List(access.Principal{Subject: subject, Teams: []string{"acme"}, Scopes: []string{"notes:write"}}) |
| 121 | retained := append([]access.Operation{}, contracts...) |
| 122 | retained[0].Name = "retained_operation" |
| 123 | server, err := New(ctx, Config{Origin: serviceOrigin, HomeIssuer: home, ConsumerID: "agent-access", HomeKeys: map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}, Directory: directory.URL, DirectoryToken: serviceToken, DEK: []byte(strings.Repeat("d", 32)), Transport: transport, Routes: []access.Route{{Team: "acme", Resource: app.URL + "/api/v1", Operations: contracts}, {Team: "acme", Resource: "https://retained.example.test/api/v1", Operations: retained}}}, d, logger) |
| 124 | if err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | serviceHandler = server.Handler |
| 128 | appHandler = appRegistry.HTTP(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) { |
| 129 | return server.Grants.Verify(ctx, token, app.URL+"/api/v1") |
| 130 | })) |
| 131 | memory := &memoryCredentials{} |
| 132 | c := client.New(memory) |
| 133 | c.HTTP = &http.Client{Transport: transport} |
| 134 | c.HTTP.Jar, _ = cookiejar.New(nil) |
| 135 | c.HTTP.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 136 | get := func(raw string) *http.Response { |
| 137 | t.Helper() |
| 138 | if strings.HasPrefix(raw, "/") { |
| 139 | raw = serviceOrigin + raw |
| 140 | } |
| 141 | resp, err := c.HTTP.Get(raw) |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | return resp |
| 146 | } |
| 147 | redirect := func(resp *http.Response) string { |
| 148 | t.Helper() |
| 149 | resp.Body.Close() |
| 150 | if resp.StatusCode != 303 { |
| 151 | t.Fatal("expected redirect", resp.StatusCode) |
| 152 | } |
| 153 | return resp.Header.Get("Location") |
| 154 | } |
| 155 | var savedAuthURL, savedProof string |
| 156 | browser := func(authURL string) error { |
| 157 | savedAuthURL = authURL |
| 158 | start := redirect(get(authURL)) |
| 159 | toHome := redirect(get(start)) |
| 160 | u, err := url.Parse(toHome) |
| 161 | if err != nil || !strings.HasPrefix(toHome, home+"/authorize?") || u.Query().Get("max_age") != "300" { |
| 162 | t.Fatal("invalid Home handoff") |
| 163 | } |
| 164 | id, _ := assertion.RandomID() |
| 165 | now := time.Now().Unix() |
| 166 | proof, err := assertion.Sign(key, assertion.Claims{Version: 1, Issuer: home, Audience: serviceOrigin, Subject: subject, KeyID: "key", ID: id, Nonce: u.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 120, AuthTime: now}) |
| 167 | if err != nil { |
| 168 | return err |
| 169 | } |
| 170 | savedProof = proof |
| 171 | post, _ := http.NewRequest("POST", serviceOrigin+"/auth/assertion", strings.NewReader(url.Values{"assertion": {proof}}.Encode())) |
| 172 | post.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 173 | post.Header.Set("Origin", home) |
| 174 | resp, err := c.HTTP.Do(post) |
| 175 | if err != nil { |
| 176 | return err |
| 177 | } |
| 178 | consentURL := redirect(get(redirect(resp))) |
| 179 | resp = get(consentURL) |
| 180 | body, _ := io.ReadAll(resp.Body) |
| 181 | resp.Body.Close() |
| 182 | if resp.StatusCode != 200 { |
| 183 | t.Fatal("consent", resp.StatusCode, string(body)) |
| 184 | } |
| 185 | ticket := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindSubmatch(body) |
| 186 | if len(ticket) != 2 { |
| 187 | t.Fatal("missing consent ticket") |
| 188 | } |
| 189 | post, _ = http.NewRequest("POST", serviceOrigin+"/oauth/authorize", strings.NewReader(url.Values{"ticket": {string(ticket[1])}, "decision": {"approve"}, "team": {"acme"}}.Encode())) |
| 190 | post.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 191 | post.Header.Set("Origin", serviceOrigin) |
| 192 | resp, err = c.HTTP.Do(post) |
| 193 | if err != nil { |
| 194 | return err |
| 195 | } |
| 196 | // The consent form is answered with a page that moves the browser on. |
| 197 | handoff, _ := io.ReadAll(resp.Body) |
| 198 | resp.Body.Close() |
| 199 | if resp.StatusCode != 200 || resp.Header.Get("Referrer-Policy") != "no-referrer" { |
| 200 | t.Fatal("consent answer", resp.StatusCode, string(handoff)) |
| 201 | } |
| 202 | refresh := regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]+)">`).FindSubmatch(handoff) |
| 203 | if len(refresh) != 2 { |
| 204 | t.Fatal("no hand-off to the client", string(handoff)) |
| 205 | } |
| 206 | callback := html.UnescapeString(string(refresh[1])) |
| 207 | resp = get(callback) |
| 208 | resp.Body.Close() |
| 209 | if resp.StatusCode != 200 { |
| 210 | t.Fatal("loopback callback", resp.StatusCode) |
| 211 | } |
| 212 | return nil |
| 213 | } |
| 214 | if err = c.Login(ctx, serviceOrigin, nil, browser); err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | ops, err := c.Operations(ctx) |
| 218 | if err != nil || len(ops) != 2 { |
| 219 | t.Fatal("tool discovery", len(ops), err) |
| 220 | } |
| 221 | info, err := c.Connection(ctx) |
| 222 | if err != nil || len(info.Teams) != 1 || info.Teams[0] != "acme" { |
| 223 | t.Fatal("connection discovery", info, err) |
| 224 | } |
| 225 | input := json.RawMessage(`{"team":"acme","title":"` + inputCanary + `"}`) |
| 226 | result, err := c.Call(ctx, "notes_create", input) |
| 227 | if err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | raw, _ := json.Marshal(result) |
| 231 | if !strings.Contains(string(raw), "9007199254740993") { |
| 232 | t.Fatal("CLI response rounded ID") |
| 233 | } |
| 234 | parent := memory.value.Token.AccessToken |
| 235 | mcpClient := mcp.NewClient(&mcp.Implementation{Name: "integration", Version: "1"}, nil) |
| 236 | session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: serviceOrigin + "/mcp", HTTPClient: &http.Client{Transport: bearerTransport{transport, parent}}}, nil) |
| 237 | if err != nil { |
| 238 | t.Fatal(err) |
| 239 | } |
| 240 | defer session.Close() |
| 241 | discovery, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "oficina_connection", Arguments: map[string]any{}}) |
| 242 | if err != nil || discovery.IsError { |
| 243 | t.Fatal("MCP discovery", discovery, err) |
| 244 | } |
| 245 | data, _ := json.Marshal(discovery.StructuredContent) |
| 246 | if !strings.Contains(string(data), `"acme"`) { |
| 247 | t.Fatal("MCP lost selected teams") |
| 248 | } |
| 249 | toolResult, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: input}) |
| 250 | if err != nil || toolResult.IsError { |
| 251 | t.Fatal(toolResult, err) |
| 252 | } |
| 253 | if calls.Load() != 2 { |
| 254 | t.Fatal("app calls", calls.Load()) |
| 255 | } |
| 256 | // A remaining app keeps the team admitted, but cannot keep this app's |
| 257 | // already minted credential valid when Home removes its destination. |
| 258 | principal, err := server.Grants.Verify(ctx, parent, serviceOrigin+"/mcp") |
| 259 | if err != nil { |
| 260 | t.Fatal(err) |
| 261 | } |
| 262 | downstream, err := server.Grants.Downstream(ctx, principal, app.URL+"/api/v1", "acme", []string{"notes:write"}) |
| 263 | if err != nil { |
| 264 | t.Fatal(err) |
| 265 | } |
| 266 | remote, err := access.NewRemoteVerifier(serviceOrigin, app.URL+"/api/v1", home) |
| 267 | if err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | remote.Client.Transport = transport |
| 271 | if _, err = remote.Verify(ctx, downstream); err != nil { |
| 272 | t.Fatal("live app credential", err) |
| 273 | } |
| 274 | canaries := []string{inputCanary, outputCanary, serviceToken, parent, memory.value.Token.RefreshToken, downstream, savedProof} |
| 275 | serviceURL, _ := url.Parse(serviceOrigin) |
| 276 | for _, cookie := range c.HTTP.Jar.Cookies(serviceURL) { |
| 277 | canaries = append(canaries, cookie.Value) |
| 278 | } |
| 279 | assertNoRuntimeRetention(t, databaseDir, logs, canaries) |
| 280 | appLive.Store(false) |
| 281 | if _, err = remote.Verify(ctx, downstream); err == nil { |
| 282 | t.Fatal("removed app retained downstream authority") |
| 283 | } |
| 284 | if _, err = c.Call(ctx, "notes_create", input); err == nil { |
| 285 | t.Fatal("removed app was routed") |
| 286 | } |
| 287 | appLive.Store(true) |
| 288 | admitted.Store(false) |
| 289 | if _, err = c.Call(ctx, "notes_create", input); err == nil { |
| 290 | t.Fatal("removed member reached app") |
| 291 | } |
| 292 | admitted.Store(true) |
| 293 | // A session remains valid for an hour, but consent and connection |
| 294 | // management must demand fresh Home authentication after five minutes. |
| 295 | resp := get("/connections") |
| 296 | resp.Body.Close() |
| 297 | if resp.StatusCode != 200 { |
| 298 | t.Fatal("fresh management", resp.StatusCode) |
| 299 | } |
| 300 | if _, err = d.Writer().Exec("UPDATE sessions SET auth_time=?", time.Now().Add(-6*time.Minute).UTC().Format(time.RFC3339)); err != nil { |
| 301 | t.Fatal(err) |
| 302 | } |
| 303 | for _, path := range []string{"/connections", savedAuthURL} { |
| 304 | toHome := redirect(get(redirect(get(path)))) |
| 305 | u, err := url.Parse(toHome) |
| 306 | if err != nil || !strings.HasPrefix(toHome, home+"/authorize?") || u.Query().Get("max_age") != "300" { |
| 307 | t.Fatal("stale session bypassed fresh Home proof") |
| 308 | } |
| 309 | } |
| 310 | if err = c.Logout(ctx); err != nil { |
| 311 | t.Fatal(err) |
| 312 | } |
| 313 | if memory.value.Token != nil { |
| 314 | t.Fatal("local credential retained after logout") |
| 315 | } |
| 316 | if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "notes_create", Arguments: input}); err == nil { |
| 317 | t.Fatal("connected MCP session survived logout") |
| 318 | } |
| 319 | if calls.Load() != 2 { |
| 320 | t.Fatal("denied call mutated") |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | // Keep production origin validation intact while routing a real TLS client to |
| 325 | // the test listener. Cookies and Host still see the public DNS origin. |
| 326 | type originTransport struct { |
| 327 | base http.RoundTripper |
| 328 | origin, target string |
| 329 | } |
| 330 | |
| 331 | func (o originTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 332 | if r.URL.Scheme+"://"+r.URL.Host != o.origin { |
| 333 | return o.base.RoundTrip(r) |
| 334 | } |
| 335 | copy := r.Clone(r.Context()) |
| 336 | target, _ := url.Parse(o.target) |
| 337 | copy.URL.Host = target.Host |
| 338 | copy.Host = r.URL.Host |
| 339 | return o.base.RoundTrip(copy) |
| 340 | } |
| 341 | |
| 342 | type lockedLog struct { |
| 343 | mu sync.Mutex |
| 344 | data bytes.Buffer |
| 345 | } |
| 346 | |
| 347 | func (l *lockedLog) Write(p []byte) (int, error) { |
| 348 | l.mu.Lock() |
| 349 | defer l.mu.Unlock() |
| 350 | return l.data.Write(p) |
| 351 | } |
| 352 | func (l *lockedLog) Bytes() []byte { |
| 353 | l.mu.Lock() |
| 354 | defer l.mu.Unlock() |
| 355 | return append([]byte(nil), l.data.Bytes()...) |
| 356 | } |
| 357 | func assertNoRuntimeRetention(t *testing.T, directory string, logs *lockedLog, canaries []string) { |
| 358 | t.Helper() |
| 359 | check := func(data []byte) { |
| 360 | for _, canary := range canaries { |
| 361 | if canary != "" && bytes.Contains(data, []byte(canary)) { |
| 362 | t.Error("connection runtime retained raw content or credentials") |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | check(logs.Bytes()) |
| 367 | if err := filepath.WalkDir(directory, func(path string, entry os.DirEntry, err error) error { |
| 368 | if err != nil { |
| 369 | return err |
| 370 | } |
| 371 | if entry.IsDir() { |
| 372 | return nil |
| 373 | } |
| 374 | data, err := os.ReadFile(path) |
| 375 | if err != nil { |
| 376 | return err |
| 377 | } |
| 378 | check(data) |
| 379 | return nil |
| 380 | }); err != nil { |
| 381 | t.Fatal(err) |
| 382 | } |
| 383 | } |
| 384 | |