Merge remote-tracking branch 'upstream/main' into codex/s3-task-archives

This commit is contained in:
Chubboy Ren
2026-11-19 03:33:51 +00:00
56 changed files with 2433 additions and 88 deletions
+35
View File
@@ -25,6 +25,13 @@ All notable changes to this project are documented in this file. The format is b
- **Release provenance**: release archives carry GitHub build provenance attestations and a CycloneDX SBOM (`gh attestation verify <zip> --repo BaaRai/ARTEX`); release notes are the matching `CHANGELOG.md` section (#219, #201).
- **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`.
- **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays go through the proxy, so the rules apply to them. Archives, a per-replay rule toggle, the web UI and the proof flag come later.
- **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289).
- **Traffic replay** (#266): replay a recorded request from the traffic detail with its method, URL, headers and stored body; replay is disabled when only the body preview is loaded.
- **Finding proof strength in reports** (#268): the Markdown report and the export show each finding's proof strength next to its verification status.
- **Opt-in Keenable web search backend** (#295): the search tool gains Keenable alongside Brave and Tavily; the key is stored encrypted and can be cleared independently.
- **Durable activity outbox** (#300): activity rows that cannot be stored are written to the new `activity_outbox` table (migration `0006_activity_outbox.sql`) and replayed once on the next start. The server stops admitting new work before the drain, and a shutdown cancel leaves an in-flight intent claim running so the next start can reset it to open instead of recording it as done or blocked.
- **LLM model search** (#284): the System → LLM model picker can search the model list, and the API-key field opts out of password-manager autofill.
- **Finding report state** (#308): findings carry a `report_state` (`none`, `submitted`, `accepted`, `rejected`, `duplicate`) for what was sent to a bug bounty program, separate from the triage status; the bulk update accepts both fields, and restoring an older archive fills `none` (migration `0007_finding_report_state.sql`).
### Changed
@@ -33,16 +40,44 @@ All notable changes to this project are documented in this file. The format is b
- **Untrusted-output boundary is now on by default**: Norma frames tool results for the worker, planner, chat and main agent unless `ARTEX_UNTRUSTED_BOUNDARY` is set to `0`, `false`, `off` or `no`. It was opt-in via `ARTEX_UNTRUSTED_BOUNDARY=1` in 0.6.0 (#166); the default flips here (#203).
- **Versioned migrations**: the `db` package applies numbered `db/migrations/NNNN_slug.sql` files once, in order, under the schema advisory lock, and records a SHA-256 checksum in `schema_migrations`; missing, renamed, changed or out-of-order migrations fail closed (#226).
- **Coverage graph performance**: the coverage graph batches its connector lookups (three queries instead of one per root and per company) and adds the partial index `idx_ts_icp`; on a task of about 3,000 assets the p50 dropped from 126 ms to 27 ms and the queries per call from 221 to 3 (#230).
- **Request body bounds** (#305): JSON request bodies decode at most 32 MiB, every non-multipart body is capped, and an oversized body answers 413 instead of a generic bad request. `ReadTimeout` bounds how long headers and the body may take to arrive without cutting a handler that is already running.
- **Chat attachments up to 512 MiB** (#252): the client, server, compose file and reverse-proxy sample agree on a 512 MiB combined multipart limit.
- **MITM passthrough TTL** (#306): a host that cannot be intercepted is tunnelled for one minute, then interception is tried again; an expired mark counts as intercepted.
- **Norma v0.4.11** (#294).
- **CI**: the suite also runs on the latest Go release as an advisory job, the rewrite-rule engine runs under the race detector, and the gzip/compression fixtures no longer depend on the local Go version (#279, #278).
- **Repository hygiene** (#275): `docs/` is no longer ignored, and contributing documents the 7-open-pull-request cap (#307).
### Fixed
- **Findings CSV formula cells**: `FindingsCSV` prefixes name, class, summary, task, and other text fields that start with `=`, `+`, `-`, `@`, tab, or CR so Excel/LibreOffice do not evaluate them as formulas when the export is opened.
- **Asset service links**: the Services tab only uses an asset URL as `href` when it is `http:` or `https:`. `javascript:`, `data:`, and other schemes render as text.
- **Chat session directories**: `ChatAgent.Chat` accepts only `[A-Za-z0-9_-]` session ids (at most 64 bytes) before joining them under `<workDir>/sessions`, so `..` and path separators cannot escape that directory.
- **Change-password rate limit**: `POST /api/auth/change-password` uses the same limiter as login, keyed by client IP and by the session token, so a stolen session cannot guess the current password without backoff.
- **Ingested traffic headers**: `RecordExternal` rejects a method that is not an HTTP token and header names or values that contain CR, LF, or NUL, matching Replay, so ingested exchanges cannot inject extra header lines into stored evidence.
- **Browser MCP starts offline** (#329): the seeded `browser` MCP ran `npx @playwright/mcp`, which contacts the npm registry on every start even with the package installed globally, and Playwright MCP defaulted to a Chrome channel the image does not ship. It now runs the image's `playwright-mcp` binary with `--headless --browser chromium`. Existing databases that still have a stock `npx @playwright/mcp` row (including the common `-y` form) or a `playwright-mcp` row with no `--browser` are rewritten once; any other command or package is left alone. The image also installs the Chromium build `@playwright/mcp` and `@playwright/cli` expect, which is not the same build `playwright install` puts in the cache.
- **CREATE DATABASE identifiers**: `ensureDatabase` now builds the statement with `pgx.Identifier`, which quotes the DSN database name and doubles any embedded quote, so the name cannot close the identifier. No database name PostgreSQL accepts is refused, so existing installs with a hyphen, a dot or non-ASCII characters keep starting.
- **ask_operator image_path**: the screenshot path must resolve inside the task working directory (`<data>/tasks/<id>`). Absolute paths, `..` segments, and symlinks that leave that directory are refused, so the tool cannot copy an arbitrary server image into the operator transcript.
- **insert_assets fail-closed**: when intercept or task allow/block rules cannot be loaded, `insert_assets` refuses the whole call instead of evaluating an empty rule set (which allowed every asset). The tool result does not include the underlying database error.
- **BlobRange length no longer wraps int64**: `offset+length > size` overflowed when length was near MaxInt64, so the cap was skipped and `make([]byte, length)` could exhaust memory. The bound is now `length > size-offset`.
- **PostgreSQL text[] literals escape backslashes**: `marshalStringArray` quoted double quotes but not backslashes, so a value ending in `\"` could close the current array element and inject another. It now doubles backslashes before quotes, matching `marshalJSONBArray`.
- **Browser MCP env null no longer crashes startup**: a stored MCP `env` of JSON `null` unmarshaled into a nil map, and `syncBrowserMCPProxy` then assigned `NODE_EXTRA_CA_CERTS` when traffic capture was on, panicking the process on every start. `decodeStrMap` now always returns a writable map.
- **Provider refusals reported as refusals**: a turn the provider's safety system declined (Anthropic `stop_reason: "refusal"`, OpenAI-compatible `finish_reason: "content_filter"`) has no text and no tool calls, so it ended as `completed` with "the model ended this turn normally", and the idle-turn rerun resent the same conversation up to the empty-response retry count, where it is expected to be refused again. The LLM recorder now hands each call's stop reason to the run (`llmrec.WithStopSink`, `agent.WithStopTracker`). After a refusal the idle-turn rerun is skipped, and the run summary says the provider refused the turn and the intent was not completed.
- **LLM health badge on every task path**: `/system/llm/` read a breaker state that only the failover Pool wrote, so a profile used by an explicit task chain, by a bound agent with failover off, or as the global provider stayed "Healthy" through a real outage. Every task LLM attempt now records its outcome through the same policy the Pool uses, keyed by the profile that served it. The LLM recording page also explains an empty list when the `llm_record` toggle is off instead of looking broken.
- **LLM health persistence** (#304): persisted breaker rows are applied in sequence at startup and written before the database closes, and a slow write no longer holds the registry lock while it runs.
- **Skill visibility survives restarts**: turning a skill off now writes an explicit disabled row instead of deleting it, so the startup seed, which only inserts missing rows, can no longer bring the skill back. Skills that were turned off before this version have no row to keep, so they come back once after the upgrade and must be turned off again.
- **Browser extension traffic capture**: CDP delivers `Network.responseReceived` response headers as an object, not an array of `{name, value}` records, so the extension threw on every response and never queued an exchange. It now accepts both shapes and lower-cases names before the body-capture gate, so captures work again and `content-type` correctly controls body capture.
- **bbot on arm64**: the image now builds on arm64 hosts such as Apple Silicon. bbot's `gowitness` downloaded an x86-64 Chrome and `retirejs` an x86-64 Node, which can't run there, so the build failed. On arm64 the image uses Debian's `chromium` for gowitness and an arm64 Node for retirejs, and the build check now covers `retirejs` too. amd64 builds are unchanged.
- **Auto-scope hygiene**: auto `task_scope` rows count for coverage and untested assets only under a declared root, and direct coverage counts anchored assets through fact anchors only; the scope is described as "coverage scope, not enforced" (#196).
- **Enrich HTTP probe**: it now dials through `intercept.PinnedDialer`, so the target gate applies and a probe without a target scope is refused (#198).
- **Agent hook data races**: the eight package-level hooks are synchronised, so a second wire-up no longer races tasks that already read them (#227).
- **Coverage flag read failure** (#303): asset-coverage tools stay available when the coverage flag cannot be read, and a failed read no longer disables coverage for the task.
- **RSI lesson correctness** (#287, #290): lessons are scoped from `task_scope`, UTF-8 is no longer split mid-character, caution lessons are looked up by cue, lesson evidence and every retest are retracted when a finding's disposition reverses, and extraction is skipped on a task with more than one company.
- **Finding disposition mirror** (#289): finding triage is mirrored onto its exploration node, so the graph and the findings table agree.
- **RSI lessons in the data envelope** (#288): lesson text reaches the planner and worker inside the same nonce-framed envelope as other target-derived content.
- **Intent summaries framed** (#311): the intent summary on the worker-finished and finding lines, and the summaries in `graph_overview`, now reach the planner inside the nonce frame; the structured intent fields stay in the plain JSON, and the operator-typed deletion reason stays outside.
- **LLM pool context window** (#286): the pool and side-question paths use the model's real context window instead of a default when computing compression thresholds.
- **Sensitive rewrite values** (#273 follow-ups): a kept sensitive value is matched on action type, header name and regex, and a host change is refused while a stored sensitive value is kept.
- **Triage bot context** (#274): the PR triage bot receives a directory map instead of a truncated file list.
### Security
+13 -4
View File
@@ -167,18 +167,27 @@ RUN set -eux; \
! grep -qE "Installing|ERRR|CRITICAL" /tmp/bbot-dry.log || { cat /tmp/bbot-dry.log; exit 1; }
# Preinstall Playwright MCP and CLI (globally) so no npx network download is needed at runtime.
# @playwright/mcp: browser MCP runs directly via `npx @playwright/mcp` (installed globally, no -y/@latest needed).
# Preinstall Playwright MCP and CLI (globally) so no network download is needed at runtime.
# @playwright/mcp: the seeded browser MCP runs the playwright-mcp binary directly.
# `npx @playwright/mcp` is not used: it queries the npm registry on every start even
# with the package installed globally.
# @playwright/cli: provides playwright-cli, verified with --help right after install.
# Then install playwright (browser management) and preinstall chromium plus its system
# dependencies via --with-deps, so MCP/CLI work on first start inside the container
# without downloading browsers over the network. All three are pinned; upgrade deliberately.
# dependencies via --with-deps. @playwright/mcp and @playwright/cli bundle their own
# playwright-core, which expects a different Chromium build than
# playwright@PLAYWRIGHT_VERSION installs, so that build is installed as well (second
# install line); without it neither can launch a browser. All three packages are
# pinned; upgrade deliberately.
ARG PLAYWRIGHT_MCP_VERSION=0.0.83
ARG PLAYWRIGHT_CLI_VERSION=0.1.22
ARG PLAYWRIGHT_VERSION=1.64.1
# playwright-core's exports map hides cli.js from require.resolve, so run the
# binary npm links for @playwright/mcp instead: it is the copy MCP actually
# loads, and it installs the Chromium revision that copy expects.
RUN npm install -g "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" "@playwright/cli@${PLAYWRIGHT_CLI_VERSION}" "playwright@${PLAYWRIGHT_VERSION}" \
&& playwright-cli --help \
&& playwright install --with-deps chromium \
&& "$(npm root -g)/@playwright/mcp/node_modules/.bin/playwright-core" install chromium \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Binary compiled from source in the build stage above.
+8 -1
View File
@@ -233,7 +233,11 @@ worker remains confined to the intent it claimed.
</details>
- **Verified findings**: findings carry a POE level, a verification status and a note; a finding is
`verified` only when a bound proof/response and verbatim evidence quotes support it. Gzip/deflate
bodies are decoded before the quote check.
bodies are decoded before the quote check. The findings table supports bulk status updates, and
the report and export show each finding's proof strength next to its status.
- **Traffic replay**: open a captured exchange and replay the recorded request (method, URL,
headers and stored body) from the traffic detail; replay stays disabled while only the body
preview is loaded.
- **Vulnerability retest loop**: a dedicated `retester` agent re-runs a finding with optional fixed
version/conditions, records `Still reproducible / Fixed / Cannot confirm`, and can move the
finding to `Fixed` automatically. Original evidence and reports are preserved.
@@ -295,6 +299,9 @@ worker remains confined to the intent it claimed.
for every call.
- **MCP servers, skills, memory and a workspace**: extend the agent with remote tools and reusable
prompt/playbook material.
- **Web search**: the agent's search tool uses Brave, Tavily or the opt-in Keenable backend,
configured in **System → Settings** with the key encrypted at rest; search can also egress
through its own proxy.
- **Single binary**: the Next.js UI is embedded with `go:embed`; PostgreSQL is the only external
dependency.
+8
View File
@@ -35,6 +35,14 @@ ARTEX is an offensive-security tool. Test only against:
Testing, scanning, or exploiting third-party systems without explicit authorization is strictly prohibited. Reports that violate this principle may be closed without action.
## Trusted Inputs and Scope Enforcement
ARTEX trusts the scanner output file (`output.json`) that `ingest_bbot` reads. The `scope_distance` field carried on scope-relevant events is the scanner's own verdict and is ingested as-is: an event the scanner marks in scope (per its own `-s`/`--no-scope` configuration) is treated as in scope without being re-checked against ARTEX's rule set.
The enforced trust boundary for asset insertion is `insert_assets`, which runs every candidate through `EvaluateAssetGate`: block rules always apply, and a task allow-list is enforced when one is configured. A rejected candidate is returned as an `insertion forbidden` error for that asset and is never inserted, so it cannot reach task execution. `in_scope_not_asset` in the `ingest_bbot` result is a different count: in-scope events that are not asset types (findings and the like).
Accepted gap: when a task has no allow-list, there is no allow rule to apply (block rules still run), and any host carried on an in-scope event that is not blocked enters the graph as an asset. Operators who rely on the scanner's scope rules alone should configure an allow-list per task, or review `output.json` before feeding it to ARTEX. Cross-checking ingested events against ARTEX's own rule set would change what existing scanner configurations mean for those operators, so it is treated as a deliberate design question (see #317), not an accepted vulnerability.
## What to Expect
This is an open-source project maintained on a best-effort basis. We aim to acknowledge a report within about a week and keep you updated, but we cannot guarantee specific response or fix timeframes.
+3
View File
@@ -37,6 +37,9 @@ func captureRun(ctx context.Context, opts agentcore.Options, input string, emit
func captureRunSession(ctx context.Context, s *agentcore.Session, input string, emit func(db.Activity)) (string, harness.TerminalReason, error) {
ctx, auditTrace := intercept.WithTrace(ctx, input, approvalHistory(s.Messages()))
defer auditTrace.Finish()
// Observe each model call's stop reason, so a provider refusal is reported as
// one (terminalText) and is not answered with an idle-turn rerun (steerHooks).
ctx = WithStopTracker(ctx)
var reason harness.TerminalReason
rec := func(r db.Activity) {
if r.Kind == "text" || r.Kind == "tool_result" {
+35
View File
@@ -2,8 +2,10 @@ package agent
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/Autumn-27/artex/db"
@@ -98,6 +100,33 @@ func chatSystem(agentKey, dataDir, workDir string) string {
// DefaultAssistantPrompt.
type chatVars struct{ DataDir, Now string }
const maxChatSessionID = 64
// validChatSessionID is the session-directory name contract. Production uses
// "conv-" plus a decimal id; tests use hyphenated suffixes. Path separators
// and ".." are rejected so Join cannot leave <workDir>/sessions.
func validChatSessionID(id string) bool {
if id == "" || len(id) > maxChatSessionID {
return false
}
for i := 0; i < len(id); i++ {
c := id[i]
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '_', c == '-':
default:
return false
}
}
return true
}
func sessionDirInside(workDir, sessionWorkDir string) bool {
base := filepath.Clean(filepath.Join(workDir, "sessions"))
clean := filepath.Clean(sessionWorkDir)
sep := string(os.PathSeparator)
return clean == base || strings.HasPrefix(clean, base+sep)
}
// Chat runs ONE turn of a conversation with the agent identified by agentKey,
// resuming prior history keyed by sessionID. maxTurns is the per-turn agent step
// budget (0 = unlimited). maxDuration is the wall-clock run budget per turn
@@ -114,9 +143,15 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
ws.Enabled = false
}
if !validChatSessionID(sessionID) {
return "", fmt.Errorf("invalid session id %q", sessionID)
}
// Per-session working directory: <workDir>/sessions/<sessionID>/
// Isolates file writes across conversations, mirroring how workers use i<intentID>/.
sessionWorkDir := filepath.Join(c.workDir, "sessions", sessionID)
if !sessionDirInside(c.workDir, sessionWorkDir) {
return "", fmt.Errorf("invalid session id %q", sessionID)
}
_ = os.MkdirAll(sessionWorkDir, 0o755)
ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir)
+79
View File
@@ -0,0 +1,79 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidChatSessionID(t *testing.T) {
ok := []string{
"conv-1",
"conv-stable",
"conv-hook-reach",
"conv-987654",
"conv-dial-probe",
"conv-redirect-probe",
"conv-new",
"conv-broken",
"conv-signed",
"conv-" + strings.Repeat("9", 19),
}
for _, id := range ok {
if !validChatSessionID(id) {
t.Fatalf("%q rejected", id)
}
}
bad := []string{
"",
".",
"..",
"../etc",
"conv/../etc",
`conv\windows`,
"/etc/passwd",
"conv-1/foo",
"a.b",
"conv 1",
"conv:1",
strings.Repeat("a", maxChatSessionID+1),
}
for _, id := range bad {
if validChatSessionID(id) {
t.Fatalf("%q accepted", id)
}
}
}
func TestChatRejectsUnsafeSessionID(t *testing.T) {
p := &sessionProbe{}
workDir := t.TempDir()
c := NewChatAgent(p, "test-model", workDir, nil, 100000)
for _, id := range []string{"..", "../etc", "conv/../etc", `..\windows`, "/etc/passwd", "conv-1/foo"} {
if _, err := c.Chat(t.Context(), "assistant", id, "hello", 1, 0, false, nil); err == nil {
t.Fatalf("%q accepted", id)
}
if n := len(p.seen()); n != 0 {
t.Fatalf("provider called for %q: %d calls", id, n)
}
}
entries, err := os.ReadDir(workDir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("unsafe session id created %v under workDir", names(entries))
}
if _, err := os.Stat(filepath.Join(workDir, "etc")); !os.IsNotExist(err) {
t.Fatalf("escaped path created: %v", err)
}
}
func names(entries []os.DirEntry) []string {
out := make([]string, len(entries))
for i, e := range entries {
out[i] = e.Name()
}
return out
}
+41
View File
@@ -0,0 +1,41 @@
package agent
import (
"encoding/json"
"fmt"
"slices"
)
// factAssetAnchors accepts the historical asset_ids spelling and its explicit
// tested_asset_ids alias. Never union conflicting lists: that could attribute
// a conclusion to assets the caller did not actually check.
func (it factItem) factAssetAnchors() ([]int64, error) {
assets, err := parseFactAssetIDs("asset_ids", it.AssetIDs)
if err != nil {
return nil, err
}
tested, err := parseFactAssetIDs("tested_asset_ids", it.TestedAssetIDs)
if err != nil {
return nil, err
}
if it.AssetIDs != nil && it.TestedAssetIDs != nil && !slices.Equal(assets, tested) {
return nil, fmt.Errorf("asset_ids and tested_asset_ids must contain the same asset IDs when both are provided; use one field or correct the conflicting lists")
}
if it.TestedAssetIDs != nil {
return tested, nil
}
return assets, nil
}
func parseFactAssetIDs(field string, raw []json.RawMessage) ([]int64, error) {
ids := make([]int64, 0, len(raw))
for i, value := range raw {
id := pid(value)
if id <= 0 {
return nil, fmt.Errorf("%s[%d] must be a positive integer asset ID", field, i)
}
ids = append(ids, id)
}
slices.Sort(ids)
return slices.Compact(ids), nil
}
+182
View File
@@ -0,0 +1,182 @@
package agent
import (
"encoding/json"
"fmt"
"slices"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestRecordFactAssetAliases(t *testing.T) {
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("fact asset alias", "test", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(task.ID)
assets := d.Assets()
first, err := assets.UpsertRootDomain(db.UpsertRootDomainReq{Domain: "fact-alias-one.example", TaskID: task.ID})
if err != nil {
t.Fatal(err)
}
second, err := assets.UpsertRootDomain(db.UpsertRootDomainReq{Domain: "fact-alias-two.example", TaskID: task.ID})
if err != nil {
t.Fatal(err)
}
defer assets.DeleteByIDs([]int64{first, second})
store := d.Exploration(task.ExplorationID)
tools := NewToolSet(store, "worker")
check := func(t *testing.T, id int64, want []int64) {
t.Helper()
rows, err := d.Query("SELECT asset_id FROM exploration_anchors WHERE node_id=$1 ORDER BY asset_id", id)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
var got []int64
for rows.Next() {
var asset int64
if err := rows.Scan(&asset); err != nil {
t.Fatal(err)
}
got = append(got, asset)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
slices.Sort(want)
if !slices.Equal(got, want) {
t.Fatalf("anchors = %v, want %v", got, want)
}
}
for _, tc := range []struct{ name, fields string }{
{"canonical", fmt.Sprintf(`"asset_ids":[%d,%d,%d]`, first, second, first)},
{"alias", fmt.Sprintf(`"tested_asset_ids":[%d,%d]`, first, second)},
{"equal sets", fmt.Sprintf(`"asset_ids":[%d,%d],"tested_asset_ids":[%d,%d,%d]`, first, second, second, first, first)},
{"numeric strings", fmt.Sprintf(`"tested_asset_ids":["%d","%d"]`, first, second)},
} {
t.Run(tc.name, func(t *testing.T) {
out := callGuardTool(t, tools.recordFact(), fmt.Sprintf(`{"summary":%q,%s}`, tc.name, tc.fields))
if out.IsError {
t.Fatal(out.Flatten())
}
id, err := strconv.ParseInt(strings.TrimPrefix(out.Flatten(), "fact recorded: "), 10, 64)
if err != nil {
t.Fatal(out.Flatten(), err)
}
check(t, id, []int64{first, second})
})
}
before := tools.Writes().Facts
for _, fields := range []string{
fmt.Sprintf(`"asset_ids":[%d],"tested_asset_ids":[%d]`, first, second),
fmt.Sprintf(`"asset_ids":[],"tested_asset_ids":[%d]`, first),
fmt.Sprintf(`"tested_asset_ids":[%d,0]`, first),
fmt.Sprintf(`"asset_ids":[%d,-1]`, first),
`"tested_asset_ids":[null]`,
`"tested_asset_ids":[1.5]`,
`"tested_asset_ids":["invalid"]`,
} {
out := callGuardTool(t, tools.recordFact(), `{"summary":"invalid assets",`+fields+`}`)
if !out.IsError || !strings.Contains(out.Flatten(), "asset_ids") {
t.Fatalf("accepted %s: %q", fields, out.Flatten())
}
}
if tools.Writes().Facts != before {
t.Fatal("invalid asset lists wrote facts")
}
out := callGuardTool(t, tools.recordFact(), fmt.Sprintf(`{"facts":[{"summary":"batch alias","tested_asset_ids":[%d]},{"summary":"batch conflict","asset_ids":[%d],"tested_asset_ids":[%d]},{"summary":"no inherited assets"}]}`, first, first, second))
var batch struct {
IDs []int64 `json:"ids"`
Errors map[string]string `json:"errors"`
}
if err := json.Unmarshal([]byte(out.Flatten()), &batch); err != nil {
t.Fatal(out.Flatten(), err)
}
if len(batch.IDs) != 3 || batch.IDs[0] <= 0 || batch.IDs[1] != 0 || batch.IDs[2] <= 0 || !strings.Contains(batch.Errors["1"], "same asset IDs") {
t.Fatalf("batch: %s", out.Flatten())
}
check(t, batch.IDs[0], []int64{first})
check(t, batch.IDs[2], nil)
before = tools.Writes().Facts
malformed := callGuardTool(t, tools.recordFact(), fmt.Sprintf(`{"facts":[{"summary":"must not be saved"},{"summary":"bad list","tested_asset_ids":%d}]}`, first))
if !malformed.IsError || tools.Writes().Facts != before {
t.Fatal("malformed list caused a partial write", malformed.Flatten())
}
}
func TestRecordFactAssetAliasSchema(t *testing.T) {
schema := NewToolSet(nil, "").recordFact().InputSchema()
props := schema["properties"].(map[string]any)
for _, name := range []string{"asset_ids", "tested_asset_ids"} {
if props[name] == nil {
t.Fatalf("single schema missing %s", name)
}
}
item := props["facts"].(map[string]any)["items"].(map[string]any)
itemProps, _ := item["properties"].(map[string]any)
for _, name := range []string{"summary", "asset_ids", "tested_asset_ids"} {
if itemProps[name] == nil {
t.Fatalf("batch schema missing %s", name)
}
}
}
func TestRecordFactRejectsMissingAssets(t *testing.T) {
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("missing fact anchors", "test", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(task.ID)
assets := d.Assets()
var ids []int64
for _, name := range []string{"missing-fact-one.example", "missing-fact-two.example", "existing-fact.example"} {
id, err := assets.UpsertRootDomain(db.UpsertRootDomainReq{Domain: name, TaskID: task.ID})
if err != nil {
t.Fatal(err)
}
ids = append(ids, id)
}
defer assets.DeleteByIDs(ids)
if _, err := assets.DeleteByIDs(ids[:2]); err != nil {
t.Fatal(err)
}
tools := NewToolSet(d.Exploration(task.ExplorationID), "worker")
var beforeFacts int
if err := d.QueryRow("SELECT count(*) FROM exploration_nodes WHERE exploration_id=$1 AND kind='fact'", task.ExplorationID).Scan(&beforeFacts); err != nil {
t.Fatal(err)
}
for _, field := range []string{"asset_ids", "tested_asset_ids"} {
out := callGuardTool(t, tools.recordFact(), fmt.Sprintf(`{"summary":"missing anchors","%s":[%d,%d,%d]}`, field, ids[0], ids[1], ids[2]))
if !out.IsError || !strings.Contains(out.Flatten(), "do not exist") ||
!strings.Contains(out.Flatten(), strconv.FormatInt(ids[0], 10)) ||
!strings.Contains(out.Flatten(), strconv.FormatInt(ids[1], 10)) ||
strings.Contains(out.Flatten(), "23503") || strings.Contains(out.Flatten(), "foreign key") {
t.Fatalf("missing assets did not produce an actionable error: %s", out.Flatten())
}
}
var count int
if err := d.QueryRow("SELECT count(*) FROM exploration_nodes WHERE exploration_id=$1 AND kind='fact'", task.ExplorationID).Scan(&count); err != nil || count != beforeFacts || tools.Writes().Facts != 0 {
t.Fatalf("failed anchors left facts: count=%d err=%v", count, err)
}
out := callGuardTool(t, tools.recordFact(), fmt.Sprintf(`{"facts":[{"summary":"valid","asset_ids":[%d]},{"summary":"missing","tested_asset_ids":[%d]}]}`, ids[2], ids[0]))
var batch struct {
IDs []int64 `json:"ids"`
Errors map[string]string `json:"errors"`
}
if err := json.Unmarshal([]byte(out.Flatten()), &batch); err != nil {
t.Fatal(out.Flatten(), err)
}
if !out.IsError || len(batch.IDs) != 2 || batch.IDs[0] <= 0 || batch.IDs[1] != 0 || !strings.Contains(batch.Errors["1"], "do not exist") || tools.Writes().Facts != 1 {
t.Fatal("missing asset batch handling:", out.Flatten())
}
}
+160
View File
@@ -0,0 +1,160 @@
package agent
import (
"bytes"
"encoding/json"
"fmt"
)
// Match strings.TrimSpace, including Unicode whitespace, in the published schema.
const factWhitespace = "\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000"
func factAssetIDSchema() map[string]any {
return map[string]any{
"type": []string{"integer", "string"}, "minimum": 1,
"pattern": "^[" + factWhitespace + "]*\\+?0*[1-9][0-9]*[" + factWhitespace + "]*$",
}
}
func factItemSchema() map[string]any {
schema := obj(map[string]any{
"summary": str("Required on every fact: a non-empty one-sentence summary of this conclusion. Batch items do not inherit summary from the top level."),
"intent_id": idp("The intent that produced this fact; only this field inherits from the top level in a batch."),
"detail": str("Details of this fact, including all related observations."),
"evidence": str("One line of key evidence: the command and the most proving output lines. Put longer output in detail."),
"confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."),
"source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"},
"asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Asset IDs explicitly involved in this fact. Use asset_ids as the canonical field; tested_asset_ids is accepted as an alias. If both are provided, they must name the same set. Do not infer IDs from the intent."},
"tested_asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Compatibility alias for asset_ids, not an additional list. When both are provided their sets must match. Only include assets actually involved in this conclusion."},
}, "summary")
summary := schema["properties"].(map[string]any)["summary"].(map[string]any)
summary["minLength"] = 1
summary["pattern"] = "[^" + factWhitespace + "]"
schema["additionalProperties"] = false
return schema
}
func recordFactSchema() map[string]any {
props := factItemSchema()["properties"].(map[string]any)
props["facts"] = map[string]any{
"type": "array", "minItems": 1, "items": factItemSchema(),
"description": "A non-empty batch of complete facts. Every item needs its own summary. Only intent_id inherits from the top level. Returned ids match item order; retry only failed indices.",
}
schema := obj(props)
// Providers reject root-level anyOf. The handler enforces single/batch mode.
schema["additionalProperties"] = false
return schema
}
// RepairRecordFactSchema restores the single/batch input contract in stored or
// cached schemas, preserving annotations only on fields the handler accepts.
func RepairRecordFactSchema(stored map[string]any) map[string]any {
raw, _ := json.Marshal(stored)
var out map[string]any
_ = json.Unmarshal(raw, &out)
if out == nil {
out = map[string]any{}
}
mergeFactContract(out, recordFactSchema())
// A batch requires summaries on its items, never a redundant top-level one.
delete(out, "required")
delete(out, "anyOf")
canonical := recordFactSchema()["properties"].(map[string]any)
props := out["properties"].(map[string]any)
for name := range props {
if _, known := canonical[name]; !known {
delete(props, name)
}
}
items := props["facts"].(map[string]any)["items"].(map[string]any)
itemProps := items["properties"].(map[string]any)
for name := range itemProps {
if _, known := canonical[name]; !known || name == "facts" {
delete(itemProps, name)
}
}
return out
}
func mergeFactContract(dst, src map[string]any) {
for key, value := range src {
if key == "description" || key == "default" {
if _, ok := dst[key]; ok {
continue
}
}
if child, ok := value.(map[string]any); ok {
target, _ := dst[key].(map[string]any)
if target == nil {
target = map[string]any{}
dst[key] = target
}
mergeFactContract(target, child)
} else {
dst[key] = value
}
}
}
type recordFactInput struct {
Facts []factItem `json:"facts"`
factItem
}
// Validate exact field names before decoding: encoding/json otherwise treats
// Summary, SUMMARY, etc. as aliases even with DisallowUnknownFields enabled.
func decodeRecordFactInput(in json.RawMessage) (recordFactInput, bool, error) {
var out recordFactInput
fields, err := exactFactFields(in, true)
if err != nil {
return out, false, err
}
_, batch := fields["facts"]
if batch {
for name := range fields {
if name != "intent_id" && name != "facts" {
return out, true, fmt.Errorf("field %q is not allowed at the top level in batch mode; only intent_id and facts are accepted", name)
}
}
var items []json.RawMessage
if err := json.Unmarshal(fields["facts"], &items); err != nil {
return out, true, fmt.Errorf("facts must be an array: %w", err)
}
if len(items) == 0 {
return out, true, fmt.Errorf("facts must be a non-empty array of complete facts, each with its own summary")
}
for i, item := range items {
if _, err := exactFactFields(item, false); err != nil {
return out, true, fmt.Errorf("facts[%d]: %w", i, err)
}
}
}
decoder := json.NewDecoder(bytes.NewReader(in))
decoder.DisallowUnknownFields() // Also applies recursively to every factItem.
if err := decoder.Decode(&out); err != nil {
return out, batch, err
}
return out, batch, nil
}
func exactFactFields(in json.RawMessage, topLevel bool) (map[string]json.RawMessage, error) {
var fields map[string]json.RawMessage
if err := json.Unmarshal(in, &fields); err != nil {
return nil, err
}
if fields == nil {
return nil, fmt.Errorf("record_fact input and each fact must be objects")
}
for name := range fields {
switch name {
case "summary", "detail", "evidence", "confidence", "source", "intent_id", "asset_ids", "tested_asset_ids":
case "facts":
if !topLevel {
return nil, fmt.Errorf("unknown field %q", name)
}
default:
return nil, fmt.Errorf("unknown field %q (field names are case-sensitive)", name)
}
}
return fields, nil
}
+165
View File
@@ -0,0 +1,165 @@
package agent
import (
"encoding/json"
"regexp"
"strings"
"testing"
actool "github.com/Autumn-27/norma/tool"
)
func TestRecordFactSummaryContract(t *testing.T) {
tools := NewToolSet(guardTaskStore(t), "worker")
tool := tools.recordFact()
for _, input := range []string{
`{}`, `null`, `[]`,
`{"summary":""}`, `{"summary":" "}`,
`{"summary":"must not substitute","facts":[]}`,
`{"summary":"must not substitute","facts":null}`,
`{"summary":"must not inherit","facts":[{"detail":"missing summary"}]}`,
`{"facts":[{"summary":"must not save"},{"summary":42}]}`,
} {
out := callGuardTool(t, tool, input)
if !out.IsError {
t.Errorf("accepted %s: %s", input, out.Flatten())
}
}
if tools.Writes().Facts != 0 {
t.Fatal("invalid inputs wrote facts")
}
single := callGuardTool(t, tool, `{"summary":"valid single"}`)
if single.IsError {
t.Fatal(single.Flatten())
}
batch := callGuardTool(t, tool, `{"facts":[{"summary":"valid batch"},{"detail":"missing summary"}]}`)
var result struct {
IDs []int64 `json:"ids"`
Errors map[string]string `json:"errors"`
Retry string `json:"retry_instruction"`
}
if err := json.Unmarshal([]byte(batch.Flatten()), &result); err != nil {
t.Fatal(batch.Flatten(), err)
}
if !batch.IsError || len(result.IDs) != 2 || result.IDs[0] <= 0 || result.IDs[1] != 0 ||
!strings.Contains(result.Errors["1"], "summary") || result.Retry == "" || tools.Writes().Facts != 2 {
t.Fatalf("partial failure is not actionable: %s", batch.Flatten())
}
}
func TestRecordFactStoredContractRepair(t *testing.T) {
old := map[string]any{
"type": "object", "required": []any{"summary"},
"anyOf": []any{map[string]any{"required": []string{"summary"}}},
"properties": map[string]any{
"summary": map[string]any{"type": "string", "description": "operator summary"},
"confidence": map[string]any{"type": "string", "default": "inferred"},
"custom_field": map[string]any{"type": "string"},
"facts": map[string]any{"type": "array", "items": map[string]any{"type": "object"}},
},
}
base := NewToolSet(nil, "").recordFact()
repaired := DecorateTool(base, "operator tool", old)
schema := repaired.InputSchema()
if _, required := schema["required"]; required {
t.Fatal("batch still requires a top-level summary")
}
if _, exists := schema["anyOf"]; exists {
t.Fatal("root anyOf reaches the provider")
}
props := schema["properties"].(map[string]any)
item := props["facts"].(map[string]any)["items"].(map[string]any)
required := item["required"].([]string)
if len(required) != 1 || required[0] != "summary" || props["facts"].(map[string]any)["minItems"] != 1 {
t.Fatal("batch must require a nonempty list with a summary per item")
}
if props["summary"].(map[string]any)["minLength"] != 1 ||
item["properties"].(map[string]any)["summary"].(map[string]any)["minLength"] != 1 {
t.Fatal("empty summaries permitted by schema")
}
if repaired.Description() != "operator tool" ||
props["summary"].(map[string]any)["description"] != "operator summary" ||
props["confidence"].(map[string]any)["default"] != "inferred" || props["custom_field"] != nil {
t.Fatal("operator annotations lost")
}
if _, ok := old["properties"].(map[string]any)["tested_asset_ids"]; ok {
t.Fatal("shared old schema mutated")
}
first, _ := json.Marshal(schema)
second, _ := json.Marshal(DecorateTool(base, "", schema).InputSchema())
if string(first) != string(second) {
t.Fatal("repair is not idempotent")
}
var roundTrip map[string]any
if err := json.Unmarshal(first, &roundTrip); err != nil {
t.Fatal(err)
}
for _, input := range []string{`{"summary":"single"}`, `{"facts":[{"summary":"batch"}]}`} {
if err := actool.ValidateInput(roundTrip, json.RawMessage(input)); err != nil {
t.Fatalf("SDK rejects valid %s after catalog round trip: %v", input, err)
}
}
}
func TestRecordFactStrictFields(t *testing.T) {
tools := NewToolSet(guardTaskStore(t), "worker")
for _, tc := range []struct{ input, field string }{
{`{"summary":"valid","typo":1}`, "typo"},
{`{"Summary":"case alias"}`, "Summary"},
{`{"summary":"valid","Facts":[]}`, "Facts"},
{`{"facts":[{"summary":"first"},{"summary":"second","typo":1}]}`, "typo"},
{`{"facts":[{"summary":"first"},{"Summary":"case alias"}]}`, "Summary"},
{`{"facts":[{"summary":"first"},{"summary":"second","ASSET_IDS":[]}]}`, "ASSET_IDS"},
{`{"facts":[{"summary":"nested","facts":[]}]}`, "facts"},
{`{"summary":"ignored","facts":[{"summary":"batch"}]}`, "summary"},
{`{"detail":"ignored","facts":[{"summary":"batch"}]}`, "detail"},
{`{"evidence":"ignored","facts":[{"summary":"batch"}]}`, "evidence"},
{`{"source":"inference","facts":[{"summary":"batch"}]}`, "source"},
{`{"confidence":"inferred","facts":[{"summary":"batch"}]}`, "confidence"},
{`{"asset_ids":[],"facts":[{"summary":"batch"}]}`, "asset_ids"},
{`{"tested_asset_ids":[],"facts":[{"summary":"batch"}]}`, "tested_asset_ids"},
} {
out := callGuardTool(t, tools.recordFact(), tc.input)
if !out.IsError || !strings.Contains(out.Flatten(), tc.field) {
t.Errorf("input %s: want named rejection for %s, got %s", tc.input, tc.field, out.Flatten())
}
}
if tools.Writes().Facts != 0 {
t.Fatal("malformed fields caused partial writes")
}
for _, input := range []string{
`{"facts":[null]}`, `{"facts":[[]]}`, `{"summary":"valid"} {"summary":"extra object"}`,
} {
if _, _, err := decodeRecordFactInput(json.RawMessage(input)); err == nil {
t.Errorf("accepted %s", input)
}
}
if _, batch, err := decodeRecordFactInput(json.RawMessage(`{"intent_id":1,"facts":[{"summary":"valid","intent_id":2}]}`)); err != nil || !batch {
t.Fatalf("valid batch: %v %v", batch, err)
}
}
func TestRecordFactSchemaMatchesStrings(t *testing.T) {
props := recordFactSchema()["properties"].(map[string]any)
summary := regexp.MustCompile(props["summary"].(map[string]any)["pattern"].(string))
for _, value := range []string{"", " ", "\t\r\n", "\u00a0\u0085", "\u2003\u3000", "conclusion", " observed "} {
if got, want := summary.MatchString(value), strings.TrimSpace(value) != ""; got != want {
t.Errorf("summary %q: schema=%v runtime=%v", value, got, want)
}
}
id := regexp.MustCompile(factAssetIDSchema()["pattern"].(string))
for _, value := range []string{"1", "001", "+1", " +001 ", "\u200312\u3000", "", "0", "-1", "1.5", "a"} {
raw, _ := json.Marshal(value)
if got, want := id.MatchString(value), pid(raw) > 0; got != want {
t.Errorf("asset ID %q: schema=%v runtime=%v", value, got, want)
}
}
for _, input := range []string{
`{"summary":"single","asset_ids":["1",2]}`,
`{"facts":[{"summary":"batch","tested_asset_ids":["1",2]}]}`,
} {
if err := actool.ValidateInput(recordFactSchema(), json.RawMessage(input)); err != nil {
t.Errorf("numeric-string compatibility rejected: %v", err)
}
}
}
+47
View File
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -449,3 +450,49 @@ func TestInsertAssetsRejectsHostnameIPPerItem(t *testing.T) {
t.Fatalf("rejected hostname still stored in assets.ip (%d rows)", stored)
}
}
func TestInsertAssetsRuleLoadFailure(t *testing.T) {
if out, refused := insertAssetsRuleLoadFailure(nil); refused || out.IsError {
t.Fatalf("nil error must not refuse: refused=%v IsError=%v %q", refused, out.IsError, out.Flatten())
}
out, refused := insertAssetsRuleLoadFailure(errors.New("sql: database is closed"))
text := out.Flatten()
if !refused || !out.IsError || !strings.Contains(text, "asset intercept rules are unavailable") {
t.Fatalf("want fail-closed refusal, refused=%v IsError=%v %q", refused, out.IsError, text)
}
for _, leak := range []string{"sql:", "database is closed"} {
if strings.Contains(text, leak) {
t.Fatalf("tool result leaked the load error: %q", text)
}
}
}
func TestInsertAssetsRefusesWhenInterceptRulesUnavailable(t *testing.T) {
d := testDB(t)
ts := NewToolSet(nil, "")
ts.SetAssetStore(d.Assets(), d.Companies())
d.Close()
raw, err := json.Marshal(map[string]any{
"assets": []any{
map[string]any{"type": "ip", "ip": "203.0.113.50"},
},
})
if err != nil {
t.Fatal(err)
}
res, err := ts.insertAssets().Call(context.Background(), raw, nil)
if err != nil {
t.Fatalf("Call error: %v", err)
}
text := res.Flatten()
if !res.IsError || !strings.Contains(text, "asset intercept rules are unavailable") {
t.Fatalf("want fail-closed refusal, IsError=%v %q", res.IsError, text)
}
for _, leak := range []string{"sql:", "database is closed", "pq:", "connection"} {
if strings.Contains(strings.ToLower(text), strings.ToLower(leak)) {
t.Fatalf("tool result leaked the load error: %q", text)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package agent
import (
"context"
"sync"
"github.com/Autumn-27/artex/llmrec"
)
// IsRefusalStop reports whether a provider stop reason means the provider's
// safety system declined the request rather than the model ending its turn.
// Anthropic returns stop_reason "refusal" with an empty or partial message;
// OpenAI-compatible endpoints return finish_reason "content_filter", which Norma
// passes through unmapped.
func IsRefusalStop(stopReason string) bool {
return stopReason == "refusal" || stopReason == "content_filter"
}
// stopTracker keeps the stop reason of the latest model call of one run. The
// harness does not expose it: a refused turn has no text and no tool calls, so it
// ends as ReasonCompleted, the same as a model that chose to stop.
type stopTracker struct {
mu sync.Mutex
last string
}
func (t *stopTracker) set(stopReason string) {
t.mu.Lock()
t.last = stopReason
t.mu.Unlock()
}
func (t *stopTracker) get() string {
t.mu.Lock()
defer t.mu.Unlock()
return t.last
}
type stopTrackerKey struct{}
// WithStopTracker attaches a fresh stop tracker to ctx and subscribes it to the
// LLM recorder's stop sink, so every model call made under the returned context
// updates it. captureRunSession installs one per run; a nested run gets its own.
func WithStopTracker(ctx context.Context) context.Context {
t := &stopTracker{}
ctx = context.WithValue(ctx, stopTrackerKey{}, t)
return llmrec.WithStopSink(ctx, t.set)
}
// LastStopReason returns the stop reason of the latest model call made under ctx
// by the run that owns it, or "" when none was observed.
func LastStopReason(ctx context.Context) string {
if t, _ := ctx.Value(stopTrackerKey{}).(*stopTracker); t != nil {
return t.get()
}
return ""
}
+113
View File
@@ -0,0 +1,113 @@
package agent
import (
"context"
"iter"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
)
// stopProvider ends every streamed call with the given stop reason and no content,
// the shape of a provider refusal before any output.
type stopProvider struct{ stop string }
func (p stopProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
if !yield(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 41}}, nil) {
return
}
if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: p.stop}, nil) {
return
}
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
func (p stopProvider) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return llm.Message{Role: llm.RoleAssistant}, p.stop, llm.Usage{InputTokens: 41}, nil
}
// streamUnder runs one recorded streaming call with the given stop reason under ctx.
func streamUnder(t *testing.T, ctx context.Context, stop string) {
t.Helper()
rec := llmrec.Wrap(stopProvider{stop: stop}, nil, "model", "profile", "", "", func() bool { return false })
for _, err := range rec.Stream(ctx, llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
}
func TestIsRefusalStop(t *testing.T) {
for stop, want := range map[string]bool{
"refusal": true, "content_filter": true,
"end_turn": false, "tool_use": false, "max_tokens": false, "stop": false, "": false,
} {
if got := IsRefusalStop(stop); got != want {
t.Errorf("IsRefusalStop(%q) = %v, want %v", stop, got, want)
}
}
}
// The tracker installed per run is fed by the LLM recorder, and each run sees only
// its own calls.
func TestStopTrackerFedByRecorder(t *testing.T) {
ctx := WithStopTracker(context.Background())
if got := LastStopReason(ctx); got != "" {
t.Fatalf("fresh tracker reports %q", got)
}
streamUnder(t, ctx, "refusal")
if got := LastStopReason(ctx); got != "refusal" {
t.Fatalf("LastStopReason = %q, want refusal", got)
}
// A later call overwrites it: the tracker describes the latest call only.
streamUnder(t, ctx, "end_turn")
if got := LastStopReason(ctx); got != "end_turn" {
t.Fatalf("LastStopReason = %q, want end_turn", got)
}
// A nested run gets its own tracker and does not leak into the outer one.
inner := WithStopTracker(ctx)
streamUnder(t, inner, "content_filter")
if LastStopReason(inner) != "content_filter" || LastStopReason(ctx) != "end_turn" {
t.Fatalf("nested tracker leaked: inner=%q outer=%q", LastStopReason(inner), LastStopReason(ctx))
}
if got := LastStopReason(context.Background()); got != "" {
t.Fatalf("context without a tracker reports %q", got)
}
}
func TestTerminalTextNamesProviderRefusal(t *testing.T) {
trace := &runTrace{startedAt: time.Now()}
for _, stop := range []string{"refusal", "content_filter"} {
ctx := WithStopTracker(context.Background())
streamUnder(t, ctx, stop)
summary, detail := terminalText(ctx, &harness.Terminal{Reason: harness.ReasonCompleted}, trace)
if !strings.Contains(summary, "provider refusal (stop_reason "+stop+")") || strings.Contains(summary, "ended this turn normally") {
t.Fatalf("%s: summary does not name the refusal: %q", stop, summary)
}
if !strings.Contains(detail, "stop_reason `"+stop+"`") || !strings.Contains(detail, "was not completed") {
t.Fatalf("%s: detail does not explain the refusal:\n%s", stop, detail)
}
}
// Control: an ordinary end of turn keeps the completed wording.
ctx := WithStopTracker(context.Background())
streamUnder(t, ctx, "end_turn")
summary, _ := terminalText(ctx, &harness.Terminal{Reason: harness.ReasonCompleted}, trace)
if !strings.Contains(summary, "terminal state completed") || strings.Contains(summary, "refusal") {
t.Fatalf("ordinary end of turn misreported: %q", summary)
}
// A refusal stop only relabels a completed run; other terminal states keep theirs.
ctx = WithStopTracker(context.Background())
streamUnder(t, ctx, "refusal")
summary, _ = terminalText(ctx, &harness.Terminal{Reason: harness.ReasonMaxTurns}, trace)
if !strings.Contains(summary, "run budget cap") {
t.Fatalf("max_turns relabelled by a refusal stop: %q", summary)
}
}
+14 -1
View File
@@ -44,6 +44,9 @@ var reasonHint = map[harness.TerminalReason]string{
harness.ReasonAbortedTools: "the run was cancelled during tool execution",
}
// refusalHint explains a turn the provider declined (see IsRefusalStop).
const refusalHint = "the provider's safety system declined this request, so the model produced no output; the intent was not completed, and resending the same request unchanged is expected to be refused again. With LLM Recording on, the raw response carries the provider's stop details"
// terminalText renders a terminal event with no final text into a compact summary
// and a Markdown detail block.
func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (string, string) {
@@ -54,6 +57,10 @@ func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (st
if reason == "" && ctx.Err() != nil {
aborted = true
}
// A provider refusal has no text and no tool calls, so the harness ends it as
// ReasonCompleted. Only the recorded stop reason tells the two apart.
stop := LastStopReason(ctx)
refused := reason == harness.ReasonCompleted && IsRefusalStop(stop)
var sum string
if aborted {
@@ -71,6 +78,8 @@ func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (st
sum = "(run interrupted: " + short + "; stopped during " + stage + progressSuffix(term, tr) + ", unfinished)"
} else if reason == harness.ReasonMaxTurns || reason == harness.ReasonTimeout {
sum = "(run budget cap reached (" + string(reason) + "); wrap-up wrote back facts" + progressSuffix(term, tr) + "; no text summary this run)"
} else if refused {
sum = "(no text summary; provider refusal (stop_reason " + stop + "): " + firstLine(refusalHint, 80) + ")"
} else {
hint := terminalReasonHint(reason)
sum = "(no text summary; terminal state " + terminalReasonLabel(reason) + ": " + firstLine(hint, 80) + ")"
@@ -80,7 +89,11 @@ func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (st
b.WriteString(sum)
b.WriteString("\n\n")
displayReason := terminalReasonLabel(reason)
fmt.Fprintf(&b, "- **Terminal state**: `%s` - %s\n", displayReason, terminalReasonHint(reason))
if refused {
fmt.Fprintf(&b, "- **Terminal state**: `%s`, but the last model call ended with stop_reason `%s` - %s\n", displayReason, stop, refusalHint)
} else {
fmt.Fprintf(&b, "- **Terminal state**: `%s` - %s\n", displayReason, terminalReasonHint(reason))
}
if aborted {
code, _, why, ok := AbortReason(ctx)
if ok {
+3
View File
@@ -162,6 +162,9 @@ func DecorateTool(t actool.CoreTool, desc string, schema map[string]any) actool.
if len(schema) == 0 {
schema = t.InputSchema()
}
if t.Name() == "record_fact" {
schema = RepairRecordFactSchema(schema)
}
return &overriddenTool{CoreTool: t, desc: desc, schema: schema}
}
+22 -25
View File
@@ -1495,13 +1495,14 @@ func (t *ToolSet) addFinding() actool.CoreTool {
// must NOT be stuffed into the asset graph via upsert_asset.
// factItem is one fact of a record_fact batch/single call.
type factItem struct {
Summary string `json:"summary"`
Detail string `json:"detail"`
Evidence string `json:"evidence"` // one line of key evidence (command + key output lines) supporting the conclusion, for later verification
Confidence string `json:"confidence"` // observed (seen directly) | inferred (inferred from phenomena)
Source string `json:"source"` // where the content came from, one of factSources; empty = inference
IntentID json.RawMessage `json:"intent_id"`
AssetIDs []json.RawMessage `json:"asset_ids"`
Summary string `json:"summary"`
Detail string `json:"detail"`
Evidence string `json:"evidence"` // one line of key evidence (command + key output lines) supporting the conclusion, for later verification
Confidence string `json:"confidence"` // observed (seen directly) | inferred (inferred from phenomena)
Source string `json:"source"` // where the content came from, one of factSources; empty = inference
IntentID json.RawMessage `json:"intent_id"`
AssetIDs []json.RawMessage `json:"asset_ids"`
TestedAssetIDs []json.RawMessage `json:"tested_asset_ids"`
}
// Fact sources (#124, F4): where a fact's content came from, as declared by the
@@ -1537,12 +1538,16 @@ func normalizeFactSource(s string) (string, error) {
// intent_id).
func (t *ToolSet) recordOneFact(it factItem, defaultIntent int64) (int64, error) {
if strings.TrimSpace(it.Summary) == "" {
return 0, fmt.Errorf("summary must not be empty")
return 0, fmt.Errorf("summary must not be empty: every fact, including each batch item, requires its own one-sentence summary")
}
source, err := normalizeFactSource(it.Source)
if err != nil {
return 0, err
}
anchors, err := it.factAssetAnchors()
if err != nil {
return 0, err
}
payload := map[string]any{"summary": it.Summary, "source": source}
if it.Detail != "" {
payload["detail"] = it.Detail
@@ -1564,7 +1569,7 @@ func (t *ToolSet) recordOneFact(it factItem, defaultIntent int64) (int64, error)
}
}
// a fact is its OWN node kind (distinct from a vuln finding).
id, err := t.ts.AddNode(db.KindFact, payload, 5, "confirmed", t.worker, pidList(it.AssetIDs))
id, err := t.ts.AddNode(db.KindFact, payload, 5, "confirmed", t.worker, anchors)
if err != nil {
return 0, err
}
@@ -1584,23 +1589,12 @@ func (t *ToolSet) recordFact() actool.CoreTool {
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n"+
" · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n"+
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" — state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen.",
obj(map[string]any{
"facts": map[string]any{"type": "array", "description": "[use when there are several distinct conclusions] array of facts; element fields same as the top-level fields below (summary/detail/evidence/confidence/source/intent_id/asset_ids); omitting intent_id falls back to the top-level intent_id. The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}},
"summary": str("a [one-sentence summary] of this exploration's conclusion (a condensation of detail)"),
"intent_id": idp("the id of the intent that produced this fact (the intent you claimed; the default for each item in batch mode)"),
"detail": str("details related to this fact: write all of this exploration's observations here"),
"evidence": str("[one line] of key evidence: the command + the one or two most proving output lines. Keep it brief; don't paste large output blocks (details go in detail)."),
"confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Always label negative conclusions honestly."),
"source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"},
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "related asset ids (optional, 0/1/many): which assets this fact involves"},
}),
recordFactSchema(),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
Facts []factItem `json:"facts"`
factItem // single mode + batch default intent_id
a, batch, err := decodeRecordFactInput(in)
if err != nil {
return actool.Errorf("invalid record_fact input: " + err.Error() + "; no facts were written"), nil
}
_ = json.Unmarshal(in, &a)
batch := len(a.Facts) > 0
items := a.Facts
if !batch {
items = []factItem{a.factItem}
@@ -1627,8 +1621,11 @@ func (t *ToolSet) recordFact() actool.CoreTool {
out := map[string]any{"ids": ids}
if len(errs) > 0 {
out["errors"] = errs
out["retry_instruction"] = "Retry only failed indices with complete facts, including summary. Successful indices were already saved; do not retry them."
}
return jsonResult(out)
result, err := jsonResult(out)
result.IsError = len(errs) > 0
return result, err
})
}
+22 -6
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/url"
"strconv"
@@ -121,6 +122,17 @@ type assetInputItem struct {
Params []map[string]any `json:"params"`
}
// insertAssetsRuleLoadFailure refuses the whole insert_assets call when
// intercept rules cannot be loaded. The underlying error stays in the process
// log so the model never sees a driver string.
func insertAssetsRuleLoadFailure(err error) (actool.Result, bool) {
if err == nil {
return actool.Result{}, false
}
log.Printf("[insert_assets] intercept rules unavailable: %v", err)
return actool.Errorf("asset intercept rules are unavailable; insertion refused"), true
}
// insertAssets is the unified insert_assets agent tool.
func (t *ToolSet) insertAssets() actool.CoreTool {
return writeTool(
@@ -233,16 +245,20 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
var results []result
var errs []errEntry
// Asset gate rules are loaded once; on read failure the check is skipped
// (insertion not blocked).
// Interception rules = global ∪ task-level block; allow rules = task-level allow.
blockRules, _ := t.as.ListAssetInterceptRules()
// Fail closed: a rule-load error must not evaluate as an empty set (allow all).
blockRules, err := t.as.ListAssetInterceptRules()
if out, refused := insertAssetsRuleLoadFailure(err); refused {
return out, nil
}
var allowRules []db.AssetInterceptRule
if t.taskID > 0 {
if tb, ta, err := t.as.TaskInterceptRulesSplit(t.taskID); err == nil {
blockRules = append(blockRules, tb...)
allowRules = ta
tb, ta, err := t.as.TaskInterceptRulesSplit(t.taskID)
if out, refused := insertAssetsRuleLoadFailure(err); refused {
return out, nil
}
blockRules = append(blockRules, tb...)
allowRules = ta
}
for i, item := range a.Assets {
+3 -1
View File
@@ -221,7 +221,9 @@ func marshalStringArray(items []string) string {
}
escaped := make([]string, len(items))
for i, s := range items {
escaped[i] = `"` + strings.ReplaceAll(s, `"`, `\"`) + `"`
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `"`, `\"`)
escaped[i] = `"` + s + `"`
}
return "{" + strings.Join(escaped, ",") + "}"
}
+11
View File
@@ -879,6 +879,17 @@ func TestMarshalStringArray(t *testing.T) {
if got2 != "{}" {
t.Errorf("empty: %q", got2)
}
quoted := marshalStringArray([]string{`say "hi"`, `a\b`})
if quoted != `{"say \"hi\"","a\\b"}` {
t.Errorf("escape: %q", quoted)
}
// A backslash before a quote must not close the element and inject another.
injected := marshalStringArray([]string{`x\",evil,\"y`})
if strings.Contains(injected, `","evil`) {
t.Errorf("backslash-quote split the array: %q", injected)
}
}
// =====================================================================
+131
View File
@@ -0,0 +1,131 @@
package db
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
)
const (
browserMCPName = "browser"
browserMCPCommand = "playwright-mcp"
browserMCPDirectBinSetting = "browser_mcp_direct_bin_v1"
)
// browserMCPSeedArgs is the JSON args array for a fresh browser MCP row.
// --headless: the image has no display.
// --browser chromium: Playwright MCP defaults to the "chrome" channel at
// /opt/google/chrome, which the image does not ship.
const browserMCPSeedArgs = `["--headless","--browser","chromium"]`
// npxMetaFlags are npx switches that do not take a value and that still leave
// the following argument as the package spec. `-y` is the form the UI mock
// used; `--` is a common separator. Flags that take a value (`-p`, `--package`)
// are treated as a custom invocation and left alone.
var npxMetaFlags = map[string]bool{
"-y": true,
"--yes": true,
"--": true,
"-q": true,
"--quiet": true,
}
func playwrightMCPPackageIndex(args []string) (int, bool) {
for i := 0; i < len(args); i++ {
a := args[i]
if npxMetaFlags[a] {
continue
}
if a == "@playwright/mcp" || strings.HasPrefix(a, "@playwright/mcp@") {
return i, true
}
return 0, false
}
return 0, false
}
// rewriteStockNpxBrowserMCP converts `npx [@meta...] @playwright/mcp [...]` to
// the image's global playwright-mcp binary. ok is false when the row is not
// that invocation (the operator changed the command or the package).
func rewriteStockNpxBrowserMCP(command string, args []string) (string, []string, bool) {
if command != "npx" {
return command, args, false
}
idx, ok := playwrightMCPPackageIndex(args)
if !ok {
return command, args, false
}
rest := append([]string{}, args[idx+1:]...)
if !hasCLIFlag(rest, "--headless") {
rest = append(rest, "--headless")
}
if !hasCLIFlag(rest, "--browser") {
rest = append(rest, "--browser", "chromium")
}
return browserMCPCommand, rest, true
}
// rewriteBrowserMCPRow is the one-time row rewrite: stock npx @playwright/mcp
// becomes playwright-mcp, and a playwright-mcp row that still has no --browser
// (the MCP defaults to a Chrome channel the image does not ship) gets
// --browser chromium. Any other command or package is left alone.
func rewriteBrowserMCPRow(command string, args []string) (string, []string, bool) {
cmd, out, ok := rewriteStockNpxBrowserMCP(command, args)
if !ok {
cmd, out = command, append([]string{}, args...)
}
if cmd == browserMCPCommand && !hasCLIFlag(out, "--browser") {
out = append(out, "--browser", "chromium")
ok = true
}
return cmd, out, ok
}
func hasCLIFlag(args []string, flag string) bool {
eq := flag + "="
for _, a := range args {
if a == flag || strings.HasPrefix(a, eq) {
return true
}
}
return false
}
// migrateStockBrowserMCP rewrites a leftover stock `npx @playwright/mcp` browser
// MCP row once, and adds `--browser chromium` to a playwright-mcp row that
// still has none. Gated by a settings flag so an operator who later puts npx
// back is not rewritten on the next start. Any other command or package is
// left as-is.
func (d *DB) migrateStockBrowserMCP() error {
if v, _, _ := d.GetSetting(browserMCPDirectBinSetting); v == "done" {
return nil
}
var command string
var argsRaw []byte
err := d.QueryRow(`SELECT COALESCE(command,''), args FROM mcp_servers WHERE name=$1`, browserMCPName).Scan(&command, &argsRaw)
if errors.Is(err, sql.ErrNoRows) {
return d.SetSetting(browserMCPDirectBinSetting, "done")
}
if err != nil {
return fmt.Errorf("read browser mcp: %w", err)
}
var args []string
if len(argsRaw) > 0 {
if err := json.Unmarshal(argsRaw, &args); err != nil {
return d.SetSetting(browserMCPDirectBinSetting, "done")
}
}
newCommand, newArgs, ok := rewriteBrowserMCPRow(command, args)
if ok {
raw, err := json.Marshal(newArgs)
if err != nil {
return fmt.Errorf("encode browser mcp args: %w", err)
}
if _, err := d.Exec(`UPDATE mcp_servers SET command=$1, args=$2 WHERE name=$3`, newCommand, string(raw), browserMCPName); err != nil {
return fmt.Errorf("update browser mcp: %w", err)
}
}
return d.SetSetting(browserMCPDirectBinSetting, "done")
}
+292
View File
@@ -0,0 +1,292 @@
package db
import (
"encoding/json"
"slices"
"testing"
)
func TestRewriteStockNpxBrowserMCP(t *testing.T) {
cases := []struct {
name string
command string
args []string
wantOK bool
wantCommand string
wantArgs []string
}{
{
name: "stock seed",
command: "npx",
args: []string{"@playwright/mcp", "--headless"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "chromium"},
},
{
name: "package only",
command: "npx",
args: []string{"@playwright/mcp"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "chromium"},
},
{
name: "pinned package version",
command: "npx",
args: []string{"@playwright/mcp@0.0.83", "--headless"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "chromium"},
},
{
name: "capture proxy args kept",
command: "npx",
args: []string{"@playwright/mcp", "--headless", "--proxy-server", "http://127.0.0.1:8788"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--proxy-server", "http://127.0.0.1:8788", "--browser", "chromium"},
},
{
name: "existing --browser kept",
command: "npx",
args: []string{"@playwright/mcp", "--headless", "--browser", "firefox"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "firefox"},
},
{
name: "equals-form --browser kept",
command: "npx",
args: []string{"@playwright/mcp", "--browser=chrome"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--browser=chrome", "--headless"},
},
{
name: "npx -y",
command: "npx",
args: []string{"-y", "@playwright/mcp", "--headless"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "chromium"},
},
{
name: "npx --yes -- separator",
command: "npx",
args: []string{"--yes", "--", "@playwright/mcp"},
wantOK: true,
wantCommand: "playwright-mcp",
wantArgs: []string{"--headless", "--browser", "chromium"},
},
{
name: "already playwright-mcp",
command: "playwright-mcp",
args: []string{"--headless"},
},
{
name: "npx -p is a custom invocation",
command: "npx",
args: []string{"-p", "@playwright/mcp", "playwright-mcp", "--headless"},
},
{
name: "different package",
command: "npx",
args: []string{"@modelcontextprotocol/server-github"},
},
{
name: "empty args",
command: "npx",
},
{
name: "empty command",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gotCommand, gotArgs, ok := rewriteStockNpxBrowserMCP(tc.command, tc.args)
if ok != tc.wantOK {
t.Fatalf("ok=%v, want %v", ok, tc.wantOK)
}
if !tc.wantOK {
if gotCommand != tc.command || !slices.Equal(gotArgs, tc.args) {
t.Fatalf("unchanged: got %q %q", gotCommand, gotArgs)
}
return
}
if gotCommand != tc.wantCommand {
t.Fatalf("command=%q, want %q", gotCommand, tc.wantCommand)
}
if !slices.Equal(gotArgs, tc.wantArgs) {
t.Fatalf("args=%q, want %q", gotArgs, tc.wantArgs)
}
})
}
}
func TestRewriteBrowserMCPRow(t *testing.T) {
cmd, args, ok := rewriteBrowserMCPRow("playwright-mcp", []string{"--headless"})
if !ok || cmd != browserMCPCommand || !slices.Equal(args, []string{"--headless", "--browser", "chromium"}) {
t.Fatalf("missing --browser: ok=%v %q %q", ok, cmd, args)
}
cmd, args, ok = rewriteBrowserMCPRow("playwright-mcp", []string{"--headless", "--browser", "firefox"})
if ok {
t.Fatalf("existing --browser rewritten: %q %q", cmd, args)
}
cmd, args, ok = rewriteBrowserMCPRow("npx", []string{"-y", "@playwright/mcp", "--headless"})
if !ok || cmd != browserMCPCommand || !slices.Equal(args, []string{"--headless", "--browser", "chromium"}) {
t.Fatalf("npx -y: ok=%v %q %q", ok, cmd, args)
}
in := []string{"--headless"}
orig := slices.Clone(in)
_, out, ok := rewriteBrowserMCPRow("playwright-mcp", in)
if !ok {
t.Fatal("expected rewrite")
}
out[0] = "mutated"
if !slices.Equal(in, orig) {
t.Fatalf("input mutated: %q", in)
}
}
func TestRewriteStockNpxBrowserMCPDoesNotAliasInput(t *testing.T) {
in := []string{"@playwright/mcp", "--headless"}
orig := slices.Clone(in)
_, out, ok := rewriteStockNpxBrowserMCP("npx", in)
if !ok {
t.Fatal("expected rewrite")
}
out[0] = "mutated"
if !slices.Equal(in, orig) {
t.Fatalf("input mutated: %q", in)
}
}
func TestSeedAndMigrateBrowserMCP(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
origCmd, _, origRaw := readBrowserMCP(t, d)
origSetting, origHad, err := d.GetSetting(browserMCPDirectBinSetting)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, err := d.Exec(`UPDATE mcp_servers SET command=$1, args=$2 WHERE name=$3`, origCmd, origRaw, browserMCPName)
cleanupErr(t, "restore browser mcp", err)
if origHad {
cleanupErr(t, "restore setting", d.SetSetting(browserMCPDirectBinSetting, origSetting))
} else {
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
}
d.Close()
})
t.Run("stock npx rewritten once", func(t *testing.T) {
putBrowserMCP(t, d, "npx", []string{"@playwright/mcp", "--headless"})
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ := readBrowserMCP(t, d)
if cmd != browserMCPCommand || !slices.Equal(args, []string{"--headless", "--browser", "chromium"}) {
t.Fatalf("got %q %q", cmd, args)
}
putBrowserMCP(t, d, "npx", []string{"@playwright/mcp", "--headless"})
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ = readBrowserMCP(t, d)
if cmd != "npx" || !slices.Equal(args, []string{"@playwright/mcp", "--headless"}) {
t.Fatalf("second pass clobbered: %q %q", cmd, args)
}
})
t.Run("npx -y rewritten", func(t *testing.T) {
putBrowserMCP(t, d, "npx", []string{"-y", "@playwright/mcp", "--headless"})
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ := readBrowserMCP(t, d)
if cmd != browserMCPCommand || !slices.Equal(args, []string{"--headless", "--browser", "chromium"}) {
t.Fatalf("got %q %q", cmd, args)
}
})
t.Run("playwright-mcp missing --browser", func(t *testing.T) {
putBrowserMCP(t, d, "playwright-mcp", []string{"--headless"})
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ := readBrowserMCP(t, d)
if cmd != browserMCPCommand || !slices.Equal(args, []string{"--headless", "--browser", "chromium"}) {
t.Fatalf("got %q %q", cmd, args)
}
})
t.Run("custom package left alone", func(t *testing.T) {
custom := []string{"@modelcontextprotocol/server-github"}
putBrowserMCP(t, d, "npx", custom)
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ := readBrowserMCP(t, d)
if cmd != "npx" || !slices.Equal(args, custom) {
t.Fatalf("custom row rewritten: %q %q", cmd, args)
}
})
t.Run("proxy args preserved", func(t *testing.T) {
putBrowserMCP(t, d, "npx", []string{"@playwright/mcp", "--headless", "--proxy-server", "http://127.0.0.1:8788"})
cleanupExec(t, d, `DELETE FROM settings WHERE key=$1`, browserMCPDirectBinSetting)
if err := d.seedBuiltins(); err != nil {
t.Fatal(err)
}
cmd, args, _ := readBrowserMCP(t, d)
want := []string{"--headless", "--proxy-server", "http://127.0.0.1:8788", "--browser", "chromium"}
if cmd != browserMCPCommand || !slices.Equal(args, want) {
t.Fatalf("got %q %q", cmd, args)
}
})
}
func putBrowserMCP(t *testing.T, d *DB, command string, args []string) {
t.Helper()
raw, err := json.Marshal(args)
if err != nil {
t.Fatal(err)
}
res, err := d.Exec(`UPDATE mcp_servers SET command=$1, args=$2 WHERE name=$3`, command, string(raw), browserMCPName)
if err != nil {
t.Fatal(err)
}
n, err := res.RowsAffected()
if err != nil {
t.Fatal(err)
}
if n != 1 {
t.Fatalf("update browser mcp: %d rows", n)
}
}
func readBrowserMCP(t *testing.T, d *DB) (command string, args []string, raw []byte) {
t.Helper()
err := d.QueryRow(`SELECT COALESCE(command,''), args FROM mcp_servers WHERE name=$1`, browserMCPName).Scan(&command, &raw)
if err != nil {
t.Fatal(err)
}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &args); err != nil {
t.Fatal(err)
}
}
return
}
+20 -3
View File
@@ -25,6 +25,7 @@ import (
"time"
"github.com/Autumn-27/artex/config"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
_ "github.com/jackc/pgx/v5/stdlib" // pgx database/sql driver ("pgx")
)
@@ -156,13 +157,21 @@ func ensureDatabase(dsn string) error {
var exists bool
_ = admin.QueryRow(`SELECT true FROM pg_database WHERE datname=$1`, dbName).Scan(&exists)
if !exists {
if _, err := admin.Exec(`CREATE DATABASE "` + dbName + `"`); err != nil {
if _, err := admin.Exec(createDatabaseSQL(dbName)); err != nil {
return fmt.Errorf("create database %q: %w", dbName, err)
}
}
return nil
}
// createDatabaseSQL builds the CREATE DATABASE statement for a DSN-supplied
// database name. pgx.Identifier quotes it and doubles any embedded quote, so
// the name cannot close the identifier, and names PostgreSQL accepts but a
// restrictive allowlist would reject (hyphens, dots, non-ASCII) keep working.
func createDatabaseSQL(name string) string {
return "CREATE DATABASE " + pgx.Identifier{name}.Sanitize()
}
// Open connects, applies the schema (idempotent) and the embedded versioned
// migrations, and seeds builtin rows.
func Open(dsn string) (*DB, error) {
@@ -317,13 +326,21 @@ ON CONFLICT (agent_id, var_name) DO UPDATE
// the recording proxy + CA at runtime (server.Manager.syncBrowserMCPProxy).
// Insert only if absent so we never clobber user edits (args/env/enabled/
// visibility) on restart.
// Launched through the installed playwright-mcp binary, not `npx
// @playwright/mcp`: npx asks the npm registry on every start, even with the
// package installed globally, so the version that runs is the registry's.
// --browser chromium: the default is the "chrome" channel (Google Chrome),
// which the image does not have; it ships Playwright's Chromium.
if _, err := d.Exec(`
INSERT INTO mcp_servers(name, transport, command, args, env, enabled)
VALUES ('browser', 'stdio', 'npx', $1, '{}', false)
VALUES ('browser', 'stdio', $1, $2, '{}', false)
ON CONFLICT (name) DO NOTHING`,
`["@playwright/mcp","--headless"]`); err != nil {
browserMCPCommand, browserMCPSeedArgs); err != nil {
return fmt.Errorf("seed browser mcp: %w", err)
}
if err := d.migrateStockBrowserMCP(); err != nil {
return fmt.Errorf("migrate browser mcp: %w", err)
}
// NOTE: the placeholder ScopeSentry data-source MCP (empty URL + empty X-API-Key,
// disabled) is seeded directly in schema.sql §F so a raw `psql < schema.sql` init
// also gets it. schema.sql is Exec'd on every startup, so it stays idempotent.
+18
View File
@@ -51,6 +51,24 @@ func TestApplySchemaRetriesOnlyDeadlocks(t *testing.T) {
}
}
func TestCreateDatabaseSQLQuotesName(t *testing.T) {
tests := []struct {
name string
want string
}{
{"artex", `CREATE DATABASE "artex"`},
{"artex-db", `CREATE DATABASE "artex-db"`},
{"café", `CREATE DATABASE "café"`},
{`artex"`, `CREATE DATABASE "artex"""`},
{`x"; DROP TABLE y; --`, `CREATE DATABASE "x""; DROP TABLE y; --"`},
}
for _, tt := range tests {
if got := createDatabaseSQL(tt.name); got != tt.want {
t.Errorf("createDatabaseSQL(%q)=%q, want %q", tt.name, got, tt.want)
}
}
}
// testDSN returns the configured DSN, skipping the test when neither the env var
// nor a config file supplies one (DSN no longer has a built-in default).
func testDSN(t *testing.T) string {
+41
View File
@@ -230,6 +230,13 @@ func (s *ExplorationStore) AddNode(kind string, payload map[string]any, priority
return 0, err
}
defer tx.Rollback()
// Validate fact anchors before creating a node. Key-share locks retain the
// checked assets through commit, closing the check/insert deletion race.
if kind == KindFact && len(anchors) > 0 {
if err := checkFactAnchorAssets(tx, anchors); err != nil {
return 0, err
}
}
var id int64
if err := tx.QueryRow(`
INSERT INTO exploration_nodes(exploration_id, kind, payload, priority, state, origin)
@@ -245,6 +252,40 @@ VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`,
return id, tx.Commit()
}
func checkFactAnchorAssets(tx *sql.Tx, ids []int64) error {
rows, err := tx.Query("SELECT id FROM assets WHERE id = ANY($1::bigint[]) ORDER BY id FOR KEY SHARE", ids)
if err != nil {
return err
}
found := make(map[int64]bool, len(ids))
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return err
}
found[id] = true
}
err = rows.Err()
closeErr := rows.Close()
if err != nil {
return err
}
if closeErr != nil {
return closeErr
}
var missing []int64
for _, id := range ids {
if !found[id] {
missing = append(missing, id)
}
}
if len(missing) != 0 {
return fmt.Errorf("asset IDs do not exist: %v; use existing IDs or register the assets first", missing)
}
return nil
}
// AddIntent is a convenience: an open intent.
func (s *ExplorationStore) AddIntent(payload map[string]any, priority int, anchors []int64, origin string) (int64, error) {
if origin == "" {
+6 -1
View File
@@ -10,6 +10,7 @@ import (
"strconv"
"strings"
"sync/atomic"
"unicode/utf8"
"github.com/Autumn-27/norma/llm"
)
@@ -262,7 +263,11 @@ func isHardFailure(err error) bool {
func trimErr(err error) string {
s := strings.TrimSpace(strings.ReplaceAll(err.Error(), "\n", " "))
if len(s) > 300 {
s = s[:300] + "…"
cut := 300
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
s = s[:cut] + "…"
}
return s
}
+14
View File
@@ -8,6 +8,7 @@ import (
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/Autumn-27/norma/llm"
)
@@ -368,3 +369,16 @@ func TestExpiredWindowIsClosed(t *testing.T) {
t.Fatal("expired window should read as closed")
}
}
// A provider error body in Chinese is cut at 300 bytes; the cut must not split
// a rune, or the breaker's last_error is rejected by PostgreSQL as invalid UTF-8.
func TestTrimErrKeepsValidUTF8(t *testing.T) {
err := errors.New("openai: status 503: " + strings.Repeat("服务暂时不可用,请稍后重试。", 10))
got := trimErr(err)
if !utf8.ValidString(got) {
t.Fatalf("trimErr returned invalid UTF-8: %q", got)
}
if !strings.HasSuffix(got, "…") || len(got) > 300+len("…") {
t.Fatalf("trimErr = %q (%d bytes), want at most 300 bytes plus …", got, len(got))
}
}
+23
View File
@@ -69,6 +69,26 @@ func WithUsageSink(ctx context.Context, sink func(llm.Usage)) context.Context {
return context.WithValue(ctx, usageSinkContextKey{}, sink)
}
type stopSinkContextKey struct{}
// WithStopSink attaches a callback that receives the stop reason of every call
// made under ctx that completes normally, once per call, after the provider's
// last event ("" when the provider reported none). The harness keeps the stop
// reason only long enough to decide whether a turn used tools, so a host that
// must tell a provider refusal (Anthropic stop_reason "refusal", or
// finish_reason "content_filter" on OpenAI-compatible endpoints) from an
// ordinary end of turn observes it here.
func WithStopSink(ctx context.Context, sink func(stopReason string)) context.Context {
return context.WithValue(ctx, stopSinkContextKey{}, sink)
}
// reportStop hands stopReason to the ctx stop sink, if one is attached.
func reportStop(ctx context.Context, stopReason string) {
if sink, _ := ctx.Value(stopSinkContextKey{}).(func(string)); sink != nil {
sink(stopReason)
}
}
// Recorder wraps an llm.Provider and records every completion call.
type Recorder struct {
inner llm.Provider
@@ -223,6 +243,7 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S
}
// Stream completed normally.
reportStop(ctx, stopReason)
finish(streamErr)
}
}
@@ -254,6 +275,8 @@ func (r *Recorder) Complete(ctx context.Context, req llm.CompletionRequest) (llm
status := "ok"
if err != nil {
status = "error"
} else {
reportStop(ctx, stopReason)
}
r.recordUsage(ctx, taskID, expID, worker, usage, int(time.Since(start).Milliseconds()), status)
if recordBodies {
+42
View File
@@ -94,6 +94,48 @@ func TestUsageSinkSeesMeteredCalls(t *testing.T) {
}
}
// The stop sink sees the final stop reason of each call that completes, which the
// harness otherwise drops: a refusal is an empty, tool-less turn like any other.
func TestStopSinkSeesFinalStopReason(t *testing.T) {
var got []string
ctx := WithStopSink(context.Background(), func(stop string) { got = append(got, stop) })
recorder := Wrap(refusalStreamProvider{}, nil, "model", "profile", "", "", func() bool { return false })
for _, err := range recorder.Stream(ctx, llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
if _, _, _, err := recorder.Complete(ctx, llm.CompletionRequest{}); err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != "refusal" || got[1] != "stop" {
t.Fatalf("sink saw %q, want [refusal stop]", got)
}
// Without a sink on the context nothing is reported and nothing breaks.
for _, err := range recorder.Stream(context.Background(), llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
}
// refusalStreamProvider streams what Anthropic sends for a refusal before any
// output: message_start, then message_delta with stop_reason "refusal" and no
// content blocks at all.
type refusalStreamProvider struct{ completeProvider }
func (refusalStreamProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
if !yield(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 41}}, nil) {
return
}
if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "refusal", Usage: llm.Usage{InputTokens: 41}}, nil) {
return
}
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
type meteredStreamProvider struct{ completeProvider }
func (meteredStreamProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
+25 -10
View File
@@ -136,7 +136,7 @@ func FindingFilename(f *db.DBFinding) string {
// Defensive: strip one more path layer to rule out zip slip.
name = path.Base(name)
if len(name) > 120 {
name = name[:120]
name = strings.ToValidUTF8(name[:120], "")
}
return name + ".md"
}
@@ -154,21 +154,36 @@ func FindingsCSV(fs []*db.DBFinding) []byte {
for _, f := range items {
_ = w.Write([]string{
fmt.Sprintf("%d", f.ID),
findingTitle(f),
f.VulnClass,
nz(f.Severity, "info"),
nz(f.Status, "pending"),
nz(f.ReportState, "none"),
f.TaskDescription,
f.CreatedAt.Format("2006-01-02 15:04:05"),
strings.TrimSpace(f.Summary),
fmt.Sprint(len(f.TrafficBindings)), findingTrafficIDs(f),
csvCell(findingTitle(f)),
csvCell(f.VulnClass),
csvCell(nz(f.Severity, "info")),
csvCell(nz(f.Status, "pending")),
csvCell(nz(f.ReportState, "none")),
csvCell(f.TaskDescription),
csvCell(f.CreatedAt.Format("2006-01-02 15:04:05")),
csvCell(strings.TrimSpace(f.Summary)),
fmt.Sprint(len(f.TrafficBindings)),
csvCell(findingTrafficIDs(f)),
})
}
w.Flush()
return buf.Bytes()
}
// csvCell prefixes cells that spreadsheet apps treat as formulas. encoding/csv
// only quotes delimiters; Excel/LibreOffice still evaluate a leading
// '=', '+', '-', '@', tab, or CR when the file is opened.
func csvCell(s string) string {
if s == "" {
return s
}
switch s[0] {
case '=', '+', '-', '@', '\t', '\r':
return "'" + s
}
return s
}
func findingTrafficIDs(f *db.DBFinding) string {
ids := make([]string, 0, len(f.TrafficBindings))
for _, b := range f.TrafficBindings {
+41
View File
@@ -1,6 +1,8 @@
package report
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
"testing"
@@ -314,3 +316,42 @@ func TestFindingsExportsCarryQuality(t *testing.T) {
t.Errorf("export lost the binding count entirely\n%s", md)
}
}
func TestFindingsCSVNeutralizesFormulas(t *testing.T) {
out := FindingsCSV([]*db.DBFinding{{
ID: 7,
Name: `=HYPERLINK("http://evil.example/x","x")`,
VulnClass: "+cmd",
Severity: "high",
Status: "pending",
ReportState: "none",
TaskDescription: "@SUM(1+1)",
CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
Summary: "-2+3",
}})
if !bytes.HasPrefix(out, []byte("\xEF\xBB\xBF")) {
t.Fatal("CSV lost the UTF-8 BOM")
}
records, err := csv.NewReader(bytes.NewReader(out[3:])).ReadAll()
if err != nil {
t.Fatal(err)
}
if len(records) != 2 {
t.Fatalf("rows=%d, want header+1", len(records))
}
row := records[1]
want := map[int]string{
1: `'=HYPERLINK("http://evil.example/x","x")`,
2: `'+cmd`,
6: `'@SUM(1+1)`,
8: `'-2+3`,
}
for i, prefix := range want {
if row[i] != prefix {
t.Errorf("col %d = %q, want %q", i, row[i], prefix)
}
}
if strings.HasPrefix(row[3], "'") {
t.Errorf("plain severity %q should not be prefixed", row[3])
}
}
+47 -10
View File
@@ -37,7 +37,7 @@ func (s *Server) toolAskOperator() actool.CoreTool {
},
"image_path": map[string]any{
"type": "string",
"description": "Optional path to a screenshot (png/jpg/jpeg/webp/gif, max 10MB), e.g. the browser_take_screenshot output. It is copied into the task uploads and shown to the operator.",
"description": "Optional path to a screenshot (png/jpg/jpeg/webp/gif, max 10MB) under this task's working directory, e.g. the browser_take_screenshot output. It is copied into the task uploads and shown to the operator.",
},
},
"required": []any{"question"},
@@ -156,6 +156,38 @@ func askOperatorActivity(text string, att []chatAttachment, derived []string) db
return a
}
// resolveAskOperatorImage maps image_path onto a regular file inside taskDir.
// Relative paths are resolved from the task working directory (the worker CWD).
// ".." segments, paths that EvalSymlinks outside taskDir, and non-images are refused.
func resolveAskOperatorImage(taskDir, src string) (string, error) {
src = strings.TrimSpace(src)
ext := strings.ToLower(filepath.Ext(src))
if !askOperatorImageExt[ext] {
return "", fmt.Errorf("image_path must be a png/jpg/jpeg/webp/gif file, got %q", filepath.Base(src))
}
for _, el := range strings.Split(filepath.ToSlash(src), "/") {
if el == ".." {
return "", fmt.Errorf("image_path must stay inside the task working directory")
}
}
if !filepath.IsAbs(src) {
src = filepath.Join(taskDir, src)
}
realRoot, err := filepath.EvalSymlinks(taskDir)
if err != nil {
return "", fmt.Errorf("image not readable")
}
real, err := filepath.EvalSymlinks(src)
if err != nil {
return "", fmt.Errorf("image not readable")
}
rel, err := filepath.Rel(realRoot, real)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("image_path must stay inside the task working directory")
}
return real, nil
}
// stageAskOperatorImage copies the referenced image into the task's uploads dir
// (the same place chat uploads land, so the transcript attachment card resolves)
// and returns the attachment descriptor. Empty src returns no attachment.
@@ -164,25 +196,30 @@ func stageAskOperatorImage(dataDir, taskID, src string) ([]chatAttachment, error
if src == "" {
return nil, nil
}
ext := strings.ToLower(filepath.Ext(src))
if !askOperatorImageExt[ext] {
return nil, fmt.Errorf("image_path must be a png/jpg/jpeg/webp/gif file, got %q", filepath.Base(src))
}
st, err := os.Stat(src)
taskDir := filepath.Join(dataDir, "tasks", taskID)
resolved, err := resolveAskOperatorImage(taskDir, src)
if err != nil {
return nil, fmt.Errorf("image not readable: %v", err)
return nil, err
}
st, err := os.Stat(resolved)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
if !st.Mode().IsRegular() {
return nil, fmt.Errorf("image_path must be a regular file")
}
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
dir := filepath.Join(dataDir, "tasks", taskID, "uploads")
dir := filepath.Join(taskDir, "uploads")
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
ext := strings.ToLower(filepath.Ext(resolved))
name := fmt.Sprintf("ask-operator-%d%s", time.Now().Unix(), ext)
in, err := os.Open(src)
in, err := os.Open(resolved)
if err != nil {
return nil, err
return nil, fmt.Errorf("image not readable")
}
defer in.Close()
out, err := os.Create(filepath.Join(dir, name))
+47 -7
View File
@@ -12,7 +12,11 @@ import (
func TestStageAskOperatorImage(t *testing.T) {
dir := t.TempDir()
src := filepath.Join(dir, "shot.png")
taskDir := filepath.Join(dir, "tasks", "7")
if err := os.MkdirAll(taskDir, 0o755); err != nil {
t.Fatal(err)
}
src := filepath.Join(taskDir, "shot.png")
if err := os.WriteFile(src, []byte("fakepng"), 0o644); err != nil {
t.Fatal(err)
}
@@ -23,31 +27,67 @@ func TestStageAskOperatorImage(t *testing.T) {
t.Fatalf("empty src: att=%v err=%v", att, err)
}
// valid image -> copied under the task uploads, descriptor matches the chat format
att, err = stageAskOperatorImage(dir, "7", src)
// relative path from the task working directory (worker CWD)
att, err = stageAskOperatorImage(dir, "7", "shot.png")
if err != nil || len(att) != 1 {
t.Fatalf("valid src: att=%v err=%v", att, err)
}
if !strings.HasPrefix(att[0].Path, "uploads/ask-operator-") || !strings.HasSuffix(att[0].Path, ".png") {
t.Fatalf("unexpected attachment path %q", att[0].Path)
}
if _, err := os.Stat(filepath.Join(dir, "tasks", "7", "uploads", att[0].Name)); err != nil {
if _, err := os.Stat(filepath.Join(taskDir, "uploads", att[0].Name)); err != nil {
t.Fatalf("copy missing: %v", err)
}
// absolute path still accepted when it stays inside the task dir
att, err = stageAskOperatorImage(dir, "7", src)
if err != nil || len(att) != 1 {
t.Fatalf("absolute inside task dir: att=%v err=%v", att, err)
}
// wrong extension rejected
bad := filepath.Join(dir, "payload.exe")
bad := filepath.Join(taskDir, "payload.exe")
if err := os.WriteFile(bad, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := stageAskOperatorImage(dir, "7", bad); err == nil || !strings.Contains(err.Error(), "png/jpg") {
if _, err := stageAskOperatorImage(dir, "7", "payload.exe"); err == nil || !strings.Contains(err.Error(), "png/jpg") {
t.Fatalf("expected extension rejection, got %v", err)
}
// missing file rejected
if _, err := stageAskOperatorImage(dir, "7", filepath.Join(dir, "nope.png")); err == nil {
if _, err := stageAskOperatorImage(dir, "7", "nope.png"); err == nil {
t.Fatal("expected missing-file rejection")
}
outside := filepath.Join(dir, "outside.png")
if err := os.WriteFile(outside, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := stageAskOperatorImage(dir, "7", filepath.Join("..", "..", "outside.png")); err == nil {
t.Fatal("expected .. rejection")
}
if _, err := stageAskOperatorImage(dir, "7", outside); err == nil {
t.Fatal("expected outside-path rejection")
}
otherDir := filepath.Join(dir, "tasks", "8")
if err := os.MkdirAll(otherDir, 0o755); err != nil {
t.Fatal(err)
}
other := filepath.Join(otherDir, "shot.png")
if err := os.WriteFile(other, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := stageAskOperatorImage(dir, "7", other); err == nil {
t.Fatal("expected other-task rejection")
}
link := filepath.Join(taskDir, "link.png")
if err := os.Symlink(outside, link); err != nil {
t.Logf("symlink test skipped: %v", err)
} else if _, err := stageAskOperatorImage(dir, "7", "link.png"); err == nil {
t.Fatal("expected symlink-out rejection")
}
}
// The emitted activity must carry the {text, attachments} Detail shape the
+29
View File
@@ -35,6 +35,8 @@ const (
// length, so passwords set under the old 8-character minimum still log in.
minPasswordRunes = 12
maxPasswordBytes = 72
pwdLimitTokenPrefix = "tok:"
)
// errDataSourceUnavailable is the uniform reply when a password-related read fails.
@@ -479,6 +481,12 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, 401, "Unauthorized")
return
}
if wait := s.passwordChangeWait(r); wait > 0 {
secs := int((wait + time.Second - 1) / time.Second)
w.Header().Set("Retry-After", strconv.Itoa(secs))
writeErr(w, 429, fmt.Sprintf("Too many password change attempts, try again in %d seconds", secs))
return
}
var req struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
@@ -520,10 +528,31 @@ func (s *Server) authChangePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, 500, "Save failed: "+err.Error())
return
}
s.passwordChangeReset(r)
s.applyPasswordVersion(version)
writeJSON(w, 200, map[string]any{"ok": true})
}
// passwordChangeWait records one authenticated change-password attempt against
// the client IP and the session token. Either bucket can block; rotating the
// source address with a stolen token still hits the token bucket.
func (s *Server) passwordChangeWait(r *http.Request) time.Duration {
if s.pwdLimit == nil {
return 0
}
ip := clientIP(r, s.trustedProxies)
tok := pwdLimitTokenPrefix + extractToken(r)
return max(s.pwdLimit.allow(ip), s.pwdLimit.allow(tok))
}
func (s *Server) passwordChangeReset(r *http.Request) {
if s.pwdLimit == nil {
return
}
s.pwdLimit.reset(clientIP(r, s.trustedProxies))
s.pwdLimit.reset(pwdLimitTokenPrefix + extractToken(r))
}
// POST /api/auth/login — validates username/password and returns a JWT.
func (s *Server) authLogin(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
+3 -1
View File
@@ -59,6 +59,7 @@ func TestChangePasswordRevokesOldTokenAndKeepsItWhenSaveFails(t *testing.T) {
m: m,
jwtKey: []byte("0123456789abcdef0123456789abcdef"),
loginLimit: newLoginLimiter(time.Now),
pwdLimit: newLoginLimiter(time.Now),
authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
}
@@ -153,7 +154,7 @@ func TestUnreadablePasswordVersionRejectsSessions(t *testing.T) {
}
defer m.Close()
key := []byte("0123456789abcdef0123456789abcdef")
s := &Server{m: m, jwtKey: key, loginLimit: newLoginLimiter(time.Now)}
s := &Server{m: m, jwtKey: key, loginLimit: newLoginLimiter(time.Now), pwdLimit: newLoginLimiter(time.Now)}
s.authVersionKey = fmt.Sprintf("test.password_version.%d", time.Now().UnixNano())
tok, err := signJWTVersion(key, 1)
if err != nil {
@@ -194,6 +195,7 @@ func TestLoginRereadsPasswordVersionWhenUnreadable(t *testing.T) {
m: m,
jwtKey: []byte("0123456789abcdef0123456789abcdef"),
loginLimit: newLoginLimiter(time.Now),
pwdLimit: newLoginLimiter(time.Now),
authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
}
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
const changePasswordOK = "correct-horse-1"
func changePasswordRequest(remote, token string) *http.Request {
r := httptest.NewRequest("POST", "/api/auth/change-password", nil)
r.RemoteAddr = remote
r.Header.Set("Authorization", "Bearer "+token)
return r
}
func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) {
clk := newFakeClock()
s := &Server{pwdLimit: newLoginLimiter(clk.now)}
const tok = "stolen-session"
for i := 0; i < loginMaxAttempts; i++ {
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait != 0 {
t.Fatalf("attempt %d blocked after %v", i+1, wait)
}
}
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait <= 0 {
t.Fatal("same IP and token not blocked")
}
s = &Server{pwdLimit: newLoginLimiter(clk.now)}
for i := 0; i < loginMaxAttempts; i++ {
remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
if wait := s.passwordChangeWait(changePasswordRequest(remote, tok)); wait != 0 {
t.Fatalf("rotated IP attempt %d blocked after %v", i+1, wait)
}
}
if wait := s.passwordChangeWait(changePasswordRequest("203.0.113.9:40000", tok)); wait <= 0 {
t.Fatal("stolen token still allowed after rotating the client IP")
}
s = &Server{pwdLimit: newLoginLimiter(clk.now)}
for i := 0; i < loginMaxAttempts; i++ {
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 {
t.Fatalf("fill attempt %d blocked after %v", i+1, wait)
}
}
s.passwordChangeReset(changePasswordRequest("192.0.2.51:40000", tok))
if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 {
t.Fatalf("after reset blocked after %v", wait)
}
}
func changePasswordServer(t *testing.T, clk *fakeClock) (*Server, string, func(remote, old, neu string) *httptest.ResponseRecorder) {
t.Helper()
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v)", err)
}
t.Cleanup(func() { m.Close() })
stamp := time.Now().UnixNano()
s := &Server{
m: m,
jwtKey: []byte("0123456789abcdef0123456789abcdef"),
loginLimit: newLoginLimiter(clk.now),
pwdLimit: newLoginLimiter(clk.now),
authHashKey: fmt.Sprintf("test.password_hash.%d", stamp),
authVersionKey: fmt.Sprintf("test.password_version.%d", stamp),
}
t.Cleanup(func() {
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, s.authHashKey, s.authVersionKey)
})
hash, err := bcrypt.GenerateFromPassword([]byte(changePasswordOK), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
if err := m.pg.SetSetting(s.passwordHashKey(), string(hash)); err != nil {
t.Fatal(err)
}
s.applyPasswordVersion(0)
tok, err := signJWTVersion(s.jwtKey, 0)
if err != nil {
t.Fatal(err)
}
post := func(remote, old, neu string) *httptest.ResponseRecorder {
body := fmt.Sprintf(`{"old_password":%q,"new_password":%q}`, old, neu)
r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
r.RemoteAddr = remote
r.Header.Set("Authorization", "Bearer "+tok)
w := httptest.NewRecorder()
s.authChangePassword(w, r)
return w
}
return s, tok, post
}
func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) {
clk := newFakeClock()
_, _, post := changePasswordServer(t, clk)
const ip = "192.0.2.40:40000"
for i := 0; i < loginMaxAttempts; i++ {
if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
}
w := post(ip, changePasswordOK, "correct-horse-9")
if w.Code != 429 {
t.Fatalf("status=%d want 429; body=%s", w.Code, w.Body.String())
}
if got := w.Header().Get("Retry-After"); got != "60" {
t.Fatalf("Retry-After=%q want 60", got)
}
var body struct {
Error string `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Error == "" {
t.Fatalf("want a JSON error body, got %s (err=%v)", w.Body.String(), err)
}
}
func TestChangePasswordRateLimitFollowsStolenTokenAcrossIPs(t *testing.T) {
clk := newFakeClock()
_, _, post := changePasswordServer(t, clk)
for i := 0; i < loginMaxAttempts; i++ {
remote := fmt.Sprintf("198.51.100.%d:40000", i+1)
if w := post(remote, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String())
}
}
if w := post("203.0.113.9:40000", changePasswordOK, "correct-horse-9"); w.Code != 429 {
t.Fatalf("rotated IP: status=%d want 429; body=%s", w.Code, w.Body.String())
}
}
func TestChangePasswordSuccessResetsCounter(t *testing.T) {
clk := newFakeClock()
s, tok, post := changePasswordServer(t, clk)
const ip = "192.0.2.41:40000"
for i := 0; i < loginMaxAttempts-1; i++ {
if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
}
if w := post(ip, changePasswordOK, "correct-horse-2"); w.Code != 200 {
t.Fatalf("status=%d want 200; body=%s", w.Code, w.Body.String())
}
if s.sessionOK(tok) {
t.Fatal("token from before the password change is still accepted")
}
w := httptest.NewRecorder()
login := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"ARTEX","password":"correct-horse-2"}`))
login.RemoteAddr = ip
s.authLogin(w, login)
if w.Code != 200 {
t.Fatalf("login after change: status=%d body=%s", w.Code, w.Body.String())
}
var issued struct {
Token string `json:"token"`
}
if err := json.Unmarshal(w.Body.Bytes(), &issued); err != nil || issued.Token == "" {
t.Fatalf("login token: %v body=%s", err, w.Body.String())
}
post2 := func(old, neu string) *httptest.ResponseRecorder {
body := fmt.Sprintf(`{"old_password":%q,"new_password":%q}`, old, neu)
r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
r.RemoteAddr = ip
r.Header.Set("Authorization", "Bearer "+issued.Token)
rec := httptest.NewRecorder()
s.authChangePassword(rec, r)
return rec
}
for i := 0; i < loginMaxAttempts; i++ {
if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("after reset attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
}
if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 429 {
t.Fatalf("after reset: status=%d want 429; body=%s", w.Code, w.Body.String())
}
}
func TestChangePasswordUnauthenticatedDoesNotCount(t *testing.T) {
clk := newFakeClock()
s, _, post := changePasswordServer(t, clk)
const ip = "192.0.2.42:40000"
body := `{"old_password":"wrong-password-xx","new_password":"correct-horse-9"}`
for i := 0; i < loginMaxAttempts+1; i++ {
r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body))
r.RemoteAddr = ip
r.Header.Set("Authorization", "Bearer not-a-token")
w := httptest.NewRecorder()
s.authChangePassword(w, r)
if w.Code != 401 {
t.Fatalf("unauthenticated attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String())
}
}
if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 {
t.Fatalf("counted unauthenticated attempts: status=%d body=%s", w.Code, w.Body.String())
}
}
+32
View File
@@ -0,0 +1,32 @@
package server
import (
"encoding/json"
"testing"
)
func TestDecodeStrMapJSONNull(t *testing.T) {
m := decodeStrMap(json.RawMessage("null"))
if m == nil {
t.Fatal("JSON null must decode to an empty map, not nil")
}
m["NODE_EXTRA_CA_CERTS"] = "/tmp/ca.pem"
if m["NODE_EXTRA_CA_CERTS"] != "/tmp/ca.pem" {
t.Fatal("decoded map must be writable")
}
empty := decodeStrMap(nil)
if empty == nil {
t.Fatal("empty input must decode to an empty map")
}
got := decodeStrMap(json.RawMessage(`{"FOO":"bar"}`))
if got["FOO"] != "bar" {
t.Fatalf("got %#v", got)
}
invalid := decodeStrMap(json.RawMessage(`["not","an","object"]`))
if invalid == nil {
t.Fatal("invalid JSON must decode to an empty map")
}
}
+8
View File
@@ -672,6 +672,14 @@ func (h steerHooks) Stop(ctx context.Context, messages []llm.Message) (bool, []s
if prevent || len(blocking) > 0 || h.nudges == nil || h.limit <= 0 || !isThinkingOnlyTurn(messages) {
return prevent, blocking, msg
}
// A refused turn is empty as well, but there the provider declined the request;
// the model did not think and forget to act. A rerun resends the same
// conversation and is refused again, so let the run end and be reported as a
// refusal (terminalText) instead.
if stop := agent.LastStopReason(ctx); agent.IsRefusalStop(stop) {
log.Printf("[work %s] provider refused the turn (stop_reason=%s), not injecting an idle-turn rerun", h.label, stop)
return prevent, blocking, msg
}
n := h.nudges.Add(1)
if n > int64(h.limit) {
log.Printf("[work %s] idle turns (thinking only, no body text, no tools) reached the rerun cap %d, letting it finish", h.label, h.limit)
+59
View File
@@ -2,12 +2,71 @@ package server
import (
"context"
"iter"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/norma/llm"
)
// stopReasonProvider ends a streamed call with the given stop reason and no
// content, the shape of a provider refusal before any output.
type stopReasonProvider struct{ stop string }
func (p stopReasonProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
if !yield(llm.StreamEvent{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: 41}}, nil) {
return
}
if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: p.stop}, nil) {
return
}
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
func (p stopReasonProvider) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return llm.Message{Role: llm.RoleAssistant}, p.stop, llm.Usage{}, nil
}
// runCtxAfter returns a run context whose latest recorded model call ended with stop.
func runCtxAfter(t *testing.T, stop string) context.Context {
t.Helper()
ctx := agent.WithStopTracker(context.Background())
rec := llmrec.Wrap(stopReasonProvider{stop: stop}, nil, "model", "profile", "", "", func() bool { return false })
for _, err := range rec.Stream(ctx, llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
return ctx
}
// A provider refusal leaves an assistant turn with no text and no tools, the same
// shape as an idle turn, but rerunning it only sends the same conversation to be
// refused again.
func TestSteerHooksStopDoesNotRerunProviderRefusal(t *testing.T) {
refused := []llm.Message{llm.UserText("start"), {Role: llm.RoleAssistant}}
for _, stop := range []string{"refusal", "content_filter"} {
h := steerHooks{nudges: &atomic.Int64{}, limit: defaultEmptyTurnNudges, label: "worker-1 · #1"}
prevent, blocking, _ := h.Stop(runCtxAfter(t, stop), refused)
if prevent || blocking != nil {
t.Fatalf("%s: refusal was rerun: prevent=%v blocking=%v", stop, prevent, blocking)
}
if n := h.nudges.Load(); n != 0 {
t.Fatalf("%s: refusal consumed the idle-turn quota: %d", stop, n)
}
}
// Control: the same empty turn after an ordinary end of turn is still nudged.
h := steerHooks{nudges: &atomic.Int64{}, limit: defaultEmptyTurnNudges, label: "worker-1 · #1"}
if _, blocking, _ := h.Stop(runCtxAfter(t, "end_turn"), refused); len(blocking) != 1 || blocking[0] != emptyTurnNudge {
t.Fatalf("idle turn after end_turn not nudged: %v", blocking)
}
}
// Identifying and nudging empty turns (thinking only, no text, no tools); see steerHooks.Stop.
func assistantThinking(text string) llm.Message {
+38
View File
@@ -0,0 +1,38 @@
package server
import (
"encoding/json"
"log"
"github.com/Autumn-27/artex/agent"
)
// SeedTool only inserts new rows. Repair existing built-ins too, while keeping
// descriptions, bindings, enabled/deferred flags and parameter annotations.
func (s *Server) seedFactInputSchema() {
row, err := s.m.pg.GetTool("record_fact")
if err != nil {
log.Printf("[facts] read record_fact schema: %v", err)
return
}
if row == nil || !row.System || row.Kind != "builtin" {
return
}
var schema map[string]any
if err := json.Unmarshal(row.Schema, &schema); err != nil {
log.Printf("[facts] decode record_fact schema: %v", err)
return
}
raw, err := json.Marshal(agent.RepairRecordFactSchema(schema))
if err != nil {
log.Printf("[facts] encode record_fact schema: %v", err)
return
}
// Compare-and-swap preserves concurrent operator edits; JSONB equality
// avoids changing updated_at again on every startup.
if _, err := s.m.pg.Exec(`UPDATE tools SET schema=$2::jsonb, updated_at=now()
WHERE key='record_fact' AND system AND kind='builtin'
AND schema=$1::jsonb AND schema IS DISTINCT FROM $2::jsonb`, string(row.Schema), string(raw)); err != nil {
log.Printf("[facts] repair record_fact schema: %v", err)
}
}
+106
View File
@@ -0,0 +1,106 @@
package server
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
actool "github.com/Autumn-27/norma/tool"
)
func TestRecordFactInputSchemaUpgrade(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.SetToolResolve(nil) })
pg := m.pg
old, err := pg.GetTool("record_fact")
if err != nil || old == nil {
t.Fatal("missing record_fact", err)
}
bindings, _ := json.Marshal(old.Agents)
t.Cleanup(func() { pg.UpdateTool(old.Key, old.Description, old.Schema, bindings, old.Enabled) })
legacy := map[string]any{
"type": "object", "required": []string{"summary"},
"anyOf": []any{map[string]any{"required": []string{"summary"}}},
"properties": map[string]any{
"summary": map[string]any{"type": "string", "description": "operator summary"},
"confidence": map[string]any{"type": "string", "default": "inferred"},
"custom": map[string]any{"type": "string"},
"facts": map[string]any{"type": "array", "items": map[string]any{"type": "object"}},
},
}
raw, _ := json.Marshal(legacy)
if err := pg.UpdateTool("record_fact", "operator tool", raw, bindings, old.Enabled); err != nil {
t.Fatal(err)
}
check := func(schema map[string]any) {
t.Helper()
if _, ok := schema["required"]; ok {
t.Fatal("top-level summary still required for batches")
}
if _, ok := schema["anyOf"]; ok {
t.Fatal("root anyOf still present")
}
if schema["additionalProperties"] != false {
t.Fatal("unknown fields allowed")
}
props := schema["properties"].(map[string]any)
items := props["facts"].(map[string]any)["items"].(map[string]any)
itemProps := items["properties"].(map[string]any)
if props["tested_asset_ids"] == nil || itemProps["tested_asset_ids"] == nil || itemProps["summary"] == nil {
t.Fatal("repaired schema missing alias or batch summary")
}
if props["summary"].(map[string]any)["description"] != "operator summary" ||
props["confidence"].(map[string]any)["default"] != "inferred" || props["custom"] != nil {
t.Fatal("operator annotations lost")
}
if err := actool.ValidateInput(schema, json.RawMessage(`{"facts":[{"summary":"complete batch item"}]}`)); err != nil {
t.Fatal("valid batch rejected", err)
}
}
// Runtime repair protects cached or edited rows even before startup migration.
tools := agent.ToolResolve()(context.Background(), "worker", agent.NewToolSet(nil, "").WorkerTools())
found := false
for _, tool := range tools {
if tool.Name() == "record_fact" {
check(tool.InputSchema())
found = true
}
}
if !found {
t.Fatal("record_fact not resolved")
}
s.seedFactInputSchema()
repaired, err := pg.GetTool("record_fact")
if err != nil || repaired == nil {
t.Fatal(err)
}
var schema map[string]any
if err := json.Unmarshal(repaired.Schema, &schema); err != nil {
t.Fatal(err)
}
check(schema)
if repaired.Description != "operator tool" || repaired.Enabled != old.Enabled {
t.Fatal("operator tool settings changed")
}
var before, after time.Time
if err := pg.QueryRow("SELECT updated_at FROM tools WHERE key='record_fact'").Scan(&before); err != nil {
t.Fatal(err)
}
s.seedFactInputSchema()
if err := pg.QueryRow("SELECT updated_at FROM tools WHERE key='record_fact'").Scan(&after); err != nil {
t.Fatal(err)
}
if !before.Equal(after) {
t.Fatal("second migration changed the row")
}
}
+2 -2
View File
@@ -47,8 +47,8 @@ func TestRecordFactSourceSchemaUpgrade(t *testing.T) {
if err := pg.UpdateTool("record_fact", "operator description", custom, bindings, true); err != nil {
t.Fatal(err)
}
if src := resolvedRecordFactProps(t)["source"]; src != nil {
t.Fatalf("precondition: stored schema should not expose source yet: %v", src)
if src := resolvedRecordFactProps(t)["source"]; src == nil {
t.Fatal("runtime contract repair must expose source even before startup migration")
}
snapshot := func() (string, string, time.Time) {
+17
View File
@@ -14,6 +14,7 @@ import (
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
@@ -480,3 +481,19 @@ func TestFindingTrafficUTF8SegmentsAndInheritedWrites(t *testing.T) {
}
}
}
func TestFindingsZipLongNonASCIINameStaysUTF8(t *testing.T) {
f := &db.DBFinding{ID: 7, Severity: "high", Name: strings.Repeat("跨站脚本", 12)}
var buf bytes.Buffer
if err := writeFindingsEvidenceZip(&buf, []*db.DBFinding{f}, t.TempDir(), time.Now()); err != nil {
t.Fatal(err)
}
archive, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatal(err)
}
entry := archive.File[0]
if entry.NonUTF8 || !utf8.ValidString(entry.Name) || !strings.HasPrefix(entry.Name, "high_跨站脚本") || !strings.HasSuffix(entry.Name, ".md") {
t.Fatalf("entry name %q (NonUTF8=%v)", entry.Name, entry.NonUTF8)
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ func loginServer(t *testing.T, clk *fakeClock) (*Server, func(remote, password s
}
return string(hash), true, nil
}
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef"), loginLimit: newLoginLimiter(clk.now)}
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef"), loginLimit: newLoginLimiter(clk.now), pwdLimit: newLoginLimiter(clk.now)}
post := func(remote, password string, hdr map[string]string) *httptest.ResponseRecorder {
body := fmt.Sprintf(`{"username":"ARTEX","password":%q}`, password)
r := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(body))
+6 -2
View File
@@ -782,8 +782,12 @@ func decodeStrSlice(raw json.RawMessage) []string {
func decodeStrMap(raw json.RawMessage) map[string]string {
out := map[string]string{}
if len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
if len(raw) == 0 {
return out
}
if err := json.Unmarshal(raw, &out); err != nil || out == nil {
// JSON null unmarshals into a nil map. Callers write env["k"]=v.
return map[string]string{}
}
return out
}
+24
View File
@@ -0,0 +1,24 @@
package server
import (
"slices"
"testing"
)
func TestStripProxyArgsLeavesBrowserMCPFlags(t *testing.T) {
in := []string{"--headless", "--browser", "chromium", "--proxy-server", "http://127.0.0.1:8788"}
got := stripProxyArgs(in)
want := []string{"--headless", "--browser", "chromium"}
if !slices.Equal(got, want) {
t.Fatalf("got %q, want %q", got, want)
}
if in[3] != "--proxy-server" {
t.Fatal("input mutated")
}
equals := []string{"--headless", "--proxy-server=http://127.0.0.1:8788", "--browser", "chromium"}
got = stripProxyArgs(equals)
if !slices.Equal(got, want) {
t.Fatalf("equals form: got %q, want %q", got, want)
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error
// discoverEmptyMCPsOnStartup fills the tool cache for any enabled MCP that has none
// yet (notably the seeded browser MCP on first run). Runs sequentially in one
// goroutine so we never spawn many stdio servers (npx) at once, and never blocks
// goroutine so we never spawn many stdio servers at once, and never blocks
// startup. Best-effort: a failure leaves the cache empty to retry next start.
func (s *Server) discoverEmptyMCPsOnStartup() {
servers, err := s.m.pg.ListMCP()
+1
View File
@@ -571,6 +571,7 @@ func (s *Server) seedOrchestrationTools() {
s.seedFindingWorkflowTools()
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.seedFactInputSchema() // restore record_fact single/batch contracts
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
+2 -1
View File
@@ -66,6 +66,7 @@ type Server struct {
authVersionKey string
loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login
pwdLimit *loginLimiter // attempt limit on POST /api/auth/change-password (IP + session token)
trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP
// concMu serializes concurrency-cap decisions (admission + reconcile) so a
@@ -182,7 +183,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
profChatAgents: map[int64]*agent.ChatAgent{},
provByProfile: map[int64]*provEntry{},
taskAgents: map[string]*taskAgentBundle{}, archiveWake: make(chan struct{}, 1),
loginLimit: newLoginLimiter(time.Now)}
loginLimit: newLoginLimiter(time.Now), pwdLimit: newLoginLimiter(time.Now)}
s.llmHealth, s.llmHealthSync = newLLMHealthRegistry(ctx, m.pg)
for _, o := range opts {
o(s)
+35
View File
@@ -0,0 +1,35 @@
package traffic
import (
"math"
"testing"
)
func TestClampBlobRange(t *testing.T) {
cases := []struct {
name string
offset, length int64
size int64
wantOff, wantN int64
wantEmpty bool
}{
{"zero length means rest", 2, 0, 10, 2, 8, false},
{"negative length means rest", 2, -1, 10, 2, 8, false},
{"exact rest", 2, 8, 10, 2, 8, false},
{"past end", 2, 100, 10, 2, 8, false},
{"offset at end", 10, 4, 10, 10, 0, true},
{"offset past end", 11, 4, 10, 11, 0, true},
{"negative offset", -3, 4, 10, 0, 4, false},
{"empty blob", 0, 10, 0, 0, 0, true},
{"overflow length", 1, math.MaxInt64, 10, 1, 9, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
off, n, empty := clampBlobRange(tc.offset, tc.length, tc.size)
if off != tc.wantOff || n != tc.wantN || empty != tc.wantEmpty {
t.Fatalf("got off=%d n=%d empty=%v, want off=%d n=%d empty=%v",
off, n, empty, tc.wantOff, tc.wantN, tc.wantEmpty)
}
})
}
}
+21
View File
@@ -38,6 +38,15 @@ func (t *Traffic) RecordExternal(e ExternalExchange) error {
if method == "" {
return fmt.Errorf("empty method for %q", e.URL)
}
if !validHeaderName(method) {
return fmt.Errorf("invalid method %q", e.Method)
}
if err := validateExternalHeaders(e.RequestHeaders); err != nil {
return err
}
if err := validateExternalHeaders(e.ResponseHeaders); err != nil {
return err
}
status := e.Status
if status == 0 {
status = 200
@@ -120,6 +129,18 @@ VALUES(?,?,?,?,?,?,?)`,
return nil
}
func validateExternalHeaders(h map[string]string) error {
for k, v := range h {
if !validHeaderName(k) {
return fmt.Errorf("invalid header name %q", k)
}
if strings.ContainsAny(v, "\r\n\x00") {
return fmt.Errorf("header %s contains a line break", k)
}
}
return nil
}
func toHeaderMap(flat map[string]string) map[string][]string {
m := make(map[string][]string, len(flat))
for k, v := range flat {
+8
View File
@@ -68,10 +68,18 @@ func TestRecordExternalRejectsBadInput(t *testing.T) {
{Method: "GET", URL: "not a url"},
{Method: "GET", URL: ""},
{Method: "", URL: "https://api.example.com/"},
{Method: "GET\r\nX-Injected: 1", URL: "https://api.example.com/"},
{Method: "GET", URL: "https://api.example.com/", RequestHeaders: map[string]string{"X-Bad\nName": "1"}},
{Method: "GET", URL: "https://api.example.com/", RequestHeaders: map[string]string{"x-ok": "one\r\ntwo"}},
{Method: "GET", URL: "https://api.example.com/", ResponseHeaders: map[string]string{"x-capture": "ok\r\nX-Forged-Header: injected"}},
{Method: "GET", URL: "https://api.example.com/", ResponseHeaders: map[string]string{"x-nul": "a\x00b"}},
}
for i, c := range cases {
if err := tr.RecordExternal(c); err == nil {
t.Fatalf("case %d: expected an error for %+v", i, c)
}
}
if n, _ := tr.Count(); n != 0 {
t.Fatalf("rejected exchanges were stored: count=%d", n)
}
}
+19 -7
View File
@@ -942,15 +942,10 @@ func (t *Traffic) BlobRange(hash string, offset, length int64) (data []byte, tot
return nil, 0, err
}
defer f.Close()
if offset < 0 {
offset = 0
}
if offset >= size {
offset, length, empty := clampBlobRange(offset, length, size)
if empty {
return nil, size, nil
}
if length <= 0 || offset+length > size {
length = size - offset
}
buf := make([]byte, length)
n, err := f.ReadAt(buf, offset)
if err != nil && !errors.Is(err, io.EOF) {
@@ -959,6 +954,23 @@ func (t *Traffic) BlobRange(hash string, offset, length int64) (data []byte, tot
return buf[:n], size, nil
}
// clampBlobRange returns a safe (offset, length) for a blob of size bytes.
// length > size-offset is used instead of offset+length > size so a huge
// length cannot wrap int64 and skip the cap.
func clampBlobRange(offset, length, size int64) (off, n int64, empty bool) {
if offset < 0 {
offset = 0
}
if size <= 0 || offset >= size {
return offset, 0, true
}
remain := size - offset
if length <= 0 || length > remain {
length = remain
}
return offset, length, false
}
// ExchangeMeta is one row of the index (returned by Search).
type ExchangeMeta struct {
ID string `json:"id"`
+6 -4
View File
@@ -60,6 +60,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import { parseCompanyScopeText } from "@/lib/company-scope";
import { httpHref } from "@/lib/http-href";
import type { Asset, Company, CompanyScopeRule } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -605,10 +606,11 @@ export default function AssetsPage() {
const isHttp = a.service_type === "http";
const svc = a.service_name || (isHttp ? "http" : "") || a.service_type || "";
let domainCell: React.ReactNode = "—";
if (isHttp && a.url) {
const href = isHttp ? httpHref(a.url) : undefined;
if (href) {
domainCell = (
<a
href={a.url}
href={href}
target="_blank"
rel="noreferrer"
className="text-blue-600 hover:underline dark:text-blue-400"
@@ -616,8 +618,8 @@ export default function AssetsPage() {
{a.domain || a.url}
</a>
);
} else if (a.domain) {
domainCell = a.domain;
} else if (a.domain || a.url) {
domainCell = a.domain || a.url;
}
return (
<TableRow key={a.id} className={selected.has(a.id) ? "bg-muted/40" : undefined}>
+19
View File
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import test from "node:test";
import { httpHref } from "./http-href.ts";
test("httpHref allows http and https", () => {
assert.equal(httpHref("https://example.com/a"), "https://example.com/a");
assert.equal(httpHref("http://192.0.2.1:8080/x"), "http://192.0.2.1:8080/x");
assert.equal(httpHref(" https://example.com/a "), "https://example.com/a");
});
test("httpHref refuses javascript, data, and junk", () => {
assert.equal(httpHref("javascript:alert(1)"), undefined);
assert.equal(httpHref("JAVASCRIPT:alert(1)"), undefined);
assert.equal(httpHref("data:text/html,x"), undefined);
assert.equal(httpHref("vbscript:x"), undefined);
assert.equal(httpHref("/relative"), undefined);
assert.equal(httpHref(""), undefined);
assert.equal(httpHref(null), undefined);
});
+18
View File
@@ -0,0 +1,18 @@
// httpHref returns raw when it is an http(s) URL, otherwise undefined.
// Asset URLs are operator/target-supplied; javascript: and data: must not
// become href values.
export function httpHref(raw: string | undefined | null): string | undefined {
const s = (raw ?? "").trim();
if (!s) {
return undefined;
}
try {
const u = new URL(s);
if (u.protocol === "http:" || u.protocol === "https:") {
return u.href;
}
} catch {
// not a URL
}
return undefined;
}