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:
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user