165 lines
7.4 KiB
Go
165 lines
7.4 KiB
Go
package api_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"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"
|
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestTicket41MigrationAdminFeedConfigurationIsAtomicAndPrivatePostgres(t *testing.T) {
|
|
db, err := sql.Open("postgres", postgresTestURL(t))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
db.SetMaxOpenConns(1)
|
|
schema := fmt.Sprintf("rss41_%d", time.Now().UnixNano())
|
|
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
|
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
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','admin@example.test','admin','hash'),('user','user@example.test','user','hash')`,
|
|
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','cnbc_business','watcherguru','reuters')),source_key TEXT UNIQUE CONSTRAINT sources_source_key_check CHECK(source_key IN ('bloomberg','yahoo_finance','cnbc_business','watcher_guru')),enabled BOOLEAN,article_limit INTEGER,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
`INSERT INTO sources(id,name,type,source_key,enabled,article_limit) VALUES('00000000-0000-0000-0000-000000004101','Bloomberg','bloomberg','bloomberg',false,77),('00000000-0000-0000-0000-000000004102','Yahoo Finance','stocktwits','yahoo_finance',true,83),('00000000-0000-0000-0000-000000004103','CNBC Business','cnbc_business','cnbc_business',true,31)`,
|
|
`CREATE TABLE articles(id TEXT PRIMARY KEY,source_id UUID REFERENCES sources(id),title TEXT)`,
|
|
`INSERT INTO articles VALUES('history','00000000-0000-0000-0000-000000004101','Synthetic history')`,
|
|
} {
|
|
if _, err = db.Exec(q); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
raw, err := os.ReadFile("../database/migrations/000021_quanwen_rss.up.sql")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(`ALTER TABLE sources ADD CONSTRAINT refuse_investing_fixture CHECK(name <> 'Investing.com')`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(string(raw)); err == nil {
|
|
t.Fatal("migration fixture did not fail")
|
|
}
|
|
var noChild bool
|
|
if err = db.QueryRow(`SELECT to_regclass('source_feeds') IS NULL`).Scan(&noChild); err != nil || !noChild {
|
|
t.Fatal("failed migration leaked child table")
|
|
}
|
|
if _, err = db.Exec(`ALTER TABLE sources DROP CONSTRAINT refuse_investing_fixture`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(string(raw)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var count int
|
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 6 {
|
|
t.Fatal("default feed migration failed")
|
|
}
|
|
if err = db.QueryRow(`SELECT count(*) FROM sources WHERE (source_key='bloomberg' AND article_limit=77 AND NOT enabled) OR (source_key='yahoo_finance' AND article_limit=83 AND enabled) OR (source_key='cnbc_business' AND article_limit=31 AND enabled)`).Scan(&count); err != nil || count != 3 {
|
|
t.Fatal("migration changed existing source switches/caps")
|
|
}
|
|
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
|
t.Fatal("history changed")
|
|
}
|
|
const secret = "ticket41-fixture"
|
|
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
|
token, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
|
|
user, _ := auth.GenerateToken("user", "user@example.test", "user", secret)
|
|
request := func(method, path, body, token string) *httptest.ResponseRecorder {
|
|
r := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
|
r.Header.Set("Content-Type", "application/json")
|
|
if token != "" {
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
path := "/api/admin/sources/00000000-0000-0000-0000-000000004101"
|
|
approved := sourcefeeds.Defaults(sourcefeeds.Bloomberg)[2]
|
|
good, _ := json.Marshal(map[string]any{"enabled": true, "article_limit": 12, "feed_urls": []string{approved}})
|
|
for _, token := range []string{"", user} {
|
|
if w := request(http.MethodPut, path, string(good), token); w.Code != 401 && w.Code != 403 {
|
|
t.Fatal("non-admin mutated feeds")
|
|
}
|
|
}
|
|
for _, body := range []string{
|
|
`null`, `{"enabled":true,"feed_urls":null}`, `{"enabled":true,"feed_urls":[]}`,
|
|
`{"enabled":true,"article_limit":0}`, `{"enabled":true,"feed_urls":[""]}`,
|
|
`{"enabled":true,"feed_urls":["https://127.0.0.1/PRIVATE_CANARY"]}`,
|
|
`{"enabled":true,"feed_urls":["https://feed.quanwenrss.com/feed/investing-news.xml"]}`,
|
|
fmt.Sprintf(`{"enabled":true,"feed_urls":[%q,%q]}`, approved, approved),
|
|
`{"enabled":true,"PRIVATE_CANARY":"ignored"}`, strings.Repeat(" ", 8193) + `{}`,
|
|
} {
|
|
w := request(http.MethodPut, path, body, token)
|
|
if w.Code != 400 || strings.Contains(w.Body.String(), "PRIVATE_CANARY") || strings.Contains(w.Body.String(), "http") {
|
|
t.Error("invalid admin configuration accepted or response exposed raw values")
|
|
}
|
|
}
|
|
var enabled bool
|
|
var cap int
|
|
if err = db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE source_key='bloomberg'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
|
|
t.Fatal("rejected update was not atomic")
|
|
}
|
|
if w := request(http.MethodPut, path, string(good), token); w.Code != 200 {
|
|
t.Fatal("valid source configuration rejected")
|
|
}
|
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds WHERE source_id='00000000-0000-0000-0000-000000004101'`).Scan(&count); err != nil || count != 1 {
|
|
t.Fatal("configuration was not replaced")
|
|
}
|
|
w := request(http.MethodGet, "/api/admin/sources", "", token)
|
|
var result struct {
|
|
Data []models.Source `json:"data"`
|
|
}
|
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
|
t.Fatal("admin cannot read saved feed configuration")
|
|
}
|
|
found := false
|
|
for _, s := range result.Data {
|
|
if s.SourceKey != nil && *s.SourceKey == models.SourceBloomberg {
|
|
found = s.Enabled && s.ArticleLimit == 12 && len(s.FeedURLs) == 1 && s.FeedURLs[0] == approved
|
|
}
|
|
}
|
|
if !found {
|
|
t.Fatal("saved feed configuration does not round-trip")
|
|
}
|
|
if w := request(http.MethodPut, path, `{"enabled":false}`, token); w.Code != 200 {
|
|
t.Fatal("omitted feed configuration rejected")
|
|
}
|
|
values, err := models.NewRepository(db).SourceFeedURLs(context.Background(), models.SourceBloomberg)
|
|
if err != nil || len(values) != 1 || values[0] != approved {
|
|
t.Fatal("omitting feeds erased saved configuration")
|
|
}
|
|
down, err := os.ReadFile("../database/migrations/000021_quanwen_rss.down.sql")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = db.Exec(string(down)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 2 {
|
|
t.Fatal("downgrade removed configuration")
|
|
}
|
|
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
|
t.Fatal("downgrade removed history")
|
|
}
|
|
|
|
}
|