package services import ( "fmt" "net" "net/http" "net/http/httptest" "os" "strings" "testing" "agent-desk/internal/models" ) // Service integration fixtures may enqueue outbound work asynchronously. Keep // those clients inside this test process's loopback fixtures even when a test // accidentally supplies an external URL. Production transports are unchanged. type loopbackTestTransport struct { base http.RoundTripper } func (t loopbackTestTransport) RoundTrip(req *http.Request) (*http.Response, error) { host := req.URL.Hostname() ip := net.ParseIP(host) if host != "localhost" && (ip == nil || !ip.IsLoopback()) { return nil, fmt.Errorf("external HTTP transport disabled in service tests: %s", host) } return t.base.RoundTrip(req) } func TestMain(m *testing.M) { // These service fixtures do not contain AI-runtime tables/configuration. // Runtime behavior has its own suite; focused hook tests install their own // spies. Never let a transitive runtime init launch unowned background work. TriggerAIReplyAsyncHook = func(models.Conversation, models.Message) {} transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil http.DefaultTransport = loopbackTestTransport{base: transport} os.Exit(m.Run()) } type testRoundTripper func(*http.Request) (*http.Response, error) func (f testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } func TestServiceTransportRejectsExternalHostsBeforeDial(t *testing.T) { for _, address := range []string{"https://slack.com/api/chat.postMessage", "https://api.telegram.org/test", "http://example.invalid", "http://192.0.2.1", "http://[2001:db8::1]"} { t.Run(address, func(t *testing.T) { transport := loopbackTestTransport{base: testRoundTripper(func(*http.Request) (*http.Response, error) { t.Fatal("external request reached the underlying transport") return nil, nil })} req, err := http.NewRequest(http.MethodGet, address, nil) if err != nil { t.Fatal(err) } if _, err := transport.RoundTrip(req); err == nil { t.Fatal("external request was not blocked") } }) } } func TestServiceTransportRejectsRedirectOutsideLoopback(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "https://example.invalid/forbidden", http.StatusFound) })) defer server.Close() response, err := http.Get(server.URL) if response != nil { response.Body.Close() } if err == nil || !strings.Contains(err.Error(), "external HTTP transport disabled") { t.Fatalf("redirect did not hit the loopback guard: %v", err) } }