feat(watchlist): add company identity catalog

Embed a pinned FinanceDatabase equity snapshot, add authenticated company search and identity-based follows, preserve legacy assets, and map selected Yahoo symbols for collection.

Refs #19

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:08:22 +01:00
parent 1123360914
commit d65222169a
50 changed files with 49897 additions and 193 deletions

View File

@ -0,0 +1,82 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
)
func TestTicket19CompanySearchIsAuthenticatedBoundedAndReturnsSafeCompanyDTO(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
const secret = "ticket-19-company-search-test-secret"
const userID = "00000000-0000-0000-0000-000000000019"
h := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
router := SetupRouter(h, secret)
call := func(token, path string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodGet, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
unauthenticated := call("", "/api/companies/search?q=BYD&limit=2")
if unauthenticated.Code != http.StatusUnauthorized {
t.Errorf("anonymous company search status=%d, want 401 (body=%s)", unauthenticated.Code, unauthenticated.Body.String())
}
token, err := auth.GenerateToken(userID, "ticket19@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
valid := call(token, "/api/companies/search?q=BYD&limit=2")
if valid.Code != http.StatusOK {
t.Errorf("authenticated company search status=%d, want 200 (body=%s)", valid.Code, valid.Body.String())
} else {
var envelope struct {
Data []map[string]json.RawMessage `json:"data"`
}
if err := json.Unmarshal(valid.Body.Bytes(), &envelope); err != nil {
t.Fatalf("decode company results: %v", err)
}
if len(envelope.Data) == 0 {
t.Fatal("company search returned no local results for BYD")
}
for i, result := range envelope.Data {
var name, companyID string
if err := json.Unmarshal(result["name"], &name); err != nil || strings.TrimSpace(name) == "" {
t.Errorf("result %d lacks display name: %s", i, valid.Body.String())
}
if err := json.Unmarshal(result["company_id"], &companyID); err != nil || strings.TrimSpace(companyID) == "" {
t.Errorf("result %d lacks resolved company_id: %s", i, valid.Body.String())
}
if len(result["exchange"]) == 0 && len(result["country"]) == 0 {
t.Errorf("result %d lacks a company disambiguator: %s", i, valid.Body.String())
}
}
for _, privateKey := range []string{`"symbol":`, `"ticker":`, `"figi":`, `"composite_figi":`} {
if strings.Contains(valid.Body.String(), privateKey) {
t.Errorf("search DTO exposes private identity field %s: %s", privateKey, valid.Body.String())
}
}
}
maxValidLimit := call(token, "/api/companies/search?q=BYD&limit=20")
if maxValidLimit.Code != http.StatusOK {
t.Errorf("company search limit=20 status=%d, want 200 (body=%s)", maxValidLimit.Code, maxValidLimit.Body.String())
}
invalidLimit := call(token, "/api/companies/search?q=BYD&limit=21")
if invalidLimit.Code != http.StatusBadRequest {
t.Errorf("company search limit=21 status=%d, want 400 (body=%s)", invalidLimit.Code, invalidLimit.Body.String())
}
}

View File

@ -0,0 +1,59 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/httputil"
"net/http"
"strconv"
"strings"
"unicode/utf8"
)
type CompanyCatalog = companycatalog.CompanyCatalog
func (h *Handler) SetCompanyCatalog(c CompanyCatalog) { h.companyCatalog = c }
type companyDTO struct {
CompanyID string `json:"company_id"`
Name string `json:"name"`
Exchange string `json:"exchange"`
Country string `json:"country"`
MIC string `json:"mic"`
}
func (h *Handler) SearchCompanies(c *gin.Context) {
query := strings.TrimSpace(c.Query("q"))
limit := 10
params := c.Request.URL.Query()
if values, ok := params["limit"]; ok {
if len(values) != 1 {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
v, err := strconv.Atoi(values[0])
if err != nil {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
limit = v
}
if len(params["q"]) != 1 || !utf8.ValidString(query) || utf8.RuneCountInString(query) < 1 || utf8.RuneCountInString(query) > 100 || limit < 1 || limit > 20 {
c.JSON(400, gin.H{"error": "invalid search parameters"})
return
}
if h.companyCatalog == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "company catalog unavailable"})
return
}
companies, err := h.companyCatalog.SearchCompanies(query, limit)
if err != nil {
c.JSON(503, gin.H{"error": "company catalog unavailable"})
return
}
results := make([]companyDTO, 0, len(companies))
for _, company := range companies {
results = append(results, companyDTO{company.CompanyID, company.Name, company.Exchange, company.Country, company.MIC})
}
httputil.OK(c, results)
}

View File

@ -0,0 +1,164 @@
package handlers
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
const (
ticket19OwnerA = "00000000-0000-0000-0000-000000000191"
ticket19OwnerB = "00000000-0000-0000-0000-000000000192"
ticket19BaiduCompany = "isin:KYG070341048"
ticket19NVDACompany = "figi:BBG000BBJQV0"
ticket19SpoofFIGI = "BBG-CLIENT-SPOOF"
)
// ticket19CompanyCatalogFake models the injected, local catalog. It supplies
// canonical domain records; the HTTP DTO remains outside this test contract.
type ticket19CompanyCatalogFake struct {
companies map[string]companycatalog.Company
}
func (f ticket19CompanyCatalogFake) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
result := make([]companycatalog.Company, 0, limit)
for _, company := range f.companies {
if query != "" && containsFold(company.Name, query) {
result = append(result, company)
}
}
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func (f ticket19CompanyCatalogFake) ResolveCompany(companyID string) (companycatalog.Company, error) {
company, ok := f.companies[companyID]
if !ok {
return companycatalog.Company{}, fmt.Errorf("unknown company id")
}
return company, nil
}
func TestTicket19FollowCompanyResolvesOpaqueIdentityIdempotentlyPerOwnerPostgres(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err := db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
catalog := ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{
ticket19BaiduCompany: {
CompanyID: ticket19BaiduCompany, ISIN: "KYG070341048", Name: "Baidu, Inc.",
YahooSymbol: "9888.HK", FIGI: "BBG00ZMFX1S5", Exchange: "Hong Kong Stock Exchange", Country: "China",
},
ticket19NVDACompany: {
CompanyID: ticket19NVDACompany, Name: "NVIDIA Corporation",
YahooSymbol: "NVDA", FIGI: "BBG000BBJQV0", Exchange: "Nasdaq", Country: "United States",
},
}}
const secret = "ticket-19-company-follow-test-secret"
tokenA, err := auth.GenerateToken(ticket19OwnerA, "owner-a@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
tokenB, err := auth.GenerateToken(ticket19OwnerB, "owner-b@example.test", "user", secret)
if err != nil {
t.Fatal(err)
}
h := New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
h.SetCompanyCatalog(catalog)
router := gin.New()
authed := router.Group("/api")
authed.Use(auth.Middleware(secret))
authed.POST("/me/assets", h.AddMyAsset)
post := func(token, companyID, symbol, name, figi string) *httptest.ResponseRecorder {
t.Helper()
requestBody := map[string]string{"company_id": companyID}
// The client may send old or hostile values; the injected catalog wins.
if symbol != "" {
requestBody["symbol"] = symbol
}
if name != "" {
requestBody["name"] = name
}
if figi != "" {
requestBody["figi"] = figi
}
payload, err := json.Marshal(requestBody)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/me/assets", bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
first := post(tokenA, ticket19BaiduCompany, "CLIENT-SPOOF-A", "Client supplied name A", ticket19SpoofFIGI)
if first.Code != http.StatusCreated {
t.Fatalf("follow company status=%d body=%s, want 201", first.Code, first.Body.String())
}
duplicate := post(tokenA, ticket19BaiduCompany, "", "", "")
if duplicate.Code != http.StatusCreated {
t.Fatalf("repeat follow by company identity status=%d body=%s, want idempotent success", duplicate.Code, duplicate.Body.String())
}
otherOwner := post(tokenB, ticket19BaiduCompany, "CLIENT-SPOOF-C", "Client supplied name C", "BBG-CLIENT-SPOOF-3")
if otherOwner.Code != http.StatusCreated {
t.Fatalf("other owner's same-company follow status=%d body=%s", otherOwner.Code, otherOwner.Body.String())
}
fallback := post(tokenB, ticket19NVDACompany, "", "", "")
if fallback.Code != http.StatusCreated {
t.Fatalf("FIGI-fallback company follow status=%d body=%s", fallback.Code, fallback.Body.String())
}
for _, tc := range []struct{ owner, companyID string }{
{ticket19OwnerA, ticket19BaiduCompany},
{ticket19OwnerB, ticket19BaiduCompany},
{ticket19OwnerB, ticket19NVDACompany},
} {
var count int
if err := db.QueryRow(`SELECT COUNT(*) FROM user_assets WHERE user_id=$1 AND company_id=$2`, tc.owner, tc.companyID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Errorf("owner %s company %s rows=%d; want one", tc.owner, tc.companyID, count)
}
}
var userID, companyID, symbol, name string
var figi sql.NullString
err = db.QueryRow(`SELECT user_id::text,company_id,symbol,name,figi FROM user_assets WHERE company_id=$1 AND user_id=$2`, ticket19BaiduCompany, ticket19OwnerA).Scan(&userID, &companyID, &symbol, &name, &figi)
if err != nil {
t.Fatalf("read resolved Baidu asset: %v", err)
}
if userID != ticket19OwnerA || companyID != ticket19BaiduCompany || symbol != "9888.HK" || name != "Baidu, Inc." || !figi.Valid || figi.String != "BBG00ZMFX1S5" {
t.Errorf("persisted identity did not come from CompanyCatalog: owner=%s id=%q symbol=%q name=%q figi=%v", userID, companyID, symbol, name, figi)
}
if bytes.Contains(first.Body.Bytes(), []byte("Client supplied")) || bytes.Contains(first.Body.Bytes(), []byte("CLIENT-SPOOF")) || bytes.Contains(first.Body.Bytes(), []byte(ticket19SpoofFIGI)) {
t.Errorf("POST response leaked client-controlled identity: %s", first.Body.String())
}
}
func containsFold(value, query string) bool {
return len(query) == 0 || strings.Contains(strings.ToLower(value), strings.ToLower(query))
}

View File

@ -0,0 +1,98 @@
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
"net/http/httptest"
"os"
"strings"
"testing"
)
func TestCompanyRepositoryPreservesLegacyAndReturnsHintsPostgres(t *testing.T) {
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
repo := models.NewRepository(db)
figi := "BBG00ZMFX1S5"
legacy, err := repo.UpsertUserAsset(ticket4OwnerA, "LEGACY INDEX", "legacy retained", &figi)
if err != nil {
t.Fatal(err)
}
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK", FIGI: figi, Country: "China", Exchange: "HKG"}
first, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
if err != nil {
t.Fatalf("company upsert: %v", err)
}
again, err := repo.UpsertCompanyAsset(ticket4OwnerA, company)
if err != nil || again.ID != first.ID {
t.Fatalf("non-idempotent: %v", err)
}
other, err := repo.UpsertCompanyAsset(ticket4OwnerB, company)
if err != nil {
t.Fatal(err)
}
assets, err := repo.GetUserAssets(ticket4OwnerA)
if err != nil || len(assets) != 2 {
t.Fatalf("assets=%+v err=%v", assets, err)
}
for _, a := range assets {
if a.ID == legacy.ID && (a.Name != "legacy retained" || a.Symbol != "LEGACY INDEX" || a.CompanyID != nil || a.YahooSymbol != nil) {
t.Fatal("legacy row changed")
}
if a.ID == first.ID && (a.YahooSymbol == nil || *a.YahooSymbol != "9888.HK" || a.CompanyID == nil || *a.CompanyID != company.CompanyID) {
t.Fatal("lost company hints")
}
}
if err := repo.RemoveUserAssetByID(ticket4OwnerA, other.ID); err != nil {
t.Fatal(err)
}
theirs, err := repo.GetUserAssets(ticket4OwnerB)
if err != nil || len(theirs) != 1 {
t.Fatal("foreign delete changed data")
}
}
func TestCompanyFollowIgnoresEvenMalformedSpoofFieldsPostgres(t *testing.T) {
db := ticket4AssetDB(t)
migration, err := os.ReadFile("../../database/migrations/000017_company_catalog.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(migration)); err != nil {
t.Fatal(err)
}
repo := models.NewRepository(db)
h := New(repo, &config.Config{}, nil, nil, nil, nil)
company := companycatalog.Company{CompanyID: "isin:KYG070341048", Name: "Baidu, Inc.", YahooSymbol: "9888.HK"}
h.SetCompanyCatalog(ticket19CompanyCatalogFake{companies: map[string]companycatalog.Company{company.CompanyID: company}})
router := gin.New()
router.Use(func(c *gin.Context) { c.Set("userID", ticket4OwnerA) })
router.POST("/assets", h.AddMyAsset)
for _, tc := range []struct {
body string
status int
}{
{`{"company_id":"isin:KYG070341048","name":{"private":"spoof"},"symbol":["SSAAPL INDEX"],"figi":123,"user_id":"foreign"}`, 201},
{`{"company_id":"isin:unknown","symbol":"CLIENT-SPOOF"}`, 400},
} {
req := httptest.NewRequest("POST", "/assets", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
if response.Code != tc.status {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
}
assets, err := repo.GetUserAssets(ticket4OwnerA)
if err != nil || len(assets) != 1 || assets[0].Name != company.Name {
t.Fatalf("assets=%+v err=%v", assets, err)
}
}

View File

@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/companycatalog"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/generation"
@ -14,6 +15,7 @@ import (
)
type Handler struct {
companyCatalog CompanyCatalog
indexSearcher indices.IndexSearcher
generationUseCase generation.UseCase
repo *models.Repository
@ -33,14 +35,19 @@ func New(
pipeline *ai.Pipeline,
sched *scheduler.Scheduler,
) *Handler {
var catalog CompanyCatalog
if embedded, err := companycatalog.Default(); err == nil {
catalog = embedded
}
return &Handler{
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
companyCatalog: catalog,
repo: repo,
cfg: cfg,
enc: enc,
registry: registry,
pipeline: pipeline,
scheduler: sched,
reportManager: ai.NewReportManager(),
}
}

View File

@ -3,6 +3,7 @@ package handlers
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/tradarr/backend/internal/httputil"
"github.com/tradarr/backend/internal/models"
"net/http"
@ -33,14 +34,39 @@ func (h *Handler) GetMyAssets(c *gin.Context) {
type addAssetRequest struct {
FIGI *string `json:"figi"`
Symbol string `json:"symbol" binding:"required"`
Symbol string `json:"symbol"`
Name string `json:"name"`
}
func (h *Handler) AddMyAsset(c *gin.Context) {
userID := c.GetString("userID")
var identity struct {
CompanyID *string `json:"company_id"`
}
if err := c.ShouldBindBodyWith(&identity, binding.JSON); err != nil {
httputil.BadRequest(c, err)
return
}
if identity.CompanyID != nil {
if h.companyCatalog == nil {
c.JSON(503, gin.H{"error": "company catalog unavailable"})
return
}
company, err := h.companyCatalog.ResolveCompany(strings.TrimSpace(*identity.CompanyID))
if err != nil {
c.JSON(400, gin.H{"error": "unknown company_id"})
return
}
asset, err := h.repo.UpsertCompanyAsset(userID, company)
if err != nil {
c.JSON(500, gin.H{"error": "asset operation failed"})
return
}
httputil.Created(c, asset)
return
}
var req addAssetRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
httputil.BadRequest(c, err)
return
}

View File

@ -34,6 +34,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
authed.Use(auth.Middleware(jwtSecret))
authed.GET("/indices/search", h.SearchIndices)
authed.GET("/companies/search", h.SearchCompanies)
authed.GET("/me", h.GetMe)
authed.GET("/me/preferences", h.GetMyPreferences)
authed.GET("/me/summary-models", h.ListMySummaryModels)