Identify approved assessment tasks in native HTTP requests

This commit is contained in:
James Khor
2026-11-23 17:45:26 +08:00
parent 565f448b58
commit 6ef25b22b1
7 changed files with 147 additions and 6 deletions
+52
View File
@@ -0,0 +1,52 @@
package config
import (
"encoding/json"
"errors"
"regexp"
"strconv"
)
const assessmentUserAgent = "ARTEX-Assessment/1.0"
var assessmentReference = regexp.MustCompile(`^[A-Za-z0-9._-]{0,64}$`)
// 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
func (a *AssessmentIdentification) UnmarshalJSON(data []byte) error {
var entries map[string]*string
if err := json.Unmarshal(data, &entries); err != nil {
return errors.New("assessment_identification must be an object mapping task IDs to public engagement references")
}
if entries == nil {
*a = nil
return nil
}
references := make(AssessmentIdentification, len(entries))
for taskID, reference := 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
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 {
return ""
}
if reference == "" {
return assessmentUserAgent
}
return assessmentUserAgent + " (engagement=" + reference + ")"
}
+4 -3
View File
@@ -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"`
AssessmentIdentification AssessmentIdentification `json:"assessment_identification,omitempty"`
}
// BaseDir is the directory that anchors all runtime artifacts (config.json and
+1
View File
@@ -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
+18
View File
@@ -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.AssessmentUserAgent == "" {
return false
}
if _, explicit := req.Header["User-Agent"]; explicit {
return false
}
req.Header.Set("User-Agent", scope.AssessmentUserAgent)
return true
}
+2
View File
@@ -97,6 +97,8 @@ type TargetScope struct {
Enabled func() bool
WaitBound time.Duration
Interceptor *Interceptor
AssessmentUserAgent string // operator-configured identifier of this task only
}
// WithTargetScope returns a child context carrying the target-gate scope of the
+33
View File
@@ -579,6 +579,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.
@@ -598,6 +601,36 @@ 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") == "" || !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
+37 -3
View File
@@ -82,6 +82,8 @@ 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
// 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
assessmentIdentification config.AssessmentIdentification // 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.AssessmentIdentification {
id, _ := strconv.ParseInt(taskID, 10, 64) // validated when the config was loaded
task, err := pg.GetTask(id)
if err != nil {
pg.Close()
return nil, fmt.Errorf("check assessment_identification task ID %s: %w", taskID, err)
}
if task == nil {
log.Printf("[config] assessment_identification task ID %s is unavailable, ignoring its entry", taskID)
delete(cfg.AssessmentIdentification, 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),
assessmentIdentification: cfg.AssessmentIdentification,
}
// 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.assessmentUserAgent = m.assessmentIdentification.UserAgent(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,
AssessmentUserAgent: t.assessmentUserAgent,
}
}
// 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)
}