package traffic import ( "database/sql" "fmt" "io" "net" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "testing" "time" ) func TestFormatAndStripProxyContext(t *testing.T) { tagged := FormatProxyContextURL("http://127.0.0.1:8788", SourceIdentity{ Scope: "task", OwnerID: "42", SessionID: "conv-9", IntentID: 123, }) u, err := url.Parse(tagged) if err != nil { t.Fatalf("parse tagged url: %v", err) } if u.User == nil || !strings.HasPrefix(u.User.Username(), proxyContextUserPrefix) { t.Fatalf("expected artexctx userinfo, got %v", u.User) } // Pre-existing proxy auth must be preserved untouched. preAuth := "http://alice:secret@127.0.0.1:8788" if got := FormatProxyContextURL(preAuth, SourceIdentity{Scope: "task", OwnerID: "1"}); got != preAuth { t.Fatalf("expected pre-auth URL unchanged, got %q", got) } req, _ := http.NewRequest("GET", "http://example.com/", nil) req.SetBasicAuth(u.User.Username(), "x") req.Header.Set("Proxy-Authorization", req.Header.Get("Authorization")) req.Header.Del("Authorization") id, _, ok := parseAndStripProxyContext(req.Header) if !ok { t.Fatalf("expected parseAndStripProxyContext ok=true") } if req.Header.Get("Proxy-Authorization") != "" { t.Fatalf("Proxy-Authorization should be stripped, got %q", req.Header.Get("Proxy-Authorization")) } if id.Scope != "task" || id.OwnerID != "42" || id.SessionID != "conv-9" || id.IntentID != 123 { t.Fatalf("unexpected parsed identity: %+v", id) } // Unrelated Proxy-Authorization must NOT be stripped. h2 := http.Header{"Proxy-Authorization": []string{"Basic dXNlcjpwYXNz"}} if _, _, ok := parseAndStripProxyContext(h2); ok { t.Fatalf("non-artexctx header should not parse as context") } if h2.Get("Proxy-Authorization") == "" { t.Fatalf("non-artexctx Proxy-Authorization must not be stripped") } } func TestResolveSourceSecurityBoundary(t *testing.T) { tr := &Traffic{} tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { if srcIP == "172.28.0.5" { return SourceIdentity{ Scope: "task", OwnerID: "42", ContainerID: "abcdef123456", SrcIP: srcIP, }, true } return SourceIdentity{}, false }) // Sandbox container attempting to forge OwnerID=99 via Proxy-Authorization. tagged := FormatProxyContextURL("http://172.28.0.1:8788", SourceIdentity{ Scope: "session", OwnerID: "99", SessionID: "sess-1", IntentID: 77, }) u, _ := url.Parse(tagged) r, _ := http.NewRequest("GET", "http://example.com/", nil) r.SetBasicAuth(u.User.Username(), "x") r.Header.Set("Proxy-Authorization", r.Header.Get("Authorization")) got := tr.resolveSource("172.28.0.5:54321", r.Header) if got.Scope != "task" || got.OwnerID != "42" || got.ContainerID != "abcdef123456" { t.Fatalf("sandbox container IP must enforce hard identity, got %+v", got) } if got.IntentID != 77 || got.SessionID != "sess-1" { t.Fatalf("observability fields should still be enriched, got %+v", got) } if got.SrcIP != "172.28.0.5" { t.Fatalf("expected normalized src_ip 172.28.0.5, got %q", got.SrcIP) } // Host loopback caller may supply full scope+owner tags. r2, _ := http.NewRequest("GET", "http://example.com/", nil) r2.SetBasicAuth(u.User.Username(), "x") r2.Header.Set("Proxy-Authorization", r2.Header.Get("Authorization")) gotHost := tr.resolveSource("127.0.0.1:41234", r2.Header) if gotHost.Scope != "session" || gotHost.OwnerID != "99" || gotHost.IntentID != 77 { t.Fatalf("loopback host caller should accept full tag, got %+v", gotHost) } } func TestProxyAttributionAndTaskIsolationLive(t *testing.T) { var seenProxyAuth string upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seenProxyAuth = r.Header.Get("Proxy-Authorization") w.Header().Set("Content-Type", "text/plain") _, _ = w.Write([]byte("hello-target")) })) defer upstream.Close() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("listen: %v", err) } proxyAddr := ln.Addr().String() _ = ln.Close() tr, err := Open(t.TempDir(), proxyAddr) if err != nil { t.Fatalf("Open: %v", err) } defer tr.Close() tr.SetTaskBlacklistChecker(func(taskID, rawHost, scheme string) (string, string) { if taskID == "10" && strings.Contains(rawHost, "blocked-task10.example") { return "task #10 intercept rule: blocked", "blocked-task10.example" } return "", "" }) go func() { _ = tr.Start() }() // Wait until proxy accepts connections. deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { c, err := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond) if err == nil { _ = c.Close() break } time.Sleep(25 * time.Millisecond) } sendThrough := func(id SourceIdentity, targetURL string) *http.Response { pURLStr := FormatProxyContextURL("http://"+proxyAddr, id) pURL, _ := url.Parse(pURLStr) client := &http.Client{ Transport: &http.Transport{Proxy: http.ProxyURL(pURL)}, Timeout: 5 * time.Second, } resp, err := client.Get(targetURL) if err != nil { t.Fatalf("GET %s via proxy: %v", targetURL, err) } return resp } // 1. Task 10 request -> recorded with attribution, Proxy-Authorization stripped before reaching target. resp1 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 55}, upstream.URL+"/t10") _, _ = io.ReadAll(resp1.Body) _ = resp1.Body.Close() if resp1.StatusCode != 200 { t.Fatalf("expected 200 for task 10, got %d", resp1.StatusCode) } if seenProxyAuth != "" { t.Fatalf("target server must never receive internal Proxy-Authorization, got %q", seenProxyAuth) } // 2. Task 20 request to the SAME target host -> must NOT leak into Task 10's query! resp2 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "20", IntentID: 88}, upstream.URL+"/t20") _, _ = io.ReadAll(resp2.Body) _ = resp2.Body.Close() // 3. Task 10 blocked by per-task intercept rule -> 403 + block event attributed to task 10. resp3 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 56}, "http://blocked-task10.example/secret") body3, _ := io.ReadAll(resp3.Body) _ = resp3.Body.Close() if resp3.StatusCode != http.StatusForbidden { t.Fatalf("expected 403 for task 10 blocked host, got %d (%s)", resp3.StatusCode, string(body3)) } events := tr.BlockEvents(10) if len(events) == 0 || events[0].Scope != "task" || events[0].OwnerID != "10" || events[0].RuleKind != "task_intercept" { t.Fatalf("expected task 10 block event, got %+v", events) } // 4. Insert a legacy unattributed row for the same host to verify backward compatibility. uParsed, _ := url.Parse(upstream.URL) targetHost := uParsed.Hostname() _, err = tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) VALUES('legacy-1', 100, ?, 'GET', '/old', ?, 200, 'text/plain', 0, 5, '')`, targetHost, upstream.URL+"/old") if err != nil { t.Fatalf("insert legacy row: %v", err) } // Query Task 10 with shared targetHost in scope: must see Task 10 + legacy, NOT Task 20! rows10, total10, err := tr.Page(PageQuery{ OwnerTaskID: "10", Hosts: []string{targetHost}, RespMin: -1, RespMax: -1, }, 0, 50) if err != nil { t.Fatalf("Page task 10: %v", err) } if total10 != 2 { t.Fatalf("expected 2 rows for task 10 (task10 + legacy, excluding task20), got %d: %+v", total10, rows10) } for _, r := range rows10 { if r.SandboxOwnerID == "20" { t.Fatalf("task 20 traffic leaked into task 10 query: %+v", r) } if strings.HasSuffix(r.URL, "/t10") { if r.SandboxScope != "task" || r.SandboxOwnerID != "10" || r.IntentID != 55 || r.SrcIP != "127.0.0.1" { t.Fatalf("unexpected attribution on /t10: %+v", r) } } } // Query Task 10 with EMPTY host scope (e.g. before assets are discovered): still returns Task 10's attributed traffic! rows10NoScope, totalNoScope, err := tr.Page(PageQuery{ OwnerTaskID: "10", RespMin: -1, RespMax: -1, }, 0, 50) if err != nil || totalNoScope != 1 || len(rows10NoScope) != 1 || rows10NoScope[0].SandboxOwnerID != "10" { t.Fatalf("expected 1 attributed row with empty host scope, got total=%d rows=%+v err=%v", totalNoScope, rows10NoScope, err) } // HostsForTask returns attributed host even with empty scope. hosts10, err := tr.HostsForTask("10", nil) if err != nil || len(hosts10) != 1 || hosts10[0].Host != targetHost { t.Fatalf("HostsForTask expected [%s], got %+v err=%v", targetHost, hosts10, err) } } func TestAttributionMigrationOnLegacyDB(t *testing.T) { dir := t.TempDir() idxDir := filepath.Join(dir, "_index") if err := os.MkdirAll(idxDir, 0o755); err != nil { t.Fatal(err) } dbPath := filepath.Join(idxDir, "index.sqlite") rawDB, err := sql.Open("sqlite", dbPath) if err != nil { t.Fatal(err) } _, err = rawDB.Exec(`CREATE TABLE exchanges ( id TEXT PRIMARY KEY, ts INTEGER, host TEXT, method TEXT, url_template TEXT, url TEXT, status INTEGER, content_type TEXT, req_len INTEGER, resp_len INTEGER, path TEXT ); INSERT INTO exchanges VALUES ('old-1', 123, 'example.com', 'GET', '/', 'http://example.com/', 200, 'text/html', 0, 10, '');`) if err != nil { t.Fatal(err) } _ = rawDB.Close() tr, err := Open(dir, "127.0.0.1:0") if err != nil { t.Fatalf("Open legacy DB failed: %v", err) } defer tr.Close() rows, total, err := tr.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 10) if err != nil { t.Fatalf("Page after migration failed: %v", err) } if total != 1 || len(rows) != 1 || rows[0].ID != "old-1" { t.Fatalf("unexpected rows after migration: total=%d rows=%+v", total, rows) } // Verify new attribution insert works on migrated DB. if _, err := tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path,sandbox_scope,sandbox_owner_id,container_id,session_id,intent_id,src_ip) VALUES('new-1', 456, 'example.com', 'GET', '/new', 'http://example.com/new', 200, 'text/plain', 0, 4, '', 'task', '7', 'cid123456789', '', 3, '172.28.0.9')`); err != nil { t.Fatalf("insert attributed row after migration failed: %v", err) } filtered, tot, err := tr.Page(PageQuery{ContainerID: "cid123", RespMin: -1, RespMax: -1}, 0, 10) if err != nil || tot != 1 || len(filtered) != 1 || filtered[0].SrcIP != "172.28.0.9" { t.Fatalf("container filter failed: tot=%d rows=%+v err=%v", tot, filtered, err) } _ = fmt.Sprintf("migrated ok") }