package api_test import ( "bytes" "database/sql" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/lib/pq" "github.com/tradarr/backend/internal/api" "github.com/tradarr/backend/internal/api/handlers" "github.com/tradarr/backend/internal/auth" "github.com/tradarr/backend/internal/config" "github.com/tradarr/backend/internal/models" ) func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgres(t *testing.T) { dbURL := postgresTestURL(t) db, err := sql.Open("postgres", dbURL) if err != nil { t.Fatal(err) } db.SetMaxOpenConns(1) schema := fmt.Sprintf("ticket13_admin_sources_%d", time.Now().UnixNano()) if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil { _ = db.Close() t.Fatal(err) } if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`) _ = db.Close() t.Fatal(err) } t.Cleanup(func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() }) for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('b-id','Bloomberg','bloomberg',true,83,'bloomberg')`} { if _, err = db.Exec(q); err != nil { t.Fatal(err) } } for _, q := range []string{`CREATE TABLE source_feeds(source_id TEXT,position INT,url TEXT)`, `INSERT INTO source_feeds VALUES('b-id',0,'https://feed.quanwenrss.com/feed/bloomberg-latest.xml')`} { if _, err = db.Exec(q); err != nil { t.Fatal(err) } } const secret = "ticket13-admin-route-test" token, err := auth.GenerateToken("admin-id", "admin@example.test", "admin", secret) if err != nil { t.Fatal(err) } router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret) get := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/api/admin/sources", nil) req.Header.Set("Authorization", "Bearer "+token) router.ServeHTTP(get, req) if get.Code != http.StatusOK { t.Fatalf("GET sources status=%d body=%s", get.Code, get.Body.String()) } var envelope struct { Data []map[string]any `json:"data"` } if err := json.Unmarshal(get.Body.Bytes(), &envelope); err != nil { t.Fatal(err) } rows := envelope.Data var old map[string]any var supported map[string]any for _, row := range rows { if row["id"] == "old-id" { old = row } if row["id"] == "b-id" { supported = row } } if old == nil { t.Fatalf("GET omitted historical source: %s", get.Body.String()) } for field, want := range map[string]any{"source_key": nil, "supported": false, "enabled": true, "operational": false} { if _, exists := old[field]; !exists { t.Errorf("historical response omitted %s: row=%v", field, old) } if old[field] != want { t.Errorf("historical %s=%v, want %v; row=%v", field, old[field], want, old) } } for _, secretField := range []string{"api_key", "password", "credentials", "article", "content", "url"} { if _, ok := old[secretField]; ok { t.Errorf("GET sources exposed forbidden %q", secretField) } } if supported == nil { t.Fatalf("GET omitted supported source: %s", get.Body.String()) } for field, want := range map[string]any{"source_key": "bloomberg", "supported": true, "operational": true} { if supported[field] != want { t.Errorf("supported source %s=%v, want %v; row=%v", field, supported[field], want, supported) } } put := httptest.NewRecorder() req = httptest.NewRequest(http.MethodPut, "/api/admin/sources/old-id", bytes.NewBufferString(`{"enabled":true,"article_limit":99}`)) req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(put, req) if put.Code != http.StatusConflict { t.Errorf("PUT historical source status=%d body=%s, want 409 source_not_supported", put.Code, put.Body.String()) } if !bytes.Contains(put.Body.Bytes(), []byte("source_not_supported")) { t.Errorf("PUT error body=%s, want source_not_supported", put.Body.String()) } var enabled bool var cap int if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='old-id'`).Scan(&enabled, &cap); err != nil { t.Fatal(err) } if !enabled || cap != 42 { t.Fatalf("rejected update mutated historical row enabled=%v cap=%d", enabled, cap) } }