mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-25 17:30:56 +08:00
Merge pull request #509 from jamesKhor/feat/assessment-identification
Add a per-task scanner User-Agent for approved sites
This commit is contained in:
@@ -557,6 +557,10 @@ 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`.
|
||||
|
||||
**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/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
|
||||
exact rate/delay flags for the installed scanners. It tells them to test one host at a time, back
|
||||
|
||||
+5
-2
@@ -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 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": {
|
||||
@@ -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_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": {}
|
||||
}
|
||||
|
||||
+15
-8
@@ -1,5 +1,5 @@
|
||||
// Package config loads runtime configuration from a JSON file, with environment
|
||||
// variables taking precedence. Currently it carries the PostgreSQL connection.
|
||||
// variables taking precedence where supported.
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -29,8 +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"`
|
||||
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
|
||||
@@ -116,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:
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const assessmentUserAgent = "ARTEX-Assessment/1.0"
|
||||
|
||||
var (
|
||||
assessmentReference = regexp.MustCompile(`^[A-Za-z0-9._-]{0,64}$`)
|
||||
asciiDNSLabel = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$`)
|
||||
)
|
||||
|
||||
// TaskUserAgents maps opted-in task IDs to their allowed origins and label.
|
||||
type TaskUserAgents map[string]AssessmentIdentity
|
||||
|
||||
func (a *TaskUserAgents) UnmarshalJSON(data []byte) error {
|
||||
var entries map[string]AssessmentIdentity
|
||||
if err := json.Unmarshal(data, &entries); err != nil {
|
||||
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("task_user_agents task IDs must be positive integers written without a sign or leading zeroes")
|
||||
}
|
||||
}
|
||||
*a = entries
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssessmentIdentity holds a task's validated assessment identifier and allowed
|
||||
// HTTP(S) origins. The zero value is disabled.
|
||||
type AssessmentIdentity struct {
|
||||
userAgent string
|
||||
origins map[string]struct{}
|
||||
}
|
||||
|
||||
func (a *AssessmentIdentity) UnmarshalJSON(data []byte) error {
|
||||
var entry struct {
|
||||
Reference json.RawMessage `json:"reference"`
|
||||
Origins []string `json:"origins"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &entry); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(entry.Origins) == 0 {
|
||||
return errors.New("each task requires a nonempty origins list")
|
||||
}
|
||||
ua := assessmentUserAgent
|
||||
if entry.Reference != nil {
|
||||
var ref *string
|
||||
if err := json.Unmarshal(entry.Reference, &ref); err != nil || ref == nil || !assessmentReference.MatchString(*ref) {
|
||||
return errors.New("reference must be an empty string or contain 1 to 64 characters from A-Z, a-z, 0-9, dot, underscore and hyphen")
|
||||
}
|
||||
if *ref != "" {
|
||||
ua += " (engagement=" + *ref + ")"
|
||||
}
|
||||
}
|
||||
origins := make(map[string]struct{}, len(entry.Origins))
|
||||
for i, raw := range entry.Origins {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawPath != "" || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") {
|
||||
return fmt.Errorf("origins entry %d must be an exact HTTP(S) origin without credentials, path, query or fragment", i+1)
|
||||
}
|
||||
key := assessmentOriginKey(u)
|
||||
if key == "" {
|
||||
return fmt.Errorf("origins entry %d requires HTTP(S), an ASCII DNS name or IP address, and a valid port", i+1)
|
||||
}
|
||||
origins[key] = struct{}{}
|
||||
}
|
||||
*a = AssessmentIdentity{userAgent: ua, origins: origins}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UserAgent returns the stable identifier for this assessment identity.
|
||||
func (a AssessmentIdentity) UserAgent() string { return a.userAgent }
|
||||
|
||||
// AllowsOrigin reports whether the URL belongs to a configured origin.
|
||||
func (a AssessmentIdentity) AllowsOrigin(u *url.URL) bool {
|
||||
if len(a.origins) == 0 {
|
||||
return false
|
||||
}
|
||||
_, ok := a.origins[assessmentOriginKey(u)]
|
||||
return ok
|
||||
}
|
||||
|
||||
// SameAssessmentOrigin compares URLs using the same rules as the origin list.
|
||||
func SameAssessmentOrigin(a, b *url.URL) bool {
|
||||
key := assessmentOriginKey(a)
|
||||
return key != "" && key == assessmentOriginKey(b)
|
||||
}
|
||||
|
||||
func assessmentOriginKey(u *url.URL) string {
|
||||
if u == nil || u.Opaque != "" || strings.HasSuffix(u.Host, ":") {
|
||||
return ""
|
||||
}
|
||||
var port string
|
||||
switch u.Scheme {
|
||||
case "http":
|
||||
port = "80"
|
||||
case "https":
|
||||
port = "443"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if p := u.Port(); p != "" {
|
||||
n, err := strconv.ParseUint(p, 10, 16)
|
||||
if err != nil || n == 0 || strconv.FormatUint(n, 10) != p {
|
||||
return ""
|
||||
}
|
||||
port = p
|
||||
}
|
||||
host := u.Hostname()
|
||||
bracketed := strings.HasPrefix(u.Host, "[")
|
||||
if addr, err := netip.ParseAddr(host); err == nil {
|
||||
if addr.Zone() != "" || addr.Is6() != bracketed {
|
||||
return ""
|
||||
}
|
||||
host = addr.String()
|
||||
} else {
|
||||
if bracketed || len(host) > 253 {
|
||||
return ""
|
||||
}
|
||||
for label := range strings.SplitSeq(host, ".") {
|
||||
if !asciiDNSLabel.MatchString(label) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
host = strings.ToLower(host) // the label check ensures ASCII-only folding
|
||||
}
|
||||
return u.Scheme + "://" + net.JoinHostPort(host, port)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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.TaskUserAgents) != 0 {
|
||||
t.Fatalf("missing file: config = %+v, error = %v", cfg, err)
|
||||
}
|
||||
|
||||
const maxReference = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._"
|
||||
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"]},
|
||||
"45":{"origins":["https://shop.example.test"]}
|
||||
}}`
|
||||
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", "ARTEX-Assessment/1.0"},
|
||||
{"46", ""},
|
||||
{"", ""},
|
||||
} {
|
||||
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.TaskUserAgents["42"]
|
||||
for _, tc := range []struct {
|
||||
rawURL string
|
||||
want bool
|
||||
}{
|
||||
{"https://shop.example.test/order?status=ok", true},
|
||||
{"http://[2001:0db8::1]:8080/order", true},
|
||||
{"http://shop.example.test/order", false},
|
||||
{"https://shop.example.test:8443/order", false},
|
||||
{"https://shop.example.test.evil.test/order", false},
|
||||
{"https://SHOP.example.test./order", false},
|
||||
} {
|
||||
u, err := url.Parse(tc.rawURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := identity.AllowsOrigin(u); got != tc.want {
|
||||
t.Errorf("allows %q = %v, want %v", tc.rawURL, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidTaskUserAgents(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, entries string
|
||||
}{
|
||||
{"empty task ID", `{"":{"origins":["https://test.example"]}}`},
|
||||
{"noncanonical task ID", `{"042":{"origins":["https://test.example"]}}`},
|
||||
{"zero task ID", `{"0":{"origins":["https://test.example"]}}`},
|
||||
{"non-task key", `{"*":{"origins":["https://test.example"]}}`},
|
||||
{"invalid shape", `["FS-17"]`},
|
||||
{"shorthand without origin", `{"42":"FS-17"}`},
|
||||
{"null identity", `{"42":null}`},
|
||||
{"null reference", `{"42":{"reference":null,"origins":["https://test.example"]}}`},
|
||||
{"embedded line breaks", `{"42":{"reference":"FS-17\r\nX-Other: value","origins":["https://test.example"]}}`},
|
||||
{"comment delimiters", `{"42":{"reference":"FS-(17)","origins":["https://test.example"]}}`},
|
||||
{"non-ASCII label", `{"42":{"reference":"équipe","origins":["https://test.example"]}}`},
|
||||
{"oversize label", `{"42":{"reference":"` + strings.Repeat("A", 65) + `","origins":["https://test.example"]}}`},
|
||||
{"missing origins", `{"42":{"reference":"FS-17"}}`},
|
||||
{"empty origins", `{"42":{"origins":[]}}`},
|
||||
{"null origin", `{"42":{"origins":[null]}}`},
|
||||
{"origin credentials", `{"42":{"origins":["https://user:testpass@test.example"]}}`},
|
||||
{"origin path", `{"42":{"origins":["https://test.example/path"]}}`},
|
||||
{"origin query", `{"42":{"origins":["https://test.example?"]}}`},
|
||||
{"origin fragment", `{"42":{"origins":["https://test.example#part"]}}`},
|
||||
{"Unicode origin", `{"42":{"origins":["https://K.example.test"]}}`},
|
||||
{"origin with ambiguous port", `{"42":{"origins":["https://test.example:0443"]}}`},
|
||||
{"invalid entry alongside valid entry", `{"42":{"origins":["https://test.example"]},"43":{"origins":["ftp://test.example"]}}`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.json")
|
||||
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(), "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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
# 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 `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
|
||||
{
|
||||
"task_user_agents": {
|
||||
"123": {
|
||||
"origins": ["https://shop.example.test"],
|
||||
"reference": "FS-17"
|
||||
},
|
||||
"456": {
|
||||
"origins": ["http://status.example.test:8080"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
On their listed origins, task `123` uses `ARTEX-Assessment/1.0 (engagement=FS-17)` and 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 and a listed destination origin. It also covers the HTTP enrichment probe if called with that task context for a listed origin. The current production code has no caller that enqueues this probe. Chat requests and editor tests use their normal User-Agent behavior.
|
||||
|
||||
The origin list also applies with the target gate or noise profile off. Check the approved scope and origin list before enabling the label. The HTTP custom tool retains the generated label while a redirect chain stays on its initial origin. A change of origin removes the label for the rest of the chain, even if the next origin is listed. 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, model and search providers, MCP, and management calls sit outside this phase.
|
||||
|
||||
### Manual replay
|
||||
|
||||
Manual replay can resend an operator-selected assessment label from a capture even after the URL is edited. Review the destination and headers before sending and remove the label when it is inappropriate for that destination. Automatic label generation applies only to the task request paths above. [Replay behavior](traffic-rewrite-rules.md#replay)
|
||||
|
||||
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, listed and unlisted destinations, redirects, and requests without a matching task context. Check that a task ID missing at startup stays disabled for that process, generated labels stay within their configured task and origins, and manual replay sends the selected User-Agent without generating an assessment label.
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,96 @@
|
||||
package enrich
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"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)
|
||||
handler := 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)
|
||||
})
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
outside := httptest.NewServer(handler)
|
||||
t.Cleanup(outside.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)}
|
||||
identity := func(reference string) config.AssessmentIdentity {
|
||||
var value config.AssessmentIdentity
|
||||
raw := fmt.Sprintf(`{"reference":%q,"origins":[%q]}`, reference, srv.URL)
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
tagged, base := identity("FS-17"), identity("")
|
||||
|
||||
for _, tc := range []struct {
|
||||
path, id string
|
||||
identity config.AssessmentIdentity
|
||||
want string
|
||||
legacy bool
|
||||
outside bool
|
||||
}{
|
||||
{path: "/tagged", id: "42", identity: tagged, want: taggedUA},
|
||||
{path: "/untagged", id: "43", want: "Go-http-client/1.1"},
|
||||
{path: "/base", id: "44", identity: base, want: "ARTEX-Assessment/1.0"},
|
||||
{path: "/tagged-with-legacy", id: "42", identity: tagged, legacy: true, want: taggedUA},
|
||||
{path: "/untagged-with-legacy", id: "43", legacy: true, want: legacyUA},
|
||||
{path: "/redirect", id: "42", identity: tagged, want: taggedUA},
|
||||
{path: "/outside", id: "42", identity: tagged, outside: true, want: "Go-http-client/1.1"},
|
||||
} {
|
||||
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, AssessmentIdentity: tc.identity,
|
||||
})
|
||||
target := srv
|
||||
if tc.outside {
|
||||
target = outside
|
||||
}
|
||||
e.doHTTP(ctx, 1, target.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))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -248,6 +248,7 @@ func (e *Engine) doHTTP(ctx context.Context, id int64, rawURL string) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
intercept.ApplyAssessmentUserAgent(req)
|
||||
resp, err := e.client.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package intercept
|
||||
|
||||
import "net/http"
|
||||
|
||||
// ApplyAssessmentUserAgent adds the task's configured identifier to a target
|
||||
// request. An explicitly supplied User-Agent, including an empty one, takes
|
||||
// precedence. It reports whether it inserted the identifier.
|
||||
func ApplyAssessmentUserAgent(req *http.Request) bool {
|
||||
scope, ok := TargetScopeFromContext(req.Context())
|
||||
if !ok || scope.TaskID == "" || scope.ConversationID != 0 || !scope.AssessmentIdentity.AllowsOrigin(req.URL) {
|
||||
return false
|
||||
}
|
||||
if _, explicit := req.Header["User-Agent"]; explicit {
|
||||
return false
|
||||
}
|
||||
req.Header.Set("User-Agent", scope.AssessmentIdentity.UserAgent())
|
||||
return true
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
@@ -97,6 +98,8 @@ type TargetScope struct {
|
||||
Enabled func() bool
|
||||
WaitBound time.Duration
|
||||
Interceptor *Interceptor
|
||||
|
||||
AssessmentIdentity config.AssessmentIdentity // operator-configured identity of this task only
|
||||
}
|
||||
|
||||
// WithTargetScope returns a child context carrying the target-gate scope of the
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"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 assessmentTaskContext(t *testing.T, id, reference string, origins ...string) context.Context {
|
||||
t.Helper()
|
||||
var identity config.AssessmentIdentity
|
||||
raw := execJSON(t, map[string]any{"reference": reference, "origins": origins})
|
||||
if err := json.Unmarshal(raw, &identity); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return gatedCtx(&Task{ID: id, assessmentIdentity: identity}, 0)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
received := make(chan string, 16)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
received <- r.UserAgent()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
tagged := assessmentTaskContext(t, "42", "FS-17", srv.URL)
|
||||
base := assessmentTaskContext(t, "43", "", srv.URL)
|
||||
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)
|
||||
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 := assessmentTaskContext(t, "42", "FS-17", origin.URL, cross.URL)
|
||||
runAssessmentHTTPTool(t, &Server{}, ctx, httpExec{URL: origin.URL + "/start"})
|
||||
ctx = assessmentTaskContext(t, "42", "FS-17", origin.URL)
|
||||
back := url.QueryEscape(origin.URL + "/return")
|
||||
runAssessmentHTTPTool(t, &Server{}, ctx, httpExec{URL: cross.URL + "/outside?return=" + back})
|
||||
for _, want := range []observation{
|
||||
{"/start", assessmentTestUA},
|
||||
{"/same", assessmentTestUA},
|
||||
{"/cross", goTestUA},
|
||||
{"/return", goTestUA},
|
||||
{"/outside", 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 TestAssessmentHTTPToolDoesNotLabelUnicodeOrigin(t *testing.T) {
|
||||
prev := egress.CurrentProfile()
|
||||
egress.SetProfile(egress.Profile{Name: "off"})
|
||||
t.Cleanup(func() { egress.SetProfile(prev) })
|
||||
|
||||
// The local HTTP proxy receives the request without resolving the target.
|
||||
// Unicode case folding of the Kelvin sign must not expand k.example.test.
|
||||
received := make(chan string, 1)
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
received <- r.UserAgent()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(proxy.Close)
|
||||
ctx := assessmentTaskContext(t, "42", "FS-17", "http://k.example.test")
|
||||
runAssessmentHTTPTool(t, &Server{}, ctx, httpExec{
|
||||
URL: "http://K.example.test/check", Proxy: proxy.URL,
|
||||
})
|
||||
select {
|
||||
case got := <-received:
|
||||
if got != goTestUA {
|
||||
t.Errorf("wire User-Agent for Unicode origin = %q, want %q", got, goTestUA)
|
||||
}
|
||||
default:
|
||||
t.Fatal("local proxy received no request")
|
||||
}
|
||||
}
|
||||
|
||||
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("scanner User-Agent 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{"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"}},
|
||||
}}
|
||||
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("scanner User-Agent 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)
|
||||
}
|
||||
scope := task.targetScope(0)
|
||||
if got := scope.AssessmentIdentity.UserAgent(); 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 := assessmentTaskContext(t, "42", "FS-17", target.URL)
|
||||
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)
|
||||
}
|
||||
}
|
||||
+23
-2
@@ -18,6 +18,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/egress"
|
||||
"github.com/Autumn-27/artex/guard"
|
||||
@@ -580,6 +581,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
||||
client := &http.Client{Timeout: timeoutOr(spec.TimeoutMs, 30000)}
|
||||
// Every redirect hop goes through the target gate, as the rendered URL did.
|
||||
client.CheckRedirect = intercept.RedirectCheck(key)
|
||||
if intercept.ApplyAssessmentUserAgent(req) {
|
||||
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
|
||||
}
|
||||
// The current egress governor paces every request and redirect hop per host
|
||||
// under the noise profile (off by default: the base transport itself). It is
|
||||
// resolved per request, so a changed profile applies to the next call.
|
||||
@@ -599,6 +603,19 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
||||
return actool.Text(actool.Capture(tc, string(b))), nil
|
||||
}
|
||||
|
||||
// assessmentRedirectCheck sheds the generated identifier on the first redirect
|
||||
// to another origin. net/http copies headers from the initial request for each
|
||||
// hop, so check the previous hop to keep the identifier off after that point.
|
||||
func assessmentRedirectCheck(check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||
return func(req *http.Request, via []*http.Request) error {
|
||||
previous := via[len(via)-1]
|
||||
if previous.Header.Get("User-Agent") == "" || !config.SameAssessmentOrigin(previous.URL, req.URL) {
|
||||
req.Header.Del("User-Agent")
|
||||
}
|
||||
return check(req, via)
|
||||
}
|
||||
}
|
||||
|
||||
// httpToolTransport is the transport of one http tool call, or nil
|
||||
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
|
||||
// dials the proxy, which makes the connection to the target. A direct call in
|
||||
@@ -629,9 +646,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 == "" {
|
||||
@@ -643,6 +662,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) {
|
||||
|
||||
+37
-3
@@ -82,6 +82,8 @@ type Task struct {
|
||||
targetGate atomic.Bool
|
||||
interceptor *intercept.Interceptor // owner of the target gate, handed to the scope
|
||||
|
||||
assessmentIdentity config.AssessmentIdentity // assigned by the manager before publishing the task
|
||||
|
||||
// pendingTriggers accumulates the concrete changes (worker done / finding) that
|
||||
// fired planning rounds since the last one consumed them. The debounce coalesces
|
||||
// a burst into one round, so several may pile up before drainTriggers() clears them.
|
||||
@@ -262,6 +264,8 @@ type Manager struct {
|
||||
enrich *enrich.Engine // engine-side asset auto-completion (DNS/HTTP)
|
||||
interceptor *intercept.Interceptor // user-configured tool-call interception rules
|
||||
|
||||
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.
|
||||
rewriteMu sync.Mutex
|
||||
@@ -397,6 +401,10 @@ func (m *Manager) Enrich() *enrich.Engine { return m.enrich }
|
||||
// NewManager connects to PostgreSQL and, if proxyAddr is non-empty, starts the
|
||||
// traffic-recording proxy. PostgreSQL is required (it is the single data source).
|
||||
func NewManager(dir, proxyAddr string) (*Manager, error) {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Resolve the data dir to an ABSOLUTE path up front. Every data path derives
|
||||
// from it — notably the MITM CA cert, whose path is injected into worker shells
|
||||
// (SSL_CERT_FILE/CURL_CA_BUNDLE) and read by WebFetch. A relative path (the
|
||||
@@ -418,6 +426,20 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 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.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 task_user_agents task ID %s: %w", taskID, err)
|
||||
}
|
||||
if task == nil {
|
||||
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.
|
||||
if err := pg.InitSecrets(config.KeyDir()); err != nil {
|
||||
pg.Close()
|
||||
@@ -434,7 +456,10 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
||||
if err := pg.EnsureLLMUsageTable(); err != nil {
|
||||
log.Printf("[llmusage] create table: %v", err)
|
||||
}
|
||||
m := &Manager{dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg)}
|
||||
m := &Manager{
|
||||
dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg),
|
||||
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
|
||||
// approval is name-only.
|
||||
@@ -1007,12 +1032,21 @@ func taskFromPG(pt *pgdb.Task, store *pgdb.ExplorationStore, ic *intercept.Inter
|
||||
return t
|
||||
}
|
||||
|
||||
func (m *Manager) taskFromPG(pt *pgdb.Task) *Task {
|
||||
t := taskFromPG(pt, m.pg.Exploration(pt.ExplorationID), m.interceptor)
|
||||
t.assessmentIdentity = m.taskUserAgents[t.ID]
|
||||
return t
|
||||
}
|
||||
|
||||
// targetScope is the approval scope of this task's tool calls for the target
|
||||
// gate. wait bounds how long a gated call may wait for a human decision.
|
||||
// Enabled reads the task's opt-in flag on every call, so a switch through the
|
||||
// API takes effect on the next tool call.
|
||||
func (t *Task) targetScope(wait time.Duration) intercept.TargetScope {
|
||||
return intercept.TargetScope{TaskID: t.ID, Enabled: t.targetGate.Load, WaitBound: wait, Interceptor: t.interceptor}
|
||||
return intercept.TargetScope{
|
||||
TaskID: t.ID, Enabled: t.targetGate.Load, WaitBound: wait, Interceptor: t.interceptor,
|
||||
AssessmentIdentity: t.assessmentIdentity,
|
||||
}
|
||||
}
|
||||
|
||||
// searchBackendEndpoints are the endpoints of the search backends. The
|
||||
@@ -1292,7 +1326,7 @@ func (m *Manager) LoadExisting() []*Task {
|
||||
if _, ok := m.tasks[id]; ok {
|
||||
continue
|
||||
}
|
||||
t := taskFromPG(pt, m.pg.Exploration(pt.ExplorationID), m.interceptor)
|
||||
t := m.taskFromPG(pt)
|
||||
m.tasks[id] = t
|
||||
loaded = append(loaded, t)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user