feat(sources): enforce supported source allowlist

Assign stable keys to the three supported sources, preserve excluded historical rows, and expose history read-only in admin. Add migration, coverage, and responsive browser spec.

Refs #13

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 00:11:26 +01:00
parent 4459a81206
commit ac17d27f51
26 changed files with 924 additions and 61 deletions

View File

@ -0,0 +1,3 @@
-- Historical rows stay preserved and disabled; rollback must not reactivate
-- sources for which the previous enabled state is no longer known.
ALTER TABLE sources DROP COLUMN source_key;

View File

@ -0,0 +1,30 @@
-- One SQL statement: validation, DDL and backfill share a transaction even when
-- executed without a caller-owned transaction. Never merge historical sources.
DO $migration$
BEGIN
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
IF (SELECT count(*) FROM sources WHERE type = 'stocktwits'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Yahoo Finance';
END IF;
IF (SELECT count(*) FROM sources WHERE type = 'bloomberg'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Bloomberg';
END IF;
IF (SELECT count(*) FROM sources WHERE type = 'watcherguru'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Watcher.Guru';
END IF;
ALTER TABLE sources ADD COLUMN source_key TEXT NULL
CONSTRAINT sources_source_key_check CHECK (source_key IN ('yahoo_finance', 'bloomberg', 'watcher_guru'));
CREATE UNIQUE INDEX sources_source_key_unique ON sources(source_key) WHERE source_key IS NOT NULL;
UPDATE sources SET source_key = CASE
WHEN type = 'stocktwits' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance' THEN 'yahoo_finance'
WHEN type = 'bloomberg' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg' THEN 'bloomberg'
WHEN type = 'watcherguru' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru' THEN 'watcher_guru'
ELSE NULL END;
UPDATE sources SET enabled = false WHERE source_key IS NULL;
END
$migration$;

View File

@ -0,0 +1,81 @@
package migrations
import (
"os"
"reflect"
"testing"
)
func TestSourceMigrationDirectExecFailureLeavesSchemaAndRowsUnchangedPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
// Caller intentionally supplies no transaction. The migration must own its
// atomicity, as when a migration driver submits a single SQL statement.
for _, row := range ticket13HistoricalRows() {
if row.typ == "bloomberg" {
continue
}
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
beforeSchema := ticket13SchemaSnapshot(t, db)
beforeRows := ticket13ReadSources(t, db)
up, err := os.ReadFile("000015_source_allowlist.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(up)); err == nil {
t.Fatal("missing exact Bloomberg identity accepted")
}
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
t.Fatal("direct Exec changed schema on failure")
}
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
t.Fatal("direct Exec changed rows on failure")
}
}
func TestSourceMigrationNormalizesNamesWithoutFuzzyMatchingOrRewritingOutcomesPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, row := range []ticket13SourceRow{
{"y", "\tYaHoO \n Finance \t", "stocktwits", true, 83},
{"b", " Bloomberg ", "bloomberg", false, 77},
{"w", " watcher.guru ", "watcherguru", true, 64},
{"fake-y", "Yahoo Finance Daily", "stocktwits", true, 42},
{"wrong-type", "Yahoo Finance", "reuters", true, 31},
{"wrong-name", "StockTwits", "stocktwits", true, 32},
{"no-dot", "Watcher Guru", "watcherguru", true, 33},
} {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`CREATE TABLE summary_generations(id TEXT PRIMARY KEY,outcome JSONB); INSERT INTO summary_generations VALUES('old','{"source_stats":[{"source_id":"wrong-name","source_type":"stocktwits","selected":4}],"status":"succeeded"}')`); err != nil {
t.Fatal(err)
}
var before, after string
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&before); err != nil {
t.Fatal(err)
}
applyTicket13(t, db)
var targets, unsupported int
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NOT NULL`).Scan(&targets); err != nil || targets != 3 {
t.Fatalf("target count=%d err=%v", targets, err)
}
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NULL AND enabled=false`).Scan(&unsupported); err != nil || unsupported != 4 {
t.Fatalf("unsupported count=%d err=%v", unsupported, err)
}
var enabled bool
var cap int
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='b'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
t.Fatalf("recognized disabled/cap state changed: %v %d %v", enabled, cap, err)
}
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&after); err != nil || after != before {
t.Fatal("historical outcome rewritten", err)
}
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('duplicate-key','x','x',true,20,'yahoo_finance')`); err == nil {
t.Fatal("duplicate source_key accepted")
}
}

View File

@ -0,0 +1,267 @@
package migrations
import (
"database/sql"
"fmt"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/lib/pq"
)
// These cases intentionally exercise the historical source identity pairs:
// Yahoo's type is stocktwits, while the actual StockTwits row has a different name.
func TestSourceAllowlistMigrationBackfillsOnlyExactTargetsPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, row := range []struct {
id, name, typ string
enabled bool
cap int
}{
{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83},
{"bloomberg-id", "Bloomberg", "bloomberg", false, 77},
{"watcher-id", "Watcher.Guru", "watcherguru", true, 64},
{"stocktwits-id", "StockTwits", "stocktwits", true, 31},
{"reuters-id", "Reuters", "reuters", true, 42},
} {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) VALUES('article-yahoo','yahoo-id','historic','https://fixture.invalid/yahoo'),('article-stocktwits','stocktwits-id','historic','https://fixture.invalid/stocktwits')`); err != nil {
t.Fatal(err)
}
applyTicket13(t, db)
want := map[string]struct {
key string
enabled bool
cap int
}{
"yahoo-id": {"yahoo_finance", true, 83}, "bloomberg-id": {"bloomberg", false, 77}, "watcher-id": {"watcher_guru", true, 64},
"stocktwits-id": {"", false, 31}, "reuters-id": {"", false, 42},
}
for id, expected := range want {
var key sql.NullString
var enabled bool
var cap int
if err := db.QueryRow(`SELECT source_key,enabled,article_limit FROM sources WHERE id=$1`, id).Scan(&key, &enabled, &cap); err != nil {
t.Fatal(err)
}
actualKey := ""
if key.Valid {
actualKey = key.String
}
if actualKey != expected.key || enabled != expected.enabled || cap != expected.cap {
t.Errorf("%s => key=%q enabled=%v cap=%d, want key=%q enabled=%v cap=%d", id, actualKey, enabled, cap, expected.key, expected.enabled, expected.cap)
}
}
for _, id := range []string{"article-yahoo", "article-stocktwits"} {
var count int
if err := db.QueryRow(`SELECT count(*) FROM articles WHERE id=$1`, id).Scan(&count); err != nil || count != 1 {
t.Errorf("historical FK article %s count=%d err=%v", id, count, err)
}
}
}
func TestSourceAllowlistMigrationFailsAtomicallyForMissingOrAmbiguousTargetPostgres(t *testing.T) {
targets := []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}}
cases := []struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{}
for i, target := range targets {
missingID := target.id
cases = append(cases, struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{
name: "missing required " + target.name,
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow {
out := []ticket13SourceRow{}
for _, row := range rows {
if row.id != missingID {
out = append(out, row)
}
}
return out
},
})
duplicate := target
duplicate.id = fmt.Sprintf("duplicate-%d", i)
duplicate.enabled, duplicate.cap = false, 19
cases = append(cases, struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{
name: "duplicate exact identity " + target.name,
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow { return append(rows, duplicate) },
})
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
rows := tc.mutate(ticket13HistoricalRows())
for _, row := range rows {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) SELECT 'article-'||id,id,'fixture','https://fixture.invalid/'||id FROM sources`); err != nil {
t.Fatal(err)
}
beforeSchema := ticket13SchemaSnapshot(t, db)
beforeRows := ticket13ReadSources(t, db)
beforeFKs := ticket13ReadArticleSources(t, db)
err := applyTicket13Err(db)
if err == nil {
t.Fatal("migration succeeded without exactly one target source")
}
if strings.Contains(err.Error(), "read migration 000015") {
t.Errorf("%s: atomic rollback cannot be exercised because migration 000015 is absent: %v", tc.name, err)
}
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
t.Errorf("failed migration changed schema\nbefore: %s\nafter: %s", beforeSchema, after)
}
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
t.Errorf("failed migration changed source data\nbefore: %#v\nafter: %#v", beforeRows, after)
}
if after := ticket13ReadArticleSources(t, db); !reflect.DeepEqual(after, beforeFKs) {
t.Errorf("failed migration changed article/source FK rows\nbefore: %#v\nafter: %#v", beforeFKs, after)
}
})
}
}
type ticket13SourceRow struct {
id, name, typ string
enabled bool
cap int
}
func ticket13HistoricalRows() []ticket13SourceRow {
return []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}, {"stocktwits-id", "StockTwits", "stocktwits", true, 31}, {"reuters-id", "Reuters", "reuters", true, 42}}
}
func ticket13SchemaSnapshot(t *testing.T, db *sql.DB) string {
t.Helper()
parts := []string{}
for _, q := range []string{`SELECT column_name||':'||data_type||':'||is_nullable||':'||COALESCE(column_default,'') FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='sources' ORDER BY ordinal_position`, `SELECT conname||':'||pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass ORDER BY conname`, `SELECT indexname||':'||indexdef FROM pg_indexes WHERE schemaname=current_schema() AND tablename='sources' ORDER BY indexname`} {
rows, err := db.Query(q)
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
rows.Close()
t.Fatal(err)
}
parts = append(parts, value)
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatal(err)
}
rows.Close()
}
return strings.Join(parts, "\n")
}
func ticket13ReadSources(t *testing.T, db *sql.DB) []ticket13SourceRow {
t.Helper()
rows, err := db.Query(`SELECT id,name,type,enabled,article_limit FROM sources ORDER BY id`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
result := []ticket13SourceRow{}
for rows.Next() {
var row ticket13SourceRow
if err := rows.Scan(&row.id, &row.name, &row.typ, &row.enabled, &row.cap); err != nil {
t.Fatal(err)
}
result = append(result, row)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return result
}
func ticket13ReadArticleSources(t *testing.T, db *sql.DB) []string {
t.Helper()
rows, err := db.Query(`SELECT id||':'||source_id FROM articles ORDER BY id`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
result := []string{}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
t.Fatal(err)
}
result = append(result, value)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return result
}
func ticket13Database(t *testing.T) (*sql.DB, func()) {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
}
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
}
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket13_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)
}
for _, q := range []string{`CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT NOT NULL,type TEXT NOT NULL,enabled BOOLEAN NOT NULL,article_limit INTEGER NOT NULL DEFAULT 20)`, `CREATE TABLE articles(id TEXT PRIMARY KEY,source_id TEXT NOT NULL REFERENCES sources(id),title TEXT NOT NULL,url TEXT NOT NULL UNIQUE)`} {
if _, err = db.Exec(q); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
t.Fatal(err)
}
}
return db, func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() }
}
func applyTicket13(t *testing.T, db *sql.DB) {
t.Helper()
if err := applyTicket13Err(db); err != nil {
t.Fatalf("apply source allowlist migration: %v", err)
}
}
func applyTicket13Err(db *sql.DB) error {
up, err := os.ReadFile("000015_source_allowlist.up.sql")
if err != nil {
return fmt.Errorf("read migration 000015: %w", err)
}
tx, err := db.Begin()
if err != nil {
return err
}
if _, err = tx.Exec(string(up)); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}