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 <noreply@anthropic.com>
This commit is contained in:
185
backend/internal/indices/openfigi/openfigi.go
Normal file
185
backend/internal/indices/openfigi/openfigi.go
Normal file
@ -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
|
||||
}
|
||||
131
backend/internal/indices/openfigi/openfigi_ticket3_test.go
Normal file
131
backend/internal/indices/openfigi/openfigi_ticket3_test.go
Normal file
@ -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)
|
||||
}
|
||||
}
|
||||
107
backend/internal/indices/openfigi/safety_test.go
Normal file
107
backend/internal/indices/openfigi/safety_test.go
Normal file
@ -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")
|
||||
}
|
||||
}
|
||||
25
backend/internal/indices/search.go
Normal file
25
backend/internal/indices/search.go
Normal file
@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user