From 1725a4454331a914f685da9cafe83d5490597e78 Mon Sep 17 00:00:00 2001 From: James Khor Date: Mon, 23 Nov 2026 18:29:58 +0800 Subject: [PATCH] Clarify scanner User-Agent settings and verify recorded redirects --- README.md | 4 +- config.example.json | 6 +- config/config.go | 22 ++- ..._identification.go => task_user_agents.go} | 10 +- ...ation_test.go => task_user_agents_test.go} | 35 +++- ...dentification.md => scanner-user-agent.md} | 8 +- server/assessment_identification_test.go | 6 +- server/customtool.go | 8 +- server/manager.go | 14 +- server/target_gate_flag_test.go | 7 +- .../task_user_agent_recording_proxy_test.go | 167 ++++++++++++++++++ 11 files changed, 244 insertions(+), 43 deletions(-) rename config/{assessment_identification.go => task_user_agents.go} (90%) rename config/{assessment_identification_test.go => task_user_agents_test.go} (75%) rename docs/{assessment-identification.md => scanner-user-agent.md} (91%) create mode 100644 server/task_user_agent_recording_proxy_test.go diff --git a/README.md b/README.md index 2414079..c5b0de1 100644 --- a/README.md +++ b/README.md @@ -534,9 +534,9 @@ every case. The **Target noise** card in System settings sets the profile at runtime (no restart) and shows the per-host counters; once saved, that setting takes precedence over `ARTEX_NOISE_PROFILE`. -**Assessment identification (opt-in per task)** adds a stable ARTEX User-Agent to supported +**Scanner User-Agent (opt-in per task)** adds a stable ARTEX User-Agent to supported target requests so defenders can correlate them with an approved assessment. See the -[configuration and WAF triage guide](docs/assessment-identification.md). +[configuration and WAF triage guide](docs/scanner-user-agent.md). **Low-and-slow agent guidance (off by default)**: when a noise profile is set, the planner, worker, main agent and chat agents receive a code-owned prompt block with the profile's per-host limits and diff --git a/config.example.json b/config.example.json index 904fe10..9e457c7 100644 --- a/config.example.json +++ b/config.example.json @@ -1,5 +1,5 @@ { - "_comment": "Copy as config.json or set ARTEX_CONFIG to its path. This file configures PostgreSQL, the skill directory, and optional assessment identification.", + "_comment": "Copy as config.json or set ARTEX_CONFIG to its path. This file configures PostgreSQL, the skill directory, and the optional Scanner User-Agent.", "_comment_database": "PostgreSQL connection. Precedence: environment variable ARTEX_PG_DSN > database in this file. Two ways, pick one: (A) fill in the component fields below; (B) fill only database.dsn with a full connection string.", "database": { @@ -21,6 +21,6 @@ "_comment_skill_dir": "Skill root directory (one skill per subdirectory, each with a SKILL.md). Precedence: environment variable ARTEX_SKILL_DIR > this field > default (skills/ next to the executable). Leave empty or delete this field to use the default. Relative paths resolve against the current working directory.", "skill_dir": "/opt/artex/skills", - "_comment_assessment_identification": "Leave empty to disable. To opt in, map a live task ID to an object with a nonempty origins list and an optional public reference. See docs/assessment-identification.md.", - "assessment_identification": {} + "_comment_task_user_agents": "Leave empty to disable. To opt in, map a live task ID to an object with a nonempty origins list and an optional public reference. See docs/scanner-user-agent.md.", + "task_user_agents": {} } diff --git a/config/config.go b/config/config.go index 25231fb..e0abd03 100644 --- a/config/config.go +++ b/config/config.go @@ -29,9 +29,9 @@ type Database struct { // Config is the on-disk config file shape. type Config struct { - Database Database `json:"database"` - SkillDir string `json:"skill_dir"` - AssessmentIdentification AssessmentIdentification `json:"assessment_identification,omitempty"` + Database Database `json:"database"` + SkillDir string `json:"skill_dir"` + TaskUserAgents TaskUserAgents `json:"task_user_agents,omitempty"` } // BaseDir is the directory that anchors all runtime artifacts (config.json and @@ -117,19 +117,25 @@ func Path() string { // callers fall back to defaults). A file that exists but cannot be read or parsed // is an error: ignoring it would run with defaults the operator did not choose. func Load() (Config, error) { - var c Config path := Path() b, err := os.ReadFile(path) if errors.Is(err, fs.ErrNotExist) { - return c, nil + return Config{}, nil } if err != nil { - return c, fmt.Errorf("read config file %s: %w", path, err) + return Config{}, fmt.Errorf("read config file %s: %w", path, err) } - if err := json.Unmarshal(b, &c); err != nil { + var disk struct { + Config + LegacyTaskUserAgents json.RawMessage `json:"assessment_identification"` + } + if err := json.Unmarshal(b, &disk); err != nil { return Config{}, fmt.Errorf("parse config file %s: %w", path, err) } - return c, nil + if disk.LegacyTaskUserAgents != nil { + return Config{}, fmt.Errorf("parse config file %s: assessment_identification was replaced by task_user_agents. Move each task entry to task_user_agents with its origins list", path) + } + return disk.Config, nil } // SkillDir returns the skill root directory with precedence: diff --git a/config/assessment_identification.go b/config/task_user_agents.go similarity index 90% rename from config/assessment_identification.go rename to config/task_user_agents.go index 67db126..95be068 100644 --- a/config/assessment_identification.go +++ b/config/task_user_agents.go @@ -19,18 +19,18 @@ var ( asciiDNSLabel = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`) ) -// AssessmentIdentification maps opted-in task IDs to their allowed origins and label. -type AssessmentIdentification map[string]AssessmentIdentity +// TaskUserAgents maps opted-in task IDs to their allowed origins and label. +type TaskUserAgents map[string]AssessmentIdentity -func (a *AssessmentIdentification) UnmarshalJSON(data []byte) error { +func (a *TaskUserAgents) UnmarshalJSON(data []byte) error { var entries map[string]AssessmentIdentity if err := json.Unmarshal(data, &entries); err != nil { - return fmt.Errorf("assessment_identification: %w", err) + return fmt.Errorf("task_user_agents: %w", err) } for taskID := range entries { id, err := strconv.ParseInt(taskID, 10, 64) if err != nil || id <= 0 || strconv.FormatInt(id, 10) != taskID { - return errors.New("assessment_identification task IDs must be positive integers written without a sign or leading zeroes") + return errors.New("task_user_agents task IDs must be positive integers written without a sign or leading zeroes") } } *a = entries diff --git a/config/assessment_identification_test.go b/config/task_user_agents_test.go similarity index 75% rename from config/assessment_identification_test.go rename to config/task_user_agents_test.go index b3c5918..16829cf 100644 --- a/config/assessment_identification_test.go +++ b/config/task_user_agents_test.go @@ -8,16 +8,16 @@ import ( "testing" ) -func TestLoadAssessmentIdentification(t *testing.T) { +func TestLoadTaskUserAgents(t *testing.T) { path := filepath.Join(t.TempDir(), "config.json") t.Setenv("ARTEX_CONFIG", path) cfg, err := Load() - if err != nil || len(cfg.AssessmentIdentification) != 0 { + if err != nil || len(cfg.TaskUserAgents) != 0 { t.Fatalf("missing file: config = %+v, error = %v", cfg, err) } const maxReference = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._" - body := `{"assessment_identification":{ + body := `{"task_user_agents":{ "42":{"reference":"FS-17","origins":["https://SHOP.example.test:443/","http://[2001:db8::1]:8080"]}, "43":{"reference":"","origins":["https://shop.example.test"]}, "44":{"reference":"` + maxReference + `","origins":["https://shop.example.test"]}, @@ -38,12 +38,12 @@ func TestLoadAssessmentIdentification(t *testing.T) { {"46", ""}, {"", ""}, } { - identity := cfg.AssessmentIdentification[tc.taskID] + identity := cfg.TaskUserAgents[tc.taskID] if got := identity.UserAgent(); got != tc.want { t.Errorf("task %q: User-Agent = %q, want %q", tc.taskID, got, tc.want) } } - identity := cfg.AssessmentIdentification["42"] + identity := cfg.TaskUserAgents["42"] for _, tc := range []struct { rawURL string want bool @@ -65,7 +65,7 @@ func TestLoadAssessmentIdentification(t *testing.T) { } } -func TestLoadRejectsInvalidAssessmentIdentification(t *testing.T) { +func TestLoadRejectsInvalidTaskUserAgents(t *testing.T) { for _, tc := range []struct { name, entries string }{ @@ -94,13 +94,30 @@ func TestLoadRejectsInvalidAssessmentIdentification(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "config.json") - if err := os.WriteFile(path, []byte(`{"assessment_identification":`+tc.entries+`}`), 0o600); err != nil { + if err := os.WriteFile(path, []byte(`{"task_user_agents":`+tc.entries+`}`), 0o600); err != nil { t.Fatal(err) } t.Setenv("ARTEX_CONFIG", path) - if _, err := Load(); err == nil || !strings.Contains(err.Error(), "assessment_identification") { - t.Fatalf("Load() error = %v, want assessment_identification validation error", err) + if _, err := Load(); err == nil || !strings.Contains(err.Error(), "task_user_agents") { + t.Fatalf("Load() error = %v, want task_user_agents validation error", err) } }) } } + +func TestLoadRejectsOldTaskUserAgentsKey(t *testing.T) { + for _, body := range []string{ + `{"assessment_identification":{"42":{"origins":["https://test.example"]}}}`, + `{"assessment_identification":null}`, + `{"assessment_identification":{},"task_user_agents":{"42":{"origins":["https://test.example"]}}}`, + } { + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("ARTEX_CONFIG", path) + if _, err := Load(); err == nil || !strings.Contains(err.Error(), "assessment_identification was replaced by task_user_agents") { + t.Fatalf("Load() error = %v, want task_user_agents migration hint", err) + } + } +} diff --git a/docs/assessment-identification.md b/docs/scanner-user-agent.md similarity index 91% rename from docs/assessment-identification.md rename to docs/scanner-user-agent.md index ee87ebf..f5709fc 100644 --- a/docs/assessment-identification.md +++ b/docs/scanner-user-agent.md @@ -1,18 +1,20 @@ -# Assessment identification +# Scanner User-Agent An authorized assessment can opt in to a stable ARTEX User-Agent on supported target HTTP requests. A security operations center (SOC), incident response team (IR), or computer incident response team (CIRT) can search for that label in web application firewall (WAF) logs and correlate candidate events with an approved assessment record. ## Configure a task -Add `assessment_identification` to the active ARTEX `config.json`, keeping the rest of your configuration. Each key is an existing task ID written as a positive decimal integer without leading zeros. Each task entry needs a nonempty `origins` list of exact approved HTTP or HTTPS origins. Use the scheme and host, with a port when needed. List each origin explicitly and leave out wildcards, paths, queries, fragments, and credentials. ARTEX matches the URL by scheme, host, and port. Host letter case and an explicitly written default port are treated as equivalent. +Add `task_user_agents` to the active ARTEX `config.json`, keeping the rest of your configuration. Each key is an existing task ID written as a positive decimal integer without leading zeros. Each task entry needs a nonempty `origins` list of exact approved HTTP or HTTPS origins. Use the scheme and host, with a port when needed. List each origin explicitly and leave out wildcards, paths, queries, fragments, and credentials. ARTEX matches the URL by scheme, host, and port. Host letter case and an explicitly written default port are treated as equivalent. Omit `reference` or use an empty string for the base label. A public reference may contain 1–64 ASCII letters, digits, dots, underscores, or hyphens. ARTEX validates this setting at startup and rejects an invalid file. Restart after editing. Remove the task's entry to disable its label. At startup, ARTEX logs a warning and ignores entries with no live task in the database. They stay off for that process even if a task later receives the ID or is restored. Restart with the task present in the database to apply its entry. +If your configuration has the pre-release key `assessment_identification`, move its entries to `task_user_agents` as shown below. Each entry needs an `origins` list. Remove the old key before restarting. + ```json { - "assessment_identification": { + "task_user_agents": { "123": { "origins": ["https://shop.example.test"], "reference": "FS-17" diff --git a/server/assessment_identification_test.go b/server/assessment_identification_test.go index 37c3700..5eb28fa 100644 --- a/server/assessment_identification_test.go +++ b/server/assessment_identification_test.go @@ -194,7 +194,7 @@ func TestAssessmentStartupScopesCurrentTasks(t *testing.T) { t.Cleanup(func() { _ = pg.Close() }) addTask := func() *db.Task { t.Helper() - task, err := pg.CreateTask("assessment identification fixture", "", nil, 0, 0) + task, err := pg.CreateTask("scanner User-Agent fixture", "", nil, 0, 0) if err != nil { t.Fatal(err) } @@ -206,7 +206,7 @@ func TestAssessmentStartupScopesCurrentTasks(t *testing.T) { untaggedID := strconv.FormatInt(untagged.ID, 10) futureID := strconv.FormatInt(untagged.ID+1, 10) cfgPath := filepath.Join(t.TempDir(), "config.json") - cfg := map[string]any{"assessment_identification": map[string]any{ + cfg := map[string]any{"task_user_agents": map[string]any{ taggedID: map[string]any{"reference": "FS-17", "origins": []string{"https://shop.example.test"}}, futureID: map[string]any{"reference": "future", "origins": []string{"https://shop.example.test"}}, }} @@ -226,7 +226,7 @@ func TestAssessmentStartupScopesCurrentTasks(t *testing.T) { _ = m.Close() }) m.LoadExisting() - created, err := m.CreateTask("assessment identification fixture created after startup", "", nil, 0, 0) + created, err := m.CreateTask("scanner User-Agent fixture created after startup", "", nil, 0, 0) if err != nil { t.Fatal(err) } diff --git a/server/customtool.go b/server/customtool.go index 9eb03c4..3ebe2eb 100644 --- a/server/customtool.go +++ b/server/customtool.go @@ -645,9 +645,11 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport { proxyStr := proxyURLString(spec.Proxy) var caFile string if spec.UseRecordingProxy { - if addr := proxyURLString(s.m.ProxyAddr()); addr != "" { + if tr := s.m.Traffic(); tr != nil && s.m.TrafficEnabled() { + proxyStr = proxyURLString(tr.ProxyAddr()) + caFile = tr.CACertPath() + } else if addr := proxyURLString(s.m.GlobalProxy()); addr != "" { proxyStr = addr - caFile = s.m.ProxyCACert() } } if proxyStr == "" { @@ -659,6 +661,8 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport { } tr := &http.Transport{Proxy: http.ProxyURL(pu)} if caFile != "" { + // Keep recorded HTTP requests on separate connections across redirects. + tr.DisableKeepAlives = true if pem, err := os.ReadFile(caFile); err == nil { pool := x509.NewCertPool() if pool.AppendCertsFromPEM(pem) { diff --git a/server/manager.go b/server/manager.go index 46b568f..d035253 100644 --- a/server/manager.go +++ b/server/manager.go @@ -264,7 +264,7 @@ type Manager struct { enrich *enrich.Engine // engine-side asset auto-completion (DNS/HTTP) interceptor *intercept.Interceptor // user-configured tool-call interception rules - assessmentIdentification config.AssessmentIdentification // existing tasks verified at startup + taskUserAgents config.TaskUserAgents // existing tasks verified at startup // Capture-proxy rewrite rules: rewriteMu serializes reloads, rewriteSet is // the snapshot last compiled, rewriteErrors outlives the reloads. @@ -428,16 +428,16 @@ func NewManager(dir, proxyAddr string) (*Manager, error) { } // Reject deferred activation: a configured ID that does not exist at startup // must not start tagging requests if a task is assigned that ID later. - for taskID := range cfg.AssessmentIdentification { + for taskID := range cfg.TaskUserAgents { id, _ := strconv.ParseInt(taskID, 10, 64) // validated when the config was loaded task, err := pg.GetTask(id) if err != nil { pg.Close() - return nil, fmt.Errorf("check assessment_identification task ID %s: %w", taskID, err) + return nil, fmt.Errorf("check task_user_agents task ID %s: %w", taskID, err) } if task == nil { - log.Printf("[config] assessment_identification task ID %s is unavailable, ignoring its entry", taskID) - delete(cfg.AssessmentIdentification, taskID) + log.Printf("[config] task_user_agents task ID %s is unavailable, ignoring its entry", taskID) + delete(cfg.TaskUserAgents, taskID) } } // Before anything reads a stored secret: load the key, encrypt legacy plaintext. @@ -458,7 +458,7 @@ func NewManager(dir, proxyAddr string) (*Manager, error) { } m := &Manager{ dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg), - assessmentIdentification: cfg.AssessmentIdentification, + taskUserAgents: cfg.TaskUserAgents, } // Behind any proxy in the path (the recording proxy, the global egress proxy, // or a custom tool's own proxy) the proxy chooses the address, so a target @@ -1034,7 +1034,7 @@ func taskFromPG(pt *pgdb.Task, store *pgdb.ExplorationStore, ic *intercept.Inter func (m *Manager) taskFromPG(pt *pgdb.Task) *Task { t := taskFromPG(pt, m.pg.Exploration(pt.ExplorationID), m.interceptor) - t.assessmentIdentity = m.assessmentIdentification[t.ID] + t.assessmentIdentity = m.taskUserAgents[t.ID] return t } diff --git a/server/target_gate_flag_test.go b/server/target_gate_flag_test.go index 5361c59..cc1eaee 100644 --- a/server/target_gate_flag_test.go +++ b/server/target_gate_flag_test.go @@ -31,9 +31,14 @@ type gateServer struct { } func newGateServer(t *testing.T) *gateServer { + t.Helper() + return newGateServerWithProxy(t, "") +} + +func newGateServerWithProxy(t *testing.T, proxyAddr string) *gateServer { t.Helper() skipWithoutDSN(t) - m, err := NewManager(t.TempDir(), "") + m, err := NewManager(t.TempDir(), proxyAddr) if err != nil { t.Fatal(err) } diff --git a/server/task_user_agent_recording_proxy_test.go b/server/task_user_agent_recording_proxy_test.go new file mode 100644 index 0000000..4fc5359 --- /dev/null +++ b/server/task_user_agent_recording_proxy_test.go @@ -0,0 +1,167 @@ +package server + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/egress" + "github.com/Autumn-27/artex/traffic" +) + +func recordingProxyTestAddr(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + if err := ln.Close(); err != nil { + t.Fatal(err) + } + return addr +} + +func TestAssessmentHTTPToolGatedRecordingProxyRedirect(t *testing.T) { + prev := egress.CurrentProfile() + t.Cleanup(func() { egress.SetProfile(prev) }) + proxyAddr := recordingProxyTestAddr(t) + g := newGateServerWithProxy(t, proxyAddr) + t.Cleanup(g.m.Enrich().Close) + egress.SetProfile(egress.Profile{Name: "off"}) + tr := g.m.Traffic() + if tr == nil { + t.Fatal("recording proxy unavailable") + } + if err := tr.SetUpstreamProxy(""); err != nil { + t.Fatal(err) + } + captureWasOn := g.m.TrafficEnabled() + t.Cleanup(func() { + if err := g.m.SetTrafficEnabled(captureWasOn); err != nil { + t.Error(err) + } + }) + if err := g.m.SetTrafficEnabled(true); err != nil { + t.Fatal(err) + } + waitUntil(t, "recording proxy", func() bool { + conn, err := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond) + if err != nil { + return false + } + _ = conn.Close() + return true + }) + + sourceUA, redirectUA := make(chan string, 16), make(chan string, 16) + dest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + redirectUA <- r.UserAgent() + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(dest.Close) + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sourceUA <- r.UserAgent() + http.Redirect(w, r, dest.URL+"/redirected", http.StatusFound) + })) + t.Cleanup(source.Close) + + on := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) + // The label permits both origins. The approval gate still decides if a + // request may reach either one, and a cross-origin hop still drops the label. + raw := execJSON(t, map[string]any{"reference": "FS-17", "origins": []string{source.URL, dest.URL}}) + if err := json.Unmarshal(raw, &task.assessmentIdentity); err != nil { + t.Fatal(err) + } + ctx := gatedCtx(task, 0) + sourceURL, redirectURL := source.URL+"/initial", dest.URL+"/redirected" + const toolName = "assessment_gated_redirect" + spec := execJSON(t, httpExec{URL: sourceURL, UseRecordingProxy: true, TimeoutMs: 5000}) + wantPending := func(target string) { + t.Helper() + res, err := g.s.runHTTPTool(ctx, toolName, spec, nil, nil) + if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "TARGET_APPROVAL_PENDING") || + !strings.Contains(res.Flatten(), strings.TrimPrefix(target, "http://")) { + t.Fatalf("expected pending approval for %s, got %v %s", target, err, res.Flatten()) + } + } + approve := func(target string) { + t.Helper() + id, name, _, ok := openTargetRequest(t, g.m.pg, task.ID, strings.TrimPrefix(target, "http://")) + if !ok || name != toolName { + t.Fatalf("no pending %s approval for %s, tool=%q", toolName, target, name) + } + if code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"allowed"}`); code != 200 { + t.Fatalf("approve %s: %d %v", target, code, body) + } + } + + wantPending(source.URL) + if len(sourceUA) != 0 || len(redirectUA) != 0 { + t.Fatal("a request reached an origin before the initial approval") + } + approve(source.URL) + wantPending(dest.URL) + if len(sourceUA) != 1 || len(redirectUA) != 0 { + t.Fatalf("before redirect approval, got %d initial requests and %d redirect requests", len(sourceUA), len(redirectUA)) + } + approve(dest.URL) + res, err := g.s.runHTTPTool(ctx, toolName, spec, nil, nil) + if err != nil || res.IsError || res.Flatten() != `{"body":"","status":204}` { + t.Fatalf("after both approvals: %v %s", err, res.Flatten()) + } + if len(sourceUA) != 2 || len(redirectUA) != 1 { + t.Fatalf("after redirect approval, got %d initial requests and %d redirect requests", len(sourceUA), len(redirectUA)) + } + for _, got := range []string{<-sourceUA, <-sourceUA} { + if got != assessmentTestUA { + t.Errorf("initial origin received User-Agent %q, want %q", got, assessmentTestUA) + } + } + if got := <-redirectUA; got != goTestUA { + t.Errorf("redirect origin received User-Agent %q, want %q", got, goTestUA) + } + pins, err := g.m.pg.ListTargetPins(taskRef(t, task)) + if err != nil || len(pins) != 2 || !pins[0].NameOnlyEffective || !pins[1].NameOnlyEffective { + t.Fatalf("expected two name-only approvals for proxied traffic, got %+v, %v", pins, err) + } + + var rows []traffic.ExchangeMeta + waitUntil(t, "three recorded HTTP exchanges", func() bool { + var err error + rows, err = tr.Search("", 0, 10) + if err != nil { + t.Fatal(err) + } + return len(rows) >= 3 + }) + wantCount := map[string]int{sourceURL: 2, redirectURL: 1} + wantUA := map[string]string{sourceURL: assessmentTestUA, redirectURL: goTestUA} + for _, row := range rows { + raw, _, err := tr.Get(row.ID) + if err != nil { + t.Fatal(err) + } + req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(raw))) + if err != nil { + t.Fatalf("parse recorded request for %s: %v", row.URL, err) + } + if want := wantUA[row.URL]; want == "" || req.UserAgent() != want { + t.Errorf("recorded User-Agent for %s = %q, want %q", row.URL, req.UserAgent(), want) + } + wantCount[row.URL]-- + } + for target, remaining := range wantCount { + if remaining != 0 { + t.Errorf("unexpected number of recorded requests for %s, remaining expected = %d", target, remaining) + } + } +}