mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:13:54 +08:00
Compare commits
199
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8881bbac45 | ||
|
|
15f1b1b845 | ||
|
|
d685e58fbc | ||
|
|
fdc6e5a614 | ||
|
|
d597c156d7 | ||
|
|
c985c83085 | ||
|
|
0b10eb7d36 | ||
|
|
029b631b58 | ||
|
|
09de4486ef | ||
|
|
bd7d430158 | ||
|
|
3fae067156 | ||
|
|
406153628c | ||
|
|
5dc4627209 | ||
|
|
38d982d5de | ||
|
|
27c0938bd8 | ||
|
|
c86cee8853 | ||
|
|
09aa564163 | ||
|
|
d058b7386d | ||
|
|
89b7986338 | ||
|
|
8e9cb6e1a5 | ||
|
|
0fd8ff579f | ||
|
|
fafe673e39 | ||
|
|
fe0aab6624 | ||
|
|
f89a297284 | ||
|
|
c34299c6cd | ||
|
|
2514469bae | ||
|
|
e91d94b18c | ||
|
|
114718fa8f | ||
|
|
afceb46e53 | ||
|
|
53957efb8b | ||
|
|
3b6caf63f5 | ||
|
|
757e1da323 | ||
|
|
4295e366b2 | ||
|
|
c7d44134a3 | ||
|
|
57304785e5 | ||
|
|
05daf29120 | ||
|
|
d6ba440c17 | ||
|
|
ffb668842e | ||
|
|
44fad586e0 | ||
|
|
9ae08ed457 | ||
|
|
c42da9388b | ||
|
|
8fa4e263e2 | ||
|
|
7a58fb2737 | ||
|
|
583c9ef3ba | ||
|
|
f5fde2aef0 | ||
|
|
0bc6ed2543 | ||
|
|
f7496e9c39 | ||
|
|
884c883cac | ||
|
|
1be54d4f62 | ||
|
|
3baa5a0a07 | ||
|
|
82f35ba3a1 | ||
|
|
0138394ce2 | ||
|
|
dc3e75c3c9 | ||
|
|
984e335174 | ||
|
|
94f90367d6 | ||
|
|
f06b8dda10 | ||
|
|
ca7fe9dc0a | ||
|
|
1174bed6e6 | ||
|
|
f427b05b67 | ||
|
|
a724e8b058 | ||
|
|
6ab60794c1 | ||
|
|
4031845b81 | ||
|
|
6d0ce3c27f | ||
|
|
37f4dea31d | ||
|
|
19b4cb3dd0 | ||
|
|
0837422feb | ||
|
|
e3272d3a5b | ||
|
|
46d4709625 | ||
|
|
2cb986ba14 | ||
|
|
40b4d41b26 | ||
|
|
0fa157989a | ||
|
|
d1b371b42f | ||
|
|
1f8941278f | ||
|
|
b78a7569bd | ||
|
|
a3dab546be | ||
|
|
55bc08a677 | ||
|
|
b9388fb70c | ||
|
|
84172221fd | ||
|
|
2a4897b1df | ||
|
|
ebb37c20bb | ||
|
|
9cf4155048 | ||
|
|
3d15d56896 | ||
|
|
189dc83930 | ||
|
|
3f610625ae | ||
|
|
9eb2fed584 | ||
|
|
f5676b99fb | ||
|
|
9fe46021da | ||
|
|
048e8a84d3 | ||
|
|
b498e006ce | ||
|
|
e2edea0369 | ||
|
|
bec7320602 | ||
|
|
f962c2540c | ||
|
|
9af8b37d29 | ||
|
|
85dfd11c19 | ||
|
|
e9bd4cae0d | ||
|
|
936f8c6a74 | ||
|
|
c620807fdc | ||
|
|
1e51287e66 | ||
|
|
8d05b6aff6 | ||
|
|
226d8a7e6c | ||
|
|
217c63bfd3 | ||
|
|
7c3aacc9da | ||
|
|
09e1d8384a | ||
|
|
f2b4eaedc0 | ||
|
|
cc4e536a32 | ||
|
|
172b3cc29e | ||
|
|
d75d24077e | ||
|
|
dc75d58f98 | ||
|
|
49635c1f8d | ||
|
|
c1c9d32a20 | ||
|
|
bf12c43e4d | ||
|
|
74adb05c79 | ||
|
|
de1ec144f1 | ||
|
|
3987f730c6 | ||
|
|
7119f5a8ab | ||
|
|
4dbfba5bea | ||
|
|
09b94d6758 | ||
|
|
71a82add81 | ||
|
|
b6a4809cc5 | ||
|
|
620d35267d | ||
|
|
43027c79df | ||
|
|
50d033e8d7 | ||
|
|
0d718d40bc | ||
|
|
8995ffa584 | ||
|
|
4caaeac215 | ||
|
|
20f923cf23 | ||
|
|
fa3693ba17 | ||
|
|
1dac5c87ee | ||
|
|
e64d6a66fe | ||
|
|
44644b075e | ||
|
|
efde93a0b4 | ||
|
|
f67f7ef4be | ||
|
|
cf3f5408f3 | ||
|
|
01a0ce9fbb | ||
|
|
d80b85ae0d | ||
|
|
df8fd0267d | ||
|
|
5a8eb0663b | ||
|
|
140f3b28f6 | ||
|
|
04366cbb41 | ||
|
|
7ec3149efa | ||
|
|
444cd1a2db | ||
|
|
a5e00e7769 | ||
|
|
8a66f1ee9b | ||
|
|
f69f94e658 | ||
|
|
3ae1b1d6c3 | ||
|
|
8070ff4899 | ||
|
|
a50008822f | ||
|
|
e38f58d46e | ||
|
|
e14570a7ff | ||
|
|
f94294867f | ||
|
|
44e6d7497d | ||
|
|
67f4b28bee | ||
|
|
27bece992a | ||
|
|
c93052f03f | ||
|
|
e605578e3e | ||
|
|
f5515df6fc | ||
|
|
6f739fae90 | ||
|
|
72822f45e1 | ||
|
|
c2fc207cc4 | ||
|
|
362b549038 | ||
|
|
46af8b45ab | ||
|
|
43f6d200ed | ||
|
|
f222d920b6 | ||
|
|
e9c8a988b0 | ||
|
|
f3a8983249 | ||
|
|
f856460889 | ||
|
|
7a730f70c1 | ||
|
|
39065e43c2 | ||
|
|
2da5993429 | ||
|
|
de16c16bdc | ||
|
|
8f91643b78 | ||
|
|
44f6f035ac | ||
|
|
33c24bbc63 | ||
|
|
52131ab78d | ||
|
|
b1a48c8ef8 | ||
|
|
8c9619672a | ||
|
|
2fb715043b | ||
|
|
8024a30c84 | ||
|
|
edd1a3c2b6 | ||
|
|
e736474085 | ||
|
|
7455d7f706 | ||
|
|
0ced7302f3 | ||
|
|
8450cdc720 | ||
|
|
de63398481 | ||
|
|
9013eeeb6a | ||
|
|
3489f7443c | ||
|
|
d4fc42eb96 | ||
|
|
c8f057a039 | ||
|
|
a0948d8792 | ||
|
|
d05740cad7 | ||
|
|
203a05ff48 | ||
|
|
7419ae5f77 | ||
|
|
2615f05fc9 | ||
|
|
175b423536 | ||
|
|
4aaf5b3375 | ||
|
|
0769120e1b | ||
|
|
442c48fddd | ||
|
|
5654a9d78f | ||
|
|
1b1eb1aa42 |
+7
-1
@@ -18,7 +18,8 @@ POSTGRES_USER=artex
|
||||
POSTGRES_PASSWORD=change-me-please
|
||||
POSTGRES_DB=artex
|
||||
# Shared secret between the panel and artex-runner for the internal execution
|
||||
# API. install.sh and update.sh generate it when empty. Keep it private.
|
||||
# API. install.sh and update.sh generate it when empty. For a manual
|
||||
# `cp .env.example .env`, generate one with: openssl rand -hex 32. Keep it private.
|
||||
ARTEX_RUNNER_TOKEN=
|
||||
# Agent execution isolation: required (default, one worker per task) or off
|
||||
# (explicit degraded mode, loud warning). docker-compose.yml includes the runner.
|
||||
@@ -85,3 +86,8 @@ ARTEX_LLM_PRIVATE_ENDPOINTS=
|
||||
# releases API for a newer ARTEX release at most once per 24 h and show a dismissible banner.
|
||||
# Off by default: unset, no update request is made.
|
||||
# ARTEX_UPDATE_CHECK=1
|
||||
|
||||
# Docker API socket the runner mounts (optional). Only the host side is configurable;
|
||||
# inside the runner the socket is always /var/run/docker.sock. install.sh and update.sh
|
||||
# detect a rootless Podman socket and write it here. Leave unset for Docker Engine.
|
||||
# ARTEX_DOCKER_SOCK=/run/user/1000/podman/podman.sock
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
## What
|
||||
|
||||
<!-- One paragraph: the problem and the change. -->
|
||||
|
||||
## Why
|
||||
|
||||
<!-- The issue or the behavior this fixes. Write "none" when it is a refactor. -->
|
||||
|
||||
## Size
|
||||
|
||||
- [ ] At most 2,500 changed lines and 15 files.
|
||||
- [ ] Or a low-risk exception (localization files, documentation, generated code, test fixtures) up to 5,000 lines or 30 files, with the verification method described below.
|
||||
- [ ] Larger: I split it by subsystem, or I am asking for the current wave to park it.
|
||||
|
||||
## Tests
|
||||
|
||||
<!-- Commands run and the result. Say which tests are skipped and why. -->
|
||||
|
||||
## Behavior change
|
||||
|
||||
<!-- What an operator or an agent will notice. Write "none" when nothing changes. -->
|
||||
+16
-10
@@ -4,13 +4,15 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
# Which areas a pull request changes. Each job below runs only for its area;
|
||||
# pushes to main, and any failure of this job, run every job.
|
||||
# Which areas a pull request, or a push to main, changes. Each job below runs
|
||||
# only for its area; a manual run, and any failure of this job, run every job.
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
outputs:
|
||||
go: ${{ steps.filter.outputs.go }}
|
||||
@@ -18,9 +20,13 @@ jobs:
|
||||
python: ${{ steps.filter.outputs.python }}
|
||||
shell: ${{ steps.filter.outputs.shell }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
if: github.event_name == 'push'
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
|
||||
id: filter
|
||||
if: github.event_name == 'pull_request'
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
with:
|
||||
predicate-quantifier: some-with-excludes
|
||||
filters: |
|
||||
@@ -50,7 +56,7 @@ jobs:
|
||||
|
||||
go:
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.go == 'true') }}
|
||||
if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.changes.result != 'success' || needs.changes.outputs.go == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
@@ -133,7 +139,7 @@ jobs:
|
||||
# this becomes a required check.
|
||||
go-stable:
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.go == 'true') }}
|
||||
if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.changes.result != 'success' || needs.changes.outputs.go == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
services:
|
||||
@@ -181,7 +187,7 @@ jobs:
|
||||
|
||||
shell:
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.shell == 'true') }}
|
||||
if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.changes.result != 'success' || needs.changes.outputs.shell == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
@@ -199,14 +205,14 @@ jobs:
|
||||
|
||||
web:
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.web == 'true') }}
|
||||
if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.changes.result != 'success' || needs.changes.outputs.web == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
@@ -235,11 +241,11 @@ jobs:
|
||||
|
||||
python:
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.python == 'true') }}
|
||||
if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.changes.result != 'success' || needs.changes.outputs.python == 'true') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python3 scripts/posture_check_test.py
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
@@ -172,12 +172,12 @@ jobs:
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name == 'push'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
id: meta
|
||||
with:
|
||||
images: ghcr.io/baarai/artex-${{ matrix.name }}
|
||||
@@ -185,7 +185,7 @@ jobs:
|
||||
type=ref,event=tag
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
file: ${{ matrix.dockerfile }}
|
||||
@@ -229,18 +229,18 @@ jobs:
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name == 'push'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Log in to Docker Hub
|
||||
if: github.event_name == 'push' && vars.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
id: meta
|
||||
with:
|
||||
images: |
|
||||
@@ -250,7 +250,7 @@ jobs:
|
||||
type=ref,event=tag
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
@@ -6,12 +6,44 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side.
|
||||
- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833.
|
||||
|
||||
- **Step slices are no longer read as bracketed IPv6 addresses.** A subscript glued to an identifier, like the Python slice `d[::2]` or the Ruby `a[1::2]`, was extracted as the address `::2`: its bounds happen to parse as a valid IPv6, and the gate then prompted for a connection the command never makes. `[...]` glued to an identifier, to the `]` closing a chained subscript or to the `)` of a call result is read as subscript syntax and consumed as no target; the URL form `http://[::2]:8080/` keeps reading as an address.
|
||||
- **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only.
|
||||
- **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out.
|
||||
- **`WebFetch` redirects through a proxy are checked against the sandbox egress policy.** In `ARTEX_SANDBOX=required` mode only the first URL of a `WebFetch` call was checked against the task's egress policy. With an operator or recording proxy configured, the sandbox dialer only connects to the proxy, so a redirect from an allowed URL to a cloud metadata address (169.254.169.254), a loopback or private address, or a domain outside the task scope was followed. Every redirect hop is now checked against the same egress policy before it is followed, and a hop the policy does not allow fails the call.
|
||||
- **Sandbox egress URL checks fail closed on DNS and check every resolved address.** In `ARTEX_SANDBOX=required` mode, `EgressPolicy.CheckURL` (the check WebFetch, the shared browser and the custom HTTP tool run on a target URL) allowed an in-scope name whose lookup failed or returned no addresses, and allowed a name that resolved to several addresses as soon as the first allowed one was found, even when the others were private, loopback, IPv6 or the cloud metadata address. Through an explicit proxy or the shared browser, which resolve the target themselves, this is the only check on the target. A lookup error or an empty answer is now a denial, and every resolved address (A and AAAA, all answers) must be allowed. Sandboxed custom HTTP tool transports now disable keep-alives on every transport, including an operator proxy and the recording proxy, so each request opens a new connection that the sandbox dialer checks again (#794). Behaviour change: an in-scope name the panel cannot resolve is refused, even when the proxy or the browser could resolve it, and a name that answers a private, loopback, link-local or IPv6 address next to a public one is refused unless that address is in the scope CIDRs.
|
||||
- **An interrupted task deletion no longer shares its staging directory with the executor group.** Since #822 a task deletion stages the task files in an owner-only `.delete-staging-<id>-*` directory next to each source (`data/tasks`, `data/spill/tasks`, `data/transcripts`). A staging directory left by a crash, or kept on purpose by a failed rollback or purge, was treated as a task directory at the next start with the executor drop enabled: the start made it world-readable and shared the staged workspace with the executor group. The start now shares only directories named by a task ID, and settles leftover staging before any task runs: the staging of a deleted task is removed, the staged files of a live task move back when their original path is free, and an entry whose path exists again stays staged, unshared, and is logged.
|
||||
|
||||
### Added
|
||||
|
||||
- **Slack notification channel**: System → Notifications can push findings to Slack by pasting an Incoming Webhook URL; each URL posts to the channel, or the installer's own direct messages, chosen when it was created in Slack. Only `https://hooks.slack.com/services/…` (and the GovSlack host) is accepted, and the URL is stored sealed and masked like other channel credentials. Finding text is escaped (`&`, `<`, `>`) so it cannot mention `@channel` or hide a link, digests are packed under 3,900 characters and link unfurling is off. The form explains the Slack setup steps in every console language.
|
||||
|
||||
- **The task target gate has a UI.** `target_gate` was API-only (`POST /api/tasks`, `PATCH /api/tasks/{id}`), so an operator could neither see nor change it: a task-level block rule added to a task whose gate was off never reached a network target, because `CheckTargets` returns before any rule is matched. The create-task sheet now carries a `Network target gate` selector (auto / on / off; auto leaves the backend default of on for scoped tasks) and warns when block rules would be stored unenforced, and the task overview's task-level rule card carries a switch with the live state, an explicit warning while enabled block rules exist with the gate off, and a retry when the state cannot be read. The switch writes through `PATCH /api/tasks/{id}` and takes effect on the next tool call. The gate governs the targets a tool call declares, not a sandboxed worker's sockets (the sandbox egress list decides those), turning it on also attaches the panel-hosted shared browser in sandbox mode, an unpinned target waits out the 300 s bound before the call is refused, task allow rules do not affect the gate, and each flip is recorded in the task's activity history with the operator, the client address, and the previous and new setting; the chat side's `target_gate` still has no UI.
|
||||
|
||||
- **Log rotation for the long-running containers.** `docker-compose.yml` and `docker-compose.ghcr.yml` now cap the logs of `postgres`, `artex` and `artex-runner` at three files of 10 MB each (`json-file` driver), through a shared `x-logging` anchor. Before, Docker kept their logs without limit, so a chatty task could fill the disk; on Docker Desktop a full VM disk turns the whole VM read-only. Operators who use another logging driver can drop the `logging` lines.
|
||||
|
||||
- **`domain_suffix` asset interception rule kind**: a domain and its subdomains, matched on a label boundary. `example.com` matches `example.com` and `a.example.com`, but not `a.example.com.other.net` or `badexample.com`, which `fuzzy_domain`'s substring match also lets through; that makes it the kind to use for a task allow-list that covers a site. `*.example.com` and `.example.com` are stored as `example.com`. It is the label-boundary semantics the sandbox egress policy already applies, and a `domain_suffix` allow rule is now a scope domain for that policy too (`taskSandboxRunInfo` already read the kind). `fuzzy_domain` is unchanged. Migration `0026_asset_intercept_domain_suffix.sql` widens the `kind` CHECK constraint of both rule tables.
|
||||
|
||||
- **egress-guard scope lists can be derived from the approved task scope** (#421): `egress-guard/export-scope.sh` regenerates `lists/scope-domains.txt` and `lists/scope-cidrs.txt` from PostgreSQL through the new `artex -export-egress-guard-scope`. It reuses the derivation of the per-task sandbox egress proxy, so only operator-approved task scope, frozen company grants and operator task allow rules are exported, never agent-added, auto-added or expanded rows. Each list is replaced by rename, and only after the complete export was read and checked; an export that fails or is malformed changes neither list, and an empty export is refused unless `--allow-empty` is given. The overlay stays opt-in and still reads the lists at startup, so the guard is restarted to apply them.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A wrong current password on `POST /api/auth/change-password` answers 403 instead of 401.** A 401 on that route now means the session is missing or expired, and the client clears the session and returns to the login page. A wrong current password is a failed re-check on a valid session, so it answers 403 with the existing message and the change-password dialog keeps the operator signed in. `/api/auth/login` still answers 401 for bad credentials.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Docker updates reuse the runtime image layers again**: the runtime stage declared `ARTEX_VERSION` and `ARTEX_REVISION` before its first `RUN`, and a declared build argument is part of the cache key of every later `RUN`. `update.sh` writes the new commit into `.env`, so each update reinstalled apt packages, bbot, Playwright and the rest of the stage (6 to 11 minutes per update) and left another copy of about 8 GB of layers in the build cache. The arguments and the `LABEL` that uses them now come at the end of the stage. The Go, Next.js and npm caches are also kept between builds as BuildKit cache mounts, so a code change recompiles only what changed: an update rebuild drops to well under a minute.
|
||||
- **A command that exits 124 no longer removes the Docker worker.** The runner treated every exit code 124 as its own timeout and removed the task's worker container, which also stopped the task's background jobs. Commands such as `timeout 5 curl ...` exit 124 by themselves. An exit 124 now counts as a runner timeout only when the command ran for at least `timeout_ms`.
|
||||
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
|
||||
- **Malformed domain patterns are refused on asset interception rules.** `exact_domain` and `domain_suffix` patterns (global rules, task rules, task creation and task templates) are now answered 400 when they contain whitespace or a control character, an empty label (`a..example.com`, a leading dot, or more than one trailing dot: `example.com..` used to be stored as `example.com.`, a form raw consumers do not match), a single label (`com`, refused for `domain_suffix` too, so a TLD-wide rule is out of scope), a URL or wildcard character (`*`, `/`, `:`; `exact_domain` took `https://example.com` or `*.example.com` and never matched), an IP literal or an all-digit last label (`192.0.2.1`, `127.1`; use `exact_ip` or `cidr`), or a non-ASCII or `xn--` label the IDNA profile refuses (`_bücher.example`), which has no single canonical spelling. `fuzzy_domain` patterns refuse whitespace, control characters and a doubled dot (including the ideographic and fullwidth dots after canonicalisation), and keep leading and trailing dots and single labels (`.gov.cn`). Valid domains are stored exactly as before, and the matcher still canonicalizes targets leniently. Existing rows are not migrated. The intercept layer now uses `idna.Lookup` for target names, the profile the rules use; the previous profile had the same options, so target normalisation does not change, and its comment wrongly said it accepted underscore labels: both profiles refuse them, and such a name is compared lower-cased as written.
|
||||
- **Switching a task's target gate off releases its waiting approvals**: the waiter observes the live flag on its 2 s poll, closes open requests so a late click can no longer pin the target, and lets a plain target-gated call continue as it would on an ungated task; a call whose rule or judge approval was merged into the request is told to retry, since that approval was not given. An approval clicked after the switch (before the close, or on another instance) is refused under the task row lock and recorded as a system denial without approver; the decide API answers 409 (#804).
|
||||
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
|
||||
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
|
||||
- **`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).
|
||||
- **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.
|
||||
|
||||
### Removed
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
|
||||
- **At most 7 open pull requests per contributor.** The repository enforces this with GitHub's pull request creation limit, drafts included: when you reach it, close or merge one before opening another. Review is manual, one change at a time, so a larger batch makes the queue unmanageable and slows everyone down, including you. If you have more changes queued, open one issue that lists them and wait for the current ones to be reviewed.
|
||||
- **One focused change per PR.** If a change has independent parts, split it into a small number of PRs and say in each description what the other parts depend on.
|
||||
- **Keep the review size bounded.** Aim for at most 2,500 changed lines and 15 files. A larger change is not rejected for its size: it is parked with the `feature` label and stays open, and we ask you to split it by subsystem, for example storage, API, UI and tests, into PRs under that size. The PR is the unit of review, not the unit of the feature.
|
||||
- **Low-risk changes have a larger allowance.** Localization files, documentation, generated code and test fixtures can go up to 5,000 lines or 30 files when the change is mechanical and a key-parity check, a schema check or a test verifies it. Say in the description how you verified it.
|
||||
- **Security, concurrency and database changes stay small.** They are reviewed line by line, with an automated audit pass before merge; split early and keep the risky part isolated.
|
||||
- **Every PR gets a first answer.** A parked PR stays open; address the split request and ask for review again. Duplicate or superseded PRs are closed with the reason and the number of the PR that replaces them.
|
||||
- **Describe the change.** State the problem, the behavior change and what you tested. A pull request with no description is a request for changes.
|
||||
- **Provider support stays generic.** Any OpenAI- or Anthropic-compatible endpoint works through a model profile; provider convenience goes in as a neutral preset (name and base URL) or a docs recipe, with no vendor logos, promotional codes, baked vendor endpoints, or vendor-specific environment variables. A new wire format needs a schema migration, a profile save/load test, and a live connection test.
|
||||
|
||||
|
||||
+13
-8
@@ -17,9 +17,11 @@ FROM --platform=$BUILDPLATFORM node:22-bookworm-slim@sha256:be979e5523c76fa4d5ca
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
WORKDIR /src/web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm ci --ignore-scripts
|
||||
# Cache mounts keep npm, Next.js and Go caches between builds, so an update
|
||||
# recompiles only what changed. They are not part of the image.
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts
|
||||
COPY web/ ./
|
||||
RUN npm run build:static
|
||||
RUN --mount=type=cache,target=/src/web/.next/cache npm run build:static
|
||||
|
||||
# ------------------------------------------------------------- Go binary ---
|
||||
# Pinned to the exact Go release go.mod requires. The official image sets
|
||||
@@ -39,7 +41,8 @@ ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
# Same flags as the release binaries job (ARTEX_COMPRESS=0, -trimpath,
|
||||
# -X main.version), driven through build.sh so there is one build path.
|
||||
RUN ARTEX_SKIP_FRONTEND=1 \
|
||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||
ARTEX_SKIP_FRONTEND=1 \
|
||||
ARTEX_SKIP_NPM_CI=1 \
|
||||
ARTEX_COMPRESS=0 \
|
||||
ARTEX_OUTPUT=/out/artex \
|
||||
@@ -162,11 +165,6 @@ RUN set -eux; \
|
||||
# ---------------------------------------------------------------- runtime ---
|
||||
FROM python:3.12-slim-bookworm@sha256:44cf1793efa7c7a476bb0f2cff81443f4a072c90c1cb127e2924933daa3e8c64
|
||||
ARG TARGETARCH
|
||||
ARG ARTEX_VERSION=dev
|
||||
ARG ARTEX_REVISION=
|
||||
LABEL org.opencontainers.image.title="ARTEX" \
|
||||
org.opencontainers.image.version="${ARTEX_VERSION}" \
|
||||
org.opencontainers.image.revision="${ARTEX_REVISION}"
|
||||
# Common tools: ripgrep / curl / vim, plus a set of recon staples (add/remove as needed).
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates ripgrep curl wget vim git jq unzip xz-utils \
|
||||
@@ -312,6 +310,13 @@ RUN chmod +x /app/artex /app/start.sh && mkdir -p -m 0700 /app/keys \
|
||||
# when the container runs without docker-compose.yml's no-new-privileges.
|
||||
RUN find / -xdev -perm /6000 -type f -exec chmod a-s {} +
|
||||
COPY skills/ /app/skills/
|
||||
# Declared last: an ARG is part of the cache key of every RUN after it, and the
|
||||
# revision changes on each commit, so declaring it earlier rebuilt the whole stage.
|
||||
ARG ARTEX_VERSION=dev
|
||||
ARG ARTEX_REVISION=
|
||||
LABEL org.opencontainers.image.title="ARTEX" \
|
||||
org.opencontainers.image.version="${ARTEX_VERSION}" \
|
||||
org.opencontainers.image.revision="${ARTEX_REVISION}"
|
||||
# persistence points: data/ (traffic index, task files, transcripts) and keys/ (jwt.key, secret.key, via ARTEX_JWT_KEY_DIR)
|
||||
VOLUME ["/app/data", "/app/keys"]
|
||||
EXPOSE 8787 8788
|
||||
|
||||
+8
-3
@@ -14,9 +14,12 @@ add it later in the UI.
|
||||
|
||||
- Docker Engine with the Compose v2 plugin and the buildx plugin. Docker Desktop includes both.
|
||||
The checkout build stops at `failed to parse platform` when buildx is missing.
|
||||
- Docker Engine, not rootless Podman. The sandbox runner mounts `/var/run/docker.sock`, while Podman
|
||||
exposes its socket under `$XDG_RUNTIME_DIR`; `install.sh` and `update.sh` refuse the engine before
|
||||
building instead of leaving an unhealthy runner after the image build (tracked in #742).
|
||||
- Rootless Podman works for the container engine when its API socket is reachable as a Unix socket.
|
||||
The runner always dials `/var/run/docker.sock` inside its container, and Compose mounts the host
|
||||
side from `ARTEX_DOCKER_SOCK`; `install.sh` and `update.sh` resolve a rootless Podman socket
|
||||
(`podman info`), validate it, and write it to `.env`. Set `ARTEX_DOCKER_SOCK` yourself for any other
|
||||
engine path. Task networking, cgroup limits and port publishing under rootless Podman are not
|
||||
verified yet (#742), so the scripts still warn rather than claiming full support.
|
||||
- PostgreSQL 16 is started by the Compose files. A local binary or a standalone container needs an
|
||||
existing database.
|
||||
- An Anthropic or OpenAI compatible API key for exploration. It can be set in `.env` or later in
|
||||
@@ -47,6 +50,8 @@ docker compose logs artex | grep "Setup token"
|
||||
git clone https://github.com/BaaRai/ARTEX.git
|
||||
cd ARTEX
|
||||
cp .env.example .env # set POSTGRES_PASSWORD, optionally an LLM key
|
||||
# set ARTEX_RUNNER_TOKEN too: Compose refuses to start while it is empty
|
||||
# (openssl rand -hex 32)
|
||||
docker compose up -d --build
|
||||
docker compose logs artex | grep "Setup token"
|
||||
```
|
||||
|
||||
@@ -51,7 +51,7 @@ justify it, and every autonomous action passes through scope rules, approval gat
|
||||
```bash
|
||||
git clone https://github.com/BaaRai/ARTEX.git
|
||||
cd ARTEX
|
||||
cp .env.example .env # set POSTGRES_PASSWORD (and optionally an LLM key)
|
||||
cp .env.example .env # set POSTGRES_PASSWORD, ARTEX_RUNNER_TOKEN (and optionally an LLM key)
|
||||
docker compose up -d --build # builds from this checkout, starts PostgreSQL
|
||||
```
|
||||
|
||||
@@ -282,8 +282,11 @@ worker remains confined to the intent it claimed.
|
||||
construction (`["git","push"]` covers `git push --force`, but `git -C /repo push` matches
|
||||
nothing). Each approval records who decided: `human`, `rule`, `model` or `system`.
|
||||
- **Scope and target gate**: scope rows define the coverage denominator; assets outside the
|
||||
declared scope are not explored. The target gate (off by default, API-only) can refuse
|
||||
destinations that were not approved.
|
||||
declared scope are not explored. The target gate (on by default for a task with a linked company
|
||||
or asset rules, off otherwise; set at creation or from the task overview) can refuse declared
|
||||
targets that were not approved. It governs the targets a tool call declares, not a sandboxed
|
||||
worker's sockets, which the sandbox egress list decides. Each flip is recorded in the task's
|
||||
activity history with the operator, the client address, and the previous and new setting.
|
||||
- **Budgets**: `ARTEX_TASK_BUDGET_TOKENS` / `ARTEX_TASK_BUDGET_TURNS` cap a whole task (planner and
|
||||
workers); `ARTEX_INTENT_BUDGET_TOKENS` / `ARTEX_INTENT_BUDGET_TURNS` cap one worker run. Near the
|
||||
limit the task enters a forced wrap-up; a worker is not started when the remaining budget cannot
|
||||
@@ -439,8 +442,10 @@ the file and `.env.example` once:
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/BaaRai/ARTEX/main/docker-compose.ghcr.yml
|
||||
curl -fsSLO https://raw.githubusercontent.com/BaaRai/ARTEX/main/.env.example
|
||||
cp .env.example .env # set POSTGRES_PASSWORD, optionally an LLM key
|
||||
docker compose -f docker-compose.ghcr.yml pull
|
||||
cp .env.example .env # set POSTGRES_PASSWORD, ARTEX_RUNNER_TOKEN (openssl rand -hex 32)
|
||||
docker compose -f docker-compose.ghcr.yml --profile build-only pull
|
||||
# --profile build-only also pulls artex-worker and artex-egress-proxy. The runner
|
||||
# starts them per task; without them the stack looks healthy but the first task fails.
|
||||
docker compose -f docker-compose.ghcr.yml up -d
|
||||
# → http://localhost:8787 (docker compose -f docker-compose.ghcr.yml logs artex | grep "Setup token")
|
||||
```
|
||||
@@ -620,6 +625,8 @@ root, paste the key, then click the **↻** button next to *Model* to load the p
|
||||
catalog (`GET /v1/models`) and pick a model; models the provider adds later appear on the
|
||||
next refresh. For example, [NotHoly](https://notholy.com) (offensive-security models) uses
|
||||
base URL `https://api.notholy.com/v1` with an API key from its console.
|
||||
Likewise, [Morse](https://trymorse.ai/inference) (private, uncensored open-weight models) uses
|
||||
base URL `https://inference.trymorse.ai/v1` with an API key from `https://console.trymorse.ai`.
|
||||
|
||||
**Bedrock gateway**: select **Bedrock gateway** in System → LLM for a gateway that
|
||||
exposes the Bedrock `InvokeModel` and `InvokeModelWithResponseStream` paths and accepts
|
||||
@@ -879,6 +886,11 @@ For a recurring problem, share the ARTEX version or commit, the model and versio
|
||||
excerpt of the affected input and result. Remove credentials, target data, and other sensitive
|
||||
content before sharing.
|
||||
|
||||
### Reviewing a published vulnerability advisory
|
||||
|
||||
See [Reviewing a published vulnerability advisory](docs/operator-advisory-review.md) for the
|
||||
CVE and GHSA review workflow.
|
||||
|
||||
### Backups
|
||||
|
||||
`scripts/backup.sh` dumps the Postgres database (and optionally the data directory) with
|
||||
|
||||
@@ -24,7 +24,7 @@ func ParseBedrockGatewayHeaders(raw string) (http.Header, error) {
|
||||
if len(raw) > 8192 {
|
||||
return nil, errors.New("custom headers exceed 8 KiB")
|
||||
}
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
for line := range strings.SplitSeq(raw, "\n") {
|
||||
line = strings.TrimSuffix(line, "\r")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
|
||||
@@ -241,7 +241,7 @@ func TestBlackboardToolsReadDirectSources(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 301; i++ {
|
||||
for i := range 301 {
|
||||
if _, err := sourceStore.AddIntent(map[string]any{"summary": fmt.Sprintf("newer live source work %d", i)}, 1, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ func TestWrapupMarginTriggersOnceAndStopsDispatch(t *testing.T) {
|
||||
t.Fatalf("at the reserve: %+v, want AtMargin and no dispatch", st)
|
||||
}
|
||||
running, wrapups := l.StartIntent(), 0
|
||||
for i := 0; i < 3; i++ { // several planner wake-ups at the reserve
|
||||
for range 3 { // several planner wake-ups at the reserve
|
||||
if l.BeginWrapup() {
|
||||
wrapups++
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ var (
|
||||
"The user paused the task via the task control API (POST /api/tasks/{id}/control, action=pause). This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are re-claimed and executed from scratch after the task resumes")
|
||||
AbortPausedByOrchestrator = cause("paused_by_orchestrator", "The orchestrating agent paused the task",
|
||||
"The orchestrating agent called the pause_task tool to pause this task. This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are executed again after resuming")
|
||||
AbortSandboxUnavailable = cause("sandbox_unavailable", "The sandbox runner is unavailable",
|
||||
"The required sandbox runner or Docker backend is unavailable. The task was paused without local execution fallback; running intents return to frontier(open) and can run again after the operator resumes the task")
|
||||
AbortTaskDeleted = cause("task_deleted", "The task was deleted",
|
||||
"The task is being deleted (DELETE /api/tasks/{id}); the deletion barrier has cancelled the task's running Planner, Worker, and main agent; this run's results will not be used")
|
||||
AbortPausedOnReload = cause("paused_on_reload", "Restored the paused state on startup",
|
||||
|
||||
+3
-2
@@ -17,6 +17,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -247,7 +248,7 @@ func (g *coldGraph) group(set map[int64]bool, p coldParams) []block {
|
||||
if len(ids) < p.K {
|
||||
continue
|
||||
}
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
slices.Sort(ids)
|
||||
memberSet := make(map[int64]bool, len(ids))
|
||||
for _, m := range ids {
|
||||
memberSet[m] = true
|
||||
@@ -269,7 +270,7 @@ func (g *coldGraph) group(set map[int64]bool, p coldParams) []block {
|
||||
for a := range anchorSet {
|
||||
anchors = append(anchors, a)
|
||||
}
|
||||
sort.Slice(anchors, func(i, j int) bool { return anchors[i] < anchors[j] })
|
||||
slices.Sort(anchors)
|
||||
blocks = append(blocks, block{Members: ids, Anchors: anchors})
|
||||
}
|
||||
// Deterministic order: by smallest member id.
|
||||
|
||||
@@ -116,7 +116,7 @@ func TestRenderCoverageLedgerInjection(t *testing.T) {
|
||||
// The wrap-up lists at most 25 gaps, then counts the rest.
|
||||
func TestRenderCoverageLedgerWrapupCap(t *testing.T) {
|
||||
var entries []db.CoverageEntry
|
||||
for i := 0; i < 100; i++ {
|
||||
for i := range 100 {
|
||||
entries = append(entries, db.CoverageEntry{Surface: "/p" + strings.Repeat("a", i%5) + string(rune('0'+i%10)), RiskArea: "xss", Outcome: db.OutcomeNeedsFollowUp})
|
||||
}
|
||||
got := renderCoverageLedger(db.BuildCoverageLedger(entries, nil, db.CoverageCompleteness{}), true, newDataEnvelope())
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -170,9 +171,7 @@ func renderOverviewSections(data map[string]any, env dataEnvelope) string {
|
||||
framed := make([]map[string]any, 0, len(entries))
|
||||
for _, m := range entries {
|
||||
copied := make(map[string]any, len(m))
|
||||
for key, v := range m {
|
||||
copied[key] = v
|
||||
}
|
||||
maps.Copy(copied, m)
|
||||
if sm, ok := copied["summary"]; ok {
|
||||
entry := map[string]any{"id": copied["id"], "summary": sm}
|
||||
for _, extra := range []string{"source_task_id", "inherited"} {
|
||||
|
||||
+6
-3
@@ -16,13 +16,16 @@ import (
|
||||
// placed as the LAST system-prompt segment, with DynamicBoundary set so the whole
|
||||
// (session-fixed) system prompt — including the block — is cached (design doc
|
||||
// §2.1 / C1). Skill-gated MCP names are NOT in this block; they surface when their
|
||||
// skill loads. Returns a single plain segment + boundary 0 when there is no global
|
||||
// block to add.
|
||||
// skill loads. With no global block the system prompt is the single session-fixed
|
||||
// segment; boundary 1 (== len) keeps it cacheable instead of disabling the cache
|
||||
// breakpoint entirely (#809: planner/mainagent/chat rebilled the whole prompt
|
||||
// every round on instances without global MCP servers).
|
||||
func deferredSystem(sysText string, def DeferredInfo) (system []string, boundary int) {
|
||||
sysText += def.FindingGuidance + def.SkillIndex
|
||||
block := actool.RenderDeferredToolsBlock(def.GlobalNames)
|
||||
if block == "" {
|
||||
return []string{sysText}, 0
|
||||
s := []string{sysText}
|
||||
return s, len(s)
|
||||
}
|
||||
system = []string{sysText, block}
|
||||
boundary = len(system) // b >= len → whole system prompt cached (SDK guard)
|
||||
|
||||
@@ -10,10 +10,12 @@ import (
|
||||
)
|
||||
|
||||
func TestDeferredSystem_NoGlobal(t *testing.T) {
|
||||
// No global MCP names → plain single-segment system, no cache boundary.
|
||||
// No global MCP names → plain single-segment system, still session-fixed,
|
||||
// so the whole prompt is cacheable (#809: boundary 0 meant no cache
|
||||
// breakpoint and every planner/mainagent/chat round rebilled ~21-28k tokens).
|
||||
sys, boundary := deferredSystem("SYS", DeferredInfo{})
|
||||
if len(sys) != 1 || sys[0] != "SYS" || boundary != 0 {
|
||||
t.Fatalf("expected [SYS],0 — got %v,%d", sys, boundary)
|
||||
if len(sys) != 1 || sys[0] != "SYS" || boundary != 1 {
|
||||
t.Fatalf("expected [SYS],1 — got %v,%d", sys, boundary)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -105,8 +105,13 @@ func normalizeDiscoverySurfaceHost(surface string) string {
|
||||
if i := strings.IndexAny(s, "/?#"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
if host, _, ok := strings.Cut(s, ":"); ok && !strings.Contains(host, "]") {
|
||||
s = host
|
||||
if strings.HasPrefix(s, "[") {
|
||||
if end := strings.IndexByte(s, ']'); end > 0 {
|
||||
return s[1:end]
|
||||
}
|
||||
}
|
||||
if strings.Count(s, ":") == 1 {
|
||||
s, _, _ = strings.Cut(s, ":")
|
||||
}
|
||||
return strings.TrimSuffix(s, ".")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package agent
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeDiscoverySurfaceHost(t *testing.T) {
|
||||
cases := []struct {
|
||||
surface string
|
||||
want string
|
||||
}{
|
||||
{"example.com", "example.com"},
|
||||
{"Example.COM:8443", "example.com"},
|
||||
{"example.com./api", "example.com"},
|
||||
{"https://example.com:8443/app", "example.com"},
|
||||
{"https://[2001:db8::1]:8443/app", "2001:db8::1"},
|
||||
{"[2001:db8::1]:8443", "2001:db8::1"},
|
||||
{"[2001:db8::1]", "2001:db8::1"},
|
||||
{"2001:db8::1", "2001:db8::1"},
|
||||
{"10.0.0.5:80/path", "10.0.0.5"},
|
||||
{"", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := normalizeDiscoverySurfaceHost(tc.surface); got != tc.want {
|
||||
t.Errorf("normalizeDiscoverySurfaceHost(%q) = %q, want %q", tc.surface, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,7 +324,7 @@ func TestFactEvidenceLines(t *testing.T) {
|
||||
}
|
||||
}
|
||||
var many strings.Builder
|
||||
for i := 0; i < factEvidenceMaxLines+5; i++ {
|
||||
for i := range factEvidenceMaxLines + 5 {
|
||||
many.WriteString("recorded output line " + strconv.Itoa(i) + "\n")
|
||||
}
|
||||
if n := len(factEvidenceLines(many.String())); n != factEvidenceMaxLines {
|
||||
|
||||
+1
-1
@@ -158,7 +158,7 @@ func openWorkRoot(base, dir string) (*workRoot, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("data directory: %w", err)
|
||||
}
|
||||
for _, c := range strings.Split(rel, string(filepath.Separator)) {
|
||||
for c := range strings.SplitSeq(rel, string(filepath.Separator)) {
|
||||
next, err := r.OpenRoot(c)
|
||||
r.Close()
|
||||
if err != nil {
|
||||
|
||||
@@ -169,19 +169,17 @@ func TestFileToolIdentityDoesNotLeakAsRoot(t *testing.T) {
|
||||
f := newFileIdentityFixture(t)
|
||||
SetFileToolIdentity(&FileToolIdentity{UID: testExecID, GID: testExecID})
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 64; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 64 {
|
||||
wg.Go(func() {
|
||||
raw, _ := json.Marshal(map[string]any{"file_path": "root-only.txt"})
|
||||
res, err := f.tools["Read"].Call(context.Background(), raw, f.tc)
|
||||
if err != nil || !res.IsError {
|
||||
t.Errorf("concurrent Read as the executor: err=%v error=%v %s", err, res.IsError, res.Flatten())
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
for i := 0; i < 16; i++ {
|
||||
for range 16 {
|
||||
if _, err := os.ReadFile(f.rootOnly); err != nil {
|
||||
t.Fatalf("the server lost root's access after the file tool calls: %v", err)
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func threadFSUID(tid int) (int, error) {
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
for line := range strings.SplitSeq(string(b), "\n") {
|
||||
if f := strings.Fields(line); len(f) == 5 && f[0] == "Uid:" {
|
||||
return strconv.Atoi(f[4])
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func TestFileToolIdentityScopedToItsThreadAsRoot(t *testing.T) {
|
||||
var ready, done sync.WaitGroup
|
||||
ready.Add(children)
|
||||
done.Add(children)
|
||||
for i := 0; i < children; i++ {
|
||||
for range children {
|
||||
go func() {
|
||||
defer done.Done()
|
||||
runtime.LockOSThread()
|
||||
@@ -196,10 +196,8 @@ func TestFileToolIdentityScopedToItsThreadAsRoot(t *testing.T) {
|
||||
}
|
||||
const observers = 32
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < observers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range observers {
|
||||
wg.Go(func() {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
tid := unix.Gettid()
|
||||
@@ -210,7 +208,7 @@ func TestFileToolIdentityScopedToItsThreadAsRoot(t *testing.T) {
|
||||
if _, err := os.ReadFile(f.rootOnly); err != nil {
|
||||
t.Errorf("observer on thread %d lost root's access during the call: %v", tid, err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
var holders []int
|
||||
@@ -301,10 +299,8 @@ func TestFileToolIdentityUnderLoadAndCancelAsRoot(t *testing.T) {
|
||||
stop := make(chan struct{})
|
||||
var samples, leaks atomic.Int64
|
||||
var observers sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
observers.Add(1)
|
||||
go func() {
|
||||
defer observers.Done()
|
||||
for range 8 {
|
||||
observers.Go(func() {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for {
|
||||
@@ -319,7 +315,7 @@ func TestFileToolIdentityUnderLoadAndCancelAsRoot(t *testing.T) {
|
||||
samples.Add(1)
|
||||
runtime.Gosched()
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
calls := []struct {
|
||||
tool string
|
||||
@@ -331,7 +327,7 @@ func TestFileToolIdentityUnderLoadAndCancelAsRoot(t *testing.T) {
|
||||
{"LS", map[string]any{"path": "."}},
|
||||
}
|
||||
var callers sync.WaitGroup
|
||||
for i := 0; i < 200; i++ {
|
||||
for i := range 200 {
|
||||
callers.Add(1)
|
||||
go func(i int) {
|
||||
defer callers.Done()
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -79,7 +80,7 @@ func canonicalFindingAssetKey(assetIDs []int64, corpus string) string {
|
||||
}
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
slices.Sort(ids)
|
||||
parts := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
parts[i] = strconv.FormatInt(id, 10)
|
||||
@@ -182,7 +183,7 @@ func sortedQueryParamNames(rawQuery string) []string {
|
||||
return nil
|
||||
}
|
||||
var names []string
|
||||
for _, pair := range strings.Split(rawQuery, "&") {
|
||||
for pair := range strings.SplitSeq(rawQuery, "&") {
|
||||
if pair == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -105,12 +105,13 @@ func newHookReachFixture(t *testing.T) hookReachFixture {
|
||||
t.Helper()
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
expID, err := d.CreateExploration("hook reach probe", "prove tool calls reach the hooks")
|
||||
on := true
|
||||
task, err := d.CreateTaskWithOptions("hook reach probe", "prove tool calls reach the hooks", db.TaskCreateOptions{TargetGate: &on})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
f := hookReachFixture{expID: expID, taskID: fmt.Sprint(expID), ts: d.Exploration(expID), workDir: t.TempDir()}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
|
||||
f := hookReachFixture{expID: task.ExplorationID, taskID: fmt.Sprint(task.ID), ts: d.Exploration(task.ExplorationID), workDir: t.TempDir()}
|
||||
f.marker = filepath.Join(f.workDir, "tool-ran")
|
||||
input, _ := json.Marshal(map[string]string{"command": "touch " + f.marker})
|
||||
f.bash = string(input)
|
||||
|
||||
@@ -26,14 +26,8 @@ func renderNoiseProfile(p egress.Profile) string {
|
||||
if p.Name == "" || p.Name == "off" || p.RPS <= 0 {
|
||||
return ""
|
||||
}
|
||||
rps := int(p.RPS + 0.5)
|
||||
if rps < 1 {
|
||||
rps = 1
|
||||
}
|
||||
conc := p.MaxPerHost
|
||||
if conc < 1 {
|
||||
conc = 1
|
||||
}
|
||||
rps := max(int(p.RPS+0.5), 1)
|
||||
conc := max(p.MaxPerHost, 1)
|
||||
// The profile's delay between requests is 1/RPS (500 ms, 200 ms, 50 ms).
|
||||
delayMS := int((time.Second / time.Duration(rps)) / time.Millisecond)
|
||||
delaySec := strconv.FormatFloat(1/float64(rps), 'f', -1, 64)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -77,8 +78,8 @@ func textMsg(text string) (llm.Message, string) {
|
||||
}
|
||||
|
||||
func lastToolResultText(req llm.CompletionRequest, toolUseID string) string {
|
||||
for i := len(req.Messages) - 1; i >= 0; i-- {
|
||||
for _, b := range req.Messages[i].Content {
|
||||
for _, v := range slices.Backward(req.Messages) {
|
||||
for _, b := range v.Content {
|
||||
if b.Type == llm.BlockToolResult && b.ToolUseID == toolUseID {
|
||||
var out strings.Builder
|
||||
for _, c := range b.Content {
|
||||
|
||||
+7
-2
@@ -232,6 +232,11 @@ func compactionConfig(windowTokens int) *compaction.Config {
|
||||
return &compaction.Config{ContextWindow: windowTokens}
|
||||
}
|
||||
|
||||
// defaultOpenAIResponsesModel is the model used by the openai-responses format
|
||||
// when none is set. OpenAI shuts gpt-5 down on 2026-12-11 and lists
|
||||
// gpt-6.2-sol as its replacement (platform deprecations page).
|
||||
const defaultOpenAIResponsesModel = "gpt-6.2-sol"
|
||||
|
||||
// FromEnv resolves the LLM provider config:
|
||||
//
|
||||
// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama (default: inferred from keys)
|
||||
@@ -276,7 +281,7 @@ func FromEnv() (Config, bool) {
|
||||
c.Format = llm.FormatOpenAIResponses
|
||||
c.APIKey = oaiKey
|
||||
if c.Model == "" {
|
||||
c.Model = "gpt-5"
|
||||
c.Model = defaultOpenAIResponsesModel
|
||||
}
|
||||
case "ollama":
|
||||
c.Format = FormatOllama
|
||||
@@ -334,7 +339,7 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config {
|
||||
// provider appends "/responses"; tolerate a full endpoint URL.
|
||||
c.BaseURL = strings.TrimRight(strings.TrimSuffix(c.BaseURL, "/responses"), "/")
|
||||
if c.Model == "" {
|
||||
c.Model = "gpt-5"
|
||||
c.Model = defaultOpenAIResponsesModel
|
||||
}
|
||||
case "ollama":
|
||||
c.Format = FormatOllama
|
||||
|
||||
@@ -28,3 +28,30 @@ func TestConfigFromOpenAIResponses(t *testing.T) {
|
||||
t.Fatalf("NewProvider: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIResponsesDefaultModel: with no model set, the openai-responses
|
||||
// format defaults to a model OpenAI still serves. gpt-5 shuts down on
|
||||
// 2026-12-11 (OpenAI deprecations page); its listed replacement is gpt-6.2-sol.
|
||||
// An explicitly chosen model is kept as is.
|
||||
func TestOpenAIResponsesDefaultModel(t *testing.T) {
|
||||
const want = "gpt-6.2-sol"
|
||||
if c := ConfigFrom("openai-responses", "", "", "sk-x", ""); c.Model != want {
|
||||
t.Fatalf("ConfigFrom default model=%q, want %q", c.Model, want)
|
||||
}
|
||||
if c := ConfigFrom("openai-responses", " gpt-5 ", "", "sk-x", ""); c.Model != "gpt-5" {
|
||||
t.Fatalf("ConfigFrom explicit model=%q, want gpt-5 kept", c.Model)
|
||||
}
|
||||
|
||||
t.Setenv("ARTEX_LLM_PROVIDER", "openai-responses")
|
||||
t.Setenv("OPENAI_API_KEY", "sk-oai")
|
||||
t.Setenv("ARTEX_LLM_BASE_URL", "")
|
||||
t.Setenv("ARTEX_LLM_MODEL", "")
|
||||
c, ok := FromEnv()
|
||||
if !ok || c.Model != want {
|
||||
t.Fatalf("FromEnv default model=%q ok=%v, want %q", c.Model, ok, want)
|
||||
}
|
||||
t.Setenv("ARTEX_LLM_MODEL", "gpt-5")
|
||||
if c, ok := FromEnv(); !ok || c.Model != "gpt-5" {
|
||||
t.Fatalf("FromEnv explicit model=%q ok=%v, want gpt-5 kept", c.Model, ok)
|
||||
}
|
||||
}
|
||||
|
||||
+54
-6
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -87,13 +88,16 @@ func containerWorkdir(taskDir, workingDir string) string {
|
||||
// In ARTEX_SANDBOX=required mode it fails closed (no local fallback) and notifies
|
||||
// OnUnavailable when the runner cannot be reached so the engine pauses the task.
|
||||
func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeoutMS int, env []string) (sandbox.ExecResponse, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return sandbox.ExecResponse{}, err
|
||||
}
|
||||
ex := activeSandboxExecutor.Load()
|
||||
if ex == nil || ex.Mode != sandbox.ModeRequired {
|
||||
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
|
||||
}
|
||||
info, ok := SandboxRunInfoFromContext(ctx)
|
||||
if !ok || info.TaskID == "" {
|
||||
return sandbox.ExecResponse{}, fmt.Errorf("%w: missing task sandbox context (no local fallback)", sandbox.ErrRunnerUnavailable)
|
||||
return sandbox.ExecResponse{}, fmt.Errorf("%w: no task sandbox run info in context (no local fallback)", sandbox.ErrMissingSandboxContext)
|
||||
}
|
||||
if ex.Runner == nil {
|
||||
err := fmt.Errorf("%w: runner client is not configured", sandbox.ErrRunnerUnavailable)
|
||||
@@ -111,7 +115,9 @@ func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeou
|
||||
ScopeCIDRs: info.ScopeCIDRs,
|
||||
}
|
||||
resp, err := ex.Runner.Exec(ctx, info.TaskID, req)
|
||||
if err != nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil {
|
||||
// A run deadline or task cancellation says nothing about runner health.
|
||||
// Keep this guard even for runner implementations that wrap cancellation.
|
||||
if err != nil && ctx.Err() == nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil {
|
||||
ex.OnUnavailable(info.TaskID, err)
|
||||
}
|
||||
return resp, err
|
||||
@@ -145,6 +151,12 @@ func (t *sandboxBashTool) Call(ctx context.Context, input json.RawMessage, tc *a
|
||||
}
|
||||
resp, err := ExecInSandbox(ctx, []string{"bash", "-c", in.Command}, workDir, in.TimeoutMS, env)
|
||||
if err != nil {
|
||||
if errors.Is(err, sandbox.ErrMissingSandboxContext) {
|
||||
// Standalone chat agents carry no task sandbox context (#805): say so,
|
||||
// name the supported workflow, and stop the model from retrying Bash
|
||||
// (the retry loop only burns LLM turns).
|
||||
return actool.Errorf("Error: Bash cannot run here: this standalone conversation has no sandbox execution context, and ARTEX_SANDBOX=required allows no local fallback. Do not retry Bash in this conversation; ask the operator to run this work as a task (or set ARTEX_SANDBOX=off)."), nil
|
||||
}
|
||||
return actool.Errorf(fmt.Sprintf("Error: sandbox execution failed (ARTEX_SANDBOX=required, no local fallback): %v", err)), nil
|
||||
}
|
||||
return formatSandboxExecResult(resp, tc), nil
|
||||
@@ -183,23 +195,43 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
|
||||
return actool.Text(out)
|
||||
}
|
||||
|
||||
// SandboxEgressPolicy is the task's sandbox.EgressPolicy for ctx, the one
|
||||
// WebFetch enforces in ARTEX_SANDBOX=required mode: the scope domains and CIDRs
|
||||
// of the run, or, when they do not parse or the run carries none, a policy that
|
||||
// allows nothing.
|
||||
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
|
||||
info, _ := SandboxRunInfoFromContext(ctx)
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
||||
}
|
||||
return pol
|
||||
}
|
||||
|
||||
// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel
|
||||
// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via
|
||||
// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback,
|
||||
// RFC1918, and IPv6 across all hops and redirects).
|
||||
// RFC1918, and IPv6). It sees each hop on a direct connection; through a proxy
|
||||
// it only sees the proxy, and sandboxRedirectCheck checks the hop.
|
||||
func sandboxScopeDialContext(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 SandboxScopeDialContext("WebFetch", policy, baseDial)
|
||||
}
|
||||
|
||||
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
|
||||
// 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) {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, portStr, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err)
|
||||
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port <= 0 || port > 65535 {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr)
|
||||
return nil, fmt.Errorf("sandbox %s blocked invalid port %q", label, portStr)
|
||||
}
|
||||
pinnedIP, err := policy.ResolveAndCheck(ctx, host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err)
|
||||
return nil, fmt.Errorf("sandbox %s blocked: %w", label, err)
|
||||
}
|
||||
pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port))
|
||||
if baseDial != nil {
|
||||
@@ -210,6 +242,22 @@ func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx con
|
||||
}
|
||||
}
|
||||
|
||||
// sandboxRedirectCheck refuses a WebFetch redirect hop to a URL the task's
|
||||
// egress policy does not allow, before check runs. Through a proxy the sandbox
|
||||
// dialer only sees the proxy, so this is where each hop is checked. A nil
|
||||
// policy refuses every hop.
|
||||
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||
return func(req *http.Request, via []*http.Request) error {
|
||||
if policy == nil {
|
||||
return errors.New("sandbox WebFetch blocked redirect: missing task egress policy")
|
||||
}
|
||||
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
|
||||
return fmt.Errorf("sandbox WebFetch blocked redirect: %w", err)
|
||||
}
|
||||
return check(req, via)
|
||||
}
|
||||
}
|
||||
|
||||
// sandboxScopeWebFetchTool gates WebFetch inputs against the task's
|
||||
// sandbox.EgressPolicy before Norma issues any HTTP request.
|
||||
type sandboxScopeWebFetchTool struct {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// TestExecInSandboxMissingContextIsNotRunnerUnavailable covers the error-
|
||||
// reporting slice of issue #805: a standalone chat agent's Bash call fails
|
||||
// with "sandbox runner unavailable: missing task sandbox context" even when
|
||||
// the runner is healthy, sending operators debugging a service that was never
|
||||
// called. Missing execution context is a different failure category and must
|
||||
// be reported as such.
|
||||
func TestExecInSandboxMissingContextIsNotRunnerUnavailable(t *testing.T) {
|
||||
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
|
||||
t.Cleanup(func() { SetSandboxExecutor(nil) })
|
||||
|
||||
// No SandboxRunInfo on the context: the standalone chat path (issue #805).
|
||||
_, err := ExecInSandbox(context.Background(), []string{"true"}, "", 1000, nil)
|
||||
if err == nil {
|
||||
t.Fatal("missing sandbox context must fail closed")
|
||||
}
|
||||
if !errors.Is(err, sandbox.ErrMissingSandboxContext) {
|
||||
t.Fatalf("missing context must match ErrMissingSandboxContext, got %v", err)
|
||||
}
|
||||
if sandbox.IsUnavailable(err) {
|
||||
t.Fatalf("missing context is not a runner-outage: IsUnavailable must be false, got %v", err)
|
||||
}
|
||||
|
||||
// Context present but runner gone: still classified as runner-unavailable,
|
||||
// so the two failure categories stay distinguishable.
|
||||
ctx := WithSandboxRunInfo(context.Background(), SandboxRunInfo{TaskID: "42"})
|
||||
_, err = ExecInSandbox(ctx, []string{"true"}, "", 1000, nil)
|
||||
if err == nil || !sandbox.IsUnavailable(err) {
|
||||
t.Fatalf("nil runner with task context must stay runner-unavailable, got %v", err)
|
||||
}
|
||||
if errors.Is(err, sandbox.ErrMissingSandboxContext) {
|
||||
t.Fatalf("runner-outage must not match ErrMissingSandboxContext, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSandboxBashToolMissingContextGuidesOperator: in required mode the Bash
|
||||
// tool must tell the model WHY execution is impossible and to stop retrying,
|
||||
// instead of a generic failure it will retry while burning LLM turns (#805).
|
||||
func TestSandboxBashToolMissingContextGuidesOperator(t *testing.T) {
|
||||
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
|
||||
t.Cleanup(func() { SetSandboxExecutor(nil) })
|
||||
|
||||
tool := &sandboxBashTool{}
|
||||
in, _ := json.Marshal(map[string]any{"command": "true"})
|
||||
res, err := tool.Call(context.Background(), in, &actool.ToolContext{})
|
||||
if err != nil {
|
||||
t.Fatalf("tool call returned Go error: %v", err)
|
||||
}
|
||||
text := strings.ToLower(res.Flatten())
|
||||
if !strings.Contains(text, "context") {
|
||||
t.Fatalf("error must name the missing execution context, got %q", res.Flatten())
|
||||
}
|
||||
if !strings.Contains(text, "task") {
|
||||
t.Fatalf("error must point at the supported workflow (run as a task), got %q", res.Flatten())
|
||||
}
|
||||
if strings.Contains(text, "runner unavailable") {
|
||||
t.Fatalf("error must not blame the runner for a context problem, got %q", res.Flatten())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
func TestSandboxRedirectCheck(t *testing.T) {
|
||||
pol, err := sandbox.NewEgressPolicy("rc", []string{"allowed.example"}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := sandbox.WithResolver(context.Background(), offlineResolver(map[string]string{
|
||||
"allowed.example": "203.0.113.10",
|
||||
"evil.example": "203.0.113.66",
|
||||
"rebind.example": "169.254.169.254",
|
||||
}))
|
||||
hop := func(rawURL string) *http.Request {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return req
|
||||
}
|
||||
via := []*http.Request{hop("http://allowed.example/start")}
|
||||
counting := func(calls *int, ret error) func(*http.Request, []*http.Request) error {
|
||||
return func(*http.Request, []*http.Request) error {
|
||||
*calls++
|
||||
return ret
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("allowed hop runs the redirect check", func(t *testing.T) {
|
||||
var calls int
|
||||
if err := sandboxRedirectCheck(pol, counting(&calls, nil))(hop("http://allowed.example/next"), via); err != nil {
|
||||
t.Fatalf("allowed hop refused: %v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("redirect check ran %d times, want 1", calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("redirect check result is returned", func(t *testing.T) {
|
||||
var calls int
|
||||
gate := errors.New("gate refused")
|
||||
err := sandboxRedirectCheck(pol, counting(&calls, gate))(hop("http://allowed.example/next"), via)
|
||||
if !errors.Is(err, gate) || calls != 1 {
|
||||
t.Fatalf("err=%v calls=%d, want the redirect check's error after one call", err, calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("intercept redirect limit kept", func(t *testing.T) {
|
||||
check := sandboxRedirectCheck(pol, intercept.RedirectCheck("WebFetch"))
|
||||
if err := check(hop("http://allowed.example/next"), via); err != nil {
|
||||
t.Fatalf("allowed hop refused: %v", err)
|
||||
}
|
||||
ten := make([]*http.Request, 10)
|
||||
for i := range ten {
|
||||
ten[i] = via[0]
|
||||
}
|
||||
err := check(hop("http://allowed.example/next"), ten)
|
||||
if err == nil || !strings.Contains(err.Error(), "stopped after 10 redirects") {
|
||||
t.Fatalf("11th hop: err=%v, want the intercept redirect limit", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("denied hops", func(t *testing.T) {
|
||||
for _, u := range []string{
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://127.0.0.1:8080/",
|
||||
"http://10.1.2.3/admin",
|
||||
"http://evil.example/collect",
|
||||
"http://rebind.example/",
|
||||
"file:///etc/passwd",
|
||||
} {
|
||||
var calls int
|
||||
err := sandboxRedirectCheck(pol, counting(&calls, nil))(hop(u), via)
|
||||
if err == nil || !strings.Contains(err.Error(), "sandbox WebFetch blocked redirect") {
|
||||
t.Fatalf("%s: err=%v, want a sandbox redirect refusal", u, err)
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("%s: redirect check ran %d times after a refusal", u, calls)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil policy blocks", func(t *testing.T) {
|
||||
var calls int
|
||||
err := sandboxRedirectCheck(nil, counting(&calls, nil))(hop("http://allowed.example/next"), via)
|
||||
if err == nil || !strings.Contains(err.Error(), "sandbox WebFetch blocked redirect") || calls != 0 {
|
||||
t.Fatalf("err=%v calls=%d, want a refusal without running the redirect check", err, calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -38,10 +39,8 @@ func openScanOutputFromWorkRoot(w *workRoot, path string) (*os.File, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, errors.New("path is required")
|
||||
}
|
||||
for _, el := range strings.Split(filepath.ToSlash(path), "/") {
|
||||
if el == ".." {
|
||||
return nil, errors.New("path must not contain ..")
|
||||
}
|
||||
if slices.Contains(strings.Split(filepath.ToSlash(path), "/"), "..") {
|
||||
return nil, errors.New("path must not contain ..")
|
||||
}
|
||||
rel, err := w.rel(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
func attachSideCapture(ctx context.Context, opts *agentcore.Options) context.Context {
|
||||
ri := RunInfoFrom(ctx)
|
||||
p := sidequestion.Parent{TaskID: ri.TaskID, ExplorationID: ri.ExplorationID, IntentID: ri.IntentID}
|
||||
if strings.HasPrefix(ri.SessionID, "conv-") {
|
||||
p.ConversationID, _ = strconv.ParseInt(strings.TrimPrefix(ri.SessionID, "conv-"), 10, 64)
|
||||
if after, ok := strings.CutPrefix(ri.SessionID, "conv-"); ok {
|
||||
p.ConversationID, _ = strconv.ParseInt(after, 10, 64)
|
||||
}
|
||||
if p.ConversationID == 0 && (p.TaskID == 0 || p.ExplorationID == 0) {
|
||||
return ctx
|
||||
|
||||
@@ -26,16 +26,17 @@ func TestSkillIndexBlock_Empty(t *testing.T) {
|
||||
if got := SkillIndexBlock(nil); got != "" {
|
||||
t.Fatalf("no skills must render nothing, got %q", got)
|
||||
}
|
||||
// An agent without skills keeps its previous prompt byte-for-byte.
|
||||
// An agent without skills keeps its previous prompt byte-for-byte, and the
|
||||
// unchanged prompt is exactly what the cache breakpoint covers (#809).
|
||||
sys, boundary := deferredSystem("SYS", DeferredInfo{})
|
||||
if len(sys) != 1 || sys[0] != "SYS" || boundary != 0 {
|
||||
t.Fatalf("expected [SYS],0 — got %v,%d", sys, boundary)
|
||||
if len(sys) != 1 || sys[0] != "SYS" || boundary != 1 {
|
||||
t.Fatalf("expected [SYS],1 — got %v,%d", sys, boundary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillIndexBlock_Caps(t *testing.T) {
|
||||
var names []string
|
||||
for i := 0; i < 200; i++ {
|
||||
for i := range 200 {
|
||||
names = append(names, fmt.Sprintf("skill-with-a-long-name-%03d", i))
|
||||
}
|
||||
block := SkillIndexBlock(names)
|
||||
@@ -50,8 +51,8 @@ func TestSkillIndexBlock_Caps(t *testing.T) {
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("index must be rule + one names line, got %d lines:\n%s", len(lines), block)
|
||||
}
|
||||
parts := strings.Split(strings.Split(lines[1], " (+")[0], ", ")
|
||||
for _, part := range parts {
|
||||
parts := strings.SplitSeq(strings.Split(lines[1], " (+")[0], ", ")
|
||||
for part := range parts {
|
||||
if !strings.HasPrefix(part, "skill-with-a-long-name-") {
|
||||
t.Fatalf("cut mid-name: %q", part)
|
||||
}
|
||||
|
||||
+2
-4
@@ -105,10 +105,8 @@ func clampMaxDuration(deadlineUnix int64, ownBudget time.Duration) (eff time.Dur
|
||||
if deadlineUnix <= 0 {
|
||||
return ownBudget, false
|
||||
}
|
||||
remaining := time.Until(time.Unix(deadlineUnix, 0))
|
||||
if remaining < time.Second {
|
||||
remaining = time.Second // max(1, …): never pass ≤0 (harness treats 0 as unlimited)
|
||||
}
|
||||
// At least 1s: never pass ≤0 (the harness treats 0 as unlimited).
|
||||
remaining := max(time.Until(time.Unix(deadlineUnix, 0)), time.Second)
|
||||
// clamped when the task deadline binds this run's time: remaining ≤ own budget,
|
||||
// or the agent has no own time budget (then remaining always binds).
|
||||
clamped = ownBudget <= 0 || remaining <= ownBudget
|
||||
|
||||
@@ -139,7 +139,7 @@ func TestTerminalTextNonAbortReasons(t *testing.T) {
|
||||
|
||||
func TestAbortCausesAreWellFormed(t *testing.T) {
|
||||
all := []*AbortCause{
|
||||
AbortPausedByUser, AbortPausedByOrchestrator, AbortTaskDeleted, AbortPausedOnReload,
|
||||
AbortPausedByUser, AbortPausedByOrchestrator, AbortSandboxUnavailable, AbortTaskDeleted, AbortPausedOnReload,
|
||||
AbortGoalMet, AbortSettleDrainTimeout, AbortKilledByPlanner, AbortWorkPausedByUser,
|
||||
AbortWorkCancelledByUser, AbortWorkClaimLost, AbortWorkFinished, AbortPausedRaceGuard,
|
||||
AbortChatStoppedByUser, AbortChatPausedWithTask, AbortChatTurnFinished,
|
||||
|
||||
@@ -134,7 +134,7 @@ func TestToolRAGDeterministic(t *testing.T) {
|
||||
// "zzz" matches nothing: every candidate ties at 0 and the name tie-break decides.
|
||||
for _, q := range []string{ragQuery, "zzz"} {
|
||||
first, _, _ := projectTools(q, ragCatalog(30), keep, 4, bm25Score)
|
||||
for i := 0; i < 20; i++ {
|
||||
for i := range 20 {
|
||||
again, _, _ := projectTools(q, ragCatalog(30), keep, 4, bm25Score)
|
||||
if !slices.Equal(ragNames(first), ragNames(again)) {
|
||||
t.Fatalf("%q: run %d = %v, want %v", q, i, ragNames(again), ragNames(first))
|
||||
|
||||
+3
-9
@@ -849,10 +849,7 @@ func relatedOverviewBudgetForSources(sourceCount int) int {
|
||||
if sourceCount > db.MaxTaskSourceCount {
|
||||
sourceCount = db.MaxTaskSourceCount
|
||||
}
|
||||
perSource := relatedOverviewTotalTextRunes / sourceCount
|
||||
if perSource > relatedOverviewMaxTextPerSource {
|
||||
perSource = relatedOverviewMaxTextPerSource
|
||||
}
|
||||
perSource := min(relatedOverviewTotalTextRunes/sourceCount, relatedOverviewMaxTextPerSource)
|
||||
return perSource
|
||||
}
|
||||
|
||||
@@ -874,10 +871,7 @@ func (b *overviewTextBudget) take(value any, fieldLimit int) string {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(text)
|
||||
limit := fieldLimit
|
||||
if limit > b.remaining {
|
||||
limit = b.remaining
|
||||
}
|
||||
limit := min(fieldLimit, b.remaining)
|
||||
if len(runes) > limit {
|
||||
b.truncated = true
|
||||
if limit == 1 {
|
||||
@@ -1999,7 +1993,7 @@ const factEvidenceMaxLines = 20
|
||||
func factEvidenceLines(evidence string) []string {
|
||||
out := make([]string, 0, 4)
|
||||
seen := map[string]bool{}
|
||||
for _, raw := range strings.Split(evidence, "\n") {
|
||||
for raw := range strings.SplitSeq(evidence, "\n") {
|
||||
line := strings.TrimSpace(raw)
|
||||
if len([]rune(line)) < factEvidenceMinRunes || seen[line] {
|
||||
continue
|
||||
|
||||
@@ -701,7 +701,7 @@ func (t *ToolSet) listCompanies() actool.CoreTool {
|
||||
// splitLines splits a multi-line string into non-empty trimmed lines.
|
||||
func splitLines(s string) []string {
|
||||
var out []string
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
for line := range strings.SplitSeq(s, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" {
|
||||
out = append(out, line)
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestCapTextCutsOnRuneBoundary(t *testing.T) {
|
||||
// the whole state must still parse as text.
|
||||
func TestBuildDuplicateStateCutsOnRuneBoundary(t *testing.T) {
|
||||
existing := make([]TriageCandidate, 0, 40)
|
||||
for i := 0; i < 40; i++ {
|
||||
for i := range 40 {
|
||||
existing = append(existing, TriageCandidate{
|
||||
FindingID: int64(i + 1),
|
||||
Name: "数据泄露",
|
||||
|
||||
@@ -231,7 +231,7 @@ func TestBuildDuplicateState_CapsPerEntry(t *testing.T) {
|
||||
|
||||
func TestBuildDuplicateState_Caps(t *testing.T) {
|
||||
var many []TriageCandidate
|
||||
for i := 0; i < 200; i++ {
|
||||
for i := range 200 {
|
||||
many = append(many, TriageCandidate{FindingID: int64(i), Summary: strings.Repeat("x", 200)})
|
||||
}
|
||||
st := buildDuplicateState(triageCandidate(), many)
|
||||
@@ -280,13 +280,13 @@ func TestTriageThresholdConcurrentSetAndRead(t *testing.T) {
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
for i := range 2000 {
|
||||
SetTriageMinConfidence(0.3 + 0.4*float64(i%2))
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
for range 2000 {
|
||||
_ = triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.6})
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestUntrustedBoundaryWiredInOptionsLiterals(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := 0
|
||||
for _, line := range strings.Split(string(src), "\n") {
|
||||
for line := range strings.SplitSeq(string(src), "\n") {
|
||||
if strings.TrimSpace(line) == want {
|
||||
n++
|
||||
}
|
||||
|
||||
+7
-6
@@ -23,23 +23,24 @@ import (
|
||||
// adds it, so the tool list keeps its order. caCert is the recording proxy's
|
||||
// CA, trusted to verify the HTTPS it re-signs. Each call goes through the shared
|
||||
// egress governor (see governedFetch). tools is not modified.
|
||||
// In ARTEX_SANDBOX=required mode each redirect hop is first checked against the
|
||||
// task's egress policy (sandboxRedirectCheck): through a proxy the sandbox
|
||||
// dialer only sees the proxy.
|
||||
func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert string) []actool.CoreTool {
|
||||
scope, scoped := intercept.TargetScopeFromContext(ctx)
|
||||
gated := scoped && scope.Enabled != nil && scope.Enabled()
|
||||
dialer := intercept.PinnedDialer("WebFetch", scoped)
|
||||
disableDirect := gated
|
||||
checkRedirect := intercept.RedirectCheck("WebFetch")
|
||||
var sbPolicy *sandbox.EgressPolicy
|
||||
if SandboxRequired() {
|
||||
info, _ := SandboxRunInfoFromContext(ctx)
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
||||
}
|
||||
pol := SandboxEgressPolicy(ctx)
|
||||
sbPolicy = pol
|
||||
dialer = sandboxScopeDialContext(pol, dialer)
|
||||
checkRedirect = sandboxRedirectCheck(pol, checkRedirect)
|
||||
disableDirect = true
|
||||
}
|
||||
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: intercept.RedirectCheck("WebFetch"),
|
||||
webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: checkRedirect,
|
||||
DialContext: dialer, DisableDirectRetry: disableDirect})
|
||||
var wrapped actool.CoreTool = governedFetch{webFetch}
|
||||
if SandboxRequired() {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
// offlineResolver answers sandbox policy lookups from answers, without the
|
||||
// network; any other name fails to resolve.
|
||||
func offlineResolver(answers map[string]string) func(context.Context, string) ([]netip.Addr, error) {
|
||||
return func(_ context.Context, host string) ([]netip.Addr, error) {
|
||||
if ip, ok := answers[strings.ToLower(host)]; ok {
|
||||
return []netip.Addr{netip.MustParseAddr(ip)}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("offline resolver: no answer for %q", host)
|
||||
}
|
||||
}
|
||||
|
||||
// redirectProxy is a plain-HTTP forward proxy that records the absolute URL of
|
||||
// every request it receives. It answers first with a 302 to location and any
|
||||
// other URL with 200 and PROXIED_BODY; it never connects anywhere itself.
|
||||
func redirectProxy(t *testing.T, first, location string) (*httptest.Server, func() []string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.URL.String())
|
||||
mu.Unlock()
|
||||
if r.URL.String() == first {
|
||||
http.Redirect(w, r, location, http.StatusFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
_, _ = w.Write([]byte("PROXIED_BODY"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), seen...)
|
||||
}
|
||||
}
|
||||
|
||||
// sandboxRedirectCtx is the context of a run in scope allowed.example, with the
|
||||
// loopback proxy in scope so the sandbox dialer lets WebFetch reach it. Names
|
||||
// resolve offline.
|
||||
func sandboxRedirectCtx() context.Context {
|
||||
ctx := WithSandboxRunInfo(context.Background(), SandboxRunInfo{
|
||||
TaskID: "wf-redirect",
|
||||
ScopeDomains: []string{"allowed.example"},
|
||||
ScopeCIDRs: []string{"127.0.0.1/32"},
|
||||
})
|
||||
return sandbox.WithResolver(ctx, offlineResolver(map[string]string{
|
||||
"allowed.example": "203.0.113.10",
|
||||
"www.allowed.example": "203.0.113.11",
|
||||
"evil.example": "203.0.113.66",
|
||||
}))
|
||||
}
|
||||
|
||||
// In ARTEX_SANDBOX=required mode, WebFetch through a proxy checks every
|
||||
// redirect hop against the task's egress policy: the sandbox dialer only sees
|
||||
// the proxy, so a hop to IMDS, a private address or an out-of-scope domain
|
||||
// must be refused before the proxy is asked for it.
|
||||
func TestSandboxWebFetchProxyRedirectChecksEgressPolicy(t *testing.T) {
|
||||
pinNoiseOff(t)
|
||||
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
|
||||
t.Cleanup(func() { SetSandboxExecutor(nil) })
|
||||
|
||||
const first = "http://allowed.example/start"
|
||||
for name, location := range map[string]string{
|
||||
"imds": "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
|
||||
"out-of-scope": "http://evil.example/collect",
|
||||
"private-address": "http://10.1.2.3/admin",
|
||||
"loopback-address": "http://127.0.0.2:8080/",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
proxy, seen := redirectProxy(t, first, location)
|
||||
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
|
||||
got := seen()
|
||||
for _, u := range got {
|
||||
if u == location {
|
||||
t.Fatalf("the proxy was asked for the denied redirect target %s (proxy log %q)", location, got)
|
||||
}
|
||||
}
|
||||
if len(got) != 1 || got[0] != first {
|
||||
t.Fatalf("proxy log = %q, want only %s", got, first)
|
||||
}
|
||||
if !isErr || !strings.Contains(text, "sandbox WebFetch blocked redirect") {
|
||||
t.Fatalf("want a sandbox redirect refusal, got isError=%v text=%q", isErr, text)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("in-scope hop is followed", func(t *testing.T) {
|
||||
const location = "http://www.allowed.example/next"
|
||||
proxy, seen := redirectProxy(t, first, location)
|
||||
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
|
||||
if got := seen(); len(got) != 2 || got[0] != first || got[1] != location {
|
||||
t.Fatalf("proxy log = %q, want %s then %s", got, first, location)
|
||||
}
|
||||
if isErr || !strings.Contains(text, "PROXIED_BODY") {
|
||||
t.Fatalf("want the in-scope hop fetched, got isError=%v text=%q", isErr, text)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Outside ARTEX_SANDBOX=required mode the WebFetch redirect handling is
|
||||
// unchanged: no egress policy applies, so the proxy is asked for the hop.
|
||||
func TestWebFetchProxyRedirectSandboxOffUnchanged(t *testing.T) {
|
||||
pinNoiseOff(t)
|
||||
SetSandboxExecutor(nil)
|
||||
|
||||
const first = "http://allowed.example/start"
|
||||
const location = "http://169.254.169.254/latest/meta-data/"
|
||||
proxy, seen := redirectProxy(t, first, location)
|
||||
text, isErr := callWebFetch(t, sandboxRedirectCtx(), proxy.URL, first)
|
||||
if got := seen(); len(got) != 2 || got[0] != first || got[1] != location {
|
||||
t.Fatalf("proxy log = %q, want %s then %s", got, first, location)
|
||||
}
|
||||
if isErr || !strings.Contains(text, "PROXIED_BODY") {
|
||||
t.Fatalf("want the hop followed, got isError=%v text=%q", isErr, text)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -277,7 +277,7 @@ const (
|
||||
|
||||
func (s *Store) readArchiveChunk(ctx context.Context, key, etag string, start, end, total int64) ([]byte, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < archiveReadAttempts; attempt++ {
|
||||
for attempt := range archiveReadAttempts {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package chatbridge
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -267,10 +268,5 @@ func parseCommand(text, botUserName string) (name, args string, forOther bool) {
|
||||
}
|
||||
|
||||
func contains(list []string, v string) bool {
|
||||
for _, s := range list {
|
||||
if s == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(list, v)
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) {
|
||||
if strings.Contains(reply, "echo") {
|
||||
t.Fatalf("refusal must not run the command: %q", reply)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
for i := range 3 {
|
||||
if d, reply := r.Route(context.Background(), KindTelegram, Access{Chats: []string{"100"}}, msg("555", "hello?")); d != DecisionMuted || reply != "" {
|
||||
t.Fatalf("repeat %d: got %v %q", i, d, reply)
|
||||
}
|
||||
@@ -67,7 +67,7 @@ func TestRouteEmptyAllowlistRefusesEveryone(t *testing.T) {
|
||||
|
||||
func TestRouteRefusalMemoryIsBounded(t *testing.T) {
|
||||
r := testRouter()
|
||||
for i := 0; i < maxRefusedChats; i++ {
|
||||
for i := range maxRefusedChats {
|
||||
r.Route(context.Background(), KindTelegram, Access{}, msg("c"+itoa(i), "hi"))
|
||||
}
|
||||
// Past the cap the memory starts over: a new chat (it may be the
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
//go:build unix
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
const (
|
||||
egressListDomainsOld = "# hand-written\nold.example.com\n"
|
||||
egressListCIDRsOld = "# hand-written\n192.0.2.0/24\n"
|
||||
)
|
||||
|
||||
// runExportScopeScript runs egress-guard/export-scope.sh against a lists
|
||||
// directory seeded with the "old" lists. The artex binary is replaced by a
|
||||
// stub that prints exportOutput and exits with exportExit.
|
||||
func runExportScopeScript(t *testing.T, exportOutput string, exportExit int, extraArgs ...string) (listsDir, output string, err error) {
|
||||
t.Helper()
|
||||
if _, lookErr := exec.LookPath("bash"); lookErr != nil {
|
||||
t.Skip("bash not available")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
listsDir = filepath.Join(tmp, "lists")
|
||||
if mkErr := os.MkdirAll(listsDir, 0o755); mkErr != nil {
|
||||
t.Fatal(mkErr)
|
||||
}
|
||||
for name, body := range map[string]string{"scope-domains.txt": egressListDomainsOld, "scope-cidrs.txt": egressListCIDRsOld} {
|
||||
if wErr := os.WriteFile(filepath.Join(listsDir, name), []byte(body), 0o644); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
}
|
||||
payload := filepath.Join(tmp, "export.out")
|
||||
if wErr := os.WriteFile(payload, []byte(exportOutput), 0o644); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
argsLog := filepath.Join(tmp, "args.log")
|
||||
stub := filepath.Join(tmp, "artex-stub")
|
||||
stubBody := "#!/usr/bin/env bash\nprintf '%s\\n' \"$*\" > '" + argsLog + "'\ncat '" + payload + "'\nexit " + strconv.Itoa(exportExit) + "\n"
|
||||
if wErr := os.WriteFile(stub, []byte(stubBody), 0o755); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
script := filepath.Join("..", "..", "egress-guard", "export-scope.sh")
|
||||
args := append([]string{script, "--lists", listsDir}, extraArgs...)
|
||||
args = append(args, "--", stub)
|
||||
out, err := exec.Command("bash", args...).CombinedOutput()
|
||||
if raw, rErr := os.ReadFile(argsLog); rErr == nil {
|
||||
output = "stub args: " + string(raw)
|
||||
}
|
||||
return listsDir, output + string(out), err
|
||||
}
|
||||
|
||||
func readEgressList(t *testing.T, listsDir, name string) string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(listsDir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
// egressListEntries reads a list the way egress-guard/entrypoint.sh read_list
|
||||
// does: comments and blank lines dropped.
|
||||
func egressListEntries(t *testing.T, listsDir, name string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
for _, line := range strings.Split(readEgressList(t, listsDir, name), "\n") {
|
||||
if i := strings.Index(line, "#"); i >= 0 {
|
||||
line = line[:i]
|
||||
}
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func assertEgressListsUnchanged(t *testing.T, listsDir string) {
|
||||
t.Helper()
|
||||
if got := readEgressList(t, listsDir, "scope-domains.txt"); got != egressListDomainsOld {
|
||||
t.Fatalf("scope-domains.txt changed on a failed export:\n%s", got)
|
||||
}
|
||||
if got := readEgressList(t, listsDir, "scope-cidrs.txt"); got != egressListCIDRsOld {
|
||||
t.Fatalf("scope-cidrs.txt changed on a failed export:\n%s", got)
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
func assertNoStagedEgressFiles(t *testing.T, listsDir string) {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(listsDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("staged files left in the lists directory: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportScopeScriptReplacesLists(t *testing.T) {
|
||||
export := "# artex egress-guard scope export v1\n# tasks: 3,7\n" +
|
||||
"domain app.example.org\ndomain example.net\ncidr 198.51.100.0/24\n" +
|
||||
"# skipped \"2001:db8::/32\": IPv6, egress-guard is IPv4-only\n" +
|
||||
"# end domains=2 cidrs=1\n"
|
||||
listsDir, out, err := runExportScopeScript(t, export, 0, "--tasks", "3,7")
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh failed: %v\n%s", err, out)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-domains.txt"); strings.Join(got, ",") != "app.example.org,example.net" {
|
||||
t.Fatalf("scope-domains.txt entries = %v", got)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-cidrs.txt"); strings.Join(got, ",") != "198.51.100.0/24" {
|
||||
t.Fatalf("scope-cidrs.txt entries = %v", got)
|
||||
}
|
||||
if !strings.Contains(out, "stub args: -export-egress-guard-scope -export-egress-guard-tasks 3,7\n") {
|
||||
t.Fatalf("artex was not called with the export flags:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "not exported: \"2001:db8::/32\"") {
|
||||
t.Fatalf("skipped entry was not reported:\n%s", out)
|
||||
}
|
||||
for _, name := range []string{"scope-domains.txt", "scope-cidrs.txt"} {
|
||||
st, err := os.Stat(filepath.Join(listsDir, name))
|
||||
if err != nil || st.Mode().Perm() != 0o644 {
|
||||
t.Fatalf("%s mode = %#o err=%v, want 0644 (read by the egress-guard container)", name, st.Mode().Perm(), err)
|
||||
}
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
// A failed or damaged export must leave both lists byte-for-byte as they were:
|
||||
// a partial list would silently widen or narrow what the overlay enforces.
|
||||
func TestExportScopeScriptLeavesListsOnFailure(t *testing.T) {
|
||||
good := "# artex egress-guard scope export v1\n# tasks: 3\ndomain new.example.org\ncidr 198.51.100.0/24\n"
|
||||
cases := []struct {
|
||||
name string
|
||||
export string
|
||||
exit int
|
||||
want string
|
||||
}{
|
||||
{"export command fails after printing", good + "# end domains=1 cidrs=1\n", 1, "export command failed"},
|
||||
{"missing trailer", good, 0, "truncated or inconsistent"},
|
||||
{"trailer count mismatch", good + "# end domains=2 cidrs=1\n", 0, "truncated or inconsistent"},
|
||||
{"no output", "", 0, "truncated or inconsistent"},
|
||||
{"data after trailer", good + "# end domains=1 cidrs=1\ndomain late.example.org\n", 0, "data after the export trailer"},
|
||||
{"domain with dnsmasq syntax", "domain evil.test/artex_allow\n# end domains=1 cidrs=0\n", 0, "malformed domain entry"},
|
||||
{"cidr that is not IPv4", "cidr 2001:db8::/32\n# end domains=0 cidrs=1\n", 0, "malformed cidr entry"},
|
||||
{"unknown line", "allow everything\n# end domains=0 cidrs=0\n", 0, "unexpected line"},
|
||||
{"empty export", "# artex egress-guard scope export v1\n# tasks: \n# end domains=0 cidrs=0\n", 0, "fall back to monitor"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
listsDir, out, err := runExportScopeScript(t, tc.export, tc.exit)
|
||||
if err == nil {
|
||||
t.Fatalf("export-scope.sh succeeded, want a failure:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(strings.Join(strings.Fields(out), " "), strings.Join(strings.Fields(tc.want), " ")) {
|
||||
t.Fatalf("output lacks %q:\n%s", tc.want, out)
|
||||
}
|
||||
assertEgressListsUnchanged(t, listsDir)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An empty export is written only on request, for an overlay pinned to enforce.
|
||||
// A list path that is a directory must be refused up front: mv would move the
|
||||
// new list inside it and report success, leaving the guard reading nothing.
|
||||
func TestExportScopeScriptRefusesDirectoryTarget(t *testing.T) {
|
||||
if _, err := exec.LookPath("bash"); err != nil {
|
||||
t.Skip("bash not available")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
listsDir := filepath.Join(tmp, "lists")
|
||||
if err := os.MkdirAll(filepath.Join(listsDir, "scope-cidrs.txt"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(listsDir, "scope-domains.txt"), []byte(egressListDomainsOld), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ran := filepath.Join(tmp, "ran")
|
||||
stub := filepath.Join(tmp, "artex-stub")
|
||||
stubBody := "#!/usr/bin/env bash\n: > '" + ran + "'\nprintf 'domain new.example.com\\ncidr 198.51.100.0/24\\n# end domains=1 cidrs=1\\n'\n"
|
||||
if err := os.WriteFile(stub, []byte(stubBody), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join("..", "..", "egress-guard", "export-scope.sh")
|
||||
out, err := exec.Command("bash", script, "--lists", listsDir, "--", stub).CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("export onto a directory target succeeded:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(string(out), "is a directory") {
|
||||
t.Fatalf("missing directory diagnostic:\n%s", out)
|
||||
}
|
||||
if _, statErr := os.Stat(ran); statErr == nil {
|
||||
t.Fatal("export command ran although a list target is a directory")
|
||||
}
|
||||
if got := readEgressList(t, listsDir, "scope-domains.txt"); got != egressListDomainsOld {
|
||||
t.Fatalf("scope-domains.txt changed: %q", got)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(listsDir, "scope-cidrs.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("a file was moved into the scope-cidrs.txt directory: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportScopeScriptAllowEmpty(t *testing.T) {
|
||||
export := "# artex egress-guard scope export v1\n# tasks: \n# end domains=0 cidrs=0\n"
|
||||
listsDir, out, err := runExportScopeScript(t, export, 0, "--allow-empty")
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh --allow-empty failed: %v\n%s", err, out)
|
||||
}
|
||||
for _, name := range []string{"scope-domains.txt", "scope-cidrs.txt"} {
|
||||
if got := egressListEntries(t, listsDir, name); len(got) != 0 {
|
||||
t.Fatalf("%s entries = %v, want none", name, got)
|
||||
}
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
// End to end without Docker: the output of -export-egress-guard-scope, read
|
||||
// from PostgreSQL, goes through export-scope.sh into the two lists.
|
||||
func TestExportEgressGuardScopeToLists(t *testing.T) {
|
||||
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
|
||||
if dsn == "" {
|
||||
t.Skip("ARTEX_PG_DSN not set")
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.Close() })
|
||||
|
||||
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
opDom := "cli-op-" + sfx + ".test"
|
||||
agentDom := "cli-agent-" + sfx + ".test"
|
||||
task, err := pg.CreateTaskWithOptions("egress-export-cli-"+sfx, "goal", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })
|
||||
as := pg.Assets()
|
||||
if _, err := as.AddOperatorScope(task.ID, "subdomain", opDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope: %v", err)
|
||||
}
|
||||
if _, err := as.AddOperatorScope(task.ID, "cidr", "198.51.100.0/24", "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope cidr: %v", err)
|
||||
}
|
||||
if _, err := as.AddAgentScope(task.ID, "subdomain", agentDom, "agent", "agent"); err != nil {
|
||||
t.Fatalf("AddAgentScope: %v", err)
|
||||
}
|
||||
|
||||
taskArg := strconv.FormatInt(task.ID, 10)
|
||||
var buf bytes.Buffer
|
||||
if rc := runExportEgressGuardScope(taskArg, &buf); rc != 0 {
|
||||
t.Fatalf("runExportEgressGuardScope rc=%d output=%q", rc, buf.String())
|
||||
}
|
||||
listsDir, out, err := runExportScopeScript(t, buf.String(), 0, "--tasks", taskArg)
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh failed: %v\n%s", err, out)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-domains.txt"); len(got) != 1 || got[0] != opDom {
|
||||
t.Fatalf("scope-domains.txt entries = %v, want [%s]", got, opDom)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-cidrs.txt"); len(got) != 1 || got[0] != "198.51.100.0/24" {
|
||||
t.Fatalf("scope-cidrs.txt entries = %v", got)
|
||||
}
|
||||
|
||||
// A failed export prints nothing, so the script has nothing to install.
|
||||
for _, bad := range []string{"0", "abc", ",", strconv.FormatInt(1<<60, 10)} {
|
||||
buf.Reset()
|
||||
if rc := runExportEgressGuardScope(bad, &buf); rc == 0 || buf.Len() != 0 {
|
||||
t.Fatalf("runExportEgressGuardScope(%q) rc=%d output=%q, want a failure and no output", bad, rc, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -125,12 +126,18 @@ func run() int {
|
||||
rotateSecrets = flag.Bool("rotate-secrets", false, "re-encrypt database secrets from -rotate-old-secret-file to -rotate-new-secret-file, invalidate active JWT sessions, and exit")
|
||||
rotateOldSecretFile = flag.String("rotate-old-secret-file", "", "path to current secret.key (used with -rotate-secrets)")
|
||||
rotateNewSecretFile = flag.String("rotate-new-secret-file", "", "path to staged new secret.key (used with -rotate-secrets)")
|
||||
// Scope export for the optional egress-guard overlay, invoked by egress-guard/export-scope.sh.
|
||||
exportEgressGuardScope = flag.Bool("export-egress-guard-scope", false, "print the operator-approved task scope in the form egress-guard/export-scope.sh reads, and exit")
|
||||
exportEgressGuardTasks = flag.String("export-egress-guard-tasks", "", "comma-separated task ids for -export-egress-guard-scope (default: every task that is not finished)")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
if *rotateSecrets {
|
||||
return runRotateSecrets(*rotateOldSecretFile, *rotateNewSecretFile)
|
||||
}
|
||||
if *exportEgressGuardScope {
|
||||
return runExportEgressGuardScope(*exportEgressGuardTasks, os.Stdout)
|
||||
}
|
||||
|
||||
// hand the build version and source revision to the server package so
|
||||
// GET /api/health can report them to the frontend top bar.
|
||||
@@ -348,6 +355,51 @@ func envBool(name string, def bool) bool {
|
||||
return v
|
||||
}
|
||||
|
||||
// runExportEgressGuardScope prints the egress-guard allowlist derived from the
|
||||
// operator-approved task scope. Nothing is written to out unless the whole
|
||||
// export succeeded, so a failed run cannot hand the caller a partial list.
|
||||
func runExportEgressGuardScope(tasksCSV string, out io.Writer) int {
|
||||
var taskIDs []int64
|
||||
for _, part := range strings.Split(tasksCSV, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.ParseInt(part, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
slog.Error("[egress-guard-export] invalid task id in -export-egress-guard-tasks", "value", part)
|
||||
return 2
|
||||
}
|
||||
taskIDs = append(taskIDs, id)
|
||||
}
|
||||
if strings.TrimSpace(tasksCSV) != "" && len(taskIDs) == 0 {
|
||||
slog.Error("[egress-guard-export] -export-egress-guard-tasks names no task")
|
||||
return 2
|
||||
}
|
||||
dsn, _, err := config.PostgresDSN()
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] database DSN unavailable", "err", err)
|
||||
return 1
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] open database failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
defer pg.Close()
|
||||
|
||||
scope, err := server.ExportEgressGuardScope(pg, taskIDs)
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] export failed, nothing written", "err", err)
|
||||
return 1
|
||||
}
|
||||
if err := scope.Render(out); err != nil {
|
||||
slog.Error("[egress-guard-export] write failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// runRotateSecrets atomically re-encrypts database secrets from oldPath to
|
||||
// newPath and increments auth.password_version to invalidate active sessions.
|
||||
func runRotateSecrets(oldPath, newPath string) int {
|
||||
|
||||
+7
-7
@@ -7,10 +7,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -80,12 +82,7 @@ func isGoRunDir(dir string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, seg := range strings.Split(filepath.ToSlash(dir), "/") {
|
||||
if seg == "go-build" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(strings.Split(filepath.ToSlash(dir), "/"), "go-build")
|
||||
}
|
||||
|
||||
// Path returns the config file path. Resolution order:
|
||||
@@ -230,6 +227,9 @@ func (d Database) buildDSN() string {
|
||||
if host == "" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
// A bare IPv6 address needs brackets in a URL authority; JoinHostPort adds
|
||||
// them, so drop any the operator already typed.
|
||||
host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]")
|
||||
port := d.Port
|
||||
if port == 0 {
|
||||
port = 5432
|
||||
@@ -240,7 +240,7 @@ func (d Database) buildDSN() string {
|
||||
}
|
||||
u := url.URL{
|
||||
Scheme: "postgres",
|
||||
Host: host + ":" + strconv.Itoa(port),
|
||||
Host: net.JoinHostPort(host, strconv.Itoa(port)),
|
||||
Path: "/" + d.DBName,
|
||||
}
|
||||
if d.User != "" {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func TestBuildDSNHost(t *testing.T) {
|
||||
cases := []struct{ host, want string }{
|
||||
{"", "127.0.0.1"},
|
||||
{"db.internal", "db.internal"},
|
||||
{"10.0.0.5", "10.0.0.5"},
|
||||
{"::1", "::1"},
|
||||
{"2001:db8::5", "2001:db8::5"},
|
||||
{"[2001:db8::5]", "2001:db8::5"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
dsn := Database{Host: tc.host, Port: 5433, User: "u", DBName: "artex"}.buildDSN()
|
||||
cfg, err := pgconn.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("host %q: DSN %q does not parse: %v", tc.host, dsn, err)
|
||||
}
|
||||
if cfg.Host != tc.want || cfg.Port != 5433 {
|
||||
t.Errorf("host %q: pgx reads host %q port %d from %q, want %q 5433", tc.host, cfg.Host, cfg.Port, dsn, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import "time"
|
||||
type AssetInterceptRule struct {
|
||||
ID int64 `json:"id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
|
||||
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|domain_suffix|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
|
||||
Pattern string `json:"pattern"`
|
||||
Note string `json:"note"`
|
||||
Builtin bool `json:"builtin"`
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
// CanonicalInterceptDomain is the comparison form of both a stored rule and a
|
||||
// target. Its output for valid names must not move, and it must stay lenient:
|
||||
// a malformed target still has to meet the rules (the built-in fuzzy ".gov.cn"
|
||||
// rule must still hit "x..gov.cn").
|
||||
func TestCanonicalInterceptDomainUnchanged(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"example.com", "example.com"},
|
||||
{"Example.COM.", "example.com"},
|
||||
{" www.Example.com ", "www.example.com"},
|
||||
{"bücher.example", "xn--bcher-kva.example"},
|
||||
{"XN--BCHER-KVA.example", "xn--bcher-kva.example"},
|
||||
{"example.com", "example.com"},
|
||||
{"faß.de", "xn--fa-hia.de"},
|
||||
{"_dmarc.Example.com", "_dmarc.example.com"},
|
||||
{".gov.cn", ".gov.cn"},
|
||||
{" .GOV.CN. ", ".gov.cn"},
|
||||
// Not valid rule patterns, but still canonicalized (not emptied) as
|
||||
// targets.
|
||||
{"a..example.com", "a..example.com"},
|
||||
{"example.com..", "example.com."},
|
||||
{"com", "com"},
|
||||
{"192.0.2.1", "192.0.2.1"},
|
||||
{"_bücher.example.com", "_bücher.example.com"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := CanonicalInterceptDomain(c.in); got != c.want {
|
||||
t.Errorf("CanonicalInterceptDomain(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
rules := []AssetInterceptRule{rule("fuzzy_domain", ".gov.cn", true)}
|
||||
if _, _, hit := MatchAssetInterceptRules(rules, []string{"x..gov.cn"}, nil, nil); !hit {
|
||||
t.Fatal(`fuzzy ".gov.cn" no longer hits the malformed target "x..gov.cn"`)
|
||||
}
|
||||
rules = []AssetInterceptRule{rule("exact_domain", "example.com", true)}
|
||||
if _, _, hit := MatchAssetInterceptRules(rules, []string{"EXAMPLE.com."}, nil, nil); !hit {
|
||||
t.Fatal(`exact "example.com" no longer hits "EXAMPLE.com."`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A database created before domain_suffix has the seven-kind CHECK constraints.
|
||||
// Migration 0026 widens them, idempotently, on both rule tables; an unknown
|
||||
// kind is still refused.
|
||||
func TestDomainSuffixKindMigration0026(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
const oldKinds = `('exact_domain','exact_ip','exact_url','fuzzy_domain','fuzzy_ip','fuzzy_url','cidr')`
|
||||
if _, err := d.Exec(`
|
||||
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
|
||||
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);
|
||||
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
|
||||
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := fs.ReadFile(migrationsFS(), "0026_asset_intercept_domain_suffix.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Whatever happens below, leave the current constraints in place.
|
||||
t.Cleanup(func() { _, _ = d.Exec(string(migration)) })
|
||||
|
||||
// Disabled, so the global rule cannot affect another test sharing the database.
|
||||
global := func(kind string) error {
|
||||
r, err := d.CreateAssetInterceptRule(kind, "example.com", "domain_suffix migration test", false)
|
||||
if err == nil {
|
||||
t.Cleanup(func() { _ = d.DeleteAssetInterceptRule(r.ID) })
|
||||
}
|
||||
return err
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("domain_suffix migration test", "goal", TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM tasks WHERE id=$1`, task.ID) })
|
||||
perTask := func(kind string) error {
|
||||
_, err := d.Assets().CreateTaskInterceptRule(task.ID, "allow", kind, "example.com", "", true)
|
||||
return err
|
||||
}
|
||||
|
||||
if global("domain_suffix") == nil || perTask("domain_suffix") == nil {
|
||||
t.Fatal("the old constraints accepted a domain_suffix rule")
|
||||
}
|
||||
for range 2 { // idempotent
|
||||
if _, err := d.Exec(string(migration)); err != nil {
|
||||
t.Fatalf("apply migration: %v", err)
|
||||
}
|
||||
}
|
||||
if err := global("domain_suffix"); err != nil {
|
||||
t.Fatalf("global domain_suffix rule refused after the migration: %v", err)
|
||||
}
|
||||
if err := perTask("domain_suffix"); err != nil {
|
||||
t.Fatalf("task domain_suffix rule refused after the migration: %v", err)
|
||||
}
|
||||
_, allow, err := d.Assets().TaskInterceptRulesSplit(task.ID)
|
||||
if err != nil || len(allow) != 1 || allow[0].Kind != "domain_suffix" {
|
||||
t.Fatalf("task allow rules = %+v, %v; want the domain_suffix rule", allow, err)
|
||||
}
|
||||
if global("domain_glob") == nil || perTask("domain_glob") == nil {
|
||||
t.Fatal("an unknown kind was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
// Malformed exact_domain / domain_suffix patterns are refused before they are
|
||||
// stored instead of being kept in a form no target ever has.
|
||||
func TestValidInterceptDomainRefuses(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
pattern string
|
||||
}{
|
||||
{"empty", ""},
|
||||
{"blank", " "},
|
||||
{"bare dot", "."},
|
||||
{"two trailing dots", "example.com.."},
|
||||
{"three trailing dots", "example.com..."},
|
||||
{"doubled dot", "a..example.com"},
|
||||
{"doubled dot before the TLD", "example..com"},
|
||||
{"leading dot", ".example.com"},
|
||||
{"space inside", "a b.example.com"},
|
||||
{"tab inside", "a\tb.example.com"},
|
||||
{"newline inside", "example.com\nevil.net"},
|
||||
{"NUL inside", "a\x00b.example.com"},
|
||||
{"DEL inside", "a\x7fb.example.com"},
|
||||
{"C1 control inside", "a\u0085b.example.com"},
|
||||
{"no-break space inside", "a b.example.com"},
|
||||
{"NUL at the end", "example.com\x00"},
|
||||
{"single label", "com"},
|
||||
{"single label with trailing dot", "COM."},
|
||||
{"single label host", "localhost"},
|
||||
{"IPv4 literal", "192.0.2.1"},
|
||||
{"IPv4 literal with trailing dot", "192.0.2.1."},
|
||||
{"IPv6 literal", "2001:db8::1"},
|
||||
{"IPv6 loopback", "::1"},
|
||||
{"IPv6 with zone", "fe80::1%eth0"},
|
||||
{"short IPv4 form", "127.1"},
|
||||
{"all-digit last label", "1.2.3.4.5"},
|
||||
{"underscore in a Unicode label", "_bücher.example.com"},
|
||||
{"punycode of an underscore label", "xn--_bcher-4ya.example.com"},
|
||||
{"invalid punycode label", "xn--zz.example.com"},
|
||||
{"URL with a scheme", "https://example.com"},
|
||||
{"port after the host", "example.com:443"},
|
||||
{"wildcard inside a label", "foo*.example.com"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got, err := ValidInterceptDomain(c.pattern); err == nil {
|
||||
t.Fatalf("ValidInterceptDomain(%q) = %q, want an error", c.pattern, got)
|
||||
}
|
||||
// As a domain_suffix, one leading dot is the suffix spelling.
|
||||
if c.pattern == ".example.com" {
|
||||
return
|
||||
}
|
||||
if got, err := ValidDomainSuffixPattern(c.pattern); err == nil {
|
||||
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want an error", c.pattern, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A valid domain keeps exactly the canonical form it had before the check:
|
||||
// ValidInterceptDomain returns what CanonicalInterceptDomain returns.
|
||||
func TestValidInterceptDomainKeepsValidDomains(t *testing.T) {
|
||||
cases := []struct {
|
||||
pattern string
|
||||
want string
|
||||
}{
|
||||
{"example.com", "example.com"},
|
||||
{"Example.COM", "example.com"},
|
||||
{"Example.COM.", "example.com"},
|
||||
{" example.com ", "example.com"},
|
||||
{"www.example.com", "www.example.com"},
|
||||
{"a.b.c.example.co.uk", "a.b.c.example.co.uk"},
|
||||
{"API.Example.Org.", "api.example.org"},
|
||||
{"bücher.example", "xn--bcher-kva.example"},
|
||||
{"BÜCHER.Example.", "xn--bcher-kva.example"},
|
||||
{"xn--bcher-kva.example", "xn--bcher-kva.example"},
|
||||
{"XN--BCHER-KVA.EXAMPLE", "xn--bcher-kva.example"},
|
||||
{"shop.xn--bcher-kva.example", "shop.xn--bcher-kva.example"},
|
||||
{"example.com", "example.com"},
|
||||
{"faß.de", "xn--fa-hia.de"},
|
||||
{"例え.テスト", "xn--r8jz45g.xn--zckzah"},
|
||||
{"_dmarc.example.com", "_dmarc.example.com"},
|
||||
{"_DMARC.Example.com.", "_dmarc.example.com"},
|
||||
{"my_host.internal", "my_host.internal"},
|
||||
{"rr1---sn-abc.googlevideo.com", "rr1---sn-abc.googlevideo.com"},
|
||||
{"ab--c.example.com", "ab--c.example.com"},
|
||||
{"-a.example.com", "-a.example.com"},
|
||||
{"1.example.com", "1.example.com"},
|
||||
{"123.example.com", "123.example.com"},
|
||||
{"example.123a", "example.123a"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.pattern, func(t *testing.T) {
|
||||
got, err := ValidInterceptDomain(c.pattern)
|
||||
if err != nil {
|
||||
t.Fatalf("ValidInterceptDomain(%q) refused: %v", c.pattern, err)
|
||||
}
|
||||
if got != c.want {
|
||||
t.Fatalf("ValidInterceptDomain(%q) = %q, want %q", c.pattern, got, c.want)
|
||||
}
|
||||
if canon := CanonicalInterceptDomain(c.pattern); canon != got {
|
||||
t.Fatalf("ValidInterceptDomain(%q) = %q but CanonicalInterceptDomain = %q", c.pattern, got, canon)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidDomainSuffixPattern(t *testing.T) {
|
||||
cases := []struct {
|
||||
pattern string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{"example.com", "example.com", false},
|
||||
{"*.Example.COM.", "example.com", false},
|
||||
{".example.com", "example.com", false},
|
||||
{"*.bücher.example", "xn--bcher-kva.example", false},
|
||||
{"*.com", "", true},
|
||||
{".com", "", true},
|
||||
{"*.example.com..", "", true},
|
||||
{"..example.com", "", true},
|
||||
{"*..example.com", "", true},
|
||||
{"*.a b.example.com", "", true},
|
||||
{"*.192.0.2.1", "", true},
|
||||
{"*.", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.pattern, func(t *testing.T) {
|
||||
got, err := ValidDomainSuffixPattern(c.pattern)
|
||||
if c.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want an error", c.pattern, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ValidDomainSuffixPattern(%q) refused: %v", c.pattern, err)
|
||||
}
|
||||
if got != c.want || got != DomainSuffixPattern(c.pattern) {
|
||||
t.Fatalf("ValidDomainSuffixPattern(%q) = %q, want %q (DomainSuffixPattern %q)", c.pattern, got, c.want, DomainSuffixPattern(c.pattern))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A fuzzy pattern is a substring: leading/trailing dots and single labels stay
|
||||
// valid, the built-in ".gov" rules included.
|
||||
func TestValidFuzzyDomainPattern(t *testing.T) {
|
||||
cases := []struct {
|
||||
pattern string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{".gov", ".gov", false},
|
||||
{".gov.cn", ".gov.cn", false},
|
||||
{" .GOV.CN. ", ".gov.cn", false},
|
||||
{"example", "example", false},
|
||||
{"EXAMPLE.COM.", "example.com", false},
|
||||
{"bücher", "xn--bcher-kva", false},
|
||||
{"", "", true},
|
||||
{".", "", true},
|
||||
{"a..b", "", true},
|
||||
{"..gov", "", true},
|
||||
{"example.com..", "", true},
|
||||
{"a。。example.com", "", true},
|
||||
{"example.com..", "", true},
|
||||
{"a b", "", true},
|
||||
{"gov\x00", "", true},
|
||||
{"ex\tample", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.pattern, func(t *testing.T) {
|
||||
got, err := ValidFuzzyDomainPattern(c.pattern)
|
||||
if c.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ValidFuzzyDomainPattern(%q) = %q, want an error", c.pattern, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ValidFuzzyDomainPattern(%q) refused: %v", c.pattern, err)
|
||||
}
|
||||
if got != c.want {
|
||||
t.Fatalf("ValidFuzzyDomainPattern(%q) = %q, want %q", c.pattern, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+153
-4
@@ -6,6 +6,7 @@ import (
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
@@ -20,15 +21,148 @@ import (
|
||||
// map, such as a fuzzy pattern with a leading dot, is compared as written).
|
||||
// Targets are canonicalized by the intercept layer with the same spelling, so a
|
||||
// rule stored as "Example.COM." must still match "example.com".
|
||||
//
|
||||
// It never refuses a name: the matcher calls it on targets too, and a malformed
|
||||
// target must still meet the rules. Patterns are checked before they are stored
|
||||
// by ValidInterceptDomain.
|
||||
//
|
||||
// The IDNA profile is idna.Lookup, the one intercept.NormalizeTarget uses. It
|
||||
// applies the STD3 rules, so a label with an underscore ("_dmarc.example.com")
|
||||
// is refused by the profile and the name is compared lower-cased as written.
|
||||
func CanonicalInterceptDomain(s string) string {
|
||||
d := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
|
||||
d, _ := canonicalInterceptDomain(s)
|
||||
return d
|
||||
}
|
||||
|
||||
// canonicalInterceptDomain is CanonicalInterceptDomain; mapped is false when
|
||||
// the IDNA profile refused the name and it was kept as written.
|
||||
func canonicalInterceptDomain(s string) (d string, mapped bool) {
|
||||
d = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
|
||||
if d == "" {
|
||||
return ""
|
||||
return "", false
|
||||
}
|
||||
if ascii, err := idna.Lookup.ToASCII(d); err == nil && ascii != "" {
|
||||
return ascii
|
||||
return ascii, true
|
||||
}
|
||||
return d
|
||||
return d, false
|
||||
}
|
||||
|
||||
// ValidInterceptDomain checks an exact_domain pattern (and the domain of a
|
||||
// domain_suffix pattern) before it is stored, and returns the canonical form,
|
||||
// which is always CanonicalInterceptDomain's. It refuses:
|
||||
// - whitespace or a control character inside the name;
|
||||
// - an empty label: a leading dot, "a..example.com", or more than one
|
||||
// trailing dot ("example.com.." is refused, not shortened: one trailing
|
||||
// dot is the DNS root, a second one is a typo, and the intercept layer
|
||||
// drops only one);
|
||||
// - a single label ("com"): it would match nothing as an exact_domain, and
|
||||
// as a domain_suffix it would cover a whole TLD, so it is refused;
|
||||
// - an IP literal, or a name whose last label is all digits: IPs are
|
||||
// exact_ip or cidr rules, and the intercept layer reads such a host as
|
||||
// an address;
|
||||
// - a URL or wildcard character ("*", "/" or ":"): exact_domain and
|
||||
// domain_suffix take a host name, not a URL or a pattern, and such a rule
|
||||
// would be stored and never match;
|
||||
// - a name with non-ASCII characters, or an "xn--" label, that the IDNA
|
||||
// profile refuses (for example an underscore in an internationalized
|
||||
// label): such a name has no single canonical spelling, so a rule written
|
||||
// in Unicode would miss the punycode target and the reverse.
|
||||
//
|
||||
// An ASCII name without an "xn--" label that the profile refuses (an
|
||||
// underscore, a leading or trailing hyphen, "--" in the third and fourth
|
||||
// positions) is kept lower-cased as written, as before: lower-casing is all the
|
||||
// profile would do to it, so the rule and the target spell it the same way.
|
||||
func ValidInterceptDomain(s string) (string, error) {
|
||||
for _, r := range strings.TrimSpace(s) {
|
||||
if unicode.IsSpace(r) || unicode.IsControl(r) {
|
||||
return "", fmt.Errorf("contains whitespace or a control character")
|
||||
}
|
||||
}
|
||||
d, mapped := canonicalInterceptDomain(s)
|
||||
if d == "" {
|
||||
return "", fmt.Errorf("empty domain")
|
||||
}
|
||||
if _, err := netip.ParseAddr(d); err == nil {
|
||||
return "", fmt.Errorf("is an IP address (use exact_ip or cidr)")
|
||||
}
|
||||
labels := strings.Split(d, ".")
|
||||
for _, l := range labels {
|
||||
if l == "" {
|
||||
return "", fmt.Errorf("has an empty label (leading, doubled or extra trailing dot)")
|
||||
}
|
||||
}
|
||||
if len(labels) < 2 {
|
||||
return "", fmt.Errorf("is a single label, not a domain (e.g. example.com)")
|
||||
}
|
||||
if strings.Trim(labels[len(labels)-1], "0123456789") == "" {
|
||||
return "", fmt.Errorf("looks like an IP address (use exact_ip or cidr)")
|
||||
}
|
||||
if strings.ContainsAny(d, "*/:") {
|
||||
return "", fmt.Errorf("contains a URL or wildcard character (*, / or :)")
|
||||
}
|
||||
if !mapped {
|
||||
for _, r := range d {
|
||||
if r > unicode.MaxASCII {
|
||||
return "", fmt.Errorf("is not a valid internationalized domain name")
|
||||
}
|
||||
}
|
||||
for _, l := range labels {
|
||||
if strings.HasPrefix(l, "xn--") {
|
||||
return "", fmt.Errorf("has an invalid punycode label: %s", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// ValidFuzzyDomainPattern checks a fuzzy_domain pattern before it is stored and
|
||||
// returns its canonical form. A fuzzy pattern is a substring, so a leading or
|
||||
// trailing dot and a single label stay valid (".gov.cn", "example"); whitespace,
|
||||
// control characters and an empty label inside it ("a..b") are refused.
|
||||
func ValidFuzzyDomainPattern(s string) (string, error) {
|
||||
t := strings.TrimSpace(s)
|
||||
for _, r := range t {
|
||||
if unicode.IsSpace(r) || unicode.IsControl(r) {
|
||||
return "", fmt.Errorf("contains whitespace or a control character")
|
||||
}
|
||||
}
|
||||
if strings.Contains(t, "..") {
|
||||
return "", fmt.Errorf("has an empty label (doubled dot)")
|
||||
}
|
||||
d := CanonicalInterceptDomain(t)
|
||||
if d == "" {
|
||||
return "", fmt.Errorf("empty domain")
|
||||
}
|
||||
// Canonicalisation maps the ideographic and fullwidth dots to ".", so a
|
||||
// fullwidth "。。" only becomes a doubled dot here. Check the canonical
|
||||
// form too, or such a pattern is stored as "a..example.com".
|
||||
if strings.Contains(d, "..") {
|
||||
return "", fmt.Errorf("has an empty label (doubled dot)")
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// DomainSuffixPattern canonicalizes a domain_suffix pattern: the domain itself,
|
||||
// with one leading "*." or "." dropped, so "*.Example.com" and ".example.com"
|
||||
// both mean example.com and its subdomains. Empty when nothing is left.
|
||||
func DomainSuffixPattern(s string) string {
|
||||
return CanonicalInterceptDomain(domainSuffixDomain(s))
|
||||
}
|
||||
|
||||
// ValidDomainSuffixPattern is DomainSuffixPattern for a pattern about to be
|
||||
// stored: the domain left once the prefix is dropped must pass
|
||||
// ValidInterceptDomain.
|
||||
func ValidDomainSuffixPattern(s string) (string, error) {
|
||||
return ValidInterceptDomain(domainSuffixDomain(s))
|
||||
}
|
||||
|
||||
// domainSuffixDomain drops one leading "*." or "." from a domain_suffix pattern.
|
||||
func domainSuffixDomain(s string) string {
|
||||
d := strings.TrimSpace(s)
|
||||
if rest, ok := strings.CutPrefix(d, "*."); ok {
|
||||
return rest
|
||||
}
|
||||
return strings.TrimPrefix(d, ".")
|
||||
}
|
||||
|
||||
// CanonicalInterceptIP canonicalizes one side of an IP comparison: IPv4-mapped
|
||||
@@ -52,6 +186,8 @@ func AssetInterceptKindLabel(kind string) string {
|
||||
return "IP (exact)"
|
||||
case "exact_url":
|
||||
return "URL (exact)"
|
||||
case "domain_suffix":
|
||||
return "Domain (suffix)"
|
||||
case "fuzzy_domain":
|
||||
return "Domain (fuzzy)"
|
||||
case "fuzzy_ip":
|
||||
@@ -119,6 +255,19 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
|
||||
return u, true
|
||||
}
|
||||
}
|
||||
case "domain_suffix":
|
||||
// The domain and its subdomains, on a label boundary: "example.com"
|
||||
// matches "a.example.com" but not "a.example.com.evil.net" or
|
||||
// "badexample.com", which fuzzy_domain's substring match lets through.
|
||||
want := DomainSuffixPattern(p)
|
||||
if want == "" {
|
||||
return "", false
|
||||
}
|
||||
for _, d := range domains {
|
||||
if cd := CanonicalInterceptDomain(d); cd == want || strings.HasSuffix(cd, "."+want) {
|
||||
return d, true
|
||||
}
|
||||
}
|
||||
case "fuzzy_domain":
|
||||
lp := CanonicalInterceptDomain(p)
|
||||
if lp == "" {
|
||||
|
||||
@@ -44,6 +44,29 @@ func TestMatchAssetInterceptRules(t *testing.T) {
|
||||
[]string{"xn--bcher-kva.example"}, nil, nil, true, "xn--bcher-kva.example"},
|
||||
{"fuzzy domain uppercase trailing-dot rule", []AssetInterceptRule{rule("fuzzy_domain", "EXAMPLE.COM.", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix hits the domain itself", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"EXAMPLE.com."}, nil, nil, true, "EXAMPLE.com."},
|
||||
{"domain suffix hits a subdomain", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.b.example.com"}, nil, nil, true, "a.b.example.com"},
|
||||
{"domain suffix wildcard spelling", []AssetInterceptRule{rule("domain_suffix", "*.Example.COM.", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix leading-dot spelling", []AssetInterceptRule{rule("domain_suffix", ".example.com", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix IDNA rule", []AssetInterceptRule{rule("domain_suffix", "bücher.example", true)},
|
||||
[]string{"shop.xn--bcher-kva.example"}, nil, nil, true, "shop.xn--bcher-kva.example"},
|
||||
// Where fuzzy_domain's substring match hits, a label-boundary suffix must not.
|
||||
{"domain suffix misses a name that only contains it", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.example.com.evil.net"}, nil, nil, false, ""},
|
||||
{"domain suffix misses a longer last label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.example.community"}, nil, nil, false, ""},
|
||||
{"domain suffix misses a longer first label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"badexample.com"}, nil, nil, false, ""},
|
||||
{"domain suffix misses the parent domain", []AssetInterceptRule{rule("domain_suffix", "api.example.com", true)},
|
||||
[]string{"example.com"}, nil, nil, false, ""},
|
||||
{"fuzzy domain hits a name that only contains it", []AssetInterceptRule{rule("fuzzy_domain", ".example.com", true)},
|
||||
[]string{"a.example.com.evil.net"}, nil, nil, true, "a.example.com.evil.net"},
|
||||
{"empty domain suffix no hit", []AssetInterceptRule{rule("domain_suffix", "*.", true)},
|
||||
[]string{"example.com"}, nil, nil, false, ""},
|
||||
{"fuzzy IP uppercase rule", []AssetInterceptRule{rule("fuzzy_ip", "FE80::", true)},
|
||||
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
|
||||
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
|
||||
@@ -117,6 +140,20 @@ func TestEvaluateAssetGate(t *testing.T) {
|
||||
); d.Allowed {
|
||||
t.Fatal("interception should take priority over allow")
|
||||
}
|
||||
|
||||
// 7. A domain_suffix allow-list admits the site and refuses look-alikes
|
||||
// that fuzzy_domain would admit.
|
||||
suffix := []AssetInterceptRule{rule("domain_suffix", "example.com", true)}
|
||||
for host, want := range map[string]bool{
|
||||
"example.com": true,
|
||||
"api.example.com": true,
|
||||
"api.example.com.evil.net": false,
|
||||
"api.example.community": false,
|
||||
} {
|
||||
if d := EvaluateAssetGate(nil, suffix, []string{host}, nil, nil); d.Allowed != want {
|
||||
t.Fatalf("domain_suffix allow-list: %s allowed=%v, want %v", host, d.Allowed, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssetInterceptCandidates(t *testing.T) {
|
||||
|
||||
+1
-1
@@ -506,7 +506,7 @@ func (s *AssetStore) UpsertSubdomain(req UpsertSubdomainReq) (id int64, err erro
|
||||
var ipStr string // first valid IP, used for the subdomain row itself
|
||||
if req.RecordType == "A" || req.RecordType == "AAAA" {
|
||||
for _, rv := range req.RecordValue {
|
||||
for _, part := range strings.Split(rv, ",") {
|
||||
for part := range strings.SplitSeq(rv, ",") {
|
||||
candidate := strings.TrimSpace(part)
|
||||
if candidate == "" || net.ParseIP(candidate) == nil {
|
||||
continue
|
||||
|
||||
+3
-3
@@ -649,7 +649,7 @@ func TestQueryByTaskPaging(t *testing.T) {
|
||||
|
||||
const taskID = int64(99998)
|
||||
const n = 60
|
||||
for i := 0; i < n; i++ {
|
||||
for i := range n {
|
||||
id, err := av2.UpsertRootDomain(UpsertRootDomainReq{
|
||||
Domain: fmt.Sprintf("paging-%02d.querybytask.test", i),
|
||||
TaskID: taskID,
|
||||
@@ -760,7 +760,7 @@ func TestQueryByCompanyPaging(t *testing.T) {
|
||||
defer d.Exec(`DELETE FROM assets WHERE root_domain = 'qbc-paging.io'`)
|
||||
|
||||
const n = 60
|
||||
for i := 0; i < n; i++ {
|
||||
for i := range n {
|
||||
if _, err := av2.UpsertSubdomain(UpsertSubdomainReq{
|
||||
Domain: fmt.Sprintf("paging-%02d.qbc-paging.io", i),
|
||||
}); err != nil {
|
||||
@@ -1060,7 +1060,7 @@ func TestAssetPaginationUsesStableIDTieBreaker(t *testing.T) {
|
||||
marker := fmt.Sprintf("stable-page-%d", stamp)
|
||||
sharedSeen := time.Date(2026, time.August, 21, 9, 0, 0, 0, time.UTC)
|
||||
ids := make([]int64, 0, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
var id int64
|
||||
domain := fmt.Sprintf("%s-%d.invalid", marker, i)
|
||||
if err := d.QueryRow(`INSERT INTO assets(type,domain,root_domain,task_ids,last_seen)
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ var npxMetaFlags = map[string]bool{
|
||||
}
|
||||
|
||||
func playwrightMCPPackageIndex(args []string) (int, bool) {
|
||||
for i := 0; i < len(args); i++ {
|
||||
for i := range args {
|
||||
a := args[i]
|
||||
if npxMetaFlags[a] {
|
||||
continue
|
||||
|
||||
@@ -63,3 +63,167 @@ RETURNING approved_by_operator`, companyID).Scan(&fresh); err != nil {
|
||||
t.Fatal("a row written after the migration defaulted to approved_by_operator=true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpawnInheritsFullyApprovedCompany (#830, #841): a task created by the
|
||||
// LLM (CompanyScopeByAgent=true) stamps the company link operator-approved and
|
||||
// freezes the egress grant for a company whose entire scope inventory the
|
||||
// operator approved - but only within the caller's trust boundary (review
|
||||
// 6154399166): the caller task must itself hold an operator-approved link to
|
||||
// that company. A company holding any unapproved row, one with no scope rows
|
||||
// at all, and one the caller cannot reach stay coverage-only, so
|
||||
// add_company_scope and invented ids still grant nothing without a fresh
|
||||
// operator decision.
|
||||
func TestSpawnInheritsFullyApprovedCompany(t *testing.T) {
|
||||
dsn := scratchDSN(t, "spawn_inherit_830")
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("initial Open: %v", err)
|
||||
}
|
||||
defer d.Close()
|
||||
mk := func(name string) int64 {
|
||||
var id int64
|
||||
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ($1, lower($1)) RETURNING id`, name).Scan(&id); err != nil {
|
||||
t.Fatalf("insert company %s: %v", name, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
exec := func(stmt string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := d.Exec(stmt, args...); err != nil {
|
||||
t.Fatalf("seed (%s): %v", stmt, err)
|
||||
}
|
||||
}
|
||||
fullID := mk("SpawnFull Co")
|
||||
exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'full830.test', 'full830.test', TRUE)`, fullID)
|
||||
exec(`INSERT INTO company_scope(company_id, kind, net, raw, approved_by_operator) VALUES ($1, 'ip', '198.51.100.9/32', '198.51.100.9', TRUE)`, fullID)
|
||||
halfID := mk("SpawnHalf Co")
|
||||
exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'half830.test', 'half830.test', TRUE)`, halfID)
|
||||
exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'agent830.test', 'agent830.test', FALSE)`, halfID)
|
||||
emptyID := mk("SpawnEmpty Co")
|
||||
// A second fully approved company the caller cannot reach: inheritance must
|
||||
// stop at the trust boundary (#841, review 6154399166).
|
||||
otherID := mk("SpawnOther Co")
|
||||
exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'other841.test', 'other841.test', TRUE)`, otherID)
|
||||
// Operator caller: linked, approved, to the full company only.
|
||||
caller, err := d.CreateTaskWithOptions("caller841", "goal", TaskCreateOptions{
|
||||
CompanyIDs: []int64{fullID},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions caller: %v", err)
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("spawn830", "goal", TaskCreateOptions{
|
||||
CompanyIDs: []int64{fullID, halfID, emptyID, otherID},
|
||||
CompanyScopeByAgent: true,
|
||||
CompanyScopeCallerID: caller.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
want := map[int64]bool{fullID: true, halfID: false, emptyID: false, otherID: false}
|
||||
rows, err := d.Query(`SELECT company_id, approved_by_operator, source FROM task_scope WHERE task_id=$1 AND kind='company'`, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("read task_scope: %v", err)
|
||||
}
|
||||
seen := map[int64]bool{}
|
||||
for rows.Next() {
|
||||
var cid int64
|
||||
var approved bool
|
||||
var source string
|
||||
if err := rows.Scan(&cid, &approved, &source); err != nil {
|
||||
t.Fatalf("scan task_scope: %v", err)
|
||||
}
|
||||
seen[cid] = true
|
||||
if approved != want[cid] {
|
||||
t.Errorf("company %d: approved_by_operator=%v, want %v", cid, approved, want[cid])
|
||||
}
|
||||
if source != "agent" {
|
||||
t.Errorf("company %d: source=%q, want agent (provenance must survive inheritance)", cid, source)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for cid := range want {
|
||||
if !seen[cid] {
|
||||
t.Errorf("company %d has no task_scope link", cid)
|
||||
}
|
||||
}
|
||||
// The snapshot holds exactly the inherited company's approved rows: the
|
||||
// half company's approved row must not be frozen while its link is
|
||||
// unapproved, and nothing comes from the empty company.
|
||||
grants, err := d.CompanyEgressForTask(task.ID, fullID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompanyEgressForTask: %v", err)
|
||||
}
|
||||
if len(grants) != 2 {
|
||||
t.Fatalf("full company egress %v, want the approved domain and IP", grants)
|
||||
}
|
||||
for _, g := range grants {
|
||||
if !(g.Kind == "domain" && g.Value == "full830.test") && !(g.Kind == "cidr" && (g.Value == "198.51.100.9/32" || g.Value == "198.51.100.9")) {
|
||||
t.Errorf("unexpected grant %+v", g)
|
||||
}
|
||||
}
|
||||
if halfGrants, err := d.CompanyEgressForTask(task.ID, halfID); err != nil || len(halfGrants) != 0 {
|
||||
t.Errorf("half company egress %v (%v), want none", halfGrants, err)
|
||||
}
|
||||
// The unreachable-but-fully-approved company crossed no trust boundary: it
|
||||
// froze nothing.
|
||||
if otherGrants, err := d.CompanyEgressForTask(task.ID, otherID); err != nil || len(otherGrants) != 0 {
|
||||
t.Errorf("unreachable company egress %v (%v), want none", otherGrants, err)
|
||||
}
|
||||
if _, err := d.Exec(`DELETE FROM task_scope_egress WHERE task_id=$1 AND company_id IS NULL`, task.ID); err != nil {
|
||||
t.Fatalf("cleanup probe: %v", err)
|
||||
}
|
||||
var stray int
|
||||
if err := d.QueryRow(`SELECT count(*) FROM task_scope_egress WHERE task_id=$1`, task.ID).Scan(&stray); err != nil {
|
||||
t.Fatalf("count egress: %v", err)
|
||||
}
|
||||
if stray != 2 {
|
||||
t.Errorf("task holds %d egress rows, want only the two inherited ones", stray)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpawnWithoutTaskCallerDoesNotAutoApprove (review 6154399166): a
|
||||
// CompanyScopeByAgent spawn with no task caller - a chat session or direct API
|
||||
// use - must not silently auto-approve even a fully operator-approved company.
|
||||
// The trust boundary between caller and child has nothing to inherit through,
|
||||
// so the link stays coverage-only until the operator confirms it on the task
|
||||
// scope; the child starts with an empty allowlist, as before #830.
|
||||
func TestSpawnWithoutTaskCallerDoesNotAutoApprove(t *testing.T) {
|
||||
dsn := scratchDSN(t, "spawn_nocaller_841")
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("initial Open: %v", err)
|
||||
}
|
||||
defer d.Close()
|
||||
var fullID int64
|
||||
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('NoCaller Co', 'nocaller co') RETURNING id`).Scan(&fullID); err != nil {
|
||||
t.Fatalf("insert company: %v", err)
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'nocaller841.test', 'nocaller841.test', TRUE)`, fullID); err != nil {
|
||||
t.Fatalf("seed approved company_scope row: %v", err)
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("nocaller841", "goal", TaskCreateOptions{
|
||||
CompanyIDs: []int64{fullID},
|
||||
CompanyScopeByAgent: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
var approved bool
|
||||
var source string
|
||||
if err := d.QueryRow(`SELECT approved_by_operator, source FROM task_scope WHERE task_id=$1 AND kind='company' AND company_id=$2`, task.ID, fullID).Scan(&approved, &source); err != nil {
|
||||
t.Fatalf("read task_scope link: %v", err)
|
||||
}
|
||||
if approved {
|
||||
t.Error("spawn with no task caller auto-approved the company link; want coverage-only pending operator confirmation")
|
||||
}
|
||||
if source != "agent" {
|
||||
t.Errorf("source=%q, want agent (provenance must survive either way)", source)
|
||||
}
|
||||
grants, err := d.CompanyEgressForTask(task.ID, fullID)
|
||||
if err != nil {
|
||||
t.Fatalf("CompanyEgressForTask: %v", err)
|
||||
}
|
||||
if len(grants) != 0 {
|
||||
t.Errorf("no-caller spawn inherited grants %v, want none", grants)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -276,7 +276,7 @@ func (d *DB) DeleteProfileContext(ctx context.Context, id int64) error {
|
||||
)
|
||||
ctx, cancel := context.WithTimeout(ctx, maxDuration)
|
||||
defer cancel()
|
||||
for attempt := 0; attempt < maxAttempts; attempt++ {
|
||||
for range maxAttempts {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -190,7 +190,7 @@ func (s *ExplorationStore) DigestMembers(digestID int64) ([]int64, error) {
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
slices.Sort(ids)
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"maps"
|
||||
"sort"
|
||||
)
|
||||
|
||||
@@ -207,9 +208,7 @@ func (s *ExplorationStore) FindingIntentsWithSources() (map[int64]int64, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for findingID, intentID := range items {
|
||||
out[findingID] = intentID
|
||||
}
|
||||
maps.Copy(out, items)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ func TestTokenStatsBySessionUsesCompleteIntentHistory(t *testing.T) {
|
||||
// More than ActivityPage's default limit proves this aggregate reads the
|
||||
// persisted history directly instead of summing the currently loaded page.
|
||||
const completedRuns = 205
|
||||
for i := 0; i < completedRuns; i++ {
|
||||
for i := range completedRuns {
|
||||
appendResult(&intentID, fmt.Sprintf("work#%d", i%3+1), 1, 2, 3, 4)
|
||||
}
|
||||
|
||||
|
||||
@@ -416,7 +416,7 @@ func isIPLiteral(host string) bool {
|
||||
if host == "" {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(host, ".") {
|
||||
for part := range strings.SplitSeq(host, ".") {
|
||||
if part == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -635,10 +635,8 @@ ORDER BY b.position, b.id`, findingID)
|
||||
}
|
||||
|
||||
hostMatchesFinding := func(snapHost string) bool {
|
||||
for _, h := range assetHosts {
|
||||
if snapHost == h {
|
||||
return true
|
||||
}
|
||||
if slices.Contains(assetHosts, snapHost) {
|
||||
return true
|
||||
}
|
||||
for _, rd := range assetRootDomains {
|
||||
if snapHost == rd || strings.HasSuffix(snapHost, "."+rd) {
|
||||
|
||||
+1
-1
@@ -426,7 +426,7 @@ func TestListFindingsPageUsesStableIDTieBreaker(t *testing.T) {
|
||||
vc := fmt.Sprintf("__test_finding_stable_page_%d__", time.Now().UnixNano())
|
||||
defer d.Exec(`DELETE FROM findings WHERE vulnclass=$1`, vc)
|
||||
ids := make([]int64, 0, 7)
|
||||
for i := 0; i < 7; i++ {
|
||||
for i := range 7 {
|
||||
id, addErr := d.AddFinding(0, 0, vc, "", SeverityHigh, fmt.Sprintf("finding %d", i), "", "test", nil)
|
||||
if addErr != nil {
|
||||
t.Fatalf("AddFinding[%d]: %v", i, addErr)
|
||||
|
||||
@@ -293,7 +293,7 @@ func TestIntentClaimTakeoverRacesHeartbeatAtomically(t *testing.T) {
|
||||
token := claimIntentToken(t, a, id, "work#1")
|
||||
|
||||
var renewed, takenOver int
|
||||
for round := 0; round < 40; round++ {
|
||||
for round := range 40 {
|
||||
ageClaimHeartbeat(t, d, id, IntentClaimTTL+time.Second)
|
||||
var heartbeatErr, resetErr error
|
||||
var reclaimed int64
|
||||
|
||||
@@ -33,9 +33,7 @@ func TestCompareAndSetIntentStateAllowsSingleWinner(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range contenders {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
wg.Go(func() {
|
||||
<-start
|
||||
changed, transitionErr := store.CompareAndSetIntentState(intentID, "running", "paused")
|
||||
if transitionErr != nil {
|
||||
@@ -45,7 +43,7 @@ func TestCompareAndSetIntentStateAllowsSingleWinner(t *testing.T) {
|
||||
if changed {
|
||||
winners.Add(1)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package db
|
||||
|
||||
import "context"
|
||||
|
||||
// InterceptPendingSummary is the small snapshot needed by task and session badges.
|
||||
// It deliberately excludes request bodies, audit context and settled history.
|
||||
type InterceptPendingSummary struct {
|
||||
Total int64 `json:"total"`
|
||||
Agents []InterceptPendingAgent `json:"agents"`
|
||||
}
|
||||
|
||||
type InterceptPendingAgent struct {
|
||||
AgentName string `json:"agent_name"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
func (d *DB) TaskInterceptPendingSummary(ctx context.Context, taskID string) (InterceptPendingSummary, error) {
|
||||
result := InterceptPendingSummary{Agents: []InterceptPendingAgent{}}
|
||||
rows, err := d.QueryContext(ctx, `
|
||||
SELECT agent_name, COUNT(*)
|
||||
FROM intercept_pending
|
||||
WHERE task_id=$1 AND status='pending'
|
||||
GROUP BY agent_name
|
||||
ORDER BY agent_name`, taskID)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var agent InterceptPendingAgent
|
||||
if err := rows.Scan(&agent.AgentName, &agent.Count); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Total += agent.Count
|
||||
result.Agents = append(result.Agents, agent)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTaskInterceptPendingSummary(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
task := "pending-summary-" + t.Name()
|
||||
t.Cleanup(func() { _, _ = d.Exec("DELETE FROM intercept_pending WHERE task_id IN ($1,$2)", task, task+"-other") })
|
||||
for _, fixture := range []struct {
|
||||
task, agent, status string
|
||||
count int
|
||||
}{
|
||||
{task, "mainagent", "pending", 3},
|
||||
{task, "planner", "pending", 1},
|
||||
{task, "work#2 · #123", "pending", 120},
|
||||
{task, "mainagent", "allowed", 1000},
|
||||
{task, "planner", "denied", 2},
|
||||
{task, "planner", "timeout", 2},
|
||||
{task + "-other", "planner", "pending", 9},
|
||||
} {
|
||||
_, err := d.Exec(`INSERT INTO intercept_pending(task_id,agent_name,tool_name,tool_input,status,reason)
|
||||
SELECT $1,$2,'Bash',jsonb_build_object('command',repeat('private-payload',300)),$3,'private reason'
|
||||
FROM generate_series(1,$4::int)`, fixture.task, fixture.agent, fixture.status, fixture.count)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := d.TaskInterceptPendingSummary(context.Background(), task)
|
||||
if err != nil || got.Total != 124 || len(got.Agents) != 3 {
|
||||
t.Fatalf("summary = %+v, err = %v", got, err)
|
||||
}
|
||||
want := map[string]int64{"mainagent": 3, "planner": 1, "work#2 · #123": 120}
|
||||
for _, agent := range got.Agents {
|
||||
if want[agent.AgentName] != agent.Count {
|
||||
t.Fatalf("wrong agent count: %+v", agent)
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(got)
|
||||
if err != nil || len(raw) > 300 || strings.Contains(string(raw), "private") {
|
||||
t.Fatalf("summary includes details: bytes=%d err=%v", len(raw), err)
|
||||
}
|
||||
if _, err := d.Exec("UPDATE intercept_pending SET status='allowed' WHERE task_id=$1 AND status='pending'", task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.TaskInterceptPendingSummary(context.Background(), task)
|
||||
if err != nil || got.Total != 0 || got.Agents == nil || len(got.Agents) != 0 {
|
||||
t.Fatalf("settled summary = %+v, err = %v", got, err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := d.TaskInterceptPendingSummary(ctx, task); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("canceled query: %v", err)
|
||||
}
|
||||
var index string
|
||||
if err := d.QueryRow("SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND indexname='idx_intercept_pending_task_agent'").Scan(&index); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(index, "(task_id, agent_name)") || !strings.Contains(index, "WHERE (status = 'pending'") {
|
||||
t.Fatalf("missing covering partial index: %s", index)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@ func TestRenderLessonsDataNotInstructions(t *testing.T) {
|
||||
if !strings.Contains(block, "[positive, 2 evidence]") || !strings.Contains(block, "[negative, 1 evidence]") {
|
||||
t.Fatalf("missing kind/support labels:\n%s", block)
|
||||
}
|
||||
for _, line := range strings.Split(block, "\n") {
|
||||
for line := range strings.SplitSeq(block, "\n") {
|
||||
if strings.Contains(line, "\x00") {
|
||||
t.Fatalf("control character survived: %q", line)
|
||||
}
|
||||
|
||||
+1
-4
@@ -383,10 +383,7 @@ func applyCostEur(d *DB, out []ProfileUsage) error {
|
||||
// fresh share is therefore input minus cache reads minus cache writes;
|
||||
// charging either subset at full input price as well bills it twice.
|
||||
// Clamped at zero for gateways that report the buckets disjointly.
|
||||
fresh := out[i].InputTokens - out[i].CacheReadTokens - out[i].CacheWriteTokens
|
||||
if fresh < 0 {
|
||||
fresh = 0
|
||||
}
|
||||
fresh := max(out[i].InputTokens-out[i].CacheReadTokens-out[i].CacheWriteTokens, 0)
|
||||
cost := float64(fresh)/1e6*pr.in + float64(out[i].OutputTokens)/1e6*pr.outp +
|
||||
float64(out[i].CacheReadTokens)/1e6*pr.cr + float64(out[i].CacheWriteTokens)/1e6*pr.cw
|
||||
c := cost
|
||||
|
||||
+2
-3
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -86,9 +87,7 @@ func withEmbedded(t *testing.T, extra fstest.MapFS) fstest.MapFS {
|
||||
}
|
||||
out[name] = &fstest.MapFile{Data: content}
|
||||
}
|
||||
for name, f := range extra {
|
||||
out[name] = f
|
||||
}
|
||||
maps.Copy(out, extra)
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- domain_suffix: a domain and its subdomains, matched on a label boundary
|
||||
-- (example.com, a.example.com; not a.example.com.other.net). Existing rules
|
||||
-- keep their kind; the CHECK constraints only gain the new value.
|
||||
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
|
||||
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check
|
||||
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
|
||||
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
|
||||
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check
|
||||
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Task/session badges aggregate only unresolved approvals, without loading history.
|
||||
-- Covers both the task filter and agent grouping; settled rows never enter this index.
|
||||
CREATE INDEX IF NOT EXISTS idx_intercept_pending_task_agent
|
||||
ON intercept_pending (task_id, agent_name) WHERE status = 'pending';
|
||||
+2
-6
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -574,12 +575,7 @@ var GoalInvalidatingFindingStatuses = []string{
|
||||
// goal met.
|
||||
func FindingStatusInvalidatesGoal(status string) bool {
|
||||
s := strings.ToLower(strings.TrimSpace(status))
|
||||
for _, inv := range GoalInvalidatingFindingStatuses {
|
||||
if s == inv {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(GoalInvalidatingFindingStatuses, s)
|
||||
}
|
||||
|
||||
// reopenGoalsProvedByNodeTx resets any goal node proved by nodeID back to open
|
||||
|
||||
@@ -342,7 +342,7 @@ func TestDigestBatchDueAndStableBatchID(t *testing.T) {
|
||||
d := notifyTestDB(t)
|
||||
ctx := context.Background()
|
||||
ch := newTestChannel(t, d, notify.KindDingTalk, NotifyModeDigest, `{}`)
|
||||
for i := 0; i < 3; i++ {
|
||||
for i := range 3 {
|
||||
addTestEvent(t, d, notify.EventFindingCreated, int64(6000+i), notify.Snapshot{Severity: "high"})
|
||||
}
|
||||
if _, _, err := d.FanOutPendingEvents(ctx, 100); err != nil {
|
||||
@@ -483,7 +483,7 @@ func TestListNotificationDeliveriesPagingAndFilter(t *testing.T) {
|
||||
d := notifyTestDB(t)
|
||||
ctx := context.Background()
|
||||
ch := newTestChannel(t, d, notify.KindDingTalk, NotifyModeRealtime, `{}`)
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
addTestEvent(t, d, notify.EventFindingCreated, int64(8000+i), notify.Snapshot{Severity: "high", Name: "paging test"})
|
||||
}
|
||||
if _, _, err := d.FanOutPendingEvents(ctx, 100); err != nil {
|
||||
@@ -862,7 +862,7 @@ func TestClaimDigestBatchHonorsCallerLimit(t *testing.T) {
|
||||
d := notifyTestDB(t)
|
||||
ctx := context.Background()
|
||||
ch := newTestChannel(t, d, notify.KindDingTalk, NotifyModeDigest, `{}`)
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := range 10 {
|
||||
addTestEvent(t, d, notify.EventFindingCreated, int64(7000+i), notify.Snapshot{Severity: "high"})
|
||||
}
|
||||
if _, _, err := d.FanOutPendingEvents(ctx, 100); err != nil {
|
||||
|
||||
+4
-3
@@ -1374,8 +1374,9 @@ ALTER TABLE side_question_requests ADD COLUMN IF NOT EXISTS context_info JSONB N
|
||||
-- Independent from §K command interception (intercept_rules): intercept_rules matches tool names/input text,
|
||||
-- while this table matches "target assets" — exact/fuzzy domains, IPs, URLs, and CIDR ranges.
|
||||
-- Rules only; the concrete match/intercept logic is implemented elsewhere.
|
||||
-- Seven kinds:
|
||||
-- Eight kinds:
|
||||
-- exact_domain / exact_ip / exact_url —— exact match
|
||||
-- domain_suffix —— a domain and its subdomains (label boundary)
|
||||
-- fuzzy_domain / fuzzy_ip / fuzzy_url —— fuzzy match
|
||||
-- cidr —— CIDR range
|
||||
-- =====================================================================
|
||||
@@ -1383,7 +1384,7 @@ CREATE TABLE IF NOT EXISTS asset_intercept_rules (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
kind TEXT NOT NULL CHECK (kind IN (
|
||||
'exact_domain', 'exact_ip', 'exact_url',
|
||||
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
|
||||
'cidr')),
|
||||
pattern TEXT NOT NULL,
|
||||
@@ -1412,7 +1413,7 @@ CREATE TABLE IF NOT EXISTS task_intercept_rules (
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
action TEXT NOT NULL DEFAULT 'block' CHECK (action IN ('block','allow')),
|
||||
kind TEXT NOT NULL CHECK (kind IN (
|
||||
'exact_domain', 'exact_ip', 'exact_url',
|
||||
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
|
||||
'cidr')),
|
||||
pattern TEXT NOT NULL,
|
||||
|
||||
@@ -49,7 +49,7 @@ func TestSideHistoryIdempotencyPagingAndRecovery(t *testing.T) {
|
||||
if _, _, err = d.StartSideRequest(ctx, s, "request-1", "question-1"); !errors.Is(err, ErrSideBusy) {
|
||||
t.Fatalf("busy %v", err)
|
||||
}
|
||||
for i := 0; i < 24; i++ {
|
||||
for i := range 24 {
|
||||
e := first
|
||||
if i > 0 {
|
||||
e, _, err = d.StartSideRequest(ctx, s, fmt.Sprintf("request-%d", i), fmt.Sprintf("question-%d", i))
|
||||
@@ -106,7 +106,7 @@ func TestSideMemoryPagingClearAndRestart(t *testing.T) {
|
||||
d, s := sideFixture(t)
|
||||
ctx := t.Context()
|
||||
var ordinal int64
|
||||
for i := 0; i < 50; i++ {
|
||||
for i := range 50 {
|
||||
e, _, err := d.StartSideRequest(ctx, s, fmt.Sprint(i), "history")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -186,7 +186,7 @@ func TestSideMemoryPagingClearAndRestart(t *testing.T) {
|
||||
|
||||
func TestSideMemoryClearRace(t *testing.T) {
|
||||
d, s := sideFixture(t)
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
e, _, err := d.StartSideRequest(t.Context(), s, "race", "question")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -261,7 +261,7 @@ func TestSideArchiveRowsWithoutNewFields(t *testing.T) {
|
||||
func TestSideClearLateWritersAndDeletedParent(t *testing.T) {
|
||||
d, s := sideFixture(t)
|
||||
ctx := t.Context()
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
e, _, err := d.StartSideRequest(ctx, s, "same-client", "question")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+121
-8
@@ -185,6 +185,84 @@ WHERE COALESCE(task_id,'')=$1 AND status='pending' AND target_key IS NOT NULL`,
|
||||
return err
|
||||
}
|
||||
|
||||
// TargetGateDisabledReason is the audit reason used when disabling a task's
|
||||
// target gate closes or refuses an approval request.
|
||||
const TargetGateDisabledReason = "the target gate was switched off; nothing was pinned"
|
||||
|
||||
// ErrTargetGateDisabled reports an approval that was system-refused because
|
||||
// the task's target gate was disabled before the decision committed.
|
||||
var ErrTargetGateDisabled = errors.New("the target gate was disabled before the target approval was decided")
|
||||
|
||||
// systemDenyTargetRequest settles one locked target request without attributing
|
||||
// the decision to a human. Its audit shape is shared by gate-off bulk closes and
|
||||
// approvals refused after the task gate was disabled.
|
||||
func systemDenyTargetRequest(tx *sql.Tx, id int64, reason string) error {
|
||||
_, err := tx.Exec(`UPDATE intercept_pending SET status='denied', decided_at=NOW(), decided_by='system',
|
||||
audit=CASE WHEN audit IS NULL THEN NULL ELSE (audit - 'approver' - 'approver_addr') ||
|
||||
jsonb_build_object(
|
||||
'effective_action', 'deny',
|
||||
'decision_reason', $2::text,
|
||||
'execution_status', 'not_executed',
|
||||
'targets', COALESCE((
|
||||
SELECT jsonb_agg(value || '{"outcome":"denied"}'::jsonb)
|
||||
FROM jsonb_array_elements(COALESCE(audit->'targets', '[]'::jsonb)) AS target(value)
|
||||
), '[]'::jsonb)
|
||||
) END
|
||||
WHERE id=$1 AND status='pending' AND target_key IS NOT NULL`, id, reason)
|
||||
return err
|
||||
}
|
||||
|
||||
// CloseTargetRequests settles every open target request in scope on behalf of
|
||||
// the system and returns the ids that were closed. Classic asks and requests in
|
||||
// other scopes are left untouched.
|
||||
func (d *DB) CloseTargetRequests(scope TargetScopeRef, reason string) ([]int64, error) {
|
||||
if err := scope.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taskID, _ := scope.pendingScope()
|
||||
taskKey := ""
|
||||
if taskID != nil {
|
||||
taskKey = *taskID
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
rows, err := tx.Query(`SELECT id FROM intercept_pending
|
||||
WHERE COALESCE(task_id,'')=$1 AND COALESCE(conversation_id,0)=$2
|
||||
AND status='pending' AND target_key IS NOT NULL
|
||||
ORDER BY id FOR UPDATE`, taskKey, scope.ConversationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := systemDenyTargetRequest(tx, id, reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// TargetRequest is a new target approval request: the intercept_pending row a
|
||||
// gated call asks for when one of its targets has no pin that covers it.
|
||||
type TargetRequest struct {
|
||||
@@ -256,20 +334,46 @@ func (d *DB) TargetRequestKey(id int64) (string, error) {
|
||||
return key.String, err
|
||||
}
|
||||
|
||||
// ResolveTargetRequest settles an open target request with a human decision, in
|
||||
// one transaction. Allowed pins the addresses the request displayed: the active
|
||||
// pin of the same key, if any, becomes superseded and a new version holds its
|
||||
// addresses plus the displayed ones (addresses leave only by revocation).
|
||||
// Denied pins nothing. approver and remoteAddr go to the pin and to the row's
|
||||
// audit; decided_by on the row stays the actor class, human. ok is false when
|
||||
// the row is not an open target request. If the pin cannot be written the row
|
||||
// stays pending.
|
||||
// ResolveTargetRequest settles an open target request in one transaction.
|
||||
// A task-scoped approval first locks the task and is refused with a system
|
||||
// denial when the task is gone or its target gate is off. Otherwise, allowed
|
||||
// pins the displayed addresses: the active pin of the same key, if any, becomes
|
||||
// superseded and a new version holds its addresses plus the displayed ones
|
||||
// (addresses leave only by revocation). Denied pins nothing. Human decisions
|
||||
// record approver and remoteAddr in the pin and row audit; decided_by remains
|
||||
// the actor class. ok is false when the row is not open. A system-refused
|
||||
// approval returns ErrTargetGateDisabled after committing the denial. If the
|
||||
// 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) {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var initialTaskID sql.NullString
|
||||
err = tx.QueryRow(`SELECT task_id FROM intercept_pending
|
||||
WHERE id=$1 AND status='pending' AND target_key IS NOT NULL`, id).Scan(&initialTaskID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
taskGateEnabled := true
|
||||
if allowed && initialTaskID.Valid {
|
||||
taskIDValue, parseErr := strconv.ParseInt(initialTaskID.String, 10, 64)
|
||||
if parseErr != nil {
|
||||
return nil, false, fmt.Errorf("target request %d: task id %q: %w", id, initialTaskID.String, parseErr)
|
||||
}
|
||||
// Lock task before pending, matching task deletion's lock order.
|
||||
lockErr := tx.QueryRow(`SELECT target_gate FROM tasks
|
||||
WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskIDValue).Scan(&taskGateEnabled)
|
||||
if errors.Is(lockErr, sql.ErrNoRows) {
|
||||
taskGateEnabled = false
|
||||
} else if lockErr != nil {
|
||||
return nil, false, lockErr
|
||||
}
|
||||
}
|
||||
var taskID sql.NullString
|
||||
var convID sql.NullInt64
|
||||
var raw []byte
|
||||
@@ -281,6 +385,15 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if allowed && taskID.Valid && !taskGateEnabled {
|
||||
if err := systemDenyTargetRequest(tx, id, TargetGateDisabledReason); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return nil, false, ErrTargetGateDisabled
|
||||
}
|
||||
var audit InterceptAudit
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, &audit); err != nil {
|
||||
|
||||
+155
-11
@@ -25,10 +25,14 @@ func openTargetDB(t *testing.T) *DB {
|
||||
return d
|
||||
}
|
||||
|
||||
// targetTask creates a task and removes it, its pins and its approval rows at
|
||||
// the end of the test (pins and approval rows outlive a task delete by design).
|
||||
// targetTask silently defaults the gate on because approvals need a gated task.
|
||||
// It removes the task, its pins and approval rows at the end of the test.
|
||||
func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task {
|
||||
t.Helper()
|
||||
if opts.TargetGate == nil {
|
||||
gateOn := true
|
||||
opts.TargetGate = &gateOn
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("target gate store", "pins and requests", opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -41,6 +45,12 @@ func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task {
|
||||
return task
|
||||
}
|
||||
|
||||
func defaultOffTargetTask(t *testing.T, d *DB) *Task {
|
||||
t.Helper()
|
||||
gateOff := false
|
||||
return targetTask(t, d, TaskCreateOptions{TargetGate: &gateOff})
|
||||
}
|
||||
|
||||
func targetConversation(t *testing.T, d *DB) *Conversation {
|
||||
t.Helper()
|
||||
c, err := d.CreateConversation("assistant", fmt.Sprintf("target gate %d", time.Now().UnixNano()), nil)
|
||||
@@ -162,7 +172,7 @@ AND contype IN ('c','f','p','u') ORDER BY 1`,
|
||||
}
|
||||
}
|
||||
// Only primary keys on the new tables: no CHECK, no foreign key.
|
||||
for _, line := range strings.Split(first, "\n") {
|
||||
for line := range strings.SplitSeq(first, "\n") {
|
||||
if (strings.HasPrefix(line, "target_pins ") || strings.HasPrefix(line, "target_gate_exemption_log ")) && !strings.Contains(line, "_pkey p ") {
|
||||
t.Errorf("unexpected constraint on a target-gate table: %s", line)
|
||||
}
|
||||
@@ -268,6 +278,47 @@ func TestTargetRequestNewRowAfterDecision(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseTargetRequestsOnlyClosesPendingTargetsInScope(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
scope := TargetScopeRef{TaskID: targetTask(t, d, TaskCreateOptions{}).ID}
|
||||
other := TargetScopeRef{TaskID: targetTask(t, d, TaskCreateOptions{}).ID}
|
||||
closed, _ := openTargetRequest(t, d, scope, "close.example.com", 443, "203.0.113.7")
|
||||
decided, _ := openTargetRequest(t, d, scope, "decided.example.com", 443, "203.0.113.8")
|
||||
if _, ok, err := d.ResolveTargetRequest(decided, false, "ARTEX", "198.51.100.9"); err != nil || !ok {
|
||||
t.Fatalf("pre-decide row: ok=%v err=%v", ok, err)
|
||||
}
|
||||
otherID, _ := openTargetRequest(t, d, other, "other.example.com", 443, "203.0.113.9")
|
||||
classic, err := d.CreateInterceptPending(0, 0, strconv.FormatInt(scope.TaskID, 10), "worker", "Bash", nil, "classic ask")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const reason = TargetGateDisabledReason
|
||||
ids, err := d.CloseTargetRequests(scope, reason)
|
||||
if err != nil || !slices.Equal(ids, []int64{closed}) {
|
||||
t.Fatalf("closed ids = %v, err=%v; want [%d]", ids, err, closed)
|
||||
}
|
||||
row, err := d.GetInterceptDetail(closed)
|
||||
if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil ||
|
||||
row.Audit.EffectiveAction != "deny" || row.Audit.DecisionReason != reason || row.Audit.ExecutionStatus != "not_executed" ||
|
||||
len(row.Audit.Targets) != 1 || row.Audit.Targets[0].Outcome != "denied" || row.Audit.Approver != "" || row.Audit.ApproverAddr != "" {
|
||||
t.Fatalf("closed row = %+v, %v", row, err)
|
||||
}
|
||||
for name, id := range map[string]int64{"already decided target": decided, "other scope target": otherID, "classic ask": classic} {
|
||||
row, err := d.GetInterceptPending(id)
|
||||
if err != nil || row == nil {
|
||||
t.Fatalf("%s row %d = %+v, %v", name, id, row, err)
|
||||
}
|
||||
if name == "already decided target" {
|
||||
if row.Status != "denied" || row.DecidedBy != "human" {
|
||||
t.Fatalf("%s changed: %+v", name, row)
|
||||
}
|
||||
} else if row.Status != "pending" || row.DecidedBy != "" {
|
||||
t.Fatalf("%s changed: %+v", name, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Settling the row, superseding the old pin and writing the new one are one
|
||||
// transaction: when the pin cannot be written the row stays pending and the
|
||||
// previous pin stays active.
|
||||
@@ -315,6 +366,88 @@ FOR EACH ROW EXECUTE FUNCTION test_refuse_target_pin()`); err != nil {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTargetRequestRefusesApprovalAfterTaskGateDisabled(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
on, off := true, false
|
||||
task := targetTask(t, d, TaskCreateOptions{TargetGate: &on})
|
||||
scope := TargetScopeRef{TaskID: task.ID}
|
||||
id, created := openTargetRequest(t, d, scope, "late-approval.example.com", 443, "203.0.113.77")
|
||||
if !created {
|
||||
t.Fatal("target request was not created")
|
||||
}
|
||||
if updated, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &off}); err != nil || updated == nil || updated.TargetGate {
|
||||
t.Fatalf("disable target gate: task=%+v err=%v", updated, err)
|
||||
}
|
||||
|
||||
if pin, ok, err := d.ResolveTargetRequest(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrTargetGateDisabled) || ok || pin != nil {
|
||||
t.Fatalf("late approval: pin=%+v ok=%v err=%v, want ErrTargetGateDisabled", pin, ok, err)
|
||||
}
|
||||
detail, err := d.GetInterceptDetail(id)
|
||||
if err != nil || detail == nil || detail.Status != "denied" || detail.DecidedBy != "system" || detail.Audit == nil ||
|
||||
detail.Audit.DecisionReason != TargetGateDisabledReason || detail.Audit.EffectiveAction != "deny" ||
|
||||
detail.Audit.ExecutionStatus != "not_executed" || len(detail.Audit.Targets) != 1 || detail.Audit.Targets[0].Outcome != "denied" ||
|
||||
detail.Audit.Approver != "" || detail.Audit.ApproverAddr != "" {
|
||||
t.Fatalf("late-approval row = %+v, %v; want unauthored system denial", detail, err)
|
||||
}
|
||||
if pins, err := d.ListTargetPins(scope); err != nil || len(pins) != 0 {
|
||||
t.Fatalf("late approval pins = %+v, err=%v; want none", pins, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTargetRequestWaitsForTaskGateLock(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
on := true
|
||||
task := targetTask(t, d, TaskCreateOptions{TargetGate: &on})
|
||||
scope := TargetScopeRef{TaskID: task.ID}
|
||||
id, _ := openTargetRequest(t, d, scope, "locked-gate.example.com", 443, "203.0.113.78")
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
var lockedID int64
|
||||
if err := blocker.QueryRow(`SELECT id FROM tasks WHERE id=$1 FOR UPDATE`, task.ID).Scan(&lockedID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := blocker.Exec(`UPDATE tasks SET target_gate=false WHERE id=$1`, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
type resolveResult struct {
|
||||
pin *TargetPin
|
||||
ok bool
|
||||
err error
|
||||
}
|
||||
started := make(chan struct{})
|
||||
done := make(chan resolveResult, 1)
|
||||
go func() {
|
||||
close(started)
|
||||
pin, ok, err := d.ResolveTargetRequest(id, true, "ARTEX", "198.51.100.9")
|
||||
done <- resolveResult{pin: pin, ok: ok, err: err}
|
||||
}()
|
||||
<-started
|
||||
select {
|
||||
case got := <-done:
|
||||
t.Fatalf("ResolveTargetRequest returned while task row was locked: %+v", got)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
if err := blocker.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case got := <-done:
|
||||
if !errors.Is(got.err, ErrTargetGateDisabled) || got.ok || got.pin != nil {
|
||||
t.Fatalf("approval after lock release = %+v, want ErrTargetGateDisabled", got)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("ResolveTargetRequest remained blocked after commit")
|
||||
}
|
||||
if pins, err := d.ListTargetPins(scope); err != nil || len(pins) != 0 {
|
||||
t.Fatalf("approval after gate-off commit pins = %+v, err=%v; want none", pins, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Approving a request for a pinned key extends the pin: the new version holds
|
||||
// the old addresses plus the displayed ones. Addresses leave only by revocation.
|
||||
func TestTargetPinVersioningExtends(t *testing.T) {
|
||||
@@ -749,7 +882,15 @@ func TestConversationBatchDeleteRevokesOnlyDeletedIds(t *testing.T) {
|
||||
|
||||
func TestTaskTargetGateDefaultsOff(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
task := targetTask(t, d, TaskCreateOptions{})
|
||||
task, err := d.CreateTaskWithOptions("target gate store", "pins and requests", TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(task.ID)
|
||||
_, _ = d.Exec(`DELETE FROM target_pins WHERE task_id=$1`, task.ID)
|
||||
_, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, strconv.FormatInt(task.ID, 10))
|
||||
})
|
||||
if task.TargetGate {
|
||||
t.Fatal("a task created without the option has the gate on")
|
||||
}
|
||||
@@ -757,8 +898,7 @@ func TestTaskTargetGateDefaultsOff(t *testing.T) {
|
||||
if err != nil || got == nil || got.TargetGate {
|
||||
t.Fatalf("stored task = %+v, %v; want the gate off", got, err)
|
||||
}
|
||||
off := false
|
||||
if explicit := targetTask(t, d, TaskCreateOptions{TargetGate: &off}); explicit.TargetGate {
|
||||
if explicit := defaultOffTargetTask(t, d); explicit.TargetGate {
|
||||
t.Fatal("a task created with the option false has the gate on")
|
||||
}
|
||||
c := targetConversation(t, d)
|
||||
@@ -837,18 +977,22 @@ func TestConversationTargetGateRoundTrip(t *testing.T) {
|
||||
// pins.
|
||||
func TestRetestConversationCopiesFlagNotPins(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
on := true
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
opts TaskCreateOptions
|
||||
want bool
|
||||
}{
|
||||
{"gate on", TaskCreateOptions{TargetGate: &on}, true},
|
||||
{"gate off", TaskCreateOptions{}, false},
|
||||
{"gate on", true},
|
||||
{"gate off", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
task := targetTask(t, d, tc.opts)
|
||||
task := targetTask(t, d, TaskCreateOptions{})
|
||||
approveTarget(t, d, TargetScopeRef{TaskID: task.ID}, "app.example.com", 443, "203.0.113.7")
|
||||
if !tc.want {
|
||||
off := false
|
||||
if updated, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &off}); err != nil || updated == nil || updated.TargetGate {
|
||||
t.Fatalf("disable target gate: task=%+v err=%v", updated, err)
|
||||
}
|
||||
}
|
||||
fid, err := d.AddFinding(task.ID, 0, "retest-gate", "gated finding", "high", "summary", "evidence", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+1
-4
@@ -309,10 +309,7 @@ LIMIT 1`, taskID).Scan(&dependent)
|
||||
}
|
||||
remaining := int64(0)
|
||||
if paused && deadline != nil {
|
||||
remaining = int64(time.Until(*deadline).Seconds())
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
remaining = max(int64(time.Until(*deadline).Seconds()), 0)
|
||||
}
|
||||
_, err = tx.Exec(`INSERT INTO task_archives(
|
||||
task_id,state,phase,progress,error,warnings,format_version,task_name,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -572,9 +573,7 @@ func findArchiveAssetNaturalID(tx *sql.Tx, row map[string]any) (int64, bool, err
|
||||
|
||||
func remapArchiveAssetReferences(tables map[string]json.RawMessage, mapping map[int64]int64) (map[string]json.RawMessage, error) {
|
||||
out := make(map[string]json.RawMessage, len(tables))
|
||||
for name, raw := range tables {
|
||||
out[name] = raw
|
||||
}
|
||||
maps.Copy(out, tables)
|
||||
for _, table := range []string{"exploration_anchors", "task_asset_links"} {
|
||||
rows, err := decodeArchiveRows(tables[table])
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -201,10 +202,5 @@ func waitForTaskDeleteResult(done <-chan error) error {
|
||||
}
|
||||
|
||||
func containsDeleteHost(hosts []string, want string) bool {
|
||||
for _, host := range hosts {
|
||||
if host == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(hosts, want)
|
||||
}
|
||||
|
||||
@@ -68,6 +68,30 @@ func TestTaskPinOrderingAndRename(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetGateChangeRollsBackOnActivityError(t *testing.T) {
|
||||
d, err := Open(scratchDSN(t, "gate_activity"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
task, err := d.CreateTaskWithOptions("gate audit", "goal", TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.Exec(`ALTER TABLE activity ADD CHECK (kind <> 'target_gate_changed')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
on := true
|
||||
if _, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &on}); err == nil {
|
||||
t.Fatal("gate update succeeded despite rejected activity")
|
||||
}
|
||||
stored, err := d.GetTask(task.ID)
|
||||
if err != nil || stored == nil || stored.TargetGate {
|
||||
t.Fatalf("stored task = %+v, %v; want gate still off", stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteConversationsReturnsExistingIDs(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
|
||||
@@ -13,7 +13,7 @@ func TestTaskRotationPersistenceAndFailover(t *testing.T) {
|
||||
}
|
||||
defer d.Close()
|
||||
ids := []int64{}
|
||||
for i := 0; i < 2; i++ {
|
||||
for i := range 2 {
|
||||
id, err := d.SaveProfile(&LLMProfile{Name: fmt.Sprintf("rotation-%d-%d", time.Now().UnixNano(), i), Format: "openai", Model: "test", APIKey: "test-key"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+89
-1
@@ -1,6 +1,9 @@
|
||||
package db
|
||||
|
||||
import "database/sql"
|
||||
import (
|
||||
"database/sql"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// egressExecer is satisfied by *DB, *sql.DB and *sql.Tx.
|
||||
type egressExecer interface {
|
||||
@@ -69,3 +72,88 @@ ORDER BY kind, value`, taskID, companyID)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// TaskEgressGrants returns the normalized egress entries an operator approved
|
||||
// for this task: the task's own approved, unexpanded task_scope rows and the
|
||||
// entries frozen into task_scope_egress by approved company grants (the same
|
||||
// rows, normalized the same way, that feed the sandbox proxy's allowlist).
|
||||
// Unapproved rows (agent-written, expanded) grant nothing, and task allow
|
||||
// interception rules play no role here either: they satisfy neither the
|
||||
// network nor the gate (TestAllowRuleDoesNotSatisfyGate). The target gate
|
||||
// consults this set so it cannot demand an approval for a target whose
|
||||
// address space the operator already granted.
|
||||
func (d *DB) TaskEgressGrants(taskID int64) ([]ScopeEgress, error) {
|
||||
if taskID <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
seenDom := map[string]bool{}
|
||||
seenCIDR := map[string]bool{}
|
||||
var out []ScopeEgress
|
||||
add := func(kind, value string) {
|
||||
if kind == "domain" {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
value = strings.TrimPrefix(value, "*.")
|
||||
value = strings.TrimPrefix(value, ".")
|
||||
} else {
|
||||
value = strings.TrimSpace(value)
|
||||
}
|
||||
if value == "" {
|
||||
return
|
||||
}
|
||||
seen := seenCIDR
|
||||
if kind == "domain" {
|
||||
seen = seenDom
|
||||
}
|
||||
if !seen[value] {
|
||||
seen[value] = true
|
||||
out = append(out, ScopeEgress{Kind: kind, Value: value})
|
||||
}
|
||||
}
|
||||
rows, err := d.Query(`SELECT kind, COALESCE(domain,''), COALESCE(net::text,''), COALESCE(value,''), COALESCE(company_id,0) FROM task_scope WHERE task_id=$1 AND approved_by_operator=true AND COALESCE(expanded,false)=false`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var companyIDs []int64
|
||||
seenComp := map[int64]bool{}
|
||||
for rows.Next() {
|
||||
var kind, dom, netStr, val string
|
||||
var compID int64
|
||||
if rows.Scan(&kind, &dom, &netStr, &val, &compID) != nil {
|
||||
continue
|
||||
}
|
||||
switch kind {
|
||||
case "company":
|
||||
if compID > 0 && !seenComp[compID] {
|
||||
seenComp[compID] = true
|
||||
companyIDs = append(companyIDs, compID)
|
||||
}
|
||||
case "domain", "root_domain", "subdomain":
|
||||
if dom != "" {
|
||||
add("domain", dom)
|
||||
} else {
|
||||
add("domain", val)
|
||||
}
|
||||
case "cidr", "ip", "ip_range":
|
||||
if netStr != "" {
|
||||
add("cidr", netStr)
|
||||
} else {
|
||||
add("cidr", val)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
rows.Close()
|
||||
for _, cid := range companyIDs {
|
||||
entries, err := d.CompanyEgressForTask(taskID, cid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
add(e.Kind, e.Value)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestTaskEgressGrants checks the gate-facing view of a task's approved
|
||||
// egress: the task's own operator-approved unexpanded rows and the entries
|
||||
// frozen by approved company grants, normalized as the sandbox proxy builds
|
||||
// them. Unapproved and expanded rows grant nothing, and allow rules are not
|
||||
// part of the set.
|
||||
func TestTaskEgressGrants(t *testing.T) {
|
||||
dsn := scratchDSN(t, "egress_grants")
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer d.Close()
|
||||
var companyID, expID, taskID int64
|
||||
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('Grant Corp', 'grant corp') RETURNING id`).Scan(&companyID); err != nil {
|
||||
t.Fatalf("insert company: %v", err)
|
||||
}
|
||||
if err := d.QueryRow(`INSERT INTO explorations(goal) VALUES ('grant fixture') RETURNING id`).Scan(&expID); err != nil {
|
||||
t.Fatalf("insert exploration: %v", err)
|
||||
}
|
||||
if err := d.QueryRow(`INSERT INTO tasks(name, description, goal, exploration_id) VALUES ('grants', 'grants', 'grants', $1) RETURNING id`, expID).Scan(&taskID); err != nil {
|
||||
t.Fatalf("insert task: %v", err)
|
||||
}
|
||||
seeds := []struct {
|
||||
stmt string
|
||||
args []any
|
||||
}{
|
||||
{`INSERT INTO task_scope(task_id, kind, net, source, approved_by_operator) VALUES ($1, 'ip', '192.0.2.5/32', 'manual', true)`, []any{taskID}},
|
||||
{`INSERT INTO task_scope(task_id, kind, domain, source, approved_by_operator) VALUES ($1, 'root_domain', 'unapproved.test', 'agent', false)`, []any{taskID}},
|
||||
{`INSERT INTO task_scope(task_id, kind, domain, source, approved_by_operator, expanded) VALUES ($1, 'subdomain', 'expanded.test', 'manual', true, true)`, []any{taskID}},
|
||||
{`INSERT INTO task_scope(task_id, kind, company_id, source, approved_by_operator) VALUES ($1, 'company', $2, 'manual', true)`, []any{taskID, companyID}},
|
||||
{`INSERT INTO task_scope_egress(task_id, kind, value, company_id) VALUES ($1, 'domain', '*.Lab.test', $2), ($1, 'cidr', '198.51.100.0/24', $2)`, []any{taskID, companyID}},
|
||||
}
|
||||
for _, s := range seeds {
|
||||
if _, err := d.Exec(s.stmt, s.args...); err != nil {
|
||||
t.Fatalf("seed (%s): %v", s.stmt, err)
|
||||
}
|
||||
}
|
||||
grants, err := d.TaskEgressGrants(taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEgressGrants: %v", err)
|
||||
}
|
||||
byKind := map[string]map[string]bool{}
|
||||
for _, g := range grants {
|
||||
if byKind[g.Kind] == nil {
|
||||
byKind[g.Kind] = map[string]bool{}
|
||||
}
|
||||
byKind[g.Kind][g.Value] = true
|
||||
}
|
||||
for _, want := range []string{"lab.test"} {
|
||||
if !byKind["domain"][want] {
|
||||
t.Errorf("domains %v, want %s", byKind["domain"], want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"unapproved.test", "expanded.test", "*.lab.test", "*.Lab.test"} {
|
||||
if byKind["domain"][bad] {
|
||||
t.Errorf("domains %v, must not hold %s", byKind["domain"], bad)
|
||||
}
|
||||
}
|
||||
// net::text may render a /32 with or without the prefix length.
|
||||
cidrOK := false
|
||||
for v := range byKind["cidr"] {
|
||||
if strings.HasPrefix(v, "192.0.2.5") {
|
||||
cidrOK = true
|
||||
}
|
||||
}
|
||||
if !cidrOK {
|
||||
t.Errorf("cidrs %v, want the approved 192.0.2.5", byKind["cidr"])
|
||||
}
|
||||
for _, want := range []string{"198.51.100.0/24"} {
|
||||
if !byKind["cidr"][want] {
|
||||
t.Errorf("cidrs %v, want %s", byKind["cidr"], want)
|
||||
}
|
||||
}
|
||||
if len(byKind["cidr"]) != 2 {
|
||||
t.Errorf("cidrs %v, want exactly the approved ip and the frozen company range", byKind["cidr"])
|
||||
}
|
||||
if got, err := d.TaskEgressGrants(0); err != nil || got != nil {
|
||||
t.Errorf("TaskEgressGrants(0) = %v, %v, want nil, nil", got, err)
|
||||
}
|
||||
}
|
||||
@@ -112,13 +112,11 @@ func TestTaskTemplateDisjointPatchesCompose(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
for _, patch := range []TaskTemplatePatch{{Description: &description}, {Goal: &goal}} {
|
||||
patch := patch
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
wg.Go(func() {
|
||||
<-start
|
||||
_, err := d.PatchTaskTemplate(created.ID, patch)
|
||||
errs <- err
|
||||
}()
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
+149
-12
@@ -182,9 +182,21 @@ type TaskCreateOptions struct {
|
||||
// OFF for unscoped tasks; pass an explicit false pointer to opt out.
|
||||
TargetGate *bool
|
||||
// CompanyScopeByAgent marks CompanyIDs supplied by an LLM orchestration tool
|
||||
// (spawn_task) rather than an authenticated operator, leaving task_scope
|
||||
// approved_by_operator=false (coverage-only) to prevent scope drift.
|
||||
// (spawn_task) rather than an authenticated operator. The link is inserted
|
||||
// approved_by_operator=false (coverage-only), except for a company whose
|
||||
// whole scope inventory the operator approved AND to which the calling
|
||||
// task itself holds an operator-approved link (CompanyScopeCallerID): that
|
||||
// standing consent is inherited, so chat-spawned tasks stop starting with
|
||||
// an empty allowlist against companies the operator configured (#830)
|
||||
// while the caller boundary keeps the agent from self-widening reach
|
||||
// (#841).
|
||||
CompanyScopeByAgent bool
|
||||
// CompanyScopeCallerID is the id of the task running spawn_task when
|
||||
// CompanyScopeByAgent is set (0 = no task caller: chat session or direct
|
||||
// API use). Standing company consent is inherited only for companies the
|
||||
// caller task itself holds operator-approved links to; with no task caller
|
||||
// nothing is auto-approved (#841, review 6154399166).
|
||||
CompanyScopeCallerID int64
|
||||
}
|
||||
|
||||
// CreateTaskWithOptions creates an exploration, task, direct source relations,
|
||||
@@ -281,7 +293,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti
|
||||
if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs, !opts.CompanyScopeByAgent); err != nil {
|
||||
if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs, !opts.CompanyScopeByAgent, opts.CompanyScopeCallerID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertTaskLLMProfiles(tx, t.ID, opts.LLMProfileIDs); err != nil {
|
||||
@@ -298,7 +310,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti
|
||||
return t, tx.Commit()
|
||||
}
|
||||
|
||||
func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedByOperator bool) error {
|
||||
func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedByOperator bool, callerTaskID int64) error {
|
||||
if len(companyIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -311,6 +323,36 @@ func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedB
|
||||
if !approvedByOperator {
|
||||
src = "agent"
|
||||
}
|
||||
// #830: migration 0025 made each company-scope row an explicit operator
|
||||
// decision, so a company whose whole inventory is operator-approved carries
|
||||
// standing operator consent. An LLM-selected company of that kind grants
|
||||
// nothing new at spawn: its task link is inserted approved and its grant
|
||||
// frozen, exactly as an operator selection would, and chat-spawned tasks
|
||||
// stop starting with an empty allowlist against a company the operator
|
||||
// configured. A company holding any agent-written (unapproved) row, or with
|
||||
// no scope rows at all, stays coverage-only: add_company_scope and invented
|
||||
// ids still cannot self-grant. Provenance is kept either way: source stays
|
||||
// agent, the approval column records who consented.
|
||||
// #841 review 6154399166 adds the trust boundary: that consent only flows
|
||||
// to a child through a caller that already reaches the company, so an
|
||||
// agent spawn inherits only within the calling task's operator-approved
|
||||
// companies, and a spawn with no task caller (chat session, direct API)
|
||||
// inherits nothing silently.
|
||||
var inherited []int64
|
||||
if !approvedByOperator {
|
||||
var err error
|
||||
inherited, err = companiesInheritableByCallerTx(tx, companyIDs, callerTaskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
grantIDs := companyIDs
|
||||
if !approvedByOperator {
|
||||
grantIDs = inherited
|
||||
}
|
||||
if grantIDs == nil {
|
||||
grantIDs = []int64{}
|
||||
}
|
||||
var inserted int
|
||||
err := tx.QueryRow(`
|
||||
WITH requested(company_id, position) AS (
|
||||
@@ -318,13 +360,14 @@ WITH requested(company_id, position) AS (
|
||||
FROM unnest($2::bigint[]) WITH ORDINALITY AS requested(company_id, position)
|
||||
), inserted AS (
|
||||
INSERT INTO task_scope(task_id, kind, company_id, source, reason, approved_by_operator)
|
||||
SELECT $1, 'company', companies.id, $3, 'associated with company at task creation', $4
|
||||
SELECT $1, 'company', companies.id, $3, 'associated with company at task creation',
|
||||
$4::boolean OR requested.company_id = ANY($5::bigint[])
|
||||
FROM requested
|
||||
JOIN companies ON companies.id=requested.company_id
|
||||
ORDER BY requested.position
|
||||
RETURNING company_id
|
||||
)
|
||||
SELECT count(*) FROM inserted`, taskID, companyIDs, src, approvedByOperator).Scan(&inserted)
|
||||
SELECT count(*) FROM inserted`, taskID, companyIDs, src, approvedByOperator, grantIDs).Scan(&inserted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -357,16 +400,62 @@ SET source=EXCLUDED.source,
|
||||
source_node_id=NULL`, taskID, companyIDs, taskCompanyAssetSource); err != nil {
|
||||
return err
|
||||
}
|
||||
if approvedByOperator {
|
||||
// Freeze the company inventory this operator decision covers: the sandbox
|
||||
// proxy reads the snapshot, not live company_scope/assets.
|
||||
if err := snapshotCompanyEgress(tx, taskID, companyIDs); err != nil {
|
||||
if len(grantIDs) > 0 {
|
||||
// Freeze the company inventory this operator decision covers: the
|
||||
// sandbox proxy reads the snapshot, not live company_scope/assets. For
|
||||
// an agent spawn that is only the inherited companies; the snapshot
|
||||
// itself copies 0025-approved rows only.
|
||||
if err := snapshotCompanyEgress(tx, taskID, grantIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// companiesInheritableByCallerTx returns the requested companies whose egress
|
||||
// inheritance is consented twice over: the company's company_scope inventory
|
||||
// exists and is entirely operator-approved (the company-level consent
|
||||
// migration 0025 introduced), AND the calling task holds its own
|
||||
// operator-approved link to that company (#841, review 6154399166). Selecting
|
||||
// such a company at spawn introduces no address the operator has not already
|
||||
// approved for it and no reach the caller did not already have; companies
|
||||
// without scope rows (an id the LLM invented, or an empty inventory),
|
||||
// companies holding any unapproved row, and companies the caller cannot reach
|
||||
// are excluded - promoting those would let the agent widen its own sandbox. A
|
||||
// callerTaskID of 0 (chat session, direct API) inherits nothing: the child
|
||||
// starts coverage-only until the operator confirms the link on the task scope.
|
||||
func companiesInheritableByCallerTx(tx *sql.Tx, companyIDs []int64, callerTaskID int64) ([]int64, error) {
|
||||
if len(companyIDs) == 0 || callerTaskID <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := tx.Query(`
|
||||
SELECT ids.id
|
||||
FROM unnest($1::bigint[]) AS ids(id)
|
||||
WHERE EXISTS (SELECT 1 FROM company_scope cs WHERE cs.company_id = ids.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM company_scope cs
|
||||
WHERE cs.company_id = ids.id
|
||||
AND cs.approved_by_operator IS DISTINCT FROM TRUE)
|
||||
AND EXISTS (SELECT 1 FROM task_scope ts
|
||||
WHERE ts.task_id = $2
|
||||
AND ts.kind = 'company'
|
||||
AND ts.company_id = ids.id
|
||||
AND ts.approved_by_operator IS TRUE)
|
||||
ORDER BY ids.id`, companyIDs, callerTaskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func insertTaskRelations(tx *sql.Tx, taskID int64, sourceIDs []int64) error {
|
||||
seen := map[int64]bool{}
|
||||
for _, sourceID := range sourceIDs {
|
||||
@@ -454,12 +543,60 @@ type TaskPatch struct {
|
||||
PlanQuietMode *bool
|
||||
// TargetGate flips the per-task target-gate opt-in; nil = leave unchanged.
|
||||
TargetGate *bool
|
||||
ChangedBy string
|
||||
ClientIP string
|
||||
}
|
||||
|
||||
// UpdateTask applies a partial task name/pin mutation and returns the updated row.
|
||||
// UpdateTask applies a metadata patch and records target gate changes in task activity.
|
||||
// Re-pinning an already pinned task preserves its original position.
|
||||
func (d *DB) UpdateTask(id int64, patch TaskPatch) (*Task, error) {
|
||||
task, err := scanTask(d.QueryRow(`UPDATE tasks SET
|
||||
if patch.TargetGate == nil {
|
||||
return updateTask(d, id, patch)
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Lock the row so concurrent patches record the value they actually replace.
|
||||
var before bool
|
||||
err = tx.QueryRow(`SELECT target_gate FROM tasks WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, id).Scan(&before)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
task, err := updateTask(tx, id, patch)
|
||||
if err != nil || task == nil {
|
||||
return nil, err
|
||||
}
|
||||
if before != task.TargetGate {
|
||||
metadata, err := json.Marshal(map[string]any{
|
||||
"task_id": id, "changed_by": patch.ChangedBy, "client_ip": patch.ClientIP,
|
||||
"before": before, "after": task.TargetGate,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = d.Exploration(task.ExplorationID).appendActivity(tx, Activity{
|
||||
Worker: "system", Kind: "target_gate_changed",
|
||||
Summary: fmt.Sprintf("Target gate changed from %t to %t", before, task.TargetGate),
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return task, nil
|
||||
}
|
||||
|
||||
func updateTask(q queryRower, id int64, patch TaskPatch) (*Task, error) {
|
||||
task, err := scanTask(q.QueryRow(`UPDATE tasks SET
|
||||
name = CASE WHEN $2::boolean THEN $3 ELSE name END,
|
||||
pinned_at = CASE
|
||||
WHEN $4::boolean IS NULL THEN pinned_at
|
||||
|
||||
+4
-6
@@ -218,7 +218,7 @@ func TestTaskRelationsAndLLMFailoverChain(t *testing.T) {
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileIDs := make([]int64, 0, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
for i := range 3 {
|
||||
id, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("task-chain-%d-%d", suffix, i), Format: "openai",
|
||||
Model: fmt.Sprintf("model-%d", i), APIKey: "test-key",
|
||||
@@ -337,17 +337,15 @@ func TestTaskRelationsAndLLMFailoverChain(t *testing.T) {
|
||||
transitions := make(chan TaskLLMTransition, 2)
|
||||
errs := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 2 {
|
||||
wg.Go(func() {
|
||||
transition, markErr := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[2], "concurrent final quota")
|
||||
if markErr != nil {
|
||||
errs <- markErr
|
||||
return
|
||||
}
|
||||
transitions <- transition
|
||||
}()
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
@@ -186,7 +186,7 @@ func TestTrafficRewriteRuleCRUDSealed(t *testing.T) {
|
||||
func TestTrafficRewriteRuleLimits(t *testing.T) {
|
||||
d := openRewriteRules(t)
|
||||
var enabled, disabled []int64
|
||||
for i := 0; i < MaxTrafficRewriteRules; i++ {
|
||||
for i := range MaxTrafficRewriteRules {
|
||||
on := i < MaxEnabledTrafficRewriteRules
|
||||
r, err := d.CreateTrafficRewriteRule(rewriteRule(fmt.Sprintf("t-rw-limit-%03d", i), on))
|
||||
if err != nil {
|
||||
|
||||
+17
-1
@@ -14,6 +14,15 @@
|
||||
# built-in /app/skills; this file does not mount a host skills/ directory. To use
|
||||
# custom skills, copy them into a host directory and add
|
||||
# `- ./skills:/app/skills` to the artex volumes.
|
||||
# Log rotation for the long-running services: Docker's default json-file driver
|
||||
# keeps container logs without a size limit, so a chatty task can fill the disk
|
||||
# (on Docker Desktop, a full VM disk turns the whole VM read-only).
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
@@ -28,6 +37,7 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
artex:
|
||||
@@ -89,6 +99,7 @@ services:
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./keys:/app/keys
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
artex-runner:
|
||||
@@ -96,10 +107,14 @@ services:
|
||||
networks:
|
||||
- runner-net
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# Only the host side of the engine socket is configurable (rootless Podman
|
||||
# exposes it under XDG_RUNTIME_DIR, issue #742). The in-container path stays
|
||||
# fixed so every deployment dials the same socket from inside the runner.
|
||||
- ${ARTEX_DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
|
||||
- ./data/tasks:/app/data/tasks
|
||||
- ./data/egress-audit:/app/data/egress-audit
|
||||
environment:
|
||||
DOCKER_SOCK: /var/run/docker.sock
|
||||
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
|
||||
ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-ghcr.io/baarai/artex-worker:${ARTEX_IMAGE_TAG:-0.7.1}}
|
||||
ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-ghcr.io/baarai/artex-egress-proxy:${ARTEX_IMAGE_TAG:-0.7.1}}
|
||||
@@ -114,6 +129,7 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
# Images the runner instantiates per task. They are pulled with
|
||||
|
||||
@@ -34,10 +34,14 @@ services:
|
||||
networks:
|
||||
- runner-net
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# Only the host side of the engine socket is configurable (rootless Podman
|
||||
# exposes it under XDG_RUNTIME_DIR, issue #742). The in-container path stays
|
||||
# fixed so every deployment dials the same socket from inside the runner.
|
||||
- ${ARTEX_DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
|
||||
- ./data/tasks:/app/data/tasks
|
||||
- ./data/egress-audit:/app/data/egress-audit
|
||||
environment:
|
||||
DOCKER_SOCK: /var/run/docker.sock
|
||||
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
|
||||
ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-artex-worker:local}
|
||||
ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-artex-egress-proxy:local}
|
||||
|
||||
+17
-1
@@ -1,3 +1,12 @@
|
||||
# Log rotation for the long-running services: Docker's default json-file driver
|
||||
# keeps container logs without a size limit, so a chatty task can fill the disk
|
||||
# (on Docker Desktop, a full VM disk turns the whole VM read-only).
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d
|
||||
@@ -18,6 +27,7 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
artex:
|
||||
@@ -96,6 +106,7 @@ services:
|
||||
# Mount skills/ from the project root into the container (overriding the image's built-in /app/skills);
|
||||
# skill changes require no image rebuild — the container reads the host copy.
|
||||
- ./skills:/app/skills
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
artex-runner:
|
||||
@@ -106,10 +117,14 @@ services:
|
||||
networks:
|
||||
- runner-net
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# Only the host side of the engine socket is configurable (rootless Podman
|
||||
# exposes it under XDG_RUNTIME_DIR, issue #742). The in-container path stays
|
||||
# fixed so every deployment dials the same socket from inside the runner.
|
||||
- ${ARTEX_DOCKER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
|
||||
- ./data/tasks:/app/data/tasks
|
||||
- ./data/egress-audit:/app/data/egress-audit
|
||||
environment:
|
||||
DOCKER_SOCK: /var/run/docker.sock
|
||||
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
|
||||
ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-artex-worker:local}
|
||||
ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-artex-egress-proxy:local}
|
||||
@@ -124,6 +139,7 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
logging: *default-logging
|
||||
restart: unless-stopped
|
||||
|
||||
artex-worker:
|
||||
|
||||
@@ -38,7 +38,7 @@ numbered migrations from `db/migrations/*.sql`, recording name + SHA-256 in
|
||||
| `egress` | Noise governor | Per-host token bucket, jitter, concurrency caps, 429/503 backoff; default profile is strict passthrough |
|
||||
| `llmpool` / `llmrec` | Provider pool / recorder | Rotation, health, usage + raw wire capture |
|
||||
| `mcphttp` | MCP client | HTTP/SSE transport for configured MCP servers |
|
||||
| `notify` | Outbound notifications | Email, webhook, Telegram, Feishu, DingTalk with masking and SSRF guards |
|
||||
| `notify` | Outbound notifications | Email, webhook, Telegram, Slack, Feishu, DingTalk, WeCom with masking and SSRF guards |
|
||||
| `report` | Deliverables | Markdown, CSV and JSON rendering of findings |
|
||||
| `sidequestion` | Operator Q&A | Asks a human mid-run and suspends intent until answered |
|
||||
| `skills/` | Skill definitions | One `SKILL.md` per subdirectory, loaded from `SkillDir()` |
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user