ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
Verify assessment labels on the wire and document SOC triage
James Khorfdd004152908
diff --git a/README.md b/README.mdindex 492701f..2414079 100644--- a/README.md+++ b/README.md@@ -534,6 +534,10 @@ every case.The **Target noise** card in System settings sets the profile at runtime (no restart) and shows theper-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+target requests so defenders can correlate them with an approved assessment. See the+[configuration and WAF triage guide](docs/assessment-identification.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 andexact rate/delay flags for the installed scanners. It tells them to test one host at a time, backdiff --git a/config.example.json b/config.example.jsonindex cc6166d..9d5ff6b 100644--- a/config.example.json+++ b/config.example.json@@ -1,5 +1,5 @@{- "_comment": "Copy as config.json (or point elsewhere with the ARTEX_CONFIG environment variable). This file only carries database and skill_dir; LLM and other settings come from environment variables or in-app settings, not this file.",+ "_comment": "Copy as config.json or set ARTEX_CONFIG to its path. This file configures PostgreSQL, the skill directory, and optional assessment identification.","_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": {@@ -19,5 +19,8 @@},"_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"+ "skill_dir": "/opt/artex/skills",++ "_comment_assessment_identification": "Leave empty to disable. To opt in, map a live task ID to a public engagement reference or an empty string for the base User-Agent. See docs/assessment-identification.md.",+ "assessment_identification": {}}diff --git a/config/assessment_identification_test.go b/config/assessment_identification_test.gonew file mode 100644index 0000000..fd51213--- /dev/null+++ b/config/assessment_identification_test.go@@ -0,0 +1,67 @@+package config++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestLoadAssessmentIdentification(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config.json")+ t.Setenv("ARTEX_CONFIG", path)+ cfg, err := Load()+ if err != nil || cfg.AssessmentIdentification.UserAgent("42") != "" {+ t.Fatalf("missing file: config = %+v, error = %v", cfg, err)+ }++ const maxReference = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._"+ body := `{"assessment_identification":{"42":"FS-17","43":"","44":"` + maxReference + `"}}`+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }+ cfg, err = Load()+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct{ taskID, want string }{+ {"42", "ARTEX-Assessment/1.0 (engagement=FS-17)"},+ {"43", "ARTEX-Assessment/1.0"},+ {"44", "ARTEX-Assessment/1.0 (engagement=" + maxReference + ")"},+ {"45", ""},+ {"", ""},+ } {+ if got := cfg.AssessmentIdentification.UserAgent(tc.taskID); got != tc.want {+ t.Errorf("task %q: User-Agent = %q, want %q", tc.taskID, got, tc.want)+ }+ }+}++func TestLoadRejectsInvalidAssessmentIdentification(t *testing.T) {+ for _, tc := range []struct {+ name, entries string+ }{+ {"empty task ID", `{"":"FS-17"}`},+ {"noncanonical task ID", `{"042":"FS-17"}`},+ {"zero task ID", `{"0":"FS-17"}`},+ {"non-task key", `{"*":"FS-17"}`},+ {"invalid shape", `["FS-17"]`},+ {"null engagement", `{"42":null}`},+ {"embedded line breaks", `{"42":"FS-17\r\nX-Other: value"}`},+ {"comment delimiters", `{"42":"FS-(17)"}`},+ {"non-ASCII label", `{"42":"équipe"}`},+ {"oversize label", `{"42":"` + strings.Repeat("A", 65) + `"}`},+ {"invalid entry alongside valid entry", `{"42":"FS-17","43":"FS 18"}`},+ } {+ 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 {+ 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)+ }+ })+ }+}diff --git a/docs/assessment-identification.md b/docs/assessment-identification.mdnew file mode 100644index 0000000..0c92aa6--- /dev/null+++ b/docs/assessment-identification.md@@ -0,0 +1,76 @@+# Assessment identification++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. Use an empty string for the base label or a 1–64 character public reference containing only ASCII letters, digits, dots, underscores, or hyphens. ARTEX validates this setting at startup and rejects an invalid file. Restart after editing. Remove a task's entry to disable identification for that task. Tasks absent from the map use their normal User-Agent behavior.++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.++```json+{+ "assessment_identification": {+ "123": "FS-17",+ "456": ""+ }+}+```++In this example, task `123` uses `ARTEX-Assessment/1.0 (engagement=FS-17)`. Task `456` uses `ARTEX-Assessment/1.0`. Use a reference that both teams can share and that is safe for the receiving service, intermediaries, and their logs. Keep credentials, personal data, and confidential ticket numbers in the private engagement record. See the configuration file search order in the [operations guide](OPS.md#2-configuration-precedence).++## Phase 1 coverage++The first phase covers ARTEX HTTP custom-tool requests with a matching live task ID. It also covers the HTTP enrichment probe if called with that task context. The current production code has no caller that enqueues this probe. Chat requests and editor tests use their normal User-Agent behavior.++An eligible HTTP custom tool can send the public label to its initial destination even with the target gate or noise profile off. Check the approved scope and initial destination before enabling the label. The HTTP custom tool keeps the generated label on same-origin redirects and removes it at the first cross-origin redirect and on subsequent hops. When enabled, the target gate evaluates each hop under its existing rules. The enrichment probe stops at redirects. Capture can help inspect the request where the route supports it.++The HTTP custom tool's existing explicit User-Agent setting takes precedence over the assessment label, including an explicitly empty value. With a noise profile active, a configured `ARTEX_TARGET_USER_AGENT` can still fill an empty value. See [configuration precedence](OPS.md#2-configuration-precedence).++WebFetch uses the Norma client's own User-Agent. Shell and external tools, browser traffic, replay, model and search providers, MCP, and management calls sit outside this phase.++Phase 1 acceptance uses local HTTP receivers to verify the exact wire value for each covered client, with the noise profile on and off and with direct and recorded routes where supported. Include unconfigured tasks, empty references, explicit User-Agents, same-origin and cross-origin redirects, and requests without a matching task context. Check that a task ID missing at startup stays disabled for that process and that a label applied to one task never carries over to another task or a replay.++## WAF triage for SOC, IR, and CIRT++1. Before testing, record the approved assets, UTC time window, permitted activity, and public reference. Share those details and the escalation contact with the defenders through the agreed channel. Treat the label as an optional field in the assessment record.+2. During triage, search for the exact User-Agent or engagement reference where the logger retains it. Check the timestamp, host, method, path, source IP, WAF action, rule ID, and request ID where available. Confirm which fields are retained and if they are redacted in your WAF. [AWS WAF field reference](https://docs.aws.amazon.com/waf/latest/developerguide/logging-fields.html)+3. Join the candidate events to the approved scope and UTC window. Corroborate individual events with evidence such as defender-issued request IDs and the operator's approved run record. Continue standard investigation for events with missing or conflicting evidence. Keep blocked and challenged requests visible for validation.++The User-Agent is self-declared metadata. Verify the engagement independently and leave authorization, authentication, WAF enforcement, alerting, and escalation decisions to the existing controls. A matching header alone cannot establish who sent a request or justify an allowlist entry.++## HackerOne reporting++1. Check the program's security page and the specific asset's scope and testing requirements. If the program specifies an exact User-Agent or another identification header, put that required header in the HTTP custom tool's request headers and check the effective value. Use the stable ARTEX label when the program permits it. [HackerOne security page guide](https://docs.hackerone.com/en/articles/8490833-security-page)+2. Submit through the program's report form and select the affected asset. Include the issue and impact, and add the exact identification value, UTC timestamps, safe request IDs, and sanitized request evidence where helpful. Share only the data the program needs to locate and validate the events. [HackerOne report submission guide](https://docs.hackerone.com/en/articles/8473994-submitting-reports)+3. Use the report thread for correlation questions and follow the program's instructions for any retest. [HackerOne post-submission guide](https://docs.hackerone.com/en/articles/15518592-post-submission-guide)++## Offline WAF log exercise++Use the rows below as a tabletop exercise. They represent fictional WAF records, with reserved TEST-NET addresses. No requests are sent. `assessment` abbreviates `ARTEX-Assessment/1.0 (engagement=FS-17)`, and `—` means the log has no User-Agent value for that event. [RFC 5737](https://www.rfc-editor.org/rfc/rfc5737.html)++The approved record for `FS-17` covers `shop.example.test` from `10:00` inclusive to `10:30` exclusive UTC on the same exercise day. The synthetic run record independently links defender-issued request IDs `W01`, `W02`, and `W03` to that window, host, and reference. Those three events are the exercise's known positives.++| Request ID | UTC time | Host | Source IP | User-Agent | WAF action |+| --- | --- | --- | --- | --- | --- |+| W01 | 10:03 | `shop.example.test` | `192.0.2.10` | assessment | Allow |+| W02 | 10:07 | `shop.example.test` | `198.51.100.24` | assessment | Block |+| W03 | 10:11 | `shop.example.test` | `198.51.100.24` | — | Challenge |+| W04 | 10:14 | `shop.example.test` | `203.0.113.9` | assessment | Block |+| W05 | 10:17 | `status.example.test` | `192.0.2.10` | assessment | Allow |+| W06 | 10:37 | `shop.example.test` | `192.0.2.10` | assessment | Block |+| W07 | 10:18 | `shop.example.test` | `203.0.113.9` | `ExampleClient/1.0` | Allow |++| Filter | Expected IDs | Compared with the known positives |+| --- | --- | --- |+| Exact User-Agent only | W01, W02, W04, W05, W06 | 2 matches, 3 false positives, 1 missed event |+| User-Agent, approved host, and UTC window | W01, W02, W04 | 2 matches, 1 false positive, 1 missed event |+| Run-record request IDs, approved host, and UTC window | W01, W02, W03 | 3 matches, 0 false positives, 0 missed events in this fixture |++`W04` still needs normal triage after the host and window filter. `W03` is recoverable through the request ID in the approved run record even though its User-Agent is missing from the log. The final join uses independent records already available in the exercise. In production, missing request IDs or incomplete records can leave the result unresolved.++## Phase 2 proposal for attributable proxy traffic++Revisit the capture-proxy route separately once it can bind each eligible shell request to a trusted task context and verify the destination against that task's approved scope. Internal attribution metadata should remain inside ARTEX. Apply the stable label once and define its precedence alongside existing proxy rewrite rules.++Before release, verify the header and scope decisions at local receivers for HTTP and intercepted HTTPS. Test same-scope and cross-scope redirects, concurrent tasks, unmarked traffic, direct shell paths, capture disabled, and replay. Include a built-in request already labelled in Phase 1 and verify that the proxy adds neither a second label nor task metadata on the wire. Document the verified routes and how an operator can inspect the outcome.diff --git a/enrich/assessment_identification_test.go b/enrich/assessment_identification_test.gonew file mode 100644index 0000000..13f980b--- /dev/null+++ b/enrich/assessment_identification_test.go@@ -0,0 +1,73 @@+package enrich++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Autumn-27/artex/egress"+ "github.com/Autumn-27/artex/intercept"+)++func TestAssessmentEnrichmentUserAgent(t *testing.T) {+ const taggedUA = "ARTEX-Assessment/1.0 (engagement=FS-17)"+ const legacyUA = "LegacyFixture/1.2"+ prev := egress.CurrentProfile()+ t.Cleanup(func() { egress.SetProfile(prev) })+ t.Setenv("ARTEX_TARGET_USER_AGENT", legacyUA)+ legacy, ok := egress.ProfileByName("balanced")+ if !ok {+ t.Fatal("balanced noise profile unavailable")+ }++ type observation struct{ path, ua string }+ received := make(chan observation, 16)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received <- observation{r.URL.Path, r.UserAgent()}+ if r.URL.Path == "/redirect" {+ http.Redirect(w, r, "/follow", http.StatusFound)+ return+ }+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(srv.Close)+ // The wire behavior only needs the real HTTP client. Use the existing+ // unreachable database fixture for the persistence step.+ e := &Engine{as: deadAssetStore(t), client: buildClient(nil)}++ for _, tc := range []struct {+ path, id, configuredUA, want string+ legacy bool+ }{+ {path: "/tagged", id: "42", configuredUA: taggedUA, want: taggedUA},+ {path: "/untagged", id: "43", want: "Go-http-client/1.1"},+ {path: "/base", id: "44", configuredUA: "ARTEX-Assessment/1.0", want: "ARTEX-Assessment/1.0"},+ {path: "/tagged-with-legacy", id: "42", configuredUA: taggedUA, legacy: true, want: taggedUA},+ {path: "/untagged-with-legacy", id: "43", legacy: true, want: legacyUA},+ {path: "/redirect", id: "42", configuredUA: taggedUA, want: taggedUA},+ } {+ t.Run(tc.path[1:], func(t *testing.T) {+ profile := egress.Profile{Name: "off"}+ if tc.legacy {+ profile = legacy+ }+ egress.SetProfile(profile)+ ctx := intercept.WithTargetScope(context.Background(), intercept.TargetScope{+ TaskID: tc.id, AssessmentUserAgent: tc.configuredUA,+ })+ e.doHTTP(ctx, 1, srv.URL+tc.path)+ select {+ case got := <-received:+ if want := (observation{tc.path, tc.want}); got != want {+ t.Errorf("observed %v, want %v", got, want)+ }+ default:+ t.Fatal("local server received no request")+ }+ if len(received) != 0 {+ t.Fatalf("unexpected additional requests: %d", len(received))+ }+ })+ }+}diff --git a/server/assessment_identification_test.go b/server/assessment_identification_test.gonew file mode 100644index 0000000..252688a--- /dev/null+++ b/server/assessment_identification_test.go@@ -0,0 +1,278 @@+package server++import (+ "context"+ "net"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strconv"+ "testing"+ "time"++ "github.com/Autumn-27/artex/db"+ "github.com/Autumn-27/artex/egress"+ "github.com/Autumn-27/artex/intercept"+ "github.com/Autumn-27/artex/traffic"+)++const (+ assessmentTestUA = "ARTEX-Assessment/1.0 (engagement=FS-17)"+ goTestUA = "Go-http-client/1.1"+ legacyTestUA = "LegacyFixture/1.2"+)++func runAssessmentHTTPTool(t *testing.T, s *Server, ctx context.Context, spec httpExec) {+ t.Helper()+ res, err := s.runHTTPTool(ctx, "assessment_label_test", execJSON(t, spec), nil, nil)+ if err != nil || res.IsError {+ t.Fatalf("HTTP custom tool failed: %v %s", err, res.Flatten())+ }+}++func TestAssessmentHTTPToolUserAgent(t *testing.T) {+ prev := egress.CurrentProfile()+ t.Cleanup(func() { egress.SetProfile(prev) })+ t.Setenv("ARTEX_TARGET_USER_AGENT", legacyTestUA)+ legacy, ok := egress.ProfileByName("balanced")+ if !ok {+ t.Fatal("balanced noise profile unavailable")+ }++ tagged := gatedCtx(&Task{ID: "42", assessmentUserAgent: assessmentTestUA}, 0)+ base := gatedCtx(&Task{ID: "43", assessmentUserAgent: "ARTEX-Assessment/1.0"}, 0)+ untagged := gatedCtx(&Task{ID: "44"}, 0)+ conversation := intercept.WithTargetScope(context.Background(), intercept.TargetScope{ConversationID: 42})+ for _, tc := range []struct {+ name string+ ctx context.Context+ headers map[string]string+ legacy bool+ want string+ }{+ {name: "tagged task, noise off", ctx: tagged, want: assessmentTestUA},+ {name: "configured without reference", ctx: base, want: "ARTEX-Assessment/1.0"},+ {name: "unconfigured task after tagged task", ctx: untagged, want: goTestUA},+ {name: "unscoped editor test", ctx: context.Background(), want: goTestUA},+ {name: "conversation ID equals configured task ID", ctx: conversation, want: goTestUA},+ {name: "tagged task, legacy configured", ctx: tagged, legacy: true, want: assessmentTestUA},+ {name: "unconfigured task, legacy configured", ctx: untagged, legacy: true, want: legacyTestUA},+ {name: "explicit UA", ctx: tagged, headers: map[string]string{"user-agent": "RequiredFixture/2.0"}, legacy: true, want: "RequiredFixture/2.0"},+ {name: "explicit empty UA", ctx: tagged, headers: map[string]string{"user-agent": ""}},+ {name: "explicit empty UA with legacy fallback", ctx: tagged, headers: map[string]string{"user-agent": ""}, legacy: true, want: legacyTestUA},+ {name: "tagged task repeated", ctx: tagged, want: assessmentTestUA},+ } {+ t.Run(tc.name, func(t *testing.T) {+ profile := egress.Profile{Name: "off"}+ if tc.legacy {+ profile = legacy+ }+ egress.SetProfile(profile)+ received := make(chan string, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received <- r.UserAgent()+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(srv.Close)+ runAssessmentHTTPTool(t, &Server{}, tc.ctx, httpExec{URL: srv.URL, Headers: tc.headers})+ select {+ case got := <-received:+ if got != tc.want {+ t.Errorf("wire User-Agent = %q, want %q", got, tc.want)+ }+ default:+ t.Fatal("local server received no request")+ }+ })+ }+}++func TestAssessmentHTTPToolRedirectIdentification(t *testing.T) {+ prev := egress.CurrentProfile()+ egress.SetProfile(egress.Profile{Name: "off"})+ t.Cleanup(func() { egress.SetProfile(prev) })++ type observation struct{ path, ua string }+ received := make(chan observation, 16)+ cross := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received <- observation{r.URL.Path, r.UserAgent()}+ http.Redirect(w, r, r.URL.Query().Get("return"), http.StatusFound)+ }))+ t.Cleanup(cross.Close)+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received <- observation{r.URL.Path, r.UserAgent()}+ switch r.URL.Path {+ case "/start":+ http.Redirect(w, r, "/same", http.StatusFound)+ case "/same":+ back := url.QueryEscape("http://" + r.Host + "/return")+ http.Redirect(w, r, cross.URL+"/cross?return="+back, http.StatusFound)+ default:+ w.WriteHeader(http.StatusNoContent)+ }+ }))+ t.Cleanup(origin.Close)+ ctx := gatedCtx(&Task{ID: "42", assessmentUserAgent: assessmentTestUA}, 0)+ runAssessmentHTTPTool(t, &Server{}, ctx, httpExec{URL: origin.URL + "/start"})+ for _, want := range []observation{+ {"/start", assessmentTestUA},+ {"/same", assessmentTestUA},+ {"/cross", goTestUA},+ {"/return", goTestUA},+ } {+ select {+ case got := <-received:+ if got != want {+ t.Errorf("observed %v, want %v", got, want)+ }+ default:+ t.Fatalf("local servers did not receive %s", want.path)+ }+ }+ if len(received) != 0 {+ t.Fatalf("unexpected additional redirect requests: %d", len(received))+ }+}++func TestAssessmentStartupScopesCurrentTasks(t *testing.T) {+ skipWithoutDSN(t)+ dsn, _, err := db.DSN()+ if err != nil {+ t.Fatal(err)+ }+ pg, err := db.Open(dsn)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = pg.Close() })+ addTask := func() *db.Task {+ t.Helper()+ task, err := pg.CreateTask("assessment identification fixture", "", nil, 0, 0)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })+ return task+ }+ tagged, untagged := addTask(), addTask()+ taggedID := strconv.FormatInt(tagged.ID, 10)+ 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]string{taggedID: "FS-17", futureID: "future"}}+ if err := os.WriteFile(cfgPath, execJSON(t, cfg), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("ARTEX_CONFIG", cfgPath)+ t.Setenv("ARTEX_PG_DSN", dsn)+ prev := egress.CurrentProfile()+ t.Cleanup(func() { egress.SetProfile(prev) })+ m, err := NewManager(t.TempDir(), "")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ m.Enrich().Close()+ _ = m.Close()+ })+ m.LoadExisting()+ created, err := m.CreateTask("assessment identification fixture created after startup", "", nil, 0, 0)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ id, _ := strconv.ParseInt(created.ID, 10, 64)+ _ = pg.DeleteTask(id)+ })+ if created.ID != futureID {+ t.Fatalf("fixture allocated task ID %s, expected next ID %s", created.ID, futureID)+ }+ for _, tc := range []struct{ id, want string }{+ {taggedID, assessmentTestUA},+ {untaggedID, ""},+ {futureID, ""},+ } {+ task, ok := m.Task(tc.id)+ if !ok {+ t.Fatalf("task %s unavailable", tc.id)+ }+ if got := task.targetScope(0).AssessmentUserAgent; got != tc.want {+ t.Errorf("task %s scope User-Agent = %q, want %q", tc.id, got, tc.want)+ }+ }+}++func TestAssessmentHTTPToolRecordingProxy(t *testing.T) {+ prev := egress.CurrentProfile()+ egress.SetProfile(egress.Profile{Name: "off"})+ t.Cleanup(func() { egress.SetProfile(prev) })+ received := make(chan string, 1)+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received <- r.UserAgent()+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(target.Close)++ 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)+ }+ tr, err := traffic.Open(t.TempDir(), addr)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = tr.Close() })+ startErr := make(chan error, 1)+ go func() { startErr <- tr.Start() }()+ deadline := time.Now().Add(3 * time.Second)+ for {+ select {+ case err := <-startErr:+ t.Fatalf("recording proxy stopped: %v", err)+ default:+ }+ conn, err := net.DialTimeout("tcp", addr, 100*time.Millisecond)+ if err == nil {+ _ = conn.Close()+ break+ }+ if time.Now().After(deadline) {+ t.Fatalf("recording proxy didn't start: %v", err)+ }+ time.Sleep(15 * time.Millisecond)+ }++ ctx := gatedCtx(&Task{ID: "42", assessmentUserAgent: assessmentTestUA}, 0)+ s := &Server{m: &Manager{traffic: tr, trafficOn: true}}+ const path = "/recorded-identification"+ runAssessmentHTTPTool(t, s, ctx, httpExec{URL: target.URL + path, UseRecordingProxy: true})+ select {+ case got := <-received:+ if got != assessmentTestUA {+ t.Errorf("wire User-Agent via recording proxy = %q, want %q", got, assessmentTestUA)+ }+ default:+ t.Fatal("local server received no request through the recording proxy")+ }++ deadline = time.Now().Add(3 * time.Second)+ for {+ rows, _, err := tr.Page(traffic.PageQuery{Path: path}, 0, 10)+ if err != nil {+ t.Fatal(err)+ }+ if len(rows) == 1 && rows[0].URL == target.URL+path {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("request did not appear in the recording proxy's traffic store")+ }+ time.Sleep(15 * time.Millisecond)+ }+}