Limit generated assessment labels to configured HTTP origins

This commit is contained in:
James Khor
2026-11-23 17:55:39 +08:00
parent fdd0041529
commit f90db65430
10 changed files with 289 additions and 93 deletions
+1 -1
View File
@@ -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 a public engagement reference or an empty string for the base User-Agent. See docs/assessment-identification.md.",
"_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": {}
}
+113 -24
View File
@@ -3,50 +3,139 @@ 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}$`)
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])?$`)
)
// AssessmentIdentification maps task IDs to optional public engagement references.
// An absent task ID opts out. An empty reference opts in with the base identifier.
type AssessmentIdentification map[string]string
// AssessmentIdentification maps opted-in task IDs to their allowed origins and label.
type AssessmentIdentification map[string]AssessmentIdentity
func (a *AssessmentIdentification) UnmarshalJSON(data []byte) error {
var entries map[string]*string
var entries map[string]AssessmentIdentity
if err := json.Unmarshal(data, &entries); err != nil {
return errors.New("assessment_identification must be an object mapping task IDs to public engagement references")
return fmt.Errorf("assessment_identification: %w", err)
}
if entries == nil {
*a = nil
return nil
}
references := make(AssessmentIdentification, len(entries))
for taskID, reference := range entries {
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")
}
if reference == nil || !assessmentReference.MatchString(*reference) {
return errors.New("assessment_identification references must be empty strings or contain 1 to 64 characters from A-Z, a-z, 0-9, dot, underscore and hyphen")
}
references[taskID] = *reference
}
*a = references
*a = entries
return nil
}
// UserAgent returns the identifier configured for taskID, or empty if it is not enabled.
func (a AssessmentIdentification) UserAgent(taskID string) string {
reference, ok := a[taskID]
if !ok {
// 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 ""
}
if reference == "" {
return assessmentUserAgent
var port string
switch u.Scheme {
case "http":
port = "80"
case "https":
port = "443"
default:
return ""
}
return assessmentUserAgent + " (engagement=" + reference + ")"
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)
}
+53 -14
View File
@@ -1,6 +1,7 @@
package config
import (
"net/url"
"os"
"path/filepath"
"strings"
@@ -11,12 +12,17 @@ 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") != "" {
if err != nil || len(cfg.AssessmentIdentification) != 0 {
t.Fatalf("missing file: config = %+v, error = %v", cfg, err)
}
const maxReference = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._"
body := `{"assessment_identification":{"42":"FS-17","43":"","44":"` + maxReference + `"}}`
body := `{"assessment_identification":{
"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)
}
@@ -28,30 +34,63 @@ func TestLoadAssessmentIdentification(t *testing.T) {
{"42", "ARTEX-Assessment/1.0 (engagement=FS-17)"},
{"43", "ARTEX-Assessment/1.0"},
{"44", "ARTEX-Assessment/1.0 (engagement=" + maxReference + ")"},
{"45", ""},
{"45", "ARTEX-Assessment/1.0"},
{"46", ""},
{"", ""},
} {
if got := cfg.AssessmentIdentification.UserAgent(tc.taskID); got != tc.want {
identity := cfg.AssessmentIdentification[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"]
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 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"}`},
{"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"]`},
{"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"}`},
{"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")
+19 -8
View File
@@ -4,32 +4,43 @@ An authorized assessment can opt in to a stable ARTEX User-Agent on supported ta
## 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.
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.
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.
```json
{
"assessment_identification": {
"123": "FS-17",
"456": ""
"123": {
"origins": ["https://shop.example.test"],
"reference": "FS-17"
},
"456": {
"origins": ["http://status.example.test:8080"]
}
}
}
```
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).
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. 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.
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.
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 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, replay, model and search providers, MCP, and management calls sit outside this phase.
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.
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.
### 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
+33 -10
View File
@@ -2,10 +2,13 @@ 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"
)
@@ -23,29 +26,45 @@ func TestAssessmentEnrichmentUserAgent(t *testing.T) {
type observation struct{ path, ua string }
received := make(chan observation, 16)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
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, configuredUA, want string
legacy bool
path, id string
identity config.AssessmentIdentity
want string
legacy bool
outside bool
}{
{path: "/tagged", id: "42", configuredUA: taggedUA, want: taggedUA},
{path: "/tagged", id: "42", identity: tagged, 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: "/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", configuredUA: taggedUA, want: taggedUA},
{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"}
@@ -54,9 +73,13 @@ func TestAssessmentEnrichmentUserAgent(t *testing.T) {
}
egress.SetProfile(profile)
ctx := intercept.WithTargetScope(context.Background(), intercept.TargetScope{
TaskID: tc.id, AssessmentUserAgent: tc.configuredUA,
TaskID: tc.id, AssessmentIdentity: tc.identity,
})
e.doHTTP(ctx, 1, srv.URL+tc.path)
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 {
+2 -2
View File
@@ -7,12 +7,12 @@ import "net/http"
// 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.AssessmentUserAgent == "" {
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.AssessmentUserAgent)
req.Header.Set("User-Agent", scope.AssessmentIdentity.UserAgent())
return true
}
+2 -1
View File
@@ -24,6 +24,7 @@ import (
"sync"
"time"
"github.com/Autumn-27/artex/config"
"github.com/Autumn-27/artex/db"
)
@@ -98,7 +99,7 @@ type TargetScope struct {
WaitBound time.Duration
Interceptor *Interceptor
AssessmentUserAgent string // operator-configured identifier of this task only
AssessmentIdentity config.AssessmentIdentity // operator-configured identity of this task only
}
// WithTargetScope returns a child context carrying the target-gate scope of the
+61 -12
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
@@ -12,6 +13,7 @@ import (
"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"
@@ -32,6 +34,16 @@ func runAssessmentHTTPTool(t *testing.T, s *Server, ctx context.Context, spec ht
}
}
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) })
@@ -41,8 +53,15 @@ func TestAssessmentHTTPToolUserAgent(t *testing.T) {
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)
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 {
@@ -70,12 +89,6 @@ func TestAssessmentHTTPToolUserAgent(t *testing.T) {
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:
@@ -114,13 +127,18 @@ func TestAssessmentHTTPToolRedirectIdentification(t *testing.T) {
}
}))
t.Cleanup(origin.Close)
ctx := gatedCtx(&Task{ID: "42", assessmentUserAgent: assessmentTestUA}, 0)
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:
@@ -136,6 +154,33 @@ func TestAssessmentHTTPToolRedirectIdentification(t *testing.T) {
}
}
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()
@@ -161,7 +206,10 @@ 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]string{taggedID: "FS-17", futureID: "future"}}
cfg := map[string]any{"assessment_identification": 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)
}
@@ -198,7 +246,8 @@ func TestAssessmentStartupScopesCurrentTasks(t *testing.T) {
if !ok {
t.Fatalf("task %s unavailable", tc.id)
}
if got := task.targetScope(0).AssessmentUserAgent; got != tc.want {
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)
}
}
@@ -248,7 +297,7 @@ func TestAssessmentHTTPToolRecordingProxy(t *testing.T) {
time.Sleep(15 * time.Millisecond)
}
ctx := gatedCtx(&Task{ID: "42", assessmentUserAgent: assessmentTestUA}, 0)
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})
+2 -18
View File
@@ -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"
@@ -607,30 +608,13 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
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") == "" || !sameAssessmentOrigin(previous.URL, req.URL) {
if previous.Header.Get("User-Agent") == "" || !config.SameAssessmentOrigin(previous.URL, req.URL) {
req.Header.Del("User-Agent")
}
return check(req, via)
}
}
func sameAssessmentOrigin(a, b *url.URL) bool {
// IPv6 zone names are case-sensitive even though host names are not.
aHost, aZone, _ := strings.Cut(a.Hostname(), "%")
bHost, bZone, _ := strings.Cut(b.Hostname(), "%")
return a.Scheme == b.Scheme && strings.EqualFold(aHost, bHost) && aZone == bZone && assessmentPort(a) == assessmentPort(b)
}
func assessmentPort(u *url.URL) string {
if p := u.Port(); p != "" {
return p
}
if u.Scheme == "https" {
return "443"
}
return "80"
}
// 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
+3 -3
View File
@@ -82,7 +82,7 @@ type Task struct {
targetGate atomic.Bool
interceptor *intercept.Interceptor // owner of the target gate, handed to the scope
assessmentUserAgent string // assigned by the manager before publishing the task
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
@@ -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.assessmentUserAgent = m.assessmentIdentification.UserAgent(t.ID)
t.assessmentIdentity = m.assessmentIdentification[t.ID]
return t
}
@@ -1045,7 +1045,7 @@ func (m *Manager) taskFromPG(pt *pgdb.Task) *Task {
func (t *Task) targetScope(wait time.Duration) intercept.TargetScope {
return intercept.TargetScope{
TaskID: t.ID, Enabled: t.targetGate.Load, WaitBound: wait, Interceptor: t.interceptor,
AssessmentUserAgent: t.assessmentUserAgent,
AssessmentIdentity: t.assessmentIdentity,
}
}