feat(ai): add provider connection test (#38)

This commit is contained in:
2026-11-24 16:21:48 +01:00
parent 2e865204c8
commit 54fced1ffb
16 changed files with 599 additions and 18 deletions

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -70,10 +71,34 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, _ GenO
return result.Content[0].Text, nil
}
func (p *anthropicProvider) ListModels(_ context.Context) ([]string, error) {
return []string{
"claude-opus-4-7",
"claude-sonnet-4-6",
"claude-haiku-4-5-20251001",
}, nil
// ListModels checks API authentication using discovery, never generation.
func (p *anthropicProvider) ListModels(ctx context.Context) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.anthropic.com/v1/models", nil)
if err != nil {
return nil, errors.New("model discovery request failed")
}
req.Header.Set("x-api-key", p.apiKey)
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := p.client.Do(req)
if err != nil {
return nil, errors.New("model discovery unavailable")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &summaryHTTPError{status: resp.StatusCode, err: errors.New("model discovery failed")}
}
var result struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
// Discovery responses are bounded; malformed bodies never reach callers.
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&result); err != nil {
return nil, errors.New("model discovery response invalid")
}
names := make([]string, 0, len(result.Data))
for _, model := range result.Data {
names = append(names, model.ID)
}
return names, nil
}

View File

@ -44,3 +44,6 @@ func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) {
"claude-haiku-4-5-20251001",
}, nil
}
// SupportsAuthCheck is false because model discovery is a local static catalog.
func (p *claudeCodeProvider) SupportsAuthCheck() bool { return false }

View File

@ -0,0 +1,88 @@
package ai
import (
"context"
"database/sql"
"errors"
"time"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
)
var (
ErrConnectionUnsupported = errors.New("auth_check_unsupported")
ErrConnectionAuth = errors.New("auth_rejected")
ErrConnectionUnavailable = errors.New("unavailable")
ErrConnectionNotFound = errors.New("not_found")
ErrConnectionLocal = errors.New("internal_error")
)
type ConnectionRepository interface {
GetAIProviderByID(string) (*models.AIProvider, error)
}
type ConnectionDecryptor interface{ Decrypt(string) (string, error) }
type ConnectionTester struct {
repo ConnectionRepository
enc ConnectionDecryptor
build func(string, string, string) (Provider, error)
}
func NewConnectionTester(repo ConnectionRepository, enc ConnectionDecryptor, build func(string, string, string) (Provider, error)) *ConnectionTester {
return &ConnectionTester{repo, enc, build}
}
// Test never propagates provider/configuration errors or model names to callers.
func (t *ConnectionTester) Test(ctx context.Context, id string) error {
p, err := t.repo.GetAIProviderByID(id)
if errors.Is(err, sql.ErrNoRows) {
return ErrConnectionNotFound
}
if err != nil {
return ErrConnectionLocal
}
if p == nil {
return ErrConnectionNotFound
}
key := ""
if p.APIKeyEncrypted != "" {
if t.enc == nil {
return ErrConnectionLocal
}
key, err = t.enc.Decrypt(p.APIKeyEncrypted)
if err != nil {
return ErrConnectionLocal
}
}
provider, err := t.build(p.Name, key, p.Endpoint)
if err != nil || provider == nil {
return ErrConnectionLocal
}
// Static model catalogs do not prove authentication. Keep their discovery
// behavior available to other callers without claiming connection success.
if capability, ok := provider.(interface{ SupportsAuthCheck() bool }); ok && !capability.SupportsAuthCheck() {
return ErrConnectionUnsupported
}
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
_, err = provider.ListModels(ctx)
if err == nil {
return nil
}
var local *summaryHTTPError
var api *openai.APIError
var request *openai.RequestError
status := 0
switch {
case errors.As(err, &local):
status = local.status
case errors.As(err, &api):
status = api.HTTPStatusCode
case errors.As(err, &request):
status = request.HTTPStatusCode
}
if status == 401 || status == 403 {
return ErrConnectionAuth
}
return ErrConnectionUnavailable
}

View File

@ -0,0 +1,41 @@
package ai
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"testing"
)
type connectionTransport func(*http.Request) (*http.Response, error)
func (f connectionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestConnectionDiscoveryHTTPStatus(t *testing.T) {
for _, code := range []int{401, 403, 429, 500} {
for _, name := range []string{"gemini", "ollama"} {
t.Run(fmt.Sprintf("%s/%d", name, code), func(t *testing.T) {
client := &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(`{"secret":"private response"}`)), Header: make(http.Header)}, nil
})}
var p Provider
if name == "gemini" {
g := newGemini("secret", "")
g.client = client
p = g
} else {
o := newOllama("https://private.invalid", "")
o.client = client
p = o
}
_, err := p.ListModels(context.Background())
var status *summaryHTTPError
if !errors.As(err, &status) || status.status != code || strings.Contains(err.Error(), "private") {
t.Fatalf("unsafe or unclassified error: %v", err)
}
})
}
}
}

View File

@ -0,0 +1,95 @@
package ai
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/models"
)
func TestConnectionClaudeCodeDoesNotClaimAuthSuccess(t *testing.T) {
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "claudecode"}}, nil, func(string, string, string) (Provider, error) { return newClaudeCode(""), nil })
err := tester.Test(context.Background(), "id")
if err == nil || err.Error() != "auth_check_unsupported" {
t.Fatalf("want unsupported auth check; got %v", err)
}
}
func TestConnectionAnthropicChecksAuthentication(t *testing.T) {
for _, code := range []int{200, 401, 403, 503} {
t.Run(http.StatusText(code), func(t *testing.T) {
calls := 0
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(r *http.Request) (*http.Response, error) {
calls++
if r.Method != "GET" || r.URL.String() != "https://api.anthropic.com/v1/models" || r.Header.Get("x-api-key") != "saved-secret" || r.Header.Get("anthropic-version") == "" || r.Body != nil {
t.Fatal("expected authenticated, bodyless model discovery")
}
body := `{"data":[{"id":"model-id"}]}`
if code != 200 {
body = `private body saved-secret https://private.invalid`
}
return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
})}
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "anthropic"}}, nil, func(string, string, string) (Provider, error) { return p, nil })
err := tester.Test(context.Background(), "id")
if calls != 1 {
t.Fatalf("auth requests=%d", calls)
}
var want error
if code == 401 || code == 403 {
want = ErrConnectionAuth
} else if code != 200 {
want = ErrConnectionUnavailable
}
if !errors.Is(err, want) {
t.Fatalf("got %v want %v", err, want)
}
})
}
}
func TestConnectionAnthropicDiscoverySanitizesFailures(t *testing.T) {
for _, tc := range []struct {
name string
code int
body string
transportErr error
}{
{name: "auth", code: 401, body: "saved-secret https://private.invalid private body"},
{name: "malformed", code: 200, body: "saved-secret https://private.invalid private body"},
{name: "transport", transportErr: errors.New("saved-secret https://private.invalid private body")},
} {
t.Run(tc.name, func(t *testing.T) {
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
if tc.transportErr != nil {
return nil, tc.transportErr
}
return &http.Response{StatusCode: tc.code, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
})}
_, err := p.ListModels(context.Background())
if err == nil {
t.Fatal("expected discovery error")
}
for _, s := range []string{"saved-secret", "https://", "private body"} {
if strings.Contains(err.Error(), s) {
t.Fatalf("discovery error leaked sensitive detail")
}
}
})
}
}
func TestConnectionAnthropicReturnsDiscoveredModels(t *testing.T) {
p := newAnthropic("saved-secret", "")
p.client = &http.Client{Transport: connectionTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"discovered-model"}]}`)), Header: make(http.Header)}, nil
})}
models, err := p.ListModels(context.Background())
if err != nil || len(models) != 1 || models[0] != "discovered-model" {
t.Fatal("expected discovered models")
}
}

View File

@ -0,0 +1,81 @@
package ai
import (
"context"
"errors"
"fmt"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
"testing"
)
type connectionRepo struct {
p *models.AIProvider
err error
}
func (r connectionRepo) GetAIProviderByID(string) (*models.AIProvider, error) { return r.p, r.err }
type connectionKey struct{ err error }
func (k connectionKey) Decrypt(s string) (string, error) {
if s != "cipher" {
panic("wrong cipher")
}
return "secret", k.err
}
type connectionProvider struct {
err error
calls int
}
func (*connectionProvider) Name() string { return "fake" }
func (*connectionProvider) Summarize(context.Context, string, GenOptions) (string, error) {
panic("must not generate")
}
func (p *connectionProvider) ListModels(context.Context) ([]string, error) {
p.calls++
return []string{"private-model"}, p.err
}
func TestConnectionSavedCredentials(t *testing.T) {
for _, tt := range []struct {
name string
upstream, want error
}{
{"success", nil, nil}, {"auth", fmt.Errorf("wrapped: %w", &openai.APIError{HTTPStatusCode: 401}), ErrConnectionAuth}, {"forbidden", &openai.RequestError{HTTPStatusCode: 403}, ErrConnectionAuth}, {"rate limit", &openai.APIError{HTTPStatusCode: 429}, ErrConnectionUnavailable}, {"untrusted text", errors.New("401 secret endpoint"), ErrConnectionUnavailable},
} {
t.Run(tt.name, func(t *testing.T) {
p := &connectionProvider{err: tt.upstream}
tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "fake", APIKeyEncrypted: "cipher", Endpoint: "private"}}, connectionKey{}, func(name, key, endpoint string) (Provider, error) {
if name != "fake" || key != "secret" || endpoint != "private" {
t.Fatal("saved config not used")
}
return p, nil
})
if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) {
t.Fatalf("got %v want %v", got, tt.want)
}
if p.calls != 1 {
t.Fatal("ListModels calls")
}
})
}
}
func TestConnectionLocalFailures(t *testing.T) {
for _, tt := range []struct {
name string
repo connectionRepo
key connectionKey
buildErr, want error
}{
{name: "missing", want: ErrConnectionNotFound}, {name: "database", repo: connectionRepo{err: errors.New("secret")}, want: ErrConnectionLocal}, {name: "decrypt", repo: connectionRepo{p: &models.AIProvider{APIKeyEncrypted: "cipher"}}, key: connectionKey{errors.New("secret")}, want: ErrConnectionLocal}, {name: "factory", repo: connectionRepo{p: &models.AIProvider{}}, buildErr: errors.New("secret"), want: ErrConnectionLocal},
} {
t.Run(tt.name, func(t *testing.T) {
tester := NewConnectionTester(tt.repo, tt.key, func(string, string, string) (Provider, error) { return nil, tt.buildErr })
if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) {
t.Fatalf("got %v", got)
}
})
}
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -87,7 +88,7 @@ func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) {
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("gemini list models error %d: %s", resp.StatusCode, raw)
return nil, &summaryHTTPError{status: resp.StatusCode, err: errors.New("model discovery failed")}
}
var result struct {
Models []struct {

View File

@ -116,6 +116,9 @@ func (p *OllamaProvider) ListModelsDetailed(ctx context.Context) ([]OllamaModelI
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("model discovery failed")}
}
raw, _ := io.ReadAll(resp.Body)
var result struct {

View File

@ -0,0 +1,28 @@
package api_test
import (
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/config"
"net/http/httptest"
"testing"
)
func TestAIProviderConnectionRequiresAuthentication(t *testing.T) {
h := handlers.New(nil, &config.Config{}, nil, nil, nil, nil)
r := api.SetupRouter(h, "test-secret")
found := false
for _, route := range r.Routes() {
if route.Method == "POST" && route.Path == "/api/admin/ai-providers/:id/test" {
found = true
}
}
if !found {
t.Fatal("test route missing")
}
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-providers/saved/test", nil))
if w.Code != 401 {
t.Fatalf("unauthenticated status=%d", w.Code)
}
}

View File

@ -551,3 +551,22 @@ func (h *Handler) CreateAdminUser(c *gin.Context) {
}
httputil.Created(c, user)
}
// TestAIProvider returns only bounded outcomes from saved configuration.
func (h *Handler) TestAIProvider(c *gin.Context) {
err := h.connectionTester.Test(c.Request.Context(), c.Param("id"))
switch {
case err == nil:
c.JSON(200, gin.H{"status": "success"})
case errors.Is(err, ai.ErrConnectionAuth):
c.JSON(200, gin.H{"status": "auth_rejected"})
case errors.Is(err, ai.ErrConnectionUnavailable):
c.JSON(200, gin.H{"status": "unavailable"})
case errors.Is(err, ai.ErrConnectionUnsupported):
c.JSON(200, gin.H{"status": "auth_check_unsupported"})
case errors.Is(err, ai.ErrConnectionNotFound):
c.JSON(404, gin.H{"error": "not found"})
default:
c.JSON(500, gin.H{"error": "internal server error"})
}
}

View File

@ -0,0 +1,37 @@
package handlers
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"net/http/httptest"
"testing"
)
type fakeConnection struct {
err error
id string
}
func (f *fakeConnection) Test(_ context.Context, id string) error { f.id = id; return f.err }
func TestAIProviderConnectionHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tt := range []struct {
err error
code int
body string
}{
{nil, 200, `{"status":"success"}`}, {ai.ErrConnectionAuth, 200, `{"status":"auth_rejected"}`}, {ai.ErrConnectionUnavailable, 200, `{"status":"unavailable"}`}, {ai.ErrConnectionUnsupported, 200, `{"status":"auth_check_unsupported"}`}, {ai.ErrConnectionNotFound, 404, `{"error":"not found"}`}, {errors.New("secret endpoint raw error"), 500, `{"error":"internal server error"}`},
} {
f := &fakeConnection{err: tt.err}
h := &Handler{connectionTester: f}
r := gin.New()
r.POST("/api/admin/ai-providers/:id/test", h.TestAIProvider)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-providers/saved-id/test", nil))
if w.Code != tt.code || w.Body.String() != tt.body || f.id != "saved-id" {
t.Fatalf("code=%d body=%s id=%s", w.Code, w.Body, f.id)
}
}
}

View File

@ -16,6 +16,9 @@ import (
)
type Handler struct {
connectionTester interface {
Test(context.Context, string) error
}
companyCatalog CompanyCatalog
indexSearcher indices.IndexSearcher
generationJobs interface {
@ -44,13 +47,16 @@ func New(
}
return &Handler{
companyCatalog: catalog,
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) {
return ai.NewProvider(name, key, "", endpoint)
}),
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
}
}

View File

@ -73,6 +73,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
admin.POST("/ai-providers/:id/activate", h.SetActiveAIProvider)
admin.DELETE("/ai-providers/:id", h.DeleteAIProvider)
admin.GET("/ai-providers/:id/models", h.ListAIModels)
admin.POST("/ai-providers/:id/test", h.TestAIProvider)
admin.POST("/ai-providers/probe-models", h.ProbeAIModels)
admin.GET("/sources", h.ListSources)