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:
@ -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
|
||||
|
||||
55
backend/internal/api/handlers/indices.go
Normal file
55
backend/internal/api/handlers/indices.go
Normal file
@ -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)
|
||||
}
|
||||
82
backend/internal/api/index_search_http_test.go
Normal file
82
backend/internal/api/index_search_http_test.go
Normal file
@ -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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
80
backend/internal/api/index_search_ticket3_test.go
Normal file
80
backend/internal/api/index_search_ticket3_test.go
Normal file
@ -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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -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)
|
||||
|
||||
Reference in New Issue
Block a user