package qaopsmirror import ( "context" "encoding/json" "knowledge-governance/internal/qaopsai" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) func TestAISettingsUseRealSyntheticProbeEncryptedStorageAndExplicitKeyActions(t *testing.T) { pool := mirrorFixture(t) ctx := context.Background() keyFile := filepath.Join(t.TempDir(), "master-key") if err := os.WriteFile(keyFile, []byte(strings.Repeat("a", 32)), 0600); err != nil { t.Fatal(err) } calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ if r.Header.Get("Authorization") != "Bearer fixture-only" { t.Error("wrong key used") } _, _ = w.Write([]byte(`{"model":"fixture","choices":[{"message":{"content":"{\"ok\":true}"},"finish_reason":"stop"}]}`)) })) defer server.Close() store := qaopsai.NewStore(pool, "fixture-ai-settings", qaopsai.Options{KeyFile: keyFile, AllowPrivate: true}) first, err := store.SaveSettings(ctx, qaopsai.SaveSettings{BaseURL: server.URL + "/v1", Model: "fixture", KeyAction: "replace", APIKey: "fixture-only"}, "fixture-admin") if err != nil || !first.KeyConfigured || first.Verification != "verified" || first.Revision != 1 || calls != 1 { t.Fatalf("save must perform real probe: settings=%+v err=%v calls=%d", first, err, calls) } raw, _ := json.Marshal(first) if strings.Contains(string(raw), "fixture-only") { t.Fatal("public settings leaked key") } var sealed []byte if err = pool.QueryRow(ctx, `SELECT key_ciphertext FROM qa_ops_ai_settings WHERE tenant_key=$1`, "fixture-ai-settings").Scan(&sealed); err != nil || len(sealed) == 0 || strings.Contains(string(sealed), "fixture-only") { t.Fatal("key not encrypted", err) } kept, err := store.SaveSettings(ctx, qaopsai.SaveSettings{BaseRevision: first.Revision, BaseURL: first.BaseURL, Model: first.Model, KeyAction: "keep"}, "fixture-admin") if err != nil || !kept.KeyConfigured || calls != 2 { t.Fatal("blank keep did not reuse saved key through probe", err) } cleared, err := store.SaveSettings(ctx, qaopsai.SaveSettings{BaseRevision: kept.Revision, BaseURL: kept.BaseURL, Model: kept.Model, KeyAction: "clear"}, "fixture-admin") if err != nil || cleared.KeyConfigured || cleared.Verification != "not_configured" || calls != 2 { t.Fatal("clear called provider or retained active key", err) } got, err := store.GetSettings(ctx) if err != nil || got.Revision != cleared.Revision || got.AutomaticEvaluation || got.AutomaticTranslation { t.Fatal("settings not read back or save started automatic processing", err) } }