Separate AI config from implementation: BYO provider, model and key per user
release gate / check (push) Failing after 6m42s
release gate / check (push) Failing after 6m42s
The plan matrix's 'use your own AI' rows, made real. internal/ai is now pure implementation: three provider adapters — openai-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent; the key travels in the x-goog-api-key HEADER, never the URL, because Go's HTTP error strings include URLs and errors get logged). One netguard-dialed client, per-source outbound budgets (ai:user:<id> vs ai:server). Configuration is data: UserAiConfig (migration 015) — one row per user with provider, base URL, model and an API key encrypted at rest via internal/crypto (the IMAP-password format), masked in every response; a PUT echoing the mask or leaving the key blank keeps the stored value; version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config, POST /api/ai/test (one probe completion through the resolved config), GET /api/ai/status (plan-gated availability, no secrets). Resolution chain (ai.ResolveForUser): the user's enabled BYO config first on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/ AI_PROVIDER) only when the tenant's plan may spend it — new entitlements.AllowServerAI: premium (credits), core (house gateway) and selfhosted (operator IS the user); free/standard are BYO-only, exactly the matrix. No AI available => 428 with a pointer to Settings -> AI (was a global 503): the precondition is per-user now. Agent compile and url_watch extraction resolve per owner, so different users' tasks can run on different providers. Web: Settings -> AI tab (provider picker with per-provider defaults and model hints, write-only key input, Test button, effective-source badge with plan context, enable switch, remove). The Automations tab reads /api/ai/status for a proactive banner and treats 428 as 'not configured'. Preparatory refactors (behavior-preserving): agent.AutomationSchema extracted as the single spec text shared by the compiler prompt (and the upcoming chat assistant), and ai.CompleteMessages for multi-turn conversations with per-provider role mapping (assistant -> model on Gemini). Tests: all three adapters against one loopback fake (asserting each provider's auth-header shape), masked-key lifecycle incl. mask-echo preservation across a provider switch, encrypted-at-rest verification, plan gate both directions (free refuses the server key, premium/core/ selfhosted allow it), BYO precedence over the server key, validation rejects, 428 paths, and compile resolution through a BYO config. Full suite green (-race), converge green (015), web lint/SSR/build clean. Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first + plan-gated server fallback, .env.example (AI_PROVIDER + the precedence story), compose passthrough, AGENTS.md invariant (config vs implementation, Gemini key-in-header rule).
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
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 ---
|
||||
created := alice.request("PUT", "/api/ai/config", map[string]any{
|
||||
"provider": "openai-compatible", "baseUrl": base + "/v1", "model": "test-model",
|
||||
"apiKey": "sk-byo-secret-123",
|
||||
}, 201)
|
||||
if created["apiKey"] != "••••••••" {
|
||||
t.Fatalf("key leaked in response: %v", created["apiKey"])
|
||||
}
|
||||
// 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)
|
||||
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)
|
||||
|
||||
// --- 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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user