package http import ( "encoding/json" "io" "net" "net/http" "net/http/cookiejar" "strings" "testing" ) // fakeAIProviders serves all three provider shapes on one loopback server: // OpenAI-compatible /v1/chat/completions, Anthropic /v1/messages, Gemini // /v1beta/models/{model}:generateContent. It records the auth header style // each adapter must use so credential plumbing is asserted, not assumed. type fakeAIProviders struct { ln net.Listener srv *http.Server lastAuth map[string]string // path -> auth header seen } func newFakeAIProviders(t *testing.T) *fakeAIProviders { t.Helper() ln, e := net.Listen("tcp", "127.0.0.1:0") if e != nil { t.Fatal(e) } f := &fakeAIProviders{ln: ln, lastAuth: map[string]string{}} mux := http.NewServeMux() mux.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) { f.lastAuth["openai"] = r.Header.Get("Authorization") w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"pong"}}]}`) }) mux.HandleFunc("/v1/messages", func(w http.ResponseWriter, r *http.Request) { f.lastAuth["anthropic"] = r.Header.Get("x-api-key") + "|" + r.Header.Get("anthropic-version") w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"content":[{"type":"text","text":"pong"}]}`) }) mux.HandleFunc("/v1beta/models/", func(w http.ResponseWriter, r *http.Request) { f.lastAuth["gemini"] = r.Header.Get("x-goog-api-key") // The key must never appear in the URL (it would land in logs). if strings.Contains(r.URL.RawQuery, "key=") { w.WriteHeader(400) return } w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"candidates":[{"content":{"parts":[{"text":"pong"}]}}]}`) }) f.srv = &http.Server{Handler: mux} go f.srv.Serve(ln) t.Cleanup(func() { f.srv.Close() }) return f } func (f *fakeAIProviders) baseURL() string { return "http://" + f.ln.Addr().String() } // TestAiConfig: BYO config lifecycle (masked write-only key, version // contract, encrypted at rest), all three provider adapters, and the // plan gate on the SERVER key (free = BYO-only, premium/core/selfhosted // may spend the operator's key). func TestAiConfig(t *testing.T) { srv, d := testServerDB(t) fake := newFakeAIProviders(t) base := fake.baseURL() jar, _ := cookiejar.New(nil) alice := apiClient{t, &http.Client{Jar: jar}, srv.URL} alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201) alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200) // Status with nothing configured anywhere. st := alice.request("GET", "/api/ai/status", nil, 200) if st["effective"] != "none" || st["userConfigured"] != false || st["serverAvailable"] != false { t.Fatalf("initial status wrong: %v", st) } // Test endpoint without any config: 428 precondition, not a 500. alice.request("POST", "/api/ai/test", nil, 428) // Compile inherits the same precondition. alice.request("POST", "/api/agent/compile", map[string]any{"text": "x"}, 428) // --- PUT create: openai-compatible with a BYO key + instructions --- created := alice.request("PUT", "/api/ai/config", map[string]any{ "provider": "openai-compatible", "baseUrl": base + "/v1", "model": "test-model", "apiKey": "sk-byo-secret-123", "instructions": "Answer like a pirate.", }, 201) if created["apiKey"] != "••••••••" { t.Fatalf("key leaked in response: %v", created["apiKey"]) } if created["instructions"] != "Answer like a pirate." { t.Fatalf("instructions not echoed: %v", created["instructions"]) } // GET returns the same projection (instructions are not a secret). gotCfg := alice.request("GET", "/api/ai/config", nil, 200) if gotCfg["instructions"] != "Answer like a pirate." || gotCfg["apiKey"] != "••••••••" { t.Fatalf("GET projection wrong: %v", gotCfg) } // Encrypted at rest, decryptable with the server secret. var storedKey string if e := d.QueryRow(`SELECT "apiKey" FROM "UserAiConfig" WHERE "ownerId"=(SELECT id FROM "User" WHERE email='alice@superbrain.test')`).Scan(&storedKey); e != nil { t.Fatal(e) } if strings.Contains(storedKey, "sk-byo-secret-123") { t.Fatal("BYO key stored in plaintext") } // Test endpoint now uses the BYO config. test := alice.request("POST", "/api/ai/test", nil, 200) if test["source"] != "user" || test["reply"] != "pong" { t.Fatalf("test call wrong: %v", test) } if got := fake.lastAuth["openai"]; got != "Bearer sk-byo-secret-123" { t.Fatalf("openai adapter auth header = %q", got) } st = alice.request("GET", "/api/ai/status", nil, 200) if st["effective"] != "user" { t.Fatalf("effective source = %v, want user", st["effective"]) } // --- Version contract + masked-key preservation on update --- alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "claude-x", "apiKey": "••••••••"}, 400) // missing version updated := alice.request("PUT", "/api/ai/config", map[string]any{ "provider": "anthropic", "baseUrl": base, "model": "claude-x", "apiKey": "••••••••", "version": int(created["version"].(float64)), }, 200) // Full-replacement semantics: omitting instructions clears them. if updated["instructions"] != "" { t.Fatalf("instructions must clear when omitted: %v", updated["instructions"]) } alice.request("POST", "/api/ai/test", nil, 200) if got := fake.lastAuth["anthropic"]; got != "sk-byo-secret-123|2023-06-01" { t.Fatalf("anthropic adapter headers = %q (mask must preserve the stored key)", got) } _ = updated // --- Gemini adapter: key must travel in the header, never the URL --- alice.request("PUT", "/api/ai/config", map[string]any{ "provider": "gemini", "baseUrl": base, "model": "gemini-test", "apiKey": "••••••••", "version": int(updated["version"].(float64)), }, 200) alice.request("POST", "/api/ai/test", nil, 200) if got := fake.lastAuth["gemini"]; got != "sk-byo-secret-123" { t.Fatalf("gemini adapter key header = %q", got) } // --- Validation --- alice.request("PUT", "/api/ai/config", map[string]any{"provider": "skynet", "model": "x", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "m", "baseUrl": "ftp://x", "apiKey": "k", "version": 3}, 400) alice.request("PUT", "/api/ai/config", map[string]any{"provider": "anthropic", "model": "m", "apiKey": "k", "instructions": strings.Repeat("x", 4001), "version": 3}, 400) // --- Plan gate on the SERVER key --- // Selfhosted (the harness default) may spend the operator's key. t.Setenv("AI_API_KEY", "server-key-abc") t.Setenv("AI_BASE_URL", base+"/v1") t.Setenv("AI_MODEL", "server-model") // Delete the BYO config -> falls back to the server key. alice.request("DELETE", "/api/ai/config", nil, 200) st = alice.request("GET", "/api/ai/status", nil, 200) if st["effective"] != "server" || st["serverAvailable"] != true { t.Fatalf("selfhosted must allow the server key: %v", st) } test = alice.request("POST", "/api/ai/test", nil, 200) if test["source"] != "server" { t.Fatalf("test source = %v, want server", test["source"]) } if got := fake.lastAuth["openai"]; got != "Bearer server-key-abc" { t.Fatalf("server key not used: %q", got) } // Free plan: BYO-only. The server key must NOT be offered. if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id='tenant-default'`); e != nil { t.Fatal(e) } st = alice.request("GET", "/api/ai/status", nil, 200) if st["effective"] != "none" || st["serverAvailable"] != false { t.Fatalf("free plan must be BYO-only: %v", st) } alice.request("POST", "/api/ai/test", nil, 428) // Premium: server key allowed again (credits model). if _, e := d.Exec(`UPDATE "Tenant" SET plan='premium' WHERE id='tenant-default'`); e != nil { t.Fatal(e) } st = alice.request("GET", "/api/ai/status", nil, 200) if st["effective"] != "server" { t.Fatalf("premium must allow the server key: %v", st) } // A BYO config always wins over the server key, on any plan. alice.request("PUT", "/api/ai/config", map[string]any{ "provider": "openai-compatible", "baseUrl": base + "/v1", "model": "byo-model", "apiKey": "sk-byo-2", }, 201) test = alice.request("POST", "/api/ai/test", nil, 200) if test["source"] != "user" { t.Fatalf("BYO must take precedence: %v", test) } // Compile flows through the same resolution (fake answers a canned // compiler payload). raw, _ := json.Marshal(map[string]any{"text": "watch https://x.test and email a@b.test"}) req, _ := http.NewRequest("POST", srv.URL+"/api/agent/compile", strings.NewReader(string(raw))) req.Header.Set("Content-Type", "application/json") res, e := (&http.Client{Jar: jar}).Do(req) if e != nil { t.Fatal(e) } res.Body.Close() // The fake's fixed "pong" reply is not valid compiler JSON -> 502/422 // territory; the point is that it is NOT 428 anymore (resolution worked). if res.StatusCode == 428 { t.Fatal("compile still reports unconfigured despite a BYO config") } }