Compare commits

...
Author SHA1 Message Date
BaaRai 3528287d61 enrich: route the HTTP probe through the pinned dialer (F13)
doHTTP now connects through intercept.PinnedDialer under the target scope of the request's context, so the probe uses the same pinned-address dial as the target gate. ProbeSite takes the context of the call that asks for the probe. A probe without a scope is refused; with the gate on, the probe bypasses the recording proxy so the dialer decides on the target itself. The path stays dormant: nothing calls ProbeSite on main.
2026-11-12 11:53:33 +01:00
BaaRai 2c1a49058e Merge pull request #196 from BaaRai/fix/auto-scope-hygiene
fix(coverage): count auto-scope only under a declared root (F8)
2026-11-12 11:03:10 +01:00
BaaRai 88306a0567 fix(tools): migrate the add_task_scope description on existing databases (F8)
add_task_scope is seeded through BuiltinToolSeeds, SeedTool inserts only
once, and ToolResolve serves the stored row, so existing installs kept the
old "this is the task's authorization boundary" text.

seedTaskScopeDescription runs from seedOrchestrationTools and updates the
description only:

  UPDATE tools SET description=$new, updated_at=now()
  WHERE key='add_task_scope' AND system AND description=$old

$old is the description as seeded at 0dc8bdf, kept verbatim; $new is the
code description from BuiltinToolSeeds. It is idempotent, a no-op when the
row is absent, and leaves an operator-edited description alone. It does not
use RefreshToolDefaults, which overwrites without condition.

TestTaskScopeDescriptionUpgrade (server, PG) covers the replacement, the
preserved custom text, an unchanged updated_at on a second run, and the
description ToolResolve serves to the planner.
2026-11-12 09:38:52 +01:00
BaaRai cd8a830b53 docs(coverage): say "declared domain or IP root" for auto-scope roots (F8)
declaredScopeFilter treats only root_domain, subdomain, ip and cidr rows as
roots. A declared company, icp or keyword row does not make an auto row
count, but the add_task_scope description said "a goal target or scope
added here or manually". The description and the code comments now say
"declared domain or IP root" and name the kinds that act as roots.
2026-11-12 09:38:52 +01:00
BaaRai 37fab18809 fix(coverage): count auto-scope only under a declared root (F8)
Auto task_scope rows (source='auto') come from insert_assets and intent
asset_ids, i.e. from target-derived content. They now count toward the
coverage denominator and list_untested_assets only when they sit under a
root the same task declared (a non-auto row: goal target registered via
add_task_scope, or manual scope): the same or a deeper domain of a declared
root_domain/subdomain, or a net inside a declared ip/cidr.

The direct-source coverage view also stops counting an asset from an intent
anchor alone; fact anchors still count, so tested evidence is unchanged.
Without this, insert_assets put a planted host back into the backlog
through its intent anchor.

task_scope is described as "coverage scope, not enforced" in the code
comments, the add_task_scope description, the goal-decomposer tail and the
task overview UI, instead of "authorization boundary".

Audit F8, 0.7.0.
2026-11-12 07:37:58 +01:00
BaaRai 0dc8bdf179 Merge pull request #195 from BaaRai/feat/derived-field-envelope
agent: frame agent-derived fields in a per-message nonce envelope (#124, F3)
2026-11-12 07:26:56 +01:00
15 changed files with 401 additions and 28 deletions
+106
View File
@@ -0,0 +1,106 @@
package agent
import (
"fmt"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
)
// TestTaskScopeLabelIsHonest pins the task_scope wording while the RoE is not
// back: the tool text and the goals tail call it coverage scope, not enforced, and
// no longer claim an authorization boundary.
func TestTaskScopeLabelIsHonest(t *testing.T) {
texts := map[string]string{
"add_task_scope": NewToolSet(nil, "").addTaskScope().Description(),
"goalsScopeTail": goalsScopeTail,
}
for name, text := range texts {
if !strings.Contains(text, taskScopeLabel) {
t.Errorf("%s lacks %q", name, taskScopeLabel)
}
if strings.Contains(text, "authorization boundary") {
t.Errorf("%s still claims an authorization boundary", name)
}
}
}
// TestAutoScopeOutsideDeclaredRootExcluded: a worker inserts one host under the
// declared root and one host outside it. Both get an auto scope row and an intent
// anchor, but only the host under the declared root enters the coverage
// denominator and list_untested_assets.
func TestAutoScopeOutsideDeclaredRootExcluded(t *testing.T) {
d := testDB(t)
defer d.Close()
stamp := time.Now().UnixNano()
declared := fmt.Sprintf("app.f8-%d.invalid", stamp)
inside := "v1." + declared
outsideRoot := fmt.Sprintf("f8-planted-%d.invalid", stamp)
outside := "x." + outsideRoot
task, err := d.CreateTask("auto scope hygiene", "test "+declared, nil, 0, 0)
if err != nil {
t.Fatal(err)
}
assets := d.Assets()
t.Cleanup(func() {
_ = d.DeleteTask(task.ID)
_, _ = d.Exec(`DELETE FROM assets WHERE domain IN ($1,$2,$3) OR root_domain IN ($4,$5)`,
declared, inside, outside, fmt.Sprintf("f8-%d.invalid", stamp), outsideRoot)
})
// The goal target, as the goal decomposer registers it through add_task_scope.
if _, err := assets.AddAgentScope(task.ID, "subdomain", declared, "goal target", "agent"); err != nil {
t.Fatal(err)
}
store := d.Exploration(task.ExplorationID)
intentID, err := store.AddNode(db.KindIntent, map[string]any{"summary": "recon"}, 0, "open", "planner", nil)
if err != nil {
t.Fatal(err)
}
worker := NewToolSet(store, "worker")
worker.SetTaskID(task.ID)
worker.SetAssetStore(assets, d.Companies())
worker.SetOwnerNode(intentID)
out := callInsertAssets(t, worker, map[string]any{"assets": []any{
map[string]any{"type": "subdomain", "domain": inside},
map[string]any{"type": "subdomain", "domain": outside},
}})
if errs, _ := out["errors"].([]any); len(errs) > 0 {
t.Fatalf("insert_assets errors: %v", errs)
}
scope, err := assets.ListTaskScope(task.ID)
if err != nil {
t.Fatal(err)
}
autoRows := map[string]bool{}
for _, row := range scope {
if row.Source == "auto" {
autoRows[row.Domain] = true
}
}
if !autoRows[inside] || !autoRows[outside] {
t.Fatalf("both hosts should be auto-scoped: %+v", scope)
}
planner := NewToolSet(store, "planner")
planner.SetTaskID(task.ID)
planner.SetAssetStore(assets, d.Companies())
coverage, ok := planner.graphOverviewData()["coverage"].(map[string]any)
if !ok {
t.Fatal("coverage block missing from graph overview")
}
if got := coverage["denominator"]; got != 1 {
t.Fatalf("coverage denominator = %v, want 1 (only %s)", got, inside)
}
untested := fmt.Sprint(callReadJSON(t, planner.listUntestedAssets(), `{"page":1,"page_size":50}`))
if !strings.Contains(untested, inside) {
t.Fatalf("host under the declared root missing from list_untested_assets: %s", untested)
}
if strings.Contains(untested, outsideRoot) {
t.Fatalf("host outside the declared root listed as untested: %s", untested)
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ Call set_goals to submit the results.`
const goalsScopeTail = `
**Extra duty: register the test asset scope**
Besides decomposing goals, you must also identify the **explicitly stated test asset scope** from the "task goal / task description" and register it via add_task_scope (this task's authorization boundary, and also the denominator of asset test coverage). **Minimal-scope principle: register only the one target the user explicitly named — never enlarge it on your own.**
Besides decomposing goals, you must also identify the **explicitly stated test asset scope** from the "task goal / task description" and register it via add_task_scope (this task's ` + taskScopeLabel + `: the denominator of asset test coverage, and the root under which auto-added hosts count). **Minimal-scope principle: register only the one target the user explicitly named — never enlarge it on your own.**
- The goal is a URL or a host-bearing address (e.g. https://xxx.example.com/path, app.example.com) → take its **full hostname**, kind=subdomain, value=full hostname.
Example: goal https://a1b2c3.lab.example.net/path → kind=subdomain, value=a1b2c3.lab.example.net (**not** example.net).
**Never** shrink a subdomain-bearing hostname to its root domain — registering all of example.com upon seeing xxx.example.com expands the scope beyond the user's target, violating the minimal-scope principle.
+1 -1
View File
@@ -221,7 +221,7 @@ func (t *ToolSet) SetNotifyFinding(fn func(int64, string)) { t.notifyFinding = f
// enrich). Kept as an interface here to avoid coupling agent → enrich.
type EnrichTrigger interface {
ResolveDomain(id int64, host string)
ProbeSite(id int64, url string)
ProbeSite(ctx context.Context, id int64, url string)
}
// WriteCounts breaks down what a worker persisted this run, by node kind, so the
+12 -3
View File
@@ -364,6 +364,11 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
// inserted by the worker at top level, adding a conservative scope per its
// type; side-effect-derived assets don't go through here, so the scope
// doesn't widen blindly. No-op when taskID=0.
// The item may come from target content, so this auto row counts toward
// coverage and list_untested_assets only under a declared domain or IP
// root (a non-auto root_domain/subdomain/ip/cidr row: goal target,
// add_task_scope or manual scope, see db.declaredScopeFilter). task_scope is
// coverage scope, not enforced: nothing blocks a call outside it.
// Independent of the coverage switch: task_scope is the task's range
// boundary (the filter basis for list/query); the coverage switch only
// decides whether to use it as the denominator for metrics, not whether
@@ -436,16 +441,20 @@ func (t *ToolSet) addCompanyScope() actool.CoreTool {
)
}
// taskScopeLabel is the honest description of task_scope while the RoE is not back:
// it drives coverage and asset filters, and nothing enforces it on tool calls.
const taskScopeLabel = "coverage scope, not enforced"
// addTaskScope lets the plan agent add test scope to THE CURRENT TASK — the coverage
// denominator and the task's authorization edge. Worker discoveries are auto-scoped
// denominator (coverage scope, not enforced). Worker discoveries are auto-scoped
// (precise host) by insertAssets; this tool is for DELIBERATELY WIDENING: pull a whole
// root domain or whole company into scope, or add a specific subdomain / ip.
func (t *ToolSet) addTaskScope() actool.CoreTool {
return writeTool(
"add_task_scope",
"Add test scope to [this task] — this is the task's authorization boundary, and also the denominator of asset test coverage.\n"+
"Add test scope to [this task] — "+taskScopeLabel+": it is the denominator of asset test coverage; nothing blocks a tool call outside it.\n"+
"Supported kinds: company (all assets under the company) / root_domain (a whole root domain, including all subdomains) / subdomain (a single precise subdomain) / ip / cidr / icp / keyword.\n"+
"Note: hosts a worker touches one by one are [automatically] added to the scope by the system (precise subdomains); this tool is for [deliberate widening] — pulling in a whole root domain / whole company, or adding a specific subdomain/IP.\n"+
"Note: hosts a worker touches one by one are [automatically] added to the scope by the system (precise subdomains), but they count toward coverage and list_untested_assets only under a declared domain or IP root (a root_domain/subdomain/ip/cidr goal target or scope added here or manually; a company/icp/keyword entry is not such a root); this tool is for [deliberate widening] — pulling in a whole root domain / whole company, or adding a specific subdomain/IP.\n"+
"value: for company pass the company name or id (the company must already exist); for root_domain/subdomain pass a domain; for ip/cidr pass an IP or range; for icp/keyword pass an ICP number or company keyword.\n"+
"Always give reason explaining the basis (auditable). Use the entries array for multiple entries.",
obj(map[string]any{
+3
View File
@@ -454,6 +454,9 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
// test scope (same conservative granularity as insertAssets). upsertTaskScope's
// ON CONFLICT DO NOTHING + the uq_task_scope unique index guarantee no
// duplicate additions; reruns/retries are idempotent no-ops as well.
// asset_ids can trace back to target content, so these auto rows count
// toward coverage only under a declared domain or IP root (db.declaredScopeFilter);
// coverage scope, not enforced.
// When the asset-coverage feature is off, the test scope (denominator) is no
// longer accumulated.
if coverageEnabled {
+2 -1
View File
@@ -754,12 +754,13 @@ WHERE t.active_llm_profile_id IS NULL
AND t.llm_profile_id IS NOT NULL
AND EXISTS (SELECT 1 FROM task_llm_profiles x WHERE x.task_id=t.id AND x.profile_id=t.llm_profile_id);
-- Task test scope (the asset-coverage denominator + authorization boundary).
-- Task test scope (the asset-coverage denominator; coverage scope, not enforced).
-- Auto-filled (source='auto'): insertAssets' top level adds a conservative scope per asset type explicitly
-- inserted by the worker (root_domain→root_domain, subdomain/service/endpoint→subdomain(host), ip→ip);
-- side-effect-derived assets do not enter the scope (the hook sits at the handler top level; derivation is internal to the db layer).
-- Agent-filled (source='agent'): add_task_scope adds company/root_domain/subdomain/ip.
-- Coverage = among assets matching active rows (denominator), the share anchored by fact nodes (numerator).
-- An auto row is active only under a declared (non-auto) domain or IP root of the same task (declaredScopeFilter in task_scope.go).
CREATE TABLE IF NOT EXISTS task_scope (
id BIGSERIAL PRIMARY KEY,
task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
+6 -3
View File
@@ -37,12 +37,13 @@ target AS (
))
)
JOIN context_tasks ctx ON ctx.task_id=ts.task_id
WHERE ` + declaredScopeFilter + `
UNION
SELECT a.id, a.type,
COALESCE(a.url, a.domain, a.ip, a.app_name, a.root_domain, '') AS label
FROM assets a
JOIN exploration_anchors ea ON ea.asset_id=a.id
JOIN exploration_nodes en ON en.id=ea.node_id
JOIN exploration_nodes en ON en.id=ea.node_id AND en.kind='fact'
JOIN context_tasks ctx ON ctx.exploration_id=en.exploration_id
),
tested AS (
@@ -118,8 +119,10 @@ ORDER BY CASE WHEN ts.task_id=$1 THEN 0 ELSE 1 END, ts.id`, taskID)
}
// TaskCoverageWithSources computes one coverage view over the union of the
// current task and its direct sources: source scopes and anchored assets extend
// the denominator, while fact anchors count as tested. No row is copied.
// current task and its direct sources: source scopes and fact-anchored assets
// extend the denominator, while fact anchors count as tested. Auto scope rows
// count only under a declared domain or IP root (declaredScopeFilter), and an intent anchor
// alone (insert_assets, asset_ids) no longer adds an asset. No row is copied.
func (s *AssetStore) TaskCoverageWithSources(taskID int64) (*Coverage, error) {
cov := &Coverage{ByType: []CoverageByType{}}
_ = s.db.QueryRow(`WITH `+directTaskContextCTE+`
+30 -7
View File
@@ -8,10 +8,14 @@ import (
"strings"
)
// TaskScope is one row of a task's test scope — the coverage denominator and the
// per-task authorization edge. Rows come either from insertAssets (source='auto',
// conservative, one per explicitly-inserted asset) or from the add_task_scope tool
// (source='agent', for company / domain / network / ICP / keyword scope).
// TaskScope is one row of a task's test scope — coverage scope, not enforced: it is
// the coverage denominator and the filter for asset queries, and nothing blocks a
// tool call outside it. Rows come from insertAssets / intent asset_ids (source='auto',
// conservative, one per explicitly-inserted asset), from the add_task_scope tool
// (source='agent': the goal targets the decomposer registers, or planner widening),
// or from the operator (source='manual'). An auto row counts toward coverage only
// under a declared domain or IP root (a non-auto root_domain/subdomain/ip/cidr row),
// see declaredScopeFilter.
type TaskScope struct {
ID int64 `json:"id"`
TaskID int64 `json:"task_id"`
@@ -105,6 +109,8 @@ func (s *AssetStore) upsertTaskScope(ts TaskScope) error {
// asset item (source='auto'). MUST be called only from insertAssets' top-level loop —
// never from a db-layer side effect (linkHostAssets), so derived assets do not blindly expand the scope.
// Rule: scope granularity follows the asset's own type. taskID<=0 → no-op.
// The asset comes from target-derived content, so the row counts toward coverage and
// list_untested_assets only under a declared domain or IP root (declaredScopeFilter).
func (s *AssetStore) AddAutoScope(taskID int64, assetType, domain, rawURL, ip string) error {
if taskID <= 0 {
return nil
@@ -274,8 +280,9 @@ type CoverageByType struct {
}
// Coverage is a task's rough asset test coverage — a reference figure for the agent,
// NOT a precise metric. Denominator = assets matching any active task_scope row;
// Tested = those anchored to at least one fact node in the exploration.
// NOT a precise metric. Denominator = assets matching a declared task_scope row or an
// auto row under a declared domain or IP root (declaredScopeFilter); Tested = those anchored to at
// least one fact node in the exploration.
type Coverage struct {
Enabled bool `json:"enabled"` // whether the asset coverage feature is on; when false the other fields are zero
ScopeRows int `json:"scope_rows"` // 0 → scope not anchored
@@ -299,6 +306,22 @@ func (s *AssetStore) CoverageEnabled(taskID int64) bool {
return enabled
}
// declaredScopeFilter keeps a task_scope row ts in the coverage match only when it is
// declared (source<>'auto': goal targets registered through add_task_scope, or manual
// scope) or when it is an auto row under a domain or IP root the same task declared:
// the same or a deeper domain of a declared root_domain/subdomain, or a net inside a
// declared ip/cidr. A declared company, icp or keyword row is not a root here. Auto
// rows come from target-derived content (insert_assets, intent asset_ids), so
// anything else stays out of the coverage denominator and list_untested_assets.
const declaredScopeFilter = `(ts.source <> 'auto' OR EXISTS (
SELECT 1 FROM task_scope d
WHERE d.task_id = ts.task_id AND d.source <> 'auto' AND (
(d.kind IN ('root_domain','subdomain') AND ts.domain IS NOT NULL
AND (ts.domain = d.domain OR right(ts.domain, length(d.domain)+1) = '.' || d.domain))
OR (d.kind IN ('ip','cidr') AND ts.net IS NOT NULL AND ts.net <<= d.net)
)
))`
// task_scope→assets match predicate, reused by the count / by-type / untested queries. $1=taskID.
const covTargetCTE = `
target AS (
@@ -314,7 +337,7 @@ target AS (
lower(regexp_replace(COALESCE(a.icp,''), '[[:space:]]+', '', 'g')) = ts.value
OR lower(regexp_replace(COALESCE(a.app_icp,''), '[[:space:]]+', '', 'g')) = ts.value
))
)
) AND ` + declaredScopeFilter + `
),
tested AS (
SELECT DISTINCT ea.asset_id
+24 -9
View File
@@ -7,6 +7,7 @@
package enrich
import (
"context"
"crypto/tls"
"html"
"io"
@@ -20,6 +21,7 @@ import (
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/miekg/dns"
"github.com/projectdiscovery/dnsx/libs/dnsx"
@@ -34,8 +36,9 @@ const (
type job struct {
kind jobKind
id int64 // asset id (domain for DNS, site for HTTP)
arg string // host (DNS) or url (HTTP)
id int64 // asset id (domain for DNS, site for HTTP)
arg string // host (DNS) or url (HTTP)
ctx context.Context // HTTP: carries the target scope the probe dials under
}
// Engine owns the resolver, the proxy-routed HTTP client, and the worker pool.
@@ -90,15 +93,23 @@ func New(as *db.AssetStore, proxy func() string, workers int) *Engine {
// buildClient returns an HTTP client that dials via the recording proxy (resolved
// per-request via proxy(), so the traffic-capture toggle applies live) and skips
// TLS verification (the proxy re-signs with its MITM CA; targets are often
// self-signed — this is a pentest probe).
// self-signed — this is a pentest probe). Every connection goes through
// intercept.PinnedDialer, under the target scope of the request's context: a
// probe without a scope is refused. When the scope's gate is on, the probe
// connects to the target itself, without the proxy, so that the dialer decides
// on the target and connects only to the addresses a pin covers.
func buildClient(proxy func() string) *http.Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
TLSHandshakeTimeout: httpTimeout,
DialContext: intercept.PinnedDialer("enrich", true),
}
if proxy != nil {
tr.Proxy = func(*http.Request) (*url.URL, error) {
tr.Proxy = func(req *http.Request) (*url.URL, error) {
if intercept.GateOn(req.Context()) {
return nil, nil // direct: the dialer decides on the target
}
p := proxy()
if p == "" {
return nil, nil // direct
@@ -116,10 +127,14 @@ func buildClient(proxy func() string) *http.Client {
// ResolveDomain enqueues a DNS resolution for a domain asset (ungated). host is the
// FQDN. No-op for an empty engine.
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host}) }
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host, nil}) }
// ProbeSite enqueues an HTTP probe for a web-asset (site). rawURL is the site URL.
func (e *Engine) ProbeSite(id int64, rawURL string) { e.enqueue(job{jobHTTP, id, rawURL}) }
// ctx carries the target scope of the call that asks for the probe: the probe
// connects under that scope (see buildClient).
func (e *Engine) ProbeSite(ctx context.Context, id int64, rawURL string) {
e.enqueue(job{jobHTTP, id, rawURL, ctx})
}
func (e *Engine) enqueue(j job) {
if e == nil || id0(j.id) || j.arg == "" {
@@ -155,7 +170,7 @@ func (e *Engine) worker() {
case jobDNS:
e.doDNS(j.id, j.arg)
case jobHTTP:
e.doHTTP(j.id, j.arg)
e.doHTTP(j.ctx, j.id, j.arg)
}
}
}
@@ -221,12 +236,12 @@ func (e *Engine) doDNS(id int64, host string) {
var reTitle = regexp.MustCompile(`(?is)<title[^>]*>(.*?)</title>`)
func (e *Engine) doHTTP(id int64, rawURL string) {
func (e *Engine) doHTTP(ctx context.Context, id int64, rawURL string) {
host := hostOf(rawURL)
if host == "" {
return
}
req, err := http.NewRequest("GET", rawURL, nil)
req, err := http.NewRequestWithContext(ctx, "GET", rawURL, nil)
if err != nil {
return
}
+56
View File
@@ -0,0 +1,56 @@
package intercept_test
import (
"context"
"net"
"slices"
"testing"
"time"
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/intercept"
)
// F13: the HTTP probe of the enrich engine connects through the pinned dialer.
// A probe without a target scope is refused and dials nothing; a probe under a
// gated scope dials the address the pin holds, never the name, and not the
// recording proxy. Without a database: no address reached here is served, so
// no probe writes to the asset store.
func TestEnrichProbeDialsThroughPinnedDialer(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
proxyAddr := l.Addr().String() // closed: a dial to it is refused
l.Close()
for _, tc := range []struct {
name string
proxy func() string
}{
{"direct", nil},
{"recording proxy set", func() string { return "http://" + proxyAddr }},
} {
t.Run(tc.name, func(t *testing.T) {
g := intercept.NewDialGate(t)
g.Resolve("app.example.com", "203.0.113.7")
g.Pin("app.example.com", 8080, "203.0.113.7")
g.Exempt("http://" + proxyAddr)
e := enrich.New(nil, tc.proxy, 1)
t.Cleanup(e.Close)
// One worker: the probe without a scope runs to its end first.
e.ProbeSite(context.Background(), 1, "http://app.example.com:8080/")
e.ProbeSite(g.Ctx(), 2, "http://app.example.com:8080/")
deadline := time.Now().Add(5 * time.Second)
for len(g.Calls()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
time.Sleep(100 * time.Millisecond)
if got := g.Calls(); !slices.Equal(got, []string{"203.0.113.7:8080"}) {
t.Fatalf("dialled %v, want the pinned address only, through the pinned dialer", got)
}
})
}
}
+33
View File
@@ -0,0 +1,33 @@
package intercept
import (
"context"
"testing"
)
// DialGate exposes the pinned-dial fixture of target_dial_test.go to the tests
// of package intercept_test, which may import the packages that import
// intercept (enrich).
type DialGate struct {
g *gateFixture
rec *dialRecorder
}
func NewDialGate(t *testing.T) *DialGate {
g, rec := dialGate(t)
return &DialGate{g: g, rec: rec}
}
// Ctx returns a context carrying the fixture's target scope, gate on.
func (d *DialGate) Ctx() context.Context { return d.g.ctx() }
func (d *DialGate) Pin(host string, port int, ips ...string) { d.g.pin(host, port, ips...) }
func (d *DialGate) Resolve(host string, ips ...string) { d.g.res.set(host, ips...) }
func (d *DialGate) Exempt(urls ...string) {
d.g.ic.SetDerivedExemptions(func() []string { return urls })
}
// Calls returns every address the base dialer was asked to connect to.
func (d *DialGate) Calls() []string { return d.rec.calls() }
+29
View File
@@ -572,6 +572,7 @@ func (s *Server) seedOrchestrationTools() {
s.seedFindingVerificationSchema() // S1: poe_level / evidence_quotes on update_finding_report, added once per DB
s.seedFindingEvidenceSchema() // optional counterevidence / confidence_rationale on report_finding, added once per DB
s.seedFactSourceSchema() // source enum on record_fact, added once per DB
s.seedTaskScopeDescription() // add_task_scope: "coverage scope, not enforced" replaces the authorization-boundary text
// Note: pentest's default tool bindings need no migration — BuiltinToolSeeds already seeds
// list_assets/insert_assets/report_finding/list_findings/list_companies together with
// pentest at fresh initialization (no old DBs exist in this project, so no migration).
@@ -612,6 +613,34 @@ WHERE key='record_fact' AND system AND NOT(COALESCE(schema->'properties','{}'::j
}
}
// oldTaskScopeDescription is the add_task_scope description as seeded up to commit
// 0dc8bdf, which called task_scope the task's authorization boundary. Kept verbatim:
// seedTaskScopeDescription replaces only a row that still holds exactly this text.
const oldTaskScopeDescription = "Add test scope to [this task] — this is the task's authorization boundary, and also the denominator of asset test coverage.\n" +
"Supported kinds: company (all assets under the company) / root_domain (a whole root domain, including all subdomains) / subdomain (a single precise subdomain) / ip / cidr / icp / keyword.\n" +
"Note: hosts a worker touches one by one are [automatically] added to the scope by the system (precise subdomains); this tool is for [deliberate widening] — pulling in a whole root domain / whole company, or adding a specific subdomain/IP.\n" +
"value: for company pass the company name or id (the company must already exist); for root_domain/subdomain pass a domain; for ip/cidr pass an IP or range; for icp/keyword pass an ICP number or company keyword.\n" +
"Always give reason explaining the basis (auditable). Use the entries array for multiple entries."
// seedTaskScopeDescription brings the add_task_scope description of existing
// databases to the code text (SeedTool is first-insert only, and ToolResolve serves
// the stored description, so without this the model would keep reading
// "authorization boundary"). Idempotent: only a system row still holding the old
// seeded text is replaced; an absent row or an operator-edited text is left alone.
func (s *Server) seedTaskScopeDescription() {
for _, seed := range agent.BuiltinToolSeeds() {
if seed.Key != "add_task_scope" {
continue
}
_, err := s.m.pg.Exec(`UPDATE tools SET description=$1,updated_at=now()
WHERE key='add_task_scope' AND system AND description=$2`, seed.Desc, oldTaskScopeDescription)
if err != nil {
log.Printf("[tools] upgrade add_task_scope description: %v", err)
}
return
}
}
// refreshBuiltinToolSchemas propagates code schema/description changes on the
// orchestration + platform tools into already-seeded rows ONCE per version flag —
// SeedTool is first-insert-only, so a new param (e.g. spawn_task's llm_profile) never
+95
View File
@@ -0,0 +1,95 @@
package server
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
)
// PG: on an existing database whose add_task_scope row still holds the old
// "authorization boundary" text, the startup seeders replace it with the code
// description; an operator-edited description is preserved; a second run changes
// nothing; and ToolResolve then serves the new description to the model.
func TestTaskScopeDescriptionUpgrade(t *testing.T) {
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
ctx, cancel := context.WithCancel(context.Background())
cancel()
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
t.Cleanup(func() { agent.ToolResolve = nil })
pg := m.pg
var want string
for _, seed := range agent.BuiltinToolSeeds() {
if seed.Key == "add_task_scope" {
want = seed.Desc
}
}
if want == "" || want == oldTaskScopeDescription {
t.Fatalf("precondition: code description must exist and differ from the old text: %q", want)
}
old, err := pg.GetTool("add_task_scope")
if err != nil || old == nil {
t.Fatal("missing add_task_scope", err)
}
bindings, _ := json.Marshal(old.Agents)
t.Cleanup(func() { pg.UpdateTool(old.Key, old.Description, old.Schema, bindings, old.Enabled) })
snapshot := func() (string, time.Time) {
var desc string
var upd time.Time
if err := pg.QueryRow(`SELECT description, updated_at FROM tools WHERE key='add_task_scope'`).Scan(&desc, &upd); err != nil {
t.Fatal(err)
}
return desc, upd
}
// An existing install still holding the old seeded text is upgraded.
if err := pg.UpdateTool("add_task_scope", oldTaskScopeDescription, old.Schema, bindings, true); err != nil {
t.Fatal(err)
}
s.seedOrchestrationTools()
desc1, upd1 := snapshot()
if desc1 != want {
t.Fatalf("old description not replaced: %q", desc1)
}
s.seedOrchestrationTools()
desc2, upd2 := snapshot()
if desc2 != desc1 || !upd2.Equal(upd1) {
t.Fatalf("second run changed the row: %q %v -> %q %v", desc1, upd1, desc2, upd2)
}
if got := resolvedTaskScopeDescription(t); got != want {
t.Fatalf("ToolResolve serves %q, want the new description", got)
}
// An operator-edited description is left alone.
if err := pg.UpdateTool("add_task_scope", "operator description", old.Schema, bindings, true); err != nil {
t.Fatal(err)
}
s.seedOrchestrationTools()
if desc, _ := snapshot(); desc != "operator description" {
t.Fatalf("operator description overwritten: %q", desc)
}
}
// resolvedTaskScopeDescription returns add_task_scope's description as
// ToolResolve serves it to the planner.
func resolvedTaskScopeDescription(t *testing.T) string {
t.Helper()
tools := agent.ToolResolve(context.Background(), "planner", agent.NewToolSet(nil, "").PlannerTools())
for _, tl := range tools {
if tl.Name() == "add_task_scope" {
return tl.Description()
}
}
t.Fatal("planner lost add_task_scope")
return ""
}
@@ -805,13 +805,13 @@ export function OverviewTab({ taskId }: { taskId: string }) {
)}
</CardContent>
</Card>
{/* Test scope: coverage denominator + authorization boundary; can be edited manually. */}
{/* Test scope: coverage denominator (coverage scope, not enforced); can be edited manually. */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheckIcon className="size-4 text-emerald-500" /> Test scope
<span className="text-muted-foreground text-xs font-normal">
(coverage denominator + authorization boundary, {scope.length} in total)
(coverage scope, not enforced, {scope.length} in total)
</span>
</CardTitle>
</CardHeader>
+1 -1
View File
@@ -350,7 +350,7 @@ export interface WorkspaceFile {
content?: string;
}
// One row of a task's test scope (coverage denominator + authorization boundary).
// One row of a task's test scope (coverage denominator; coverage scope, not enforced).
export interface TaskScopeRow {
id: number;
task_id: number;