test(e2e): add isolated browser journey and cleanup supervision
Add a fake-only end-to-end stack, Firefox journey, and bounded process cleanup for normal, failed, and interrupted runs. Refs #12 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
193
backend/internal/e2estack/fakes.go
Normal file
193
backend/internal/e2estack/fakes.go
Normal file
@ -0,0 +1,193 @@
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type Fixtures struct {
|
||||
IndexQuery string `json:"indexQuery"`
|
||||
IndexName string `json:"indexName"`
|
||||
IndexSymbol string `json:"indexSymbol"`
|
||||
IndexFIGI string `json:"indexFIGI"`
|
||||
SummarySentinel string `json:"summarySentinel"`
|
||||
ArticleTitle string `json:"articleTitle"`
|
||||
ArticleURL string `json:"articleURL"`
|
||||
ArticleContent string `json:"articleContent"`
|
||||
CandidateID string `json:"candidateID"`
|
||||
}
|
||||
|
||||
func DefaultFixtures() Fixtures {
|
||||
return Fixtures{"E2E index", "E2E Financial Index", "E2EIDX", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Kind string `json:"kind"`
|
||||
Symbols []string `json:"symbols,omitempty"`
|
||||
CandidateID string `json:"candidate_id,omitempty"`
|
||||
}
|
||||
type Fakes struct {
|
||||
mu sync.Mutex
|
||||
Fixture Fixtures
|
||||
Events []Event
|
||||
counts map[string]int
|
||||
}
|
||||
|
||||
func NewFakes() *Fakes {
|
||||
return &Fakes{Fixture: DefaultFixtures(), Events: []Event{}, counts: map[string]int{}}
|
||||
}
|
||||
func (f *Fakes) record(event Event) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.Events = append(f.Events, event)
|
||||
f.counts[event.Kind]++
|
||||
}
|
||||
func (f *Fakes) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/audit", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
|
||||
})
|
||||
mux.HandleFunc("/v3/search", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Query string `json:"query"`
|
||||
Market string `json:"marketSecDes"`
|
||||
}
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil || req.Market != "Index" {
|
||||
http.Error(w, "invalid fixture search", 400)
|
||||
return
|
||||
}
|
||||
f.record(Event{Kind: "openfigiSearches"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.IndexName, "ticker": f.Fixture.IndexSymbol, "figi": f.Fixture.IndexFIGI, "marketSector": "Index"}}})
|
||||
})
|
||||
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
|
||||
var symbols []string
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&symbols) != nil {
|
||||
http.Error(w, "invalid fixture scrape", 400)
|
||||
return
|
||||
}
|
||||
f.record(Event{Kind: "scraperCalls", Symbols: symbols})
|
||||
_ = json.NewEncoder(w).Encode([]scraper.Article{{Title: f.Fixture.ArticleTitle, Content: f.Fixture.ArticleContent, URL: f.Fixture.ArticleURL}})
|
||||
})
|
||||
mux.HandleFunc("/api/generate", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Prompt string `json:"prompt"`
|
||||
Format string `json:"format"`
|
||||
}
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil {
|
||||
http.Error(w, "invalid fixture provider", 400)
|
||||
return
|
||||
}
|
||||
response := f.Fixture.SummarySentinel
|
||||
if req.Format == "json" {
|
||||
// The candidate UUID is generated by the real use case; never hard-code it.
|
||||
start := strings.LastIndex(req.Prompt, "\n{")
|
||||
if start < 0 {
|
||||
http.Error(w, "ranking payload missing", 400)
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Articles []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"articles"`
|
||||
}
|
||||
if json.Unmarshal([]byte(req.Prompt[start+1:]), &payload) != nil || len(payload.Articles) != 1 {
|
||||
http.Error(w, "ranking candidate missing", 400)
|
||||
return
|
||||
}
|
||||
id := payload.Articles[0].ID
|
||||
f.mu.Lock()
|
||||
f.Fixture.CandidateID = id
|
||||
f.mu.Unlock()
|
||||
f.record(Event{Kind: "layaRankingCalls", CandidateID: id})
|
||||
encoded, _ := json.Marshal(map[string]any{"ranked_article_ids": []string{id}})
|
||||
response = string(encoded)
|
||||
} else {
|
||||
f.record(Event{Kind: "layaSummaryCalls"})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"response": response})
|
||||
})
|
||||
return mux
|
||||
}
|
||||
func Listen(handler http.Handler) (string, func(), error) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
server := &http.Server{Handler: handler}
|
||||
go server.Serve(listener)
|
||||
return "http://" + listener.Addr().String(), func() { _ = server.Close() }, nil
|
||||
}
|
||||
|
||||
type FakeScraper struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
func (FakeScraper) Name() string { return "e2e" }
|
||||
func (s FakeScraper) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
if err := ValidateURL(s.URL, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, _ := json.Marshal(symbols)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", s.URL+"/scrape", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := s.Client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("fake scraper failed")
|
||||
}
|
||||
var articles []scraper.Article
|
||||
err = json.NewDecoder(resp.Body).Decode(&articles)
|
||||
return articles, err
|
||||
}
|
||||
|
||||
type FakeProvider struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
func (FakeProvider) Name() string { return "fake-laya" }
|
||||
func (FakeProvider) ListModels(context.Context) ([]string, error) { return []string{"fake-laya"}, nil }
|
||||
func (p FakeProvider) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
|
||||
if err := ValidateURL(p.URL, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
body := map[string]any{"prompt": prompt, "model": "fake-laya", "stream": false}
|
||||
if opts.JSONMode {
|
||||
body["format"] = "json"
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", p.URL+"/api/generate", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := p.Client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return "", fmt.Errorf("fake provider failed")
|
||||
}
|
||||
var result struct {
|
||||
Response string `json:"response"`
|
||||
}
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
return result.Response, err
|
||||
}
|
||||
49
backend/internal/e2estack/network.go
Normal file
49
backend/internal/e2estack/network.go
Normal file
@ -0,0 +1,49 @@
|
||||
// Package e2estack contains test-only loopback adapters. Production does not import it.
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func ValidateURL(raw string, database bool) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return errors.New("invalid E2E URL")
|
||||
}
|
||||
scheme := u.Scheme == "http" || u.Scheme == "https"
|
||||
if database {
|
||||
scheme = u.Scheme == "postgres" || u.Scheme == "postgresql"
|
||||
}
|
||||
ip := net.ParseIP(u.Hostname())
|
||||
if !scheme || ip == nil || !ip.IsLoopback() || u.Port() == "" {
|
||||
return errors.New("E2E URL must use a literal loopback IP and explicit port")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type loopbackTransport struct{ base *http.Transport }
|
||||
|
||||
func (t loopbackTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if err := ValidateURL(r.URL.String(), false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.base.RoundTrip(r)
|
||||
}
|
||||
func LoopbackClient() *http.Client {
|
||||
transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil || !ip.IsLoopback() {
|
||||
return nil, errors.New("E2E external egress forbidden")
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, address)
|
||||
}}
|
||||
return &http.Client{Transport: loopbackTransport{transport}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
}
|
||||
11
backend/internal/e2estack/process_linux.go
Normal file
11
backend/internal/e2estack/process_linux.go
Normal file
@ -0,0 +1,11 @@
|
||||
//go:build linux
|
||||
|
||||
package e2estack
|
||||
|
||||
import "syscall"
|
||||
|
||||
// ChildProcessAttrs prevents a Vite/Playwright launcher surviving e2e-stack.
|
||||
// The subreaper separately owns and cleans their detached descendants.
|
||||
func ChildProcessAttrs() *syscall.SysProcAttr {
|
||||
return &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
|
||||
}
|
||||
7
backend/internal/e2estack/process_other.go
Normal file
7
backend/internal/e2estack/process_other.go
Normal file
@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package e2estack
|
||||
|
||||
import "syscall"
|
||||
|
||||
func ChildProcessAttrs() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }
|
||||
50
backend/internal/e2estack/safety_test.go
Normal file
50
backend/internal/e2estack/safety_test.go
Normal file
@ -0,0 +1,50 @@
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
func TestRejectNonLoopbackDestinationsWithoutEgress(t *testing.T) {
|
||||
for _, destination := range []string{"https://api.openfigi.com:443", "http://203.0.113.10:80", "http://localhost:8080", "http://127.0.0.1.evil.test:80", "file:///tmp/fixture"} {
|
||||
if ValidateURL(destination, false) == nil {
|
||||
t.Fatalf("unsafe base URL accepted: %s", destination)
|
||||
}
|
||||
request, err := http.NewRequest("GET", destination, nil)
|
||||
if err == nil {
|
||||
if _, err = LoopbackClient().Do(request); err == nil {
|
||||
t.Fatal("external request accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
if ValidateURL("postgres://127.0.0.1:5432/tradarr_e2e", true) != nil {
|
||||
t.Fatal("loopback DB rejected")
|
||||
}
|
||||
}
|
||||
func TestFakesRankActualCandidateIDAndJournalCalls(t *testing.T) {
|
||||
fake := NewFakes()
|
||||
base, closeServer, err := Listen(fake.Handler())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeServer()
|
||||
provider := FakeProvider{URL: base, Client: LoopbackClient()}
|
||||
articles := []models.Article{{ID: "runtime-candidate-uuid", Title: fake.Fixture.ArticleTitle, Content: fake.Fixture.ArticleContent}}
|
||||
ranked, err := ai.RankArticles(context.Background(), provider, []string{"Index (IDX)"}, articles, 20, "title_content")
|
||||
if err != nil || len(ranked) != 1 || ranked[0].ID != articles[0].ID {
|
||||
t.Fatalf("ranking=%v err=%v", ranked, err)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
if fake.counts["layaRankingCalls"] != 1 || fake.Events[0].CandidateID != "runtime-candidate-uuid" {
|
||||
t.Fatal("ranking call not journaled")
|
||||
}
|
||||
if strings.Contains(fake.Fixture.SummarySentinel, fake.Fixture.ArticleTitle) {
|
||||
t.Fatal("unsafe summary fixture")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user