Compare commits

...
Author SHA1 Message Date
BaaRai 49b9421ed8 Gate the custom HTTP tool's own proxy
With the target gate on, only the tool URL was checked and the proxy in the
tool's proxy field was dialled without a check, so an approved target could
be fetched through any host and port. Read the proxy as a target, as a proxy
named on a Bash command line is: the call waits for its approval, the
request records the proxy without credentials, and the proxy is dialled
through the pinned dialer. The recording and global proxies, required mode
and the gate-off paths are unchanged.
2026-12-04 01:06:32 +01:00
BaaRai 3286e2009c Merge pull request #955 from BaaRai/fix/rm-rule-backslash
fix(intercept): match text deny rules on Bash words as the shell decodes them
2026-12-04 01:06:23 +01:00
BaaRai d92a9e51e2 Match text deny rules on Bash words as the shell decodes them
Regex and string intercept rules were matched on the raw tool input,
but Bash removes quotes and backslashes and decodes $'...' before it
runs a command: r\m -rf, r''m -rf, rm -r''f, rm -R -$'f' and a
backslash-newline inside a word all ran rm -rf while the built-in
recursive-force-delete rule did not match, and so did rm -rf on the
line after another command, because the JSON escape of the newline
glued an "n" to the command name.

A deny or ask rule on a Bash call now also meets the command decoded
with the argv word decoder, the simple commands joined by "; ". Allow
rules are still matched on the text as written. The word decoder now
decodes ANSI-C strings instead of treating them as opaque, which also
lets argv deny and ask rules meet $'nmap' and bash -c $'nmap x'.
2026-12-04 00:43:02 +01:00
BaaRai dcffc35233 Merge pull request #954 from BaaRai/fix/asset-block-ipv6-forms
fix(db): match fuzzy_ip asset rules on canonical IP addresses
2026-12-04 00:42:50 +01:00
BaaRai 44913c1c63 Match fuzzy_ip asset rules on canonical IP addresses
A fuzzy_ip rule compared the raw strings, so a block rule "::1" let
insert_assets register "0:0:0:0:0:0:0:1" or "::0001", and a rule
written expanded missed the compressed address. Match each candidate
as written and in its canonical form, and canonicalize a pattern that
is a whole address; a partial pattern keeps its substring meaning.

cidr rules now also match a zone-qualified address, and a
zone-qualified IPv6 URL host is classified as an IP in insert_assets
and for stored assets, so exact_ip, fuzzy_ip and cidr rules see it.
2026-12-03 23:25:01 +01:00
BaaRai d0645b6370 Merge pull request #940 from BaaRai/fix/alwaysallow-denylist
fix(intercept): refuse always-allow rules for sqlmap, sqlite3 and nmap
2026-12-03 23:24:03 +01:00
BaaRai 978b497ac4 intercept: deny always-allow for sqlmap, sqlite and nmap 2026-12-03 22:59:00 +01:00
BaaRai ba22ce4015 Merge pull request #944 from BaaRai/fix/customtool-secret-origin
fix(server): bind custom HTTP tool secrets to one origin
2026-12-03 22:58:48 +01:00
BaaRai ad5e4e8484 server: bind custom HTTP tool secrets to one origin 2026-12-03 22:34:47 +01:00
BaaRai c1bd9530fe Merge pull request #942 from BaaRai/fix/enrich-sandbox-egress
fix(enrich): apply the sandbox egress policy to panel HTTP probes
2026-12-03 22:34:35 +01:00
BaaRai 6045a2c80f enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:20 +01:00
BaaRai 2653cf57ca enrich: apply the sandbox egress policy to panel HTTP probes 2026-12-03 22:11:11 +01:00
BaaRai 4a4fa45245 Merge pull request #941 from BaaRai/fix/ask-operator-root
fix(server): anchor ask_operator image reads at the task root
2026-12-03 22:10:59 +01:00
BaaRai aeb094d5ef server: anchor ask_operator image reads at the task root 2026-12-03 21:49:41 +01:00
BaaRai eb05248804 Merge pull request #939 from BaaRai/fix/archive-symlink
fix(server): keep task archive packing inside the payload
2026-12-03 21:49:28 +01:00
BaaRai 130fe9a0c4 server: keep task archive packing inside the payload
writeTaskArchivePackage listed each directory of the staged run tree and
then opened its files by full path as root. Code running as the executor
uid with a working directory inside the moved run tree could swap a
listed directory for a symlink, so later children were read through it
and root-only files outside the payload were copied into the archive,
then handed back to the executor group on restore.

Walk and open the payload through an os.Root anchored at it, so no
lookup can leave the payload, and refuse the archive when an opened file
is not the regular file the walk listed. Add regression tests that swap
a directory or a file for an outside, a ../ or an inside symlink right
before the packer opens it, plus guards for existing symlinks and for
link and nested ../ entries on extraction.
2026-12-03 21:24:40 +01:00
BaaRai e4f6de91d2 Merge pull request #938 from BaaRai/fix/session-background-tools
fix(agent): disable Norma background-task tools in sandboxed sessions
2026-12-03 21:23:51 +01:00
BaaRai 6f544185cf Disable Norma background-task tools in sandboxed agent sessions
Norma adds Monitor, TaskOutput, TaskStop and TaskList to each session
unless DisableBackgroundTasks is set, and only the connection test and
the goal decomposer set it. Monitor starts a shell command in the panel
process, outside the sandbox Bash goes through, so with
ARTEX_SANDBOX=required a worker, planner, chat or main-agent model could
run commands in the panel container.

All agent sessions are now built by newSession, which sets
DisableBackgroundTasks while the sandbox is required and turns a nil
tool list into an empty one (Norma reads nil as "install my default
file and shell tools"). With the sandbox off the tools stay: local Bash
needs the same task manager for background runs, the pause kill switch
and the interactive shell. The tool catalogue resolver no longer
returns nil when the tools table cannot be read.

Tests drive each production session (chat, Auto chat, goal
decomposition, planner, main agent, worker, captureRun) under the
required sandbox mode and fail when a background-task tool is offered
to the model, check that no file calls agentcore.NewSession directly,
and check the resolver's catalogue failure path.
2026-12-03 20:27:43 +01:00
BaaRai c03939c1b1 Merge pull request #917 from NeuraMax/fix/sandbox-agent-workdir-path
fix(sandbox): show agents the container work dir, not the host path
2026-12-03 16:23:57 +01:00
BaaRai 6e4c6e7da1 Merge pull request #918 from NeuraMax/feat/content-policy-failover
feat(llmpool): fail over on provider content-policy refusals (HTTP 400)
2026-12-03 16:00:18 +01:00
BaaRai dc828a3251 fix(agent): only mention the container path in sandbox mode
The extra sentence appeared with the host path outside sandbox mode,
where it is false. Add it only when SandboxRequired, pin that with the
host test, and cover workerArtifactSpec in the sandbox test.
2026-12-03 15:58:37 +01:00
BaaRai f4ce2669aa Merge pull request #896 from thecorporatetractor/fix/telegram-oneline
fix(notify): keep untrusted Telegram fields on one line
2026-12-03 14:54:39 +01:00
BaaRai e7c36f7a6a Merge pull request #887 from thecorporatetractor/fix/tamper-hooks-recorded-status
fix(web): read the status of a recorded response in the hook dry run
2026-12-03 14:54:32 +01:00
BaaRai f8f61f1c97 Merge pull request #886 from thecorporatetractor/fix/finding-asset-ipv6-label
fix(db): bracket an IPv6 address in a finding asset service label
2026-12-03 14:54:25 +01:00
BaaRai 3407f8b0a7 Merge pull request #885 from thecorporatetractor/test/web-apifetch-hardening
test(web): cover the apiFetch and sign-out cookie hardening
2026-12-03 14:54:19 +01:00
BaaRai 403bb1f4b3 fix(agent): keep the work dir prompt accurate for file tools
Move promptWorkDir above the artifactSpec doc comment, and stop
claiming that the container absolute path works for file tools: those
run in the panel and take relative paths. Add the sandbox and non
sandbox tests and the CHANGELOG entry.
2026-12-03 14:29:26 +01:00
Maximilian KönigandClaude Opus 4.8 ad7082d339 fix(sandbox): show agents the container work dir, not the host path
In SANDBOX=required mode the agent's filesystem is the worker container's,
where the per-intent run dir is mounted at /workspace/<leaf>.
artifactSpec/workerArtifactSpec told the agent the panel host path under
/app/data/tasks instead. Because only the cwd is remapped into the
container (not absolute paths inside a raw shell command), the agent would
write intermediate artifacts to a read-only /app and silently fail, losing
captured response bodies and scripts.

Add promptWorkDir(), which returns the container path in sandbox mode and
the host path otherwise, and route both specs through it. Also tell the
agent explicitly not to invent paths under /app.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-12-03 14:29:14 +01:00
BaaRai 025b40f221 Merge pull request #901 from renaesop/codex/retest-sandbox
fix(retest): run finding retests in isolated sandboxes
2026-12-03 14:28:48 +01:00
BaaRai d497bd1e65 Merge pull request #847 from Amirhosseing/feat/task-dns
feat(runner): pin task DNS servers on the egress proxy
2026-12-03 14:28:42 +01:00
BaaRai 557ff1cd0e Merge pull request #890 from thecorporatetractor/feat/iam-users-storage
feat(db): users, identities and sessions tables
2026-12-03 14:28:34 +01:00
BaaRai eb11d03e29 Merge pull request #899 from jamesKhor/codex/issue-803-posture-console
Show live target-gate warning in the console
2026-12-03 14:27:34 +01:00
BaaRai ef60f226db Merge pull request #844 from jamesKhor/codex/issue-803-live-posture
Expose authenticated target-gate posture API
2026-12-03 14:27:19 +01:00
Maximilian KönigandClaude Opus 4.8 8a1a7b36ef Address review on #918: health-neutral refusals, exact codes, tests, CHANGELOG
- Exclude content/safety refusals from the failover-health score so repeated
  refusals of one prompt no longer trip a healthy profile's circuit breaker
  (RecordCall: neutral — no Trip, no Pass).
- Match specific provider refusal codes (cyber_policy, content_policy_violation,
  invalid_prompt, Azure content_filter) instead of loose words; drop the bare
  'safety' marker that caught OpenAI safety_identifier / Gemini safety_settings.
- Refresh the stale shouldFailover doc comment.
- Add tests (shouldFailover code matrix, RecordCall refusal-neutrality) and a
  CHANGELOG entry.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-12-03 14:24:53 +01:00
renaesop 6089691658 fix(retest): run finding retests in isolated sandboxes
Give only active finding retests their own runner identity and workspace. Reuse the source task operator-approved egress scope, keep target approvals, and clean up runtime resources on completion or cancellation. Drain conversation cleanup during shutdown. Related to #805; ordinary standalone chats remain unsupported in required mode.
2026-12-03 14:02:17 +01:00
BaaRai 4794d1e4d3 feat(runner): wire ARTEX_TASK_DNS through compose and docs
Add the variable to the runner environment of the three compose files,
document it in .env.example, docs/SANDBOX.md and the CHANGELOG, and
correct the TaskDNS comment: only the egress proxy resolves names.
2026-12-03 14:01:54 +01:00
AmirGhasemi c7b52f297f fix(runner): review feedback — unicode.IsSpace split, Dns only on proxy, parser test
- parseDNSList: split on comma or any unicode.IsSpace rune so tabs and
  newlines in ARTEX_TASK_DNS act as separators, not address bytes.
- proxySpec: add HostConfig.Dns only when the list is non-empty so the
  serialized spec is byte-identical when ARTEX_TASK_DNS is unset.
- workerSpec: drop Dns entirely — the worker sits on the --internal
  task network and resolves through the egress proxy; setting Dns there
  would relay worker DNS around the proxy.
- add cmd/artex-runner/main_test.go: TestParseDNSList covers valid
  comma/space/mixed/newline-separated lists, IPv6, empty and
  separator-only input, invalid entries dropped (with valid kept),
  hostnames dropped, and asserts every output entry parses as an IP.
2026-12-03 14:01:54 +01:00
AmirGhasemi 9eba087697 feat(runner): ARTEX_TASK_DNS — pinned DNS servers for task containers
On Docker Desktop the embedded resolver (127.0.0.11) forwards to the
host's resolver path; when that path is slow or changes underneath
running containers (host roaming networks), per-request DNS in the
worker and egress proxy exceeds resolve budgets or times out entirely.

ARTEX_TASK_DNS (comma/space separated IP list) sets HostConfig.Dns on
every runner-created task container (worker + egress proxy). Empty
keeps Docker's default. Invalid entries are dropped with a warning:
DNS placement is a reliability knob, not a security control — the
egress proxy's scope allowlist remains the security boundary.
2026-12-03 14:01:54 +01:00
Marco Azarmaneche e39bf0ff08 feat(db): users, identities and sessions tables
Storage step of the multi-user work in #790 (phase 2a).

Migration 0029_users.sql adds three tables:
- users: case-insensitive unique username, display name, optional email,
  optional bcrypt hash (SSO-only users have none), account source
  (local now; oidc, saml, ldap, scim later), break-glass flag (local
  accounts only), disabled, login and update times.
- user_identities: links a subject at an identity provider to one user,
  unique on (provider_id, subject). An identity is never linked by
  matching email or username.
- user_sessions: one row per token id (jti) with expiry, last use,
  revocation, user agent and client address.

The migration seeds the existing ARTEX account as the break-glass local
user, so later changes have a row to point to. It does not copy the
password hash: login still reads the auth.password_hash setting, and a
copy would go stale when the password changes. The change that moves
login onto these tables moves the hash with it. An existing ARTEX row is
left unchanged.

Every CHECK constraint is named, so a later migration can alter it by
name. Usernames are at most 128 characters without control characters.
Only a local account can have a password (users_password_local_only), so
an account from an identity provider cannot gain a second way in. The
session user agent is at most 512 bytes and the client address 64; the
address is TEXT because the peer is not always an IP address.

db/users.go adds the store functions later phases need: create and look
up users, set a password, disable a user (which also revokes its
sessions), link and resolve identities, and create, read, touch and
revoke sessions and delete expired ones. The Go side applies the same
limits first (ErrUserInvalid; user agent and address are cut). A session
is created only for an existing, enabled user (ErrUserDisabled), is not
active and cannot be touched while its user is disabled, and a missing
row means no session. DisableUser refuses the last enabled break-glass
user (ErrLastBreakGlass), locking the break-glass rows so two concurrent
calls cannot disable the last two. Expired sessions are deleted by the
database clock, as TouchSession checks expiry.

Nothing reads these tables yet. Login still uses the single ARTEX account
and the setting, so behaviour does not change.
2026-12-03 14:01:19 +01:00
BaaRai 0885bdd720 Merge pull request #780 from thecorporatetractor/feat/k8s-sandbox-backend
feat(sandbox): Kubernetes backend for artex-runner
2026-12-03 14:00:28 +01:00
BaaRai 4fda8db604 Merge pull request #895 from thecorporatetractor/fix/sandbox-reserved-env
fix(sandbox): refuse exec env names that override the proxy, PATH or the loader
2026-12-03 14:00:01 +01:00
BaaRai 972219f887 Merge pull request #868 from sisantaChhatoi/split/task-detail-tabs
refactor(web): useReducer for the task assets, credentials, retests and coverage tabs
2026-12-03 13:55:35 +01:00
BaaRai 443cf894da Merge pull request #916 from sisantaChhatoi/split/chat-dashboard
refactor(web): useReducer for chat, dashboard, shared browser and auth pages
2026-12-03 13:55:28 +01:00
BaaRai e724364da7 Merge pull request #915 from sisantaChhatoi/split/system-settings-skills
refactor(web): useReducer for the system skills, settings, logs, MCP and chat bridge pages
2026-12-03 13:55:22 +01:00
BaaRai 953c361f80 Merge pull request #914 from sisantaChhatoi/split/system-intercept-notify
refactor(web): useReducer for the system intercept and notify pages
2026-12-03 13:55:17 +01:00
BaaRai 2bc5baebbb Merge pull request #913 from sisantaChhatoi/split/system-llm-tools
refactor(web): useReducer for the system LLM, tools and agents pages
2026-12-03 13:55:11 +01:00
BaaRai f3c961db36 test(web): cover the failed-search guard with unchanged data
A successful load after a failed search must clear the error even when
the rows, total and counts match the state the failed search left
behind. Without the !dslError check the reducer returns that state and
the error stays visible.
2026-12-03 13:46:04 +01:00
Marco Azarmaneche 3eedbdc326 fix(sandbox): pass scope entries on in canonical form and refuse IPv6 zones
Review of the scope filter:
- netip.ParseAddr accepts any text after % as an IPv6 zone, commas
  included, so "fe80::1%eth0,10.0.0.0/8" was kept and the comma join
  added 10.0.0.0/8. Zoned addresses are now dropped, and every kept
  entry is passed on in canonical form (p.Masked().String(),
  a.String()), which never holds a comma or space. IPv4-mapped entries
  become the IPv4 range they map.
- The cap was 1,024 entries; a company scope can be larger. It is now
  8,192 entries and 120 KiB per list (the proxy gets each list as one
  environment string, limited to 128 KiB).
- The runner logs dropped entries with the task ID and their values (up
  to 20), so an operator can see why an approved target is refused.
- More names that make a shell or interpreter run extra code are
  refused: SHELLOPTS, BASHOPTS, PS4, IFS, PROMPT_COMMAND, GLIBC_TUNABLES,
  PYTHONSTARTUP, PYTHONHOME, NODE_OPTIONS, PERL5OPT, PERL5LIB, RUBYOPT,
  JAVA_TOOL_OPTIONS, GIT_SSH_COMMAND, GIT_CONFIG_PARAMETERS.
2026-12-03 14:38:15 +02:00
Marco Azarmaneche 3666be70e8 fix(sandbox): refuse exec env names that override the proxy, PATH or the loader
ValidateEnv refused secret-looking names only. An exec request could set
HTTP_PROXY, HTTPS_PROXY, ALL_PROXY or NO_PROXY (any case) and send the
command around the egress proxy, or set PATH, LD_* (LD_PRELOAD,
LD_LIBRARY_PATH, LD_AUDIT, ...), BASH_ENV, ENV, GCONV_PATH or PYTHONPATH
and run code before the command. In the Docker backend the exec Env
overrides the worker container's env, so this applied there.

- ValidateEnv refuses these names with 400. FilterPanelEnv drops them, so
  the panel does not send a request the runner refuses.
- ValidateExecRequest checks every scope entry: a domain must be a host
  name (optionally "*."), a CIDR entry a valid prefix or address. Both
  backends join the entries with commas into the egress proxy
  environment, so "1.2.3.4/32,10.0.0.0/8" added an entry nobody
  approved. Invalid entries (including any with a comma or a space) are
  dropped whole, never split, and the valid ones are kept: the panel
  builds scope from free-text fields, and a narrower scope fails closed
  at the deny-by-default proxy. The runner logs how many entries it
  dropped. More than 1,024 entries in either list is still a 400.
2026-12-03 14:37:44 +02:00
BaaRai 2b3ed3829c Merge pull request #701 from renaesop/codex/allow-constraints-additive
fix(agent): preserve target allowlists and prevent scope evasion
2026-12-03 13:36:53 +01:00
BaaRai 9dd540f188 Merge pull request #880 from Hop89/feat/proxy-pool-store
feat(db): store proxy pool entries behind a masked API (part 1 of 4, #545)
2026-12-03 13:01:18 +01:00
BaaRai de80783e16 Merge pull request #706 from jedrzejsieracki/fix/prompt-cache
fix(agent): cache the goal decomposer's system prompt
2026-12-03 13:01:10 +01:00
Maximilian KönigandClaude Opus 4.8 9fc8fd6bd1 feat(llmpool): fail over on provider content-policy refusals (HTTP 400)
shouldFailover treated every 400 as "fails identically everywhere" and
never failed over. But a provider content/safety refusal (e.g. OpenAI's
cyber_policy block) is not identical everywhere: a different, non-refusing
model in the chain may well accept the same request. For an offensive-
security tool that is the difference between a dead run and a working one.

Narrow the 400 case: fail over only when the error body carries a content/
safety-refusal marker (cyber_policy, content_policy, invalid_prompt,
safety, ...). A malformed or over-long 400 still fails identically
everywhere and is not retried.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-12-03 10:59:29 +01:00
sisantaChhatoiandClaude Opus 5.5 8379522e4c refactor(web): useReducer for chat, dashboard, shared browser and auth pages
Converts the chat page, chat view and draft chat, the dashboard, the
shared browser page, and the login and setup pages to typed reducers in
_state/. The selected conversation and approval focus stay in the URL.

The chat list poll (2 s) and the dashboard live (5 s) and system (15 s)
polls return the same state when the data is unchanged.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:47:14 +05:30
sisantaChhatoiandClaude Opus 5.5 f8c639565a refactor(web): useReducer for the system skills, settings, logs, MCP and chat bridge pages
Converts these pages to typed reducers in _state/, on the shared list
and request slices. The chat bridge status poll returns the same state
when the bridge is unchanged.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:43:02 +05:30
sisantaChhatoiandClaude Opus 5.5 a4f031c852 refactor(web): useReducer for the system intercept and notify pages
Converts the intercept rules page and judge card, the asset intercept
page, and the notify page and its delivery list to typed reducers in
_state/, on the shared list, request and pagination slices.

InterceptPage's regexErr state is removed: it was only ever set to "",
so its error message could never render.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:40:17 +05:30
sisantaChhatoiandClaude Opus 5.5 bdc762854f refactor(web): useReducer for the system LLM, tools and agents pages
Converts the LLM page and profile sheet, the tools page, tool editor and
custom tool dialog, and the create-agent dialog to typed reducers in
_state/, on the shared request slice.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:38:02 +05:30
sisantaChhatoiandClaude Opus 5.5 7dd9fcfa32 fix(web): correct assets/credentials reducer comments; add review tests
The unchanged-poll comments now say what the code guarantees: the same
state object is returned, so React can bail out of the update. The
assets list comment now says when loaded is reset (first load and a
manual refresh, not tab, page or query changes).

Tests, as requested in review: a poll that changes one nested field of
one row updates that row (assets and credentials), and a successful load
after a failed search clears the error and shows the rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:28:42 +05:30
Jędrzej SierackiandClaude Opus 5.5 7a07c64118 fix(agent): cache the goal decomposer's system prompt
DecomposeGoalsWithProvider built its session without a DynamicBoundary,
and Norma reads 0 as "no cache breakpoint", so every turn of goal
decomposition resent its tools and system prompt uncached on Anthropic
profiles. It now sets 1 for its single static segment, the breakpoint

docs/context-telemetry.md still said deferredSystem returns 0 without
a global deferred-MCP block. It now describes the always-on boundary
and what system_dynamic holds on each lane.

Tests: TestDecomposeGoalsValidStructuredToolCallAccepted checks the
boundary on every request (needs Postgres); it fails with the fix
reverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:40:43 +01:00
Codex 832cdda1e4 fix(agent): preserve target allowlists and prevent scope evasion 2026-12-03 14:32:30 +08:00
James Khor c8f27c7f3c feat(web): show live target-gate posture warning 2026-12-03 11:17:38 +08:00
James Khor b9bc78f20e feat: expose authenticated target-gate posture API 2026-12-03 11:17:33 +08:00
Grady May a383e5bcb2 feat(db): store proxy pool entries behind a masked API
Part 1 of 4 of the proxy pool design in #545: storage and a CRUD API.
Nothing activates an entry yet, so the global proxy is unchanged.

- Migration 0028 adds proxy_pool: a unique keyed address hash, at most
  one active entry (partial unique index), a CHECK that the active entry
  is enabled, and nullable egress_ip, last_check_at and last_check_ok for
  the health check.
- Addresses are normalized, sealed at rest (AAD proxy_pool.address) and
  covered by the startup key check and key rotation. Uniqueness uses an
  HMAC under a sub-key kept on secretBox; RotateSecretKey locks the table
  and rehashes in its transaction, and pool writes seal under that lock.
- GET/POST /api/proxy-pool and PATCH/DELETE /api/proxy-pool/{id} never
  return an address; a masked address on update keeps the stored one.
2026-12-02 22:05:05 -05:00
Marco Azarmaneche 2e516c5125 fix(sandbox): unique pod names per generation and stricter probes in the Kubernetes backend
- Each worker and proxy pod gets a new name per generation
  (artex-w-<hash>-<6 hex>). Exec targets the exact pod of the task state,
  so an exec delayed at the API server fails with 404 instead of running
  in a replacement pod before that pod passed its network probes.
- setupTask lists the task's pods by label and deletes every pod except
  the ones it keeps, with a UID precondition, before it creates new ones.
  Same-named pods are no longer deleted without an ownership check.
- Recover adopts only pods whose name matches artex-[wp]-<32 hex>-<6 hex>
  and whose name, labels and task annotation agree.
- podAlive returns an error for API failures. Only 404, a UID mismatch, a
  deletion timestamp, or a pod that is not running and ready count as
  dead. On other errors (a cancelled request too) the exec fails and the
  task's pods and policies stay.
- waitPodReady fails fast on CrashLoopBackOff and on exited containers.
- The deny probes print one token per outcome. Only timed out, refused or
  unroutable connections count as blocked. Any other result (missing
  timeout binary, failed fork, no API env) fails setup at once.
- Probe output, stderr and HTTP client errors go to the runner log only.
  The returned errors are generic. A cancelled API request returns a
  cancellation error, not "runner unavailable".
- Add fd20:ce::254/128 (GCE IPv6 metadata) to the never-reachable ranges.
- Document that ARTEX_KUBE_CLUSTER_CIDRS must also list the API server
  endpoint addresses when they lie outside the cluster ranges (managed
  clusters).
- Exec, Kill and Delete reject task IDs with surrounding whitespace.
- go.mod: gopkg.in/yaml.v3 back to indirect (go mod tidy).
- Test: a cancelled exec keeps the task. The scope and probe tests move to
  the test PR to stay inside the size limit.
2026-12-03 04:03:17 +02:00
Marco Azarmaneche 0ab3b9ef23 test(web): check the sign-out cookie keeps path=/
The route-guard cookie is written with path=/; expiring it without the
same path leaves it in place.
2026-12-03 03:36:23 +02:00
Marco Azarmaneche a969dc51bc fix(web): colour the status of a recorded response head
StartLine in http-code-block.tsx had the same HTTP/<version> pattern, so
recorded responses ("HTTP <status>") on the traffic, replay and evidence
views showed no status colour. Make the version optional there too.
2026-12-03 03:36:05 +02:00
BaaRai 507309c94d Merge pull request #888 from BaaRai/fix/web-auth-401-followup
fix(web): keep the session on auth 401s and pin the API tests
2026-12-03 02:28:46 +01:00
Marco Azarmaneche d92a02faef fix(sandbox): close IPv4-mapped and unspecified ranges in the Kubernetes scope
From a second review of the backend:
- Scope CIDRs written as IPv4-mapped IPv6 (::ffff:10.0.0.0/104) are read
  as the IPv4 range they map, so the private-range filter and the
  never-reachable excepts apply to them. netip treats the two families as
  distinct, so such an entry skipped both.
- The never-reachable list adds 0.0.0.0/8 and :: (they reach the proxy's
  own host), ::ffff:0:0/96 and link-local through NAT64
  (64:ff9b::a9fe:0/112).
- ARTEX_KUBE_CLUSTER_CIDRS and ARTEX_KUBE_PROXY_DENIED_CIDRS refuse /0
  (an except equal to its block is rejected by the API server) and
  IPv4-mapped prefixes (they would never match).
2026-12-03 03:16:02 +02:00
Marco Azarmaneche cda87d8dfc fix(notify): keep untrusted Telegram fields on one line
Slack flattens titles, types and assets with OneLine so a newline in an
untrusted field cannot forge another line (TestSlackKeepsUntrustedFieldsOnOneLine).
Telegram did not: a finding named "a\n2. Critical · fake entry" added a
forged entry to a digest, and a newline in the vulnerability class or an
asset added a forged line to a single notification. Flatten the digest
line and the Type and Assets fields the same way.
2026-12-03 03:13:47 +02:00
BaaRai 2f065a958e Merge pull request #882 from AdrianSantamariaR/claude/dropdown-close-form-focus-824957
fix(web): keep side-panel forms open when you close a dropdown
2026-12-03 02:11:27 +01:00
BaaRai 95afea7d5c Merge pull request #878 from thecorporatetractor/refactor/route-permissions
refactor(server): register API routes with a permission
2026-12-03 02:04:04 +01:00
Marco Azarmaneche 1c262d3af6 feat(sandbox): Kubernetes backend for artex-runner
ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own
egress-proxy pod, created through the Kubernetes API (kube_client.go) with no
container runtime socket. Per-task NetworkPolicies are applied before the pods
and removed after them; the runner proves they are in effect before the first
command, runs commands through pods/exec under env -i and artex-exec-wrap, and
re-adopts task pods after a restart. Unit tests run against a fake API
server; this commit keeps the tests for the review items, and the other
unit tests and the live cluster test follow in a separate PR.

Changes since the first review (502e42d):

NetworkPolicies and scope:
- Delete and failed setups delete the task's pods and wait until they are
  gone before removing the service and, last, the policies. If a pod
  cannot be deleted, the policies stay and the task stays tracked. Pods
  get a 1s grace, not 0: a zero grace removes the API object before the
  kubelet has stopped the containers.
- applyPolicy replaces an existing policy only when it carries the
  runner's labels for the same task, and sends its resourceVersion.
- ARTEX_KUBE_PROXY_DENIED_CIDRS adds to DefaultProxyDeniedCIDRs instead
  of replacing it. An empty DNSPodLabels map falls back to k8s-app=kube-dns.
- No scope opens the cluster: ARTEX_KUBE_CLUSTER_CIDRS (pod, service and
  node CIDRs) plus metadata, loopback, link-local and the API server
  address form a never-reachable list. Each scope ipBlock gets them as
  except (a block inside one is dropped), the public rule excepts them,
  and the proxy refuses them through ARTEX_NEVER_CIDRS (new
  EgressPolicy.Never; Docker does not set it). Without
  ARTEX_KUBE_CLUSTER_CIDRS, scope CIDRs overlapping private, loopback or
  link-local ranges are dropped (logged), so the scope fails closed.
- Isolation does not rely on an outside default-deny policy: every task
  pod has its own Ingress+Egress policy, adopted tasks get theirs applied
  again, and before the first command the runner checks that the worker
  reaches neither the API server nor a public address directly and that
  the proxy cannot reach the API server; setup fails otherwise. A scope
  change replaces the worker too, so the checks run in a worker no
  command has used.
- The proxy pod uses ndots 1, so scope names are not first looked up as
  cluster names.

Exec:
- The worker base env comes after the request env in the env(1) argv.
  Refusing PATH, proxy and loader variables (LD_*, BASH_ENV, ...) in a
  request is a separate change to the shared ValidateEnv, which also
  covers the Docker backend.
- Any exec error after the stream started (cancel, broken stream, read
  limit) kills the worker's processes, and so does a wrapper timeout
  (exit 124 after at least timeout_ms, the Docker rule).
- Exec, Kill and Delete validate the task ID; Exec validates the request.

Concurrency and cleanup:
- Kill takes the task lock; stored tasks are copied, never changed in
  place. A Kill caused by an exec acts only on the worker pod UID that
  ran it; pod deletes carry a UID precondition.
- An exec queued behind a Delete returns ErrNotFound instead of creating
  the task again. Per-task locks are reference counted and removed.
- A failed setup removes what it created, found by label (a foreign
  object with the same name stays). Delete returns ErrNotFound only when
  no object of the task exists.
- Recover adopts only pods named artex-w-/artex-p-<hash> and services
  with a real ClusterIP; adopted tasks are re-checked on first use.
- Scope hash: full SHA-256; task object names use 128 bits.

Config: http:// API servers are refused, the tasks and audit sub paths
must not be ".", equal or nested, and NewKubernetesBackend documents what
the deployment must provide (PID limits, restricted namespace, quotas,
shared volume, shared Kill).
2026-12-03 03:03:09 +02:00
Marco Azarmaneche 37e4bb7f2f fix(web): read the status of a recorded response in the hook dry run
The traffic recorder stores the response head as "HTTP <status>" with no
version (traffic/traffic.go, stream.go, external.go). parseRawResponse
required "HTTP/<version> <status>", so the match always failed and a dry
run from a recorded exchange used status 200, whatever the response was.
Make the version optional.
2026-12-03 02:02:42 +02:00
Marco Azarmaneche e9d6c48737 fix(db): bracket an IPv6 address in a finding asset service label
assetRow.label joined the host and port of a service asset with a plain
colon, so an IPv6 service on port 445 was labelled 2001:db8::1:445, which
reads as a longer IPv6 address. Build it with net.JoinHostPort, as #845 did
for the server's asset label. IPv4 and domain labels are unchanged.
2026-12-03 02:01:47 +02:00
Marco Azarmaneche 66dc0da802 test(web): cover the apiFetch credentials, redirect and sign-out cookie hardening
d597c15 made apiFetch set credentials: "same-origin" and redirect: "error"
after ...init, and made auth.clearToken expire the route-guard cookie with
the attributes setToken writes. Two tests pin both: a caller that asks for
credentials: "include" and redirect: "follow" still gets the safe values,
and sign-out expires the cookie with SameSite=Lax, plus Secure on HTTPS.
Both fail if either change is reverted.
2026-12-03 01:57:15 +02:00
AdrianSantamariaRandClaude Opus 5.5 5b711855a1 fix(web): treat an open Base UI Combobox as an open popup; test the guard
With the category Combobox of the New task sheet open, an overlay click
closed the whole sheet: isRadixOverlayOpenNow did not match the Base UI
popup, whose open state is data-open, not data-state. Add
[data-slot='combobox-content'][data-open] to the selector.

Add web/src/lib/utils.test.mjs, run by test:reducers: a DOM-free test of
preventDismissUnlessOverlayClick with a stub document, covering Select,
popper content, Combobox, menu triggers, the open sheet/dialog trigger
and an expanded Collapsible. The alias loader now adds the JSON import
attribute so tests can import modules that depend on @/i18n.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:47:42 +01:00
Marco Azarmaneche eb045647cf fix(server): apply the route permission and test the production chain
requirePerm now applies the recorded permission instead of only checking
that one exists: a perm.Authenticated pattern answers 401 without a valid
session. requireAuth exempts /api/auth/ by prefix, so a wildcard pattern
such as "GET /api/{kind}/items" would otherwise be public for
/api/auth/items.

Handler builds its chain with handlerFor, and TestUntaggedRouteIsForbidden
uses handlerFor, so removing requirePerm from the production chain fails
the test. A wildcard route is tested with a path under /api/auth/.

TestNoRawRouteRegistration allows only root.Handle("/api/", ...) and
root.HandleFunc("/", ...) in server.go; any other root route would skip
requireAuth.

TestHandlerDeniesAuthenticatedRoutesWithoutSession checks every
authenticated route through the real Handler.
2026-12-03 01:18:22 +02:00
Marco Azarmaneche fe121a2cea refactor(server): register API routes with a permission
Every /api route is now added with s.handle(mux, pattern, perm, h), which
records the permission the route needs. There are two permissions for now:
perm.Public for the routes requireAuth already exempts (/api/auth/*,
/api/health, /api/ready) and perm.Authenticated for all others.

A new check runs after requireAuth and answers 403 when the matched pattern
has no recorded permission, so a route added with a plain HandleFunc call is
denied instead of served. requireAuth itself is unchanged.

Tests check that every route has a permission, that the public routes are
exactly the ones requireAuth exempts, that no file registers a route outside
s.handle, and that an untagged route returns 403.
2026-12-03 01:12:39 +02:00
AdrianSantamariaRandClaude Opus 5.5 693825946e refactor(web): share the overlay-dismiss guard between Sheet and Dialog
SheetContent and DialogContent each carried a copy of the same
onInteractOutside guard, and losing one copy is how the Sheet guard
disappeared. Move it to preventDismissUnlessOverlayClick in lib/utils.ts
and call it from both. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:25:56 +01:00
AdrianSantamariaRandClaude Opus 5.5 611f232201 fix(web): let a sheet or dialog opened by its trigger close on overlay click
isRadixOverlayOpenNow treated any element with aria-expanded=true and
data-state=open as an open popover. The trigger of the open sheet or
dialog itself (aria-haspopup=dialog) and an expanded Collapsible match
that selector, so with the guard in place an overlay click never closed
a sheet or dialog that was opened through SheetTrigger/DialogTrigger
(Tasks category management, Agents create dialog). Count only triggers
that announce a non-dialog popup; popover content is still matched by
the Radix popper wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:21:05 +01:00
AdrianSantamariaRandClaude Opus 5.5 60eaf6719d fix(web): keep side-panel forms open when dismissing a dropdown
With a Select/Popover open inside a Sheet, any click (inside the form or
on the backdrop) closed the whole sheet and dropped unsaved input. The
onInteractOutside guard added in aef0376 was lost when 32ec7fe restored
the pre-fix sheet.tsx. Restore it, mirroring DialogContent: only a click
on the overlay with no popover open closes the sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:21:05 +01:00
sisantaChhatoiandClaude Opus 5.5 7dbf935f79 refactor(web): useReducer for the task assets, credentials, retests and coverage tabs
Converts the remaining task detail tabs to typed reducers in
tasks/detail/_state/, on the shared list and pagination slices.
The assets (10 s) and credentials (15 s) polls return the same state
when nothing changed, so an unchanged poll does not re-render the tab.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:08:22 +05:30
187 changed files with 13771 additions and 1914 deletions
+5
View File
@@ -71,6 +71,11 @@ ARTEX_LLM_PRIVATE_ENDPOINTS=
# list (IP, IP:port or host:port) sends queries only to those resolvers.
# ARTEX_DNS_RESOLVERS=
# Pinned DNS servers for the task containers (optional). The egress proxy is the only
# container that resolves target names; this overrides Docker's embedded resolver for it.
# Comma- or space-separated IPs. Unset keeps Docker's default.
# ARTEX_TASK_DNS=
# Run budgets (optional). Unset or 0 = unlimited, nothing changes. TASK_* caps a whole task
# (planner rounds and all its workers); INTENT_* caps one worker run. Kept in memory: a
# restart, or a revive of a finished task, starts a fresh budget.
+22
View File
@@ -6,6 +6,15 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **A custom HTTP tool's own proxy goes through the target gate.** With the gate on, only the tool URL was checked: the proxy in the tool's `proxy` field was dialled without any check, so a tool whose target was approved could send its request to any host and port, loopback and private addresses included, through a proxy nobody approved. With the gate on, the proxy's host and port are now a target like the URL, as a proxy named on a Bash command line is: the call waits for an approval or is refused, the approval request shows the proxy without its credentials, and the connection to the proxy goes through the gate's dialer. That connection is checked and dialled as a direct hop: the approval pins the addresses it resolved rather than the name alone, so a proxy name that later answers another address is refused instead of being dialled unpinned. The recording and global proxies (`use_recording_proxy`) are unchanged. `ARTEX_SANDBOX=required` is unchanged: the sandbox egress policy already checks the proxy connection. With the gate off (no task scope, a task with the gate off, or the custom tool test endpoint) the proxy is not checked, as before, and neither is the tool URL, which can already name a loopback or private address in that mode. Behaviour change: with the gate on, a tool that uses its own proxy now raises an approval request for the proxy host and port (or is refused when none is granted) until the proxy is approved for the task.
- **Text deny and ask rules see a Bash command as the shell decodes it.** Regex and string intercept rules on `tool_input` were matched on the raw text, but Bash removes quotes and backslashes and decodes `$'...'` before it runs a command, so `r\m -rf ./x`, `r''m -rf`, `"r"m -rf`, `/bin/r\m -rf`, `rm -r''f`, `rm -R -$'f'` or a backslash-newline inside a word ran `rm -rf` while the built-in recursive-force-delete rule did not match; so did `rm -rf ./x` on the line after another command, since the input encodes the newline as `\n` and its `n` hid the word boundary. A deny or ask rule on a Bash call now also meets the command decoded with the word decoder argv rules use: the simple commands joined by `; `, every word with its quotes, backslash escapes and line continuations removed, a word with an expansion kept as written. This covers every built-in regex rule and operator deny and ask rules; allow rules are still matched on the text as written only. The word decoder now also decodes ANSI-C strings (`$'r\x6d'`), so argv deny and ask rules meet `$'nmap'` and `bash -c $'nmap x'` too.
- **`fuzzy_ip` asset rules and the URL host check match every spelling of an IP address.** `fuzzy_ip` compared the raw strings, so a block rule `::1` let `insert_assets` register `0:0:0:0:0:0:0:1` or `::0001`, and a rule written expanded missed the compressed form. The rule is now also matched against the canonical form of each address (zeros compressed, lower case, IPv4-mapped addresses unmapped, zone dropped), and a pattern that is a whole address is canonicalized too; a partial pattern such as `10.0.` keeps its substring meaning. `cidr` rules now match a zone-qualified address (`fe80::1%eth0`), and a zone-qualified IPv6 URL host (`http://[fe80::1%25eth0]/`) is classified as an IP instead of a domain, so `exact_ip`, `fuzzy_ip` and `cidr` rules see it, in `insert_assets` and for stored assets.
- **The always-allow denylist refuses `sqlmap`, `sqlite3` and `nmap`.** An argv allow rule covers every flag, and each of these programs has a flag or script hook that runs code chosen by the caller: `sqlmap --eval`, `sqlite3 .shell` and `nmap --script` with a Lua NSE file. After an operator clicked "always allow" on a harmless call, later calls of the same program matched the rule and skipped the fallback judge, so those flags ran arbitrary code. The three names join the code-owned denylist; `sqlite3` is stored as `sqlite` because `argvProgramName` strips the version suffix, and `sqlmap.py`/`sqlmapapi.py` reduce to their bare names through the same extension stripping. Allow rules already stored for these programs stop matching because the denylist is checked again at match time: their calls go back to the judge or to an ask rule, and the rows stay in the rules table.
- **HTTP custom tools bind stored headers and body to one origin.** A tool saved with a masked secret kept it while the literal url template stayed the same, so a template with a parameterized host (`https://{host}/collect`) could send the stored `X-API-Key` and body to an attacker-chosen host. A redirect from the configured host could also replay them to another origin: Go copies custom headers, and 307/308 replay the body. A secret-bearing HTTP tool now needs a fixed scheme, host and port in its url template, the rendered url must stay on that origin, and a redirect to another origin is refused; an edit that keeps a masked value may not add or change the proxy either (clearing it is allowed, the request then goes to the fixed origin). Tools without stored headers or body are unchanged. Every non-empty header value and body counts as stored, so a saved tool with a parameterized url and a constant header (`Content-Type`) or a body template is now refused at save and at run, and a secret-bearing tool whose API redirects to another host, port or scheme (apex to `www`, `http` to `https`, a CDN) now fails on that redirect.
- **Panel-side asset enrichment obeys the sandbox egress policy.** `insert_assets` starts an HTTP probe in the panel process, and the probe dialed through the recording proxy whenever the target gate was off, with no destination check: a worker could submit a service URL for loopback, RFC1918 or the cloud metadata address and read the status, length and title with `list_assets`, or the full body through the traffic store. While `ARTEX_SANDBOX=required`, the probe now uses the task's `sandbox.EgressPolicy` for the URL, every redirect and every connection, resolves and pins the address itself, then hands that address to the target gate's pinned dialer as WebFetch and the http tool do (a probe without a target scope, or one a gated scope does not cover, still dials nothing), and uses neither the recording nor the environment proxy. A task without an approved scope probes nothing, as in the rest of the sandbox.
- **`ask_operator` reads run-directory images through a task-rooted handle.** The copy path resolved the asking run directory with `EvalSymlinks` and then opened the resolved path, so a worker that replaced its run directory with a symlink to `/` made the confinement root `/`: an absolute `image_path` to a symlink named `*.png` could have the panel copy `/proc/1/environ` or `/app/keys/jwt.key` into `tasks/<id>/uploads`, where the worker reads it. The read and the upload write are now both anchored with `os.Root` at `tasks/<id>`; the run directory must be a real directory, no path component may be a symlink, the opened file must be the one `Lstat` saw, and the copy is bounded to 10 MB. Existing `..`, outside-path and non-image refusals are unchanged.
- **Task archives no longer follow a directory swapped for a symlink while the task is packed.** The packer, running as root, listed each directory of the staged run tree and then opened its files by full path, so code running as the executor uid that kept a working directory inside the run tree could replace a listed directory with a symlink (for example to `/app/keys`) and have root-only files such as the session signing key copied into the archive, then read them back from the run directory after a restore. The packer now walks and opens the payload through an `os.Root` anchored at it, so no lookup can leave the payload, and refuses the archive when a file it opens is not the regular file the walk listed (device and inode compared). Symlinks already present in the run tree are still skipped and never followed. Behaviour change: an archive whose run tree changes this way while it is packed fails instead of completing, and the task stays in place.
- **Agent sessions no longer offer Norma's background-task tools.** Norma adds `Monitor`, `TaskOutput`, `TaskStop` and `TaskList` to every session that does not opt out, and only the connection test and the goal decomposer opted out. `Monitor` starts a shell command in the panel process, not through the sandbox that `Bash` uses, so in `ARTEX_SANDBOX=required` mode a worker, planner, chat or main-agent model could run commands in the panel container, outside the task's worker, and read or write other tasks' workspaces and transcripts. Every agent session is now built through one constructor. It turns these tools off while the sandbox is required, and always for a session that has neither `Bash` nor the interactive shell, so an orchestration agent cannot gain a shell through `Monitor`. Sessions that do have `Bash` or `shell_*` keep them when the sandbox is off: their background runs, PTY sessions and the pause kill switch depend on the same task manager. The constructor also turns a nil tool list into an empty one, because Norma reads nil as "use my own default tools" and installs its unconfined `Bash` and file tools; the tool catalogue resolver also returns an empty list instead of nil when the tools table cannot be read, the case of the Auto chat agent, whose base list is empty.
- **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.
@@ -18,22 +27,35 @@ All notable changes to this project are documented in this file. The format is b
### Added
- **Kubernetes sandbox backend for `artex-runner`.** With `ARTEX_RUNNER_BACKEND=kubernetes` each task runs in a worker pod behind its own egress-proxy pod, created through the Kubernetes API with no container runtime socket. The worker runs as uid/gid 10001 with `runAsNonRoot`, a read-only root filesystem, all capabilities dropped, `seccomp: RuntimeDefault`, no service-account token and no service links, and mounts only its task directory. Per-task NetworkPolicies are created before the pods and deleted after them: the worker can reach only its own proxy, and the proxy only cluster DNS, public addresses and the task's scope CIDRs. No scope opens the cluster's own ranges, the API server or cloud metadata: set `ARTEX_KUBE_CLUSTER_CIDRS` to the pod, service and node CIDRs, plus the API server endpoint addresses when they lie outside them as on managed clusters (without it, private scope CIDRs are dropped). The runner waits until the policies are in effect before the first command, runs commands through `pods/exec`, and re-adopts task pods after a restart.
- **User, identity and session tables (#790).** Migration `0029_users.sql` adds `users` (case-insensitive unique username, optional email and password hash, account source, break-glass flag, disabled time), `user_identities` (an identity-provider subject linked to one user; never matched by email) and `user_sessions` (one row per token id, with expiry and revocation), plus their store functions in `db/users.go`. The existing `ARTEX` account is seeded as the break-glass local user; its password stays in the setting login reads. Nothing reads these tables yet: login and sessions are unchanged.
- **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.
- **Proxy pool storage and API (#545, part 1 of 4).** A `proxy_pool` table (migration `0028_proxy_pool.sql`) and an operator API, `GET/POST /api/proxy-pool` and `PATCH/DELETE /api/proxy-pool/{id}`, store labelled candidates for the global proxy. Nothing activates an entry yet: the global proxy and every route that follows it are unchanged. Addresses (`http`, `https` or `socks5`, optional `user:pass`) are normalized (lower-case scheme and host, explicit default port, no path or query), sealed at rest (AAD `proxy_pool.address`) and never returned: reads give `__masked__` and `address_set`, and a masked address on update keeps the stored one. Uniqueness is on an HMAC of the normalized address under a sub-key of the secret key, recomputed by key rotation, since sealing is randomized. The schema allows at most one active entry and only an enabled one, and the API refuses to disable or delete the active entry (409). `egress_ip`, `last_check_at` and `last_check_ok` are left for the health check and are null until one runs.
- **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.
- **Pinned DNS servers for task containers.** `ARTEX_TASK_DNS` sets the resolver of the task's egress proxy, the only container that resolves target names. Comma- or space-separated IPs; invalid entries are dropped with a warning; unset keeps Docker's embedded resolver.
- **`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
- **The LLM failover chain treats a provider content/safety refusal as a reason to try the next profile, not a dead end.** `shouldFailover` returned `false` for every HTTP 400, on the grounds that a malformed request fails identically everywhere. That holds for a malformed or over-long request, but not for a provider content/safety refusal: OpenAI returns 400 `cyber_policy` for offensive-security prompts (and Azure returns 400 `content_filter`), while a different, non-refusing model configured later in the chain may accept the same request — so the chain now fails over on a 400 whose body carries a known refusal code (`cyber_policy`, `content_policy_violation`, `invalid_prompt`, `content_filter`). Matching is on those specific codes, so request-shape 400s that merely contain the word *safety* (OpenAI's `safety_identifier`, Gemini's `safety_settings`) are not retried. Because a refusal is the model's own policy and not an outage, it is excluded from the profile's failover-health score: repeated refusals of one prompt no longer trip a healthy profile's circuit breaker.
- **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
- **Agents are shown the container work directory in sandbox mode.** In `ARTEX_SANDBOX=required` mode the prompt named the panel host path under `/app/data/tasks`, so a script that used an absolute path wrote to the read-only `/app` and lost its captured responses. The prompt now names the worker path (`/workspace/...`) and tells the agent to use relative paths for shell and file tools.
- **Finding retests get an independent sandbox in required mode** (related to #805): the first retest turn uses its own worker and workspace, shared by Bash and file tools, and inherits only the source task's operator-approved egress scope. Completion, failure and cancellation remove the worker, proxy and network while retaining evidence files. Shutdown waits for conversation cleanup. Standalone chats and follow-up discussion of sealed retests still have no execution context.
- **The goal decomposer caches its system prompt**: `DecomposeGoalsWithProvider` built its session without a `DynamicBoundary`, and Norma reads 0 as "no cache breakpoint", so each turn of goal decomposition resent its tools and system prompt uncached on Anthropic profiles. It now sets 1, the same breakpoint #836 gave the other agents without global MCP tools.
- **Exec requests can no longer set the worker's proxy, `PATH` or interpreter start-up variables, or smuggle scope entries.** The runner accepted any non-secret env name in an exec request. It now refuses with 400 the proxy variables (any case), `PATH`, `LD_*`, and variables that make a shell or interpreter run extra code (`BASH_ENV`, `ENV`, `SHELLOPTS`, `PS4`, `NODE_OPTIONS`, `PERL5OPT`, `PYTHONSTARTUP` and similar); the panel drops them from the env it forwards. Scope entries are checked one by one and passed on in canonical form: an entry that is not a valid domain, prefix or address, or an IPv6 address with a zone, is dropped and logged with the task, never split at a comma, so `1.2.3.4/32,10.0.0.0/8` or `fe80::1%x,0.0.0.0/0` can no longer add scope nobody approved. Scope lists are capped at 8,192 entries and 120 KiB each.
- **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.
+1 -1
View File
@@ -27,7 +27,7 @@ import (
// contiguous run is coalesced into a single record so the trace shows whole
// messages, not dozens of fragments.
func captureRun(ctx context.Context, opts agentcore.Options, input string, emit func(db.Activity)) (string, harness.TerminalReason, error) {
s := agentcore.NewSession(opts)
s := newSession(opts)
defer s.Close() // release the session's background-task manager (temp dir + processes)
return captureRunSession(ctx, s, input, emit)
}
+22 -2
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -185,6 +186,21 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
if !sessionDirInside(c.workDir, sessionWorkDir) {
return "", fmt.Errorf("invalid session id %q", sessionID)
}
// Sandboxed retests share the runner's task workspace with file tools. Bind
// this exception to the retester, conversation, and exact task directory;
// ordinary conversations keep the sessions/ boundary above.
if info, ok := SandboxRunInfoFromContext(ctx); ok && strings.HasPrefix(info.TaskID, "retest-") {
raw, isConversation := strings.CutPrefix(sessionID, "conv-")
id, err := strconv.ParseInt(raw, 10, 64)
taskID := "retest-" + raw
taskDir := filepath.Join(c.workDir, "tasks", taskID)
if agentKey != db.FindingRetestAgentKey || !isConversation ||
err != nil || id <= 0 || strconv.FormatInt(id, 10) != raw ||
info.TaskID != taskID || info.TaskDir != taskDir {
return "", fmt.Errorf("invalid retest workspace for session %q", sessionID)
}
sessionWorkDir = taskDir
}
// A run directory like the task ones, created the same way (makeRunDir).
makeRunDir(c.workDir, sessionWorkDir)
ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir)
@@ -201,7 +217,11 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
bashEnv = proxyEnv(c.proxyAddr, c.proxyCACert) // Bash subcommands go through the proxy + trust the CA by default
}
system, boundary := deferredSystem(chatSystem(agentKey, c.workDir, sessionWorkDir), def)
systemPrompt := chatSystem(agentKey, c.workDir, sessionWorkDir)
if info, ok := SandboxRunInfoFromContext(ctx); ok && strings.HasPrefix(info.TaskID, "retest-") {
systemPrompt += "\n**Sandbox paths**: Bash runs in /workspace, which is the same directory as the file-tool working directory above. Prefer relative paths when sharing files between Bash and file tools; their absolute path prefixes differ."
}
system, boundary := deferredSystem(systemPrompt, def)
opts := agentcore.Options{
Provider: c.prov,
SystemPrompt: system,
@@ -256,7 +276,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
// experimental feature: when enabled, noa takes over context compression (archive centralized under <workDir>/noa/<SessionID>, persistent).
enableNoa(&opts, c.noaEnabledFn, c.workDir, "chat-"+sessionID, noaWarn("chat-"+sessionID))
ctx = attachSideCapture(ctx, &opts)
s := agentcore.NewSession(opts)
s := newSession(opts)
defer s.Close()
// reload prior conversation so the agent has context across turns (each Chat is
// a fresh session). First turn: no file yet → Resume loads nothing and proceeds.
+75
View File
@@ -0,0 +1,75 @@
package agent
import (
"os"
"path/filepath"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestChatRetestWorkspace(t *testing.T) {
for _, sandboxed := range []bool{false, true} {
name := "ordinary"
if sandboxed {
name = "sandboxed"
}
t.Run(name, func(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "sessions", "conv-1499")
ctx := t.Context()
if sandboxed {
dir = filepath.Join(root, "tasks", "retest-1499")
ctx = WithSandboxRunInfo(ctx, SandboxRunInfo{TaskID: "retest-1499", TaskDir: dir})
}
p := &sessionProbe{}
c := NewChatAgent(p, "test-model", root, nil, 100000)
if _, err := c.Chat(ctx, db.FindingRetestAgentKey, "conv-1499", "hello", 1, 0, false, nil); err != nil {
t.Fatal(err)
}
if ids := p.seen(); len(ids) != 1 || ids[0] != "conv-1499" {
t.Fatalf("session ids: %v", ids)
}
if st, err := os.Stat(dir); err != nil || !st.IsDir() {
t.Fatalf("workspace not created: %v", err)
}
if sandboxed {
if _, err := os.Stat(filepath.Join(root, "sessions", "conv-1499")); !os.IsNotExist(err) {
t.Fatalf("created a second workspace: %v", err)
}
}
})
}
}
func TestChatRejectsMismatchedRetestWorkspace(t *testing.T) {
for _, tc := range []struct{ name, agent, session, task, dir string }{
{"another_conversation", db.FindingRetestAgentKey, "conv-1499", "retest-1500", "tasks/retest-1500"},
{"another_directory", db.FindingRetestAgentKey, "conv-1499", "retest-1499", "tasks/retest-1500"},
{"outside_tasks", db.FindingRetestAgentKey, "conv-1499", "retest-1499", "retest-1499"},
{"outside_root", db.FindingRetestAgentKey, "conv-1499", "retest-1499", "../retest-1499"},
{"session_directory", db.FindingRetestAgentKey, "conv-1499", "retest-1499", "sessions/conv-1499"},
{"wrong_agent", "assistant", "conv-1499", "retest-1499", "tasks/retest-1499"},
{"wrong_prefix", db.FindingRetestAgentKey, "other-1499", "retest-1499", "tasks/retest-1499"},
{"zero_id", db.FindingRetestAgentKey, "conv-0", "retest-0", "tasks/retest-0"},
{"noncanonical_id", db.FindingRetestAgentKey, "conv-01499", "retest-01499", "tasks/retest-01499"},
{"nonnumeric_id", db.FindingRetestAgentKey, "conv-test", "retest-test", "tasks/retest-test"},
} {
t.Run(tc.name, func(t *testing.T) {
root := t.TempDir()
p := &sessionProbe{}
c := NewChatAgent(p, "test-model", root, nil, 100000)
ctx := WithSandboxRunInfo(t.Context(), SandboxRunInfo{TaskID: tc.task, TaskDir: filepath.Join(root, tc.dir)})
if _, err := c.Chat(ctx, tc.agent, tc.session, "hello", 1, 0, false, nil); err == nil {
t.Fatal("accepted mismatched retest workspace")
}
if len(p.seen()) != 0 {
t.Fatal("provider called before rejecting workspace")
}
entries, err := os.ReadDir(root)
if err != nil || len(entries) != 0 {
t.Fatalf("rejected request changed filesystem: %v %v", entries, err)
}
})
}
}
+8 -1
View File
@@ -44,6 +44,13 @@ func constraintBlock(ts *db.ExplorationStore) string {
b.WriteString("\nForbidden operations:\n")
b.WriteString(strings.Join(deny, "\n"))
}
b.WriteString("\n(Discovering a new target/port/host outside the constraints does not grant authorization: unless it falls within the allowed range above, record it as an out-of-scope fact and skip it — do not spawn intents or execute actions for it.)")
b.WriteString("\nRestrictions apply to the actual destination and operation, not merely to a URL's spelling or the tool used. A known alias/CNAME, origin IP, Host/SNI override, redirect, proxy/SSRF route, alternative port, tool, or entry point that reaches a denied target for the forbidden operation is still denied, even when that route is separately listed in scope. A scope listing, ordinary allowance, or goal/intent is not an exception to a deny. Do not retry a platform authorization denial through another tool or route. A platform authorization denial is not a target defense or HTTP error to bypass. These techniques remain usable for otherwise-authorized destinations and operations with no applicable denial; merely sharing infrastructure does not establish target equivalence. If a destination's scope is genuinely unclear, stop only that action and report the uncertainty; discovery does not grant authorization.")
b.WriteString("\n(Distinguish target-scope boundaries from method/operation permissions. " +
"Any allow entry naming a target, host, domain, URL, IP address, CIDR, or port is itself a binding target-scope boundary (a whitelist), even without an 'Authorized target scope:' prefix or the word 'only'. " +
"Bare entries such as '10.0.0.0/24' and 'app.example.com' restrict targets to the declared scope; they are not merely additional permissions. " +
"An allowance for an operation or method that does not name a target or port, such as 'Public proxies may be used.', is an additional permission, not a complete whitelist of otherwise-authorized work. " +
"Explicit scope declarations, restrictions (e.g. 'only', 'limited to', or exclusions), and every deny remain binding boundaries. " +
"Permission to use a method by itself neither requires that method nor expands target scope. A goal or assigned intent cannot override those boundaries. " +
"Newly discovered targets, ports, or hosts outside the operator's declared scope must be recorded as out-of-scope facts and skipped; do not spawn intents or execute actions for them.)")
return b.String()
}
+164
View File
@@ -0,0 +1,164 @@
package agent
import (
"strings"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/norma/llm"
)
func TestConstraintBlockEmpty(t *testing.T) {
if got := constraintBlock(nil); got != "" {
t.Fatalf("nil store: %q", got)
}
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("Constraint fixture", "Check the authorized endpoint", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(task.ID)
ts := d.Exploration(task.ExplorationID)
if got := constraintBlock(ts); got != "" {
t.Fatalf("empty constraints: %q", got)
}
if _, err = ts.AddConstraint("allow", " \t ", "human"); err != nil {
t.Fatal(err)
}
if got := constraintBlock(ts); got != "" {
t.Fatalf("blank constraint: %q", got)
}
}
// Both execution roles consume the same operation-constraint contract. Check
// the real request assembly so a prompt fix cannot silently miss one role or
// bypass the task's existing constraint-injection switch.
func TestConstraintBlockReachesPlannerAndWorker(t *testing.T) {
t.Setenv("ARTEX_SANDBOX", "off")
for _, scopeCase := range []struct {
name string
allow []string
}{
{name: "method only"},
{name: "bare CIDR", allow: []string{"10.0.0.0/24"}},
{name: "bare domain", allow: []string{"app.example.com"}},
{name: "bare IP", allow: []string{"192.0.2.10"}},
{name: "bare URL", allow: []string{"https://app.example.com/health"}},
{name: "bare port", allow: []string{"port 443"}},
{name: "explicit scope", allow: []string{"Authorized target scope: https://api.example.test on port 443."}},
{name: "explicit restriction", allow: []string{"ONLY api.example.test may be accessed."}},
} {
for _, role := range []string{"planner", "worker"} {
for _, inject := range []bool{true, false} {
name := scopeCase.name + "/" + role + "/disabled"
if inject {
name = scopeCase.name + "/" + role + "/enabled"
}
t.Run(name, func(t *testing.T) {
d := testDB(t)
defer d.Close()
goal := "Check the operator-authorized endpoint without expanding scope."
task, err := d.CreateTask("Constraint injection fixture", goal, nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(task.ID)
ts := d.Exploration(task.ExplorationID)
rules := []db.Constraint{
{Kind: "allow", Text: "Public proxies may be used."},
{Kind: "deny", Text: "Do not issue DELETE requests."},
}
for _, text := range scopeCase.allow {
rules = append(rules, db.Constraint{Kind: "allow", Text: text})
}
for _, r := range rules {
if _, err = ts.AddConstraint(r.Kind, r.Text, "human"); err != nil {
t.Fatal(err)
}
}
block := constraintBlock(ts)
_, allowed, ok := strings.Cut(block, "Allowed operations:\n")
if !ok {
t.Fatal("allow section missing")
}
allowed, _, _ = strings.Cut(allowed, "\nForbidden operations:")
for _, r := range rules {
if r.Kind == "allow" && !strings.Contains("\n"+allowed+"\n", "\n- "+r.Text+"\n") {
t.Fatalf("allow entry was removed, prefixed or reclassified: %q", r.Text)
}
}
for _, semantic := range []string{
"Any allow entry naming a target, host, domain, URL, IP address, CIDR, or port is itself a binding target-scope boundary (a whitelist)",
"even without an 'Authorized target scope:' prefix or the word 'only'",
"An allowance for an operation or method that does not name a target or port, such as 'Public proxies may be used.', is an additional permission, not a complete whitelist",
} {
if !strings.Contains(block, semantic) {
t.Errorf("missing bare-target/method contract: %s", semantic)
}
}
if strings.Contains(block, "unless it falls within the allowed range above") {
t.Fatal("ordinary allow entries are still treated as a complete target whitelist")
}
for _, semantic := range []string{"additional permission", "not a complete whitelist", "scope declaration", "every deny", "nor expands target scope", "actual destination and operation", "still denied, even", "platform authorization denial", "merely sharing infrastructure does not establish target equivalence", "stop only that action"} {
if !strings.Contains(block, semantic) {
t.Fatalf("missing constraint distinction: %s", semantic)
}
}
requests := 0
provider := &progressProbeProvider{response: func(_ int, req llm.CompletionRequest) (llm.Message, string, error) {
requests++
system := strings.Join(req.System, "\n\n")
for _, r := range rules {
if strings.Contains(system, r.Text) != inject {
t.Fatalf("%s constraint injection=%v, rule=%q", role, inject, r.Text)
}
}
if inject && !strings.Contains(system, block) {
t.Fatal("the shared constraint contract was not injected intact")
}
if role == "planner" && inject {
found := false
for _, m := range req.Messages {
for _, b := range m.Content {
found = found || strings.Contains(b.Text, strings.TrimSpace(block))
}
}
if !found {
t.Fatal("planner goal anchor lost operation constraints")
}
}
return progressText("No tools executed in this request-assembly fixture."), "end_turn", nil
}}
if role == "planner" {
planner := NewPlanner(provider, "fixture", t.TempDir(), nil, 100000, 2)
planner.SetNonStreaming(func() bool { return true })
planner.SetConstraintInject(func() bool { return inject })
_, _, err = planner.Plan(t.Context(), task.ID, nil, ts, goal, nil, nil, nil)
if err != nil && !isEmptyPlanningRound(err) {
t.Fatal(err)
}
} else {
id, e := ts.AddIntent(map[string]any{"summary": goal}, 0, nil, "fixture")
if e != nil {
t.Fatal(e)
}
intent, e := ts.GetNode(id)
if e != nil {
t.Fatal(e)
}
worker := NewWorker(provider, "fixture", t.TempDir(), nil, 100000, 2)
worker.SetNonStreaming(func() bool { return true })
worker.SetConstraintInject(func() bool { return inject })
if _, _, err = worker.Execute(t.Context(), "fixture-worker", task.ID, nil, ts, intent, nil, nil, nil, nil); err != nil {
t.Fatal(err)
}
}
if requests == 0 {
t.Fatal("no assembled model request observed")
}
})
}
}
}
}
+2 -1
View File
@@ -181,9 +181,10 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
emit(r)
}
}
session := agentcore.NewSession(agentcore.Options{
session := newSession(agentcore.Options{
Provider: prov,
SystemPrompt: []string{sys},
DynamicBoundary: 1, // the whole static system prompt gets a cache breakpoint across the turns
Tools: tools,
PermissionMode: acperm.ModeBypass,
DisableBackgroundTasks: true,
+7
View File
@@ -166,6 +166,13 @@ func TestDecomposeGoalsValidStructuredToolCallAccepted(t *testing.T) {
if prov.calls() != 2 {
t.Fatalf("expected 2 turns with no retry, got %d", prov.calls())
}
// A multi-turn session: the static system prompt (with the tools before it)
// must carry a cache breakpoint, or every turn resends it uncached.
for i, req := range prov.reqs {
if req.DynamicBoundary < 1 {
t.Fatalf("request %d: DynamicBoundary=%d, want the system prompt cached", i, req.DynamicBoundary)
}
}
}
func TestDecomposeGoalsRejectsEmptyTaskGoalAndEmptyToolArgs(t *testing.T) {
+58
View File
@@ -496,3 +496,61 @@ func TestInsertAssetsRefusesWhenInterceptRulesUnavailable(t *testing.T) {
}
}
}
// TestAssetInterceptCandidatesIPv6URLHost: a URL host that is an IPv6 literal
// in any spelling, zone-qualified or not, is an IP candidate, so exact_ip,
// fuzzy_ip and cidr rules see it.
func TestAssetInterceptCandidatesIPv6URLHost(t *testing.T) {
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
_, ips, _ := assetInterceptCandidates(assetInputItem{Type: "service", URL: u})
for _, r := range []db.AssetInterceptRule{
{Kind: "exact_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "fuzzy_ip", Pattern: "fe80::1", Enabled: true},
{Kind: "cidr", Pattern: "fe80::/10", Enabled: true},
} {
if d := db.EvaluateAssetGate([]db.AssetInterceptRule{r}, nil, nil, ips, nil); d.Allowed {
t.Fatalf("URL %s: %s rule %s did not block, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
// TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings: a fuzzy_ip block rule holds
// for every spelling of the address it names, through the insert_assets
// handler, both for an ip asset and for a URL host.
func TestInsertAssetsFuzzyIPRuleBlocksIPv6Spellings(t *testing.T) {
d := testDB(t)
defer d.Close()
rule, err := d.CreateAssetInterceptRule("fuzzy_ip", "2001:db8:5e::1", "ipv6 spelling test", true)
if err != nil {
t.Fatal(err)
}
defer d.DeleteAssetInterceptRule(rule.ID)
defer d.Exec(`DELETE FROM assets WHERE ip ILIKE '2001:%db8:%5e:%' OR url ILIKE 'http://[2001:%db8:%5e:%'`)
ts := NewToolSet(nil, "")
ts.SetAssetStore(d.Assets(), d.Companies())
items := []any{
map[string]any{"type": "ip", "ip": "2001:db8:5e::1"},
map[string]any{"type": "ip", "ip": "2001:db8:5e:0:0:0:0:1"},
map[string]any{"type": "ip", "ip": "2001:0db8:005e:0000:0000:0000:0000:0001"},
map[string]any{"type": "ip", "ip": "2001:DB8:5E::0001"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0::1]:8080/"},
map[string]any{"type": "service", "url": "http://[2001:db8:5e:0:0:0:0:1%25eth0]/"},
}
out := callInsertAssets(t, ts, map[string]any{"assets": items})
if results, _ := out["results"].([]any); len(results) != 0 {
t.Fatalf("results=%v, want every spelling blocked", results)
}
errs, _ := out["errors"].([]any)
if len(errs) != len(items) {
t.Fatalf("errors=%v, want one per item", errs)
}
for _, e := range errs {
entry, _ := e.(map[string]any)
if msg, _ := entry["error"].(string); !strings.Contains(msg, "insertion forbidden") {
t.Fatalf("item %v not refused by the block rule: %q", entry["index"], msg)
}
}
}
+1 -1
View File
@@ -193,7 +193,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
}
enableNoa(&opts, m.noaEnabledFn, m.workDir, noaSession, noaWarn(noaSession))
ctx = attachSideCapture(ctx, &opts)
s := agentcore.NewSession(opts)
s := newSession(opts)
defer s.Close()
// reload the prior conversation from the transcript so the agent has context
// across turns (each Chat is a fresh session; without this it can't see earlier
+34
View File
@@ -2,10 +2,44 @@ package agent
import (
"fmt"
"strings"
"github.com/Autumn-27/norma/agentcore"
actool "github.com/Autumn-27/norma/tool"
)
// newSession builds every Norma session ARTEX runs. Norma's background-task
// tools (Monitor, TaskOutput, TaskStop, TaskList) start commands in the panel
// process, outside the sandbox that Bash goes through, so no session gets them
// while the sandbox is required. With the sandbox off, a session that has no
// shell tool still must not gain one through Monitor: orchestration agents get
// no background tools at all. A session that does have Bash or the interactive
// shell keeps the task manager when the sandbox is off: Bash backgrounds long
// commands, the pause kill switch ends a command's whole process group, and the
// interactive shell keeps its PTY sessions on the same manager.
// A nil tool list makes Norma install its own unconfined file and shell tools,
// so nil becomes an empty list.
func newSession(opts agentcore.Options) *agentcore.Session {
if opts.Tools == nil {
opts.Tools = []actool.CoreTool{}
}
if SandboxRequired() || !hasShellTool(opts.Tools) {
opts.DisableBackgroundTasks = true
}
return agentcore.NewSession(opts)
}
// hasShellTool reports whether the session offers Bash or the interactive shell
// (shell_open and its companions), the session tools that need the task manager.
func hasShellTool(tools []actool.CoreTool) bool {
for _, tool := range tools {
if name := tool.Name(); name == "Bash" || strings.HasPrefix(name, "shell_") {
return true
}
}
return false
}
// resumeSession reloads the persisted conversation of session id into s. Norma's
// transcript.Store.Load treats a missing file as a fresh session (no records, no
// error); any other failure, such as a corrupt line or an unreadable path, is
+317
View File
@@ -0,0 +1,317 @@
package agent
import (
"encoding/json"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
"github.com/Autumn-27/norma/agentcore"
actool "github.com/Autumn-27/norma/tool"
)
// Norma's background-task tools run commands in the panel process, outside
// the sandbox. While the sandbox is required, no production session may offer
// them to the model.
var backgroundTaskTools = []string{"Monitor", "TaskOutput", "TaskStop", "TaskList"}
// requireSandboxForTest puts the process in ARTEX_SANDBOX=required mode, with
// no tool augmentation or catalogue, for the duration of the test.
func requireSandboxForTest(t *testing.T) {
t.Helper()
t.Setenv("ARTEX_SANDBOX", sandbox.ModeRequired)
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
oldEx, oldAug, oldRes := CurrentSandboxExecutor(), ToolAugment(), ToolResolve()
t.Cleanup(func() {
SetSandboxExecutor(oldEx)
SetToolAugment(oldAug)
SetToolResolve(oldRes)
})
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
SetToolAugment(nil)
SetToolResolve(nil)
if !SandboxRequired() {
t.Fatal("sandbox is not in required mode")
}
}
// requireSandboxOffForTest puts the process in ARTEX_SANDBOX=off mode, with no
// tool augmentation or catalogue, for the duration of the test.
func requireSandboxOffForTest(t *testing.T) {
t.Helper()
t.Setenv("ARTEX_SANDBOX", sandbox.ModeOff)
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
oldEx, oldAug, oldRes := CurrentSandboxExecutor(), ToolAugment(), ToolResolve()
t.Cleanup(func() {
SetSandboxExecutor(oldEx)
SetToolAugment(oldAug)
SetToolResolve(oldRes)
})
SetSandboxExecutor(nil)
SetToolAugment(nil)
SetToolResolve(nil)
if SandboxRequired() {
t.Fatal("sandbox is still required")
}
}
// offeredTools returns the tool names of the first model request, failing the
// test when the session never called the model.
func offeredTools(t *testing.T, p *captureToolNamesProvider) map[string]bool {
t.Helper()
p.mu.Lock()
called := p.names != nil
p.mu.Unlock()
if !called {
t.Fatal("the session never sent a model request")
}
return p.seen()
}
func assertNoBackgroundTaskTools(t *testing.T, p *captureToolNamesProvider) {
t.Helper()
got := offeredTools(t, p)
for _, name := range backgroundTaskTools {
if got[name] {
t.Errorf("model was offered %s (offered: %v)", name, got)
}
}
}
func TestProductionSessionsOfferNoBackgroundTaskTools(t *testing.T) {
requireSandboxForTest(t)
workDir := t.TempDir()
t.Run("chat execution agent", func(t *testing.T) {
prov := &captureToolNamesProvider{}
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
if _, err := c.Chat(t.Context(), "pentest", "conv-bgtools-pentest", "hello", 1, 0, false, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
})
// Auto's base list is nil. Norma reads a nil list as "install my own
// unconfined file and shell tools", so none of those may appear either.
t.Run("chat orchestration agent", func(t *testing.T) {
// With finding-traffic binding on, the finding workflow keeps Auto's list
// nil (with it off, it copies the list into a new empty slice), so this is
// the setting under which a nil list reaches the session.
oldBinding := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(oldBinding) })
SetFindingTrafficBindingEnabled(func() bool { return true })
prov := &captureToolNamesProvider{}
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
if _, err := c.Chat(t.Context(), "auto", "conv-bgtools-auto", "hello", 1, 0, false, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
got := prov.seen()
for _, name := range []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep"} {
if got[name] {
t.Errorf("auto was offered Norma's default tool %s", name)
}
}
})
t.Run("goal decomposition", func(t *testing.T) {
prov := &captureToolNamesProvider{}
// The fixture answers in plain text, so the decomposer reports a contract
// error. Only the offered tools matter here.
_, _ = DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit auth on lab.local", "", nil, guardTaskStore(t), 0, nil)
assertNoBackgroundTaskTools(t, prov)
})
t.Run("planner", func(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTaskWithOptions("", "", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
ts := d.Exploration(task.ExplorationID)
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Audit /admin"}, 0, "open", "goals", nil); err != nil {
t.Fatal(err)
}
if _, err := ts.AddIntent(map[string]any{"summary": "Audit the fixture admin endpoint"}, 0, nil, "fixture"); err != nil {
t.Fatal(err)
}
prov := &captureToolNamesProvider{}
p := NewPlanner(prov, "test-model", workDir, nil, 0, 2)
_, _, _ = p.Plan(t.Context(), task.ID, nil, ts, "", nil, nil, nil)
assertNoBackgroundTaskTools(t, prov)
})
t.Run("main agent", func(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
expID, err := d.CreateExploration("bgtools main agent", "no background-task tools")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
prov := &captureToolNamesProvider{}
m := NewMainAgent(prov, "test-model", workDir, nil, 0, 1)
if _, err := m.Chat(t.Context(), expID, 0, nil, d.Exploration(expID), "verify goal", "status?", nil, nil, nil, nil, nil, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
})
t.Run("worker", func(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
expID, err := d.CreateExploration("bgtools worker", "no background-task tools")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
es := d.Exploration(expID)
payload := map[string]any{"summary": "probe"}
intentID, err := es.AddNode("intent", payload, 0, "running", "planner", nil)
if err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(payload)
prov := &captureToolNamesProvider{}
w := NewWorker(prov, "test-model", workDir, nil, 0, 1)
if _, _, err := w.Execute(t.Context(), "work#1", expID, nil, es, &db.Node{ID: intentID, Payload: raw}, nil, nil, nil, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
})
// captureRun is the constructor the planner uses. Check it on its own too,
// with a nil tool list: Norma reads nil as "install my own unconfined file
// and shell tools", so the model must be offered no tools at all.
t.Run("captureRun", func(t *testing.T) {
prov := &captureToolNamesProvider{}
if _, _, err := captureRun(t.Context(), agentcore.Options{Provider: prov, MaxTurns: 1}, "hello", nil); err != nil {
t.Fatal(err)
}
if got := offeredTools(t, prov); len(got) != 0 {
t.Fatalf("nil tool list offered %v, want no tools", got)
}
})
}
// Without the sandbox, a session that has no Bash must still not gain a shell
// through Norma's background-task tools. The planner is excluded because it
// does have Bash, and then the task manager is needed for pause and background
// runs.
func TestSessionsWithoutBashOfferNoBackgroundTaskTools(t *testing.T) {
requireSandboxOffForTest(t)
workDir := t.TempDir()
t.Run("chat orchestration agent", func(t *testing.T) {
// With finding-traffic binding on, the finding workflow keeps Auto's list
// nil (with it off, it copies the list into a new empty slice), so this is
// the setting under which a nil list reaches the session.
oldBinding := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(oldBinding) })
SetFindingTrafficBindingEnabled(func() bool { return true })
prov := &captureToolNamesProvider{}
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
if _, err := c.Chat(t.Context(), "auto", "conv-bgtools-auto-off", "hello", 1, 0, false, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
got := prov.seen()
for _, name := range []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep"} {
if got[name] {
t.Errorf("auto was offered Norma's default tool %s", name)
}
}
})
t.Run("main agent", func(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
expID, err := d.CreateExploration("bgtools main agent off", "no background-task tools")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
prov := &captureToolNamesProvider{}
m := NewMainAgent(prov, "test-model", workDir, nil, 0, 1)
if _, err := m.Chat(t.Context(), expID, 0, nil, d.Exploration(expID), "verify goal", "status?", nil, nil, nil, nil, nil, nil); err != nil {
t.Fatal(err)
}
assertNoBackgroundTaskTools(t, prov)
})
}
func TestHasShellTool(t *testing.T) {
if hasShellTool(nil) {
t.Fatal("nil tool list reported a shell tool")
}
if hasShellTool([]actool.CoreTool{dummyTool("Read"), dummyTool("Grep")}) {
t.Fatal("a session without a shell tool reported one")
}
if !hasShellTool([]actool.CoreTool{dummyTool("Read"), dummyTool("Bash")}) {
t.Fatal("a session with Bash was not detected")
}
if !hasShellTool(append([]actool.CoreTool{dummyTool("Read")}, actool.ShellSessionTools()...)) {
t.Fatal("a session with the interactive shell was not detected")
}
}
// With the sandbox off, an agent whose interactive shell is on keeps the task
// manager its PTY sessions live on, even when Bash is not bound to it.
func TestInteractiveShellWithoutBashKeepsTaskManager(t *testing.T) {
requireSandboxOffForTest(t)
prov := &captureToolNamesProvider{}
s := newSession(agentcore.Options{Provider: prov, Tools: actool.ShellSessionTools(), NonStreaming: true, WorkingDir: t.TempDir()})
defer s.Close()
for _, err := range s.Prompt(t.Context(), "hello") {
if err != nil {
t.Fatal(err)
}
}
if got := offeredTools(t, prov); !got["TaskList"] {
t.Fatalf("a session with shell_open has no task manager (offered: %v)", got)
}
}
// TestNoDirectNormaSessions keeps every session behind newSession: a direct
// agentcore.NewSession call would bring the background-task tools back. It covers
// the server and command packages too, and keeps agentcore.Run to the connection
// test, which sets the flag itself.
func TestNoDirectNormaSessions(t *testing.T) {
for _, root := range []string{".", "../server", "../cmd"} {
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
if filepath.Base(path) == "session.go" && filepath.Clean(filepath.Dir(path)) == "." {
return nil
}
src, err := os.ReadFile(path)
if err != nil {
return err
}
text := string(src)
if strings.Contains(text, "agentcore.NewSession(") {
t.Errorf("%s calls agentcore.NewSession directly; use newSession", path)
}
if strings.Contains(text, "agentcore.Run(") && path != "provider.go" {
t.Errorf("%s calls agentcore.Run directly; only the connection test may", path)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}
+2 -2
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"net/url"
"strconv"
"strings"
@@ -34,7 +33,8 @@ func assetInterceptCandidates(item assetInputItem) (domains, ips, urls []string)
if item.URL != "" {
if u, err := url.Parse(item.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
// A zone-qualified IPv6 host is an IP too; net.ParseIP refuses it.
if _, ok := db.CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+22 -3
View File
@@ -325,18 +325,37 @@ func workerTrafficBlock(recording bool) string {
return "\n\n**Traffic tools**:\n- traffic_search / traffic_get / traffic_blob / traffic_messages: review responses, find already-visited resources — **check the traffic first, don't curl the same URL twice**. traffic_search **requires a host** and by default returns only 3 ultra-light index entries (id/method/url/status/resp_len, no response content) — explicitly raise limit when you need more; body_contains does full-text search in request/response bodies (at least 3 characters; supports substrings and CJK text, e.g. for passwords/keys/errors/internal addresses); to see one entry's raw content use traffic_get(id) — oversized bodies show as @blob sha256:<hash>, fetched in segments with traffic_blob(hash). WebSocket (status 101) and SSE (text/event-stream) records are captured too: traffic_get shows the handshake, and traffic_messages(id) lists their messages in order with direction and type."
}
// promptWorkDir is the work-directory path shown to an agent in its prompt. In
// sandbox mode the agent's filesystem is the worker container's, where the
// per-intent run dir is mounted at /workspace/<leaf> — NOT the panel host path
// under /app/data/tasks. Telling the agent the host path makes it write to a
// read-only /app in raw shell commands (only the cwd is remapped, not absolute
// paths inside a command). Outside sandbox mode the host path is the real path.
func promptWorkDir(runDir string) string {
if SandboxRequired() {
return containerWorkdir(filepath.Dir(runDir), runDir)
}
return runDir
}
// artifactSpec is section [C]: the code-owned, non-editable tail appended to every
// pentest agent's prompt — intermediate artifacts must land in the shared work
// dir, never /tmp. Guaranteed present regardless of how the DB body is edited.
func artifactSpec(dir string) string {
return "\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this task's work directory " + dir + "** (a relative path writes here; the absolute path works too) — **do NOT write to /tmp, do NOT use other absolute paths**."
dir = promptWorkDir(dir)
containerNote := ""
if SandboxRequired() {
containerNote = "; the absolute path above is the container path for shell commands only"
}
return "\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this task's work directory " + dir + "** (it is your current working directory — use relative paths for shell commands and file tools" + containerNote + ") — **do NOT write to /tmp, do NOT use other absolute paths, and do NOT invent paths under /app**."
}
// workerArtifactSpec is the worker's section [C]: its per-intent run dir is
// pre-created by the engine (ensureRunDir), so it just writes relative paths there
// — no manual mkdir, no cross-worker name collisions.
func workerArtifactSpec(runDir string) string {
return "\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this intent's dedicated work directory " + runDir + "** (already created automatically; just write with relative paths there — no manual mkdir needed) — **do NOT write to /tmp, do NOT use other absolute paths**."
dir := promptWorkDir(runDir)
return "\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this intent's dedicated work directory " + dir + "** (already created automatically and set as your current working directory; just write with relative paths — no manual mkdir needed) — **do NOT write to /tmp, do NOT use other absolute paths, and do NOT invent paths under /app**."
}
// mainRunDirName is the run directory of a task's main agent and planner.
@@ -759,7 +778,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
noaSession := WorkerSessionID(ts.ID(), intent.ID)
enableNoa(&opts, w.noaEnabledFn, w.workDir, noaSession, noaWarn(noaSession))
ctx = attachSideCapture(ctx, &opts)
s := agentcore.NewSession(opts)
s := newSession(opts)
defer s.Close() // release the session's background-task manager (temp dir + processes)
// Resume prior conversation if this intent was paused/blocked/exhausted and is
+43
View File
@@ -0,0 +1,43 @@
package agent
import (
"strings"
"testing"
"github.com/Autumn-27/artex/sandbox"
)
func TestArtifactSpecUsesContainerWorkdirInSandbox(t *testing.T) {
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { SetSandboxExecutor(nil) })
got := artifactSpec("/app/data/tasks/t1/main")
if !strings.Contains(got, "/workspace/main") {
t.Fatalf("artifactSpec = %q, want the container work dir", got)
}
if strings.Contains(got, "/app/data/tasks") {
t.Fatalf("artifactSpec leaks the host path: %q", got)
}
}
func TestArtifactSpecKeepsHostPathOutsideSandbox(t *testing.T) {
SetSandboxExecutor(nil)
got := artifactSpec("/app/data/tasks/t1/main")
if !strings.Contains(got, "/app/data/tasks/t1/main") {
t.Fatalf("artifactSpec = %q, want the host work dir", got)
}
if strings.Contains(got, "container path") {
t.Fatalf("artifactSpec claims a container path outside sandbox mode: %q", got)
}
}
func TestWorkerArtifactSpecUsesContainerWorkdirInSandbox(t *testing.T) {
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { SetSandboxExecutor(nil) })
got := workerArtifactSpec("/app/data/tasks/t1/i10")
if !strings.Contains(got, "/workspace/i10") {
t.Fatalf("workerArtifactSpec = %q, want the container work dir", got)
}
if strings.Contains(got, "/app/data/tasks") {
t.Fatalf("workerArtifactSpec leaks the host path: %q", got)
}
}
+10
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"net/netip"
"os"
"os/signal"
"strconv"
@@ -40,6 +41,15 @@ func main() {
if err != nil {
log.Fatalf("[egress-proxy] invalid scope policy: %v", err)
}
// Ranges no scope may open (set by the Kubernetes backend: cluster networks,
// API server, metadata).
for _, c := range sandbox.ParseCSV(os.Getenv("ARTEX_NEVER_CIDRS")) {
pfx, err := netip.ParsePrefix(c)
if err != nil {
log.Fatalf("[egress-proxy] invalid ARTEX_NEVER_CIDRS entry %q: %v", c, err)
}
policy.Never = append(policy.Never, pfx.Masked())
}
proxy := sandbox.NewEgressProxy(policy)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+71 -19
View File
@@ -2,13 +2,16 @@ package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"unicode"
"github.com/Autumn-27/artex/sandbox"
)
@@ -22,33 +25,82 @@ func envOr(k, def string) string {
return def
}
// parseDNSList splits ARTEX_TASK_DNS (comma, space, tab or newline separated
// IPv4/IPv6 addresses) into the DockerConfig.TaskDNS slice. Invalid entries
// are dropped with a warning rather than failing the runner: DNS placement
// is a performance tuning knob, not a security control.
func parseDNSList(v string) []string {
var out []string
for _, f := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || unicode.IsSpace(r) }) {
f = strings.TrimSpace(f)
if f == "" {
continue
}
if net.ParseIP(f) == nil {
log.Printf("[runner] ARTEX_TASK_DNS: ignoring invalid address %q", f)
continue
}
out = append(out, f)
}
return out
}
// buildBackend selects the container backend from ARTEX_RUNNER_BACKEND
// ("docker", the default, or "kubernetes").
func buildBackend() (sandbox.Backend, error) {
wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot)
auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot)
workerImage := envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage)
proxyImage := envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage)
switch kind := strings.ToLower(envOr(sandbox.EnvRunnerBackend, sandbox.BackendDocker)); kind {
case sandbox.BackendDocker:
sock := envOr("DOCKER_SOCK", "/var/run/docker.sock")
if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") {
sock = strings.TrimPrefix(dh, "unix://")
}
log.Printf("[runner] backend=docker socket=%s", sock)
return sandbox.NewDockerBackend(sandbox.DockerConfig{
SocketPath: sock,
WorkerImage: workerImage,
ProxyImage: proxyImage,
WorkspaceRoot: wsRoot,
HostWorkspaceRoot: envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot),
AuditRoot: auditRoot,
HostAuditRoot: envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot),
TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix),
EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet),
TaskDNS: parseDNSList(os.Getenv("ARTEX_TASK_DNS")),
}), nil
case sandbox.BackendKubernetes:
cfg, err := sandbox.KubeConfigFromEnv()
if err != nil {
return nil, err
}
cfg.WorkerImage, cfg.ProxyImage = workerImage, proxyImage
cfg.WorkspaceRoot, cfg.AuditRoot = wsRoot, auditRoot
b, err := sandbox.NewKubernetesBackend(cfg)
if err != nil {
return nil, err
}
log.Printf("[runner] backend=kubernetes namespace=%s claim=%s", b.Namespace(), cfg.DataClaim)
return b, nil
default:
return nil, fmt.Errorf("invalid %s=%q (want %q or %q)", sandbox.EnvRunnerBackend, kind, sandbox.BackendDocker, sandbox.BackendKubernetes)
}
}
func main() {
token := strings.TrimSpace(os.Getenv(sandbox.EnvRunnerToken))
if token == "" {
log.Fatalf("[runner] %s is required (refusing to start unauthenticated)", sandbox.EnvRunnerToken)
}
addr := envOr("ARTEX_RUNNER_ADDR", sandbox.DefaultRunnerAddr)
sock := envOr("DOCKER_SOCK", "/var/run/docker.sock")
if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") {
sock = strings.TrimPrefix(dh, "unix://")
backend, err := buildBackend()
if err != nil {
log.Fatalf("[runner] %v", err)
}
wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot)
hostWSRoot := envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot)
auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot)
hostAuditRoot := envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot)
backend := sandbox.NewDockerBackend(sandbox.DockerConfig{
SocketPath: sock,
WorkerImage: envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage),
ProxyImage: envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage),
WorkspaceRoot: wsRoot,
HostWorkspaceRoot: hostWSRoot,
AuditRoot: auditRoot,
HostAuditRoot: hostAuditRoot,
TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix),
EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet),
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"net"
"reflect"
"testing"
)
func TestParseDNSList(t *testing.T) {
cases := []struct {
name string
input string
want []string
}{
{
name: "comma separated",
input: "10.21.232.232,10.22.232.232,1.1.1.1",
want: []string{"10.21.232.232", "10.22.232.232", "1.1.1.1"},
},
{
name: "space separated",
input: "10.21.232.232 10.22.232.232",
want: []string{"10.21.232.232", "10.22.232.232"},
},
{
name: "mixed separators with surrounding whitespace",
input: " 10.21.232.232 , 10.22.232.232\t1.1.1.1 ",
want: []string{"10.21.232.232", "10.22.232.232", "1.1.1.1"},
},
{
name: "newline separated",
input: "10.21.232.232\n10.22.232.232\n",
want: []string{"10.21.232.232", "10.22.232.232"},
},
{
name: "ipv6 addresses",
input: "2001:db8::1,fd00::53",
want: []string{"2001:db8::1", "fd00::53"},
},
{
name: "empty input",
input: "",
want: nil,
},
{
name: "only separators and whitespace",
input: " , \t\n ,, ",
want: nil,
},
{
name: "invalid entries dropped with valid kept",
input: "10.21.232.232,not-an-ip,10.22.232.232",
want: []string{"10.21.232.232", "10.22.232.232"},
},
{
name: "hostnames are not addresses and are dropped",
input: "dns.corp.example,10.21.232.232",
want: []string{"10.21.232.232"},
},
{
name: "all invalid",
input: "nope,,still-nope",
want: nil,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := parseDNSList(tc.input)
if !reflect.DeepEqual(got, tc.want) {
t.Fatalf("parseDNSList(%q) = %v, want %v", tc.input, got, tc.want)
}
// Every returned entry must be a parseable IP (the contract the
// Docker daemon will enforce on HostConfig.Dns).
for _, e := range got {
if net.ParseIP(e) == nil {
t.Fatalf("parseDNSList(%q) returned non-IP entry %q", tc.input, e)
}
}
})
}
}
+12 -12
View File
@@ -249,19 +249,19 @@ func run() int {
}
defer mgr.Close()
// Emit prominent startup warnings if egress enforcement is off or active tasks run without target_gate.
ungatedActive := 0
if tasks, err := mgr.PG().ListTasks(); err == nil {
for _, t := range tasks {
if t.Status != "completed" && t.Status != "failed" && t.Status != "stopped" && !t.TargetGate {
ungatedActive++
}
}
// This log is a startup snapshot. The operator UI reads current posture through
// the authenticated API, so later task changes never rely on this old count.
postureCheck := server.SecurityPostureCheck{EgressMode: os.Getenv("EGRESS_MODE")}
postureCtx, cancelPostureRead := context.WithTimeout(ctx, 5*time.Second)
posture, postureErr := mgr.PG().GetTargetGatePosture(postureCtx)
cancelPostureRead()
if postureErr != nil {
postureCheck.TargetGatePostureUnavailable = true
} else {
postureCheck.UngatedActiveTasks = posture.UngatedUnfinishedTasks
postureCheck.TargetGateOptedOut = posture.ExplicitOptOutTasks > 0
}
server.LogSecurityStartupWarnings(server.SecurityPostureCheck{
EgressMode: os.Getenv("EGRESS_MODE"),
UngatedActiveTasks: ungatedActive,
})
server.LogSecurityStartupWarnings(postureCheck)
sandboxCfg, err := sandbox.PanelConfigFromEnv()
if err != nil {
+17 -3
View File
@@ -279,9 +279,22 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
}
}
case "fuzzy_ip":
// A substring of the address as written and of its canonical form, so
// "0:0:0:0:0:0:0:1" and "::0001" meet a "::1" rule. A pattern that is a
// whole address is canonicalized too; a partial one ("10.0.") is not.
lp := strings.ToLower(p)
if c, ok := CanonicalInterceptIP(p); ok {
lp = c
}
for _, ip := range ips {
if ip != "" && strings.Contains(strings.ToLower(strings.TrimSpace(ip)), lp) {
raw := strings.ToLower(strings.TrimSpace(ip))
if raw == "" {
continue
}
if strings.Contains(raw, lp) {
return ip, true
}
if c, ok := CanonicalInterceptIP(raw); ok && strings.Contains(c, lp) {
return ip, true
}
}
@@ -298,7 +311,8 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
return "", false
}
for _, ip := range ips {
if pip := net.ParseIP(strings.TrimSpace(ip)); pip != nil && ipnet.Contains(pip) {
// Canonical first: net.ParseIP refuses a zone-qualified address.
if c, ok := CanonicalInterceptIP(ip); ok && ipnet.Contains(net.ParseIP(c)) {
return ip, true
}
}
@@ -340,7 +354,7 @@ func (a *Asset) interceptCandidates() (domains, ips, urls []string) {
if a.URL != "" {
if u, err := url.Parse(a.URL); err == nil {
if h := u.Hostname(); h != "" {
if net.ParseIP(h) != nil {
if _, ok := CanonicalInterceptIP(h); ok {
add(&ips, h)
} else {
add(&domains, h)
+31
View File
@@ -71,10 +71,30 @@ func TestMatchAssetInterceptRules(t *testing.T) {
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
nil, []string{"203.0.113.99"}, nil, true, "203.0.113.99"},
// Another spelling of the same address must not slip past a fuzzy rule,
// whichever side carries it.
{"fuzzy IP fully expanded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:1"}, nil, true, "0:0:0:0:0:0:0:1"},
{"fuzzy IP zero-padded IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"::0001"}, nil, true, "::0001"},
{"fuzzy IP padded uppercase IPv6 target", []AssetInterceptRule{rule("fuzzy_ip", "2001:db8::", true)},
nil, []string{"2001:0DB8:0000:0000:0000:0000:0000:0005"}, nil, true, "2001:0DB8:0000:0000:0000:0000:0000:0005"},
{"fuzzy IP fully expanded IPv6 rule", []AssetInterceptRule{rule("fuzzy_ip", "0:0:0:0:0:0:0:1", true)},
nil, []string{"::1"}, nil, true, "::1"},
{"fuzzy IP mapped IPv4 target", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.5", true)},
nil, []string{"::ffff:cb00:7105"}, nil, true, "::ffff:cb00:7105"},
{"fuzzy IP zone-qualified target", []AssetInterceptRule{rule("fuzzy_ip", "fe80::1", true)},
nil, []string{"FE80:0:0:0:0:0:0:1%eth0"}, nil, true, "FE80:0:0:0:0:0:0:1%eth0"},
{"fuzzy IP still misses another address", []AssetInterceptRule{rule("fuzzy_ip", "::1", true)},
nil, []string{"0:0:0:0:0:0:0:2"}, nil, false, ""},
{"fuzzy IP matches a range as written", []AssetInterceptRule{rule("fuzzy_ip", "10.0.", true)},
nil, []string{"10.0.0.0/8"}, nil, true, "10.0.0.0/8"},
{"CIDR hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"192.168.5.20"}, nil, true, "192.168.5.20"},
{"CIDR no hit", []AssetInterceptRule{rule("cidr", "192.168.0.0/16", true)},
nil, []string{"10.0.0.1"}, nil, false, ""},
{"CIDR zone-qualified target", []AssetInterceptRule{rule("cidr", "fe80::/10", true)},
nil, []string{"fe80::1%eth0"}, nil, true, "fe80::1%eth0"},
{"exact URL hit", []AssetInterceptRule{rule("exact_url", "https://a.gov.cn/login", true)},
nil, nil, []string{"https://a.gov.cn/login"}, true, "https://a.gov.cn/login"},
{"fuzzy URL hits path", []AssetInterceptRule{rule("fuzzy_url", "/admin", true)},
@@ -184,4 +204,15 @@ func TestAssetInterceptCandidates(t *testing.T) {
if r, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{rule("cidr", "10.0.0.0/8", true)}, nil, ips, nil); !ok {
t.Fatalf("an IP in a URL should be hit by CIDR, ips=%v rule=%+v", ips, r)
}
// A zone-qualified or expanded IPv6 URL host is an IP too, not a domain.
for _, u := range []string{"http://[fe80::1%25eth0]:8080/x", "http://[FE80:0:0:0:0:0:0:1]/"} {
c := &Asset{Type: "service", URL: u}
_, ips, _ := c.interceptCandidates()
for _, r := range []AssetInterceptRule{rule("exact_ip", "fe80::1", true), rule("fuzzy_ip", "fe80::1", true), rule("cidr", "fe80::/10", true)} {
if _, _, ok := MatchAssetInterceptRules([]AssetInterceptRule{r}, nil, ips, nil); !ok {
t.Fatalf("URL %s: %s rule %s missed, ips=%v", u, r.Kind, r.Pattern, ips)
}
}
}
}
+2 -1
View File
@@ -2,6 +2,7 @@ package db
import (
"encoding/json"
"net"
"slices"
"sort"
"strconv"
@@ -95,7 +96,7 @@ func (a *assetRow) coverageNode() CoverageGraphNode {
func (a *assetRow) label() string {
if a.kind == "service" && a.url == "" {
if host, port := a.hostPort(); host != "" && port > 0 {
return host + ":" + strconv.Itoa(port)
return net.JoinHostPort(host, strconv.Itoa(port))
}
}
n := a.coverageNode()
+19
View File
@@ -0,0 +1,19 @@
package db
import "testing"
func TestAssetRowLabelBracketsIPv6ServicePort(t *testing.T) {
cases := []struct {
row assetRow
want string
}{
{assetRow{kind: "service", ip: "2001:db8::1", port: 445}, "[2001:db8::1]:445"},
{assetRow{kind: "service", ip: "10.0.0.5", port: 445}, "10.0.0.5:445"},
{assetRow{kind: "service", domain: "smb.example.com", port: 445}, "smb.example.com:445"},
}
for _, c := range cases {
if got := c.row.label(); got != c.want {
t.Errorf("label(%+v) = %q, want %q", c.row, got, c.want)
}
}
}
+1 -1
View File
@@ -122,7 +122,7 @@ func readApplied(t *testing.T, d *DB) []appliedMigration {
// embedded migration is recorded with the SHA-256 of its file.
func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration {
t.Helper()
for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions", "chat_bridges", "chat_bridge_chats", "chat_bridge_approvals", "planner_progress"} {
for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions", "chat_bridges", "chat_bridge_chats", "chat_bridge_approvals", "planner_progress", "users", "user_identities", "user_sessions"} {
var exists bool
if err := d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, table).Scan(&exists); err != nil {
t.Fatal(err)
+33
View File
@@ -0,0 +1,33 @@
-- Proxy pool: stored candidates for the global egress proxy (#545). Global
-- configuration: the table is not part of a task archive.
--
-- An entry only ever chooses the existing global proxy; it adds no egress path
-- of its own. This migration stores entries; nothing activates one yet.
--
-- address is sealed at rest by db/secrets.go (AAD "proxy_pool.address"): it may
-- carry user:pass. Because sealing is randomized, uniqueness is enforced on
-- address_hash, an HMAC of the normalized address under a sub-key of the secret
-- key (db/proxy_pool.go), recomputed when the key is rotated.
--
-- At most one entry is active, and the active entry is enabled.
-- egress_ip, last_check_at and last_check_ok are written by the health check;
-- NULL means never checked.
CREATE TABLE IF NOT EXISTS proxy_pool (
id BIGSERIAL PRIMARY KEY,
label TEXT NOT NULL CHECK (length(btrim(label)) > 0),
address TEXT NOT NULL,
address_hash TEXT NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT true,
active BOOLEAN NOT NULL DEFAULT false,
egress_ip TEXT,
last_check_at TIMESTAMPTZ,
last_check_ok BOOLEAN,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT proxy_pool_address_hash_key UNIQUE (address_hash),
CONSTRAINT proxy_pool_active_enabled CHECK (NOT active OR enabled)
);
CREATE UNIQUE INDEX IF NOT EXISTS proxy_pool_one_active ON proxy_pool ((true)) WHERE active;
DROP TRIGGER IF EXISTS trg_proxy_pool_upd ON proxy_pool;
CREATE TRIGGER trg_proxy_pool_upd BEFORE UPDATE ON proxy_pool
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
+99
View File
@@ -0,0 +1,99 @@
-- User accounts, identity-provider links and server-side sessions (#790,
-- phase 2, storage only).
--
-- Nothing reads these tables yet: login still accepts only the ARTEX account,
-- checks the bcrypt hash in settings (auth.password_hash) and issues tokens
-- with subject "ARTEX". A later change moves login and session checks onto
-- these tables.
--
-- Every CHECK constraint is named, so a later migration can ALTER or DROP it
-- by name. Tables that later record a user id (approvals, audit) should
-- reference users(id) without ON DELETE CASCADE (RESTRICT or SET NULL): a
-- deleted user must not take its history with it.
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
-- Stored as typed; uniqueness is case-insensitive (uq_users_username_lower),
-- so "Alice" and "alice" cannot both exist.
-- TODO(#790): normalise to Unicode NFC once SCIM/LDAP provisioning
-- writes usernames, so look-alike forms cannot both exist.
username TEXT NOT NULL
CONSTRAINT users_username_nonblank CHECK (btrim(username) <> '')
CONSTRAINT users_username_limits
CHECK (length(username) <= 128 AND username !~ '[[:cntrl:]]'),
display_name TEXT NOT NULL DEFAULT '',
email TEXT,
-- bcrypt hash. NULL for a user who signs in only through an identity
-- provider: such a user has no local password (users_password_local_only).
password_hash TEXT,
-- Where the account comes from. Only 'local' is written today.
source TEXT NOT NULL DEFAULT 'local'
CONSTRAINT users_source_valid
CHECK (source IN ('local', 'oidc', 'saml', 'ldap', 'scim')),
-- The break-glass account signs in with its local password even when SSO
-- is enforced, so it must be a local account.
is_break_glass BOOLEAN NOT NULL DEFAULT FALSE
CONSTRAINT users_break_glass_local
CHECK (NOT is_break_glass OR source = 'local'),
disabled_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ,
-- Only a local account has a local password: an account from an identity
-- provider must not gain a second way in.
CONSTRAINT users_password_local_only CHECK (password_hash IS NULL OR source = 'local')
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username_lower ON users (lower(username));
-- Links a user to an account at an identity provider (OIDC, SAML, LDAP, SCIM).
-- provider_id names the configured provider, subject is the provider's stable
-- id for the account (OIDC "sub", SAML NameID, LDAP objectGUID, SCIM id).
-- A login through a provider finds the user by (provider_id, subject) only.
-- An identity is never linked to an existing user by matching email or
-- username: either can be set by whoever controls the provider account, so
-- that would let a provider account take over a local one.
CREATE TABLE IF NOT EXISTS user_identities (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider_id TEXT NOT NULL CONSTRAINT user_identities_provider_nonblank CHECK (provider_id <> ''),
subject TEXT NOT NULL CONSTRAINT user_identities_subject_nonblank CHECK (subject <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_user_identities_provider_subject UNIQUE (provider_id, subject)
);
CREATE INDEX IF NOT EXISTS idx_user_identities_user ON user_identities (user_id);
-- One row per issued session token. id is the token's jti. A session is valid
-- while revoked_at IS NULL, expires_at > now() and its user is not disabled;
-- revoked rows are kept until they expire so a revoked token is still
-- recognised as revoked. A token whose row is missing is invalid.
--
-- client_ip is TEXT, not INET: it holds what the server saw as the peer, which
-- is not always an IP address (a Unix socket listener has none).
CREATE TABLE IF NOT EXISTS user_sessions (
id TEXT PRIMARY KEY CONSTRAINT user_sessions_id_nonblank CHECK (id <> ''),
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
revoked_at TIMESTAMPTZ,
user_agent TEXT NOT NULL DEFAULT ''
CONSTRAINT user_sessions_user_agent_len CHECK (octet_length(user_agent) <= 512),
client_ip TEXT NOT NULL DEFAULT ''
CONSTRAINT user_sessions_client_ip_len CHECK (octet_length(client_ip) <= 64)
);
CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions (user_id);
CREATE INDEX IF NOT EXISTS idx_user_sessions_expires ON user_sessions (expires_at);
-- Seed the existing single account as the break-glass local user, so later
-- changes (user ids on approvals, role bindings) have a row to point to. An
-- existing ARTEX user, in any letter case, is left unchanged.
--
-- The password hash is not copied: login still reads the setting
-- auth.password_hash, and a copy here would go stale as soon as the password
-- changes. The change that moves login onto this table moves the hash with it.
INSERT INTO users (username, display_name, source, is_break_glass)
VALUES ('ARTEX', 'ARTEX', 'local', TRUE)
ON CONFLICT ((lower(username))) DO NOTHING;
+370
View File
@@ -0,0 +1,370 @@
package db
import (
"context"
"crypto/hmac"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5/pgconn"
)
// Proxy pool (#545): stored candidates for the global egress proxy. This layer
// stores entries and keeps their addresses sealed; it never activates one.
// The address is in clear on ProxyPoolEntry, so a handler must never return
// the struct as is.
const (
MaxProxyPoolEntries = 100
MaxProxyPoolLabelRunes = 100
)
var (
ErrProxyPoolInvalid = errors.New("invalid proxy pool entry")
ErrProxyPoolDuplicate = errors.New("a proxy pool entry with this address already exists")
ErrProxyPoolLimit = fmt.Errorf("the limit of %d proxy pool entries is reached", MaxProxyPoolEntries)
// ErrProxyPoolActive refuses to disable or delete the active entry.
ErrProxyPoolActive = errors.New("the active proxy pool entry cannot be disabled or deleted")
)
var colProxyPoolAddress = secretColumn{"proxy_pool", "address", false, ""}
// ProxyPoolEntry is one row of proxy_pool. Address is the normalized address
// in clear, credentials included.
type ProxyPoolEntry struct {
ID int64
Label string
Address string
Enabled bool
Active bool
EgressIP *string // nil: never checked
LastCheckAt *time.Time // nil: never checked
LastCheckOK *bool // nil: never checked
CreatedAt time.Time
UpdatedAt time.Time
}
const proxyPoolCols = `id, label, address, enabled, active, egress_ip, last_check_at, last_check_ok, created_at, updated_at`
func scanProxyPoolEntry(row interface{ Scan(...any) error }) (ProxyPoolEntry, error) {
var e ProxyPoolEntry
var egress sql.NullString
var checkedAt sql.NullTime
var ok sql.NullBool
err := row.Scan(&e.ID, &e.Label, &e.Address, &e.Enabled, &e.Active, &egress, &checkedAt, &ok, &e.CreatedAt, &e.UpdatedAt)
if err != nil {
return e, err
}
if egress.Valid {
e.EgressIP = &egress.String
}
if checkedAt.Valid {
e.LastCheckAt = &checkedAt.Time
}
if ok.Valid {
e.LastCheckOK = &ok.Bool
}
e.Address, err = openSecret(colProxyPoolAddress, e.Address)
return e, err
}
// proxyPoolDefaultPorts are the ports net/http assumes for a proxy URL without
// one, made explicit so "http://h" and "http://h:80" are the same entry.
var proxyPoolDefaultPorts = map[string]string{"http": "80", "https": "443", "socks5": "1080"}
// NormalizeProxyAddress checks a proxy address and returns its canonical form:
// scheme://[user[:pass]@]host:port, with the scheme and host in lower case and
// the default port made explicit. It accepts http, https and socks5, the
// schemes of the global proxy, and refuses a path, query or fragment.
func NormalizeProxyAddress(raw string) (string, error) {
raw = strings.TrimSpace(raw)
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("%w: the address does not parse as a URL", ErrProxyPoolInvalid)
}
scheme := strings.ToLower(u.Scheme)
defPort, ok := proxyPoolDefaultPorts[scheme]
if !ok {
return "", fmt.Errorf("%w: use an http://, https:// or socks5:// address", ErrProxyPoolInvalid)
}
if u.Opaque != "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return "", fmt.Errorf("%w: a proxy address has no path, query or fragment", ErrProxyPoolInvalid)
}
host := strings.ToLower(u.Hostname())
if host == "" {
return "", fmt.Errorf("%w: the address has no host", ErrProxyPoolInvalid)
}
port := u.Port()
if port == "" {
if strings.HasSuffix(u.Host, ":") {
return "", fmt.Errorf("%w: the port is empty", ErrProxyPoolInvalid)
}
port = defPort
}
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return "", fmt.Errorf("%w: the port must be between 1 and 65535", ErrProxyPoolInvalid)
}
port = strconv.Itoa(n) // "080" and "80" are the same port
out := url.URL{Scheme: scheme, User: u.User, Host: net.JoinHostPort(host, port)}
return out.String(), nil
}
func normalizeProxyPoolLabel(label string) (string, error) {
label = strings.TrimSpace(label)
switch {
case label == "":
return "", fmt.Errorf("%w: a label is required", ErrProxyPoolInvalid)
case utf8.RuneCountInString(label) > MaxProxyPoolLabelRunes:
return "", fmt.Errorf("%w: the label exceeds %d characters", ErrProxyPoolInvalid, MaxProxyPoolLabelRunes)
}
return label, nil
}
// proxyPoolKeyMu orders pool writes against a key rotation in this process
// (proxyPoolTx, RotateSecretKey).
var proxyPoolKeyMu sync.RWMutex
// proxyPoolHashDomain separates the address-hash key from the secret key it
// is derived from.
const proxyPoolHashDomain = "artex-proxy-pool-address"
// proxyAddressHash is the uniqueness key of a normalized address: an HMAC
// under the box's sub-key, so the table never holds an unkeyed digest of a
// credential.
func (b *secretBox) proxyAddressHash(normalized string) string {
m := hmac.New(sha256.New, b.proxyPoolHashKey)
m.Write([]byte(normalized))
return hex.EncodeToString(m.Sum(nil))
}
// rehashProxyPool recomputes every address hash under box. RotateSecretKey
// runs it inside its transaction, which holds the table lock from before the
// addresses are sealed again until commit, so no pool write interleaves and
// the placeholder below never commits.
func rehashProxyPool(ctx context.Context, tx *sql.Tx, box *secretBox) error {
rows, err := tx.QueryContext(ctx, `SELECT id, address FROM proxy_pool`)
if err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
type rehash struct {
id int64
hash string
}
var todo []rehash
for rows.Next() {
var id int64
var addr string
if err = rows.Scan(&id, &addr); err != nil {
break
}
if isSealed(colProxyPoolAddress, addr) {
if addr, err = box.open(colProxyPoolAddress, addr); err != nil {
break
}
}
todo = append(todo, rehash{id, box.proxyAddressHash(addr)})
}
rows.Close()
if err == nil {
err = rows.Err()
}
if err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
// Move every hash out of the way first: a new hash may equal another
// row's old one, which the unique constraint would refuse mid-update.
if _, err := tx.ExecContext(ctx, `UPDATE proxy_pool SET address_hash='rehash:'||id`); err != nil {
return fmt.Errorf("rehash proxy_pool: %w", err)
}
for _, r := range todo {
if _, err := tx.ExecContext(ctx, `UPDATE proxy_pool SET address_hash=$2 WHERE id=$1`, r.id, r.hash); err != nil {
return fmt.Errorf("rehash proxy_pool id=%d: %w", r.id, err)
}
}
return nil
}
// proxyPoolWriteErr maps a constraint violation to the error the caller
// reports.
func proxyPoolWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case pgErr.Code == "23505" && pgErr.ConstraintName == "proxy_pool_address_hash_key":
return ErrProxyPoolDuplicate
case pgErr.Code == "23514" && pgErr.ConstraintName == "proxy_pool_active_enabled":
return ErrProxyPoolActive
}
}
return err
}
// sealProxyAddress returns the sealed form and hash of a normalized address.
// Writers call it under the table lock, which RotateSecretKey also takes, so a
// write never interleaves a rotation's reseal and rehash. A server process
// still holds the old key after an out-of-process rotation until it restarts
// (docs/OPS.md), as for every sealed column.
func sealProxyAddress(normalized string) (sealed, hash string, err error) {
b := activeSecretBox.Load() // one box for both, so they share a key
if b == nil {
return "", "", errNoSecretKey
}
sealed, err = b.seal(colProxyPoolAddress, normalized)
return sealed, b.proxyAddressHash(normalized), err
}
// ListProxyPool returns every entry, oldest first.
func (d *DB) ListProxyPool() ([]ProxyPoolEntry, error) {
rows, err := d.Query(`SELECT ` + proxyPoolCols + ` FROM proxy_pool ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []ProxyPoolEntry{}
for rows.Next() {
e, err := scanProxyPoolEntry(rows)
if err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}
// GetProxyPoolEntry returns one entry, sql.ErrNoRows when it does not exist.
func (d *DB) GetProxyPoolEntry(id int64) (ProxyPoolEntry, error) {
return scanProxyPoolEntry(d.QueryRow(`SELECT `+proxyPoolCols+` FROM proxy_pool WHERE id=$1`, id))
}
// proxyPoolTx runs fn with the table locked against concurrent writers, so the
// limit count and the row fn reads cannot change before it commits.
//
// It also holds proxyPoolKeyMu shared through commit. RotateSecretKey holds it
// exclusively from before its transaction until the new box is published, so
// a write in this process never runs between the rotation's commit (which
// releases the table lock) and the key swap.
func (d *DB) proxyPoolTx(fn func(tx *sql.Tx) error) error {
proxyPoolKeyMu.RLock()
defer proxyPoolKeyMu.RUnlock()
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
if _, err := tx.Exec(`LOCK TABLE proxy_pool IN SHARE ROW EXCLUSIVE MODE`); err != nil {
return err
}
if err := fn(tx); err != nil {
return proxyPoolWriteErr(err)
}
return proxyPoolWriteErr(tx.Commit())
}
// CreateProxyPoolEntry stores a new, inactive entry. The address is
// normalized (NormalizeProxyAddress) and sealed.
func (d *DB) CreateProxyPoolEntry(label, address string, enabled bool) (out ProxyPoolEntry, err error) {
if label, err = normalizeProxyPoolLabel(label); err != nil {
return out, err
}
normalized, err := NormalizeProxyAddress(address)
if err != nil {
return out, err
}
err = d.proxyPoolTx(func(tx *sql.Tx) error {
sealed, hash, err := sealProxyAddress(normalized)
if err != nil {
return err
}
var n int
if err := tx.QueryRow(`SELECT count(*) FROM proxy_pool`).Scan(&n); err != nil {
return err
}
if n >= MaxProxyPoolEntries {
return ErrProxyPoolLimit
}
out, err = scanProxyPoolEntry(tx.QueryRow(`
INSERT INTO proxy_pool(label, address, address_hash, enabled)
VALUES ($1, $2, $3, $4)
RETURNING `+proxyPoolCols, label, sealed, hash, enabled))
return err
})
return out, err
}
// ProxyPoolEdit is a partial update: a nil field keeps the stored value.
type ProxyPoolEdit struct {
Label *string
Address *string
Enabled *bool
}
// UpdateProxyPoolEntry applies edit to entry id. sql.ErrNoRows when it does
// not exist, ErrProxyPoolActive when it would disable the active entry.
func (d *DB) UpdateProxyPoolEntry(id int64, edit ProxyPoolEdit) (out ProxyPoolEntry, err error) {
var label, normalized *string
if edit.Label != nil {
l, err := normalizeProxyPoolLabel(*edit.Label)
if err != nil {
return out, err
}
label = &l
}
if edit.Address != nil {
n, err := NormalizeProxyAddress(*edit.Address)
if err != nil {
return out, err
}
normalized = &n
}
err = d.proxyPoolTx(func(tx *sql.Tx) error {
var sealed, hash *string
if normalized != nil {
s, h, err := sealProxyAddress(*normalized)
if err != nil {
return err
}
sealed, hash = &s, &h
}
var active bool
if err := tx.QueryRow(`SELECT active FROM proxy_pool WHERE id=$1`, id).Scan(&active); err != nil {
return err
}
if active && edit.Enabled != nil && !*edit.Enabled {
return ErrProxyPoolActive
}
out, err = scanProxyPoolEntry(tx.QueryRow(`
UPDATE proxy_pool
SET label=COALESCE($2, label), address=COALESCE($3, address),
address_hash=COALESCE($4, address_hash), enabled=COALESCE($5, enabled)
WHERE id=$1
RETURNING `+proxyPoolCols, id, label, sealed, hash, edit.Enabled))
return err
})
return out, err
}
// DeleteProxyPoolEntry removes an entry. sql.ErrNoRows when it does not
// exist, ErrProxyPoolActive when it is the active entry.
func (d *DB) DeleteProxyPoolEntry(id int64) error {
return d.proxyPoolTx(func(tx *sql.Tx) error {
var active bool
if err := tx.QueryRow(`SELECT active FROM proxy_pool WHERE id=$1`, id).Scan(&active); err != nil {
return err
}
if active {
return ErrProxyPoolActive
}
return oneRow(tx.Exec(`DELETE FROM proxy_pool WHERE id=$1`, id))
})
}
+250
View File
@@ -0,0 +1,250 @@
package db
import (
"database/sql"
"encoding/base64"
"errors"
"fmt"
"strings"
"testing"
)
// openProxyPool opens the test database with an empty proxy_pool, and empties
// it again at the end. It skips when the table holds entries that are not
// fixtures of this file: the limit test counts rows.
func openProxyPool(t *testing.T) *DB {
t.Helper()
d, err := Open(testDSN(t))
if err != nil {
SkipPGUnavailable(t, err)
}
clean := func() { d.Exec(`DELETE FROM proxy_pool WHERE label LIKE 't-pp-%'`) }
clean()
t.Cleanup(func() { clean(); d.Close() })
var others int
if err := d.QueryRow(`SELECT count(*) FROM proxy_pool`).Scan(&others); err != nil {
t.Fatal(err)
}
if others > 0 {
t.Skipf("proxy_pool holds %d entr(ies) that are not test fixtures — skipping", others)
}
return d
}
func TestNormalizeProxyAddress(t *testing.T) {
ok := map[string]string{
"http://proxy.example": "http://proxy.example:80",
" HTTP://Proxy.Example:3128/ ": "http://proxy.example:3128",
"https://u:p%40ss@proxy.example": "https://u:p%40ss@proxy.example:443",
"socks5://user@10.0.0.1": "socks5://user@10.0.0.1:1080",
"socks5://[2001:db8::1]:9050": "socks5://[2001:db8::1]:9050",
"http://CaseUser:CasePass@h.example:8": "http://CaseUser:CasePass@h.example:8",
"http://h.example:080": "http://h.example:80",
}
for in, want := range ok {
got, err := NormalizeProxyAddress(in)
if err != nil || got != want {
t.Errorf("NormalizeProxyAddress(%q) = %q, %v; want %q", in, got, err, want)
}
}
for _, in := range []string{"", "proxy.example:3128", "ftp://proxy.example", "socks4://p.example", "http://",
"http://p.example/path", "http://p.example?x=1", "http://p.example#f", "http://p.example:", "http://p.example:0",
"http://p.example:65536", "http://p.example:abc", "mailto:x@y"} {
if got, err := NormalizeProxyAddress(in); !errors.Is(err, ErrProxyPoolInvalid) {
t.Errorf("NormalizeProxyAddress(%q) = %q, %v; want ErrProxyPoolInvalid", in, got, err)
}
}
}
// The address is sealed at rest, never in clear in either column, and read
// back in clear; an entry is created inactive.
func TestProxyPoolCRUDSealed(t *testing.T) {
d := openProxyPool(t)
const secret = "pp-sealed-pass-0001"
e, err := d.CreateProxyPoolEntry(" t-pp-one ", "HTTP://user:"+secret+"@Proxy.Example:3128", true)
if err != nil {
t.Fatal(err)
}
if e.Label != "t-pp-one" || e.Address != "http://user:"+secret+"@proxy.example:3128" || !e.Enabled || e.Active {
t.Fatalf("created entry = %+v", e)
}
var addr, hash string
if err := d.QueryRow(`SELECT address, address_hash FROM proxy_pool WHERE id=$1`, e.ID).Scan(&addr, &hash); err != nil {
t.Fatal(err)
}
if !isEncrypted(addr) || strings.Contains(addr+hash, secret) || strings.Contains(hash, "proxy.example") {
t.Fatalf("address not sealed at rest: address=%q hash=%q", addr, hash)
}
got, err := d.GetProxyPoolEntry(e.ID)
if err != nil || got.Address != e.Address {
t.Fatalf("get = %+v, %v", got, err)
}
label, other, off := "t-pp-renamed", "socks5://other.example:1080", false
up, err := d.UpdateProxyPoolEntry(e.ID, ProxyPoolEdit{Label: &label})
if err != nil || up.Label != label || up.Address != e.Address {
t.Fatalf("label-only update = %+v, %v", up, err)
}
up, err = d.UpdateProxyPoolEntry(e.ID, ProxyPoolEdit{Address: &other, Enabled: &off})
if err != nil || up.Address != other || up.Enabled || up.Label != label {
t.Fatalf("address update = %+v, %v", up, err)
}
var newHash string
if err := d.QueryRow(`SELECT address_hash FROM proxy_pool WHERE id=$1`, e.ID).Scan(&newHash); err != nil || newHash == hash {
t.Fatalf("address change did not change the hash (%v)", err)
}
list, err := d.ListProxyPool()
if err != nil || len(list) != 1 || list[0].ID != e.ID {
t.Fatalf("list = %+v, %v", list, err)
}
if err := d.DeleteProxyPoolEntry(e.ID); err != nil {
t.Fatal(err)
}
if _, err := d.GetProxyPoolEntry(e.ID); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("get after delete: %v", err)
}
}
// A never-checked entry scans its NULL check columns as nil; a checked one
// reads them back.
func TestProxyPoolNullCheckColumnsScan(t *testing.T) {
d := openProxyPool(t)
e, err := d.CreateProxyPoolEntry("t-pp-null", "http://null.example:3128", true)
if err != nil {
t.Fatal(err)
}
if e.EgressIP != nil || e.LastCheckAt != nil || e.LastCheckOK != nil {
t.Fatalf("never-checked entry = %+v", e)
}
if _, err := d.Exec(`UPDATE proxy_pool SET egress_ip='203.0.113.7', last_check_at=now(), last_check_ok=true WHERE id=$1`, e.ID); err != nil {
t.Fatal(err)
}
list, err := d.ListProxyPool()
if err != nil || len(list) != 1 {
t.Fatalf("list = %+v, %v", list, err)
}
if g := list[0]; g.EgressIP == nil || *g.EgressIP != "203.0.113.7" || g.LastCheckAt == nil || g.LastCheckOK == nil || !*g.LastCheckOK {
t.Fatalf("checked entry = %+v", g)
}
}
func TestProxyPoolUnknownIDs(t *testing.T) {
d := openProxyPool(t)
label := "t-pp-ghost"
if _, err := d.UpdateProxyPoolEntry(1<<62, ProxyPoolEdit{Label: &label}); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("update unknown id: %v", err)
}
if err := d.DeleteProxyPoolEntry(1 << 62); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("delete unknown id: %v", err)
}
if _, err := d.GetProxyPoolEntry(1 << 62); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("get unknown id: %v", err)
}
}
// Uniqueness is on the normalized address, credentials included.
func TestProxyPoolDuplicateAddress(t *testing.T) {
d := openProxyPool(t)
a, err := d.CreateProxyPoolEntry("t-pp-a", "http://u:p@dup.example", true)
if err != nil {
t.Fatal(err)
}
if _, err := d.CreateProxyPoolEntry("t-pp-b", "HTTP://u:p@DUP.example:80/", true); !errors.Is(err, ErrProxyPoolDuplicate) {
t.Fatalf("same normalized address: %v", err)
}
if _, err := d.CreateProxyPoolEntry("t-pp-b2", "http://u:p@dup.example:0080", true); !errors.Is(err, ErrProxyPoolDuplicate) {
t.Fatalf("same port spelled with leading zeros: %v", err)
}
b, err := d.CreateProxyPoolEntry("t-pp-c", "http://u:other@dup.example", true)
if err != nil {
t.Fatalf("other credentials are another entry: %v", err)
}
same := "http://u:p@dup.example:80"
if _, err := d.UpdateProxyPoolEntry(b.ID, ProxyPoolEdit{Address: &same}); !errors.Is(err, ErrProxyPoolDuplicate) {
t.Fatalf("update onto an existing address: %v", err)
}
if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Address: &same}); err != nil {
t.Fatalf("re-saving an entry's own address: %v", err)
}
}
func TestProxyPoolValidation(t *testing.T) {
d := openProxyPool(t)
for _, c := range []struct{ label, addr string }{{"", "http://v.example"}, {" ", "http://v.example"},
{"t-pp-" + strings.Repeat("x", MaxProxyPoolLabelRunes), "http://v.example"}, {"t-pp-v", "v.example:3128"}} {
if _, err := d.CreateProxyPoolEntry(c.label, c.addr, true); !errors.Is(err, ErrProxyPoolInvalid) {
t.Errorf("create(%q, %q): %v", c.label, c.addr, err)
}
}
}
// The schema keeps at most one active entry, and only an enabled one; the
// store refuses to disable or delete the active entry.
func TestProxyPoolActiveConstraints(t *testing.T) {
d := openProxyPool(t)
a, err := d.CreateProxyPoolEntry("t-pp-act-a", "http://a.example", true)
if err != nil {
t.Fatal(err)
}
b, err := d.CreateProxyPoolEntry("t-pp-act-b", "http://b.example", true)
if err != nil {
t.Fatal(err)
}
c, err := d.CreateProxyPoolEntry("t-pp-act-c", "http://c.example", false)
if err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, a.ID); err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, b.ID); err == nil {
t.Fatal("a second active entry was accepted")
}
if _, err := d.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, c.ID); err == nil {
t.Fatal("a disabled entry was made active")
}
if _, err := d.Exec(`UPDATE proxy_pool SET enabled=false WHERE id=$1`, a.ID); err == nil {
t.Fatal("the active entry was disabled")
}
off := false
if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Enabled: &off}); !errors.Is(err, ErrProxyPoolActive) {
t.Fatalf("disable active entry: %v", err)
}
if err := d.DeleteProxyPoolEntry(a.ID); !errors.Is(err, ErrProxyPoolActive) {
t.Fatalf("delete active entry: %v", err)
}
label := "t-pp-act-a2"
if _, err := d.UpdateProxyPoolEntry(a.ID, ProxyPoolEdit{Label: &label}); err != nil {
t.Fatalf("relabel active entry: %v", err)
}
}
func TestProxyPoolLimit(t *testing.T) {
d := openProxyPool(t)
for i := 0; i < MaxProxyPoolEntries; i++ {
if _, err := d.Exec(`INSERT INTO proxy_pool(label, address, address_hash) VALUES ('t-pp-lim', '', $1)`, fmt.Sprint("lim-", i)); err != nil {
t.Fatal(err)
}
}
if _, err := d.CreateProxyPoolEntry("t-pp-over", "http://over.example", true); !errors.Is(err, ErrProxyPoolLimit) {
t.Fatalf("create past the limit: %v", err)
}
}
// A pool address sealed under another key fails the startup key check.
func TestProxyPoolAddressInStartupKeyCheck(t *testing.T) {
d := openProxyPool(t)
other, _ := newSecretBox([]byte("ffffffffffffffffffffffffffffffff"))
v, err := other.encrypt(colProxyPoolAddress.aad(), "http://other.example:3128")
if err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`INSERT INTO proxy_pool(label, address, address_hash) VALUES ('t-pp-wrongkey', $1, 'wrongkey')`, v); err != nil {
t.Fatal(err)
}
t.Setenv(secretKeyEnv, base64.StdEncoding.EncodeToString(testSecretKey))
if err := d.InitSecrets(t.TempDir()); err == nil || !strings.Contains(err.Error(), "proxy_pool.address") {
t.Fatalf("want a key-check failure on proxy_pool.address, got %v", err)
}
}
+27 -3
View File
@@ -98,7 +98,7 @@ var (
colHookSource = secretColumn{"traffic_tamper_hooks", "source", false, ""}
colHookVerMatchers = secretColumn{"traffic_tamper_hook_versions", "matchers", true, ""}
colHookVerSource = secretColumn{"traffic_tamper_hook_versions", "source", false, ""}
secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...)
secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource, colProxyPoolAddress}, secretSettingColumns()...)
)
// secretSettingKeys are the settings stored encrypted, AAD "settings.<key>".
@@ -124,7 +124,13 @@ func secretSetting(key string) (secretColumn, bool) {
return secretColumn{}, false
}
type secretBox struct{ aead cipher.AEAD }
// secretBox seals and opens secrets with one key, and carries the keys derived
// from it, so a box can never be installed without them.
type secretBox struct {
aead cipher.AEAD
// proxyPoolHashKey keys the proxy pool's address uniqueness hash.
proxyPoolHashKey []byte
}
var activeSecretBox atomic.Pointer[secretBox]
@@ -157,7 +163,7 @@ func newSecretBox(key []byte) (*secretBox, error) { // key: 32 bytes, see parseS
return nil, err
}
aead, err := cipher.NewGCM(block)
return &secretBox{aead}, err
return &secretBox{aead: aead, proxyPoolHashKey: deriveSubKey(key, proxyPoolHashDomain)}, err
}
func isEncrypted(v string) bool { return strings.HasPrefix(v, secretPrefix) }
@@ -443,6 +449,11 @@ func (d *DB) RotateSecretKey(ctx context.Context, oldKey, newKey []byte, invalid
if err != nil {
return 0, 0, fmt.Errorf("new secret key: %w", err)
}
// Held until the new box is published: a pool write in this process
// waits for it, so it never seals or hashes under the old key after the
// rotation commits (see proxyPoolTx).
proxyPoolKeyMu.Lock()
defer proxyPoolKeyMu.Unlock()
err = withSchemaMigrationLock(ctx, d.DB, func(conn *sql.Conn) error {
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
@@ -450,6 +461,13 @@ func (d *DB) RotateSecretKey(ctx context.Context, oldKey, newKey []byte, invalid
}
defer tx.Rollback() //nolint:errcheck
// Hold off proxy pool writers from before the addresses are sealed
// again until commit: the uniqueness hashes are rehashed below, and a
// write in between would be sealed or hashed under the old key.
if _, err := tx.ExecContext(ctx, `LOCK TABLE proxy_pool IN SHARE ROW EXCLUSIVE MODE`); err != nil {
return fmt.Errorf("lock proxy_pool: %w", err)
}
for _, c := range secretColumns {
type rowUpdate struct {
id any
@@ -508,6 +526,12 @@ func (d *DB) RotateSecretKey(ctx context.Context, oldKey, newKey []byte, invalid
}
}
// The proxy pool's uniqueness hashes are keyed too: recompute them
// under the new key in the same transaction.
if err := rehashProxyPool(ctx, tx, newBox); err != nil {
return err
}
if invalidateSessions {
var rawVer string
var cur int64
+14
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
@@ -59,6 +60,11 @@ func TestRotateSecretKeyAtomicallyReencryptsAndInvalidatesSessions(t *testing.T)
t.Fatal(err)
}
t.Cleanup(func() { _ = d.SetSetting("global_proxy", "") })
poolEntry, err := d.CreateProxyPoolEntry("rotate-pool", "http://u:rotate-pool-pass@pool.example.test:3128", true)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteProxyPoolEntry(poolEntry.ID) })
rotated, newVer, err := d.RotateSecretKey(context.Background(), keyA, keyB, true)
if err != nil {
@@ -91,6 +97,14 @@ func TestRotateSecretKeyAtomicallyReencryptsAndInvalidatesSessions(t *testing.T)
if err != nil || !ok || proxyVal != "http://u:rotate-proxy-pass@127.0.0.1:8080" {
t.Fatalf("global_proxy after rotation = %q ok=%v err=%v", proxyVal, ok, err)
}
// The pool address reads back, and its uniqueness hash follows the new key.
if e, err := d.GetProxyPoolEntry(poolEntry.ID); err != nil || e.Address != poolEntry.Address {
t.Fatalf("pool entry after rotation = %+v err=%v", e, err)
}
if _, err := d.CreateProxyPoolEntry("rotate-pool-dup", poolEntry.Address, true); !errors.Is(err, ErrProxyPoolDuplicate) {
t.Fatalf("duplicate pool address after rotation: %v", err)
}
}
func TestTaskTargetGateDefaultsOnWhenScoped(t *testing.T) {
+34
View File
@@ -0,0 +1,34 @@
package db
import (
"context"
"fmt"
"time"
)
// TargetGatePosture is a committed, database-observed view of unfinished tasks.
// ExplicitOptOutTasks is a subset of UngatedUnfinishedTasks.
type TargetGatePosture struct {
UngatedUnfinishedTasks int `json:"ungated_unfinished_tasks"`
ExplicitOptOutTasks int `json:"explicit_opt_out_tasks"`
ObservedAt time.Time `json:"observed_at"`
}
// GetTargetGatePosture reads the current counts in one PostgreSQL statement.
func (d *DB) GetTargetGatePosture(ctx context.Context) (TargetGatePosture, error) {
var posture TargetGatePosture
err := d.QueryRowContext(ctx, `
SELECT COUNT(*), COUNT(*) FILTER (WHERE target_gate_opt_out), CURRENT_TIMESTAMP
FROM tasks
WHERE deleted_at IS NULL
AND status NOT IN ('done', 'failed', 'timeout')
AND target_gate = false`).Scan(
&posture.UngatedUnfinishedTasks,
&posture.ExplicitOptOutTasks,
&posture.ObservedAt,
)
if err != nil {
return TargetGatePosture{}, fmt.Errorf("get target-gate posture: %w", err)
}
return posture, nil
}
+102
View File
@@ -0,0 +1,102 @@
package db
import (
"context"
"testing"
)
// This catches stale posture, incorrect terminal filtering, and confusion
// between an implicit open gate and an explicit operator opt-out.
func TestTargetGatePostureCountsCurrentUnfinishedTasks(t *testing.T) {
d, err := Open(scratchDSN(t, "target_gate_posture"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
check := func(label string, ungated, optedOut int) {
t.Helper()
got, err := d.GetTargetGatePosture(context.Background())
if err != nil {
t.Fatalf("%s: posture query: %v", label, err)
}
if got.UngatedUnfinishedTasks != ungated || got.ExplicitOptOutTasks != optedOut {
t.Fatalf("%s: posture = (%d, %d), want (%d, %d)", label,
got.UngatedUnfinishedTasks, got.ExplicitOptOutTasks, ungated, optedOut)
}
if got.ObservedAt.IsZero() {
t.Fatalf("%s: missing database observation time", label)
}
}
create := func(name string, opts TaskCreateOptions) *Task {
t.Helper()
task, err := d.CreateTaskWithOptions(name, "goal", opts)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
return task
}
check("empty", 0, 0)
implicit := create("implicit off", TaskCreateOptions{})
check("implicit off", 1, 0)
// A scoped task defaults to gate-on and does not change either count.
create("scoped on", TaskCreateOptions{InterceptRules: []TaskInterceptRuleInput{{
Kind: "exact_domain", Pattern: "posture.example.com", Action: "allow", Enabled: true,
}}})
check("default on", 1, 0)
off, on := false, true
explicit := create("scoped explicit off", TaskCreateOptions{
TargetGate: &off,
InterceptRules: []TaskInterceptRuleInput{{
Kind: "exact_domain", Pattern: "opted-out.example.com", Action: "allow", Enabled: true,
}},
})
check("explicit off", 2, 1)
if err := d.SetPaused(implicit.ID, true); err != nil {
t.Fatal(err)
}
if err := d.Enqueue(explicit.ID, "bootstrap"); err != nil {
t.Fatal(err)
}
check("paused and queued", 2, 1)
if _, err := d.UpdateTask(implicit.ID, TaskPatch{TargetGate: &on}); err != nil {
t.Fatal(err)
}
check("gate switched on", 1, 1)
if _, err := d.UpdateTask(implicit.ID, TaskPatch{TargetGate: &off}); err != nil {
t.Fatal(err)
}
check("gate switched off explicitly", 2, 2)
if err := d.SetStatus(implicit.ID, "done"); err != nil {
t.Fatal(err)
}
check("done excluded", 1, 1)
if err := d.SetStatus(explicit.ID, "failed"); err != nil {
t.Fatal(err)
}
check("failed excluded", 0, 0)
timedOut := create("timeout", TaskCreateOptions{TargetGate: &off})
check("new unfinished", 1, 1)
if err := d.SetStatus(timedOut.ID, "timeout"); err != nil {
t.Fatal(err)
}
check("timeout excluded", 0, 0)
softDeleted := create("soft deleted", TaskCreateOptions{})
check("before soft delete", 1, 0)
if _, err := d.Exec(`UPDATE tasks SET deleted_at=now() WHERE id=$1`, softDeleted.ID); err != nil {
t.Fatal(err)
}
check("soft deleted excluded", 0, 0)
if err := d.SetStatus(implicit.ID, "running"); err != nil {
t.Fatal(err)
}
check("revived task included", 1, 1)
}
+373
View File
@@ -0,0 +1,373 @@
package db
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5/pgconn"
)
// Users, identity-provider links and sessions (migration 0029_users.sql).
// Nothing outside this package calls these yet: login still uses the single
// ARTEX account in settings (server/auth.go).
// User sources: the only values the users.source CHECK allows.
const (
UserSourceLocal = "local"
UserSourceOIDC = "oidc"
UserSourceSAML = "saml"
UserSourceLDAP = "ldap"
UserSourceSCIM = "scim"
)
var (
ErrUsernameTaken = errors.New("a user with this username already exists")
ErrIdentityLinked = errors.New("this identity is already linked to a user")
ErrUserInvalid = errors.New("invalid user")
ErrSessionIDNeeded = errors.New("session id is required")
// ErrUserDisabled: no session is created for a disabled or missing user.
ErrUserDisabled = errors.New("user is disabled or does not exist")
// ErrLastBreakGlass: the last enabled break-glass account cannot be
// disabled, or no one could sign in when SSO is down.
ErrLastBreakGlass = errors.New("the last enabled break-glass user cannot be disabled")
)
// Limits the users and user_sessions CHECK constraints enforce; the store
// functions apply them first so a caller gets ErrUserInvalid or a cut value
// instead of a constraint error.
const (
UsernameMaxChars = 128 // users_username_limits
SessionUserAgentMax = 512 // bytes, user_sessions_user_agent_len
SessionClientIPMax = 64 // bytes, user_sessions_client_ip_len
)
// validUsername checks a trimmed username against users_username_nonblank and
// users_username_limits.
// TODO(#790): normalise to Unicode NFC once SCIM/LDAP provisioning writes
// usernames (see 0029_users.sql).
func validUsername(username string) error {
if username == "" {
return fmt.Errorf("%w: username is required", ErrUserInvalid)
}
if utf8.RuneCountInString(username) > UsernameMaxChars {
return fmt.Errorf("%w: username is longer than %d characters", ErrUserInvalid, UsernameMaxChars)
}
if !utf8.ValidString(username) || strings.IndexFunc(username, unicode.IsControl) >= 0 {
return fmt.Errorf("%w: username contains a control character", ErrUserInvalid)
}
return nil
}
// cutUTF8 returns s cut to at most max bytes, on a character boundary, as
// valid UTF-8.
func cutUTF8(s string, max int) string {
s = strings.ToValidUTF8(s, "")
if len(s) <= max {
return s
}
s = s[:max]
for len(s) > 0 && !utf8.ValidString(s) {
s = s[:len(s)-1]
}
return s
}
// User is one row of users. PasswordHash is "" when the user has no local
// password (an SSO-only account).
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
Email *string `json:"email,omitempty"`
PasswordHash string `json:"-"`
Source string `json:"source"`
IsBreakGlass bool `json:"is_break_glass"`
DisabledAt *time.Time `json:"disabled_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
}
// NewUser holds the fields CreateUser writes. An empty PasswordHash stores
// NULL; an empty Source means local. The break-glass flag is set only by the
// migration seed, never through this API.
type NewUser struct {
Username string
DisplayName string
Email *string
PasswordHash string
Source string
}
const userCols = `id, username, display_name, email, COALESCE(password_hash, ''), source, is_break_glass, disabled_at, created_at, updated_at, last_login_at`
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
var u User
if err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.Email, &u.PasswordHash, &u.Source,
&u.IsBreakGlass, &u.DisabledAt, &u.CreatedAt, &u.UpdatedAt, &u.LastLoginAt); err != nil {
return nil, err
}
return &u, nil
}
// getUser runs a single-row user query and returns nil, nil when no row matches.
func (d *DB) getUser(query string, args ...any) (*User, error) {
u, err := scanUser(d.QueryRow(query, args...))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return u, err
}
func userUniqueViolation(err error, constraint string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
}
func userCheckViolation(err error, constraint string) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23514" && pgErr.ConstraintName == constraint
}
// CreateUser inserts a user. The username is trimmed and must not be empty,
// longer than UsernameMaxChars characters or hold a control character
// (ErrUserInvalid); a username that differs from an existing one only in
// letter case is refused with ErrUsernameTaken. Only a local user may have a
// password (ErrUserInvalid otherwise).
func (d *DB) CreateUser(n NewUser) (*User, error) {
username := strings.TrimSpace(n.Username)
if err := validUsername(username); err != nil {
return nil, err
}
source := n.Source
if source == "" {
source = UserSourceLocal
}
if n.PasswordHash != "" && source != UserSourceLocal {
return nil, fmt.Errorf("%w: only a local user can have a password", ErrUserInvalid)
}
u, err := scanUser(d.QueryRow(`INSERT INTO users (username, display_name, email, password_hash, source)
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
RETURNING `+userCols, username, n.DisplayName, n.Email, n.PasswordHash, source))
if userUniqueViolation(err, "uq_users_username_lower") {
return nil, ErrUsernameTaken
}
return u, err
}
// GetUserByID returns the user, or nil when there is none.
func (d *DB) GetUserByID(id int64) (*User, error) {
return d.getUser(`SELECT `+userCols+` FROM users WHERE id=$1`, id)
}
// GetUserByUsername matches the username case-insensitively, as the unique
// index does, and returns nil when there is no such user. Disabled users are
// returned too: the caller decides what a disabled account may do.
func (d *DB) GetUserByUsername(username string) (*User, error) {
return d.getUser(`SELECT `+userCols+` FROM users WHERE lower(username)=lower($1)`, strings.TrimSpace(username))
}
// SetUserPassword stores a new bcrypt hash; an empty hash clears the local
// password. A user from an identity provider cannot get one
// (ErrUserInvalid, users_password_local_only). It does not revoke sessions:
// the caller does that with RevokeUserSessions when the change must sign the
// user out. ok is false when the user does not exist.
func (d *DB) SetUserPassword(id int64, hash string) (ok bool, err error) {
res, err := d.Exec(`UPDATE users SET password_hash=NULLIF($2, ''), updated_at=now() WHERE id=$1`, id, hash)
if userCheckViolation(err, "users_password_local_only") {
return false, fmt.Errorf("%w: only a local user can have a password", ErrUserInvalid)
}
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
// DisableUser marks the user disabled and revokes all of its sessions in the
// same transaction, so a disabled user keeps no working session. Disabling a
// disabled user keeps the first disabled_at. ok is false when the user does
// not exist. The last enabled break-glass user is not disabled
// (ErrLastBreakGlass). A server that caches session checks must drop its
// cache after calling this.
func (d *DB) DisableUser(id int64) (ok bool, err error) {
tx, err := d.Begin()
if err != nil {
return false, err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
// Lock every enabled break-glass row, so two concurrent calls cannot each
// disable one of the last two: the second one waits and then no longer
// sees the row the first one disabled.
rows, err := tx.Query(`SELECT id FROM users WHERE is_break_glass AND disabled_at IS NULL ORDER BY id FOR UPDATE`)
if err != nil {
return false, err
}
var enabledBreakGlass []int64
for rows.Next() {
var bid int64
if err := rows.Scan(&bid); err != nil {
rows.Close()
return false, err
}
enabledBreakGlass = append(enabledBreakGlass, bid)
}
rows.Close()
if err := rows.Err(); err != nil {
return false, err
}
if len(enabledBreakGlass) == 1 && enabledBreakGlass[0] == id {
return false, ErrLastBreakGlass
}
res, err := tx.Exec(`UPDATE users SET disabled_at=COALESCE(disabled_at, now()), updated_at=now() WHERE id=$1`, id)
if err != nil {
return false, err
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return false, err
}
if _, err := tx.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL`, id); err != nil {
return false, err
}
return true, tx.Commit()
}
// LinkIdentity links the account subject at identity provider providerID to
// the user. An identity belongs to one user only: linking one that is already
// linked, to this user or another, returns ErrIdentityLinked. Callers must
// never pick userID by matching the provider's email or username (see the
// comment on user_identities in 0029_users.sql).
func (d *DB) LinkIdentity(userID int64, providerID, subject string) error {
if providerID == "" || subject == "" {
return fmt.Errorf("%w: provider and subject are required", ErrUserInvalid)
}
_, err := d.Exec(`INSERT INTO user_identities (user_id, provider_id, subject) VALUES ($1, $2, $3)`, userID, providerID, subject)
if userUniqueViolation(err, "uq_user_identities_provider_subject") {
return ErrIdentityLinked
}
return err
}
// GetUserByIdentity returns the user linked to subject at providerID, or nil
// when the identity is not linked. The match is exact: subjects are opaque.
func (d *DB) GetUserByIdentity(providerID, subject string) (*User, error) {
return d.getUser(`SELECT `+userCols+` FROM users
WHERE id = (SELECT user_id FROM user_identities WHERE provider_id=$1 AND subject=$2)`, providerID, subject)
}
// UserSession is one row of user_sessions. ID is the session token's jti.
type UserSession struct {
ID string `json:"id"`
UserID int64 `json:"user_id"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
LastSeenAt time.Time `json:"last_seen_at"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
UserAgent string `json:"user_agent"`
ClientIP string `json:"client_ip"`
// UserDisabled is set when the session's user is disabled (GetSession).
UserDisabled bool `json:"user_disabled,omitempty"`
}
// Active reports whether the session is neither revoked nor expired at now,
// and its user is not disabled.
func (s *UserSession) Active(now time.Time) bool {
return s.RevokedAt == nil && !s.UserDisabled && now.Before(s.ExpiresAt)
}
// CreateSession records a new session for an existing, enabled user
// (ErrUserDisabled otherwise). The caller generates id (the token's jti)
// from a cryptographic random source. userAgent is cut to
// SessionUserAgentMax and clientIP to SessionClientIPMax bytes.
func (d *DB) CreateSession(id string, userID int64, expiresAt time.Time, userAgent, clientIP string) (*UserSession, error) {
if id == "" {
return nil, ErrSessionIDNeeded
}
s := UserSession{ID: id, UserID: userID, ExpiresAt: expiresAt,
UserAgent: cutUTF8(userAgent, SessionUserAgentMax), ClientIP: cutUTF8(clientIP, SessionClientIPMax)}
err := d.QueryRow(`INSERT INTO user_sessions (id, user_id, expires_at, user_agent, client_ip)
SELECT $1, id, $3, $4, $5 FROM users WHERE id=$2 AND disabled_at IS NULL
RETURNING created_at, expires_at, last_seen_at`, s.ID, s.UserID, s.ExpiresAt, s.UserAgent, s.ClientIP).Scan(
&s.CreatedAt, &s.ExpiresAt, &s.LastSeenAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserDisabled
}
if err != nil {
return nil, err
}
return &s, nil
}
// GetSession returns the session, revoked or expired ones and those of a
// disabled user included (check Active), or nil when there is none. Callers
// must treat nil as an invalid session: a token whose row is gone is not
// valid.
func (d *DB) GetSession(id string) (*UserSession, error) {
var s UserSession
err := d.QueryRow(`SELECT s.id, s.user_id, s.created_at, s.expires_at, s.last_seen_at, s.revoked_at,
s.user_agent, s.client_ip, u.disabled_at IS NOT NULL
FROM user_sessions s JOIN users u ON u.id = s.user_id
WHERE s.id=$1`, id).Scan(
&s.ID, &s.UserID, &s.CreatedAt, &s.ExpiresAt, &s.LastSeenAt, &s.RevokedAt, &s.UserAgent, &s.ClientIP, &s.UserDisabled)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &s, nil
}
// TouchSession sets last_seen_at to now on an active session. ok is false when
// the session does not exist, is revoked, has expired or belongs to a
// disabled user; nothing is written then.
func (d *DB) TouchSession(id string) (ok bool, err error) {
res, err := d.Exec(`UPDATE user_sessions s SET last_seen_at=now()
FROM users u
WHERE s.id=$1 AND u.id=s.user_id AND u.disabled_at IS NULL
AND s.revoked_at IS NULL AND s.expires_at > now()`, id)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
// RevokeSession revokes one session. ok is false when the session does not
// exist or was already revoked; the first revoked_at is kept.
func (d *DB) RevokeSession(id string) (ok bool, err error) {
res, err := d.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL`, id)
if err != nil {
return false, err
}
n, err := res.RowsAffected()
return n > 0, err
}
// RevokeUserSessions revokes every session of the user that is not revoked yet
// and returns how many it revoked.
func (d *DB) RevokeUserSessions(userID int64) (int64, error) {
res, err := d.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL`, userID)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// DeleteExpiredSessions deletes the sessions that have expired by the
// database clock, revoked or not, and returns how many it deleted. It uses
// now(), as TouchSession does, so a server clock ahead of the database cannot
// delete a session the database still treats as live. A session that is
// revoked but not yet expired is kept, so it still reads as revoked.
func (d *DB) DeleteExpiredSessions() (int64, error) {
res, err := d.Exec(`DELETE FROM user_sessions WHERE expires_at <= now()`)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
+435
View File
@@ -0,0 +1,435 @@
package db
import (
"errors"
"slices"
"strings"
"testing"
"time"
)
// openScratch opens a new, empty database named after suffix (see scratchDSN)
// and returns its DSN with the open handle.
func openScratch(t *testing.T, suffix string) (string, *DB) {
t.Helper()
dsn := scratchDSN(t, suffix)
d, err := Open(dsn)
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { d.Close() })
return dsn, d
}
// rerunUsersMigration removes the 0029 marker and opens dsn again, so Open
// runs 0029_users.sql a second time over the existing tables.
func rerunUsersMigration(t *testing.T, d *DB, dsn string) *DB {
t.Helper()
if _, err := d.Exec(`DELETE FROM schema_migrations WHERE version >= 29`); err != nil {
t.Fatal(err)
}
d.Close()
d2, err := Open(dsn)
if err != nil {
t.Fatalf("re-Open: %v", err)
}
t.Cleanup(func() { d2.Close() })
return d2
}
func mustBreakGlass(t *testing.T, d *DB) *User {
t.Helper()
u, err := d.GetUserByUsername("ARTEX")
if err != nil {
t.Fatal(err)
}
if u == nil {
t.Fatal("ARTEX user missing after migration")
}
if !u.IsBreakGlass || u.Source != UserSourceLocal || u.DisabledAt != nil {
t.Fatalf("ARTEX user = %+v, want an enabled local break-glass account", u)
}
return u
}
func countUsers(t *testing.T, d *DB) int {
t.Helper()
var n int
if err := d.QueryRow(`SELECT count(*) FROM users`).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
// A fresh install has no password yet: the seed creates ARTEX without a hash,
// and running the migration again neither fails nor adds a second row.
func TestUsersMigrationFreshInstall(t *testing.T) {
dsn, d := openScratch(t, "users_fresh")
if u := mustBreakGlass(t, d); u.PasswordHash != "" {
t.Fatalf("fresh install: password_hash = %q, want none", u.PasswordHash)
}
d = rerunUsersMigration(t, d, dsn)
mustBreakGlass(t, d)
if n := countUsers(t, d); n != 1 {
t.Fatalf("users after second run = %d, want 1", n)
}
}
// An upgrade seeds ARTEX without copying the password hash: login still reads
// the setting, which stays as it was. A rerun leaves an existing ARTEX row (in
// any letter case) unchanged.
func TestUsersMigrationUpgradeKeepsPasswordInSetting(t *testing.T) {
dsn, d := openScratch(t, "users_upgrade")
// Simulate a database from before 0029 that already has a password.
if _, err := d.Exec(`DROP TABLE user_sessions, user_identities, users`); err != nil {
t.Fatal(err)
}
const hash = "$2a$10$abcdefghijklmnopqrstuuJ0123456789abcdefghijklmnopqrstu"
if err := d.SetSetting("auth.password_hash", hash); err != nil {
t.Fatal(err)
}
d = rerunUsersMigration(t, d, dsn)
if u := mustBreakGlass(t, d); u.PasswordHash != "" {
t.Fatalf("password_hash = %q, want none: the hash stays in the setting", u.PasswordHash)
}
if got, _, err := d.GetSetting("auth.password_hash"); err != nil || got != hash {
t.Fatalf("setting after migration = %q, %v; want it unchanged", got, err)
}
// The seed is not re-applied over an existing row.
if _, err := d.Exec(`UPDATE users SET username='artex', password_hash='kept'`); err != nil {
t.Fatal(err)
}
d = rerunUsersMigration(t, d, dsn)
if n := countUsers(t, d); n != 1 {
t.Fatalf("users after rerun = %d, want 1", n)
}
u := mustBreakGlass(t, d)
if u.Username != "artex" || u.PasswordHash != "kept" {
t.Fatalf("rerun changed the existing user: %+v", u)
}
}
// Every CHECK constraint on the 0029 tables has a name a later migration can
// use.
func TestUsersMigrationNamesChecks(t *testing.T) {
_, d := openScratch(t, "users_checks")
rows, err := d.Query(`SELECT conname FROM pg_constraint
WHERE contype='c' AND conrelid IN ('users'::regclass, 'user_identities'::regclass, 'user_sessions'::regclass)`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
t.Fatal(err)
}
names = append(names, n)
}
slices.Sort(names)
want := []string{
"user_identities_provider_nonblank", "user_identities_subject_nonblank",
"user_sessions_client_ip_len", "user_sessions_id_nonblank", "user_sessions_user_agent_len",
"users_break_glass_local", "users_password_local_only", "users_source_valid",
"users_username_limits", "users_username_nonblank",
}
if !slices.Equal(names, want) {
t.Errorf("CHECK constraints = %v, want %v", names, want)
}
}
func TestUsersStore(t *testing.T) {
_, d := openScratch(t, "users_store")
email := "alice@example.com"
alice, err := d.CreateUser(NewUser{Username: " Alice ", DisplayName: "Alice", Email: &email, PasswordHash: "h1"})
if err != nil {
t.Fatal(err)
}
if alice.Username != "Alice" || alice.Source != UserSourceLocal || alice.IsBreakGlass || alice.PasswordHash != "h1" {
t.Fatalf("created user = %+v", alice)
}
t.Run("username is unique case-insensitively", func(t *testing.T) {
for _, name := range []string{"alice", "ALICE", "artex"} {
if _, err := d.CreateUser(NewUser{Username: name}); !errors.Is(err, ErrUsernameTaken) {
t.Errorf("CreateUser(%q) err = %v, want ErrUsernameTaken", name, err)
}
}
if _, err := d.CreateUser(NewUser{Username: " "}); !errors.Is(err, ErrUserInvalid) {
t.Errorf("blank username err = %v, want ErrUserInvalid", err)
}
got, err := d.GetUserByUsername("aLiCe")
if err != nil || got == nil || got.ID != alice.ID {
t.Fatalf("GetUserByUsername(aLiCe) = %+v, %v", got, err)
}
if got, err := d.GetUserByUsername("nobody"); got != nil || err != nil {
t.Fatalf("GetUserByUsername(nobody) = %+v, %v; want nil, nil", got, err)
}
})
t.Run("SSO user has no password and cannot be break-glass", func(t *testing.T) {
u, err := d.CreateUser(NewUser{Username: "sso-user", Source: UserSourceOIDC})
if err != nil {
t.Fatal(err)
}
if u.PasswordHash != "" || u.Source != UserSourceOIDC {
t.Fatalf("sso user = %+v", u)
}
if _, err := d.Exec(`UPDATE users SET is_break_glass=TRUE WHERE id=$1`, u.ID); err == nil {
t.Fatal("a non-local user was marked break-glass")
}
if _, err := d.CreateUser(NewUser{Username: "bad-source", Source: "kerberos"}); err == nil {
t.Fatal("unknown source accepted")
}
})
t.Run("only a local user has a password", func(t *testing.T) {
if _, err := d.CreateUser(NewUser{Username: "sso-pw", Source: UserSourceSAML, PasswordHash: "h"}); !errors.Is(err, ErrUserInvalid) {
t.Errorf("CreateUser(SSO with password) err = %v, want ErrUserInvalid", err)
}
u, err := d.GetUserByUsername("sso-user")
if err != nil || u == nil {
t.Fatalf("sso-user: %v, %v", u, err)
}
if ok, err := d.SetUserPassword(u.ID, "h"); ok || !errors.Is(err, ErrUserInvalid) {
t.Errorf("SetUserPassword(SSO) = %v, %v; want ErrUserInvalid", ok, err)
}
if ok, err := d.SetUserPassword(u.ID, ""); !ok || err != nil {
t.Errorf("clearing an SSO user's password = %v, %v", ok, err)
}
// The constraint holds without the Go check too.
if _, err := d.Exec(`UPDATE users SET password_hash='h' WHERE id=$1`, u.ID); !userCheckViolation(err, "users_password_local_only") {
t.Errorf("raw password on an SSO user err = %v, want users_password_local_only", err)
}
})
t.Run("username limits", func(t *testing.T) {
for _, name := range []string{strings.Repeat("a", UsernameMaxChars+1), "tab\tuser", "nul\x00user", "del\x7fuser", "c1\u0085user"} {
if _, err := d.CreateUser(NewUser{Username: name}); !errors.Is(err, ErrUserInvalid) {
t.Errorf("CreateUser(%q) err = %v, want ErrUserInvalid", name, err)
}
}
// 128 characters, more than 128 bytes.
long := strings.Repeat("é", UsernameMaxChars)
if _, err := d.CreateUser(NewUser{Username: long}); err != nil {
t.Errorf("CreateUser(128 characters) err = %v", err)
}
for _, name := range []string{strings.Repeat("b", UsernameMaxChars+1), "tab\tuser"} {
if _, err := d.Exec(`INSERT INTO users (username) VALUES ($1)`, name); !userCheckViolation(err, "users_username_limits") {
t.Errorf("raw insert of %q err = %v, want users_username_limits", name, err)
}
}
})
t.Run("password", func(t *testing.T) {
if ok, err := d.SetUserPassword(alice.ID, "h2"); !ok || err != nil {
t.Fatalf("SetUserPassword = %v, %v", ok, err)
}
if u, _ := d.GetUserByID(alice.ID); u.PasswordHash != "h2" {
t.Fatalf("password_hash = %q, want h2", u.PasswordHash)
}
if ok, err := d.SetUserPassword(-1, "h"); ok || err != nil {
t.Fatalf("SetUserPassword(missing) = %v, %v", ok, err)
}
})
t.Run("identity is linked to one user only", func(t *testing.T) {
bob, err := d.CreateUser(NewUser{Username: "bob"})
if err != nil {
t.Fatal(err)
}
if err := d.LinkIdentity(alice.ID, "okta", "00u1"); err != nil {
t.Fatal(err)
}
for _, uid := range []int64{alice.ID, bob.ID} {
if err := d.LinkIdentity(uid, "okta", "00u1"); !errors.Is(err, ErrIdentityLinked) {
t.Errorf("relink to user %d err = %v, want ErrIdentityLinked", uid, err)
}
}
// The same subject at another provider is another identity.
if err := d.LinkIdentity(bob.ID, "entra", "00u1"); err != nil {
t.Fatal(err)
}
if u, err := d.GetUserByIdentity("okta", "00u1"); err != nil || u == nil || u.ID != alice.ID {
t.Fatalf("GetUserByIdentity(okta) = %+v, %v", u, err)
}
if u, err := d.GetUserByIdentity("entra", "00u1"); err != nil || u == nil || u.ID != bob.ID {
t.Fatalf("GetUserByIdentity(entra) = %+v, %v", u, err)
}
// Subjects are opaque: no case folding.
if u, err := d.GetUserByIdentity("okta", "00U1"); u != nil || err != nil {
t.Fatalf("GetUserByIdentity(okta, 00U1) = %+v, %v; want nil, nil", u, err)
}
})
t.Run("sessions", func(t *testing.T) {
now := time.Now()
s, err := d.CreateSession("jti-1", alice.ID, now.Add(time.Hour), "ua", "192.0.2.1")
if err != nil {
t.Fatal(err)
}
if !s.Active(now) || s.UserAgent != "ua" || s.ClientIP != "192.0.2.1" {
t.Fatalf("new session = %+v", s)
}
if _, err := d.CreateSession("", alice.ID, now.Add(time.Hour), "", ""); !errors.Is(err, ErrSessionIDNeeded) {
t.Fatalf("empty id err = %v", err)
}
if ok, err := d.TouchSession("jti-1"); !ok || err != nil {
t.Fatalf("TouchSession = %v, %v", ok, err)
}
if ok, _ := d.RevokeSession("jti-1"); !ok {
t.Fatal("RevokeSession: not revoked")
}
if ok, _ := d.RevokeSession("jti-1"); ok {
t.Fatal("second RevokeSession reported a change")
}
if ok, _ := d.TouchSession("jti-1"); ok {
t.Fatal("TouchSession accepted a revoked session")
}
got, err := d.GetSession("jti-1")
if err != nil || got == nil || got.Active(time.Now()) {
t.Fatalf("revoked session = %+v, %v; want inactive", got, err)
}
// Expired: stored but inactive, cannot be touched, and deleted by the sweep.
if _, err := d.CreateSession("jti-old", alice.ID, now.Add(-time.Minute), "", ""); err != nil {
t.Fatal(err)
}
if ok, _ := d.TouchSession("jti-old"); ok {
t.Fatal("TouchSession accepted an expired session")
}
n, err := d.DeleteExpiredSessions()
if err != nil || n != 1 {
t.Fatalf("DeleteExpiredSessions = %d, %v; want 1", n, err)
}
if got, _ := d.GetSession("jti-old"); got != nil {
t.Fatal("expired session not deleted")
}
if got, _ := d.GetSession("jti-1"); got == nil {
t.Fatal("revoked but unexpired session was deleted")
}
// RevokeUserSessions revokes only the open sessions of that user.
for _, id := range []string{"jti-2", "jti-3"} {
if _, err := d.CreateSession(id, alice.ID, now.Add(time.Hour), "", ""); err != nil {
t.Fatal(err)
}
}
if n, err := d.RevokeUserSessions(alice.ID); err != nil || n != 2 {
t.Fatalf("RevokeUserSessions = %d, %v; want 2", n, err)
}
})
t.Run("disable revokes sessions", func(t *testing.T) {
carol, err := d.CreateUser(NewUser{Username: "carol"})
if err != nil {
t.Fatal(err)
}
if _, err := d.CreateSession("carol-1", carol.ID, time.Now().Add(time.Hour), "", ""); err != nil {
t.Fatal(err)
}
if ok, err := d.DisableUser(carol.ID); !ok || err != nil {
t.Fatalf("DisableUser = %v, %v", ok, err)
}
u, _ := d.GetUserByID(carol.ID)
if u.DisabledAt == nil {
t.Fatal("disabled_at not set")
}
if s, _ := d.GetSession("carol-1"); s == nil || s.RevokedAt == nil {
t.Fatalf("session after disable = %+v, want revoked", s)
}
if ok, err := d.DisableUser(-1); ok || err != nil {
t.Fatalf("DisableUser(missing) = %v, %v", ok, err)
}
})
t.Run("a disabled user gets and keeps no session", func(t *testing.T) {
erin, err := d.CreateUser(NewUser{Username: "erin"})
if err != nil {
t.Fatal(err)
}
if _, err := d.CreateSession("erin-1", erin.ID, time.Now().Add(time.Hour), "", ""); err != nil {
t.Fatal(err)
}
// Disabled outside DisableUser, so the session is not revoked.
if _, err := d.Exec(`UPDATE users SET disabled_at=now() WHERE id=$1`, erin.ID); err != nil {
t.Fatal(err)
}
s, err := d.GetSession("erin-1")
if err != nil || s == nil || s.RevokedAt != nil || !s.UserDisabled || s.Active(time.Now()) {
t.Fatalf("session of a disabled user = %+v, %v; want unrevoked but inactive", s, err)
}
if ok, err := d.TouchSession("erin-1"); ok || err != nil {
t.Errorf("TouchSession for a disabled user = %v, %v; want false", ok, err)
}
if _, err := d.CreateSession("erin-2", erin.ID, time.Now().Add(time.Hour), "", ""); !errors.Is(err, ErrUserDisabled) {
t.Errorf("CreateSession for a disabled user err = %v, want ErrUserDisabled", err)
}
if _, err := d.CreateSession("nobody-1", -1, time.Now().Add(time.Hour), "", ""); !errors.Is(err, ErrUserDisabled) {
t.Errorf("CreateSession for a missing user err = %v, want ErrUserDisabled", err)
}
})
t.Run("session user agent and client address are cut", func(t *testing.T) {
ua := strings.Repeat("x", SessionUserAgentMax-1) + "é" // the cut falls inside é
s, err := d.CreateSession("long-ua", alice.ID, time.Now().Add(time.Hour), ua, strings.Repeat("1", 100))
if err != nil {
t.Fatal(err)
}
if len(s.UserAgent) != SessionUserAgentMax-1 || len(s.ClientIP) != SessionClientIPMax {
t.Errorf("stored user agent %d bytes, client IP %d bytes", len(s.UserAgent), len(s.ClientIP))
}
got, err := d.GetSession("long-ua")
if err != nil || got == nil || got.UserAgent != s.UserAgent || got.ClientIP != s.ClientIP {
t.Errorf("GetSession = %+v, %v; want the cut values", got, err)
}
})
t.Run("the last enabled break-glass user cannot be disabled", func(t *testing.T) {
artex := mustBreakGlass(t, d)
if ok, err := d.DisableUser(artex.ID); ok || !errors.Is(err, ErrLastBreakGlass) {
t.Fatalf("DisableUser(last break-glass) = %v, %v; want ErrLastBreakGlass", ok, err)
}
mustBreakGlass(t, d)
// With a second enabled break-glass user, one of them can go.
second, err := d.CreateUser(NewUser{Username: "second-break-glass"})
if err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`UPDATE users SET is_break_glass=TRUE WHERE id=$1`, second.ID); err != nil {
t.Fatal(err)
}
if ok, err := d.DisableUser(second.ID); !ok || err != nil {
t.Fatalf("DisableUser(one of two break-glass) = %v, %v", ok, err)
}
if ok, err := d.DisableUser(artex.ID); ok || !errors.Is(err, ErrLastBreakGlass) {
t.Fatalf("DisableUser(now the last break-glass) = %v, %v; want ErrLastBreakGlass", ok, err)
}
})
t.Run("deleting a user deletes its identities and sessions", func(t *testing.T) {
dave, err := d.CreateUser(NewUser{Username: "dave"})
if err != nil {
t.Fatal(err)
}
if err := d.LinkIdentity(dave.ID, "ldap", "guid-dave"); err != nil {
t.Fatal(err)
}
if _, err := d.CreateSession("dave-1", dave.ID, time.Now().Add(time.Hour), "", ""); err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`DELETE FROM users WHERE id=$1`, dave.ID); err != nil {
t.Fatal(err)
}
var n int
if err := d.QueryRow(`SELECT (SELECT count(*) FROM user_identities WHERE user_id=$1) + (SELECT count(*) FROM user_sessions WHERE user_id=$1)`, dave.ID).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {
t.Fatalf("%d identity/session rows left after deleting the user", n)
}
})
}
+1
View File
@@ -124,6 +124,7 @@ services:
ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit}
ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-}
ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net}
ARTEX_TASK_DNS: ${ARTEX_TASK_DNS:-}
healthcheck:
test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"]
interval: 5s
+1
View File
@@ -51,6 +51,7 @@ services:
ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit}
ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-}
ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net}
ARTEX_TASK_DNS: ${ARTEX_TASK_DNS:-}
healthcheck:
test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"]
interval: 5s
+1
View File
@@ -134,6 +134,7 @@ services:
ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit}
ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-}
ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net}
ARTEX_TASK_DNS: ${ARTEX_TASK_DNS:-}
healthcheck:
test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"]
interval: 5s
+18 -7
View File
@@ -26,8 +26,9 @@ from disposable per-task **worker** containers (`artex-worker:local`).
allowlists (deny by default, blocking RFC1918, loopback, link-local, metadata
endpoints `169.254.169.254`, `fd00:ec2::254`, `168.63.129.16`, `100.100.100.200`,
and IPv6 unless explicitly in `ARTEX_SCOPE_CIDRS`) on both HTTP/HTTPS CONNECT
(`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window). Logs
one JSON line per connection to `/app/data/egress-audit/<id>/egress.jsonl` and stdout.
(`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window).
`ARTEX_TASK_DNS` can pin the proxy's resolver; the worker never resolves
names. Logs one JSON line per connection to `/app/data/egress-audit/<id>/egress.jsonl` and stdout.
## Running with the sandbox
@@ -79,11 +80,21 @@ worker have separate package lists in [the panel Dockerfile](../Dockerfile) and
[the worker Dockerfile](../Dockerfile.worker). The task egress policy also
applies to any runtime dependency downloads initiated inside the worker.
Finding retests run in a conversation without a task sandbox context. In
required mode, Bash reports a missing task sandbox context and WebFetch can
reject the request for lack of a task egress policy. When these restrictions
prevent verification, a retest may return **Cannot confirm**. Check the retest
transcript for the reason before interpreting the result.
In required mode, a finding retest gets its own worker, egress proxy and
workspace at `tasks/retest-<conversation-id>`. Bash and the confined file tools
share that workspace. The first retest turn inherits the source task's current
operator-approved egress scope through the same scope builder as normal tasks.
Finding evidence, retest notes and conversation approval pins do not grant
egress. A finding without a source task or approved scope can run local commands
in the worker, but its network access remains denied by default. The conversation's
target approval gate still applies.
The worker, proxy and network are removed when the retest finishes, fails or is
cancelled; workspace files and the conversation transcript are retained. A new
retest uses a new workspace. Follow-up discussion of a completed retest and
ordinary standalone chats do not gain sandbox execution context (see #805).
Check the transcript before interpreting **Cannot confirm**: a denied target,
missing worker dependency or unavailable runner still prevents verification.
## Security Hardening Notes
+2 -2
View File
@@ -32,7 +32,7 @@ Every enabled `Stream` and `Complete` call measures the assembled `llm.Completio
- `norma`'s `CompletionRequest.System` is a slice of segments that `llm.joinSystem` trims (`strings.TrimSpace`), drops when empty, and joins with blank lines (`"\n\n"`). `MeasureContext` applies the exact same trim, drop-empty, and `"\n\n"` join rules per slice.
- When `DynamicBoundary > 0`, `System` is split at `b = min(DynamicBoundary, len(System))`: `System[:b]` is measured into `system_static_bytes` and `System[b:]` into `system_dynamic_bytes`.
- When `DynamicBoundary <= 0`, there is no provider-visible cache split, so the entire `System` slice is measured as one block in `system_static_bytes` and `system_dynamic_bytes` is `0`.
- **Why this choice**: `agent/deferred.go` returns `boundary = 0` when no global deferred-MCP block exists and `boundary = len(system)` when one does. Placing the single unsplit block in `system_static_bytes` ensures `system_static_bytes + system_dynamic_bytes` always equals total system bytes and `system_dynamic_bytes > 0` strictly signals a dynamic suffix placed after a cache breakpoint.
- **Why this choice**: placing the single unsplit block in `system_static_bytes` ensures `system_static_bytes + system_dynamic_bytes` always equals total system bytes, and `system_dynamic_bytes` measures only what sits after a cache breakpoint. The boundary covers all of the agent's segments (`agent/deferred.go` sets `len(system)`; the goal decomposer sets 1 for its single segment). The planner, worker, chat and main agent turn on the untrusted-output boundary (on by default), so their one segment after it is the constant note `norma` appends (about 270 bytes); the goal decomposer does not, so its `system_dynamic_bytes` is 0. The opt-in `ARTEX_CACHE_PREFIX` worker split also moves the per-intent tail after the boundary.
- **`tool_count` & `tools_bytes`**: `len(req.Tools)` and `len(json.Marshal(req.Tools))` (`0` when no tools). Go's `encoding/json` sorts map keys deterministically.
- **`message_count`, `messages_user_bytes`, `messages_assistant_bytes`, `messages_other_bytes`, `last_message_bytes`**: each `llm.Message` is measured by `len(json.Marshal(msg))` and accumulated by role (`user`, `assistant`, or other); `last_message_bytes` is the serialized byte size of the final message.
- **`tool_result_bytes`**: serialized byte length of `tool_result` content blocks inside messages. Reported as an **informational subset** of `messages_user_bytes` (not added to the partition denominator, avoiding double counting).
@@ -122,7 +122,7 @@ ORDER BY input_tokens DESC;
- **Recommendation: Proceed with a surgical `worker` prefix split (`ARTEX_CACHE_PREFIX`); verify `planner` cross-round cache behavior and `ARTEX_COMPACTION_MEMO` with live `ARTEX_CONTEXT_TELEMETRY=1` data before changing them.**
- **Actual system-prompt volatility by lane (built-in prompts)**:
`system_dynamic` is **0.0%** across all lanes today because `agent/deferred.go` sets `DynamicBoundary = 0` (no global deferred MCP) or `len(system)` (everything before the boundary). Auditing the built-in templates and assembly in `agent/worker.go` and `agent/planner.go` shows what actually varies:
In production `system_dynamic` holds only the constant untrusted-output note (about 270 bytes, on the lanes that turn that boundary on), because `agent/deferred.go` always sets `DynamicBoundary = len(system)`; the opt-in `ARTEX_CACHE_PREFIX` worker split sets it to 1 and moves the per-intent tail after it. The 0.0% in the table comes from the representative fixture (`TestLLMContextRepresentativeFixtureReport`), which does not model `system_dynamic`. Auditing the built-in templates and assembly in `agent/worker.go` and `agent/planner.go` shows what actually varies:
| Lane | Stable per task | Volatile per intent / round |
|---|---|---|
+60 -1
View File
@@ -27,6 +27,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/egress"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/miekg/dns"
"github.com/projectdiscovery/dnsx/libs/dnsx"
@@ -67,6 +68,10 @@ type Engine struct {
resolv *dnsx.DNSX
client *http.Client
// sandboxPolicy returns the task's egress policy while the panel runs in
// ARTEX_SANDBOX=required mode, nil otherwise. It is set once, before jobs.
sandboxPolicy func(context.Context) *sandbox.EgressPolicy
jobs chan job
cool sync.Map // dedup/cooldown: "kind:id" -> time.Time (last run)
once sync.Once
@@ -256,6 +261,50 @@ func buildClient(proxy func() string) *http.Client {
}
}
// SetSandboxPolicy installs the source of the task egress policy applied to
// panel-side HTTP probes while ARTEX_SANDBOX=required. It must return nil when
// the sandbox is off; the probe then keeps the recording-proxy path. Set it once
// at construction, before any job is enqueued.
func (e *Engine) SetSandboxPolicy(policy func(context.Context) *sandbox.EgressPolicy) {
e.sandboxPolicy = policy
}
// sandboxClient probes through the task's sandbox egress policy: every connection
// is resolved, checked and pinned by the policy, with no proxy and no environment
// proxy, so a proxy cannot route around it. The pinned address then goes through
// the target gate's pinned dialer, as on the recording-proxy client: a probe
// without a target scope is refused, and a gated scope still needs a pin. This
// is the order the WebFetch and http tool sandbox dialers use. Redirects stay
// off, as on the recording-proxy client.
func sandboxClient(policy *sandbox.EgressPolicy) *http.Client {
gate := intercept.PinnedDialer("enrich", true)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
TLSHandshakeTimeout: httpTimeout,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked invalid target %q: %w", addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox enrich blocked invalid port %q", portStr)
}
ip, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox enrich blocked: %w", err)
}
return gate(ctx, network, net.JoinHostPort(ip.String(), portStr))
},
}
return &http.Client{
Transport: egress.Dynamic("enrich", tr),
Timeout: httpTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
}
// ResolveDomain enqueues a DNS resolution for a domain asset (ungated). host is the
// FQDN. No-op for an empty engine.
func (e *Engine) ResolveDomain(id int64, host string) { e.enqueue(job{jobDNS, id, host, nil}) }
@@ -377,7 +426,17 @@ func (e *Engine) doHTTP(ctx context.Context, id int64, rawURL string) {
return
}
intercept.ApplyAssessmentUserAgent(req)
resp, err := e.client.Do(req)
client := e.client
if e.sandboxPolicy != nil {
if policy := e.sandboxPolicy(ctx); policy != nil {
if err := policy.CheckURL(ctx, rawURL); err != nil {
slog.Warn("[enrich] HTTP probe blocked by sandbox egress policy", "url", rawURL, "err", err)
return
}
client = sandboxClient(policy)
}
}
resp, err := client.Do(req)
if err != nil {
return
}
+182
View File
@@ -0,0 +1,182 @@
package enrich
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
)
// A probe scheduled while ARTEX_SANDBOX=required must use the task egress policy,
// not the recording proxy: loopback, IMDS and RFC1918 are refused even when the
// target name is in scope and resolves there.
func TestSandboxPolicyBlocksInternalProbes(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 4)
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
e := New(nil, nil, 1)
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
defer e.Close()
for _, target := range []string{
"http://127.0.0.1:" + strconv.Itoa(port) + "/",
"http://169.254.169.254/",
"http://10.0.0.1/",
"http://allowed.example:" + strconv.Itoa(port) + "/",
} {
e.doHTTP(context.Background(), 1, target)
}
select {
case <-accepted:
t.Fatal("a sandboxed probe connected to a forbidden target")
case <-time.After(100 * time.Millisecond):
}
}
// The sandbox dialer resolves and pins the target itself: a name in scope that
// answers a private address is refused before any connection, even when the URL
// check is bypassed.
func TestSandboxDialerPinsResolvedAddress(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
accepted := make(chan struct{}, 1)
go func() {
c, err := ln.Accept()
if err == nil {
accepted <- struct{}{}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
policy, err := sandbox.NewEgressPolicy("t1", []string{"allowed.example"}, nil, nil)
if err != nil {
t.Fatal(err)
}
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}
if _, err := sandboxClient(policy).Get("http://allowed.example:" + strconv.Itoa(port) + "/"); err == nil {
t.Fatal("the sandbox dialer connected to a name resolving to loopback")
}
select {
case <-accepted:
t.Fatal("the sandbox dialer opened a connection to loopback")
case <-time.After(100 * time.Millisecond):
}
}
// A target explicitly inside the task scope CIDRs still probes normally through
// the sandbox transport.
func TestSandboxClientAllowsScopedTarget(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("ok"))
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
ctx := intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "t1"})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := sandboxClient(policy).Do(req)
if err != nil {
t.Fatalf("scoped target refused: %v", err)
}
resp.Body.Close()
}
// The sandbox policy narrows the target gate, it does not replace it: a target
// inside the sandbox scope is still refused without a target scope, and under a
// gated scope that does not decide it.
func TestSandboxClientKeepsTargetGate(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
hits.Add(1)
}))
defer srv.Close()
policy, err := sandbox.NewEgressPolicy("t1", nil, []string{"127.0.0.1/32"}, nil)
if err != nil {
t.Fatal(err)
}
gated := intercept.WithTargetScope(context.Background(), intercept.TargetScope{
TaskID: "t1", Enabled: func() bool { return true },
})
for name, ctx := range map[string]context.Context{"no target scope": context.Background(), "gate on": gated} {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if resp, err := sandboxClient(policy).Do(req); err == nil {
resp.Body.Close()
t.Fatalf("%s: the sandbox client skipped the target gate", name)
}
}
if hits.Load() != 0 {
t.Fatalf("the target received %d request(s)", hits.Load())
}
}
type countingRoundTripper struct{ calls *atomic.Int32 }
func (c countingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
c.calls.Add(1)
return nil, errors.New("normal client used")
}
// doHTTP must select the sandbox client when the policy hook is set: the normal
// recording-proxy client would otherwise be used even in required mode.
func TestDoHTTPUsesSandboxClient(t *testing.T) {
var normalCalls atomic.Int32
e := New(nil, nil, 1)
defer e.Close()
e.client = &http.Client{Transport: countingRoundTripper{calls: &normalCalls}}
policy, err := sandbox.NewEgressPolicy("t1", nil, nil, nil)
if err != nil {
t.Fatal(err)
}
e.SetSandboxPolicy(func(context.Context) *sandbox.EgressPolicy { return policy })
e.doHTTP(context.Background(), 1, "http://127.0.0.1:1/")
if n := normalCalls.Load(); n != 0 {
t.Fatalf("doHTTP used the normal client %d time(s) under a sandbox policy", n)
}
}
+3 -3
View File
@@ -19,8 +19,8 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
Pattern: "--force", Action: "deny", Message: "force push is forbidden"},
{ID: 2, Name: "argv allow curl", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["curl"]`, Action: "allow"},
{ID: 3, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 3, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
g := NewWithInterceptor(ic)
gate := &fakeGate{t: t, check: unpinnedOnce, request: func(int, []intercept.TargetRequest, *intercept.Decision) intercept.TargetResult {
@@ -29,7 +29,7 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) {
g.gate = gate
ctx := gateOn(context.Background(), "7", time.Minute)
if block, msg := pre(g, ctx, "Bash", `{"command":"nmap --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
if block, msg := pre(g, ctx, "Bash", `{"command":"whois --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") {
t.Fatalf("deny over argv allow: block=%v msg=%q", block, msg)
}
if gate.checks != 0 {
+50
View File
@@ -180,6 +180,56 @@ func TestTargetOnlyGuardAppliesBuiltinDenyRules(t *testing.T) {
}
}
// The seeded recursive-force-delete rule holds for every shell spelling of the
// command: Bash removes quotes, backslashes and line continuations and decodes
// $'...' before it runs rm, so the hook decides on the same words. Both the
// worker guard and the target-only guard read the rules from the database.
func TestBuiltinRecursiveDeleteRuleDecodesShellWords(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
db.SkipPGUnavailable(t, err)
}
d, err := db.Open(dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
const ruleMsg = "Recursive force delete is forbidden"
denied := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`/bin/r\m -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m --recursive ./x`,
"r\\\nm -rf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr\\m -rf ./x",
"true\nrm -rf ./x",
}
for name, g := range map[string]*Guard{
"worker guard": NewWithInterceptor(intercept.New(d)),
"target-only guard": NewTargetOnly(intercept.New(d)),
} {
for _, cmd := range denied {
input, _ := json.Marshal(map[string]string{"command": cmd})
if block, msg := pre(g, context.Background(), "Bash", string(input)); !block || !strings.Contains(msg, ruleMsg) {
t.Errorf("%s: %q block=%v msg=%q, want the recursive-force-delete rule", name, cmd, block, msg)
}
}
input, _ := json.Marshal(map[string]string{"command": "rm -r ./x"})
if block, msg := pre(g, context.Background(), "Bash", string(input)); block {
t.Errorf("%s: rm -r without force was blocked: %s", name, msg)
}
}
}
// A deny rule with an oversized message reaches the model capped, with the
// platform framing and the guidance intact.
func TestDenyRuleReasonIsCapped(t *testing.T) {
+1 -1
View File
@@ -78,10 +78,10 @@ func TestHardeningInterceptRules(t *testing.T) {
{"closed: git -c option", `{"command":"git -c protocol.ext.allow=always clone https://github.com/a/b"}`, true, "ask"},
{"closed: bash -c $(curl)", `{"command":"bash -c \"$(curl -s https://e/x.sh)\""}`, true, "ask"},
{"closed: curl | tar", `{"command":"curl -s https://e/x.tgz | tar xzf -"}`, true, "ask"},
{"closed: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, true, "ask"},
// Documented OPEN bypasses: no prompt fires (the skill still binds the agent).
{"open: download host not listed", `{"command":"curl -s https://files.example.com/tool.py -o t.py"}`, false, ""},
{"open: JSON-escaped whitespace", `{"command":"pip\tinstall requests"}`, false, ""},
{"open: base64 split from run", `{"command":"base64 -d blob.b64 > s.sh"}`, false, ""},
// Documented false positive: harmless command trips the net.
+13 -1
View File
@@ -29,6 +29,9 @@ var alwaysAllowDenylist = func() map[string]bool {
"mvn gradle dotnet apt apt-get dpkg dnf yum rpm pacman apk brew snap flatpak",
// version control and build generators: run hooks, aliases and script files
"git cmake ctest cpack",
// tools whose flags run code chosen by the caller: a prefix covers every flag
// (sqlmapapi: sqlmap's REST API server; argvProgramName strips its .py launcher)
"sqlmap sqlmapapi sqlite nmap",
// orchestration: run images, playbooks and plans
"docker docker-compose podman nerdctl kubectl helm ansible ansible-playbook terraform pulumi vagrant",
// destructive
@@ -44,13 +47,22 @@ var alwaysAllowDenylist = func() map[string]bool {
}()
// argvProgramName normalises a program token for the denylist: the basename,
// in lower case, without a trailing version (python3.11, php8.2, perl5, pip3)
// in lower case, without an interpreter or launcher extension (sqlmap.py,
// sqlite3.exe), without a trailing version (python3.11, php8.2, perl5, pip3)
// and with every mkfs.* variant reduced to mkfs.
func argvProgramName(tok string) string {
name := strings.ToLower(path.Base(tok))
if strings.HasPrefix(name, "mkfs.") {
return "mkfs"
}
// A script or a Windows launcher runs the same program as its bare name:
// sqlmap.py, nmap.exe and sqlite3.exe must not slip past the denylist.
for _, ext := range []string{".exe", ".cmd", ".bat", ".ps1", ".py", ".pl", ".rb", ".sh", ".bash", ".lua", ".php", ".js"} {
if strings.HasSuffix(name, ext) {
name = strings.TrimSuffix(name, ext)
break
}
}
// Strip a trailing run of digits and dots, but only after a letter, so a
// name made only of digits (or ".") is kept as is.
end := len(name)
+18 -7
View File
@@ -14,12 +14,14 @@ func TestArgvAllowDenylist(t *testing.T) {
"env", "/usr/bin/env", "bash", "/bin/sh", "find", "rm", "mkfs", "mkfs.ext4", "/sbin/mkfs.xfs",
"docker", "kubectl", "npm", "sudo", "xargs", "Rscript", ".",
"git", "/usr/bin/git", "cmake", "cmake3", "/usr/bin/cmake", "ctest", "cpack",
"sqlmap", "/usr/bin/sqlmap", "sqlite", "sqlite3", "/usr/bin/sqlite3", "nmap", "/usr/bin/nmap",
"sqlmap.py", "/opt/sqlmap/sqlmap.py", "sqlmapapi", "/opt/sqlmap/sqlmapapi.py", "sqlite3.exe", "nmap.exe", "nmap.sh",
} {
if !ArgvAllowDenied(prog) {
t.Errorf("%q is not denied", prog)
}
}
for _, prog := range []string{"nmap", "curl", "ls", "gh", "x", "7z", "pythonic"} {
for _, prog := range []string{"whois", "curl", "ls", "gh", "x", "7z", "pythonic"} {
if ArgvAllowDenied(prog) {
t.Errorf("%q is denied, want allowable", prog)
}
@@ -34,8 +36,8 @@ func TestAlwaysAllowPrefix(t *testing.T) {
if got, err := AlwaysAllowPrefix("Bash", bash("gh pr list --limit 5")); err != nil || !slices.Equal(got, []string{"gh", "pr", "list"}) {
t.Fatalf("gh pr list: %q %v", got, err)
}
if got, err := AlwaysAllowPrefix("Bash", bash("nmap -p 80 10.0.0.1")); err != nil || !slices.Equal(got, []string{"nmap"}) {
t.Fatalf("nmap: %q %v", got, err)
if got, err := AlwaysAllowPrefix("Bash", bash("whois example.com")); err != nil || !slices.Equal(got, []string{"whois"}) {
t.Fatalf("whois: %q %v", got, err)
}
for name, c := range map[string]struct {
tool string
@@ -58,6 +60,14 @@ func TestAlwaysAllowPrefix(t *testing.T) {
"git config": {"Bash", bash("git config user.name x")},
"cmake": {"Bash", bash("cmake --version")},
"ctest": {"Bash", bash("ctest -N")},
"sqlmap": {"Bash", bash("sqlmap --version")},
"path to sqlmap": {"Bash", bash("/usr/bin/sqlmap -u http://127.0.0.1/")},
"sqlmap.py": {"Bash", bash("/opt/sqlmap/sqlmap.py -u http://127.0.0.1/")},
"sqlmapapi": {"Bash", bash("/opt/sqlmap/sqlmapapi.py --version")},
"sqlite3": {"Bash", bash("sqlite3 -version")},
"sqlite3.exe": {"Bash", bash("sqlite3.exe -version")},
"nmap": {"Bash", bash("nmap -sV -p 80 127.0.0.1")},
"path to nmap": {"Bash", bash("/usr/bin/nmap -p 80 127.0.0.1")},
} {
if got, err := AlwaysAllowPrefix(c.tool, c.input); err == nil {
t.Errorf("%s: prefix %q, want a refusal", name, got)
@@ -92,17 +102,18 @@ func TestArgvDenylistAtMatching(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
argv(1, `["python"]`, "allow"), argv(2, `["python3.11"]`, "allow"), argv(3, `["find"]`, "allow"),
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), ask,
argv(4, `["/usr/bin/env"]`, "allow"), argv(5, `["nmap"]`, "allow"), argv(8, `["whois"]`, "allow"),
argv(9, `["sqlmap"]`, "allow"), argv(10, `["sqlite3"]`, "allow"), ask,
})
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env"} {
for _, cmd := range []string{"python x.py", "python3.11 -c 'import os'", "find . -name x", "/usr/bin/env", "nmap -p 80 x", "sqlmap -u http://127.0.0.1/", "sqlite3 -version"} {
input, _ := json.Marshal(map[string]string{"command": cmd})
dec, ok := ic.Match("Bash", input)
if !ok || dec.Action != "ask" || dec.RuleID != 99 {
t.Errorf("%q: %+v %v, want the fallback ask rule", cmd, dec, ok)
}
}
if dec, ok := ic.Match("Bash", []byte(`{"command":"nmap -p 80 x"}`)); !ok || dec.Action != "allow" || dec.RuleID != 5 {
t.Errorf("nmap: %+v %v, want the argv allow", dec, ok)
if dec, ok := ic.Match("Bash", []byte(`{"command":"whois example.com"}`)); !ok || dec.Action != "allow" || dec.RuleID != 8 {
t.Errorf("whois: %+v %v, want the argv allow", dec, ok)
}
ic.SetRulesForTest([]db.InterceptRule{argv(1, `["python"]`, "allow"), argv(6, `["python"]`, "deny"), argv(7, `["find"]`, "ask")})
+138 -1
View File
@@ -1,8 +1,10 @@
package intercept
import (
"bytes"
"encoding/json"
"path"
"strconv"
"strings"
"mvdan.cc/sh/v3/syntax"
@@ -51,6 +53,68 @@ func argvCompoundMatches(tokens []string, toolName string, input []byte) bool {
return bashCommandMatchesArgv(tokens, in.Command, 0)
}
// bashDecodedInput returns the input of a Bash call with its command replaced
// by the commands the shell runs, joined by "; ", each word decoded as callWordOf
// decodes it (backslash escapes, line continuations, single and double quotes,
// $'...'), so a text rule written for "rm -rf" also meets r\m -rf. A word
// that holds an expansion is kept as written. ok is false for another tool, or
// when the command is empty or does not parse.
func bashDecodedInput(toolName string, input []byte) (string, bool) {
if toolName != "Bash" {
return "", false
}
var in map[string]json.RawMessage
if json.Unmarshal(input, &in) != nil {
return "", false
}
var command string
if json.Unmarshal(in["command"], &command) != nil || strings.TrimSpace(command) == "" {
return "", false
}
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
return "", false
}
printer := syntax.NewPrinter()
var cmds []string
syntax.Walk(f, func(n syntax.Node) bool {
call, ok := n.(*syntax.CallExpr)
if !ok || len(call.Args) == 0 {
return true
}
words := make([]string, len(call.Args))
for i, w := range call.Args {
if cw := callWordOf(w); cw.Literal {
words[i] = cw.Value
continue
}
var sb strings.Builder
_ = printer.Print(&sb, w)
words[i] = sb.String()
}
cmds = append(cmds, strings.Join(words, " "))
return true
})
if len(cmds) == 0 {
return "", false
}
// "; " and not a newline: JSON writes a newline as \n, and its "n" would
// glue to the next word (no word boundary before "rm" in "\nrm"). No HTML
// escaping, so < > & read as they do in the input as written.
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if enc.Encode(strings.Join(cmds, "; ")) != nil {
return "", false
}
in["command"] = bytes.Clone(bytes.TrimSpace(buf.Bytes()))
buf.Reset()
if enc.Encode(in) != nil {
return "", false
}
return string(bytes.TrimSpace(buf.Bytes())), true
}
func bashCommandMatchesArgv(rule []string, command string, depth int) bool {
f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")
if err != nil {
@@ -190,8 +254,9 @@ func callWordOf(w *syntax.Word) callWord {
}
sb.WriteString(s)
case *syntax.SglQuoted:
// $'...' is fixed text too, once its escapes are decoded.
if p.Dollar {
literal = false
sb.WriteString(unescapeANSIC(p.Value))
continue
}
sb.WriteString(p.Value)
@@ -276,6 +341,78 @@ func unescapeDblQuotedLit(s string) string {
return sb.String()
}
// unescapeANSIC decodes the body of a $'...' string as Bash does: \a \b \e \E
// \f \n \r \t \v \\ \' \" \?, octal \nnn, \xHH, \uHHHH, \UHHHHHHHH and \cX.
// An unknown escape is kept as written, backslash included.
func unescapeANSIC(s string) string {
var sb strings.Builder
sb.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] != '\\' || i+1 >= len(s) {
sb.WriteByte(s[i])
continue
}
i++
switch e := s[i]; e {
case 'a':
sb.WriteByte('\a')
case 'b':
sb.WriteByte('\b')
case 'e', 'E':
sb.WriteByte(0x1b)
case 'f':
sb.WriteByte('\f')
case 'n':
sb.WriteByte('\n')
case 'r':
sb.WriteByte('\r')
case 't':
sb.WriteByte('\t')
case 'v':
sb.WriteByte('\v')
case '\\', '\'', '"', '?':
sb.WriteByte(e)
case 'c':
if i+1 < len(s) {
i++
sb.WriteByte(s[i] & 0x1f)
} else {
sb.WriteString(`\c`)
}
case '0', '1', '2', '3', '4', '5', '6', '7':
j := i
for j < len(s) && j < i+3 && s[j] >= '0' && s[j] <= '7' {
j++
}
v, _ := strconv.ParseUint(s[i:j], 8, 16)
sb.WriteByte(byte(v))
i = j - 1
case 'x', 'u', 'U':
digits := map[byte]int{'x': 2, 'u': 4, 'U': 8}[e]
j := i + 1
for j < len(s) && j <= i+digits && strings.IndexByte("0123456789abcdefABCDEF", s[j]) >= 0 {
j++
}
if j == i+1 {
sb.WriteByte('\\')
sb.WriteByte(e)
continue
}
v, _ := strconv.ParseUint(s[i+1:j], 16, 32)
if e == 'x' {
sb.WriteByte(byte(v))
} else {
sb.WriteRune(rune(v))
}
i = j - 1
default:
sb.WriteByte('\\')
sb.WriteByte(e)
}
}
return sb.String()
}
func hasAssignPrefix(s string) bool {
eq := strings.IndexByte(s, '=')
if eq <= 0 {
+117 -19
View File
@@ -231,20 +231,20 @@ func TestArgvAllowRemainsStrict(t *testing.T) {
cmd string
want bool
}{
{"nmap -p 80 x", true},
{"command nmap x", false},
{"nmap x; true", false},
{"bash -c 'nmap x'", false},
{"/usr/bin/nmap x", false},
{"sudo nmap x", false},
{"env FOO=1 nmap x", false},
{"nmap $(id)", false},
{"whois -p 80 x", true},
{"command whois x", false},
{"whois x; true", false},
{"bash -c 'whois x'", false},
{"/usr/bin/whois x", false},
{"sudo whois x", false},
{"env FOO=1 whois x", false},
{"whois $(id)", false},
}
for _, tc := range cases {
t.Run(tc.cmd, func(t *testing.T) {
_, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd))
_, got := matchSingleArgvRule("allow", `["whois"]`, "Bash", bashInput(tc.cmd))
if got != tc.want {
t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want)
t.Errorf("allow [\"whois\"] on %q = %v, want %v", tc.cmd, got, tc.want)
}
})
}
@@ -256,15 +256,15 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
[]byte(``),
[]byte(`not json`),
[]byte(`{}`),
bashInput(`nmap 'unterminated`),
bashInput(`nmap $(`),
bashInput(`whois 'unterminated`),
bashInput(`whois $(`),
bashInput(`if then fi; (( (`),
bashInput(`bash -c "unterminated`),
bashInput(`eval "((("`),
}
for _, action := range []string{"deny", "ask", "allow"} {
for _, in := range inputs {
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok {
if dec, ok := matchSingleArgvRule(action, `["whois"]`, "Bash", in); ok {
t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec)
}
}
@@ -274,18 +274,116 @@ func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) {
func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
{ID: 1, Name: "allow simple whois", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"},
{ID: 2, Name: "deny compound whois", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "deny"},
})
// Simple command hits the higher-priority allow rule.
dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x"))
dec, ok := ic.Match("Bash", bashInput("whois -p 80 x"))
if !ok || dec.Action != "allow" || dec.RuleID != 1 {
t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok)
t.Fatalf("simple whois: got (%+v, %v), want allow rule 1", dec, ok)
}
// Compound command fails the strict allow rule and falls through to the deny rule.
dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true"))
dec, ok = ic.Match("Bash", bashInput("whois -p 80 x; true"))
if !ok || dec.Action != "deny" || dec.RuleID != 2 {
t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok)
t.Fatalf("compound whois: got (%+v, %v), want deny rule 2", dec, ok)
}
}
// An ANSI-C string is fixed text: $'nmap' and $'\x6emap' run nmap.
func TestArgvDenyDecodesANSICQuoting(t *testing.T) {
for _, cmd := range []string{`$'nmap' -sV x`, `$'\x6emap' -sV x`, `$'\156map' -sV x`, `n$'\u006d'ap x`, `bash -c $'nmap x'`} {
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(cmd)); !ok {
t.Errorf("deny nmap missed %q", cmd)
}
}
if _, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(`$'nmapx' x`)); ok {
t.Error(`deny nmap matched $'nmapx'`)
}
}
func TestUnescapeANSIC(t *testing.T) {
for in, want := range map[string]string{
`rm`: "rm",
`r\x6d`: "rm",
`r\155`: "rm",
`r\u006D`: "rm",
`r\U0000006d`: "rm",
`-r\x66`: "-rf",
`a\tb\n`: "a\tb\n",
`\'\"\\\?`: `'"\?`,
`\e\E`: "\x1b\x1b",
`\cA`: "\x01",
`\q\x`: `\q\x`,
} {
if got := unescapeANSIC(in); got != want {
t.Errorf("unescapeANSIC(%q) = %q, want %q", in, got, want)
}
}
}
// A text deny or ask rule on a Bash command also meets the command as the
// shell decodes it: quotes, backslashes, ANSI-C strings and line
// continuations removed, each command on its own line.
func TestTextRulesMatchShellDecodedCommand(t *testing.T) {
const rmrf = `(?i)\brm\b.{0,80}(?:-[a-z]*r[a-z]*f|-[a-z]*r[a-z]*\s+-+[a-z]*f)`
cmds := []string{
`rm -rf ./x`,
`r\m -rf ./x`,
`\r\m -rf ./x`,
`r''m -rf ./x`,
`"r"m -rf ./x`,
`'rm' -rf ./x`,
`/bin/r\m -rf ./x`,
`$'rm' -rf ./x`,
`$'r\x6d' -rf ./x`,
`rm -r''f ./x`,
`rm -r"f" ./x`,
`rm $'-rf' ./x`,
`rm -r$'f' ./x`,
`rm -R -$'f' ./x`,
`command r\m -rf ./x`,
"r\\\nm -rf ./x",
"rm -r\\\nf ./x",
"rm -r \\\n -f ./x",
"cd ./w\nr''m -rf ./x",
"true\nrm -rf ./x",
"echo $(r\\m -rf ./x)",
}
stringCmds := []string{`r\m -rf ./x`, `r''m -rf ./x`, `"r"m -rf ./x`, `rm -r''f ./x`, `rm -r$'f' ./x`}
for _, action := range []string{"deny", "ask"} {
for _, typ := range []string{"regex", "string"} {
pattern, hits := rmrf, cmds
if typ == "string" {
pattern, hits = "rm -rf", stringCmds
}
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: typ, Pattern: pattern, Action: action}})
for _, cmd := range hits {
if _, ok := ic.Match("Bash", bashInput(cmd)); !ok {
t.Errorf("%s %s rule missed %q", action, typ, cmd)
}
}
for _, cmd := range []string{`rm -r ./x`, `echo r\m`, `ls -rf`} {
if _, ok := ic.Match("Bash", bashInput(cmd)); ok {
t.Errorf("%s %s rule matched %q", action, typ, cmd)
}
}
}
}
// An allow rule is matched on the text as written only.
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "allow rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "allow"}})
if _, ok := ic.Match("Bash", bashInput(`r\m -rf ./x`)); ok {
t.Error(`allow rule matched the decoded form of r\m -rf`)
}
// Other tools are matched as written.
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "deny rm", Enabled: true, Priority: 100,
MatchTarget: "tool_input", MatchType: "regex", Pattern: rmrf, Action: "deny"}})
if _, ok := ic.Match("Write", []byte(`{"command":"r\\m -rf ./x"}`)); ok {
t.Error("a non-Bash tool input was shell-decoded")
}
}
+9 -9
View File
@@ -133,9 +133,9 @@ func TestArgvRejectsWrappers(t *testing.T) {
// no rule and the normal flow (judge, approval) continues.
func TestArgvParseFailureIsNoMatch(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow nmap", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}})
for _, input := range []string{`{"command":"nmap 'unterminated"}`, `{"command":"nmap $("}`, `{"command":""}`, `{}`, `not json`} {
ic.SetRulesForTest([]db.InterceptRule{{ID: 1, Name: "argv allow whois", Enabled: true, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}})
for _, input := range []string{`{"command":"whois 'unterminated"}`, `{"command":"whois $("}`, `{"command":""}`, `{}`, `not json`} {
if dec, ok := ic.Match("Bash", []byte(input)); ok {
t.Errorf("%s matched: %+v", input, dec)
}
@@ -216,18 +216,18 @@ func TestArgvAllowBelowDeny(t *testing.T) {
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex",
Pattern: `--force`, Action: "deny"},
{ID: 2, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["nmap"]`, Action: "allow"},
{ID: 2, Name: "argv allow whois", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv",
Pattern: `["whois"]`, Action: "allow"},
})
dec, ok := ic.Match("Bash", []byte(`{"command":"nmap --force 10.0.0.1"}`))
dec, ok := ic.Match("Bash", []byte(`{"command":"whois --force 10.0.0.1"}`))
if !ok || dec.Action != "deny" || dec.RuleID != 1 {
t.Fatalf("force flag: %+v %v, want the deny rule", dec, ok)
}
dec, ok = ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1"}`))
dec, ok = ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1"}`))
if !ok || dec.Action != "allow" || dec.RuleID != 2 {
t.Fatalf("nmap: %+v %v, want the argv allow", dec, ok)
t.Fatalf("whois: %+v %v, want the argv allow", dec, ok)
}
if _, ok := ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1; id"}`)); ok {
if _, ok := ic.Match("Bash", []byte(`{"command":"whois 10.0.0.1; id"}`)); ok {
t.Fatal("a compound command matched the argv rule")
}
if _, ok := compileRule(db.InterceptRule{MatchType: "argv", Pattern: `["-x"]`}); ok {
+21
View File
@@ -0,0 +1,21 @@
package intercept
import "context"
// directHopKey marks a check or a connection the platform opens itself to a
// named hop. A custom HTTP tool's own proxy is such a hop: the tool dials the
// proxy directly, and the proxy, not ARTEX, connects to the target. Pins for it
// bind the addresses the decision compared, never the name alone.
type directHopKey struct{}
// WithDirectHop marks ctx as a direct connection to the hop being checked or
// dialled: the target gate does not treat its pins as name-only.
func WithDirectHop(ctx context.Context) context.Context {
return context.WithValue(ctx, directHopKey{}, true)
}
// DirectHop reports whether ctx was marked by WithDirectHop.
func DirectHop(ctx context.Context) bool {
v, _ := ctx.Value(directHopKey{}).(bool)
return v
}
+16
View File
@@ -834,6 +834,22 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
default:
return false
}
if textRuleMatches(r, subject) {
return true
}
// Bash runs a command only after it removes quotes and backslashes and
// decodes $'...', so r\m -rf runs rm -rf. A deny or ask rule also meets
// the command decoded that way; an allow rule meets the text as written
// only, so decoding never widens what it allows.
if r.MatchTarget != "tool_input" || (r.Action != "deny" && r.Action != "ask") {
return false
}
decoded, ok := bashDecodedInput(toolName, input)
return ok && textRuleMatches(r, decoded)
}
// textRuleMatches matches a regex or string rule against subject.
func textRuleMatches(r compiledRule, subject string) bool {
if r.MatchType == "regex" {
return r.re != nil && r.re.MatchString(subject)
}
+11
View File
@@ -58,6 +58,17 @@ func PinnedDialer(toolName string, scoped bool) func(ctx context.Context, networ
}
}
// PinnedDialerDirect is PinnedDialer for a connection ARTEX opens itself to a
// named hop, such as a custom HTTP tool's own proxy. The hop is not behind the
// proxy: the dial is checked and opened on the addresses the decision compared,
// so a pin for its name cannot be satisfied by a name that later rebinds.
func PinnedDialerDirect(toolName string) func(ctx context.Context, network, addr string) (net.Conn, error) {
dial := PinnedDialer(toolName, true)
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return dial(WithDirectHop(ctx), network, addr)
}
}
// GateOn reports whether ctx carries a target scope whose gate is on.
func GateOn(ctx context.Context) bool {
_, on := renderedScope(ctx)
+15 -10
View File
@@ -233,8 +233,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
// Behind a proxy the proxy chooses the address it connects to, so every pin
// is name-only for this call, whatever the pin row says: the proxy can be
// turned on after a pin was approved. The recording proxy, the global egress
// proxy and a custom tool's own proxy all count.
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
// proxy and a custom tool's own proxy all count. A direct hop (WithDirectHop)
// is not behind them: the tool dials it itself, so its pins bind the
// addresses the decision compared.
direct := DirectHop(c.ctx)
nameOnly := !direct && ((proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)))
var unpinned []TargetRequest
var uses []func()
@@ -280,7 +283,7 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if err != nil {
return c.block(TargetGateUnavailable, "gate_unavailable", ct, "the pins could not be read: "+err.Error())
}
pin := coveringPin(pins, ct.ips, nameOnly)
pin := coveringPin(pins, ct.ips, nameOnly, direct)
if pin == nil && ct.Kind == TargetDomain && !c.fresh {
// A request is about to be raised: the addresses a human reads and
// pins are resolved now, never taken from the cache. A fresh run
@@ -291,11 +294,11 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
if rule, hit := blockRule(rules, ct); hit {
return c.block(TargetRuleBlocked, "rule_blocked", ct, fmt.Sprintf("%s is blocked by an asset rule. %s", ct.Target, rule.Reason()))
}
pin = coveringPin(pins, ct.ips, nameOnly)
pin = coveringPin(pins, ct.ips, nameOnly, direct)
}
if pin != nil {
ct.cover = coverPin
if nameOnly || pin.NameOnlyEffective {
if nameOnly || (pin.NameOnlyEffective && !direct) {
ct.cover = coverNameOnly
}
uses = append(uses, func() { c.pinUsed(ct, pin, nameOnly) })
@@ -396,7 +399,7 @@ func (c *targetCheck) pinUsed(ct *checkedTarget, pin *db.TargetPin, nameOnly boo
return
}
t := ct.audit("pin_match")
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, pin.NameOnlyEffective || nameOnly
t.PinID, t.PinVersion, t.PinnedIPs, t.NameOnlyEffective = pin.ID, pin.Version, pin.PinnedIPs, nameOnly || (pin.NameOnlyEffective && !DirectHop(c.ctx))
c.log("allowed", fmt.Sprintf("Target %s is covered by pin v%d of %s.", ct.Target, pin.Version, c.scope.scopeName()), "", t)
}
@@ -529,11 +532,13 @@ func exemptionHolds(ct *checkedTarget) bool {
}
// coveringPin returns the pin that covers the resolved addresses: the first
// candidate that is name-only, or that holds every address. The address sets
// of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly bool) *db.TargetPin {
// candidate that is name-only, or that holds every address. A direct hop does
// not accept a name-only pin on its name alone: the connection is opened to the
// addresses the decision compared, so such a pin covers only when it holds them
// too. The address sets of two pins are never merged.
func coveringPin(pins []*db.TargetPin, resolved []string, nameOnly, direct bool) *db.TargetPin {
for _, p := range pins {
if nameOnly || p.NameOnlyEffective || subset(resolved, p.PinnedIPs) {
if nameOnly || (!direct && p.NameOnlyEffective) || subset(resolved, p.PinnedIPs) {
return p
}
}
+4 -2
View File
@@ -295,8 +295,10 @@ func (i *Interceptor) openTargetRequest(ctx context.Context, ref db.TargetScopeR
proxied := i.upstreamProxy
i.mu.RUnlock()
// Behind the upstream proxy the proxy chooses the address: the approval is
// for the name, and the pin created from this row says so.
nameOnly := proxied != nil && proxied()
// for the name, and the pin created from this row says so. A direct hop is
// not behind it: the tool dials it itself, so the approval and its pin bind
// the addresses a human reads.
nameOnly := !DirectHop(ctx) && proxied != nil && proxied()
dec := Decision{Action: "ask"}
if ask != nil {
+9
View File
@@ -194,6 +194,15 @@ func (r *Registry) RecordCall(ctx context.Context, id int64, stream, committed b
}
return false, ""
}
if isContentPolicyRefusal(err) {
// A content/safety refusal is the model's own policy, not an outage:
// shouldFailover routes the request to the next profile, but the refusal
// must not move this profile's health score. Otherwise softTrip refusals
// of one prompt would bench an otherwise-healthy profile. Neutral: it
// neither trips nor clears (no Pass), so a real failure already on record
// stays put.
return false, ""
}
if stream && committed {
return false, ""
}
+25
View File
@@ -117,3 +117,28 @@ func TestPoolFeedsRecordCallPolicy(t *testing.T) {
}
})
}
// A provider content/safety refusal fails over but must not move the profile's
// health score: repeated refusals never bench an otherwise-healthy profile, and
// a refusal does not clear a real failure already on record.
func TestRecordCallContentPolicyNeutral(t *testing.T) {
ctx := context.Background()
refusal := fmt.Errorf(`openai: status 400: {"error":{"code":"cyber_policy","message":"flagged"}}`)
reg := NewRegistry(nil, nil)
for i := 0; i < 5; i++ {
if tripped, _ := reg.RecordCall(ctx, 9, false, false, refusal); tripped {
t.Fatalf("refusal #%d tripped the breaker; refusals must be health-neutral", i+1)
}
}
if st := reg.Get(9); st.Fails != 0 || st.Trips != 0 || st.Open() {
t.Fatalf("state=%+v after five content-policy refusals, want untouched", st)
}
// A refusal must leave a real failure already on record in place (no Pass).
reg.RecordCall(ctx, 9, false, false, fmt.Errorf("openai: status 500: down"))
reg.RecordCall(ctx, 9, false, false, refusal)
if st := reg.Get(9); st.Fails != 1 {
t.Fatalf("state=%+v, a refusal must not clear an existing failure", st)
}
}
+36 -3
View File
@@ -226,8 +226,10 @@ func statusOf(err error) int {
//
// Never fails over on context cancellation — that's the user stopping a task or a
// task-level timeout, and burning a backup key on it would both waste credit and
// pollute the run's termination diagnosis. Never on 400 either: a malformed or
// over-long request fails identically everywhere.
// pollute the run's termination diagnosis. A 400 fails over only when it is a
// provider content/safety refusal (isContentPolicyRefusal): a different model may
// accept the same request. A malformed or over-long 400 fails identically
// everywhere and is not retried.
func shouldFailover(ctx context.Context, err error) bool {
if err == nil {
return false
@@ -239,7 +241,11 @@ func shouldFailover(ctx context.Context, err error) bool {
case code == 0:
return true // no status → transport-level failure (reset / DNS / timeout)
case code == 400:
return false // bad or over-long request: identical everywhere
// A provider content/safety refusal (e.g. OpenAI cyber_policy) is NOT
// "identical everywhere": a non-refusing fallback model may well accept
// the same request, so fail over to it. A malformed/over-long 400 still
// fails identically everywhere and does not.
return isContentPolicyRefusal(err)
case code == 401, code == 402, code == 403, code == 404, code == 408, code == 429:
return true
case code >= 500:
@@ -248,6 +254,33 @@ func shouldFailover(ctx context.Context, err error) bool {
return false
}
// isContentPolicyRefusal reports whether a 400 is a provider content/safety
// refusal (which a different model may not share) rather than a malformed
// request. Such a refusal is worth failing over to a non-refusing fallback.
//
// It matches the specific error codes providers return when they decline a
// prompt on content/safety grounds, not loose words. In particular it does NOT
// match request-shape 400s that merely contain the word "safety" — OpenAI's
// safety_identifier parameter or Gemini's safety_settings — which fail
// identically everywhere and must not trigger failover.
func isContentPolicyRefusal(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
for _, code := range []string{
"cyber_policy", // OpenAI offensive-security refusal
"content_policy_violation", // OpenAI moderation refusal
"invalid_prompt", // OpenAI flagged-prompt refusal
"content_filter", // Azure OpenAI content filter (ResponsibleAIPolicyViolation)
} {
if strings.Contains(s, code) {
return true
}
}
return false
}
// isHardFailure reports whether the failure is deterministic (the profile will
// keep failing until a human fixes it) rather than transient. Hard failures open
// the breaker on the first occurrence.
+26
View File
@@ -412,3 +412,29 @@ func TestWindowFilterChargesMaxTokens(t *testing.T) {
t.Fatalf("sent a request whose prompt+max_tokens cannot fit the window (calls=%d)", small.calls)
}
}
// A provider content/safety refusal (HTTP 400 with a known refusal code) fails
// over, because a different model may accept the same request; a malformed 400
// or a request-shape 400 that merely contains "safety" does not.
func TestShouldFailoverContentPolicy(t *testing.T) {
ctx := context.Background()
cases := []struct {
name string
err error
want bool
}{
{"openai cyber_policy", fmt.Errorf(`openai: status 400: {"error":{"code":"cyber_policy"}}`), true},
{"openai moderation", fmt.Errorf("openai: status 400: content_policy_violation"), true},
{"openai invalid_prompt", fmt.Errorf(`openai: status 400: {"code":"invalid_prompt"}`), true},
{"azure content_filter", fmt.Errorf(`azure: status 400: {"code":"content_filter"}`), true},
{"openai safety_identifier param", fmt.Errorf("openai: status 400: Unknown parameter: 'safety_identifier'"), false},
{"gemini safety_settings param", fmt.Errorf("gemini: status 400: invalid safety_settings"), false},
{"plain malformed 400", fmt.Errorf("openai: status 400: bad request"), false},
{"500 still fails over", fmt.Errorf("openai: status 500: down"), true},
}
for _, c := range cases {
if got := shouldFailover(ctx, c.err); got != c.want {
t.Errorf("%s: shouldFailover=%v, want %v", c.name, got, c.want)
}
}
}
+21
View File
@@ -522,3 +522,24 @@ func TestPermanentErrorUnwrap(t *testing.T) {
type permanentSentinel struct{}
func (*permanentSentinel) Error() string { return "sentinel" }
func TestTelegramKeepsUntrustedFieldsOnOneLine(t *testing.T) {
single := Message{Items: []Item{{
Severity: "high",
Name: "title",
VulnClass: "c\nFake: x",
Assets: []string{"h\nq"},
}}}
text, _ := telegramHTML(single)
for _, forged := range []string{"\nFake", "\nq"} {
if strings.Contains(text, forged) {
t.Errorf("untrusted newline forged a line %q in %q", forged, text)
}
}
digest := batchMsg(1)
digest.Items[0].Name = "a\n2. Critical · fake entry"
text, _ = telegramHTML(digest)
if strings.Contains(text, "\n2. Critical") {
t.Errorf("untrusted newline forged a digest entry in %q", text)
}
}
+8 -3
View File
@@ -149,9 +149,9 @@ func telegramHTML(m Message) (string, int) {
telegramEscape(StatusLabel(it.FromStatus)), telegramEscape(StatusLabel(it.ToStatus))))
}
if it.VulnClass != "" && it.VulnClass != it.Title() {
b.WriteString("\n<b>Type</b>: " + telegramEscape(it.VulnClass))
b.WriteString("\n<b>Type</b>: " + telegramEscape(OneLine(it.VulnClass, 0)))
}
if a := assetLine(it.Assets, lim.AssetsShown); a != "" {
if a := OneLine(assetLine(it.Assets, lim.AssetsShown), 0); a != "" {
b.WriteString("\n<b>Assets</b>: " + telegramEscape(a))
}
if s := OneLine(it.Summary, lim.SummaryRunes); s != "" {
@@ -168,8 +168,13 @@ func telegramHTML(m Message) (string, int) {
const telegramReservedRunes = 160
// telegramBatchLine renders one entry of a digest (unescaped; the caller escapes
// it uniformly).
// it uniformly). It is flattened to one line, so a newline in an untrusted
// title or asset cannot forge another digest entry.
func telegramBatchLine(it Item, idx int, lim Limits) string {
return OneLine(telegramBatchLineRaw(it, idx, lim), 0)
}
func telegramBatchLineRaw(it Item, idx int, lim Limits) string {
if a := assetLine(it.Assets, lim.AssetsShown); a != "" {
return fmt.Sprintf("%d. %s · %s — %s", idx, SeverityLabel(it.Severity), it.Title(), a)
}
+12
View File
@@ -32,6 +32,13 @@ type DockerConfig struct {
HostAuditRoot string // host path used in Docker bind mounts for AuditRoot
TaskNetPrefix string // default artex-task-
EgressNet string // default egress-net
// TaskDNS overrides the DNS servers of the egress proxy. The worker does
// not resolve names, so it keeps no DNS configuration. Empty keeps
// Docker's default (the embedded resolver at 127.0.0.11). On Docker
// Desktop, and any host where the embedded resolver forwards to a slow
// upstream, per-request DNS overhead can exceed the egress proxy's
// resolve budget; explicit servers keep it low.
TaskDNS []string
}
type taskContainers struct {
@@ -531,6 +538,11 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
"Binds": []string{b.hostAuditDir(ctx, taskID) + ":/audit:rw"},
},
}
// Omit "Dns" when unset so the serialized spec stays byte-identical
// to the pre-feature form for ARTEX_TASK_DNS-less deployments.
if len(b.cfg.TaskDNS) > 0 {
proxySpec["HostConfig"].(map[string]any)["Dns"] = b.cfg.TaskDNS
}
pid, err := b.createContainer(ctx, proxyName, proxySpec)
if err != nil {
return nil, err
+1331
View File
File diff suppressed because it is too large Load Diff
+385
View File
@@ -0,0 +1,385 @@
package sandbox
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
)
// Container names in the task pods of the Kubernetes backend.
const (
kubeWorkerName = "worker"
kubeProxyName = "egress-proxy"
)
// kubeClient is the minimal Kubernetes API client of the Kubernetes sandbox
// backend: JSON requests on one namespace and pods/exec over WebSocket, with the
// in-cluster service-account token (re-read on every request: bound tokens
// rotate).
type kubeClient struct {
apiServer string
tokenPath string
namespace string
plainHTTP bool // tests only: http:// API server
http *http.Client
tls *tls.Config
}
// newKubeClient builds a client for apiServer. An https:// server is verified
// against the CA in caPath. An http:// server is refused unless allowPlainHTTP
// (set only by tests): the token would travel in clear.
func newKubeClient(apiServer, tokenPath, caPath, namespace string, allowPlainHTTP bool) (*kubeClient, error) {
apiServer = strings.TrimRight(apiServer, "/")
tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12}
if !strings.HasPrefix(apiServer, "https://") && !allowPlainHTTP {
return nil, fmt.Errorf("kubernetes backend: API server %q must use https:// (the service-account token would be sent in clear)", apiServer)
}
if strings.HasPrefix(apiServer, "https://") {
ca, err := os.ReadFile(caPath)
if err != nil {
return nil, fmt.Errorf("kubernetes backend: read CA %s: %w", caPath, err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(ca) {
return nil, fmt.Errorf("kubernetes backend: no certificates in %s", caPath)
}
tlsCfg.RootCAs = pool
}
return &kubeClient{
apiServer: apiServer,
tokenPath: tokenPath,
namespace: namespace,
plainHTTP: allowPlainHTTP && strings.HasPrefix(apiServer, "http://"),
tls: tlsCfg,
http: &http.Client{
Transport: &http.Transport{Proxy: nil, TLSClientConfig: tlsCfg},
Timeout: 30 * time.Second,
// Never follow a redirect: it could carry the bearer token elsewhere.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
},
}, nil
}
func (c *kubeClient) token() (string, error) {
raw, err := os.ReadFile(c.tokenPath)
if err != nil {
return "", fmt.Errorf("%w: read service account token: %v", ErrDockerUnavailable, err)
}
return strings.TrimSpace(string(raw)), nil
}
// kubeAPIError carries the HTTP status and the metav1.Status reason of a failed
// API call. The response body is never forwarded: it can echo object specs or
// exec commands.
type kubeAPIError struct {
Code int
Reason string
}
func (e *kubeAPIError) Error() string {
return fmt.Sprintf("kubernetes API HTTP %d %s", e.Code, e.Reason)
}
var kubeReasonRE = regexp.MustCompile(`^[A-Za-z]{1,64}$`)
func newKubeAPIError(code int, body io.Reader) (*kubeAPIError, string) {
raw, _ := io.ReadAll(io.LimitReader(body, 4096))
var st struct {
Reason string `json:"reason"`
}
_ = json.Unmarshal(raw, &st)
if !kubeReasonRE.MatchString(st.Reason) {
st.Reason = ""
}
return &kubeAPIError{Code: code, Reason: st.Reason}, string(raw)
}
func isKubeStatus(err error, code int) bool {
var ae *kubeAPIError
return errors.As(err, &ae) && ae.Code == code
}
func (c *kubeClient) do(ctx context.Context, method, apiPath string, body, out any) error {
var r io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return err
}
r = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.apiServer+apiPath, r)
if err != nil {
return err
}
tok, err := c.token()
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+tok)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
// The error holds the API URL and namespace: log it, return a generic one.
if ctx.Err() != nil {
return fmt.Errorf("kubernetes API request cancelled: %w", ctx.Err())
}
log.Printf("[runner] kubernetes API %s %s: %v", method, apiPath, err)
return fmt.Errorf("%w: kubernetes API request failed", ErrDockerUnavailable)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
ae, raw := newKubeAPIError(resp.StatusCode, resp.Body)
if ae.Code != http.StatusNotFound && ae.Code != http.StatusConflict {
log.Printf("[runner] kubernetes API %s %s: HTTP %d: %.512s", method, apiPath, ae.Code, raw)
}
return ae
}
if out != nil {
return json.NewDecoder(resp.Body).Decode(out)
}
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}
func (c *kubeClient) nsPath(kind string) string {
switch kind {
case "networkpolicies":
return "/apis/networking.k8s.io/v1/namespaces/" + url.PathEscape(c.namespace) + "/networkpolicies"
default:
return "/api/v1/namespaces/" + url.PathEscape(c.namespace) + "/" + kind
}
}
func (c *kubeClient) create(ctx context.Context, kind string, obj, out any) error {
return c.do(ctx, http.MethodPost, c.nsPath(kind), obj, out)
}
// deleteObj deletes an object and reports whether it existed. Pods get a 1s
// grace, not 0: a zero grace force-removes the API object before the kubelet has
// stopped the containers, while with a grace the pod stays (terminating) until
// they are dead, so waiting for 404 proves its processes are gone. A non-empty
// uid makes the API server refuse (409) to delete a different object reusing the name.
func (c *kubeClient) deleteObj(ctx context.Context, kind, name, uid string) (bool, error) {
body := map[string]any{"propagationPolicy": "Background"}
if kind == "pods" {
body["gracePeriodSeconds"] = 1
}
if uid != "" {
body["preconditions"] = map[string]any{"uid": uid}
}
err := c.do(ctx, http.MethodDelete, c.nsPath(kind)+"/"+url.PathEscape(name), body, nil)
if isKubeStatus(err, http.StatusNotFound) {
return false, nil
}
return err == nil, err
}
type kubeObjectMeta struct {
Name string `json:"name"`
UID string `json:"uid,omitempty"`
ResourceVersion string `json:"resourceVersion,omitempty"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
Deletion *string `json:"deletionTimestamp,omitempty"`
}
type kubePod struct {
Metadata kubeObjectMeta `json:"metadata"`
Status struct {
Phase string `json:"phase"`
ContainerStatuses []struct {
Ready bool `json:"ready"`
State struct {
Waiting *struct {
Reason string `json:"reason"`
Message string `json:"message"`
} `json:"waiting"`
Terminated *struct {
Reason string `json:"reason"`
} `json:"terminated"`
} `json:"state"`
} `json:"containerStatuses"`
} `json:"status"`
}
func (c *kubeClient) getPod(ctx context.Context, name string) (*kubePod, error) {
var p kubePod
if err := c.do(ctx, http.MethodGet, c.nsPath("pods")+"/"+url.PathEscape(name), nil, &p); err != nil {
return nil, err
}
return &p, nil
}
// kubeExecStatus is the metav1.Status sent on the exec error channel.
type kubeExecStatus struct {
Status string `json:"status"`
Reason string `json:"reason"`
Details struct {
Causes []struct {
Reason string `json:"reason"`
Message string `json:"message"`
} `json:"causes"`
} `json:"details"`
}
// cappedBuffer keeps the first max bytes written and records truncation.
type cappedBuffer struct {
buf bytes.Buffer
max int
truncated bool
}
func (c *cappedBuffer) Write(p []byte) {
rem := c.max - c.buf.Len()
if rem <= 0 {
if len(p) > 0 {
c.truncated = true
}
return
}
if len(p) > rem {
p = p[:rem]
c.truncated = true
}
c.buf.Write(p)
}
// kubeExecReadLimit caps one exec WebSocket message. The API server forwards
// output in frames of at most a few tens of KiB; a larger frame means a broken or
// hostile peer and fails the exec before its payload is read into memory.
const kubeExecReadLimit = 4 << 20
// podExec runs argv in the pod's worker container over the Kubernetes exec
// WebSocket (channel.k8s.io v5/v4) and returns stdout, stderr and the exit code.
func (c *kubeClient) podExec(ctx context.Context, pod string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
return c.containerExec(ctx, pod, kubeWorkerName, argv, maxBytes)
}
// containerExec runs argv over pods/exec. The API only takes the command as
// command= query parameters, so the URL carries argv (and the env(1) arguments):
// it is never put in an error or a log line, and API error bodies are dropped.
func (c *kubeClient) containerExec(ctx context.Context, pod, container string, argv []string, maxBytes int) (stdout, stderr string, truncated bool, exitCode int, err error) {
q := url.Values{}
q.Set("container", container)
q.Set("stdout", "true")
q.Set("stderr", "true")
for _, a := range argv {
q.Add("command", a)
}
u := "wss" + strings.TrimPrefix(c.apiServer, "https")
if c.plainHTTP && strings.HasPrefix(c.apiServer, "http://") {
u = "ws" + strings.TrimPrefix(c.apiServer, "http")
}
u += c.nsPath("pods") + "/" + url.PathEscape(pod) + "/exec?" + q.Encode()
tok, err := c.token()
if err != nil {
return "", "", false, -1, err
}
dialer := websocket.Dialer{
Proxy: nil,
TLSClientConfig: c.tls,
HandshakeTimeout: 30 * time.Second,
Subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"},
}
hdr := http.Header{}
hdr.Set("Authorization", "Bearer "+tok)
conn, resp, err := dialer.DialContext(ctx, u, hdr)
if err != nil {
if resp != nil {
ae, _ := newKubeAPIError(resp.StatusCode, resp.Body)
resp.Body.Close()
if ae.Code == http.StatusNotFound {
return "", "", false, -1, fmt.Errorf("%w: pod %s", ErrNotFound, pod)
}
return "", "", false, -1, ae
}
if ctx.Err() != nil {
return "", "", false, -1, ctx.Err()
}
return "", "", false, -1, fmt.Errorf("%w: exec dial to pod %s failed", ErrDockerUnavailable, pod)
}
defer conn.Close()
proto := conn.Subprotocol()
if proto != "v5.channel.k8s.io" && proto != "v4.channel.k8s.io" {
return "", "", false, -1, fmt.Errorf("exec: API server negotiated unsupported subprotocol %q", proto)
}
conn.SetReadLimit(kubeExecReadLimit)
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
defer stop()
out := &cappedBuffer{max: maxBytes}
errb := &cappedBuffer{max: maxBytes}
closed := map[byte]bool{}
var status *kubeExecStatus
for {
_, msg, rerr := conn.ReadMessage()
if rerr != nil {
if ctx.Err() != nil {
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, -1, ctx.Err()
}
if errors.Is(rerr, websocket.ErrReadLimit) {
return "", "", false, -1, fmt.Errorf("exec: message larger than %d bytes", kubeExecReadLimit)
}
break
}
if len(msg) == 0 || closed[msg[0]] {
continue
}
switch msg[0] {
case 1:
out.Write(msg[1:])
case 2:
errb.Write(msg[1:])
case 3:
var st kubeExecStatus
if json.Unmarshal(msg[1:], &st) == nil {
status = &st
}
case 255: // v5 CLOSE: [255, stream]; that stream sends nothing more.
if proto == "v5.channel.k8s.io" && len(msg) == 2 {
closed[msg[1]] = true
}
}
}
res := func(code int, err error) (string, string, bool, int, error) {
return out.buf.String(), errb.buf.String(), out.truncated || errb.truncated, code, err
}
switch {
case status == nil:
return res(-1, errors.New("exec stream ended without a status"))
case status.Status == "Success":
return res(0, nil)
case status.Reason == "NonZeroExitCode":
for _, c := range status.Details.Causes {
if n, perr := strconv.Atoi(c.Message); c.Reason == "ExitCode" && perr == nil {
return res(n, nil)
}
}
return res(-1, errors.New("exec failed without an exit code"))
}
// status.Message can quote the command: report only the reason.
reason := status.Reason
if !kubeReasonRE.MatchString(reason) {
reason = "unknown"
}
return res(-1, fmt.Errorf("exec failed: %s", reason))
}
+115
View File
@@ -0,0 +1,115 @@
package sandbox
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
)
func newTestKubeClient(t *testing.T, f *fakeKubeAPI, srv *httptest.Server) *kubeClient {
t.Helper()
tok := filepath.Join(t.TempDir(), "token")
if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil {
t.Fatal(err)
}
c, err := newKubeClient(srv.URL, tok, "", f.ns, true)
if err != nil {
t.Fatal(err)
}
return c
}
func TestKubeClientRefusesPlainHTTPAndMissingCA(t *testing.T) {
if _, err := newKubeClient("http://127.0.0.1:1", "tok", "", "ns", false); err == nil || !strings.Contains(err.Error(), "https://") {
t.Fatalf("http:// API server accepted outside tests: %v", err)
}
if _, err := newKubeClient("https://127.0.0.1:6443", "tok", filepath.Join(t.TempDir(), "missing.crt"), "ns", false); err == nil {
t.Fatal("https API server without a readable CA accepted")
}
}
func TestKubeClientRefusesRedirects(t *testing.T) {
var hits atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
defer target.Close()
redir := httptest.NewServer(http.RedirectHandler(target.URL+"/api/v1/namespaces/artex/pods", http.StatusFound))
defer redir.Close()
f, _ := newFakeKubeAPI(t)
c := newTestKubeClient(t, f, redir)
if err := c.do(context.Background(), http.MethodGet, c.nsPath("pods"), nil, nil); err == nil || hits.Load() != 0 {
t.Fatalf("redirect followed: err=%v hits=%d", err, hits.Load())
}
}
func TestKubeClientDeleteAndErrors(t *testing.T) {
f, srv := newFakeKubeAPI(t)
c := newTestKubeClient(t, f, srv)
ctx := context.Background()
if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil {
t.Fatal(err)
}
// A UID precondition protects a different pod reusing the name.
if _, err := c.deleteObj(ctx, "pods", "p1", "uid-other"); !isKubeStatus(err, http.StatusConflict) || f.obj("pods", "p1") == nil {
t.Fatalf("delete with a stale UID = %v", err)
}
// The API body never reaches the caller: only the status and the reason.
f.failDelete["p1"] = true
if _, err := c.deleteObj(ctx, "pods", "p1", ""); err == nil || strings.Contains(err.Error(), "etcd") || !strings.Contains(err.Error(), "InternalError") {
t.Fatalf("failed delete = %v", err)
}
f.failDelete["p1"] = false
uid := dig(f.obj("pods", "p1"), "metadata", "uid").(string)
if found, err := c.deleteObj(ctx, "pods", "p1", uid); !found || err != nil || f.obj("pods", "p1") != nil {
t.Fatalf("delete = %v %v", found, err)
}
if found, err := c.deleteObj(ctx, "pods", "p1", ""); found || err != nil {
t.Fatalf("delete of a missing pod = %v %v", found, err)
}
}
func TestKubeClientExecStream(t *testing.T) {
f, srv := newFakeKubeAPI(t)
c := newTestKubeClient(t, f, srv)
ctx := context.Background()
if err := c.create(ctx, "pods", map[string]any{"metadata": map[string]any{"name": "p1"}}, nil); err != nil {
t.Fatal(err)
}
set := func(frames [][]byte, fn func(string, []string) (string, string, int)) {
f.mu.Lock()
f.preFrames, f.execFn = frames, fn
f.mu.Unlock()
}
// v5 CLOSE on stdout: later stdout frames are ignored.
set([][]byte{{1, 'a'}, {255, 1}, {1, 'b'}}, func(string, []string) (string, string, int) { return "", "", 0 })
if out, _, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "a" || code != 0 {
t.Fatalf("v5 close: %q %d %v", out, code, err)
}
// A frame over the read limit fails the exec instead of being buffered.
set([][]byte{append([]byte{1}, make([]byte, kubeExecReadLimit+1)...)}, nil)
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "larger than") {
t.Fatalf("oversized frame = %v", err)
}
// The status message (which can quote the command) is not passed on.
set(nil, func(string, []string) (string, string, int) { return "", "", -1 })
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"secret-arg"}, 1024); err == nil ||
strings.Contains(err.Error(), "container not found") || strings.Contains(err.Error(), "secret-arg") {
t.Fatalf("exec failure = %v", err)
}
// Exit codes come from the status channel.
set(nil, func(string, []string) (string, string, int) { return "o", "e", 3 })
if out, serr, _, code, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err != nil || out != "o" || serr != "e" || code != 3 {
t.Fatalf("exit 3: %q %q %d %v", out, serr, code, err)
}
// Only the channel.k8s.io v5/v4 subprotocols are accepted.
f.mu.Lock()
f.subprotocols = []string{"base64.channel.k8s.io"}
f.mu.Unlock()
if _, _, _, _, err := c.podExec(ctx, "p1", []string{"x"}, 1024); err == nil || !strings.Contains(err.Error(), "subprotocol") {
t.Fatalf("unsupported subprotocol = %v", err)
}
}
+376
View File
@@ -0,0 +1,376 @@
package sandbox
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/gorilla/websocket"
)
// fakeKubeAPI is an in-memory stand-in for the parts of the Kubernetes API the
// sandbox client and backend use: pods, services, networkpolicies (CRUD +
// label-selector list) and the pods/exec WebSocket.
type fakeKubeAPI struct {
t *testing.T
ns string
token string
mu sync.Mutex
objs map[string]map[string]map[string]any // kind -> name -> object
ops []string // "create pods/artex-w-..." in order
execs [][]string // argv of every exec
// container of every exec, parallel to execs
execContainers []string
nextIP int
podMode map[string]string // pod name -> "ready" (default) | "pull-error" | "pending"
// execFn answers an exec; default echoes argv to stdout with exit 0. denyFn
// answers the isolation deny probes; default reports them blocked.
execFn, denyFn func(pod string, argv []string) (stdout, stderr string, exit int)
// failPing makes pod list return 403.
failPing atomic.Bool
rv int // resourceVersion / uid counter
podLinger int // GETs a deleted pod stays visible (terminating)
terminating map[string]int // pod name -> remaining GETs
failDelete map[string]bool
subprotocols []string // exec subprotocols the server offers
preFrames [][]byte // raw exec frames sent before stdout
}
func newFakeKubeAPI(t *testing.T) (*fakeKubeAPI, *httptest.Server) {
f := &fakeKubeAPI{
t: t,
ns: "artex",
token: "test-sa-token",
objs: map[string]map[string]map[string]any{"pods": {}, "services": {}, "networkpolicies": {}},
podMode: map[string]string{},
nextIP: 10,
terminating: map[string]int{},
failDelete: map[string]bool{},
subprotocols: []string{"v5.channel.k8s.io", "v4.channel.k8s.io"},
}
srv := httptest.NewServer(http.HandlerFunc(f.serve))
t.Cleanup(srv.Close)
return f, srv
}
var fakeKubePathRE = regexp.MustCompile(`^/(?:api/v1|apis/networking\.k8s\.io/v1)/namespaces/([^/]+)/(pods|services|networkpolicies)(?:/([^/]+))?(?:/(exec))?$`)
func (f *fakeKubeAPI) serve(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+f.token {
http.Error(w, `{"reason":"Unauthorized"}`, http.StatusUnauthorized)
return
}
m := fakeKubePathRE.FindStringSubmatch(r.URL.Path)
if m == nil {
http.Error(w, "no route "+r.URL.Path, http.StatusNotFound)
return
}
ns, kind, name, sub := m[1], m[2], m[3], m[4]
if ns != f.ns {
http.Error(w, "forbidden namespace "+ns, http.StatusForbidden)
return
}
if sub == "exec" {
f.serveExec(w, r, name)
return
}
f.mu.Lock()
defer f.mu.Unlock()
store := f.objs[kind]
switch {
case r.Method == http.MethodGet && name == "":
if kind == "pods" && f.failPing.Load() {
http.Error(w, `{"reason":"Forbidden"}`, http.StatusForbidden)
return
}
sel := r.URL.Query().Get("labelSelector")
items := []any{}
for _, o := range store {
if matchSelector(o, sel) {
items = append(items, o)
}
}
writeJSON(w, map[string]any{"items": items})
case r.Method == http.MethodGet:
o, ok := store[name]
if n, term := f.terminating[name]; ok && kind == "pods" && term {
if f.terminating[name] = n - 1; n <= 0 {
delete(store, name)
delete(f.terminating, name)
f.ops = append(f.ops, "gone pods/"+name)
ok = false
}
}
if !ok {
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
return
}
writeJSON(w, o)
case r.Method == http.MethodPost:
var o map[string]any
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta := o["metadata"].(map[string]any)
n := meta["name"].(string)
if !dnsLabelRE.MatchString(n) {
http.Error(w, "invalid name "+n, http.StatusUnprocessableEntity)
return
}
if _, exists := store[n]; exists {
http.Error(w, `{"reason":"AlreadyExists"}`, http.StatusConflict)
return
}
f.finalize(kind, n, o)
f.rv++
meta["uid"], meta["resourceVersion"] = fmt.Sprintf("uid-%d", f.rv), strconv.Itoa(f.rv)
store[n] = o
f.ops = append(f.ops, "create "+kind+"/"+n)
writeJSON(w, o)
case r.Method == http.MethodPut:
var o map[string]any
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cur, exists := store[name]
if !exists {
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
return
}
// Like the API server: an update must carry the current resourceVersion.
meta := o["metadata"].(map[string]any)
switch meta["resourceVersion"] {
case nil, "":
http.Error(w, `{"reason":"Invalid","message":"metadata.resourceVersion: must be specified for an update"}`, http.StatusUnprocessableEntity)
return
case dig(cur, "metadata", "resourceVersion"):
default:
http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict)
return
}
f.rv++
meta["uid"], meta["resourceVersion"] = dig(cur, "metadata", "uid"), strconv.Itoa(f.rv)
store[name] = o
f.ops = append(f.ops, "update "+kind+"/"+name)
writeJSON(w, o)
case r.Method == http.MethodDelete:
o, ok := store[name]
if !ok {
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
return
}
var opts map[string]any
_ = json.NewDecoder(r.Body).Decode(&opts)
if uid := dig(opts, "preconditions", "uid"); uid != nil && uid != dig(o, "metadata", "uid") {
http.Error(w, `{"reason":"Conflict"}`, http.StatusConflict)
return
}
if kind == "pods" && dig(opts, "gracePeriodSeconds") == float64(0) {
f.t.Errorf("pod %s force-deleted (grace 0): its containers may outlive the API object", name)
}
if f.failDelete[name] {
http.Error(w, `{"reason":"InternalError","message":"etcd says no to `+name+`"}`, http.StatusInternalServerError)
return
}
f.ops = append(f.ops, "delete "+kind+"/"+name)
if _, term := f.terminating[name]; kind == "pods" && f.podLinger > 0 {
if !term {
f.terminating[name] = f.podLinger
o["metadata"].(map[string]any)["deletionTimestamp"] = "now"
}
writeJSON(w, map[string]any{"status": "Success"})
return
}
delete(store, name)
writeJSON(w, map[string]any{"status": "Success"})
default:
http.Error(w, "method", http.StatusMethodNotAllowed)
}
}
// finalize fills in server-side fields (pod status, service ClusterIP).
func (f *fakeKubeAPI) finalize(kind, name string, o map[string]any) {
switch kind {
case "services":
f.nextIP++
o["spec"].(map[string]any)["clusterIP"] = fmt.Sprintf("10.43.0.%d", f.nextIP)
case "pods":
switch f.podMode[name[:max(0, len(name)-7)]] { // keyed by name without the generation
case "pull-error":
o["status"] = map[string]any{"phase": "Pending", "containerStatuses": []any{map[string]any{
"ready": false, "state": map[string]any{"waiting": map[string]any{"reason": "ImagePullBackOff", "message": "pull access denied"}},
}}}
case "pending":
o["status"] = map[string]any{"phase": "Pending"}
default:
o["status"] = map[string]any{"phase": "Running", "containerStatuses": []any{map[string]any{"ready": true, "state": map[string]any{}}}}
}
}
}
func (f *fakeKubeAPI) setPodPhase(name, phase string, ready bool) {
f.mu.Lock()
defer f.mu.Unlock()
if p := f.objs["pods"][name]; p != nil {
p["status"] = map[string]any{"phase": phase, "containerStatuses": []any{map[string]any{"ready": ready, "state": map[string]any{}}}}
}
}
func (f *fakeKubeAPI) serveExec(w http.ResponseWriter, r *http.Request, pod string) {
f.mu.Lock()
_, ok := f.objs["pods"][pod]
f.mu.Unlock()
if !ok {
http.Error(w, `{"reason":"NotFound"}`, http.StatusNotFound)
return
}
q := r.URL.Query()
if c := q.Get("container"); c != kubeWorkerName && c != kubeProxyName {
http.Error(w, "unexpected container "+c, http.StatusBadRequest)
return
}
if q.Get("stdout") != "true" || q.Get("stderr") != "true" || q.Has("stdin") || q.Has("tty") {
http.Error(w, "unexpected exec query "+r.URL.RawQuery, http.StatusBadRequest)
return
}
argv := q["command"]
f.mu.Lock()
f.execs = append(f.execs, argv)
f.execContainers = append(f.execContainers, q.Get("container"))
fn, pre := f.execFn, f.preFrames
if strings.Contains(strings.Join(argv, " "), kubeProbeBlocked) {
fn = f.denyFn
if fn == nil {
fn = func(string, []string) (string, string, int) { return kubeProbeBlocked + "\n", "", 0 }
}
}
up := websocket.Upgrader{Subprotocols: f.subprotocols}
f.mu.Unlock()
conn, err := up.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
for _, fr := range pre {
if conn.WriteMessage(websocket.BinaryMessage, fr) != nil {
return
}
}
stdout, stderr, exit := strings.Join(argv, " "), "", 0
if fn != nil {
stdout, stderr, exit = fn(pod, argv)
}
send := func(ch byte, data string) {
// Split large payloads into frames like the API server does.
for len(data) > 0 {
n := min(len(data), 32*1024)
_ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{ch}, data[:n]...))
data = data[n:]
}
}
send(1, stdout)
send(2, stderr)
var st map[string]any
switch {
case exit == 0:
st = map[string]any{"status": "Success"}
case exit < 0:
st = map[string]any{"status": "Failure", "reason": "InternalError", "message": "container not found"}
default:
st = map[string]any{"status": "Failure", "reason": "NonZeroExitCode", "message": "command terminated with non-zero exit code",
"details": map[string]any{"causes": []any{map[string]any{"reason": "ExitCode", "message": strconv.Itoa(exit)}}}}
}
raw, _ := json.Marshal(st)
_ = conn.WriteMessage(websocket.BinaryMessage, append([]byte{3}, raw...))
_ = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
}
var dnsLabelRE = regexp.MustCompile(`^[a-z]([-a-z0-9]{0,61}[a-z0-9])?$`)
func matchSelector(o map[string]any, sel string) bool {
if sel == "" {
return true
}
labels, _ := o["metadata"].(map[string]any)["labels"].(map[string]any)
for _, term := range strings.Split(sel, ",") {
k, v, _ := strings.Cut(term, "=")
if labels[k] != v {
return false
}
}
return true
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
func (f *fakeKubeAPI) obj(kind, name string) map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return f.objs[kind][name]
}
func (f *fakeKubeAPI) count(kind string) int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.objs[kind])
}
func (f *fakeKubeAPI) opsSnapshot() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.ops...)
}
func (f *fakeKubeAPI) lastExec() []string {
f.mu.Lock()
defer f.mu.Unlock()
if len(f.execs) == 0 {
return nil
}
return f.execs[len(f.execs)-1]
}
// dig walks nested map/slice JSON values: dig(o, "spec", "containers", 0, "name").
func dig(v any, path ...any) any {
for _, p := range path {
switch k := p.(type) {
case string:
m, ok := v.(map[string]any)
if !ok {
return nil
}
v = m[k]
case int:
s, ok := v.([]any)
if !ok || k >= len(s) {
return nil
}
v = s[k]
}
}
return v
}
func envOf(container any) map[string]string {
out := map[string]string{}
for _, e := range dig(container, "env").([]any) {
out[e.(map[string]any)["name"].(string)] = e.(map[string]any)["value"].(string)
}
return out
}
+188
View File
@@ -0,0 +1,188 @@
package sandbox
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
func newTestKubeBackend(t *testing.T, f *fakeKubeAPI, srv *httptest.Server, mods ...func(*KubeConfig)) *KubernetesBackend {
t.Helper()
dir := t.TempDir()
tok := filepath.Join(dir, "token")
if err := os.WriteFile(tok, []byte(f.token+"\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg := KubeConfig{
APIServer: srv.URL,
TokenPath: tok,
Namespace: f.ns,
DataClaim: "artex-data",
WorkerImage: "artex-worker:test",
ProxyImage: "artex-egress-proxy:test",
WorkspaceRoot: filepath.Join(dir, "tasks"),
AuditRoot: filepath.Join(dir, "audit"),
PodReadyTimeout: 3 * time.Second,
allowPlainHTTP: true,
}
for _, m := range mods {
m(&cfg)
}
b, err := NewKubernetesBackend(cfg)
if err != nil {
t.Fatalf("NewKubernetesBackend: %v", err)
}
return b
}
func execReq(argv ...string) ExecRequest {
req := ExecRequest{Argv: argv}
if err := ValidateExecRequest(&req); err != nil {
panic(err)
}
return req
}
func TestKubeDeleteRemovesPoliciesOnlyAfterPodsAreGone(t *testing.T) {
f, srv := newFakeKubeAPI(t)
b := newTestKubeBackend(t, f, srv)
ctx := context.Background()
f.podLinger = 3 // a deleted pod stays visible (terminating) for 3 GETs
for _, id := range []string{"t1", "t2"} {
if _, err := b.Exec(ctx, id, execReq("true")); err != nil {
t.Fatal(err)
}
}
mark := len(f.opsSnapshot())
if err := b.Delete(ctx, "t1"); err != nil {
t.Fatal(err)
}
h := kubeTaskHash("t1")
ops := f.opsSnapshot()[mark:]
firstPol, gone := -1, 0
for i, op := range ops {
if strings.HasPrefix(op, "gone pods/") {
gone++
}
if strings.HasPrefix(op, "delete networkpolicies/") && firstPol < 0 {
firstPol = i
if gone != 2 {
t.Fatalf("policy deleted while a pod still ran: %v", ops)
}
}
}
if firstPol < 0 || f.obj("networkpolicies", "artex-p-"+h) != nil || f.count("pods") != 2 {
t.Fatalf("delete incomplete: %v", ops)
}
// A pod that cannot be deleted keeps its policies, and the task stays tracked.
h2 := kubeTaskHash("t2")
f.failDelete[b.getTask("t2").workerPod] = true
err := b.Delete(ctx, "t2")
if err == nil || strings.Contains(err.Error(), "etcd") {
t.Fatalf("failed pod delete = %v (want error without the API body)", err)
}
if f.obj("networkpolicies", "artex-w-"+h2) == nil || f.obj("networkpolicies", "artex-p-"+h2) == nil || b.WorkerCount() != 1 {
t.Fatal("policies removed although the worker pod is still running")
}
f.failDelete = map[string]bool{}
if err := b.Delete(ctx, "t2"); err != nil {
t.Fatal(err)
}
if f.count("pods")+f.count("services")+f.count("networkpolicies") != 0 {
t.Fatalf("objects left: %v", f.opsSnapshot())
}
if err := b.Delete(ctx, "t2"); !errors.Is(err, ErrNotFound) {
t.Fatalf("delete of nothing = %v", err)
}
b.mu.Lock()
locks := len(b.locks)
b.mu.Unlock()
if locks != 0 {
t.Fatalf("%d task locks left after Delete", locks)
}
}
func TestKubeApplyPolicyUpdatesWithResourceVersionOnlyOwnPolicy(t *testing.T) {
f, srv := newFakeKubeAPI(t)
b := newTestKubeBackend(t, f, srv)
ctx := context.Background()
h := kubeTaskHash("t1")
if _, err := b.Exec(ctx, "t1", execReq("true")); err != nil {
t.Fatal(err)
}
// The fake enforces the API server rule: an update without resourceVersion is 422.
pol := b.workerPolicyObj("artex-w-"+h, &kubeTask{taskID: "t1", hash: h})
if err := b.do(ctx, http.MethodPut, b.nsPath("networkpolicies")+"/artex-w-"+h, pol, nil); !isKubeStatus(err, http.StatusUnprocessableEntity) {
t.Fatalf("PUT without resourceVersion = %v", err)
}
rv := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion")
if err := b.applyPolicy(ctx, pol); err != nil {
t.Fatalf("409 -> PUT: %v", err)
}
if got := dig(f.obj("networkpolicies", "artex-w-"+h), "metadata", "resourceVersion"); got == rv {
t.Fatal("policy not replaced")
}
// A same-named policy without the runner's labels is never overwritten, and the
// failed setup leaves nothing of its own behind.
h2 := kubeTaskHash("t2")
f.mu.Lock()
f.objs["networkpolicies"]["artex-p-"+h2] = map[string]any{
"metadata": map[string]any{"name": "artex-p-" + h2, "labels": map[string]any{"app": "x"}, "resourceVersion": "1"},
"spec": map[string]any{"podSelector": map[string]any{"foreign": true}}}
f.mu.Unlock()
_, err := b.Exec(ctx, "t2", execReq("true"))
if err == nil || !strings.Contains(err.Error(), "not managed by the runner") {
t.Fatalf("foreign policy = %v", err)
}
if dig(f.obj("networkpolicies", "artex-p-"+h2), "spec", "podSelector", "foreign") != true || f.obj("networkpolicies", "artex-w-"+h2) != nil {
t.Fatal("foreign policy replaced or own policy left behind")
}
}
func TestKubeDeniedCIDRsExtendDefaults(t *testing.T) {
f, srv := newFakeKubeAPI(t)
cfg := newTestKubeBackend(t, f, srv).cfg
cfg.ProxyDeniedCIDRs = []string{"198.51.100.7/24", "10.0.0.0/8"}
nb, err := NewKubernetesBackend(cfg)
if err != nil {
t.Fatal(err)
}
want := strings.Join(append(slices.Clone(DefaultProxyDeniedCIDRs), "198.51.100.0/24"), ",")
if got := strings.Join(nb.cfg.ProxyDeniedCIDRs, ","); got != want {
t.Fatalf("denied CIDRs = %s\nwant %s", got, want)
}
cfg.ProxyDeniedCIDRs = []string{"fc00::/7"}
if _, err := NewKubernetesBackend(cfg); err == nil {
t.Fatal("IPv6 denied CIDR accepted")
}
// An empty label map must not select every pod in the DNS namespace.
cfg.ProxyDeniedCIDRs, cfg.DNSPodLabels = nil, map[string]string{}
if nb, err = NewKubernetesBackend(cfg); err != nil || nb.cfg.DNSPodLabels["k8s-app"] != "kube-dns" {
t.Fatalf("empty DNS labels: %v", err)
}
}
func TestKubeCancelledExecKeepsTask(t *testing.T) {
f, srv := newFakeKubeAPI(t)
b := newTestKubeBackend(t, f, srv)
if _, err := b.Exec(context.Background(), "t1", execReq("true")); err != nil {
t.Fatal(err)
}
// A failed pod lookup (here a cancelled request) says nothing about the pods:
// only this exec fails, and it is not reported as the runner being unavailable.
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := b.Exec(ctx, "t1", execReq("true"))
if !errors.Is(err, context.Canceled) || errors.Is(err, ErrDockerUnavailable) || f.count("pods")+f.count("networkpolicies") != 4 || b.WorkerCount() != 1 {
t.Fatalf("cancelled exec = %v; %d pods, %d tasks", err, f.count("pods"), b.WorkerCount())
}
}
+18 -2
View File
@@ -133,6 +133,9 @@ type EgressPolicy struct {
Resolver func(ctx context.Context, host string) ([]netip.Addr, error)
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
Logger *EgressLogger
// Never lists prefixes denied even when a scope CIDR covers them (the
// Kubernetes backend passes cluster and metadata ranges here).
Never []netip.Prefix
}
// NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries.
@@ -198,8 +201,21 @@ func (p *EgressPolicy) domainAllowed(host string) bool {
return false
}
func (p *EgressPolicy) inNever(addr netip.Addr) bool {
addr = addr.Unmap()
for _, pfx := range p.Never {
if pfx.Contains(addr) {
return true
}
}
return false
}
func (p *EgressPolicy) ipInScopeCIDR(addr netip.Addr) bool {
addr = addr.Unmap()
if p.inNever(addr) {
return false
}
for _, pfx := range p.CIDRs {
if pfx.Contains(addr) {
return true
@@ -283,7 +299,7 @@ func (p *EgressPolicy) ResolveAndCheck(ctx context.Context, host string) (netip.
if p.ipInScopeCIDR(addr) {
return addr, nil
}
if isDefaultDeniedAddr(addr) {
if isDefaultDeniedAddr(addr) || p.inNever(addr) {
continue
}
return addr, nil
@@ -381,7 +397,7 @@ func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error {
}
for _, addr := range addrs {
addr = addr.Unmap()
if !p.ipInScopeCIDR(addr) && isDefaultDeniedAddr(addr) {
if !p.ipInScopeCIDR(addr) && (isDefaultDeniedAddr(addr) || p.inNever(addr)) {
return fmt.Errorf("egress denied: %q resolved to disallowed/private/IPv6 address %s", host, addr)
}
}
+6
View File
@@ -107,6 +107,12 @@ func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) {
writeRunnerErr(w, http.StatusBadRequest, err.Error())
return
}
if d := req.droppedScope; len(d) > 0 {
if len(d) > 20 {
d = append(d[:20:20], fmt.Sprintf("... %d more", len(req.droppedScope)-20))
}
log.Printf("[runner] task %s: dropped %d invalid scope entries: %q", taskID, len(req.droppedScope), d)
}
res, err := rs.backend.Exec(r.Context(), taskID, req)
if err != nil {
rs.writeBackendErr(w, err)
+8
View File
@@ -21,6 +21,10 @@ const (
EnvAuditRoot = "ARTEX_AUDIT_ROOT"
EnvTaskNetPrefix = "ARTEX_TASK_NET_PREFIX"
EnvEgressNet = "ARTEX_EGRESS_NET"
EnvRunnerBackend = "ARTEX_RUNNER_BACKEND"
BackendDocker = "docker"
BackendKubernetes = "kubernetes"
DefaultRunnerURL = "http://artex-runner:8789"
DefaultRunnerAddr = ":8789"
@@ -73,6 +77,10 @@ type ExecRequest struct {
Env map[string]string `json:"env,omitempty"`
ScopeDomains []string `json:"scope_domains,omitempty"`
ScopeCIDRs []string `json:"scope_cidrs,omitempty"`
// droppedScope holds the scope entries ValidateExecRequest dropped as
// invalid, for the runner's log.
droppedScope []string
}
// ExecResponse is the response body for POST /v1/tasks/{id}/exec.
+91 -5
View File
@@ -2,6 +2,7 @@ package sandbox
import (
"fmt"
"net/netip"
"path"
"regexp"
"strings"
@@ -10,6 +11,16 @@ import (
var (
taskIDRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`)
envNameRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`)
// A scope domain: labels of letters, digits, '-' or '_', optionally "*." first.
scopeDomainRE = regexp.MustCompile(`^(\*\.)?[\p{L}\p{N}_-]+(\.[\p{L}\p{N}_-]+)*\.?$`)
)
// MaxScopeEntries caps scope_domains and scope_cidrs (each) in one request, and
// MaxScopeBytes their comma-joined length: the egress proxy gets each list as one
// environment string, which Linux limits to 128 KiB.
const (
MaxScopeEntries = 8192
MaxScopeBytes = 120 << 10
)
// ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths.
@@ -41,14 +52,31 @@ func IsForbiddenEnvName(name string) bool {
return false
}
// ValidateEnv rejects forbidden variable names, invalid names, NUL bytes, or values > 8192 bytes.
// isReservedEnvName reports whether name is set by the worker itself (proxy
// routing, PATH) or makes a shell, the loader or Python run code the command did
// not ask for (LD_*, BASH_ENV, ENV, GCONV_PATH, PYTHONPATH). A request may not
// set these in either backend.
func isReservedEnvName(name string) bool {
u := strings.ToUpper(name)
switch u {
case "PATH", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "PROMPT_COMMAND",
"GCONV_PATH", "GLIBC_TUNABLES", "PYTHONPATH", "PYTHONSTARTUP", "PYTHONHOME",
"NODE_OPTIONS", "PERL5OPT", "PERL5LIB", "RUBYOPT", "JAVA_TOOL_OPTIONS",
"GIT_SSH_COMMAND", "GIT_CONFIG_PARAMETERS":
return true
}
return strings.HasPrefix(u, "LD_")
}
// ValidateEnv rejects forbidden or reserved variable names, invalid names, NUL bytes, or values > 8192 bytes.
// Per CONTRACT.md §3 this is always a 400 validation error, never a silent drop.
func ValidateEnv(env map[string]string) error {
for k, v := range env {
if !envNameRE.MatchString(k) {
return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k)
}
if IsForbiddenEnvName(k) {
if IsForbiddenEnvName(k) || isReservedEnvName(k) {
return fmt.Errorf("%w: forbidden env variable %q", ErrBadRequest, k)
}
if len(v) > MaxEnvValueBytes {
@@ -67,12 +95,12 @@ func FilterPanelEnv(kvs []string) map[string]string {
out := make(map[string]string)
for _, kv := range kvs {
k, v, ok := strings.Cut(kv, "=")
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || isReservedEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) {
continue
}
// Never override worker proxy or home variables from panel process env.
// Never override worker home variables from panel process env.
switch strings.ToUpper(k) {
case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY":
case "HOME", "XDG_CACHE_HOME":
continue
}
out[k] = v
@@ -108,5 +136,63 @@ func ValidateExecRequest(req *ExecRequest) error {
}
req.Workdir = clean
}
if len(req.ScopeDomains) > MaxScopeEntries || len(req.ScopeCIDRs) > MaxScopeEntries {
return fmt.Errorf("%w: more than %d scope entries", ErrBadRequest, MaxScopeEntries)
}
var d1, d2 []string
req.ScopeDomains, d1 = filterScope(req.ScopeDomains, canonScopeDomain)
req.ScopeCIDRs, d2 = filterScope(req.ScopeCIDRs, canonScopeCIDR)
req.droppedScope = append(d1, d2...)
if joinedLen(req.ScopeDomains) > MaxScopeBytes || joinedLen(req.ScopeCIDRs) > MaxScopeBytes {
return fmt.Errorf("%w: scope lists longer than %d bytes", ErrBadRequest, MaxScopeBytes)
}
return ValidateEnv(req.Env)
}
// filterScope keeps the canonical form of each entry canon accepts and returns
// the dropped ones. Backends join scope entries with commas into the egress
// proxy's environment, so only the canonical form (which never holds a comma,
// space or IPv6 zone) is passed on, and an invalid entry is dropped whole,
// never split. The panel builds scope from free-text fields, so one odd entry
// must not fail every command: a narrower scope fails closed at the
// deny-by-default proxy.
func filterScope(entries []string, canon func(string) (string, bool)) (kept, dropped []string) {
kept = entries[:0:0]
for _, e := range entries {
if c, ok := canon(e); ok {
kept = append(kept, c)
} else {
dropped = append(dropped, e)
}
}
return kept, dropped
}
func joinedLen(entries []string) int {
n := 0
for _, e := range entries {
n += len(e) + 1
}
return n
}
func canonScopeDomain(d string) (string, bool) {
return d, len(d) <= 253 && scopeDomainRE.MatchString(d)
}
// canonScopeCIDR returns a prefix or address in canonical form. An address with
// a zone is refused (the zone may hold any text, commas included), and an
// IPv4-mapped IPv6 entry becomes the IPv4 range it maps.
func canonScopeCIDR(c string) (string, bool) {
if p, err := netip.ParsePrefix(c); err == nil {
if p.Addr().Is4In6() && p.Bits() >= 96 {
p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96)
}
return p.Masked().String(), true
}
a, err := netip.ParseAddr(c)
if err != nil || a.Zone() != "" {
return "", false
}
return a.Unmap().String(), true
}
+61
View File
@@ -0,0 +1,61 @@
package sandbox
import (
"errors"
"strings"
"testing"
)
func TestValidateEnvRefusesReservedNames(t *testing.T) {
for _, k := range []string{"PATH", "path", "HTTP_PROXY", "https_proxy", "All_Proxy", "no_proxy",
"LD_PRELOAD", "LD_LIBRARY_PATH", "ld_audit", "BASH_ENV", "env", "GCONV_PATH", "PythonPath",
"SHELLOPTS", "PS4", "NODE_OPTIONS", "PERL5OPT", "GIT_SSH_COMMAND", "GLIBC_TUNABLES"} {
if err := ValidateEnv(map[string]string{k: "x"}); !errors.Is(err, ErrBadRequest) {
t.Errorf("ValidateEnv(%s) = %v", k, err)
}
// The panel drops them instead of sending a request the runner refuses.
if got := FilterPanelEnv([]string{k + "=x", "KEEP=1"}); len(got) != 1 || got["KEEP"] != "1" {
t.Errorf("FilterPanelEnv kept %s: %v", k, got)
}
}
if err := ValidateEnv(map[string]string{"PYTHONUNBUFFERED": "1", "LANGUAGE": "en", "ENVIRONMENT": "x"}); err != nil {
t.Fatalf("ordinary names refused: %v", err)
}
}
func TestValidateExecRequestFiltersScopeEntries(t *testing.T) {
req := ExecRequest{Argv: []string{"true"},
ScopeDomains: []string{"example.com", "a.example,evil.example", "*.example.org", "a.example evil", "",
"example.com:8443", "https://x", "api-*.example.com", "xn--bcher-kva.example", "bücher.example", "host_1.lab.", strings.Repeat("a", 254)},
ScopeCIDRs: []string{"203.0.113.0/24", "1.2.3.4/32,10.0.0.0/8", "10.0.0.0/33", " 10.0.0.1", "198.51.100.7", "2001:db8::/32",
"fe80::1%eth0,10.0.0.0/8", "::1%a,0.0.0.0/0", "fe80::1%eth0", "203.0.113.9/24", "::ffff:10.1.0.0/112", "::ffff:198.51.100.8"}}
if err := ValidateExecRequest(&req); err != nil {
t.Fatalf("invalid entries failed the request: %v", err)
}
// Invalid entries are dropped whole (never split at the comma); valid ones stay.
if got := strings.Join(req.ScopeDomains, " "); got != "example.com *.example.org xn--bcher-kva.example bücher.example host_1.lab." {
t.Errorf("domains = %q", got)
}
// An IPv6 zone may hold any text, commas included, so zoned addresses are
// dropped; entries are passed on in canonical form, mapped ones as IPv4.
if got := strings.Join(req.ScopeCIDRs, " "); got != "203.0.113.0/24 198.51.100.7 2001:db8::/32 203.0.113.0/24 10.1.0.0/16 198.51.100.8" {
t.Errorf("CIDRs = %q", got)
}
long := make([]string, MaxScopeBytes/200)
for i := range long {
long[i] = strings.Repeat("a", 240) + ".example"
}
if err := ValidateExecRequest(&ExecRequest{Argv: []string{"true"}, ScopeDomains: long}); !errors.Is(err, ErrBadRequest) {
t.Errorf("%d bytes of scope accepted: %v", joinedLen(long), err)
}
many := make([]string, MaxScopeEntries+1)
for i := range many {
many[i] = "a.example"
}
for _, req := range []ExecRequest{{ScopeDomains: many}, {ScopeCIDRs: many}} {
req.Argv = []string{"true"}
if err := ValidateExecRequest(&req); !errors.Is(err, ErrBadRequest) {
t.Errorf("%d scope entries accepted: %v", len(many), err)
}
}
}
+112 -49
View File
@@ -170,10 +170,11 @@ func askOperatorActivity(text string, att []chatAttachment, derived []string) db
return a
}
// resolveAskOperatorImage maps image_path onto a regular file inside runDir, the
// run directory of the agent that asks (its CWD). Relative paths are resolved from it.
// ".." segments, paths that EvalSymlinks outside runDir, and non-images are refused.
func resolveAskOperatorImage(runDir, src string) (string, error) {
// askOperatorImageRel maps image_path onto a path relative to the task root.
// Relative paths resolve from runName, the run directory of the agent that asks
// (i<intentID>, or main). An absolute path must be inside that run directory.
// ".." segments, paths outside the run directory and non-images are refused.
func askOperatorImageRel(taskDir, runName, src string) (string, error) {
src = strings.TrimSpace(src)
ext := strings.ToLower(filepath.Ext(src))
if !askOperatorImageExt[ext] {
@@ -182,34 +183,54 @@ func resolveAskOperatorImage(runDir, src string) (string, error) {
if slices.Contains(strings.Split(filepath.ToSlash(src), "/"), "..") {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
if !filepath.IsAbs(src) {
src = filepath.Join(runDir, src)
var rel string
if filepath.IsAbs(src) {
r, err := filepath.Rel(taskDir, filepath.Clean(src))
if err != nil {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
rel = r
} else {
rel = filepath.Join(runName, src)
}
realRoot, err := filepath.EvalSymlinks(runDir)
if err != nil {
return "", fmt.Errorf("image not readable")
}
real, err := filepath.EvalSymlinks(src)
if err != nil {
return "", fmt.Errorf("image not readable")
}
rel, err := filepath.Rel(realRoot, real)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
if !filepath.IsLocal(rel) || (rel != runName && !strings.HasPrefix(rel, runName+string(filepath.Separator))) {
return "", fmt.Errorf("image_path must stay inside the run directory")
}
return real, nil
return rel, nil
}
// openAskOperatorImage opens the image at path and requires the opened file to be
// the regular file lst describes, lst being the Lstat of path. Between the
// EvalSymlinks of resolveAskOperatorImage and this open, the agent can replace the
// file with a symlink: Lstat does not follow one and the open does, so the two then
// name different files and the image is refused.
func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
// askOperatorRejectSymlinks refuses a symlink in any component of rel below the
// task root. os.Root follows links that stay inside the root, so a link from the
// run directory to a sibling would otherwise be read.
func askOperatorRejectSymlinks(root *os.Root, rel string) error {
parts := strings.Split(rel, string(filepath.Separator))
prefix := parts[0]
for i, part := range parts {
if i > 0 {
prefix = filepath.Join(prefix, part)
}
info, err := root.Lstat(prefix)
if err != nil {
return fmt.Errorf("image not readable")
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("image_path must stay inside the run directory")
}
if i < len(parts)-1 && !info.IsDir() {
return fmt.Errorf("image not readable")
}
}
return nil
}
// openAskOperatorImage opens rel under the task root and requires the opened file
// to be the regular file lst describes. The root refuses a path outside the task
// and a symlink that leaves it; Lstat does not follow the last component.
func openAskOperatorImage(root *os.Root, rel string, lst os.FileInfo) (*os.File, error) {
if !lst.Mode().IsRegular() {
return nil, fmt.Errorf("image_path must be a regular file")
}
f, err := os.Open(path)
f, err := root.Open(rel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
@@ -220,18 +241,22 @@ func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
return f, nil
}
// askOperatorUploadsDir returns tasks/<id>/uploads, created when absent. A symlink
// or anything else that is not a directory is refused: the copy would be written
// through it.
func askOperatorUploadsDir(taskDir string) (string, error) {
dir := filepath.Join(taskDir, "uploads")
if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return "", err
// askOperatorUploadsRoot returns tasks/<id>/uploads as a root anchored at the
// task directory. A symlink or anything else that is not a directory is refused:
// the copy would be written through it.
func askOperatorUploadsRoot(taskRoot *os.Root) (*os.Root, error) {
if err := taskRoot.Mkdir("uploads", 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
return nil, err
}
if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() {
return "", fmt.Errorf("the task uploads directory is not a directory")
fi, err := taskRoot.Lstat("uploads")
if err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return dir, nil
uploads, err := taskRoot.OpenRoot("uploads")
if err != nil {
return nil, fmt.Errorf("the task uploads directory is not a directory")
}
return uploads, nil
}
// askOperatorStageTries bounds the names tried for one staged copy.
@@ -257,33 +282,57 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
if src == "" {
return nil, nil
}
taskDir := filepath.Join(dataDir, "tasks", strconv.FormatInt(taskID, 10))
resolved, err := resolveAskOperatorImage(agent.EnsureRunDir(dataDir, taskID, intentID), src)
if err != nil {
return nil, err
taskRel := filepath.Join("tasks", strconv.FormatInt(taskID, 10))
runName := "main"
if intentID > 0 {
runName = "i" + strconv.FormatInt(intentID, 10)
}
st, err := os.Lstat(resolved)
// Every lookup is anchored at the task directory: a run directory or an
// intermediate directory swapped for a symlink cannot leave the task.
dataRoot, err := os.OpenRoot(dataDir)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
in, err := openAskOperatorImage(resolved, st)
defer dataRoot.Close()
taskRoot, err := dataRoot.OpenRoot(taskRel)
if err != nil {
return nil, fmt.Errorf("image not readable")
}
defer taskRoot.Close()
runInfo, err := taskRoot.Lstat(runName)
if err != nil || runInfo.Mode()&os.ModeSymlink != 0 || !runInfo.IsDir() {
return nil, fmt.Errorf("image_path must stay inside the run directory")
}
rel, err := askOperatorImageRel(filepath.Join(dataDir, taskRel), runName, src)
if err != nil {
return nil, err
}
if err := askOperatorRejectSymlinks(taskRoot, rel); err != nil {
return nil, err
}
st, err := taskRoot.Lstat(rel)
if err != nil || !st.Mode().IsRegular() {
return nil, fmt.Errorf("image not readable")
}
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
in, err := openAskOperatorImage(taskRoot, rel, st)
if err != nil {
return nil, err
}
defer in.Close()
if st.Size() > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
}
dir, err := askOperatorUploadsDir(taskDir)
uploads, err := askOperatorUploadsRoot(taskRoot)
if err != nil {
return nil, err
}
ext := strings.ToLower(filepath.Ext(resolved))
defer uploads.Close()
ext := strings.ToLower(filepath.Ext(rel))
var name string
var out *os.File
for try := 1; ; try++ {
name = askOperatorStageName(ext)
out, err = os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
out, err = uploads.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
if err == nil {
break
}
@@ -291,9 +340,23 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
return nil, err
}
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
committed := false
defer func() {
if !committed {
_ = out.Close()
_ = uploads.Remove(name)
}
}()
n, err := io.Copy(out, io.LimitReader(in, askOperatorMaxImage+1))
if err != nil {
return nil, err
}
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: st.Size()}}, nil
if n > askOperatorMaxImage {
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(n))
}
if err := out.Close(); err != nil {
return nil, err
}
committed = true
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: n}}, nil
}
+76 -7
View File
@@ -282,16 +282,22 @@ func TestStageAskOperatorImageNeverOverwrites(t *testing.T) {
// elsewhere.
func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
root, err := os.OpenRoot(taskDir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = root.Close() })
src := filepath.Join(taskDir, "i3", "shot.png")
rel := filepath.Join("i3", "shot.png")
outside := filepath.Join(dir, "outside.png")
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
t.Fatal(err)
}
lst, err := os.Lstat(src)
lst, err := root.Lstat(rel)
if err != nil {
t.Fatal(err)
}
f, err := openAskOperatorImage(src, lst)
f, err := openAskOperatorImage(root, rel, lst)
if err != nil {
t.Fatalf("unchanged file: %v", err)
}
@@ -305,32 +311,95 @@ func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
if err := os.Rename(other, src); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a file that replaced the checked one")
}
// A symlink to a file outside the run directory takes the path.
// A symlink to a file outside the run directory takes the path. os.Root
// refuses the absolute target because it leaves the task root.
if err := os.Remove(src); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, src); err != nil {
t.Skipf("no symlink here: %v", err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened the target of a symlink that replaced the checked file")
}
// The swap came before the Lstat: the last component is a symlink.
if lst, err = os.Lstat(src); err != nil {
if lst, err = root.Lstat(rel); err != nil {
t.Fatal(err)
}
if f, err := openAskOperatorImage(src, lst); err == nil {
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
f.Close()
t.Fatal("opened a path whose last component is a symlink")
}
}
// A run directory replaced by a symlink must not turn the task root into the
// confinement root: the read stays anchored at tasks/<id>.
func TestStageAskOperatorImageRejectsRunDirSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
runDir := filepath.Join(taskDir, "i3")
moved := filepath.Join(taskDir, "i3.real")
if err := os.Rename(runDir, moved); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.Remove(runDir)
_ = os.Rename(moved, runDir)
})
if err := os.Symlink("/", runDir); err != nil {
t.Skipf("no symlink here: %v", err)
}
// taskDir/shot.png is outside the run directory but inside the task. With the
// run directory symlinked to /, the old confinement root resolved to / and
// accepted it; the task root must not move.
outsideRun := filepath.Join(taskDir, "shot.png")
if err := os.WriteFile(outsideRun, []byte("outside the run dir"), 0o644); err != nil {
t.Fatal(err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, outsideRun); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked run directory", att)
}
}
// A symlink inside the run directory must not lead to a sibling run directory.
func TestStageAskOperatorImageRejectsSiblingSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
link := filepath.Join(taskDir, "i3", "sibling")
if err := os.Symlink(filepath.Join("..", "main"), link); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, filepath.Join("sibling", "shot.png")); err == nil {
t.Fatalf("staged %v through a sibling symlink", att)
}
}
// uploads/ swapped for a symlink must not redirect the copy outside the task.
func TestStageAskOperatorImageRejectsUploadsSymlink(t *testing.T) {
dir, taskDir := askOperatorRunDirs(t)
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(taskDir, "uploads")); err != nil {
t.Skipf("no symlink here: %v", err)
}
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
t.Fatalf("staged %v through a symlinked uploads directory", att)
}
entries, err := os.ReadDir(outside)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("wrote %d file(s) outside the task", len(entries))
}
}
// The emitted activity must carry the {text, attachments} Detail shape the
// transcript parser expects, so the operator sees the question with the
// attachment card for the screenshot.
+5
View File
@@ -307,6 +307,11 @@ func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) {
rows, err := pg.ListTools()
if err != nil {
log.Printf("[tools] failed to read tools table, passing through with code defaults: %v", err)
// Auto's base list is nil, and Norma reads nil as "use its own
// unconfined default tools". Keep it an empty list.
if tools == nil {
return []actool.CoreTool{}
}
return tools
}
byKey := make(map[string]*db.Tool, len(rows))
+14 -1
View File
@@ -496,7 +496,11 @@ func (s *Server) runConversation(c *db.Conversation, msg, busyKey string, userMe
if len(userMessage) == 1 {
ctx = intercept.WithReviewContext(ctx, "", intercept.ReviewBackground{Source: intercept.BackgroundUserMessage, Text: userMessage[0]})
}
go s.runConversationTurn(ctx, cancel, c, msg, busyKey)
s.conversationWG.Add(1)
go func() {
defer s.conversationWG.Done()
s.runConversationTurn(ctx, cancel, c, msg, busyKey)
}()
}
// runConversationSync runs ONE agent turn on a conversation and BLOCKS until the
@@ -509,6 +513,8 @@ func (s *Server) runConversationSync(c *db.Conversation, msg, busyKey string, so
// them as a server-owned value (never from tool arguments) so finding tools
// can scope writes to the originating task; no source task = no task context.
ctx = agent.WithSourceTasks(ctx, sourceTaskIDs)
s.conversationWG.Add(1)
defer s.conversationWG.Done()
s.runConversationTurn(ctx, cancel, c, msg, busyKey)
}
@@ -565,6 +571,13 @@ func (s *Server) runConversationTurn(ctx context.Context, cancel context.CancelC
if !started {
return
}
sandboxCtx, cleanup, err := s.retestSandboxContext(ctx, r)
if err != nil {
finishReason = err.Error()
return
}
ctx = sandboxCtx
defer cleanup()
}
}
if ctx.Err() != nil {
+194 -3
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
@@ -413,8 +414,25 @@ func unmaskToolExec(storedKind string, stored json.RawMessage, kind string, in j
}
oldURL, _ := old["url"].(string)
newURL, _ := e["url"].(string)
if kept && (oldURL != newURL || storedKind != kind) {
return nil, fmt.Errorf("destination changed (url or kind) while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
oldProxy, _ := old["proxy"].(string)
newProxy, _ := e["proxy"].(string)
oldRecording, _ := old["use_recording_proxy"].(bool)
newRecording, _ := e["use_recording_proxy"].(bool)
if kept {
if oldURL != newURL || storedKind != kind || oldRecording != newRecording {
return nil, fmt.Errorf("destination or recording proxy changed while a stored secret was kept: re-enter the masked header/proxy/body or clear it; stored secrets are not sent to a new destination")
}
// Clearing the configured proxy sends the request to the tool's fixed
// destination, not to a third party. Switching to another proxy does not
// have that guarantee.
if newProxy != "" && newProxy != oldProxy {
return nil, fmt.Errorf("proxy changed while a stored secret was kept: re-enter the masked header/body or clear it; stored secrets are not sent to a new proxy")
}
}
if kind == "http" {
if err := validateHTTPToolExec(e); err != nil {
return nil, err
}
}
if !changed {
return in, nil
@@ -698,6 +716,13 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if strings.TrimSpace(rawURL) == "" {
return actool.Errorf("http url is empty"), nil
}
// A tool with stored headers or body may only send them to the origin it was
// configured for: the scheme, host and port of the url template cannot be
// parameters, and the rendered url must stay on that origin.
secretOrigin, originErr := httpToolSecretOrigin(spec, rawURL)
if originErr != nil {
return actool.Errorf(originErr.Error()), nil
}
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
// the task's worker container and its egress proxy. The task's egress policy,
// the one WebFetch enforces, applies here to the URL, to every redirect hop
@@ -716,6 +741,20 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if res := intercept.GateRenderedURL(ctx, key, rawURL); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
// The tool's own proxy is a connection the panel opens too: with the gate
// on it is a target, as a proxy named on a Bash command line is, and the
// dial is checked again (httpToolTransport). Gate off, it is not checked,
// like the tool URL itself, which may name a loopback or private address
// in that mode. In required mode the sandbox policy checks the proxy dial.
if sbPolicy == nil {
if proxy := s.toolOwnProxy(spec); proxy != "" {
// The proxy is a direct hop: ARTEX dials it itself, so its pin binds
// the addresses the approval resolved, not the name alone.
if res := intercept.GateRenderedURL(intercept.WithDirectHop(ctx), key, gateProxyURL(proxy)); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
}
}
if err := intercept.CheckStatefulTool(ctx, key, nil, rawURL, method); err != nil {
return actool.Errorf(err.Error()), nil
}
@@ -741,6 +780,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if sbPolicy != nil {
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
}
if secretOrigin != "" {
client.CheckRedirect = secretOriginRedirectCheck(secretOrigin, client.CheckRedirect)
}
// The current egress governor paces every request and redirect hop per host
// under the noise profile (off by default: the base transport itself). It is
// resolved per request, so a changed profile applies to the next call.
@@ -765,6 +807,114 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
return actool.Text(actool.Capture(tc, string(b))), nil
}
// httpToolHasSecrets reports whether an HTTP tool carries stored values the API
// masks: any non-empty header value or body.
func httpToolHasSecrets(spec httpExec) bool {
for _, v := range spec.Headers {
if strings.TrimSpace(v) != "" {
return true
}
}
return strings.TrimSpace(spec.Body) != ""
}
// validateHTTPToolExec refuses a secret-bearing HTTP tool whose url authority is
// parameterized. The stored headers and body would otherwise follow the rendered
// host to any third party.
func validateHTTPToolExec(e map[string]any) error {
raw, err := json.Marshal(e)
if err != nil {
return nil
}
var spec httpExec
if json.Unmarshal(raw, &spec) != nil {
return errors.New("invalid HTTP tool exec")
}
if !httpToolHasSecrets(spec) {
return nil
}
if _, ok := fixedHTTPOrigin(spec.URL); !ok {
return errors.New("an HTTP tool with stored headers or body needs a fixed origin: the url scheme, host and port cannot contain parameters")
}
return nil
}
// httpToolSecretOrigin returns the origin a secret-bearing HTTP tool must stay
// on, or "" when the tool carries no stored header or body.
func httpToolSecretOrigin(spec httpExec, rawURL string) (string, error) {
if !httpToolHasSecrets(spec) {
return "", nil
}
fixed, ok := fixedHTTPOrigin(spec.URL)
if !ok {
return "", errors.New("this HTTP tool sends stored headers or body, so its url must have a fixed scheme, host and port (no parameters)")
}
u, err := url.Parse(rawURL)
if err != nil {
return "", errors.New("http url is invalid")
}
rendered, err := canonicalOrigin(u)
if err != nil || rendered != fixed {
return "", fmt.Errorf("this HTTP tool sends stored headers or body, so the rendered url must stay on %s", fixed)
}
return fixed, nil
}
// fixedHTTPOrigin returns the canonical origin of a url template whose scheme,
// host and port are literal. ok is false when a parameter or an invalid url
// makes the destination dynamic.
func fixedHTTPOrigin(template string) (string, bool) {
u, err := url.Parse(strings.TrimSpace(template))
if err != nil || u.Scheme == "" || u.Host == "" {
return "", false
}
if strings.ContainsAny(u.Scheme, "{}") || strings.ContainsAny(u.Host, "{}") ||
(u.User != nil && strings.ContainsAny(u.User.String(), "{}")) {
return "", false
}
origin, err := canonicalOrigin(u)
if err != nil {
return "", false
}
return origin, true
}
// canonicalOrigin normalizes scheme, host case and default port, so a redirect
// is same-origin only when it keeps all three.
func canonicalOrigin(u *url.URL) (string, error) {
scheme := strings.ToLower(strings.TrimSpace(u.Scheme))
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("scheme %q is not http or https", u.Scheme)
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if host == "" {
return "", errors.New("url has no host")
}
port := u.Port()
if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
port = ""
}
if port != "" {
return scheme + "://" + net.JoinHostPort(host, port), nil
}
if strings.Contains(host, ":") {
return scheme + "://[" + host + "]", nil
}
return scheme + "://" + host, nil
}
// secretOriginRedirectCheck refuses a redirect hop that leaves the origin the
// tool's stored headers and body were configured for.
func secretOriginRedirectCheck(origin string, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
next, err := canonicalOrigin(req.URL)
if err != nil || next != origin {
return errors.New("redirect to a different origin refused: this HTTP tool sends stored headers or body")
}
return check(req, via)
}
}
// assessmentRedirectCheck sheds the generated identifier on the first redirect
// to another origin. net/http copies headers from the initial request for each
// hop, so check the previous hop to keep the identifier off after that point.
@@ -813,9 +963,16 @@ func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *htt
// httpToolTransport is the transport of one http tool call, or nil
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
// dials the proxy, which makes the connection to the target. A direct call in
// a gated scope connects through the pinned dialer, to addresses a pin covers.
// a gated scope connects through the pinned dialer, to addresses a pin covers;
// so does the tool's own proxy outside required mode.
func (s *Server) httpToolTransport(ctx context.Context, key string, spec httpExec) *http.Transport {
if tr := s.httpProxyTransport(spec); tr != nil {
if intercept.GateOn(ctx) && !agent.SandboxRequired() && s.toolOwnProxy(spec) != "" {
// The proxy hop is direct: the dial resolves and pins its addresses,
// so a proxy name that later answers another address is refused.
tr.DialContext = intercept.PinnedDialerDirect(key)
tr.DisableKeepAlives = true
}
return tr
}
if !intercept.GateOn(ctx) {
@@ -868,6 +1025,40 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport {
return tr
}
// toolOwnProxy returns the proxy URL of the tool's own exec.proxy when the call
// goes through it, "" when the call is direct or goes through the recording or
// global proxy, endpoints the gate exempts as configured (see
// httpProxyTransport).
func (s *Server) toolOwnProxy(spec httpExec) string {
if spec.UseRecordingProxy {
if tr := s.m.Traffic(); tr != nil && s.m.TrafficEnabled() {
return ""
}
if proxyURLString(s.m.GlobalProxy()) != "" {
return ""
}
}
proxy := proxyURLString(spec.Proxy)
if _, err := url.Parse(proxy); err != nil {
return "" // httpProxyTransport goes direct
}
return proxy
}
// gateProxyURL is a tool proxy as the gate reads it: without credentials,
// since the gate records the URL it checks, and with the port net/http dials
// for a socks5 proxy that names none. "" (no host) fails closed in the gate.
func gateProxyURL(proxy string) string {
u, err := url.Parse(proxyWithoutCredentials(proxy))
if err != nil || u.Host == "" {
return ""
}
if s := strings.ToLower(u.Scheme); (s == "socks5" || s == "socks5h") && u.Port() == "" {
u.Host = strings.TrimSuffix(u.Host, ":") + ":1080" // u.Host keeps IPv6 brackets
}
return u.String()
}
// proxyURLString returns a proxy address as a URL: a bare host:port gets
// "http://", an address that already has a scheme (as ProxyAddr returns it) is
// kept as is.
+42 -22
View File
@@ -118,10 +118,12 @@ func TestCustomHTTPDirectDialPinned(t *testing.T) {
// With the gate off (and without a scope) the call keeps http.DefaultTransport:
// no transport is built. A spec with a proxy keeps its proxy transport, without
// a dialer. Gate on and direct: a transport with the pinned dialer, no
// environment proxy, keep-alive off.
// environment proxy, keep-alive off. Gate on, the tool's own proxy is dialled
// through the pinned dialer too.
func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
s := &Server{}
direct := httpExec{URL: "http://api.example.com/"}
proxied := httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}
scope := func(on bool) context.Context {
return intercept.WithTargetScope(context.Background(), intercept.TargetScope{TaskID: "7", Enabled: func() bool { return on }})
}
@@ -129,9 +131,12 @@ func TestCustomHTTPGateOffTransportUnchanged(t *testing.T) {
if tr := s.httpToolTransport(ctx, "probe", direct); tr != nil {
t.Fatalf("%s: transport %+v, want nil (http.DefaultTransport)", name, tr)
}
if tr := s.httpToolTransport(ctx, "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext != nil || tr.DisableKeepAlives {
t.Fatalf("%s, operator proxy: transport %+v, want the proxy transport without a dialer", name, tr)
}
}
if tr := s.httpToolTransport(scope(true), "probe", httpExec{URL: direct.URL, Proxy: "http://127.0.0.1:1"}); tr == nil || tr.Proxy == nil || tr.DialContext != nil {
t.Fatalf("operator proxy: transport %+v, want the proxy transport without a dialer", tr)
if tr := s.httpToolTransport(scope(true), "probe", proxied); tr == nil || tr.Proxy == nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated operator proxy: transport %+v, want the proxy transport with the pinned dialer", tr)
}
if tr := s.httpToolTransport(scope(true), "probe", direct); tr == nil || tr.Proxy != nil || tr.DialContext == nil || !tr.DisableKeepAlives {
t.Fatalf("gated direct call: transport %+v", tr)
@@ -239,13 +244,13 @@ func TestCustomToolTestEndpointDialUngated(t *testing.T) {
}
}
// Documents a known limit: a custom http tool that goes through a proxy is not
// bound to pins. The pinned dialer covers direct connections only; through a
// proxy the connection to the target is the proxy's, and the proxy here
// connects to a peer nobody pinned. Step 2.2 binds the recording proxy (and
// flips its half of this test); an operator-written proxy stays unbound
// (OPEN-6).
func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
// A custom http tool that goes through a proxy: the target pin is name-only,
// since the proxy makes the connection to the target, and the proxy here
// connects to a peer nobody pinned. The tool's own proxy is a gate target
// (formerly the known limit OPEN-6): the call waits for its approval, then the
// proxy is dialled through the pinned dialer. The recording and global proxies
// are not checked here and are dialled as before.
func TestCustomHTTPOwnProxyGated(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
@@ -270,28 +275,43 @@ func TestBypass_CustomHTTPProxyPeerNotPinned(t *testing.T) {
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, key)
// The tool's own proxy: refused until its host:port is approved, then
// dialled through the pinned dialer, at the pinned proxy address only.
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
dialer.route(proxyKey, proxy.Listener.Addr().String())
ownProxy := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "proxy": proxy.URL})})
callOwn := func() (string, bool) { return callTool(t, ownProxy, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, ownProxy, callOwn, proxyKey)
if hits.Load() != 0 || len(dialer.calls()) != 0 {
t.Fatalf("the proxy was dialled before its approval: hits=%d dialled %v", hits.Load(), dialer.calls())
}
if out, isErr := callOwn(); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("operator proxy after the approval: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
if got := dialer.calls(); !slices.Equal(got, []string{proxyKey}) {
t.Fatalf("dialled %v, want the pinned proxy only; the pinned address 203.0.113.7 is never dialled through a proxy", got)
}
// use_recording_proxy through the global proxy: not checked here, as before.
// The global proxy carries a scheme, as in production (ProxyAddr returns it
// as is with capture off); httpProxyTransport must not write a second one.
global := httptest.NewServer(proxy.Config.Handler)
t.Cleanup(global.Close)
g.m.mu.Lock()
g.m.globalProxy = proxy.URL
g.m.globalProxy = global.URL
g.m.mu.Unlock()
t.Cleanup(func() {
g.m.mu.Lock()
g.m.globalProxy = ""
g.m.mu.Unlock()
})
for name, exec := range map[string]map[string]any{
"operator proxy": {"url": url, "proxy": proxy.URL},
"use_recording_proxy": {"url": url, "use_recording_proxy": true},
} {
before := hits.Load()
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, exec)})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("%s: error=%v out=%q", name, isErr, out)
}
before, dialled := hits.Load(), len(dialer.calls())
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_bypass", Kind: "http", Exec: execJSON(t, map[string]any{"url": url, "use_recording_proxy": true})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != before+1 {
t.Fatalf("use_recording_proxy: error=%v out=%q", isErr, out)
}
if got := dialer.calls(); len(got) != 0 {
t.Fatalf("dialled %v; the pinned address 203.0.113.7 is never dialled through a proxy", got)
if got := dialer.calls(); len(got) != dialled {
t.Fatalf("dialled %v; the global proxy is not dialled through the gate", got[dialled:])
}
}
+141
View File
@@ -0,0 +1,141 @@
package server
import (
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
// Gate on: the tool's own proxy is a target. An approved target URL does not
// let the call reach an unapproved proxy: the proxy is not dialled and a
// request opens on its host:port, recorded without the proxy credentials.
func TestCustomHTTPGatedOwnProxyNotDialed(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
_, proxyHits, _, proxyPort := countingServer(t)
targetURL := "http://" + host + ":" + port + "/"
direct := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http", Exec: execJSON(t, map[string]any{"url": targetURL})})
approveTarget(t, g, task, direct, func() (string, bool) { return callTool(t, direct, gatedCtx(task, 0), `{}`, nil) }, host+":"+port)
if out, isErr := callTool(t, direct, gatedCtx(task, 0), `{}`, nil); isErr || targetHits.Load() != 1 {
t.Fatalf("approved direct call: error=%v out=%q", isErr, out)
}
proxyKey := "127.0.0.1:" + proxyPort
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_own_proxy", Kind: "http",
Exec: execJSON(t, map[string]any{"url": targetURL, "proxy": "http://user:pw-secret@" + proxyKey})})
out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil)
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("unapproved proxy: error=%v out=%q", isErr, out)
}
if n := proxyHits.Load(); n != 0 {
t.Fatalf("unapproved proxy received %d request(s)", n)
}
if n := targetHits.Load(); n != 1 {
t.Fatalf("target received %d request(s), want only the direct one", n)
}
_, toolName, input, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey)
if !ok || toolName != "probe_own_proxy" || strings.Contains(input, "pw-secret") || strings.Contains(input, "user") {
t.Fatalf("request on the proxy: ok=%v tool=%q input=%s", ok, toolName, input)
}
}
// A saved tool's own proxy is a direct hop: the approval pins the addresses it
// resolved, and a proxy name that later answers another address is refused
// instead of being dialled unpinned (DNS rebinding). The tool is saved so the
// manager knows it uses a proxy, as in production.
func TestCustomHTTPOwnProxyHostnameRebindingRefused(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
_, targetHits, host, port := countingServer(t)
proxy, proxyHits, _, _ := countingServer(t)
targetKey := host + ":" + port
proxyKey := "proxy.example.com:3128"
res := &countingResolver{answers: map[string][]string{"proxy.example.com": {"203.0.113.7"}}}
g.m.interceptor.SetResolver(res)
dialer := newRouteDialer(g)
dialer.route("203.0.113.7:3128", proxy.Listener.Addr().String())
tool := &db.Tool{Key: "probe_rebind_proxy", Kind: "http", Description: "probe",
Exec: execJSON(t, map[string]any{"url": "http://" + targetKey + "/", "proxy": "http://" + proxyKey})}
if err := g.m.pg.CreateCustomTool(tool); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = g.m.pg.DeleteCustomTool(tool.Key) })
built := g.s.buildCustomTool(tool)
call := func() (string, bool) { return callTool(t, built, gatedCtx(task, 0), `{}`, nil) }
approveTarget(t, g, task, built, call, targetKey)
approveTarget(t, g, task, built, call, proxyKey)
if out, isErr := call(); isErr || !strings.Contains(out, "probe-reached") || proxyHits.Load() != 1 {
t.Fatalf("approved proxy: error=%v out=%q hits=%d", isErr, out, proxyHits.Load())
}
pins, err := g.m.pg.ActiveTargetPins(taskRef(t, task), "proxy.example.com", 3128)
if err != nil || len(pins) != 1 || pins[0].NameOnlyEffective ||
len(pins[0].PinnedIPs) != 1 || pins[0].PinnedIPs[0] != "203.0.113.7" {
t.Fatalf("proxy pin: %+v, %v", pins, err)
}
res.set("proxy.example.com", "203.0.113.9")
beforeTarget, beforeProxy, beforeCalls := targetHits.Load(), proxyHits.Load(), len(dialer.calls())
out, isErr := call()
if !isErr || !strings.Contains(out, "TARGET_APPROVAL_PENDING") || !strings.Contains(out, proxyKey) {
t.Fatalf("rebound proxy: error=%v out=%q", isErr, out)
}
if proxyHits.Load() != beforeProxy || targetHits.Load() != beforeTarget {
t.Fatalf("rebound proxy was reached: proxy=%d target=%d",
proxyHits.Load()-beforeProxy, targetHits.Load()-beforeTarget)
}
if got := len(dialer.calls()); got != beforeCalls {
t.Fatalf("dialled %v after the rebind", dialer.calls()[beforeCalls:])
}
}
// Gate off (sandbox off): the proxy is not checked, as on c03939c1. The tool
// URL itself is not checked in that mode either.
func TestCustomHTTPOwnProxyGateOffUnchanged(t *testing.T) {
g := newGateServer(t)
off := false
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &off})
_, hits, host, port := countingServer(t)
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_gate_off", Kind: "http",
Exec: execJSON(t, map[string]any{"url": "http://api.example.com/", "proxy": "http://" + host + ":" + port})})
if out, isErr := callTool(t, tool, gatedCtx(task, 0), `{}`, nil); isErr || !strings.Contains(out, "probe-reached") || hits.Load() != 1 {
t.Fatalf("gate off, loopback proxy: error=%v out=%q hits=%d", isErr, out, hits.Load())
}
}
// ARTEX_SANDBOX=required with the gate on: the proxy is checked by the sandbox
// egress policy only, as on c03939c1. A proxy inside the sandbox scope and
// never approved in the gate is dialled, and no gate request opens on it.
func TestSandboxHTTPToolGatedProxyUnchanged(t *testing.T) {
g := newGateServer(t)
on := true
task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on})
target, targetHits := canaryServer(t, "127.0.0.1", nil)
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
targetKey := strings.TrimPrefix(target.URL, "http://")
proxyKey := strings.TrimPrefix(proxy.URL, "http://")
sandboxRequired(t)
call := func(exec map[string]any) (string, bool) {
tool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, exec)})
ctx := agent.WithSandboxRunInfo(gatedCtx(task, 0), agent.SandboxRunInfo{
TaskID: task.ID, ScopeCIDRs: []string{"127.0.0.1/32", "127.0.0.2/32"},
})
return callTool(t, tool, ctx, `{}`, nil)
}
direct := map[string]any{"method": "GET", "url": target.URL + "/"}
directTool := g.s.buildCustomTool(&db.Tool{Key: "probe_sb_proxy", Kind: "http", Exec: execJSON(t, direct)})
approveTarget(t, g, task, directTool, func() (string, bool) { return call(direct) }, targetKey)
before := targetHits.Load()
out, isErr := call(map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
if isErr || !strings.Contains(out, "CANARY_BODY") || proxyHits.Load() != 1 || targetHits.Load() != before {
t.Fatalf("required mode, in-scope proxy: error=%v out=%q proxy hits=%d", isErr, out, proxyHits.Load())
}
if _, _, _, ok := openTargetRequest(t, g.m.pg, task.ID, proxyKey); ok {
t.Fatal("required mode opened a gate request on the proxy")
}
}
+20
View File
@@ -0,0 +1,20 @@
package server
import "testing"
// The gate reads a tool proxy without its credentials, with the port a socks5
// proxy without one is dialled on.
func TestGateProxyURL(t *testing.T) {
for in, want := range map[string]string{
"http://user:pw@10.0.0.5:8080": "http://10.0.0.5:8080",
"socks5://user:pw@10.0.0.5": "socks5://10.0.0.5:1080",
"socks5h://[::1]": "socks5h://[::1]:1080",
"socks5://10.0.0.5:9050": "socks5://10.0.0.5:9050",
"https://proxy.example": "https://proxy.example",
"http://": "",
} {
if got := gateProxyURL(in); got != want {
t.Fatalf("gateProxyURL(%q) = %q, want %q", in, got, want)
}
}
}
+225
View File
@@ -0,0 +1,225 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/notify"
)
func TestFixedHTTPOrigin(t *testing.T) {
for _, tc := range []struct {
url string
want string
ok bool
}{
{"https://api.example.com/x", "https://api.example.com", true},
{"https://API.Example.com:443/x", "https://api.example.com", true},
{"http://api.example.com:80/x", "http://api.example.com", true},
{"http://api.example.com:8080/x", "http://api.example.com:8080", true},
{"https://api.example.com/{path}", "https://api.example.com", true},
{"https://[::1]:443/x", "https://[::1]", true},
{"https://[::1]:8443/x", "https://[::1]:8443", true},
{"https://{user}@api.example.com/x", "", false},
{"https://{host}/x", "", false},
{"https://api.{domain}/x", "", false},
{"https://api.example.com:{port}/x", "", false},
{"ftp://api.example.com/x", "", false},
{"/relative", "", false},
} {
got, ok := fixedHTTPOrigin(tc.url)
if ok != tc.ok || got != tc.want {
t.Errorf("fixedHTTPOrigin(%q) = %q, %v; want %q, %v", tc.url, got, ok, tc.want, tc.ok)
}
}
}
func TestHTTPToolSecretOrigin(t *testing.T) {
// A tool without stored headers or body may keep a parameterized authority.
if origin, err := httpToolSecretOrigin(httpExec{URL: "https://{host}/collect"}, "https://attacker.example/collect"); err != nil || origin != "" {
t.Fatalf("no-secret tool: origin=%q err=%v", origin, err)
}
// The rendered url must stay on the template origin.
if _, err := httpToolSecretOrigin(httpExec{
URL: "https://api.example.com/x",
Headers: map[string]string{"X-API-Key": "secret"},
}, "https://attacker.example/x"); err == nil {
t.Fatal("rendered url outside the template origin accepted")
}
}
func TestUnmaskToolExecRequiresFixedOriginForSecrets(t *testing.T) {
exec := func(url string, headers map[string]string) json.RawMessage {
b, _ := json.Marshal(map[string]any{"method": "GET", "url": url, "headers": headers})
return b
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", map[string]string{"X-API-Key": "secret"})); err == nil {
t.Fatal("parameterized authority with a stored header accepted")
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/collect", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("fixed origin refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://{host}/collect", nil)); err != nil {
t.Fatalf("parameterized authority without secrets refused: %v", err)
}
if _, err := unmaskToolExec("", nil, "http", exec("https://api.example.com/{path}", map[string]string{"X-API-Key": "secret"})); err != nil {
t.Fatalf("path parameter with a fixed origin refused: %v", err)
}
}
func noSandbox(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(nil)
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
func TestHTTPToolRefusesParameterizedAuthorityWithSecrets(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": "https://{host}/collect",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestUnmaskToolExecRejectsMalformedHTTPExec(t *testing.T) {
raw := json.RawMessage(`{"method":"GET","url":"https://api.example.com/","headers":{"X":1}}`)
if _, err := unmaskToolExec("", nil, "http", raw); err == nil {
t.Fatal("numeric header value accepted")
}
}
func TestUnmaskToolExecRefusesProxyChangeWithSecrets(t *testing.T) {
stored := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"}}`)
masked := func(proxy string, recording bool) json.RawMessage {
m := map[string]any{
"method": "GET",
"url": "https://api.example.com/collect",
"headers": map[string]string{"X-API-Key": notify.MaskedPrefix},
}
if proxy != "" {
m["proxy"] = proxy
}
if recording {
m["use_recording_proxy"] = true
}
b, _ := json.Marshal(m)
return b
}
if _, err := unmaskToolExec("http", stored, "http", masked("http://attacker.example:8080", false)); err == nil {
t.Fatal("proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", true)); err == nil {
t.Fatal("recording proxy change with a kept secret accepted")
}
if _, err := unmaskToolExec("http", stored, "http", masked("", false)); err != nil {
t.Fatalf("unchanged destination refused: %v", err)
}
storedProxy := json.RawMessage(`{"method":"GET","url":"https://api.example.com/collect","headers":{"X-API-Key":"secret"},"proxy":"http://proxy.example:8080"}`)
if _, err := unmaskToolExec("http", storedProxy, "http", masked("", false)); err != nil {
t.Fatalf("clearing the configured proxy refused: %v", err)
}
}
func TestHTTPToolRefusesParameterizedAuthorityWithBodySecret(t *testing.T) {
noSandbox(t)
raw, _ := json.Marshal(map[string]any{
"method": "POST",
"url": "https://{host}/collect",
"body": "token=secret",
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, map[string]any{"host": "attacker.example"}, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "fixed scheme, host and port") {
t.Fatalf("body-bearing parameterized authority not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
}
func TestHTTPToolSecretStaysOnConfiguredOrigin(t *testing.T) {
noSandbox(t)
for _, code := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
t.Run(http.StatusText(code), func(t *testing.T) {
var outsideHits atomic.Int32
outside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
outsideHits.Add(1)
_, _ = w.Write([]byte("outside"))
}))
defer outside.Close()
var startHits atomic.Int32
start := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startHits.Add(1)
if got := r.Header.Get("X-API-Key"); got != "secret" {
t.Errorf("first hop header = %q, want secret", got)
}
http.Redirect(w, r, outside.URL+"/stolen", code)
}))
defer start.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": start.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "different origin") {
t.Fatalf("cross-origin redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
}
if n := outsideHits.Load(); n != 0 {
t.Fatalf("outside origin received %d request(s)", n)
}
if n := startHits.Load(); n != 1 {
t.Fatalf("start origin hits = %d, want 1", n)
}
})
}
}
func TestHTTPToolSecretAllowsSameOriginRedirect(t *testing.T) {
noSandbox(t)
var finalHits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/start" {
http.Redirect(w, r, "/final", http.StatusFound)
return
}
finalHits.Add(1)
_, _ = w.Write([]byte("final"))
}))
defer srv.Close()
raw, _ := json.Marshal(map[string]any{
"method": "GET",
"url": srv.URL + "/start",
"headers": map[string]string{"X-API-Key": "secret"},
})
res, err := (&Server{}).runHTTPTool(context.Background(), "probe", raw, nil, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("same-origin redirect refused: %s", res.Flatten())
}
if n := finalHits.Load(); n != 1 {
t.Fatalf("final origin hits = %d, want 1", n)
}
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"context"
"errors"
"fmt"
"log"
"path/filepath"
"strconv"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
)
// retestSandboxContext gives a running retest its own runner identity and
// workspace. Only the source task's operator-approved egress is inherited;
// the finding snapshot, notes, and conversation approval pins grant no egress.
func (s *Server) retestSandboxContext(ctx context.Context, r *db.FindingRetest) (context.Context, func(), error) {
cleanup := func() {}
if s.sandboxMode != sandbox.ModeRequired {
return ctx, cleanup, nil
}
if r.ConversationID == nil || *r.ConversationID <= 0 {
return ctx, cleanup, errors.New("retest has no conversation")
}
if err := s.checkSandboxReady(ctx); err != nil {
return ctx, cleanup, err
}
f, err := s.m.pg.GetFinding(r.FindingID)
if err != nil {
return ctx, cleanup, fmt.Errorf("load retest source: %w", err)
}
if f == nil {
return ctx, cleanup, errors.New("retest source finding no longer exists")
}
var info agent.SandboxRunInfo
if f.TaskID != nil {
info, err = taskSandboxRunInfoChecked(s.m.pg, s.m.dir, strconv.FormatInt(*f.TaskID, 10))
if err != nil {
return ctx, cleanup, fmt.Errorf("load retest egress scope: %w", err)
}
}
info.TaskID = "retest-" + strconv.FormatInt(*r.ConversationID, 10)
info.TaskDir = filepath.Join(s.m.dir, "tasks", info.TaskID)
client := s.sandboxClient
cleanup = func() {
// The run context may already be cancelled. Delete stops the worker and
// removes its proxy/network, preserving the retest's files for inspection.
stop, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := client.Delete(stop, info.TaskID); err != nil && !errors.Is(err, sandbox.ErrNotFound) {
log.Printf("[retest] sandbox cleanup %s: %v", info.TaskID, err)
}
}
return agent.WithSandboxRunInfo(ctx, info), cleanup, nil
}
+317
View File
@@ -0,0 +1,317 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/transcript"
)
func newSandboxRetestServer(t *testing.T) (*Server, int64, *stubSandboxClient) {
t.Helper()
s, fid := newRetestServer(t)
stub := &stubSandboxClient{health: sandbox.HealthResponse{OK: true, Docker: true}}
s.sandboxMode, s.sandboxClient = sandbox.ModeRequired, stub
prev := agent.CurrentSandboxExecutor()
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired, Runner: stub})
return s, fid, stub
}
func retestToolReply(name, input string) (llm.Message, string, llm.Usage, error) {
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: name, Name: name, Input: json.RawMessage(input),
}}}, "tool_use", llm.Usage{}, nil
}
func launchSandboxRetest(t *testing.T, s *Server, fid int64) db.FindingRetest {
t.Helper()
w := retestRequest(s.startFindingRetest, "POST", fid, "{}")
if w.Code != 202 {
t.Fatalf("start: %d %s", w.Code, w.Body)
}
var body struct {
Retest db.FindingRetest `json:"retest"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body.Retest
}
func TestRetestSandboxSharesWorkspaceAndApprovedScope(t *testing.T) {
s, fid, stub := newSandboxRetestServer(t)
task, err := s.m.pg.CreateTaskWithOptions("retest source", "", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.m.pg.DeleteTask(task.ID) })
if _, err := s.m.pg.Exec("UPDATE findings SET task_id=$1 WHERE id=$2", task.ID, fid); err != nil {
t.Fatal(err)
}
if _, err := s.m.pg.Exec("UPDATE tasks SET target_gate=true WHERE id=$1", task.ID); err != nil {
t.Fatal(err)
}
for _, scope := range []struct{ kind, value string }{{"root_domain", "approved.example"}, {"cidr", "203.0.113.0/24"}} {
if _, err := s.m.pg.Assets().AddOperatorScope(task.ID, scope.kind, scope.value, "operator"); err != nil {
t.Fatal(err)
}
}
if _, err := s.m.pg.Assets().AddAgentScope(task.ID, "root_domain", "unapproved.example", "agent", "agent"); err != nil {
t.Fatal(err)
}
var ranIDs []string
stub.execFn = func(ctx context.Context, taskID string, req sandbox.ExecRequest) (sandbox.ExecResponse, error) {
info, ok := agent.SandboxRunInfoFromContext(ctx)
if !ok || taskID != info.TaskID || taskID == strconv.FormatInt(task.ID, 10) || req.Workdir != "/workspace" {
return sandbox.ExecResponse{}, fmt.Errorf("wrong execution identity/workspace: %s %s", taskID, req.Workdir)
}
if strings.Join(req.ScopeDomains, ",") != "approved.example" || strings.Join(req.ScopeCIDRs, ",") != "203.0.113.0/24" {
return sandbox.ExecResponse{}, fmt.Errorf("unexpected egress: %+v", req)
}
data, err := os.ReadFile(filepath.Join(info.TaskDir, "probe.txt"))
if err != nil {
return sandbox.ExecResponse{}, err
}
ranIDs = append(ranIDs, taskID)
return sandbox.ExecResponse{Stdout: string(data)}, nil
}
for attempt := 0; attempt < 2; attempt++ {
var calls atomic.Int32
setRetestProvider(s, retestProvider{complete: func(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
info, ok := agent.SandboxRunInfoFromContext(ctx)
if !ok || "conv-"+strings.TrimPrefix(info.TaskID, "retest-") != transcript.SessionIDFrom(ctx) {
return llm.Message{}, "", llm.Usage{}, errors.New("missing or mismatched retest identity")
}
gate, ok := intercept.TargetScopeFromContext(ctx)
if !ok || !gate.Enabled() {
return llm.Message{}, "", llm.Usage{}, errors.New("target approval gate lost")
}
if !strings.Contains(strings.Join(req.System, "\n"), "Bash runs in /workspace") {
return llm.Message{}, "", llm.Usage{}, errors.New("sandbox path mapping missing from prompt")
}
switch calls.Add(1) {
case 1:
return retestToolReply("Write", `{"file_path":"probe.txt","content":"retest-workspace-ok"}`)
case 2:
return retestToolReply("Bash", `{"command":"cat probe.txt","timeout_ms":1000}`)
case 3:
raw, _ := json.Marshal(req.Messages)
if !strings.Contains(string(raw), "retest-workspace-ok") {
return llm.Message{}, "", llm.Usage{}, errors.New("Bash did not return written evidence")
}
return retestToolReply("record_finding_retest_result", `{"verdict":"inconclusive","summary":"isolated fixture","evidence":"Write and Bash shared the retest workspace."}`)
}
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("done")}}, "end_turn", llm.Usage{}, nil
}})
r := launchSandboxRetest(t, s, fid)
waitRetestIdle(t, s)
rows, err := s.m.pg.ListFindingRetests(fid)
if err != nil || len(rows) != attempt+1 || rows[0].Status != "completed" || rows[0].Verdict != "inconclusive" {
t.Fatalf("history=%+v err=%v", rows, err)
}
id := "retest-" + strconv.FormatInt(*r.ConversationID, 10)
if len(ranIDs) != attempt+1 || ranIDs[attempt] != id {
t.Fatalf("execution IDs: %v", ranIDs)
}
stub.mu.Lock()
deleted := append([]string(nil), stub.deletes...)
stub.mu.Unlock()
if len(deleted) != attempt+1 || deleted[attempt] != id {
t.Fatalf("cleanup IDs: %v", deleted)
}
if data, err := os.ReadFile(filepath.Join(s.m.dir, "tasks", id, "probe.txt")); err != nil || string(data) != "retest-workspace-ok" {
t.Fatalf("evidence removed: %q %v", data, err)
}
}
if ranIDs[0] == ranIDs[1] {
t.Fatal("separate retests reused a workspace")
}
}
func TestRetestSandboxNoSourceTaskDeniesEgress(t *testing.T) {
s, fid, _ := newSandboxRetestServer(t)
r, _, _, err := s.m.pg.CreateFindingRetest(t.Context(), fid, "https://notes-do-not-authorize.example")
if err != nil {
t.Fatal(err)
}
ctx, cleanup, err := s.retestSandboxContext(t.Context(), r)
if err != nil {
t.Fatal(err)
}
defer cleanup()
info, ok := agent.SandboxRunInfoFromContext(ctx)
if !ok || len(info.ScopeDomains) != 0 || len(info.ScopeCIDRs) != 0 {
t.Fatalf("unscoped finding gained egress: %+v", info)
}
policy := agent.SandboxEgressPolicy(ctx)
policy.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
}
if _, err := policy.ResolveAndCheck(t.Context(), "notes-do-not-authorize.example"); err == nil {
t.Fatal("notes granted egress")
}
}
func TestRetestSandboxPreparationFailsClosed(t *testing.T) {
for _, mode := range []string{"runner_down", "docker_down", "scope_read_error"} {
t.Run(mode, func(t *testing.T) {
s, fid, stub := newSandboxRetestServer(t)
switch mode {
case "runner_down":
stub.healthEr = errors.New("runner unavailable")
case "docker_down":
stub.health.Docker = false
case "scope_read_error":
task, err := s.m.pg.CreateTaskWithOptions("broken source scope", "", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.m.pg.DeleteTask(task.ID) })
if _, err := s.m.pg.Exec("UPDATE findings SET task_id=$1 WHERE id=$2", task.ID, fid); err != nil {
t.Fatal(err)
}
if _, err := s.m.pg.Exec("ALTER TABLE task_scope RENAME TO task_scope_retest_unavailable"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if _, err := s.m.pg.Exec("ALTER TABLE task_scope_retest_unavailable RENAME TO task_scope"); err != nil {
t.Error(err)
}
})
}
var calls atomic.Int32
setRetestProvider(s, retestProvider{complete: func(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
calls.Add(1)
return llm.Message{}, "", llm.Usage{}, errors.New("unexpected provider call")
}})
launchSandboxRetest(t, s, fid)
waitRetestIdle(t, s)
rows, err := s.m.pg.ListFindingRetests(fid)
if err != nil || len(rows) != 1 || rows[0].Status != "failed" || rows[0].Error == "" || calls.Load() != 0 {
t.Fatalf("history=%+v calls=%d err=%v", rows, calls.Load(), err)
}
if len(stub.execs) != 0 {
t.Fatal("ran a command after preparation failed")
}
})
}
}
type retestCleanupClient struct {
*stubSandboxClient
entered chan struct{}
release chan struct{}
}
func (c *retestCleanupClient) Delete(ctx context.Context, id string) (sandbox.DeleteResponse, error) {
close(c.entered)
select {
case <-c.release:
case <-ctx.Done():
return sandbox.DeleteResponse{}, ctx.Err()
}
return c.stubSandboxClient.Delete(ctx, id)
}
func TestRetestSandboxCancellationDrainsCleanup(t *testing.T) {
s, fid, stub := newSandboxRetestServer(t)
commandStarted := make(chan struct{})
stub.execFn = func(ctx context.Context, _ string, _ sandbox.ExecRequest) (sandbox.ExecResponse, error) {
close(commandStarted)
<-ctx.Done()
return sandbox.ExecResponse{}, ctx.Err()
}
cleanup := &retestCleanupClient{stubSandboxClient: stub, entered: make(chan struct{}), release: make(chan struct{})}
s.sandboxClient = cleanup
// Release even when an assertion fails, before fixture cleanup waits for idle.
t.Cleanup(func() {
select {
case <-cleanup.release:
default:
close(cleanup.release)
}
})
setRetestProvider(s, retestProvider{complete: func(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return retestToolReply("Bash", `{"command":"sleep 60","timeout_ms":60000}`)
}})
r := launchSandboxRetest(t, s, fid)
select {
case <-commandStarted:
case <-time.After(3 * time.Second):
t.Fatal("sandbox command not reached")
}
w := retestRequest(s.pgStopConversation, "POST", *r.ConversationID, "{}")
if w.Code != 200 {
t.Fatalf("stop: %d %s", w.Code, w.Body)
}
select {
case <-cleanup.entered:
case <-time.After(3 * time.Second):
t.Fatal("cleanup not reached")
}
waitCtx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
defer cancel()
if err := s.Wait(waitCtx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("shutdown did not wait for sandbox cleanup: %v", err)
}
close(cleanup.release)
drain, cancelDrain := context.WithTimeout(t.Context(), 3*time.Second)
defer cancelDrain()
if err := s.Wait(drain); err != nil {
t.Fatal(err)
}
rows, err := s.m.pg.ListFindingRetests(fid)
if err != nil || len(rows) != 1 || rows[0].Status != "stopped" || rows[0].Verdict != "" {
t.Fatalf("history=%+v err=%v", rows, err)
}
if len(stub.deletes) != 1 || stub.deletes[0] != "retest-"+strconv.FormatInt(*r.ConversationID, 10) {
t.Fatalf("cleanup did not survive cancellation: %v", stub.deletes)
}
}
func TestRetestSandboxModelFailureAndSealedFollowup(t *testing.T) {
s, fid, stub := newSandboxRetestServer(t)
setRetestProvider(s, retestProvider{complete: func(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return llm.Message{}, "", llm.Usage{}, errors.New("fixture model failure")
}})
r := launchSandboxRetest(t, s, fid)
waitRetestIdle(t, s)
rows, err := s.m.pg.ListFindingRetests(fid)
if err != nil || len(rows) != 1 || rows[0].Status != "failed" || len(stub.deletes) != 1 {
t.Fatalf("history=%+v cleanup=%v err=%v", rows, stub.deletes, err)
}
var calls atomic.Int32
var sandboxSeen atomic.Bool
setRetestProvider(s, retestProvider{complete: func(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
calls.Add(1)
if _, ok := agent.SandboxRunInfoFromContext(ctx); ok {
sandboxSeen.Store(true)
return llm.Message{}, "", llm.Usage{}, errors.New("sealed followup gained execution context")
}
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("explanation")}}, "end_turn", llm.Usage{}, nil
}})
c, err := s.m.pg.GetConversation(*r.ConversationID)
if err != nil {
t.Fatal(err)
}
s.runConversationSync(c, "explain", s.convBusyKey(c.ID), nil)
if calls.Load() != 1 || sandboxSeen.Load() || len(stub.deletes) != 1 {
t.Fatalf("followup calls=%d cleanup=%v", calls.Load(), stub.deletes)
}
}
+9 -8
View File
@@ -16,6 +16,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/evidence"
"github.com/Autumn-27/artex/server/perm"
actool "github.com/Autumn-27/norma/tool"
)
@@ -79,15 +80,15 @@ WHERE key=$1 AND system AND NOT(COALESCE(schema->'properties','{}'::jsonb) ? $2)
_ = s.m.pg.SetSetting(flag, "true")
}
func (s *Server) registerFindingTraffic(mux *http.ServeMux) {
func (s *Server) registerFindingTraffic(mux *apiMux) {
base := "/api/exploration/findings/{id}/traffic"
mux.HandleFunc("GET "+base, s.getFindingTraffic)
mux.HandleFunc("POST "+base, s.bindFindingTraffic)
mux.HandleFunc("PATCH "+base+"/{binding_id}", s.editFindingTraffic)
mux.HandleFunc("DELETE "+base+"/{binding_id}", s.editFindingTraffic)
mux.HandleFunc("PUT "+base+"/order", s.editFindingTraffic)
mux.HandleFunc("GET "+base+"/{binding_id}", s.getFindingTrafficDetail)
mux.HandleFunc("GET "+base+"/{binding_id}/body", s.getFindingTrafficBody)
s.handle(mux, "GET "+base, perm.Authenticated, s.getFindingTraffic)
s.handle(mux, "POST "+base, perm.Authenticated, s.bindFindingTraffic)
s.handle(mux, "PATCH "+base+"/{binding_id}", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "DELETE "+base+"/{binding_id}", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "PUT "+base+"/order", perm.Authenticated, s.editFindingTraffic)
s.handle(mux, "GET "+base+"/{binding_id}", perm.Authenticated, s.getFindingTrafficDetail)
s.handle(mux, "GET "+base+"/{binding_id}/body", perm.Authenticated, s.getFindingTrafficBody)
}
func evidenceError(w http.ResponseWriter, err error) {
+5 -5
View File
@@ -7,7 +7,7 @@ import (
)
func TestValidateArgvRuleReq(t *testing.T) {
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["whois"]`, Action: "allow"}
if err := validateInterceptRuleReq(base); err != nil {
t.Fatalf("valid argv rule refused: %v", err)
}
@@ -15,8 +15,8 @@ func TestValidateArgvRuleReq(t *testing.T) {
"tool_name target": func(r *interceptRuleReq) { r.MatchTarget = "tool_name" },
"empty pattern": func(r *interceptRuleReq) { r.Pattern = "" },
"empty token": func(r *interceptRuleReq) { r.Pattern = `["git",""]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["nmap","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["nmap;id"]` },
"flag token": func(r *interceptRuleReq) { r.Pattern = `["whois","-C"]` },
"metacharacter": func(r *interceptRuleReq) { r.Pattern = `["whois;id"]` },
"nine tokens": func(r *interceptRuleReq) { r.Pattern = `["a","b","c","d","e","f","g","h","i"]` },
"not an array": func(r *interceptRuleReq) { r.Pattern = `git push` },
} {
@@ -31,7 +31,7 @@ func TestValidateArgvRuleReq(t *testing.T) {
// The manual rule form refuses an argv allow rule for a denylisted program,
// with the message of the "always allow" endpoint; deny and ask stay creatable.
func TestValidateArgvAllowDenylist(t *testing.T) {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`} {
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`, `["nmap"]`, `["sqlmap"]`, `["sqlite3"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
tokens, _ := intercept.ParseArgvPattern(pattern)
want := intercept.CheckArgvAllow(tokens)
@@ -45,7 +45,7 @@ func TestValidateArgvAllowDenylist(t *testing.T) {
}
}
}
for _, pattern := range []string{`["nmap"]`, `["curl"]`} {
for _, pattern := range []string{`["whois"]`, `["curl"]`} {
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
if err := validateInterceptRuleReq(req); err != nil {
t.Errorf("allow %s refused: %v", pattern, err)
+13 -6
View File
@@ -121,11 +121,12 @@ func logDegradedBanner(cause error, escaped bool) {
}
}
// SecurityPostureCheck describes startup posture warnings for target gating and egress enforcement.
// SecurityPostureCheck describes the startup snapshot for target approvals and egress enforcement.
type SecurityPostureCheck struct {
EgressMode string
UngatedActiveTasks int
TargetGateOptedOut bool
EgressMode string
UngatedActiveTasks int
TargetGateOptedOut bool
TargetGatePostureUnavailable bool
}
// SecurityStartupWarnings builds loud operator warnings when egress enforcement
@@ -141,14 +142,20 @@ func SecurityStartupWarnings(c SecurityPostureCheck) []string {
fmt.Sprintf("EGRESS ENFORCEMENT IS OFF (EGRESS_MODE=%s): outbound connections from agent commands are not restricted by egress-guard. Enable docker-compose.egress.yml with EGRESS_MODE=enforce and populate egress-guard/lists/scope-domains.txt.", mode),
)
}
if c.TargetGatePostureUnavailable {
warnings = append(warnings,
"TARGET GATE STATUS UNKNOWN AT STARTUP: the task posture could not be read. Review task settings after database access is restored.",
)
return warnings
}
if c.TargetGateOptedOut {
warnings = append(warnings,
"TARGET GATE IS OFF BY OPT-OUT: agent commands may contact unapproved hosts without operator confirmation.",
"TARGET GATE IS OFF BY EXPLICIT OPT-OUT AT STARTUP: one or more unfinished tasks do not require approval for declared targets. Other network controls apply separately.",
)
}
if c.UngatedActiveTasks > 0 {
warnings = append(warnings,
fmt.Sprintf("TARGET GATE IS OFF ON %d ACTIVE TASK(S): those tasks can contact arbitrary hosts without target-gate approval. Enable target_gate on scoped tasks.", c.UngatedActiveTasks),
fmt.Sprintf("TARGET GATE IS OFF ON %d UNFINISHED TASK(S) AT STARTUP: declared targets for these tasks do not require target-gate approval. Other network controls apply separately.", c.UngatedActiveTasks),
)
}
return warnings
+10
View File
@@ -25,6 +25,7 @@ import (
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/guard"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/sandbox"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/artex/traffic/rewrite"
actool "github.com/Autumn-27/norma/tool"
@@ -582,6 +583,15 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
}
}
m.enrich = enrich.New(m.assets, m.ProxyAddr, 4)
// Panel-side asset probes are agent-triggered: while the sandbox is required,
// they leave through the task's sandbox egress policy, as WebFetch and custom
// HTTP tools do, instead of the recording proxy that has no destination check.
m.enrich.SetSandboxPolicy(func(ctx context.Context) *sandbox.EgressPolicy {
if !agent.SandboxRequired() {
return nil
}
return agent.SandboxEgressPolicy(ctx)
})
// Reconcile the seeded browser MCP with the persisted capture state, so a
// restart with capture already on keeps Playwright routed through the proxy.
m.syncBrowserMCPProxy()
+11 -1
View File
@@ -86,9 +86,19 @@ func TestSecurityStartupWarnings(t *testing.T) {
out := captureLog(t, func() {
LogSecurityStartupWarnings(SecurityPostureCheck{EgressMode: "monitor", UngatedActiveTasks: 2, TargetGateOptedOut: true})
})
for _, want := range []string{"SECURITY POSTURE WARNING", "EGRESS ENFORCEMENT IS OFF", "EGRESS_MODE=monitor", "TARGET GATE IS OFF ON 2 ACTIVE TASK(S)", "TARGET GATE IS OFF BY OPT-OUT"} {
for _, want := range []string{"SECURITY POSTURE WARNING", "EGRESS ENFORCEMENT IS OFF", "EGRESS_MODE=monitor", "TARGET GATE IS OFF ON 2 UNFINISHED TASK(S) AT STARTUP", "TARGET GATE IS OFF BY EXPLICIT OPT-OUT AT STARTUP"} {
if !strings.Contains(out, want) {
t.Errorf("startup warning output missing %q:\n%s", want, out)
}
}
if strings.Contains(out, "arbitrary hosts") {
t.Errorf("target-gate warning overstates network access under sandbox egress:\n%s", out)
}
unknown := SecurityStartupWarnings(SecurityPostureCheck{
EgressMode: "enforce",
TargetGatePostureUnavailable: true,
})
if len(unknown) != 1 || !strings.Contains(unknown[0], "STATUS UNKNOWN AT STARTUP") {
t.Fatalf("failed posture read must report unknown, not zero: %v", unknown)
}
}
+27
View File
@@ -0,0 +1,27 @@
// Package perm lists the permissions an API route can require.
//
// Every route is registered with one of them (Server.handle). For now there
// are only two: Public routes answer without a session, Authenticated routes
// need a valid session. Finer permissions come with user accounts and roles.
package perm
// Perm is the permission a route needs. The zero value means "not set", and
// a route without a permission is denied.
type Perm uint8
const (
// Public routes are served without a session (sign-in, health, ready).
Public Perm = iota + 1
// Authenticated routes need a valid session.
Authenticated
)
func (p Perm) String() string {
switch p {
case Public:
return "public"
case Authenticated:
return "authenticated"
}
return "none"
}
+157
View File
@@ -0,0 +1,157 @@
package server
import (
"database/sql"
"errors"
"log"
"net/http"
"time"
"github.com/Autumn-27/artex/db"
)
// --- proxy pool (#545) ---
//
// Stored candidates for the global egress proxy. Operator API only, never an
// agent tool. This layer stores entries; nothing activates one yet, so the
// global proxy is unaffected by every call here.
//
// An address is never returned: reads give maskedSecret and address_set. On
// update, an address that is absent or masked keeps the stored one.
type proxyPoolDTO struct {
ID int64 `json:"id"`
Label string `json:"label"`
Address string `json:"address"` // maskedSecret, never the address
AddressSet bool `json:"address_set"`
Enabled bool `json:"enabled"`
Active bool `json:"active"`
EgressIP *string `json:"egress_ip"` // null: never checked
LastCheckAt *time.Time `json:"last_check_at"` // null: never checked
LastCheckOK *bool `json:"last_check_ok"` // null: never checked
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func proxyPoolEntryDTO(e db.ProxyPoolEntry) proxyPoolDTO {
return proxyPoolDTO{ID: e.ID, Label: e.Label, Address: maskedSecret(e.Address), AddressSet: e.Address != "",
Enabled: e.Enabled, Active: e.Active, EgressIP: e.EgressIP, LastCheckAt: e.LastCheckAt, LastCheckOK: e.LastCheckOK,
CreatedAt: e.CreatedAt, UpdatedAt: e.UpdatedAt}
}
type proxyPoolCreateReq struct {
Label string `json:"label"`
Address string `json:"address"`
Enabled *bool `json:"enabled"` // default true
}
type proxyPoolPatchReq struct {
Label *string `json:"label"`
Address *string `json:"address"` // null or masked: keep
Enabled *bool `json:"enabled"`
}
// proxyPoolWriteErr answers a failed entry write.
func proxyPoolWriteErr(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, sql.ErrNoRows):
writeErr(w, 404, "proxy pool entry not found")
case errors.Is(err, db.ErrProxyPoolInvalid), errors.Is(err, db.ErrProxyPoolLimit):
writeErr(w, 400, err.Error())
case errors.Is(err, db.ErrProxyPoolDuplicate), errors.Is(err, db.ErrProxyPoolActive):
writeErr(w, 409, err.Error())
default:
proxyPoolStoreErr(w, err)
}
}
// proxyPoolStoreErr answers an unexpected store error with a fixed message:
// this API handles proxy credentials, so no store detail reaches the client.
// The log gets the error, which never carries an address: addresses reach
// the database sealed, and constraint errors name only the column.
func proxyPoolStoreErr(w http.ResponseWriter, err error) {
log.Printf("[proxy-pool] store error: %v", err)
writeErr(w, 500, "proxy pool store error")
}
func (s *Server) proxyPoolList(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
entries, err := pg.ListProxyPool()
if err != nil {
proxyPoolStoreErr(w, err)
return
}
out := make([]proxyPoolDTO, 0, len(entries))
for _, e := range entries {
out = append(out, proxyPoolEntryDTO(e))
}
writeJSON(w, 200, map[string]any{"entries": out})
}
// proxyPoolCreate stores a new entry, never active: creating an entry does not
// change the global proxy.
func (s *Server) proxyPoolCreate(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
var req proxyPoolCreateReq
if err := decode(w, r, &req); err != nil {
writeErr(w, 400, err.Error())
return
}
if isMaskedSecret(req.Address) {
writeErr(w, 400, "send the proxy address: nothing is stored for a new entry")
return
}
enabled := req.Enabled == nil || *req.Enabled
e, err := pg.CreateProxyPoolEntry(req.Label, req.Address, enabled)
if err != nil {
proxyPoolWriteErr(w, err)
return
}
writeJSON(w, 200, proxyPoolEntryDTO(e))
}
func (s *Server) proxyPoolUpdate(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, ok := pathInt(r, "id")
if !ok {
writeErr(w, 400, "bad proxy pool entry id")
return
}
var req proxyPoolPatchReq
if err := decode(w, r, &req); err != nil {
writeErr(w, 400, err.Error())
return
}
e, err := pg.UpdateProxyPoolEntry(id, db.ProxyPoolEdit{Label: req.Label, Address: keepIfMasked(req.Address), Enabled: req.Enabled})
if err != nil {
proxyPoolWriteErr(w, err)
return
}
writeJSON(w, 200, proxyPoolEntryDTO(e))
}
func (s *Server) proxyPoolDelete(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, ok := pathInt(r, "id")
if !ok {
writeErr(w, 400, "bad proxy pool entry id")
return
}
if err := pg.DeleteProxyPoolEntry(id); err != nil {
proxyPoolWriteErr(w, err)
return
}
writeJSON(w, 200, map[string]any{"deleted": id})
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"net/http"
"github.com/Autumn-27/artex/server/perm"
)
// apiMux is the /api/ mux plus the permission recorded for each pattern.
// Routes are added with Server.handle. requirePerm applies the recorded
// permission and denies a pattern that has none, so a route added with a
// plain HandleFunc call answers 403 instead of being served.
type apiMux struct {
*http.ServeMux
perms map[string]perm.Perm
}
func newAPIMux() *apiMux {
return &apiMux{ServeMux: http.NewServeMux(), perms: map[string]perm.Perm{}}
}
// handle registers h for pattern and records the permission it needs.
func (s *Server) handle(mux *apiMux, pattern string, p perm.Perm, h http.HandlerFunc) {
if p == 0 {
panic("server: route " + pattern + " registered without a permission")
}
mux.perms[pattern] = p
mux.HandleFunc(pattern, h)
}
// requirePerm runs after requireAuth and applies the permission recorded for
// the pattern that would serve the request:
// - no recorded permission: 403, so a route added with a plain HandleFunc
// call is denied instead of served;
// - perm.Authenticated: 401 without a valid session. requireAuth exempts
// paths by prefix (/api/auth/...), and a wildcard pattern such as
// "GET /api/{kind}/items" also matches /api/auth/items; this check keeps
// such a route behind a session.
//
// Requests that match no pattern (404, 405) go to the mux unchanged.
func (s *Server) requirePerm(mux *apiMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, pattern := mux.Handler(r); pattern != "" {
switch p := mux.perms[pattern]; p {
case perm.Public:
case perm.Authenticated:
if !s.sessionOK(extractToken(r)) {
writeErr(w, 401, "Unauthorized")
return
}
default:
writeErr(w, 403, "Forbidden")
return
}
}
mux.ServeHTTP(w, r)
})
}
+235
View File
@@ -0,0 +1,235 @@
package server
import (
"go/ast"
"go/parser"
"go/token"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/server/perm"
)
// The routes requireAuth serves without a session. They must be exactly the
// routes tagged perm.Public.
var wantPublicRoutes = []string{
"GET /api/auth/status",
"POST /api/auth/init",
"POST /api/auth/login",
"POST /api/auth/change-password",
"GET /api/health",
"GET /api/ready",
}
// Every API route is registered with a permission, and the public ones are
// exactly the routes requireAuth exempts.
func TestEveryRouteHasPermission(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
mux := s.apiRoutes()
if len(mux.perms) < 250 {
t.Fatalf("only %d routes recorded; the route table looks incomplete", len(mux.perms))
}
var public []string
for pattern, p := range mux.perms {
switch p {
case perm.Public:
public = append(public, pattern)
case perm.Authenticated:
default:
t.Errorf("%s: unknown permission %v", pattern, p)
}
}
slices.Sort(public)
want := slices.Clone(wantPublicRoutes)
slices.Sort(want)
if !slices.Equal(public, want) {
t.Errorf("public routes = %v, want %v", public, want)
}
// requireAuth without a token: a route is served only if it is public.
wildcard := regexp.MustCompile(`\{[^}]*\}`)
h := s.requireAuth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }))
for pattern, p := range mux.perms {
method, path, ok := strings.Cut(pattern, " ")
if !ok {
t.Errorf("%s: pattern has no method", pattern)
continue
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, wildcard.ReplaceAllString(path, "x"), nil))
if exempt := rec.Code == 204; exempt != (p == perm.Public) {
t.Errorf("%s: requireAuth exempt=%v, but permission is %v", pattern, exempt, p)
}
}
}
// No file in the package registers an API route without Server.handle. The
// only allowed direct calls are the one inside handle and the two root mux
// routes that split /api/ from the web UI: root.Handle("/api/", ...) and
// root.HandleFunc("/", ...). Any other root route, such as
// root.HandleFunc("GET /api/leak", ...), would skip requireAuth.
func TestNoRawRouteRegistration(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, name := range files {
if strings.HasSuffix(name, "_test.go") {
continue
}
src, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
f, err := parser.ParseFile(fset, name, src, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok || (sel.Sel.Name != "HandleFunc" && sel.Sel.Name != "Handle") {
return true
}
recv, _ := sel.X.(*ast.Ident)
switch {
case name == "routes.go" && recv != nil && recv.Name == "mux":
case name == "server.go" && recv != nil && recv.Name == "root" && rootRouteAllowed(sel.Sel.Name, call):
default:
t.Errorf("%s: raw %s call; register API routes with s.handle", fset.Position(call.Pos()), sel.Sel.Name)
}
return true
})
}
}
// rootRouteAllowed reports whether a root mux call registers one of the two
// allowed patterns.
func rootRouteAllowed(method string, call *ast.CallExpr) bool {
if len(call.Args) == 0 {
return false
}
lit, ok := call.Args[0].(*ast.BasicLit)
if !ok || lit.Kind != token.STRING {
return false
}
pattern, err := strconv.Unquote(lit.Value)
if err != nil {
return false
}
return (method == "Handle" && pattern == "/api/") || (method == "HandleFunc" && pattern == "/")
}
// The real handler answers 401 without a session for every authenticated
// route, so the permission check is part of the production chain.
func TestHandlerDeniesAuthenticatedRoutesWithoutSession(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
h := s.Handler()
wildcard := regexp.MustCompile(`\{[^}]*\}`)
for pattern, p := range s.apiRoutes().perms {
if p != perm.Authenticated {
continue
}
method, path, _ := strings.Cut(pattern, " ")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, wildcard.ReplaceAllString(path, "x"), nil))
if rec.Code != 401 {
t.Errorf("%s without a session: status %d, want 401", pattern, rec.Code)
}
}
}
// A route added to the mux without a permission is denied with 403, even
// with a valid session, and an authenticated route needs a session even when
// its path falls under the /api/auth/ prefix that requireAuth exempts.
// Unknown paths and methods behave as before. The routes go through
// handlerFor, the same chain Handler builds.
func TestUntaggedRouteIsForbidden(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
tok, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
mux := newAPIMux()
s.handle(mux, "GET /api/tagged", perm.Authenticated, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
s.handle(mux, "GET /api/auth/open", perm.Public, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
reached := false
mux.HandleFunc("GET /api/untagged/{id}", func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.WriteHeader(204)
})
mux.HandleFunc("GET /api/auth/untagged", func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.WriteHeader(204)
})
wildcardReached := false
s.handle(mux, "GET /api/{kind}/items/list", perm.Authenticated, func(w http.ResponseWriter, _ *http.Request) {
wildcardReached = true
w.WriteHeader(204)
})
h := s.handlerFor(mux)
for _, tc := range []struct {
method, path string
bearer bool
want int
}{
{"GET", "/api/tagged", true, 204},
{"GET", "/api/tagged", false, 401},
{"GET", "/api/auth/open", false, 204},
{"GET", "/api/untagged/1", true, 403},
{"GET", "/api/untagged/1", false, 401},
{"GET", "/api/auth/untagged", false, 403},
{"GET", "/api/missing", true, 404},
{"POST", "/api/tagged", true, 405},
{"GET", "/api//tagged", true, 307}, // the mux's own path clean-up redirect, as before
} {
reached = false
r := httptest.NewRequest(tc.method, tc.path, nil)
if tc.bearer {
r.Header.Set("Authorization", "Bearer "+tok)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != tc.want || reached {
t.Errorf("%s %s bearer=%v: status=%d reached=%v, want %d", tc.method, tc.path, tc.bearer, rec.Code, reached, tc.want)
}
}
// "GET /api/{kind}/items/list" matches /api/auth/items/list, which requireAuth
// exempts by prefix. The recorded permission still requires a session.
for _, tc := range []struct {
bearer bool
want int
}{{false, 401}, {true, 204}} {
wildcardReached = false
r := httptest.NewRequest("GET", "/api/auth/items/list", nil)
if tc.bearer {
r.Header.Set("Authorization", "Bearer "+tok)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != tc.want || wildcardReached != tc.bearer {
t.Errorf("GET /api/auth/items/list bearer=%v: status=%d reached=%v, want %d", tc.bearer, rec.Code, wildcardReached, tc.want)
}
}
}
func TestHandleWithoutPermissionPanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("handle with a zero permission did not panic")
}
}()
(&Server{}).handle(newAPIMux(), "GET /api/x", 0, func(http.ResponseWriter, *http.Request) {})
}
+109
View File
@@ -3,11 +3,14 @@ package server
import (
"context"
"encoding/json"
"errors"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/traffic"
)
// No read endpoint returns a stored secret in clear, and a masked placeholder
@@ -265,3 +268,109 @@ func TestProxySecretsAPI(t *testing.T) {
t.Fatalf("a placeholder on a new profile must be refused, got HTTP %d", resp.Code)
}
}
// The proxy pool API never returns an address in clear, a masked address sent
// back keeps the stored one, and no pool call changes the global proxy.
func TestProxyPoolAPINeverReturnsAddress(t *testing.T) {
s, _, request := trafficEvidenceServer(t)
pg := s.m.PG()
clean := func() { pg.Exec(`DELETE FROM proxy_pool WHERE label LIKE 't-ppapi-%'`) }
clean()
t.Cleanup(clean)
const secret = "ppapi-plain-pass-0001"
globalBefore := s.m.GlobalProxy()
resp := request("POST", "/api/proxy-pool", `{"label":"t-ppapi-one","address":"http://u:`+secret+`@pp.example:3128"}`)
if resp.Code != 200 || strings.Contains(resp.Body.String(), secret) || strings.Contains(resp.Body.String(), "pp.example") {
t.Fatalf("create: HTTP %d, or the address returned: %s", resp.Code, resp.Body.String())
}
var created proxyPoolDTO
if err := json.Unmarshal(resp.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
if created.Address != "__masked__" || !created.AddressSet || created.Active || !created.Enabled || created.EgressIP != nil {
t.Fatalf("created entry = %+v", created)
}
id := strconv.FormatInt(created.ID, 10)
if resp := request("GET", "/api/proxy-pool", ""); resp.Code != 200 || strings.Contains(resp.Body.String(), secret) || !strings.Contains(resp.Body.String(), `"egress_ip":null`) {
t.Fatalf("list: HTTP %d, or the address returned: %s", resp.Code, resp.Body.String())
}
// Echo the masked entry back with a new label: the address survives.
if resp := request("PATCH", "/api/proxy-pool/"+id, `{"label":"t-ppapi-renamed","address":"__masked__"}`); resp.Code != 200 || strings.Contains(resp.Body.String(), secret) {
t.Fatalf("masked update: HTTP %d %s", resp.Code, resp.Body.String())
}
if e, err := pg.GetProxyPoolEntry(created.ID); err != nil || e.Label != "t-ppapi-renamed" || !strings.Contains(e.Address, secret) {
t.Fatalf("a masked placeholder replaced the stored address (%v)", err)
}
for _, c := range []struct {
method, path, body string
want int
}{
{"POST", "/api/proxy-pool", `{"label":"t-ppapi-new","address":"__masked__"}`, 400},
{"POST", "/api/proxy-pool", `{"label":"t-ppapi-dup","address":"HTTP://u:` + secret + `@PP.example:3128/"}`, 409},
{"POST", "/api/proxy-pool", `{"label":"t-ppapi-bad","address":"pp.example:3128"}`, 400},
{"POST", "/api/proxy-pool", `{"label":"","address":"http://nolabel.example"}`, 400},
{"PATCH", "/api/proxy-pool/4611686018427387904", `{"label":"t-ppapi-ghost"}`, 404},
{"PATCH", "/api/proxy-pool/abc", `{"label":"t-ppapi-ghost"}`, 400},
{"DELETE", "/api/proxy-pool/4611686018427387904", "", 404},
} {
if resp := request(c.method, c.path, c.body); resp.Code != c.want || strings.Contains(resp.Body.String(), secret) {
t.Errorf("%s %s %s: HTTP %d, want %d (%s)", c.method, c.path, c.body, resp.Code, c.want, resp.Body.String())
}
}
// An entry created disabled stays disabled.
resp = request("POST", "/api/proxy-pool", `{"label":"t-ppapi-off","address":"http://off.example","enabled":false}`)
var off proxyPoolDTO
if resp.Code != 200 || json.Unmarshal(resp.Body.Bytes(), &off) != nil || off.Enabled {
t.Fatalf("create disabled: HTTP %d %s", resp.Code, resp.Body.String())
}
// The active entry cannot be disabled or deleted. Nothing activates one in
// this API yet, so the test sets the flag directly.
if _, err := pg.Exec(`UPDATE proxy_pool SET active=true WHERE id=$1`, created.ID); err != nil {
t.Fatal(err)
}
if resp := request("PATCH", "/api/proxy-pool/"+id, `{"enabled":false}`); resp.Code != 409 {
t.Fatalf("disable the active entry: HTTP %d %s", resp.Code, resp.Body.String())
}
if resp := request("DELETE", "/api/proxy-pool/"+id, ""); resp.Code != 409 {
t.Fatalf("delete the active entry: HTTP %d %s", resp.Code, resp.Body.String())
}
if _, err := pg.Exec(`UPDATE proxy_pool SET active=false WHERE id=$1`, created.ID); err != nil {
t.Fatal(err)
}
if resp := request("DELETE", "/api/proxy-pool/"+id, ""); resp.Code != 200 {
t.Fatalf("delete: HTTP %d %s", resp.Code, resp.Body.String())
}
if got := s.m.GlobalProxy(); got != globalBefore {
t.Fatal("a proxy pool call changed the global proxy")
}
}
// Every address the pool accepts is one the global proxy accepts, so
// activating an entry can never fail validation.
func TestProxyPoolAddressesAreValidGlobalProxies(t *testing.T) {
for _, in := range []string{"http://h.example", "HTTPS://u:p@H.example:8443/", "socks5://[2001:db8::1]", "socks5://u@10.0.0.1:9050"} {
norm, err := db.NormalizeProxyAddress(in)
if err != nil {
t.Fatalf("NormalizeProxyAddress(%q): %v", in, err)
}
if _, err := traffic.ValidateProxyURL(norm); err != nil {
t.Errorf("pool address %q is refused as a global proxy: %v", norm, err)
}
}
}
// An unexpected store error answers a fixed message, never the error's text.
func TestProxyPoolStoreErrorIsFixed(t *testing.T) {
rec := httptest.NewRecorder()
proxyPoolWriteErr(rec, errors.New("store failed near http://u:leak-pass@pp.example:3128"))
if rec.Code != 500 || strings.Contains(rec.Body.String(), "leak-pass") || !strings.Contains(rec.Body.String(), "proxy pool store error") {
t.Fatalf("HTTP %d %s", rec.Code, rec.Body.String())
}
}
+322 -291
View File
@@ -33,6 +33,7 @@ import (
"github.com/Autumn-27/artex/llmpool"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/artex/report"
"github.com/Autumn-27/artex/server/perm"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/norma/llm"
actool "github.com/Autumn-27/norma/tool"
@@ -127,6 +128,8 @@ type Server struct {
// cleared alongside chatBusy under chatMu. Aborting a run does NOT touch the P3
// trigger queue — the drain goroutine simply proceeds to the next queued fire.
chatCancel map[string]context.CancelCauseFunc
// Includes retest sandbox cleanup before shutdown.
conversationWG sync.WaitGroup
// triggerQ buffers P3 trigger fires PER AGENT. A per-agent "pump" launches runs up
// to a concurrency limit derived from the agent's policy: serial → limit 1 (+ optional
@@ -406,8 +409,8 @@ func (s *Server) restoreTaskRuntimes() {
}
}
// Wait blocks until the task goroutines snapshotted now, and the archive
// worker, have finished, or until ctx ends.
// Wait blocks until task and conversation runs (including sandbox cleanup),
// and the archive worker, have finished, or until ctx ends.
func (s *Server) Wait(ctx context.Context) error {
if s == nil {
return nil
@@ -419,6 +422,7 @@ func (s *Server) Wait(ctx context.Context) error {
}
done := make(chan struct{})
go func() {
s.conversationWG.Wait()
s.archiveWG.Wait()
close(done)
}()
@@ -802,339 +806,366 @@ func (s *Server) chatAgentRef() *agent.ChatAgent {
return s.chatAgent
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
// apiRoutes builds the /api/ mux with every API route and its permission.
func (s *Server) apiRoutes() *apiMux {
mux := newAPIMux()
s.registerSideRoutes(mux)
s.registerSharedBrowserRoutes(mux)
// Auth routes — exempt from JWT check (handled in requireAuth)
mux.HandleFunc("GET /api/auth/status", s.authStatus)
mux.HandleFunc("POST /api/auth/init", s.authInit)
mux.HandleFunc("POST /api/auth/login", s.authLogin)
mux.HandleFunc("POST /api/auth/change-password", s.authChangePassword)
s.handle(mux, "GET /api/auth/status", perm.Public, s.authStatus)
s.handle(mux, "POST /api/auth/init", perm.Public, s.authInit)
s.handle(mux, "POST /api/auth/login", perm.Public, s.authLogin)
s.handle(mux, "POST /api/auth/change-password", perm.Public, s.authChangePassword)
mux.HandleFunc("GET /api/health", s.health)
mux.HandleFunc("GET /api/ready", s.ready)
mux.HandleFunc("GET /api/stats", s.stats)
mux.HandleFunc("GET /api/logs", s.getLogs)
mux.HandleFunc("GET /api/logs/history", s.getLogsHistory)
mux.HandleFunc("GET /api/logs/stream", s.streamLogs)
s.handle(mux, "GET /api/health", perm.Public, s.health)
s.handle(mux, "GET /api/ready", perm.Public, s.ready)
s.handle(mux, "GET /api/stats", perm.Authenticated, s.stats)
s.handle(mux, "GET /api/logs", perm.Authenticated, s.getLogs)
s.handle(mux, "GET /api/logs/history", perm.Authenticated, s.getLogsHistory)
s.handle(mux, "GET /api/logs/stream", perm.Authenticated, s.streamLogs)
mux.HandleFunc("GET /api/tasks", s.listTasks)
mux.HandleFunc("POST /api/tasks", s.createTask)
mux.HandleFunc("GET /api/skill-gaps", s.skillGaps)
mux.HandleFunc("GET /api/task-categories", s.pgListTaskCategories)
mux.HandleFunc("POST /api/task-categories", s.pgCreateTaskCategory)
mux.HandleFunc("PATCH /api/task-categories/{id}", s.pgRenameTaskCategory)
mux.HandleFunc("DELETE /api/task-categories/{id}", s.pgDeleteTaskCategory)
mux.HandleFunc("POST /api/tasks/category/batch", s.updateTasksCategoryBatch)
mux.HandleFunc("GET /api/task-templates", s.pgListTaskTemplates)
mux.HandleFunc("POST /api/task-templates", s.pgCreateTaskTemplate)
mux.HandleFunc("PATCH /api/task-templates/{id}", s.pgUpdateTaskTemplate)
mux.HandleFunc("DELETE /api/task-templates/{id}", s.pgDeleteTaskTemplate)
mux.HandleFunc("GET /api/tasks/{id}", s.getTask)
mux.HandleFunc("GET /api/tasks/{id}/outcome", s.taskOutcome)
mux.HandleFunc("GET /api/tasks/{id}/lessons", s.taskLessons)
mux.HandleFunc("POST /api/tasks/{id}/lessons/extract", s.extractTaskLessons)
mux.HandleFunc("PATCH /api/tasks/{id}", s.updateTaskMetadata)
mux.HandleFunc("PATCH /api/tasks/{id}/category", s.updateTaskCategory)
s.handle(mux, "GET /api/tasks", perm.Authenticated, s.listTasks)
s.handle(mux, "POST /api/tasks", perm.Authenticated, s.createTask)
s.handle(mux, "GET /api/skill-gaps", perm.Authenticated, s.skillGaps)
s.handle(mux, "GET /api/task-categories", perm.Authenticated, s.pgListTaskCategories)
s.handle(mux, "POST /api/task-categories", perm.Authenticated, s.pgCreateTaskCategory)
s.handle(mux, "PATCH /api/task-categories/{id}", perm.Authenticated, s.pgRenameTaskCategory)
s.handle(mux, "DELETE /api/task-categories/{id}", perm.Authenticated, s.pgDeleteTaskCategory)
s.handle(mux, "POST /api/tasks/category/batch", perm.Authenticated, s.updateTasksCategoryBatch)
s.handle(mux, "GET /api/task-templates", perm.Authenticated, s.pgListTaskTemplates)
s.handle(mux, "POST /api/task-templates", perm.Authenticated, s.pgCreateTaskTemplate)
s.handle(mux, "PATCH /api/task-templates/{id}", perm.Authenticated, s.pgUpdateTaskTemplate)
s.handle(mux, "DELETE /api/task-templates/{id}", perm.Authenticated, s.pgDeleteTaskTemplate)
s.handle(mux, "GET /api/tasks/{id}", perm.Authenticated, s.getTask)
s.handle(mux, "GET /api/tasks/{id}/outcome", perm.Authenticated, s.taskOutcome)
s.handle(mux, "GET /api/tasks/{id}/lessons", perm.Authenticated, s.taskLessons)
s.handle(mux, "POST /api/tasks/{id}/lessons/extract", perm.Authenticated, s.extractTaskLessons)
s.handle(mux, "PATCH /api/tasks/{id}", perm.Authenticated, s.updateTaskMetadata)
s.handle(mux, "PATCH /api/tasks/{id}/category", perm.Authenticated, s.updateTaskCategory)
// task-level asset interception/allow rules
mux.HandleFunc("GET /api/tasks/{id}/intercept-rules", s.taskInterceptListRules)
mux.HandleFunc("POST /api/tasks/{id}/intercept-rules", s.taskInterceptCreateRule)
mux.HandleFunc("PUT /api/tasks/{id}/intercept-rules/{rid}", s.taskInterceptUpdateRule)
mux.HandleFunc("DELETE /api/tasks/{id}/intercept-rules/{rid}", s.taskInterceptDeleteRule)
mux.HandleFunc("POST /api/tasks/{id}/intercept-rules/{rid}/toggle", s.taskInterceptToggleRule)
mux.HandleFunc("GET /api/tasks/{id}/target-pins", s.taskListTargetPins)
mux.HandleFunc("POST /api/tasks/{id}/target-pins/{pid}/revoke", s.taskRevokeTargetPin)
mux.HandleFunc("POST /api/tasks/control/batch", s.controlTasksBatch)
mux.HandleFunc("GET /api/task-archives", s.listTaskArchives)
mux.HandleFunc("GET /api/task-archives/{id}", s.getTaskArchive)
mux.HandleFunc("GET /api/tasks/{id}/credentials", s.listTaskCredentials)
mux.HandleFunc("POST /api/tasks/{id}/credentials", s.addTaskCredential)
mux.HandleFunc("DELETE /api/tasks/{id}/credentials/{cid}", s.deleteTaskCredential)
mux.HandleFunc("POST /api/tasks/{id}/archive", s.queueTaskArchive)
mux.HandleFunc("POST /api/tasks/archive/batch", s.queueTaskArchivesBatch)
mux.HandleFunc("POST /api/task-archives/{id}/restore", s.queueTaskArchiveRestore)
mux.HandleFunc("POST /api/task-archives/restore/batch", s.restoreTaskArchivesBatch)
mux.HandleFunc("DELETE /api/task-archives/{id}", s.queueTaskArchiveDelete)
mux.HandleFunc("POST /api/task-archives/delete/batch", s.deleteTaskArchivesBatch)
mux.HandleFunc("GET /api/tasks/{id}/coverage", s.taskCoverage)
mux.HandleFunc("GET /api/tasks/{id}/coverage-graph", s.taskCoverageGraph)
mux.HandleFunc("GET /api/tasks/{id}/asset-refs", s.taskAssetRefs)
mux.HandleFunc("POST /api/tasks/{id}/assets", s.attachTaskAssets)
mux.HandleFunc("DELETE /api/tasks/{id}/assets/{assetID}", s.detachTaskAsset)
mux.HandleFunc("GET /api/tasks/{id}/intent-assets", s.taskIntentAssets)
s.handle(mux, "GET /api/tasks/{id}/intercept-rules", perm.Authenticated, s.taskInterceptListRules)
s.handle(mux, "POST /api/tasks/{id}/intercept-rules", perm.Authenticated, s.taskInterceptCreateRule)
s.handle(mux, "PUT /api/tasks/{id}/intercept-rules/{rid}", perm.Authenticated, s.taskInterceptUpdateRule)
s.handle(mux, "DELETE /api/tasks/{id}/intercept-rules/{rid}", perm.Authenticated, s.taskInterceptDeleteRule)
s.handle(mux, "POST /api/tasks/{id}/intercept-rules/{rid}/toggle", perm.Authenticated, s.taskInterceptToggleRule)
s.handle(mux, "GET /api/tasks/{id}/target-pins", perm.Authenticated, s.taskListTargetPins)
s.handle(mux, "POST /api/tasks/{id}/target-pins/{pid}/revoke", perm.Authenticated, s.taskRevokeTargetPin)
s.handle(mux, "POST /api/tasks/control/batch", perm.Authenticated, s.controlTasksBatch)
s.handle(mux, "GET /api/task-archives", perm.Authenticated, s.listTaskArchives)
s.handle(mux, "GET /api/task-archives/{id}", perm.Authenticated, s.getTaskArchive)
s.handle(mux, "GET /api/tasks/{id}/credentials", perm.Authenticated, s.listTaskCredentials)
s.handle(mux, "POST /api/tasks/{id}/credentials", perm.Authenticated, s.addTaskCredential)
s.handle(mux, "DELETE /api/tasks/{id}/credentials/{cid}", perm.Authenticated, s.deleteTaskCredential)
s.handle(mux, "POST /api/tasks/{id}/archive", perm.Authenticated, s.queueTaskArchive)
s.handle(mux, "POST /api/tasks/archive/batch", perm.Authenticated, s.queueTaskArchivesBatch)
s.handle(mux, "POST /api/task-archives/{id}/restore", perm.Authenticated, s.queueTaskArchiveRestore)
s.handle(mux, "POST /api/task-archives/restore/batch", perm.Authenticated, s.restoreTaskArchivesBatch)
s.handle(mux, "DELETE /api/task-archives/{id}", perm.Authenticated, s.queueTaskArchiveDelete)
s.handle(mux, "POST /api/task-archives/delete/batch", perm.Authenticated, s.deleteTaskArchivesBatch)
s.handle(mux, "GET /api/tasks/{id}/coverage", perm.Authenticated, s.taskCoverage)
s.handle(mux, "GET /api/tasks/{id}/coverage-graph", perm.Authenticated, s.taskCoverageGraph)
s.handle(mux, "GET /api/tasks/{id}/asset-refs", perm.Authenticated, s.taskAssetRefs)
s.handle(mux, "POST /api/tasks/{id}/assets", perm.Authenticated, s.attachTaskAssets)
s.handle(mux, "DELETE /api/tasks/{id}/assets/{assetID}", perm.Authenticated, s.detachTaskAsset)
s.handle(mux, "GET /api/tasks/{id}/intent-assets", perm.Authenticated, s.taskIntentAssets)
// workspace file manager (over workDir)
mux.HandleFunc("GET /api/workspace/list", s.wsList)
mux.HandleFunc("GET /api/workspace/read", s.wsRead)
mux.HandleFunc("POST /api/workspace/write", s.wsWrite)
mux.HandleFunc("POST /api/workspace/mkdir", s.wsMkdir)
mux.HandleFunc("DELETE /api/workspace/delete", s.wsDelete)
mux.HandleFunc("GET /api/workspace/download", s.wsDownload)
mux.HandleFunc("POST /api/workspace/upload", s.wsUpload)
mux.HandleFunc("GET /api/tasks/{id}/scope", s.taskScopeList)
mux.HandleFunc("POST /api/tasks/{id}/scope", s.taskScopeAdd)
mux.HandleFunc("DELETE /api/tasks/{id}/scope/{sid}", s.taskScopeDelete)
mux.HandleFunc("GET /api/tasks/{id}/goals", s.listGoals) // goal management: list all goals of this task
mux.HandleFunc("POST /api/tasks/{id}/goals", s.addGoal) // goal management: human-added goal (revives the task)
mux.HandleFunc("PATCH /api/tasks/{id}/goals/{gid}", s.editGoal) // goal management: edit a goal (revives the task)
mux.HandleFunc("DELETE /api/tasks/{id}/goals/{gid}", s.deleteGoal) // goal management: hard-delete a goal (no revival)
mux.HandleFunc("GET /api/tasks/{id}/constraints", s.listConstraints) // constraint management: list this task's operation constraints
mux.HandleFunc("POST /api/tasks/{id}/constraints", s.addConstraint) // constraint management: add a constraint (planner not notified)
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // constraint management: edit a constraint
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // constraint management: delete a constraint
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
mux.HandleFunc("POST /api/tasks/{id}/retarget", s.retargetTaskHandler)
mux.HandleFunc("POST /api/tasks/{id}/extend", s.extendTaskHandler)
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/messages", s.sendWorkerMessage)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/rerun", s.rerunIntent) // rerun one blocked/exhausted/stopped intent
mux.HandleFunc("POST /api/tasks/{id}/intents/rerun-blocked", s.rerunBlocked) // batch-rerun all blocked intents of this task
mux.HandleFunc("POST /api/active", s.setActive)
s.handle(mux, "GET /api/workspace/list", perm.Authenticated, s.wsList)
s.handle(mux, "GET /api/workspace/read", perm.Authenticated, s.wsRead)
s.handle(mux, "POST /api/workspace/write", perm.Authenticated, s.wsWrite)
s.handle(mux, "POST /api/workspace/mkdir", perm.Authenticated, s.wsMkdir)
s.handle(mux, "DELETE /api/workspace/delete", perm.Authenticated, s.wsDelete)
s.handle(mux, "GET /api/workspace/download", perm.Authenticated, s.wsDownload)
s.handle(mux, "POST /api/workspace/upload", perm.Authenticated, s.wsUpload)
s.handle(mux, "GET /api/tasks/{id}/scope", perm.Authenticated, s.taskScopeList)
s.handle(mux, "POST /api/tasks/{id}/scope", perm.Authenticated, s.taskScopeAdd)
s.handle(mux, "DELETE /api/tasks/{id}/scope/{sid}", perm.Authenticated, s.taskScopeDelete)
s.handle(mux, "GET /api/tasks/{id}/goals", perm.Authenticated, s.listGoals) // goal management: list all goals of this task
s.handle(mux, "POST /api/tasks/{id}/goals", perm.Authenticated, s.addGoal) // goal management: human-added goal (revives the task)
s.handle(mux, "PATCH /api/tasks/{id}/goals/{gid}", perm.Authenticated, s.editGoal) // goal management: edit a goal (revives the task)
s.handle(mux, "DELETE /api/tasks/{id}/goals/{gid}", perm.Authenticated, s.deleteGoal) // goal management: hard-delete a goal (no revival)
s.handle(mux, "GET /api/tasks/{id}/constraints", perm.Authenticated, s.listConstraints) // constraint management: list this task's operation constraints
s.handle(mux, "POST /api/tasks/{id}/constraints", perm.Authenticated, s.addConstraint) // constraint management: add a constraint (planner not notified)
s.handle(mux, "PATCH /api/tasks/{id}/constraints/{cid}", perm.Authenticated, s.editConstraint) // constraint management: edit a constraint
s.handle(mux, "DELETE /api/tasks/{id}/constraints/{cid}", perm.Authenticated, s.deleteConstraint) // constraint management: delete a constraint
s.handle(mux, "POST /api/tasks/{id}/control", perm.Authenticated, s.control)
s.handle(mux, "POST /api/tasks/{id}/retarget", perm.Authenticated, s.retargetTaskHandler)
s.handle(mux, "POST /api/tasks/{id}/extend", perm.Authenticated, s.extendTaskHandler)
s.handle(mux, "PUT /api/tasks/{id}/llm", perm.Authenticated, s.updateTaskLLMProfiles)
s.handle(mux, "GET /api/tasks/{id}/llm/resolution", perm.Authenticated, s.taskLLMResolutionHandler)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/control", perm.Authenticated, s.controlIntent)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/messages", perm.Authenticated, s.sendWorkerMessage)
s.handle(mux, "POST /api/tasks/{id}/intents/{iid}/rerun", perm.Authenticated, s.rerunIntent) // rerun one blocked/exhausted/stopped intent
s.handle(mux, "POST /api/tasks/{id}/intents/rerun-blocked", perm.Authenticated, s.rerunBlocked) // batch-rerun all blocked intents of this task
s.handle(mux, "POST /api/active", perm.Authenticated, s.setActive)
mux.HandleFunc("GET /api/llm", s.getLLM)
mux.HandleFunc("POST /api/llm", s.setLLM)
mux.HandleFunc("POST /api/llm/test", s.testLLM)
s.handle(mux, "GET /api/llm", perm.Authenticated, s.getLLM)
s.handle(mux, "POST /api/llm", perm.Authenticated, s.setLLM)
s.handle(mux, "POST /api/llm/test", perm.Authenticated, s.testLLM)
// asset system
mux.HandleFunc("GET /api/assets", s.listAssets)
mux.HandleFunc("GET /api/assets/counts", s.assetCounts)
mux.HandleFunc("POST /api/assets", s.insertAssets)
mux.HandleFunc("DELETE /api/assets", s.deleteAssets)
s.handle(mux, "GET /api/assets", perm.Authenticated, s.listAssets)
s.handle(mux, "GET /api/assets/counts", perm.Authenticated, s.assetCounts)
s.handle(mux, "POST /api/assets", perm.Authenticated, s.insertAssets)
s.handle(mux, "DELETE /api/assets", perm.Authenticated, s.deleteAssets)
// company system
mux.HandleFunc("GET /api/companies", s.listCompanies)
mux.HandleFunc("POST /api/companies", s.createCompany)
mux.HandleFunc("GET /api/companies/{id}", s.getCompany)
mux.HandleFunc("DELETE /api/companies/{id}", s.deleteCompany)
mux.HandleFunc("POST /api/companies/{id}/scope", s.addCompanyScope)
mux.HandleFunc("POST /api/companies/reattribute", s.reattribute)
s.handle(mux, "GET /api/companies", perm.Authenticated, s.listCompanies)
s.handle(mux, "POST /api/companies", perm.Authenticated, s.createCompany)
s.handle(mux, "GET /api/companies/{id}", perm.Authenticated, s.getCompany)
s.handle(mux, "DELETE /api/companies/{id}", perm.Authenticated, s.deleteCompany)
s.handle(mux, "POST /api/companies/{id}/scope", perm.Authenticated, s.addCompanyScope)
s.handle(mux, "POST /api/companies/reattribute", perm.Authenticated, s.reattribute)
mux.HandleFunc("GET /api/exploration/frontier", s.frontier)
mux.HandleFunc("GET /api/exploration/findings", s.findings)
mux.HandleFunc("GET /api/exploration/findings/groups", s.findingGroups)
mux.HandleFunc("GET /api/exploration/findings/asset-tree", s.findingAssetTree)
mux.HandleFunc("GET /api/exploration/findings/stats", s.findingStats)
mux.HandleFunc("GET /api/exploration/findings/export", s.findingsExport)
s.handle(mux, "GET /api/exploration/frontier", perm.Authenticated, s.frontier)
s.handle(mux, "GET /api/exploration/findings", perm.Authenticated, s.findings)
s.handle(mux, "GET /api/exploration/findings/groups", perm.Authenticated, s.findingGroups)
s.handle(mux, "GET /api/exploration/findings/asset-tree", perm.Authenticated, s.findingAssetTree)
s.handle(mux, "GET /api/exploration/findings/stats", perm.Authenticated, s.findingStats)
s.handle(mux, "GET /api/exploration/findings/export", perm.Authenticated, s.findingsExport)
s.registerFindingTraffic(mux)
mux.HandleFunc("GET /api/exploration/findings/{id}", s.getFinding)
mux.HandleFunc("GET /api/exploration/findings/{id}/lineage", s.findingLineage)
mux.HandleFunc("POST /api/exploration/findings/{id}/deepen", s.deepenFinding)
mux.HandleFunc("GET /api/exploration/findings/{id}/retests", s.listFindingRetests)
mux.HandleFunc("GET /api/exploration/findings/retests/active", s.listActiveFindingRetests)
mux.HandleFunc("POST /api/exploration/findings/{id}/retests", s.startFindingRetest)
mux.HandleFunc("PATCH /api/exploration/findings/{id}", s.patchFinding)
mux.HandleFunc("POST /api/exploration/findings/bulk-status", s.bulkPatchFindingStatus)
mux.HandleFunc("POST /api/exploration/findings/bulk-report-state", s.bulkPatchFindingReportState)
mux.HandleFunc("DELETE /api/exploration/findings/{id}", s.deleteFinding)
mux.HandleFunc("GET /api/exploration/intents", s.intents)
mux.HandleFunc("GET /api/exploration/graph", s.explorationGraph)
mux.HandleFunc("GET /api/exploration/nodes", s.explorationNodes)
mux.HandleFunc("GET /api/exploration/activity", s.activity)
mux.HandleFunc("GET /api/exploration/activity/history", s.activityHistory)
mux.HandleFunc("GET /api/exploration/main-sessions", s.mainSessions)
mux.HandleFunc("POST /api/exploration/main-session/new", s.newMainSession)
mux.HandleFunc("GET /api/exploration/activity/stream", s.streamActivity)
mux.HandleFunc("GET /api/exploration/activity/{seq}", s.activityDetail)
mux.HandleFunc("GET /api/exploration/tokens", s.tokenStats)
mux.HandleFunc("GET /api/tokens/daily", s.tokenDailyStats)
mux.HandleFunc("GET /api/tokens/conversations", s.conversationTokens)
mux.HandleFunc("GET /api/tokens/usage", s.pgUsageStats) // global llm_usage aggregation (new dashboard view)
s.handle(mux, "GET /api/exploration/findings/{id}", perm.Authenticated, s.getFinding)
s.handle(mux, "GET /api/exploration/findings/{id}/lineage", perm.Authenticated, s.findingLineage)
s.handle(mux, "POST /api/exploration/findings/{id}/deepen", perm.Authenticated, s.deepenFinding)
s.handle(mux, "GET /api/exploration/findings/{id}/retests", perm.Authenticated, s.listFindingRetests)
s.handle(mux, "GET /api/exploration/findings/retests/active", perm.Authenticated, s.listActiveFindingRetests)
s.handle(mux, "POST /api/exploration/findings/{id}/retests", perm.Authenticated, s.startFindingRetest)
s.handle(mux, "PATCH /api/exploration/findings/{id}", perm.Authenticated, s.patchFinding)
s.handle(mux, "POST /api/exploration/findings/bulk-status", perm.Authenticated, s.bulkPatchFindingStatus)
s.handle(mux, "POST /api/exploration/findings/bulk-report-state", perm.Authenticated, s.bulkPatchFindingReportState)
s.handle(mux, "DELETE /api/exploration/findings/{id}", perm.Authenticated, s.deleteFinding)
s.handle(mux, "GET /api/exploration/intents", perm.Authenticated, s.intents)
s.handle(mux, "GET /api/exploration/graph", perm.Authenticated, s.explorationGraph)
s.handle(mux, "GET /api/exploration/nodes", perm.Authenticated, s.explorationNodes)
s.handle(mux, "GET /api/exploration/activity", perm.Authenticated, s.activity)
s.handle(mux, "GET /api/exploration/activity/history", perm.Authenticated, s.activityHistory)
s.handle(mux, "GET /api/exploration/main-sessions", perm.Authenticated, s.mainSessions)
s.handle(mux, "POST /api/exploration/main-session/new", perm.Authenticated, s.newMainSession)
s.handle(mux, "GET /api/exploration/activity/stream", perm.Authenticated, s.streamActivity)
s.handle(mux, "GET /api/exploration/activity/{seq}", perm.Authenticated, s.activityDetail)
s.handle(mux, "GET /api/exploration/tokens", perm.Authenticated, s.tokenStats)
s.handle(mux, "GET /api/tokens/daily", perm.Authenticated, s.tokenDailyStats)
s.handle(mux, "GET /api/tokens/conversations", perm.Authenticated, s.conversationTokens)
s.handle(mux, "GET /api/tokens/usage", perm.Authenticated, s.pgUsageStats) // global llm_usage aggregation (new dashboard view)
mux.HandleFunc("GET /api/audit", s.getAudit)
mux.HandleFunc("POST /api/gc", s.gc)
mux.HandleFunc("GET /api/traffic", s.getTraffic)
mux.HandleFunc("GET /api/traffic/hosts", s.getTrafficHosts)
mux.HandleFunc("DELETE /api/traffic", s.deleteTraffic)
mux.HandleFunc("DELETE /api/traffic/hosts", s.deleteTrafficHosts)
mux.HandleFunc("DELETE /api/traffic/all", s.deleteAllTraffic)
mux.HandleFunc("GET /api/traffic/exchange", s.getTrafficExchange)
mux.HandleFunc("GET /api/traffic/stream", s.getTrafficStream)
mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob)
mux.HandleFunc("POST /api/traffic/ingest", s.ingestTraffic)
mux.HandleFunc("POST /api/traffic/replay", s.replayTraffic)
mux.HandleFunc("POST /api/traffic/import/har", s.importTrafficHAR)
mux.HandleFunc("GET /api/traffic/export/har", s.exportTrafficHAR)
mux.HandleFunc("GET /api/commands", s.pgListCommands)
mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // aggregate call counts per tool
mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords)
mux.HandleFunc("GET /api/llm/context/summary", s.pgLLMContextSummary)
mux.HandleFunc("DELETE /api/llm/records", s.pgDeleteLLMRecords)
mux.HandleFunc("GET /api/llm/records/tasks", s.pgLLMTasks)
mux.HandleFunc("GET /api/llm/records/by-model", s.pgTokenByModel) // aggregate this task's token usage by model
mux.HandleFunc("GET /api/llm/records/{id}", s.pgGetLLMRecord)
mux.HandleFunc("GET /api/settings", s.getSettings)
mux.HandleFunc("PUT /api/settings", s.putSettings)
mux.HandleFunc("GET /api/settings/noise", s.noiseStatus) // current noise profile + per-host counters (no reset)
s.handle(mux, "GET /api/audit", perm.Authenticated, s.getAudit)
s.handle(mux, "POST /api/gc", perm.Authenticated, s.gc)
s.handle(mux, "GET /api/traffic", perm.Authenticated, s.getTraffic)
s.handle(mux, "GET /api/traffic/hosts", perm.Authenticated, s.getTrafficHosts)
s.handle(mux, "DELETE /api/traffic", perm.Authenticated, s.deleteTraffic)
s.handle(mux, "DELETE /api/traffic/hosts", perm.Authenticated, s.deleteTrafficHosts)
s.handle(mux, "DELETE /api/traffic/all", perm.Authenticated, s.deleteAllTraffic)
s.handle(mux, "GET /api/traffic/exchange", perm.Authenticated, s.getTrafficExchange)
s.handle(mux, "GET /api/traffic/stream", perm.Authenticated, s.getTrafficStream)
s.handle(mux, "GET /api/traffic/blob", perm.Authenticated, s.getTrafficBlob)
s.handle(mux, "POST /api/traffic/ingest", perm.Authenticated, s.ingestTraffic)
s.handle(mux, "POST /api/traffic/replay", perm.Authenticated, s.replayTraffic)
s.handle(mux, "POST /api/traffic/import/har", perm.Authenticated, s.importTrafficHAR)
s.handle(mux, "GET /api/traffic/export/har", perm.Authenticated, s.exportTrafficHAR)
s.handle(mux, "GET /api/commands", perm.Authenticated, s.pgListCommands)
s.handle(mux, "GET /api/commands/stats", perm.Authenticated, s.pgToolStats) // aggregate call counts per tool
s.handle(mux, "GET /api/llm/records", perm.Authenticated, s.pgListLLMRecords)
s.handle(mux, "GET /api/llm/context/summary", perm.Authenticated, s.pgLLMContextSummary)
s.handle(mux, "DELETE /api/llm/records", perm.Authenticated, s.pgDeleteLLMRecords)
s.handle(mux, "GET /api/llm/records/tasks", perm.Authenticated, s.pgLLMTasks)
s.handle(mux, "GET /api/llm/records/by-model", perm.Authenticated, s.pgTokenByModel) // aggregate this task's token usage by model
s.handle(mux, "GET /api/llm/records/{id}", perm.Authenticated, s.pgGetLLMRecord)
s.handle(mux, "GET /api/settings", perm.Authenticated, s.getSettings)
s.handle(mux, "PUT /api/settings", perm.Authenticated, s.putSettings)
s.handle(mux, "GET /api/settings/noise", perm.Authenticated, s.noiseStatus) // current noise profile + per-host counters (no reset)
// Vulnerability IM push. Channels are "multi-instance + per-instance filter rules" resources, so they get their own group of
// REST endpoints instead of being stuffed into the flat /api/settings key-value store.
mux.HandleFunc("GET /api/notify/meta", s.notifyMeta)
mux.HandleFunc("GET /api/notify/channels", s.notifyListChannels)
mux.HandleFunc("POST /api/notify/channels", s.notifyCreateChannel)
mux.HandleFunc("PATCH /api/notify/channels/{id}", s.notifyUpdateChannel)
mux.HandleFunc("DELETE /api/notify/channels/{id}", s.notifyDeleteChannel)
mux.HandleFunc("POST /api/notify/channels/{id}/test", s.notifyTestChannel)
mux.HandleFunc("GET /api/notify/deliveries", s.notifyListDeliveries)
mux.HandleFunc("POST /api/notify/deliveries/{id}/retry", s.notifyRetryDelivery)
s.handle(mux, "GET /api/notify/meta", perm.Authenticated, s.notifyMeta)
s.handle(mux, "GET /api/notify/channels", perm.Authenticated, s.notifyListChannels)
s.handle(mux, "POST /api/notify/channels", perm.Authenticated, s.notifyCreateChannel)
s.handle(mux, "PATCH /api/notify/channels/{id}", perm.Authenticated, s.notifyUpdateChannel)
s.handle(mux, "DELETE /api/notify/channels/{id}", perm.Authenticated, s.notifyDeleteChannel)
s.handle(mux, "POST /api/notify/channels/{id}/test", perm.Authenticated, s.notifyTestChannel)
s.handle(mux, "GET /api/notify/deliveries", perm.Authenticated, s.notifyListDeliveries)
s.handle(mux, "POST /api/notify/deliveries/{id}/retry", perm.Authenticated, s.notifyRetryDelivery)
// Inbound chat bridges, one per transport kind (telegram).
mux.HandleFunc("GET /api/chat-bridges", s.chatBridgeList)
mux.HandleFunc("PUT /api/chat-bridges/{kind}", s.chatBridgeSave)
mux.HandleFunc("POST /api/chat-bridges/{kind}/test", s.chatBridgeTest)
mux.HandleFunc("POST /api/settings/web-search/test", s.testWebSearch)
mux.HandleFunc("GET /api/report", s.getReport)
mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions)
mux.HandleFunc("POST /api/chat", s.chat)
mux.HandleFunc("POST /api/chat/upload", s.chatUpload) // upload method 1: files land in uploads/ under the conversation/task work dir
mux.HandleFunc("GET /api/tasks/{id}/chat/status", s.taskChatStatus)
mux.HandleFunc("POST /api/tasks/{id}/chat/stop", s.stopChat)
s.handle(mux, "GET /api/chat-bridges", perm.Authenticated, s.chatBridgeList)
s.handle(mux, "PUT /api/chat-bridges/{kind}", perm.Authenticated, s.chatBridgeSave)
s.handle(mux, "POST /api/chat-bridges/{kind}/test", perm.Authenticated, s.chatBridgeTest)
s.handle(mux, "POST /api/settings/web-search/test", perm.Authenticated, s.testWebSearch)
s.handle(mux, "GET /api/report", perm.Authenticated, s.getReport)
s.handle(mux, "GET /api/chat/mentions", perm.Authenticated, s.searchChatMentions)
s.handle(mux, "POST /api/chat", perm.Authenticated, s.chat)
s.handle(mux, "POST /api/chat/upload", perm.Authenticated, s.chatUpload) // upload method 1: files land in uploads/ under the conversation/task work dir
s.handle(mux, "GET /api/tasks/{id}/chat/status", perm.Authenticated, s.taskChatStatus)
s.handle(mux, "POST /api/tasks/{id}/chat/stop", perm.Authenticated, s.stopChat)
// --- Admin API (PostgreSQL data source; new database & admin console plan) ---
mux.HandleFunc("DELETE /api/tasks/{id}", s.pgDeleteTask)
s.handle(mux, "DELETE /api/tasks/{id}", perm.Authenticated, s.pgDeleteTask)
// Agents
// conversations (chat page)
mux.HandleFunc("GET /api/conversations", s.pgListConversations)
mux.HandleFunc("POST /api/conversations", s.pgCreateConversation)
mux.HandleFunc("POST /api/conversations/delete/batch", s.pgDeleteConversationsBatch)
mux.HandleFunc("PATCH /api/conversations/{id}", s.pgRenameConversation)
mux.HandleFunc("PATCH /api/conversations/{id}/profile", s.pgUpdateConversation)
mux.HandleFunc("DELETE /api/conversations/{id}", s.pgDeleteConversation)
mux.HandleFunc("GET /api/conversations/{id}/messages", s.pgConversationMessages)
mux.HandleFunc("POST /api/conversations/{id}/messages", s.pgSendConversationMessage)
mux.HandleFunc("POST /api/conversations/{id}/stop", s.pgStopConversation)
mux.HandleFunc("GET /api/conversations/{id}/messages/{seq}", s.pgConversationMsgDetail)
mux.HandleFunc("GET /api/conversations/{id}/target-pins", s.convListTargetPins)
mux.HandleFunc("POST /api/conversations/{id}/target-pins/{pid}/revoke", s.convRevokeTargetPin)
s.handle(mux, "GET /api/conversations", perm.Authenticated, s.pgListConversations)
s.handle(mux, "POST /api/conversations", perm.Authenticated, s.pgCreateConversation)
s.handle(mux, "POST /api/conversations/delete/batch", perm.Authenticated, s.pgDeleteConversationsBatch)
s.handle(mux, "PATCH /api/conversations/{id}", perm.Authenticated, s.pgRenameConversation)
s.handle(mux, "PATCH /api/conversations/{id}/profile", perm.Authenticated, s.pgUpdateConversation)
s.handle(mux, "DELETE /api/conversations/{id}", perm.Authenticated, s.pgDeleteConversation)
s.handle(mux, "GET /api/conversations/{id}/messages", perm.Authenticated, s.pgConversationMessages)
s.handle(mux, "POST /api/conversations/{id}/messages", perm.Authenticated, s.pgSendConversationMessage)
s.handle(mux, "POST /api/conversations/{id}/stop", perm.Authenticated, s.pgStopConversation)
s.handle(mux, "GET /api/conversations/{id}/messages/{seq}", perm.Authenticated, s.pgConversationMsgDetail)
s.handle(mux, "GET /api/conversations/{id}/target-pins", perm.Authenticated, s.convListTargetPins)
s.handle(mux, "POST /api/conversations/{id}/target-pins/{pid}/revoke", perm.Authenticated, s.convRevokeTargetPin)
mux.HandleFunc("GET /api/agents", s.pgListAgents)
mux.HandleFunc("POST /api/agents", s.pgCreateAgent)
mux.HandleFunc("GET /api/agents/{key}", s.pgGetAgent)
mux.HandleFunc("PATCH /api/agents/{key}", s.pgUpdateAgent)
mux.HandleFunc("DELETE /api/agents/{key}", s.pgDeleteAgent)
mux.HandleFunc("PUT /api/agents/{key}/config", s.pgSaveAgentConfig)
mux.HandleFunc("PUT /api/agents/{key}/prompt", s.pgSavePrompt)
mux.HandleFunc("POST /api/agents/{key}/prompt/reset", s.pgResetPrompt)
mux.HandleFunc("PUT /api/agents/{key}/wrapup", s.pgSaveWrapup)
mux.HandleFunc("POST /api/agents/{key}/wrapup/reset", s.pgResetWrapup)
mux.HandleFunc("PUT /api/agents/{key}/wrapup/task-timeout", s.pgSaveTaskTimeoutWrapup)
mux.HandleFunc("POST /api/agents/{key}/wrapup/task-timeout/reset", s.pgResetTaskTimeoutWrapup)
mux.HandleFunc("GET /api/agents/{key}/triggers", s.pgListTriggers)
mux.HandleFunc("POST /api/agents/{key}/triggers", s.pgCreateTrigger)
mux.HandleFunc("PATCH /api/triggers/{id}", s.pgUpdateTrigger)
mux.HandleFunc("DELETE /api/triggers/{id}", s.pgDeleteTrigger)
mux.HandleFunc("GET /api/agents/{key}/prompts", s.pgListPromptVersions)
mux.HandleFunc("GET /api/agents/{key}/variables", s.pgPromptVars)
mux.HandleFunc("POST /api/agents/{key}/prompt/preview", s.pgPreviewPrompt)
mux.HandleFunc("GET /api/agents/{key}/visibility", s.pgGetAgentVisibility)
mux.HandleFunc("PUT /api/agents/{key}/visibility", s.pgSetAgentVisibility)
s.handle(mux, "GET /api/agents", perm.Authenticated, s.pgListAgents)
s.handle(mux, "POST /api/agents", perm.Authenticated, s.pgCreateAgent)
s.handle(mux, "GET /api/agents/{key}", perm.Authenticated, s.pgGetAgent)
s.handle(mux, "PATCH /api/agents/{key}", perm.Authenticated, s.pgUpdateAgent)
s.handle(mux, "DELETE /api/agents/{key}", perm.Authenticated, s.pgDeleteAgent)
s.handle(mux, "PUT /api/agents/{key}/config", perm.Authenticated, s.pgSaveAgentConfig)
s.handle(mux, "PUT /api/agents/{key}/prompt", perm.Authenticated, s.pgSavePrompt)
s.handle(mux, "POST /api/agents/{key}/prompt/reset", perm.Authenticated, s.pgResetPrompt)
s.handle(mux, "PUT /api/agents/{key}/wrapup", perm.Authenticated, s.pgSaveWrapup)
s.handle(mux, "POST /api/agents/{key}/wrapup/reset", perm.Authenticated, s.pgResetWrapup)
s.handle(mux, "PUT /api/agents/{key}/wrapup/task-timeout", perm.Authenticated, s.pgSaveTaskTimeoutWrapup)
s.handle(mux, "POST /api/agents/{key}/wrapup/task-timeout/reset", perm.Authenticated, s.pgResetTaskTimeoutWrapup)
s.handle(mux, "GET /api/agents/{key}/triggers", perm.Authenticated, s.pgListTriggers)
s.handle(mux, "POST /api/agents/{key}/triggers", perm.Authenticated, s.pgCreateTrigger)
s.handle(mux, "PATCH /api/triggers/{id}", perm.Authenticated, s.pgUpdateTrigger)
s.handle(mux, "DELETE /api/triggers/{id}", perm.Authenticated, s.pgDeleteTrigger)
s.handle(mux, "GET /api/agents/{key}/prompts", perm.Authenticated, s.pgListPromptVersions)
s.handle(mux, "GET /api/agents/{key}/variables", perm.Authenticated, s.pgPromptVars)
s.handle(mux, "POST /api/agents/{key}/prompt/preview", perm.Authenticated, s.pgPreviewPrompt)
s.handle(mux, "GET /api/agents/{key}/visibility", perm.Authenticated, s.pgGetAgentVisibility)
s.handle(mux, "PUT /api/agents/{key}/visibility", perm.Authenticated, s.pgSetAgentVisibility)
// built-in tool catalog (description/param defaults editable, bound per agent; key and handler live in code)
mux.HandleFunc("GET /api/tools", s.pgListTools)
mux.HandleFunc("PUT /api/tools/{key}", s.pgUpdateTool)
mux.HandleFunc("POST /api/tools/custom", s.pgCreateCustomTool)
mux.HandleFunc("POST /api/tools/custom/test", s.pgTestCustomTool)
mux.HandleFunc("PUT /api/tools/custom/{key}", s.pgUpdateCustomTool)
mux.HandleFunc("DELETE /api/tools/custom/{key}", s.pgDeleteCustomTool)
mux.HandleFunc("POST /api/settings/python/detect", s.pgDetectPython)
mux.HandleFunc("POST /api/tools/{key}/reset", s.pgResetTool)
s.handle(mux, "GET /api/tools", perm.Authenticated, s.pgListTools)
s.handle(mux, "PUT /api/tools/{key}", perm.Authenticated, s.pgUpdateTool)
s.handle(mux, "POST /api/tools/custom", perm.Authenticated, s.pgCreateCustomTool)
s.handle(mux, "POST /api/tools/custom/test", perm.Authenticated, s.pgTestCustomTool)
s.handle(mux, "PUT /api/tools/custom/{key}", perm.Authenticated, s.pgUpdateCustomTool)
s.handle(mux, "DELETE /api/tools/custom/{key}", perm.Authenticated, s.pgDeleteCustomTool)
s.handle(mux, "POST /api/settings/python/detect", perm.Authenticated, s.pgDetectPython)
s.handle(mux, "POST /api/tools/{key}/reset", perm.Authenticated, s.pgResetTool)
// MCP CRUD
mux.HandleFunc("GET /api/mcp", s.pgListMCP)
mux.HandleFunc("POST /api/mcp", s.pgSaveMCP)
mux.HandleFunc("DELETE /api/mcp/{id}", s.pgDeleteMCP)
mux.HandleFunc("GET /api/mcp/{id}/tools", s.pgMCPTools)
mux.HandleFunc("POST /api/mcp/{id}/refresh", s.pgRefreshMCP)
s.handle(mux, "GET /api/mcp", perm.Authenticated, s.pgListMCP)
s.handle(mux, "POST /api/mcp", perm.Authenticated, s.pgSaveMCP)
s.handle(mux, "DELETE /api/mcp/{id}", perm.Authenticated, s.pgDeleteMCP)
s.handle(mux, "GET /api/mcp/{id}/tools", perm.Authenticated, s.pgMCPTools)
s.handle(mux, "POST /api/mcp/{id}/refresh", perm.Authenticated, s.pgRefreshMCP)
// asset sync — ScopeSentry data source
mux.HandleFunc("GET /api/sync/scopesentry/status", s.syncSSStatus)
mux.HandleFunc("POST /api/sync/scopesentry/datasource", s.syncSSDatasource)
mux.HandleFunc("GET /api/sync/scopesentry/projects", s.syncSSProjects)
mux.HandleFunc("GET /api/sync/scopesentry/tasks", s.syncSSTasks)
mux.HandleFunc("POST /api/sync/scopesentry/sync", s.syncSSRun)
s.handle(mux, "GET /api/sync/scopesentry/status", perm.Authenticated, s.syncSSStatus)
s.handle(mux, "POST /api/sync/scopesentry/datasource", perm.Authenticated, s.syncSSDatasource)
s.handle(mux, "GET /api/sync/scopesentry/projects", perm.Authenticated, s.syncSSProjects)
s.handle(mux, "GET /api/sync/scopesentry/tasks", perm.Authenticated, s.syncSSTasks)
s.handle(mux, "POST /api/sync/scopesentry/sync", perm.Authenticated, s.syncSSRun)
// Skill CRUD (filesystem)
mux.HandleFunc("GET /api/skills", s.fsListSkills)
mux.HandleFunc("POST /api/skills", s.fsCreateSkill)
mux.HandleFunc("POST /api/skills/upload", s.fsUploadSkill)
mux.HandleFunc("DELETE /api/skills/{name}", s.fsDeleteSkill)
mux.HandleFunc("GET /api/skills/missing", s.fsMissingSkills) // names of skills that were invoked but do not exist
mux.HandleFunc("GET /api/skills/{name}/usage", s.fsSkillUsage) // recent invocations of one skill
mux.HandleFunc("PUT /api/skills/{name}/meta", s.fsUpdateSkillMeta)
mux.HandleFunc("POST /api/skills/{name}/dirs", s.fsCreateDir)
mux.HandleFunc("GET /api/skills/{name}/files", s.fsListFiles)
s.handle(mux, "GET /api/skills", perm.Authenticated, s.fsListSkills)
s.handle(mux, "POST /api/skills", perm.Authenticated, s.fsCreateSkill)
s.handle(mux, "POST /api/skills/upload", perm.Authenticated, s.fsUploadSkill)
s.handle(mux, "DELETE /api/skills/{name}", perm.Authenticated, s.fsDeleteSkill)
s.handle(mux, "GET /api/skills/missing", perm.Authenticated, s.fsMissingSkills) // names of skills that were invoked but do not exist
s.handle(mux, "GET /api/skills/{name}/usage", perm.Authenticated, s.fsSkillUsage) // recent invocations of one skill
s.handle(mux, "PUT /api/skills/{name}/meta", perm.Authenticated, s.fsUpdateSkillMeta)
s.handle(mux, "POST /api/skills/{name}/dirs", perm.Authenticated, s.fsCreateDir)
s.handle(mux, "GET /api/skills/{name}/files", perm.Authenticated, s.fsListFiles)
// {file...} captures path segments including slashes (e.g. scripts/extract.py)
mux.HandleFunc("GET /api/skills/{name}/files/{file...}", s.fsReadFile)
mux.HandleFunc("PUT /api/skills/{name}/files/{file...}", s.fsWriteFile)
mux.HandleFunc("DELETE /api/skills/{name}/files/{file...}", s.fsDeletePath)
s.handle(mux, "GET /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsReadFile)
s.handle(mux, "PUT /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsWriteFile)
s.handle(mux, "DELETE /api/skills/{name}/files/{file...}", perm.Authenticated, s.fsDeletePath)
// MCP resource-side visibility (more specific skill routes match first)
mux.HandleFunc("GET /api/visibility/{kind}/{id}", s.pgResourceVisibility)
mux.HandleFunc("POST /api/visibility/toggle", s.pgToggleVisibility)
s.handle(mux, "GET /api/visibility/{kind}/{id}", perm.Authenticated, s.pgResourceVisibility)
s.handle(mux, "POST /api/visibility/toggle", perm.Authenticated, s.pgToggleVisibility)
// Skill visibility (by name, more specific, takes priority over the wildcard routes above)
mux.HandleFunc("GET /api/visibility/skill/{name}", s.pgSkillVisibility)
mux.HandleFunc("POST /api/visibility/skill/toggle", s.pgToggleSkillVisibility)
s.handle(mux, "GET /api/visibility/skill/{name}", perm.Authenticated, s.pgSkillVisibility)
s.handle(mux, "POST /api/visibility/skill/toggle", perm.Authenticated, s.pgToggleSkillVisibility)
// LLM multi-profile
mux.HandleFunc("GET /api/llm/profiles", s.pgListProfiles)
mux.HandleFunc("POST /api/llm/profiles", s.pgSaveProfile)
mux.HandleFunc("DELETE /api/llm/profiles/{id}", s.pgDeleteProfile)
mux.HandleFunc("POST /api/llm/profiles/active", s.pgActivateProfile)
mux.HandleFunc("GET /api/llm/retry-policy", s.pgGetLLMRetryPolicy)
mux.HandleFunc("POST /api/llm/retry-policy", s.pgSaveLLMRetryPolicy)
mux.HandleFunc("GET /api/llm/pool", s.pgLLMPoolStatus)
mux.HandleFunc("POST /api/llm/pool/reset", s.pgLLMPoolReset)
mux.HandleFunc("POST /api/llm/models", s.pgListModels)
s.handle(mux, "GET /api/llm/profiles", perm.Authenticated, s.pgListProfiles)
s.handle(mux, "POST /api/llm/profiles", perm.Authenticated, s.pgSaveProfile)
s.handle(mux, "DELETE /api/llm/profiles/{id}", perm.Authenticated, s.pgDeleteProfile)
s.handle(mux, "POST /api/llm/profiles/active", perm.Authenticated, s.pgActivateProfile)
s.handle(mux, "GET /api/llm/retry-policy", perm.Authenticated, s.pgGetLLMRetryPolicy)
s.handle(mux, "POST /api/llm/retry-policy", perm.Authenticated, s.pgSaveLLMRetryPolicy)
s.handle(mux, "GET /api/llm/pool", perm.Authenticated, s.pgLLMPoolStatus)
s.handle(mux, "POST /api/llm/pool/reset", perm.Authenticated, s.pgLLMPoolReset)
s.handle(mux, "POST /api/llm/models", perm.Authenticated, s.pgListModels)
// interception rule management
mux.HandleFunc("GET /api/intercept/rules", s.interceptListRules)
mux.HandleFunc("POST /api/intercept/rules", s.interceptCreateRule)
mux.HandleFunc("PUT /api/intercept/rules/{id}", s.interceptUpdateRule)
mux.HandleFunc("DELETE /api/intercept/rules/{id}", s.interceptDeleteRule)
mux.HandleFunc("POST /api/intercept/rules/{id}/toggle", s.interceptToggleRule)
s.handle(mux, "GET /api/intercept/rules", perm.Authenticated, s.interceptListRules)
s.handle(mux, "POST /api/intercept/rules", perm.Authenticated, s.interceptCreateRule)
s.handle(mux, "PUT /api/intercept/rules/{id}", perm.Authenticated, s.interceptUpdateRule)
s.handle(mux, "DELETE /api/intercept/rules/{id}", perm.Authenticated, s.interceptDeleteRule)
s.handle(mux, "POST /api/intercept/rules/{id}/toggle", perm.Authenticated, s.interceptToggleRule)
// capture-proxy rewrite rule management (stored and compiled; not applied by the proxy yet)
mux.HandleFunc("GET /api/traffic/rewrite-rules", s.rewriteListRules)
mux.HandleFunc("POST /api/traffic/rewrite-rules", s.rewriteCreateRule)
mux.HandleFunc("PUT /api/traffic/rewrite-rules/{id}", s.rewriteUpdateRule)
mux.HandleFunc("DELETE /api/traffic/rewrite-rules/{id}", s.rewriteDeleteRule)
mux.HandleFunc("POST /api/traffic/rewrite-rules/{id}/toggle", s.rewriteToggleRule)
s.handle(mux, "GET /api/traffic/rewrite-rules", perm.Authenticated, s.rewriteListRules)
s.handle(mux, "POST /api/traffic/rewrite-rules", perm.Authenticated, s.rewriteCreateRule)
s.handle(mux, "PUT /api/traffic/rewrite-rules/{id}", perm.Authenticated, s.rewriteUpdateRule)
s.handle(mux, "DELETE /api/traffic/rewrite-rules/{id}", perm.Authenticated, s.rewriteDeleteRule)
s.handle(mux, "POST /api/traffic/rewrite-rules/{id}/toggle", perm.Authenticated, s.rewriteToggleRule)
// Proxy pool (#545): stored candidates for the global proxy; nothing activates one yet.
s.handle(mux, "GET /api/proxy-pool", perm.Authenticated, s.proxyPoolList)
s.handle(mux, "POST /api/proxy-pool", perm.Authenticated, s.proxyPoolCreate)
s.handle(mux, "PATCH /api/proxy-pool/{id}", perm.Authenticated, s.proxyPoolUpdate)
s.handle(mux, "DELETE /api/proxy-pool/{id}", perm.Authenticated, s.proxyPoolDelete)
// capture-proxy constrained Go tampering hooks (P4.2, operator-only, opt-in via ARTEX_TAMPER_HOOKS_ENABLED)
mux.HandleFunc("GET /api/traffic/hooks", s.tamperListHooks)
mux.HandleFunc("POST /api/traffic/hooks", s.tamperCreateHook)
mux.HandleFunc("PUT /api/traffic/hooks/{id}", s.tamperUpdateHook)
mux.HandleFunc("DELETE /api/traffic/hooks/{id}", s.tamperDeleteHook)
mux.HandleFunc("POST /api/traffic/hooks/{id}/toggle", s.tamperToggleHook)
mux.HandleFunc("GET /api/traffic/hooks/{id}/versions", s.tamperListHookVersions)
mux.HandleFunc("POST /api/traffic/hooks/{id}/rollback", s.tamperRollbackHook)
mux.HandleFunc("POST /api/traffic/hooks/dry-run", s.tamperDryRunHook)
s.handle(mux, "GET /api/traffic/hooks", perm.Authenticated, s.tamperListHooks)
s.handle(mux, "POST /api/traffic/hooks", perm.Authenticated, s.tamperCreateHook)
s.handle(mux, "PUT /api/traffic/hooks/{id}", perm.Authenticated, s.tamperUpdateHook)
s.handle(mux, "DELETE /api/traffic/hooks/{id}", perm.Authenticated, s.tamperDeleteHook)
s.handle(mux, "POST /api/traffic/hooks/{id}/toggle", perm.Authenticated, s.tamperToggleHook)
s.handle(mux, "GET /api/traffic/hooks/{id}/versions", perm.Authenticated, s.tamperListHookVersions)
s.handle(mux, "POST /api/traffic/hooks/{id}/rollback", perm.Authenticated, s.tamperRollbackHook)
s.handle(mux, "POST /api/traffic/hooks/dry-run", perm.Authenticated, s.tamperDryRunHook)
// asset interception rule management (global blocklist: domains/IPs/URLs/CIDRs)
mux.HandleFunc("GET /api/asset-intercept/rules", s.assetInterceptListRules)
mux.HandleFunc("POST /api/asset-intercept/rules", s.assetInterceptCreateRule)
mux.HandleFunc("PUT /api/asset-intercept/rules/{id}", s.assetInterceptUpdateRule)
mux.HandleFunc("DELETE /api/asset-intercept/rules/{id}", s.assetInterceptDeleteRule)
mux.HandleFunc("POST /api/asset-intercept/rules/{id}/toggle", s.assetInterceptToggleRule)
s.handle(mux, "GET /api/asset-intercept/rules", perm.Authenticated, s.assetInterceptListRules)
s.handle(mux, "POST /api/asset-intercept/rules", perm.Authenticated, s.assetInterceptCreateRule)
s.handle(mux, "PUT /api/asset-intercept/rules/{id}", perm.Authenticated, s.assetInterceptUpdateRule)
s.handle(mux, "DELETE /api/asset-intercept/rules/{id}", perm.Authenticated, s.assetInterceptDeleteRule)
s.handle(mux, "POST /api/asset-intercept/rules/{id}/toggle", perm.Authenticated, s.assetInterceptToggleRule)
mux.HandleFunc("GET /api/intercept/pending", s.interceptListPending)
mux.HandleFunc("GET /api/intercept/pending/{id}", s.interceptGetOne)
mux.HandleFunc("POST /api/intercept/pending/{id}/decide", s.interceptDecide)
mux.HandleFunc("POST /api/intercept/pending/batch-decide", s.interceptBatchDecide)
mux.HandleFunc("POST /api/intercept/pending/{id}/always-allow", s.interceptAlwaysAllow) // creates an argv allow rule; the request stays pending
mux.HandleFunc("GET /api/intercept/history", s.interceptHistory)
mux.HandleFunc("GET /api/intercept/history/{id}", s.interceptDetail)
mux.HandleFunc("GET /api/intercept/history/{id}/execution", s.interceptExecution)
mux.HandleFunc("GET /api/intercept/task/{taskID}", s.interceptListTaskItems)
mux.HandleFunc("GET /api/intercept/task/{taskID}/pending-summary", s.interceptTaskPendingSummary)
mux.HandleFunc("GET /api/intercept/tool-config", s.interceptGetToolConfig)
mux.HandleFunc("PUT /api/intercept/tool-config", s.interceptSetToolConfig)
mux.HandleFunc("GET /api/target-gate/exemptions", s.targetGateGetExemptions)
mux.HandleFunc("PUT /api/target-gate/exemptions", s.targetGateSetExemptions)
mux.HandleFunc("GET /api/target-gate/exemptions/history", s.targetGateExemptionHistory)
mux.HandleFunc("GET /api/intercept/judge", s.interceptGetJudgeConfig)
mux.HandleFunc("PUT /api/intercept/judge", s.interceptSetJudgeConfig)
mux.HandleFunc("GET /api/intercept/judge/usage", s.interceptJudgeUsage) // cumulative token usage of fallback approval
s.handle(mux, "GET /api/intercept/pending", perm.Authenticated, s.interceptListPending)
s.handle(mux, "GET /api/intercept/pending/{id}", perm.Authenticated, s.interceptGetOne)
s.handle(mux, "POST /api/intercept/pending/{id}/decide", perm.Authenticated, s.interceptDecide)
s.handle(mux, "POST /api/intercept/pending/batch-decide", perm.Authenticated, s.interceptBatchDecide)
s.handle(mux, "POST /api/intercept/pending/{id}/always-allow", perm.Authenticated, s.interceptAlwaysAllow) // creates an argv allow rule; the request stays pending
s.handle(mux, "GET /api/intercept/history", perm.Authenticated, s.interceptHistory)
s.handle(mux, "GET /api/intercept/history/{id}", perm.Authenticated, s.interceptDetail)
s.handle(mux, "GET /api/intercept/history/{id}/execution", perm.Authenticated, s.interceptExecution)
s.handle(mux, "GET /api/intercept/task/{taskID}", perm.Authenticated, s.interceptListTaskItems)
s.handle(mux, "GET /api/intercept/task/{taskID}/pending-summary", perm.Authenticated, s.interceptTaskPendingSummary)
s.handle(mux, "GET /api/intercept/tool-config", perm.Authenticated, s.interceptGetToolConfig)
s.handle(mux, "PUT /api/intercept/tool-config", perm.Authenticated, s.interceptSetToolConfig)
s.handle(mux, "GET /api/target-gate/exemptions", perm.Authenticated, s.targetGateGetExemptions)
s.handle(mux, "PUT /api/target-gate/exemptions", perm.Authenticated, s.targetGateSetExemptions)
s.handle(mux, "GET /api/target-gate/exemptions/history", perm.Authenticated, s.targetGateExemptionHistory)
s.handle(mux, "GET /api/target-gate/posture", perm.Authenticated, s.targetGatePosture)
s.handle(mux, "GET /api/intercept/judge", perm.Authenticated, s.interceptGetJudgeConfig)
s.handle(mux, "PUT /api/intercept/judge", perm.Authenticated, s.interceptSetJudgeConfig)
s.handle(mux, "GET /api/intercept/judge/usage", perm.Authenticated, s.interceptJudgeUsage) // cumulative token usage of fallback approval
// /api/* goes through CORS + JWT; everything else is served by the embedded
// frontend (public — auth is enforced client-side and on the API). With the
return mux
}
func (s *Server) Handler() http.Handler {
return s.handlerFor(s.apiRoutes())
}
// handlerFor builds the production handler around an API mux. Handler uses
// it with the real route table; tests use it with their own routes, so they
// exercise the same chain.
func (s *Server) handlerFor(mux *apiMux) http.Handler {
// /api/* goes through CORS, JWT and the route permission check (routes.go);
// everything else is served by the embedded frontend (public — auth is
// enforced client-side and on the API). With the
// no-embed build the webui handler just 404s (run `next dev` separately).
api := cors(s.requireAuth(mux))
securedAPI := cors(s.requireAuth(s.requirePerm(mux)))
api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Posture is a live security snapshot. Set no-store before auth so counts
// and 401/503 responses cannot be reused from a browser or proxy cache.
if r.URL.Path == "/api/target-gate/posture" {
w.Header().Set("Cache-Control", "no-store")
}
securedAPI.ServeHTTP(w, r)
})
root := http.NewServeMux()
root.Handle("/api/", api)
webui := s.webuiHandler()
+8 -6
View File
@@ -8,6 +8,8 @@ import (
"net/http"
"strings"
"time"
"github.com/Autumn-27/artex/server/perm"
)
// Shared browser API (Function → Browser in the web UI).
@@ -20,12 +22,12 @@ import (
//
// All of them sit behind requireAuth like every other /api route.
func (s *Server) registerSharedBrowserRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/browser/status", s.browserStatus)
mux.HandleFunc("GET /api/browser/stream", s.browserStream)
mux.HandleFunc("POST /api/browser/start", s.browserStart)
mux.HandleFunc("POST /api/browser/control", s.browserControl)
mux.HandleFunc("POST /api/browser/input", s.browserInput)
func (s *Server) registerSharedBrowserRoutes(mux *apiMux) {
s.handle(mux, "GET /api/browser/status", perm.Authenticated, s.browserStatus)
s.handle(mux, "GET /api/browser/stream", perm.Authenticated, s.browserStream)
s.handle(mux, "POST /api/browser/start", perm.Authenticated, s.browserStart)
s.handle(mux, "POST /api/browser/control", perm.Authenticated, s.browserControl)
s.handle(mux, "POST /api/browser/input", perm.Authenticated, s.browserInput)
}
func (s *Server) browserStatus(w http.ResponseWriter, _ *http.Request) {
+5 -4
View File
@@ -18,6 +18,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/artex/server/perm"
"github.com/Autumn-27/artex/sidequestion"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/transcript"
@@ -270,10 +271,10 @@ func (s *Server) sideParent(w http.ResponseWriter, r *http.Request, kind string)
return p, true
}
func (s *Server) registerSideRoutes(mux *http.ServeMux) {
func (s *Server) registerSideRoutes(mux *apiMux) {
for _, route := range []struct{ path, kind string }{{"/api/conversations/{id}", "conversation"}, {"/api/tasks/{id}/chat", "main"}, {"/api/tasks/{id}/intents/{iid}", "worker"}} {
for _, method := range []string{"GET", "POST", "DELETE"} {
mux.HandleFunc(method+" "+route.path+"/side-questions", func(w http.ResponseWriter, r *http.Request) {
s.handle(mux, method+" "+route.path+"/side-questions", perm.Authenticated, func(w http.ResponseWriter, r *http.Request) {
p, ok := s.sideParent(w, r, route.kind)
if ok {
s.handleSideQuestions(w, r, p)
@@ -281,8 +282,8 @@ func (s *Server) registerSideRoutes(mux *http.ServeMux) {
})
}
}
mux.HandleFunc("GET /api/side-questions/{requestID}/events", s.sideEvents)
mux.HandleFunc("POST /api/side-questions/{requestID}/cancel", s.cancelSideRequest)
s.handle(mux, "GET /api/side-questions/{requestID}/events", perm.Authenticated, s.sideEvents)
s.handle(mux, "POST /api/side-questions/{requestID}/cancel", perm.Authenticated, s.cancelSideRequest)
}
func (s *Server) handleSideQuestions(w http.ResponseWriter, r *http.Request, p sidequestion.Parent) {
+27
View File
@@ -0,0 +1,27 @@
package server
import (
"context"
"log"
"net/http"
"time"
)
const targetGatePostureQueryTimeout = 5 * time.Second
// targetGatePosture reports current committed task counts to a signed-in operator.
func (s *Server) targetGatePosture(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
ctx, cancel := context.WithTimeout(r.Context(), targetGatePostureQueryTimeout)
defer cancel()
posture, err := pg.GetTargetGatePosture(ctx)
if err != nil {
log.Printf("[target-gate] posture query failed: %v", err)
writeErr(w, http.StatusServiceUnavailable, "target-gate posture unavailable")
return
}
writeJSON(w, http.StatusOK, posture)
}
+133
View File
@@ -0,0 +1,133 @@
package server
import (
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
"github.com/golang-jwt/jwt/v5"
)
func postureGET(s *Server, token string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, "/api/target-gate/posture", nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, req)
return rec
}
// The route must use the real mux and JWT middleware; anonymous and expired
// sessions cannot receive either count or the time of the security observation.
func TestTargetGatePostureRequiresCurrentSession(t *testing.T) {
key := []byte("0123456789abcdef0123456789abcdef")
s := &Server{m: &Manager{}, jwtKey: key}
claims := testJWTClaims(jwtIssuer, []string{jwtAudience}, 0)
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(-time.Minute))
expired := signTestJWT(t, jwt.SigningMethodHS256, key, claims)
for _, tc := range []struct{ name, token string }{
{"missing", ""},
{"expired", expired},
} {
t.Run(tc.name, func(t *testing.T) {
rec := postureGET(s, tc.token)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401: %s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("Cache-Control = %q, want no-store", rec.Header().Get("Cache-Control"))
}
if strings.Contains(rec.Body.String(), "ungated_unfinished_tasks") ||
strings.Contains(rec.Body.String(), "explicit_opt_out_tasks") ||
strings.Contains(rec.Body.String(), "observed_at") {
t.Fatalf("unauthorized response leaks posture: %s", rec.Body.String())
}
})
}
}
// A failed PostgreSQL query must be an unavailable response, never an apparent
// zero. A closed handle provides a real database/sql error without a network.
func TestTargetGatePostureDatabaseFailureIsUnavailable(t *testing.T) {
sqlDB, err := sql.Open("pgx", "postgres://localhost/postgres")
if err != nil {
t.Fatal(err)
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
key := []byte("0123456789abcdef0123456789abcdef")
s := &Server{m: &Manager{pg: &db.DB{DB: sqlDB}}, jwtKey: key}
token, err := signJWT(key)
if err != nil {
t.Fatal(err)
}
var rec *httptest.ResponseRecorder
logged := captureLog(t, func() { rec = postureGET(s, token) })
if !strings.Contains(logged, "[target-gate] posture query failed") {
t.Fatalf("database error was not logged: %q", logged)
}
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503: %s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("Cache-Control = %q, want no-store", rec.Header().Get("Cache-Control"))
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if _, ok := body["error"]; !ok {
t.Fatalf("missing unavailable error: %v", body)
}
for _, key := range []string{"ungated_unfinished_tasks", "explicit_opt_out_tasks", "observed_at"} {
if _, ok := body[key]; ok {
t.Fatalf("database error exposed %s: %v", key, body)
}
}
if strings.Contains(rec.Body.String(), "database is closed") {
t.Fatalf("database detail leaked: %s", rec.Body.String())
}
}
// The returned view is global and is read after every committed gate change.
func TestTargetGatePostureRouteFollowsGatePatch(t *testing.T) {
g := newGateServer(t)
baseline, err := g.m.pg.GetTargetGatePosture(t.Context())
if err != nil {
t.Fatal(err)
}
task := g.newTask(t, db.TaskCreateOptions{})
check := func(label string, ungated, optedOut int) {
t.Helper()
rec := postureGET(g.s, g.token)
if rec.Code != http.StatusOK {
t.Fatalf("%s: status = %d: %s", label, rec.Code, rec.Body.String())
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("%s: Cache-Control = %q", label, rec.Header().Get("Cache-Control"))
}
var got db.TargetGatePosture
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.UngatedUnfinishedTasks != ungated || got.ExplicitOptOutTasks != optedOut || got.ObservedAt.IsZero() {
t.Fatalf("%s: posture = %+v, want counts (%d, %d) and observation time", label, got, ungated, optedOut)
}
}
check("new implicit-off task", baseline.UngatedUnfinishedTasks+1, baseline.ExplicitOptOutTasks)
if code, body := g.do(t, http.MethodPatch, "/api/tasks/"+task.ID, `{"target_gate":true}`); code != http.StatusOK {
t.Fatalf("enable gate: %d %v", code, body)
}
check("gate on", baseline.UngatedUnfinishedTasks, baseline.ExplicitOptOutTasks)
if code, body := g.do(t, http.MethodPatch, "/api/tasks/"+task.ID, `{"target_gate":false}`); code != http.StatusOK {
t.Fatalf("disable gate: %d %v", code, body)
}
check("explicit off", baseline.UngatedUnfinishedTasks+1, baseline.ExplicitOptOutTasks+1)
}
+64 -6
View File
@@ -28,6 +28,11 @@ const (
maxArchiveBytes = int64(1 << 47) // 128 TiB safety ceiling for corrupt headers.
)
// taskArchiveBeforeOpenHook is an optional test hook invoked with the payload-relative
// name of each regular file immediately before writeTaskArchivePackage opens it,
// allowing deterministic TOCTOU regression tests (always nil in production).
var taskArchiveBeforeOpenHook func(name string)
type archiveFileMove struct {
Source string `json:"source"`
Relative string `json:"relative"`
@@ -700,15 +705,24 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return 0, 0, "", err
}
// Code running as the executor uid can keep a working directory inside the moved run
// directory and swap a directory for a symlink after it was listed. Walk and open
// through a root anchored at the payload so no lookup can leave it, and check that
// each opened file is the one the walk saw.
root, err := os.OpenRoot(payloadDir)
if err != nil {
return 0, 0, "", err
}
defer root.Close()
tarWriter := tar.NewWriter(encoder)
walkErr := filepath.WalkDir(payloadDir, func(current string, entry fs.DirEntry, walkErr error) error {
walkErr := walkTaskArchiveRoot(root, ".", func(relative string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
relative, err := filepath.Rel(payloadDir, current)
if err != nil || relative == "." {
return err
if relative == "." {
return nil
}
current := filepath.Join(payloadDir, filepath.FromSlash(relative))
info, err := entry.Info()
if err != nil {
return err
@@ -730,7 +744,7 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
if err != nil {
return err
}
header.Name = filepath.ToSlash(relative)
header.Name = relative
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
@@ -738,10 +752,21 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return nil
}
originalSize += info.Size()
input, err := os.Open(current)
if taskArchiveBeforeOpenHook != nil {
taskArchiveBeforeOpenHook(relative)
}
input, err := root.Open(filepath.FromSlash(relative))
if err != nil {
return err
}
opened, err := input.Stat()
if err == nil && (!opened.Mode().IsRegular() || !os.SameFile(info, opened)) {
err = fmt.Errorf("task archive entry %s changed while it was packed", relative)
}
if err != nil {
_ = input.Close()
return err
}
_, copyErr := io.Copy(tarWriter, input)
closeErr := input.Close()
return errors.Join(copyErr, closeErr)
@@ -780,6 +805,39 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
return originalSize, compressedSize, checksum, nil
}
// walkTaskArchiveRoot walks dir inside root like fs.WalkDir, in lexical order, with
// slash-separated names. It does not go through root.FS(), which refuses names that
// are not valid UTF-8, so a run tree holding such a file can still be archived as
// before. Entries come from ReadDir on a handle opened in root, so their FileInfo is
// read relative to that handle, never through a path that could leave the root.
func walkTaskArchiveRoot(root *os.Root, dir string, fn fs.WalkDirFunc) error {
handle, err := root.Open(filepath.FromSlash(dir))
if err != nil {
return fn(dir, nil, err)
}
entries, err := handle.ReadDir(-1)
_ = handle.Close()
if err != nil {
return fn(dir, nil, err)
}
slices.SortFunc(entries, func(a, b fs.DirEntry) int { return strings.Compare(a.Name(), b.Name()) })
for _, entry := range entries {
name := entry.Name()
if dir != "." {
name = dir + "/" + name
}
if err := fn(name, entry, nil); err != nil {
return err
}
if entry.IsDir() {
if err := walkTaskArchiveRoot(root, name, fn); err != nil {
return err
}
}
}
return nil
}
func extractTaskArchivePackage(path, expectedSHA, destination string) error {
file, err := os.Open(path)
if err != nil {
+339
View File
@@ -0,0 +1,339 @@
//go:build unix
package server
import (
"archive/tar"
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
pgdb "github.com/Autumn-27/artex/db"
"github.com/klauspost/compress/zstd"
)
const archiveOutsideSecret = "root-only secret outside the payload"
// sameSizeAsSecret returns a filler as long as archiveOutsideSecret, so a tar header
// taken from the listed file still matches the bytes read through a swapped path.
func sameSizeAsSecret(fill string) string {
return strings.Repeat(fill, len(archiveOutsideSecret))
}
// archiveSymlinkFixture builds a payload with main/zzz/{a_big,jwt.key} and, next to
// the payload, an outside directory holding jwt.key with archiveOutsideSecret.
func archiveSymlinkFixture(t *testing.T) (payload, outside string) {
t.Helper()
base := t.TempDir()
payload = filepath.Join(base, "payload")
outside = filepath.Join(base, "keys")
for path, body := range map[string]string{
filepath.Join(payload, "main", "zzz", "a_big"): "earlier sibling",
filepath.Join(payload, "main", "zzz", "jwt.key"): sameSizeAsSecret("d"),
filepath.Join(outside, "jwt.key"): archiveOutsideSecret,
} {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
return payload, outside
}
// swapBeforeOpen runs swap once, right before the packer opens the file named at.
func swapBeforeOpen(t *testing.T, at string, swap func() error) {
t.Helper()
taskArchiveBeforeOpenHook = func(name string) {
if name != at {
return
}
taskArchiveBeforeOpenHook = nil
if err := swap(); err != nil {
t.Errorf("swap: %v", err)
}
}
t.Cleanup(func() { taskArchiveBeforeOpenHook = nil })
}
// readArchiveEntries returns the regular file contents of a task archive by name.
func readArchiveEntries(t *testing.T, path string) map[string]string {
t.Helper()
file, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer file.Close()
decoder, err := zstd.NewReader(file)
if err != nil {
t.Fatal(err)
}
defer decoder.Close()
entries := map[string]string{}
tr := tar.NewReader(decoder)
for {
header, err := tr.Next()
if errors.Is(err, io.EOF) {
return entries
}
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(tr)
if err != nil {
t.Fatal(err)
}
entries[header.Name] = string(body)
}
}
// packSwapped writes the archive and fails the test if the outside secret, or the
// content of a file other than the one the walk listed, reached it.
func packSwapped(t *testing.T, payload string, unexpected string) {
t.Helper()
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err != nil {
t.Logf("refused: %v", err)
return
}
for name, body := range readArchiveEntries(t, archivePath) {
if strings.Contains(body, unexpected) {
t.Fatalf("archive entry %s holds %q, read through a swapped path", name, body)
}
}
t.Fatal("the archive was written although a path changed under the packer")
}
// A directory swapped for a symlink to an outside directory after it was listed and
// an earlier child packed: its later children must not be read through the link.
func TestTaskArchivePackageDirSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(outside, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A regular file swapped for a symlink to an outside file after it was listed.
func TestTaskArchivePackageFileSwappedForOutsideSymlink(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
target := filepath.Join(payload, "main", "zzz", "jwt.key")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Remove(target); err != nil {
return err
}
return os.Symlink(filepath.Join(outside, "jwt.key"), target)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a relative symlink climbing out with ../ segments.
func TestTaskArchivePackageDirSwappedForDotDotSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("../../keys", dir)
})
packSwapped(t, payload, archiveOutsideSecret)
}
// A directory swapped for a symlink after its parent was listed but before the walk
// descends into it (outside and ../ targets): listing its children must not leave the
// payload either. The same-file check cannot catch this case, because the children
// would be listed and opened through the same link.
func TestTaskArchivePackageDirSwappedBeforeDescent(t *testing.T) {
for name, link := range map[string]string{"outside": "", "dotdot": "../../keys"} {
t.Run(name, func(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.WriteFile(filepath.Join(payload, "main", "a_first"), []byte("earlier file"), 0o600); err != nil {
t.Fatal(err)
}
target := link
if target == "" {
target = outside
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/a_first", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink(target, dir)
})
packSwapped(t, payload, archiveOutsideSecret)
})
}
}
// A directory swapped for a symlink that stays inside the payload: the file opened
// is not the one the walk listed, so it is refused rather than packed under the
// listed name.
func TestTaskArchivePackageDirSwappedForInsideSymlink(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
other := filepath.Join(payload, "main", "other")
if err := os.MkdirAll(other, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(other, "jwt.key"), []byte(sameSizeAsSecret("o")), 0o600); err != nil {
t.Fatal(err)
}
dir := filepath.Join(payload, "main", "zzz")
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
if err := os.Rename(dir, dir+".original"); err != nil {
return err
}
return os.Symlink("other", dir)
})
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
if err == nil {
got := readArchiveEntries(t, archivePath)["main/zzz/jwt.key"]
t.Fatalf("archive written with main/zzz/jwt.key = %q after the directory was swapped", got)
}
t.Logf("refused: %v", err)
}
// Symlinks already present to an outside file and an outside directory are skipped:
// neither the file nor the directory's children are packed.
func TestTaskArchivePackageSkipsOutsideSymlinks(t *testing.T) {
payload, outside := archiveSymlinkFixture(t)
if err := os.Symlink(filepath.Join(outside, "jwt.key"), filepath.Join(payload, "main", "key-link")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(payload, "main", "keys-link")); err != nil {
t.Fatal(err)
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive should skip symlinks, not fail: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for name, body := range entries {
if strings.Contains(body, archiveOutsideSecret) || strings.HasPrefix(name, "main/key") {
t.Fatalf("outside symlink packed as %s = %q", name, body)
}
}
if entries["main/zzz/jwt.key"] != sameSizeAsSecret("d") {
t.Fatalf("regular file not packed: %q", entries["main/zzz/jwt.key"])
}
}
// File and directory names that are not valid UTF-8 are packed as before: a run tree
// may hold them (tool output, extracted target data), and refusing them would make
// the task impossible to archive.
func TestTaskArchivePackageKeepsNonUTF8Names(t *testing.T) {
payload, _ := archiveSymlinkFixture(t)
dir := filepath.Join(payload, "main", "\xfe-dir")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for _, path := range []string{filepath.Join(payload, "main", "\xff\xfe.txt"), filepath.Join(dir, "inner.txt")} {
if err := os.WriteFile(path, []byte("body"), 0o600); err != nil {
t.Fatal(err)
}
}
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
t.Fatalf("archive with non-UTF-8 names failed: %v", err)
}
entries := readArchiveEntries(t, archivePath)
for _, name := range []string{"main/\xff\xfe.txt", "main/\xfe-dir/inner.txt"} {
if entries[name] != "body" {
t.Fatalf("entry %q = %q, want body", name, entries[name])
}
}
}
// Restoring never creates a link or writes outside the destination: a symlink or hard
// link entry followed by a regular entry written through it, and nested ../ names.
func TestTaskArchiveExtractRefusesLinksAndNestedTraversal(t *testing.T) {
type entry struct {
header tar.Header
body string
}
reg := func(name string) entry {
return entry{tar.Header{Name: name, Mode: 0o600, Size: 5, Typeflag: tar.TypeReg}, "pwned"}
}
cases := map[string][]entry{
"symlink then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE", Typeflag: tar.TypeSymlink, Mode: 0o777}},
reg("link/pwned"),
},
"hard link then write through it": {
{header: tar.Header{Name: "link", Linkname: "OUTSIDE/pwned", Typeflag: tar.TypeLink, Mode: 0o600}},
reg("link"),
},
"nested dotdot": {reg("a/../../pwned")},
"deep nested dotdot": {reg("a/b/../../../pwned")},
"dotdot after directory": {{header: tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o700}}, reg("a/../../pwned")},
}
for name, entries := range cases {
t.Run(name, func(t *testing.T) {
base := t.TempDir()
outside := filepath.Join(base, "outside")
if err := os.MkdirAll(outside, 0o755); err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
encoder, err := zstd.NewWriter(&compressed)
if err != nil {
t.Fatal(err)
}
tw := tar.NewWriter(encoder)
for _, e := range entries {
header := e.header
header.Linkname = strings.ReplaceAll(header.Linkname, "OUTSIDE", outside)
if err := tw.WriteHeader(&header); err != nil {
t.Fatal(err)
}
if e.body != "" {
if _, err := tw.Write([]byte(e.body)); err != nil {
t.Fatal(err)
}
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
if err := encoder.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(base, "malicious.tar.zst")
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
destination := filepath.Join(base, "restore", "dest")
if err := extractTaskArchivePackage(path, "", destination); err == nil {
t.Fatal("unsafe archive was accepted")
}
for _, escaped := range []string{
filepath.Join(outside, "pwned"),
filepath.Join(base, "restore", "pwned"),
filepath.Join(base, "pwned"),
} {
if _, err := os.Lstat(escaped); !os.IsNotExist(err) {
t.Fatalf("extraction wrote %s: %v", escaped, err)
}
}
if _, err := os.Lstat(filepath.Join(destination, "link")); !os.IsNotExist(err) {
t.Fatalf("extraction created a link entry: %v", err)
}
})
}
}

Some files were not shown because too many files have changed in this diff Show More