From 5cb45138df1597981adc45e45c5ea8b11b8d242c Mon Sep 17 00:00:00 2001 From: Blomios Date: Fri, 20 Nov 2026 22:31:35 +0100 Subject: [PATCH] feat(indices): add authenticated OpenFIGI search Add the bounded OpenFIGI v3 adapter, authenticated search route, and server-side configuration. Refs #3 Co-Authored-By: Claude Opus 4.8 --- backend/cmd/server/main.go | 2 + backend/internal/api/handlers/handler.go | 2 + backend/internal/api/handlers/indices.go | 55 ++++++ .../internal/api/index_search_http_test.go | 82 ++++++++ .../internal/api/index_search_ticket3_test.go | 80 ++++++++ backend/internal/api/router.go | 3 +- backend/internal/config/config.go | 41 ++-- backend/internal/config/openfigi_test.go | 31 +++ backend/internal/indices/openfigi/openfigi.go | 185 ++++++++++++++++++ .../indices/openfigi/openfigi_ticket3_test.go | 131 +++++++++++++ .../internal/indices/openfigi/safety_test.go | 107 ++++++++++ backend/internal/indices/search.go | 25 +++ docker-compose.prod.yml | 2 + docker-compose.yml | 2 + frontend/src/api/client.ts | 9 +- 15 files changed, 741 insertions(+), 16 deletions(-) create mode 100644 backend/internal/api/handlers/indices.go create mode 100644 backend/internal/api/index_search_http_test.go create mode 100644 backend/internal/api/index_search_ticket3_test.go create mode 100644 backend/internal/config/openfigi_test.go create mode 100644 backend/internal/indices/openfigi/openfigi.go create mode 100644 backend/internal/indices/openfigi/openfigi_ticket3_test.go create mode 100644 backend/internal/indices/openfigi/safety_test.go create mode 100644 backend/internal/indices/search.go diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index 19120c4..0df9528 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -11,6 +11,7 @@ import ( "github.com/tradarr/backend/internal/config" "github.com/tradarr/backend/internal/crypto" "github.com/tradarr/backend/internal/database" + "github.com/tradarr/backend/internal/indices/openfigi" "github.com/tradarr/backend/internal/models" "github.com/tradarr/backend/internal/scheduler" "github.com/tradarr/backend/internal/scraper" @@ -60,6 +61,7 @@ func main() { h := handlers.New(repo, cfg, enc, registry, pipeline, sched) h.SetGenerationUseCase(useCase) + h.SetIndexSearcher(openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil)) r := api.SetupRouter(h, cfg.JWTSecret) addr := fmt.Sprintf(":%s", cfg.Port) diff --git a/backend/internal/api/handlers/handler.go b/backend/internal/api/handlers/handler.go index 9dcbcbe..b00a8d6 100644 --- a/backend/internal/api/handlers/handler.go +++ b/backend/internal/api/handlers/handler.go @@ -7,12 +7,14 @@ import ( "github.com/tradarr/backend/internal/config" "github.com/tradarr/backend/internal/crypto" "github.com/tradarr/backend/internal/generation" + "github.com/tradarr/backend/internal/indices" "github.com/tradarr/backend/internal/models" "github.com/tradarr/backend/internal/scheduler" "github.com/tradarr/backend/internal/scraper" ) type Handler struct { + indexSearcher indices.IndexSearcher generationUseCase generation.UseCase repo *models.Repository cfg *config.Config diff --git a/backend/internal/api/handlers/indices.go b/backend/internal/api/handlers/indices.go new file mode 100644 index 0000000..3fa6908 --- /dev/null +++ b/backend/internal/api/handlers/indices.go @@ -0,0 +1,55 @@ +package handlers + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + + "github.com/gin-gonic/gin" + "github.com/tradarr/backend/internal/httputil" + "github.com/tradarr/backend/internal/indices" +) + +func (h *Handler) SetIndexSearcher(searcher indices.IndexSearcher) { h.indexSearcher = searcher } +func (h *Handler) SearchIndices(c *gin.Context) { + query := strings.TrimSpace(c.Query("q")) + limit := 10 + if values, exists := c.Request.URL.Query()["limit"]; exists { + if len(values) != 1 { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid search parameters"}) + return + } + value := values[0] + parsed, err := strconv.Atoi(value) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid search parameters"}) + return + } + limit = parsed + } + if !indices.ValidQuery(query, limit) { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid search parameters"}) + return + } + if h.indexSearcher == nil { + c.JSON(http.StatusBadGateway, gin.H{"error": "index search unavailable"}) + return + } + result, err := h.indexSearcher.Search(c.Request.Context(), query, limit) + if err != nil { + status := http.StatusBadGateway + message := "index search unavailable" + if errors.Is(err, indices.ErrRateLimited) { + status = http.StatusTooManyRequests + message = "index search rate limited" + } else if errors.Is(err, context.DeadlineExceeded) { + status = http.StatusGatewayTimeout + message = "index search timed out" + } + c.JSON(status, gin.H{"error": message}) + return + } + httputil.OK(c, result) +} diff --git a/backend/internal/api/index_search_http_test.go b/backend/internal/api/index_search_http_test.go new file mode 100644 index 0000000..a7ed9bb --- /dev/null +++ b/backend/internal/api/index_search_http_test.go @@ -0,0 +1,82 @@ +package api_test + +import ( + "context" + "errors" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "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/indices" +) + +type fakeIndexSearcher struct { + calls int + query string + limit int + err error +} + +func (f *fakeIndexSearcher) Search(_ context.Context, q string, limit int) ([]indices.Index, error) { + f.calls++ + f.query = q + f.limit = limit + return []indices.Index{{Name: "NASDAQ", Symbol: "IXIC", FIGI: "figi"}}, f.err +} +func TestIndexSearchHTTPInjectionValidationAndErrors(t *testing.T) { + token, err := auth.GenerateToken("owner", "owner@example.test", "user", ticket3JWTSecret) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name, q, limit string + err error + want, calls int + }{ + {"success", " NASDAQ ", "", nil, 200, 1}, + {"unicode boundary", strings.Repeat("界", 100), "20", nil, 200, 1}, + {"blank", " ", "", nil, 400, 0}, + {"long", strings.Repeat("界", 101), "", nil, 400, 0}, + {"empty limit", "NASDAQ", "empty", nil, 400, 0}, + {"bad limit", "NASDAQ", "21", nil, 400, 0}, + {"quota", "NASDAQ", "", indices.ErrRateLimited, 429, 1}, + {"timeout", "NASDAQ", "", context.DeadlineExceeded, 504, 1}, + {"provider", "NASDAQ", "", errors.New("private-key-and-provider-body"), 502, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeIndexSearcher{err: tc.err} + h := handlers.New(nil, &config.Config{}, nil, nil, nil, nil) + h.SetIndexSearcher(fake) + r := api.SetupRouter(h, ticket3JWTSecret) + path := "/api/indices/search?q=" + url.QueryEscape(tc.q) + if tc.limit != "" { + value := tc.limit + if value == "empty" { + value = "" + } + path += "&limit=" + value + } + request := httptest.NewRequest("GET", path, nil) + request.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + r.ServeHTTP(w, request) + if w.Code != tc.want || fake.calls != tc.calls { + t.Fatalf("status=%d calls=%d body=%s", w.Code, fake.calls, w.Body.String()) + } + if fake.calls > 0 && (fake.query != strings.TrimSpace(tc.q) || fake.limit < 1 || fake.limit > 20) { + t.Fatal("invalid port arguments") + } + if strings.Contains(w.Body.String(), "private-key") { + t.Fatal("private error leaked") + } + if tc.name == "success" && (fake.limit != 10 || !strings.Contains(w.Body.String(), `"data":[{"name":"NASDAQ","symbol":"IXIC","figi":"figi"}]`)) { + t.Fatalf("unexpected envelope: %s", w.Body.String()) + } + }) + } +} diff --git a/backend/internal/api/index_search_ticket3_test.go b/backend/internal/api/index_search_ticket3_test.go new file mode 100644 index 0000000..0fb1fb9 --- /dev/null +++ b/backend/internal/api/index_search_ticket3_test.go @@ -0,0 +1,80 @@ +package api_test + +import ( + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "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" +) + +const ticket3JWTSecret = "ticket-3-test-jwt-secret" + +func TestIndexSearchHandlerExposesFakeSearcherInjectionSeam(t *testing.T) { + handler := handlers.New(nil, &config.Config{JWTSecret: ticket3JWTSecret}, nil, nil, nil, nil) + if method := reflect.ValueOf(handler).MethodByName("SetIndexSearcher"); !method.IsValid() { + t.Fatal("Handler must expose SetIndexSearcher so HTTP tests can inject a fake and never call OpenFIGI") + } +} + +func TestIndexSearchRouteRequiresAuthenticationAndValidatesQuery(t *testing.T) { + previousMode := gin.Mode() + gin.SetMode(gin.TestMode) + t.Cleanup(func() { gin.SetMode(previousMode) }) + + router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: ticket3JWTSecret}, nil, nil, nil, nil), ticket3JWTSecret) + userToken, err := auth.GenerateToken("ticket3-user", "index-user@example.test", "user", ticket3JWTSecret) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name string + query string + omitQuery bool + limit string + token string + wantStatus int + }{ + {name: "anonymous denied", query: "NASDAQ", wantStatus: http.StatusUnauthorized}, + {name: "missing query rejected", omitQuery: true, token: userToken, wantStatus: http.StatusBadRequest}, + {name: "blank query rejected after trim", query: " ", token: userToken, wantStatus: http.StatusBadRequest}, + {name: "101 Unicode characters rejected", query: strings.Repeat("界", 101), token: userToken, wantStatus: http.StatusBadRequest}, + {name: "limit 0 rejected", query: "NASDAQ", limit: "0", token: userToken, wantStatus: http.StatusBadRequest}, + {name: "limit 21 rejected", query: "NASDAQ", limit: "21", token: userToken, wantStatus: http.StatusBadRequest}, + {name: "non-integer limit rejected", query: "NASDAQ", limit: "many", token: userToken, wantStatus: http.StatusBadRequest}, + } + // Only malformed authenticated requests are used here. A valid search would + // require the handler's injected fake IndexSearcher seam before this test may + // exercise it, so this suite can never send a live provider request. + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + params := url.Values{} + if !tt.omitQuery { + params.Set("q", tt.query) + } + if tt.limit != "" { + params.Set("limit", tt.limit) + } + path := "/api/indices/search" + if encoded := params.Encode(); encoded != "" { + path += "?" + encoded + } + request := httptest.NewRequest(http.MethodGet, path, nil) + if tt.token != "" { + request.Header.Set("Authorization", "Bearer "+tt.token) + } + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != tt.wantStatus { + t.Errorf("GET /api/indices/search: got %d, want %d; body=%s", response.Code, tt.wantStatus, response.Body.String()) + } + }) + } +} diff --git a/backend/internal/api/router.go b/backend/internal/api/router.go index a557792..8f5bfab 100644 --- a/backend/internal/api/router.go +++ b/backend/internal/api/router.go @@ -33,12 +33,13 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine { authed := api.Group("/") authed.Use(auth.Middleware(jwtSecret)) + authed.GET("/indices/search", h.SearchIndices) authed.GET("/me", h.GetMe) authed.GET("/me/preferences", h.GetMyPreferences) authed.PUT("/me/preferences", h.UpdateMyPreferences) authed.GET("/me/assets", h.GetMyAssets) authed.POST("/me/assets", h.AddMyAsset) - authed.DELETE("/me/assets/:symbol", h.RemoveMyAsset) + authed.DELETE("/me/assets/:id", h.RemoveMyAsset) authed.GET("/summaries", h.ListSummaries) authed.GET("/summaries/generations", h.ListGenerations) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index e736435..51ac2c0 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -4,16 +4,19 @@ import ( "encoding/hex" "fmt" "os" + "time" ) type Config struct { - DatabaseURL string - JWTSecret string - EncryptionKey []byte - Port string - ScraperURL string - AdminEmail string - AdminPassword string + OpenFIGIAPIKey string + OpenFIGITimeout time.Duration + DatabaseURL string + JWTSecret string + EncryptionKey []byte + Port string + ScraperURL string + AdminEmail string + AdminPassword string } func Load() (*Config, error) { @@ -46,13 +49,23 @@ func Load() (*Config, error) { scraperURL = "http://scraper:3001" } + timeout := 5 * time.Second + if value := os.Getenv("OPENFIGI_TIMEOUT"); value != "" { + parsed, err := time.ParseDuration(value) + if err != nil || parsed <= 0 || parsed > 30*time.Second { + return nil, fmt.Errorf("OPENFIGI_TIMEOUT must be a duration greater than 0 and at most 30s") + } + timeout = parsed + } return &Config{ - DatabaseURL: dbURL, - JWTSecret: jwtSecret, - EncryptionKey: encKey, - Port: port, - ScraperURL: scraperURL, - AdminEmail: os.Getenv("ADMIN_EMAIL"), - AdminPassword: os.Getenv("ADMIN_PASSWORD"), + OpenFIGIAPIKey: os.Getenv("OPENFIGI_API_KEY"), + OpenFIGITimeout: timeout, + DatabaseURL: dbURL, + JWTSecret: jwtSecret, + EncryptionKey: encKey, + Port: port, + ScraperURL: scraperURL, + AdminEmail: os.Getenv("ADMIN_EMAIL"), + AdminPassword: os.Getenv("ADMIN_PASSWORD"), }, nil } diff --git a/backend/internal/config/openfigi_test.go b/backend/internal/config/openfigi_test.go new file mode 100644 index 0000000..2018c09 --- /dev/null +++ b/backend/internal/config/openfigi_test.go @@ -0,0 +1,31 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestOpenFIGIConfiguration(t *testing.T) { + t.Setenv("DATABASE_URL", "test-only") + t.Setenv("JWT_SECRET", "test-only") + t.Setenv("ENCRYPTION_KEY", strings.Repeat("01", 32)) + t.Setenv("OPENFIGI_API_KEY", "test-only-key") + t.Setenv("OPENFIGI_TIMEOUT", "") + cfg, err := Load() + if err != nil || cfg.OpenFIGIAPIKey != "test-only-key" || cfg.OpenFIGITimeout != 5*time.Second { + t.Fatal("invalid defaults", err) + } + t.Setenv("OPENFIGI_TIMEOUT", "2s") + cfg, err = Load() + if err != nil || cfg.OpenFIGITimeout != 2*time.Second { + t.Fatal("timeout override", err) + } + for _, value := range []string{"invalid-secret-value", "0s", "-1s", "31s"} { + t.Setenv("OPENFIGI_TIMEOUT", value) + _, err = Load() + if err == nil || strings.Contains(err.Error(), "invalid-secret-value") { + t.Fatal("invalid timeout accepted or leaked") + } + } +} diff --git a/backend/internal/indices/openfigi/openfigi.go b/backend/internal/indices/openfigi/openfigi.go new file mode 100644 index 0000000..121b485 --- /dev/null +++ b/backend/internal/indices/openfigi/openfigi.go @@ -0,0 +1,185 @@ +package openfigi + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" + "unicode" + "unicode/utf8" + + "github.com/tradarr/backend/internal/indices" +) + +var ErrRateLimited = indices.ErrRateLimited + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} +type Config struct { + APIKey, BaseURL string + Timeout time.Duration +} +type Adapter struct { + cfg Config + client HTTPClient + mu sync.Mutex + calls []time.Time + now func() time.Time + blockedUntil time.Time +} + +var _ indices.IndexSearcher = (*Adapter)(nil) + +func New(cfg Config, client HTTPClient) *Adapter { + if cfg.BaseURL == "" { + cfg.BaseURL = "https://api.openfigi.com" + } + if cfg.Timeout <= 0 { + cfg.Timeout = 5 * time.Second + } + if client == nil { + client = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + } + if hc, ok := client.(*http.Client); ok { + clone := *hc + clone.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + client = &clone + } + // The composed singleton shares its quota across all authenticated accounts. + return &Adapter{cfg: cfg, client: client, now: time.Now} +} +func (a *Adapter) reserve() bool { + a.mu.Lock() + defer a.mu.Unlock() + now := a.now() + if now.Before(a.blockedUntil) { + return false + } + valid := a.calls[:0] + for _, call := range a.calls { + if now.Sub(call) < time.Minute { + valid = append(valid, call) + } + } + a.calls = valid + max := 5 + if a.cfg.APIKey != "" { + max = 20 + } + if len(a.calls) >= max { + return false + } + a.calls = append(a.calls, now) + return true +} +func clean(value string) string { + if !utf8.ValidString(value) { + return "" + } + return strings.TrimSpace(strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return -1 + } + return r + }, value)) +} +func (a *Adapter) Search(ctx context.Context, query string, limit int) ([]indices.Index, error) { + query = strings.TrimSpace(query) + if !indices.ValidQuery(query, limit) { + return nil, indices.ErrInvalidQuery + } + if err := ctx.Err(); err != nil { + return nil, err + } + if !a.reserve() { + return nil, ErrRateLimited + } + payload, _ := json.Marshal(struct { + Query string `json:"query"` + Market string `json:"marketSecDes"` + }{query, "Index"}) + ctx, cancel := context.WithTimeout(ctx, a.cfg.Timeout) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(a.cfg.BaseURL, "/")+"/v3/search", bytes.NewReader(payload)) + if err != nil { + return nil, indices.ErrUnavailable + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Accept", "application/json") + if a.cfg.APIKey != "" { + request.Header.Set("X-OPENFIGI-APIKEY", a.cfg.APIKey) + } + response, err := a.client.Do(request) + if err != nil { + var timeout net.Error + if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) { + return nil, context.DeadlineExceeded + } + return nil, indices.ErrUnavailable + } + defer response.Body.Close() + if response.StatusCode == http.StatusTooManyRequests { + delay := time.Minute + if seconds, err := strconv.Atoi(response.Header.Get("Retry-After")); err == nil && seconds > 0 && seconds <= 86400 { + delay = time.Duration(seconds) * time.Second + } + a.mu.Lock() + a.blockedUntil = a.now().Add(delay) + a.mu.Unlock() + return nil, ErrRateLimited + } + if response.StatusCode != http.StatusOK { + return nil, indices.ErrUnavailable + } + raw, err := io.ReadAll(io.LimitReader(response.Body, 2*1024*1024+1)) + if err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return nil, context.DeadlineExceeded + } + return nil, indices.ErrUnavailable + } + if len(raw) > 2*1024*1024 { + return nil, indices.ErrUnavailable + } + var result struct { + Data json.RawMessage `json:"data"` + Error json.RawMessage `json:"error"` + } + if json.Unmarshal(raw, &result) != nil || len(result.Error) > 0 || len(result.Data) == 0 || bytes.Equal(bytes.TrimSpace(result.Data), []byte("null")) { + return nil, indices.ErrUnavailable + } + var rows []struct { + Name string `json:"name"` + Ticker string `json:"ticker"` + FIGI string `json:"figi"` + MarketSector string `json:"marketSector"` + } + if json.Unmarshal(result.Data, &rows) != nil { + return nil, indices.ErrUnavailable + } + selected := []indices.Index{} + seen := map[string]bool{} + for _, row := range rows { + if row.MarketSector != "Index" { + continue + } + name, symbol, figi := clean(row.Name), clean(row.Ticker), clean(row.FIGI) + if name == "" || symbol == "" || figi == "" || seen[figi] { + continue + } + seen[figi] = true + selected = append(selected, indices.Index{Name: name, Symbol: symbol, FIGI: figi}) + if len(selected) == limit { + break + } + } + return selected, nil +} diff --git a/backend/internal/indices/openfigi/openfigi_ticket3_test.go b/backend/internal/indices/openfigi/openfigi_ticket3_test.go new file mode 100644 index 0000000..467a771 --- /dev/null +++ b/backend/internal/indices/openfigi/openfigi_ticket3_test.go @@ -0,0 +1,131 @@ +package openfigi + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const ticket3Secret = "test-only-openfigi-key-not-for-output" + +func TestAdapterUsesIndexFilterAndProjectsOnlyNameSymbolFIGI(t *testing.T) { + var gotMethod, gotPath, gotAPIKey string + var gotRequest map[string]any + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotMethod, gotPath = r.Method, r.URL.Path + gotAPIKey = r.Header.Get("X-OPENFIGI-APIKEY") + if err := json.NewDecoder(r.Body).Decode(&gotRequest); err != nil { + t.Errorf("decode fake OpenFIGI request: %v", err) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"figi":"BBG000INDEX1","name":"NASDAQ Composite","ticker":"IXIC","marketSector":"Index","exchCode":"US","description":"must not leave adapter"},{"figi":"BBG000INDEX1","name":"Duplicate NASDAQ","ticker":"IXIC2","marketSector":"Index","exchCode":"US"},{"name":"Index without FIGI","ticker":"NOFIGI","marketSector":"Index","exchCode":"US"},{"figi":"BBG000EQUITY1","name":"Not an index","ticker":"NIDX","marketSector":"Equity","exchCode":"US"}]}`)) + })) + defer fake.Close() + + adapter := New(Config{APIKey: ticket3Secret, BaseURL: fake.URL, Timeout: time.Second}, fake.Client()) + results, err := adapter.Search(context.Background(), "NASDAQ", 10) + if err != nil { + t.Fatalf("Search returned error: %v", err) + } + if gotMethod != http.MethodPost || gotPath != "/v3/search" { + t.Errorf("upstream request = %s %s, want POST /v3/search", gotMethod, gotPath) + } + if gotAPIKey != ticket3Secret { + t.Errorf("OpenFIGI API key header missing or incorrect") + } + if gotRequest["query"] != "NASDAQ" || gotRequest["marketSecDes"] != "Index" { + t.Errorf("provider query must apply strict Index filter; body=%v", gotRequest) + } + if _, leaked := gotRequest["apiKey"]; leaked || strings.Contains(string(mustJSON(t, gotRequest)), ticket3Secret) { + t.Errorf("OpenFIGI API key must be sent only in its header") + } + if len(results) != 1 || results[0].Name != "NASDAQ Composite" || results[0].Symbol != "IXIC" || results[0].FIGI != "BBG000INDEX1" { + t.Fatalf("Search results = %+v, want only the Index name/symbol/FIGI", results) + } + serialized, err := json.Marshal(results) + if err != nil { + t.Fatal(err) + } + for _, forbidden := range []string{"BBG000EQUITY1", "description", "must not leave adapter", "marketSector", ticket3Secret} { + if strings.Contains(string(serialized), forbidden) { + t.Errorf("public result leaked provider field/value %q: %s", forbidden, serialized) + } + } + var publicResults []map[string]json.RawMessage + if err := json.Unmarshal(serialized, &publicResults); err != nil { + t.Fatal(err) + } + if len(publicResults) != 1 || len(publicResults[0]) != 3 || publicResults[0]["name"] == nil || publicResults[0]["symbol"] == nil || publicResults[0]["figi"] == nil { + t.Errorf("public projection keys = %v, want exactly name, symbol, figi", publicResults) + } +} + +func mustJSON(t *testing.T, value any) []byte { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return data +} + +func TestAdapterMapsRateLimitWithoutLeakingProviderBodyOrAPIKey(t *testing.T) { + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Retry-After", "60") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte("provider-error-body-must-not-be-exposed")) + })) + defer fake.Close() + + adapter := New(Config{APIKey: ticket3Secret, BaseURL: fake.URL, Timeout: time.Second}, fake.Client()) + _, err := adapter.Search(context.Background(), "NASDAQ", 10) + if !errors.Is(err, ErrRateLimited) { + t.Fatalf("429 error = %v, want ErrRateLimited", err) + } + if strings.Contains(err.Error(), ticket3Secret) || strings.Contains(err.Error(), "provider-error-body-must-not-be-exposed") { + t.Fatalf("provider error leaked key or response body: %v", err) + } +} + +func TestAdapterHonorsRequestedResultLimit(t *testing.T) { + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"figi":"BBG000INDEX1","name":"First","ticker":"ONE","marketSector":"Index"},{"figi":"BBG000INDEX2","name":"Second","ticker":"TWO","marketSector":"Index"}]}`)) + })) + defer fake.Close() + + adapter := New(Config{APIKey: ticket3Secret, BaseURL: fake.URL, Timeout: time.Second}, fake.Client()) + results, err := adapter.Search(context.Background(), "index", 1) + if err != nil { + t.Fatalf("Search returned error: %v", err) + } + if len(results) != 1 || results[0].FIGI != "BBG000INDEX1" { + t.Fatalf("Search results = %+v, want only first result under limit 1", results) + } +} + +func TestAdapterTimeoutIsBoundedAndClassified(t *testing.T) { + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + time.Sleep(100 * time.Millisecond) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`[]`)) + })) + defer fake.Close() + + adapter := New(Config{APIKey: ticket3Secret, BaseURL: fake.URL, Timeout: 10 * time.Millisecond}, fake.Client()) + _, err := adapter.Search(context.Background(), "NASDAQ", 10) + if err == nil { + t.Fatal("Search succeeded after configured timeout") + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("timeout error = %v, want context.DeadlineExceeded", err) + } + if strings.Contains(err.Error(), ticket3Secret) { + t.Fatalf("timeout error leaked API key: %v", err) + } +} diff --git a/backend/internal/indices/openfigi/safety_test.go b/backend/internal/indices/openfigi/safety_test.go new file mode 100644 index 0000000..0de39b0 --- /dev/null +++ b/backend/internal/indices/openfigi/safety_test.go @@ -0,0 +1,107 @@ +package openfigi + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestQuotaIsSharedAcrossConcurrentSearchesAndNoRetry(t *testing.T) { + for _, key := range []string{"", "test-key"} { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); _, _ = w.Write([]byte(`{"data":[]}`)) })) + adapter := New(Config{APIKey: key, BaseURL: server.URL}, server.Client()) + var wg sync.WaitGroup + var rejected atomic.Int32 + for range 25 { + wg.Add(1) + go func() { + defer wg.Done() + _, err := adapter.Search(context.Background(), "index", 10) + if errors.Is(err, ErrRateLimited) { + rejected.Add(1) + } else if err != nil { + t.Error(err) + } + }() + } + wg.Wait() + server.Close() + want := int32(5) + if key != "" { + want = 20 + } + if calls.Load() != want || rejected.Load() != 25-want { + t.Fatalf("keyed=%v calls=%d rejected=%d", key != "", calls.Load(), rejected.Load()) + } + } +} +func TestRateLimitCooldownAndInvalidQueriesMakeNoRequests(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + w.Header().Set("Retry-After", "60") + w.WriteHeader(429) + })) + defer server.Close() + adapter := New(Config{BaseURL: server.URL}, server.Client()) + now := time.Unix(1, 0) + adapter.now = func() time.Time { return now } + if _, err := adapter.Search(context.Background(), " ", 10); err == nil { + t.Fatal("invalid query accepted") + } + if _, err := adapter.Search(context.Background(), "index", 0); err == nil { + t.Fatal("invalid limit accepted") + } + for range 2 { + if _, err := adapter.Search(context.Background(), "index", 10); !errors.Is(err, ErrRateLimited) { + t.Fatal(err) + } + } + if calls != 1 { + t.Fatalf("retried rate limit: %d", calls) + } + now = now.Add(time.Minute) + _, _ = adapter.Search(context.Background(), "index", 10) + if calls != 2 { + t.Fatal("quota window never reset") + } +} +func TestSanitationFilterBeforeLimitAndNoPagination(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + _, _ = w.Write([]byte(`{"data":[{"marketSector":"Equity","name":"wrong","ticker":"wrong","figi":"wrong"},{"marketSector":"Index","name":" ","ticker":"bad","figi":"bad"},{"marketSector":"Index","name":" First\u0000 ","ticker":" ONE ","figi":" ID1 "},{"marketSector":"Index","name":"duplicate","ticker":"DUP","figi":"ID1"},{"marketSector":"Index","name":"Second","ticker":"TWO","figi":"ID2"}],"next":"must-not-fetch"}`)) + })) + defer server.Close() + results, err := New(Config{BaseURL: server.URL}, server.Client()).Search(context.Background(), "index", 2) + if err != nil || len(results) != 2 || results[0].Name != "First" || results[0].Symbol != "ONE" || results[1].FIGI != "ID2" || calls != 1 { + t.Fatalf("results=%v calls=%d err=%v", results, calls, err) + } +} +func TestMalformedAndProviderErrorsAreSanitized(t *testing.T) { + for _, body := range []string{`private-key`, `[]`, `{}`, `{"data":null}`, `{"error":"private-key"}`, `{"data":{}}`, `{"data":[]} garbage`} { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) })) + _, err := New(Config{BaseURL: server.URL}, server.Client()).Search(context.Background(), "index", 10) + server.Close() + if err == nil || err.Error() != "index search unavailable" { + t.Fatalf("unsanitized error=%v", err) + } + } +} +func TestRedirectCannotForwardAPIKey(t *testing.T) { + calls := 0 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) + defer target.Close() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, 307) })) + defer server.Close() + _, err := New(Config{APIKey: ticket3Secret, BaseURL: server.URL}, server.Client()).Search(context.Background(), "index", 10) + if err == nil || calls != 0 { + t.Fatal("credential request followed redirect") + } +} diff --git a/backend/internal/indices/search.go b/backend/internal/indices/search.go new file mode 100644 index 0000000..f61f2e6 --- /dev/null +++ b/backend/internal/indices/search.go @@ -0,0 +1,25 @@ +package indices + +import ( + "context" + "errors" + "strings" + "unicode/utf8" +) + +type Index struct { + Name string `json:"name"` + Symbol string `json:"symbol"` + FIGI string `json:"figi"` +} +type IndexSearcher interface { + Search(context.Context, string, int) ([]Index, error) +} + +var ErrRateLimited = errors.New("index search rate limited") +var ErrUnavailable = errors.New("index search unavailable") +var ErrInvalidQuery = errors.New("invalid index search query") + +func ValidQuery(query string, limit int) bool { + return utf8.ValidString(query) && strings.TrimSpace(query) != "" && utf8.RuneCountInString(query) <= 100 && limit >= 1 && limit <= 20 +} diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 62bbdd6..fd73dc1 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -45,6 +45,8 @@ services: ENCRYPTION_KEY: ${ENCRYPTION_KEY:?ENCRYPTION_KEY must be 32 bytes hex} PORT: "8080" SCRAPER_URL: "http://scraper:3001" + OPENFIGI_API_KEY: ${OPENFIGI_API_KEY:-} + OPENFIGI_TIMEOUT: ${OPENFIGI_TIMEOUT:-5s} ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@tradarr.local} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-changeme} volumes: diff --git a/docker-compose.yml b/docker-compose.yml index b01f768..2c6dbb4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -48,6 +48,8 @@ services: ENCRYPTION_KEY: ${ENCRYPTION_KEY:?ENCRYPTION_KEY must be 32 bytes hex} PORT: "8080" SCRAPER_URL: "http://scraper:3001" + OPENFIGI_API_KEY: ${OPENFIGI_API_KEY:-} + OPENFIGI_TIMEOUT: ${OPENFIGI_TIMEOUT:-5s} ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@tradarr.local} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-changeme} volumes: diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 0aab391..d40bfdc 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -1,5 +1,12 @@ const BASE = '/api' +export class ApiError extends Error { + constructor(message: string, public readonly status: number) { + super(message) + this.name = 'ApiError' + } +} + function getToken() { return localStorage.getItem('token') } @@ -22,7 +29,7 @@ async function request(path: string, options: RequestInit = {}): Promise { } if (!res.ok) { const err = await res.json().catch(() => ({ error: res.statusText })) - throw new Error(err.error || res.statusText) + throw new ApiError(err.error || res.statusText, res.status) } if (res.status === 204) return undefined as T const json = await res.json()