package ingestionbench import ( "bufio" "context" "encoding/json" "errors" "github.com/tradarr/backend/internal/scraper/sourcehttp" "io" "net/http" "net/netip" "net/url" "os" "os/exec" "strconv" "strings" "time" ) func ValidateMode(mode string, allowLive bool) error { if mode != "offline" && mode != "live" || mode == "live" && !allowLive || mode == "offline" && allowLive { return errors.New("invalid_bench_mode") } return nil } func StartOfflineScraper(ctx context.Context, script string) (string, func(), error) { child := exec.CommandContext(ctx, "node", script) child.Stderr = io.Discard child.Env = []string{"PATH=" + os.Getenv("PATH"), "NODE_NO_WARNINGS=1"} stdout, err := child.StdoutPipe() if err != nil { return "", nil, errors.New("fixture_service_unavailable") } if child.Start() != nil { return "", nil, errors.New("fixture_service_unavailable") } cleanup := func() { _ = child.Process.Kill(); _ = child.Wait() } ready := make(chan int, 1) go func() { scanner := bufio.NewScanner(io.LimitReader(stdout, 1024)) port := 0 if scanner.Scan() { var v struct { Port int `json:"port"` } if json.Unmarshal(scanner.Bytes(), &v) == nil { port = v.Port } } ready <- port }() select { case port := <-ready: if port > 0 && port < 65536 { return "http://127.0.0.1:" + strconv.Itoa(port), cleanup, nil } case <-time.After(10 * time.Second): case <-ctx.Done(): } cleanup() return "", nil, errors.New("fixture_service_unavailable") } const LiveScraperEndpoint = "http://ingestion-scraper:3001" // Live credentials have exactly one configured service destination. Loopback // ports belong exclusively to the separately constructed offline fixture client. func TrustedScraperURL(value string) (string, error) { if value != LiveScraperEndpoint && value != LiveScraperEndpoint+"/" { return "", errors.New("invalid_scraper_service") } return LiveScraperEndpoint, nil } func ReadCredentialFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", errors.New("credentials_unavailable") } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, 16385)) if err != nil || len(b) > 16384 { return "", errors.New("credentials_unavailable") } value := strings.TrimSuffix(strings.TrimSuffix(string(b), "\n"), "\r") if value == "" { return "", errors.New("credentials_unavailable") } return value, nil } type credentialRPCTransport struct { endpoint string base http.RoundTripper } func (t credentialRPCTransport) RoundTrip(r *http.Request) (*http.Response, error) { base, err := url.Parse(t.endpoint) if err != nil || r.Method != http.MethodPost || r.URL == nil || r.URL.Scheme != base.Scheme || r.URL.Host != base.Host || r.URL.User != nil || r.URL.Opaque != "" || r.URL.RawPath != "" || r.URL.RawQuery != "" || r.URL.ForceQuery || r.URL.Fragment != "" || (r.URL.Path != "/bloomberg/scrape" && r.URL.Path != "/bloomberg/enrich") { return nil, errors.New("credential_destination_rejected") } return t.base.RoundTrip(r) } func rpcClientForEndpoint(endpoint string) *http.Client { base := http.DefaultTransport.(*http.Transport).Clone() base.Proxy = nil // Credentials must never be forwarded through an ambient proxy. return &http.Client{Timeout: 10 * time.Minute, Transport: credentialRPCTransport{endpoint, base}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } // RPCClient is the live client: only the exact Compose service can receive a POST. func RPCClient() *http.Client { return rpcClientForEndpoint(LiveScraperEndpoint) } // OfflineRPCClient is bound to the specific locally launched fixture server. // The CLI never passes live credential files to this client. func OfflineRPCClient(endpoint string) (*http.Client, error) { u, err := url.Parse(endpoint) if err != nil || u.Scheme != "http" || u.User != nil || u.Opaque != "" || u.Path != "" || u.RawPath != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Hostname() != "127.0.0.1" && u.Hostname() != "::1") { return nil, errors.New("invalid_fixture_service") } port, err := strconv.Atoi(u.Port()) if err != nil || port < 1 || port > 65535 { return nil, errors.New("invalid_fixture_service") } return rpcClientForEndpoint(u.String()), nil } func publicIP(ip netip.Addr) bool { return sourcehttp.IsPublicAddress(ip) } type liveTransport struct{ base http.RoundTripper } func allowedLiveRequest(r *http.Request) bool { if r.Method != "GET" || r.URL.Scheme != "https" || r.URL.User != nil || r.URL.Port() != "" { return false } switch r.URL.Host { case "feeds.finance.yahoo.com", "finance.yahoo.com", "www.cnbc.com": return true } return false } func (t liveTransport) RoundTrip(r *http.Request) (*http.Response, error) { if !allowedLiveRequest(r) { return nil, errors.New("source_request_rejected") } return t.base.RoundTrip(r) } func LiveArticleClient() *http.Client { transport := sourcehttp.NewTransport(nil, nil) return &http.Client{Timeout: 15 * time.Second, Transport: liveTransport{transport}, CheckRedirect: func(r *http.Request, via []*http.Request) error { if len(via) >= 3 || !allowedLiveRequest(r) { return http.ErrUseLastResponse } return nil }} }