package http import ( "bytes" "encoding/json" "io" "net/http" "net/http/cookiejar" "strings" "testing" "gitea.federated.computer/Federated_Computer/brain/internal/db" ) // machineReq calls the API with an API-key Bearer header and no cookies — // the shape a gateway-spawned MCP server uses. func machineReq(t *testing.T, base, method, path, apiKey string, body any) (int, map[string]any) { t.Helper() var b io.Reader if body != nil { raw, _ := json.Marshal(body) b = bytes.NewReader(raw) } req, _ := http.NewRequest(method, base+path, b) req.Header.Set("Content-Type", "application/json") if apiKey != "" { req.Header.Set("Authorization", "Bearer "+apiKey) } res, e := http.DefaultClient.Do(req) if e != nil { t.Fatal(e) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) var v map[string]any json.Unmarshal(raw, &v) return res.StatusCode, v } func TestAPIKeys(t *testing.T) { srv, d := testServerDB(t) newClient := func() apiClient { jar, _ := cookiejar.New(nil); return apiClient{t, &http.Client{Jar: jar}, srv.URL} } alice, bob := newClient(), newClient() post := func(email string) map[string]any { return map[string]any{"email": email, "password": "a-long-test-password"} } alice.request("POST", "/api/signup", post("alice@superbrain.test"), 201) alice.request("POST", "/api/auth/login", post("alice@superbrain.test"), 200) bob.request("POST", "/api/signup", post("bob@superbrain.test"), 201) bob.request("POST", "/api/auth/login", post("bob@superbrain.test"), 200) au := meID(alice) // Plan gate: the test deployment derives the selfhosted plan, whose // connectors do NOT include mcp-core — issuance is refused and the list // reports the feature as unavailable (the UI gates on this flag). alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 403) v := alice.request("GET", "/api/keys", nil, 200) if v["allowed"] != false { t.Fatalf("expected allowed=false on a plan without mcp-core: %v", v) } // Upgrade the implicit tenant to the core plan (catalog data, not env). if _, e := d.Exec(`UPDATE "Tenant" SET plan='core' WHERE id=$1`, db.DefaultTenantID); e != nil { t.Fatal(e) } out := alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 201) key, _ := out["key"].(string) if !strings.HasPrefix(key, "sb_") || len(key) != 46 { t.Fatalf("unexpected key shape: %q", key) } if out["prefix"] != key[:11] { t.Fatalf("prefix %v does not match key", out["prefix"]) } if _, leaked := out["keyHash"]; leaked { t.Fatal("keyHash leaked into the API response") } id, _ := out["id"].(string) // Bad input. alice.request("POST", "/api/keys", map[string]any{"name": ""}, 400) alice.request("POST", "/api/keys", map[string]any{"name": strings.Repeat("x", 101)}, 400) // The key authenticates machine requests: identity resolves to the // owner and data endpoints work without any cookie. code, body := machineReq(t, srv.URL, "GET", "/api/me", key, nil) if code != 200 || body["user"].(map[string]any)["id"] != au { t.Fatalf("api key did not resolve to its owner: %d %v", code, body) } code, _ = machineReq(t, srv.URL, "POST", "/api/bookmarks", key, map[string]any{"url": "https://127.0.0.1/mcp", "title": "via key"}) if code != 201 { t.Fatalf("bookmark create with api key: wanted 201, got %d", code) } // Unknown and malformed keys are 401 (a malformed token falls through // to the assertion channel, which also rejects it). code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_"+strings.Repeat("A", 43), nil) if code != 401 { t.Fatalf("unknown api key: wanted 401, got %d", code) } code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_short", nil) if code != 401 { t.Fatalf("malformed api key: wanted 401, got %d", code) } // List projection: masked, owner-scoped, lastUsedAt touched by the use // above (throttled to once a minute, but this is the first use). v = alice.request("GET", "/api/keys", nil, 200) if v["allowed"] != true { t.Fatalf("expected allowed=true on the core plan: %v", v) } keys := v["keys"].([]any) first := keys[0].(map[string]any) if first["name"] != "mcpserver" || first["lastUsedAt"] == nil { t.Fatalf("unexpected list projection: %v", first) } if _, hasKey := first["key"]; hasKey { t.Fatal("plaintext key echoed by the list endpoint") } // Owner-scoped revocation. bob.request("DELETE", "/api/keys/"+id, nil, 404) // Cap: 10 live keys per user (1 exists; create 9 more, then refuse). for i := 0; i < maxTestKeys-1; i++ { alice.request("POST", "/api/keys", map[string]any{"name": "script"}, 201) } alice.request("POST", "/api/keys", map[string]any{"name": "one-too-many"}, 400) // Revocation is immediate: the row is deleted and the key stops working. alice.request("DELETE", "/api/keys/"+id, nil, 200) code, _ = machineReq(t, srv.URL, "GET", "/api/me", key, nil) if code != 401 { t.Fatalf("revoked api key: wanted 401, got %d", code) } // Deliberate semantics (apikeys.go): keys are independent of // tokenVersion. A revocation bump kills the browser session (existing // SEC-02 contract) but NOT the machine credential — gateways must not // break because a user changed their password. keys = alice.request("GET", "/api/keys", nil, 200)["keys"].([]any) alice.request("DELETE", "/api/keys/"+keys[0].(map[string]any)["id"].(string), nil, 200) out = alice.request("POST", "/api/keys", map[string]any{"name": "survivor"}, 201) key2 := out["key"].(string) if _, e := d.Exec(`UPDATE "User" SET "tokenVersion"="tokenVersion"+1 WHERE id=$1`, au); e != nil { t.Fatal(e) } alice.request("GET", "/api/me", nil, 401) // cookie session revoked (SEC-02) code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil) if code != 200 { t.Fatalf("api key must survive a tokenVersion bump: got %d", code) } // Downgrade fails closed at USE time too: the key is valid but the plan // no longer includes mcp-core. if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil { t.Fatal(e) } code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil) if code != 403 { t.Fatalf("downgraded plan: wanted 403 for a valid key, got %d", code) } } // maxTestKeys mirrors handlers.maxAPIKeys (kept local so the test states the // product number explicitly). const maxTestKeys = 10