mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 06:33:57 +08:00
Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aeb094d5ef | ||
|
|
eb05248804 | ||
|
|
130fe9a0c4 | ||
|
|
e4f6de91d2 | ||
|
|
6f544185cf | ||
|
|
c03939c1b1 | ||
|
|
6e4c6e7da1 | ||
|
|
dc828a3251 | ||
|
|
f4ce2669aa | ||
|
|
e7c36f7a6a | ||
|
|
f8f61f1c97 | ||
|
|
3407f8b0a7 | ||
|
|
403bb1f4b3 | ||
|
|
ad7082d339 | ||
|
|
025b40f221 | ||
|
|
d497bd1e65 | ||
|
|
557ff1cd0e | ||
|
|
eb11d03e29 | ||
|
|
ef60f226db | ||
|
|
8a1a7b36ef | ||
|
|
6089691658 | ||
|
|
4794d1e4d3 | ||
|
|
c7b52f297f | ||
|
|
9eba087697 | ||
|
|
e39bf0ff08 | ||
|
|
0885bdd720 | ||
|
|
4fda8db604 | ||
|
|
972219f887 | ||
|
|
443cf894da | ||
|
|
e724364da7 | ||
|
|
953c361f80 | ||
|
|
2bc5baebbb | ||
|
|
f3c961db36 | ||
|
|
3eedbdc326 | ||
|
|
3666be70e8 | ||
|
|
2b3ed3829c | ||
|
|
9dd540f188 | ||
|
|
de80783e16 | ||
|
|
9fc8fd6bd1 | ||
|
|
8379522e4c | ||
|
|
f8c639565a | ||
|
|
a4f031c852 | ||
|
|
bdc762854f | ||
|
|
7dd9fcfa32 | ||
|
|
7a07c64118 | ||
|
|
832cdda1e4 | ||
|
|
c8f27c7f3c | ||
|
|
b9bc78f20e | ||
|
|
a383e5bcb2 | ||
|
|
2e516c5125 | ||
|
|
0ab3b9ef23 | ||
|
|
a969dc51bc | ||
|
|
507309c94d | ||
|
|
d92a02faef | ||
|
|
cda87d8dfc | ||
|
|
2f065a958e | ||
|
|
95afea7d5c | ||
|
|
1c262d3af6 | ||
|
|
37e4bb7f2f | ||
|
|
e9d6c48737 | ||
|
|
66dc0da802 | ||
|
|
5b711855a1 | ||
|
|
eb045647cf | ||
|
|
fe121a2cea | ||
|
|
693825946e | ||
|
|
611f232201 | ||
|
|
60eaf6719d | ||
|
|
7dbf935f79 |
@@ -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.
|
||||
|
||||
@@ -6,6 +6,9 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **`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 +21,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
@@ -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
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-3
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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()
|
||||
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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();
|
||||
@@ -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;
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -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 |
|
||||
|---|---|---|
|
||||
|
||||
@@ -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, ""
|
||||
}
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
+13
-6
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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})
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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) {})
|
||||
}
|
||||
@@ -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
@@ -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 +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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// When the tools table cannot be read, Auto's nil base list must come back as
|
||||
// an empty list: Norma reads nil as "install my own unconfined default tools".
|
||||
func TestToolResolveCatalogFailureReturnsEmptyList(t *testing.T) {
|
||||
sqlDB, err := sql.Open("pgx", "postgres://127.0.0.1:1/unused?sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = sqlDB.Close() // every query now fails without touching the network
|
||||
oldBinding, oldCapture := agent.FindingTrafficBindingEnabled(), agent.TrafficCaptureEnabled()
|
||||
t.Cleanup(func() {
|
||||
agent.SetToolResolve(nil)
|
||||
agent.SetFindingTrafficBindingEnabled(oldBinding)
|
||||
agent.SetTrafficCaptureEnabled(oldCapture)
|
||||
})
|
||||
wireTools(&db.DB{DB: sqlDB}, nil)
|
||||
|
||||
got := agent.ToolResolve()(context.Background(), "auto", nil)
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("catalogue failure returned %#v, want an empty non-nil list", got)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -13,7 +13,7 @@
|
||||
"check:fix": "biome check --write",
|
||||
"prepare": "cd .. && husky web/.husky",
|
||||
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
|
||||
"test:polling": "node --test scripts/polling.test.mjs",
|
||||
"test:polling": "node --import ./scripts/register-alias.mjs --test scripts/polling.test.mjs src/lib/target-gate-posture.test.mjs src/lib/mock/posture-integration.test.mjs",
|
||||
"test:replay": "node --test scripts/replay.test.mjs",
|
||||
"test:tamper-hooks": "node --test scripts/tamper-hooks.test.mjs",
|
||||
"test:upload": "node --test scripts/upload.test.mjs",
|
||||
@@ -25,7 +25,7 @@
|
||||
"test:navigation": "node --test src/lib/navigation.test.mjs",
|
||||
"test:chat-filter": "node --test src/lib/chat-agent-filter.test.mjs",
|
||||
"test:openai-compatible": "node --test src/lib/openai-compatible.test.mjs",
|
||||
"test:reducers": "node --import ./scripts/register-alias.mjs --test \"src/lib/reducers/*.test.mjs\" \"src/**/_state/*.test.mjs\"",
|
||||
"test:reducers": "node --import ./scripts/register-alias.mjs --test \"src/lib/reducers/*.test.mjs\" \"src/**/_state/*.test.mjs\" src/lib/utils.test.mjs",
|
||||
"test:activity-merge": "node --test src/lib/activity-merge.test.mjs",
|
||||
"test:chat-mentions": "node --test src/lib/chat-mentions.test.mjs",
|
||||
"test:format": "node --test src/lib/format.test.mjs",
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// "@/..." path alias (tsconfig "paths") to src/, adding the ".ts" extension that the
|
||||
// bundler normally infers. Registered by scripts/register-alias.mjs.
|
||||
|
||||
import ts from "typescript";
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
const SRC = new URL("../src/", import.meta.url);
|
||||
|
||||
export async function resolve(specifier, context, nextResolve) {
|
||||
@@ -15,5 +19,37 @@ export async function resolve(specifier, context, nextResolve) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (context.parentURL && (specifier.startsWith("./") || specifier.startsWith("../"))) {
|
||||
try {
|
||||
return await nextResolve(specifier, context);
|
||||
} catch (error) {
|
||||
const base = new URL(specifier, context.parentURL).href;
|
||||
for (const candidate of [`${base}.ts`, `${base}.tsx`, `${base}/index.ts`]) {
|
||||
try {
|
||||
return await nextResolve(candidate, context);
|
||||
} catch {
|
||||
// try the next TypeScript path
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return nextResolve(specifier, context);
|
||||
}
|
||||
|
||||
// The bundler imports locale JSON (src/i18n) without `with { type: "json" }`; Node requires the
|
||||
// attribute, so add it here. This lets tests import modules that depend on @/i18n (e.g. @/lib/utils).
|
||||
export async function load(url, context, nextLoad) {
|
||||
if (url.endsWith(".ts") || url.endsWith(".tsx")) {
|
||||
const source = await readFile(new URL(url), "utf8");
|
||||
const output = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
|
||||
fileName: url,
|
||||
}).outputText;
|
||||
return { format: "module", shortCircuit: true, source: output };
|
||||
}
|
||||
if (url.endsWith(".json") && context.importAttributes?.type !== "json") {
|
||||
return nextLoad(url, { ...context, importAttributes: { ...context.importAttributes, type: "json" } });
|
||||
}
|
||||
return nextLoad(url, context);
|
||||
}
|
||||
|
||||
@@ -152,6 +152,27 @@ test("apiFetch sends the bearer token and keeps the caller's headers", async ()
|
||||
assert.equal(b.window.location.href, "/tasks");
|
||||
});
|
||||
|
||||
test("apiFetch keeps credentials same-origin and refuses redirects, even if the caller asks otherwise", async () => {
|
||||
const b = browser(() => ({ status: 200, body: "{}" }));
|
||||
await b.apiFetch("/tasks", { credentials: "include", redirect: "follow" });
|
||||
assert.equal(b.requests[0].init.credentials, "same-origin");
|
||||
assert.equal(b.requests[0].init.redirect, "error");
|
||||
});
|
||||
|
||||
test("clearToken expires the cookie with the attributes setToken writes", () => {
|
||||
for (const protocol of ["https:", "http:"]) {
|
||||
const b = browser(() => assert.fail("no request expected"), protocol);
|
||||
b.auth.clearToken();
|
||||
assert.equal(b.storage.has("artex_token"), false);
|
||||
assert.ok(b.document.cookie.startsWith("artex_token=;"), b.document.cookie);
|
||||
assert.ok(b.document.cookie.includes("max-age=0"));
|
||||
assert.ok(b.document.cookie.includes("path=/"));
|
||||
assert.ok(b.document.cookie.includes("SameSite=Lax"));
|
||||
assert.equal(b.document.cookie.includes("; Secure"), protocol === "https:");
|
||||
assert.equal(b.window.location.href, "/tasks");
|
||||
}
|
||||
});
|
||||
|
||||
// http() and every API call that used to call fetch itself.
|
||||
const callers = {
|
||||
"http()": (b) => b.http("/tasks"),
|
||||
|
||||
@@ -104,3 +104,11 @@ test("decodeTraceAfter decodes base64 UTF-8 and isTraceLineMasked flags HMAC-mas
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("parseRawResponse reads the status of a recorded head without an HTTP version", () => {
|
||||
// The traffic recorder stores the response head as "HTTP <status>" (traffic.go).
|
||||
const r = hooks.parseRawResponse("HTTP 404\nContent-Type: text/plain\n\nnot found");
|
||||
assert.equal(r.status, 404);
|
||||
assert.deepEqual(plain(r.headers), { "Content-Type": ["text/plain"] });
|
||||
assert.equal(r.body, "not found");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type LoginForm = {
|
||||
password: string;
|
||||
agreed: boolean;
|
||||
};
|
||||
|
||||
export type LoginTerms = {
|
||||
open: boolean;
|
||||
readToEnd: boolean;
|
||||
};
|
||||
|
||||
export type LoginStatus = {
|
||||
checking: boolean;
|
||||
submitting: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type LoginPageState = {
|
||||
form: LoginForm;
|
||||
terms: LoginTerms;
|
||||
status: LoginStatus;
|
||||
};
|
||||
|
||||
export type LoginPageAction =
|
||||
| { type: "formChanged"; patch: Partial<LoginForm> }
|
||||
| { type: "termsChanged"; patch: Partial<LoginTerms> }
|
||||
| { type: "termsAgreed" }
|
||||
| { type: "statusCheckFailed"; error: string }
|
||||
| { type: "statusChecked" }
|
||||
| { type: "validationFailed"; error: string }
|
||||
| { type: "submitStarted" }
|
||||
| { type: "submitFailed"; error: string }
|
||||
| { type: "submitFinished" };
|
||||
|
||||
export const initialLoginPageState: LoginPageState = {
|
||||
form: { password: "", agreed: false },
|
||||
terms: { open: false, readToEnd: false },
|
||||
status: { checking: true, submitting: false, error: "" },
|
||||
};
|
||||
|
||||
function withStatus(state: LoginPageState, patch: Partial<LoginStatus>): LoginPageState {
|
||||
return setSlice(state, "status", mergePatch(state.status, patch));
|
||||
}
|
||||
|
||||
export function loginPageReducer(state: LoginPageState, action: LoginPageAction): LoginPageState {
|
||||
switch (action.type) {
|
||||
case "formChanged":
|
||||
return setSlice(state, "form", mergePatch(state.form, action.patch));
|
||||
case "termsChanged":
|
||||
return setSlice(state, "terms", mergePatch(state.terms, action.patch));
|
||||
case "termsAgreed":
|
||||
return { ...state, form: { ...state.form, agreed: true }, status: { ...state.status, error: "" } };
|
||||
case "statusCheckFailed":
|
||||
case "validationFailed":
|
||||
case "submitFailed":
|
||||
return withStatus(state, { error: action.error });
|
||||
case "statusChecked":
|
||||
return withStatus(state, { checking: false });
|
||||
case "submitStarted":
|
||||
return withStatus(state, { submitting: true, error: "" });
|
||||
case "submitFinished":
|
||||
return withStatus(state, { submitting: false });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useReducer, useRef } from "react";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
@@ -15,30 +15,30 @@ import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
import { initialLoginPageState, loginPageReducer } from "./_state/login-page.reducer";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checking, setChecking] = useState(true);
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [termsOpen, setTermsOpen] = useState(false);
|
||||
const [readToEnd, setReadToEnd] = useState(false);
|
||||
const [state, dispatch] = useReducer(loginPageReducer, initialLoginPageState);
|
||||
const { password, agreed } = state.form;
|
||||
const { open: termsOpen, readToEnd } = state.terms;
|
||||
const { checking, submitting: loading, error } = state.status;
|
||||
const termsBodyRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Scroll to the bottom of the terms (including when everything fits without scrolling) to unlock "Agree".
|
||||
function handleTermsScroll() {
|
||||
const el = termsBodyRef.current;
|
||||
if (!el) return;
|
||||
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 8) setReadToEnd(true);
|
||||
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 8)
|
||||
dispatch({ type: "termsChanged", patch: { readToEnd: true } });
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!termsOpen) return;
|
||||
// Reset on open, and cover the case where the content is shorter than one screen and never fires a scroll.
|
||||
setReadToEnd(false);
|
||||
dispatch({ type: "termsChanged", patch: { readToEnd: false } });
|
||||
const el = termsBodyRef.current;
|
||||
if (el && el.scrollHeight <= el.clientHeight + 8) setReadToEnd(true);
|
||||
if (el && el.scrollHeight <= el.clientHeight + 8) dispatch({ type: "termsChanged", patch: { readToEnd: true } });
|
||||
}, [termsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -56,26 +56,25 @@ export default function LoginPage() {
|
||||
.then(({ initialized }) => {
|
||||
if (!initialized) router.replace("/setup");
|
||||
})
|
||||
.catch(() => setError(t("Unable to connect to the backend service")))
|
||||
.finally(() => setChecking(false));
|
||||
.catch(() => dispatch({ type: "statusCheckFailed", error: t("Unable to connect to the backend service") }))
|
||||
.finally(() => dispatch({ type: "statusChecked" }));
|
||||
}, [router]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!agreed) {
|
||||
setError(t("Please read and agree to the Terms of Use first"));
|
||||
dispatch({ type: "validationFailed", error: t("Please read and agree to the Terms of Use first") });
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "submitStarted" });
|
||||
try {
|
||||
const { token } = await api.login("ARTEX", password);
|
||||
auth.setToken(token);
|
||||
window.location.replace("/function/tasks");
|
||||
} catch {
|
||||
setError(t("Incorrect username or password"));
|
||||
dispatch({ type: "submitFailed", error: t("Incorrect username or password") });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
dispatch({ type: "submitFinished" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +130,7 @@ export default function LoginPage() {
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "formChanged", patch: { password: e.target.value } })}
|
||||
placeholder={t("Enter your password")}
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
@@ -141,14 +140,14 @@ export default function LoginPage() {
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={agreed}
|
||||
onCheckedChange={(v) => setAgreed(v === true)}
|
||||
onCheckedChange={(v) => dispatch({ type: "formChanged", patch: { agreed: v === true } })}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<Label htmlFor="agree-terms" className="text-sm font-normal leading-relaxed text-muted-foreground">
|
||||
{agreeBefore}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTermsOpen(true)}
|
||||
onClick={() => dispatch({ type: "termsChanged", patch: { open: true } })}
|
||||
className="mx-0.5 font-medium text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
{t("Terms of Use")}
|
||||
@@ -164,7 +163,7 @@ export default function LoginPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Dialog open={termsOpen} onOpenChange={setTermsOpen}>
|
||||
<Dialog open={termsOpen} onOpenChange={(open) => dispatch({ type: "termsChanged", patch: { open } })}>
|
||||
<DialogContent className="gap-0 p-0 sm:max-w-2xl">
|
||||
<DialogHeader className="flex-row items-center gap-3 border-b px-6 py-4">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||
@@ -339,14 +338,7 @@ export default function LoginPage() {
|
||||
{readToEnd ? t("You have read all the terms") : t("Scroll the terms to the bottom to confirm")}
|
||||
</p>
|
||||
<DialogClose asChild>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!readToEnd}
|
||||
onClick={() => {
|
||||
setAgreed(true);
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
<Button type="button" disabled={!readToEnd} onClick={() => dispatch({ type: "termsAgreed" })}>
|
||||
{t("I have read and agree to all the terms")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type SetupForm = {
|
||||
password: string;
|
||||
confirm: string;
|
||||
setupToken: string;
|
||||
};
|
||||
|
||||
export type SetupStatus = {
|
||||
checking: boolean;
|
||||
/**
|
||||
* The initialization state could not be fetched. Do not default to "not initialized": that would show the setup
|
||||
* form to an instance that already has a password, and following it would overwrite the original.
|
||||
*/
|
||||
unavailable: boolean;
|
||||
submitting: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type SetupPageState = {
|
||||
form: SetupForm;
|
||||
status: SetupStatus;
|
||||
};
|
||||
|
||||
export type SetupPageAction =
|
||||
| { type: "formFieldChanged"; patch: Partial<SetupForm> }
|
||||
| { type: "statusCheckFailed"; error: string }
|
||||
| { type: "statusChecked" }
|
||||
| { type: "validationFailed"; error: string }
|
||||
| { type: "submitStarted" }
|
||||
| { type: "submitFailed"; error: string }
|
||||
| { type: "submitFinished" };
|
||||
|
||||
export const initialSetupPageState: SetupPageState = {
|
||||
form: { password: "", confirm: "", setupToken: "" },
|
||||
status: { checking: true, unavailable: false, submitting: false, error: "" },
|
||||
};
|
||||
|
||||
function withStatus(state: SetupPageState, patch: Partial<SetupStatus>): SetupPageState {
|
||||
return setSlice(state, "status", mergePatch(state.status, patch));
|
||||
}
|
||||
|
||||
export function setupPageReducer(state: SetupPageState, action: SetupPageAction): SetupPageState {
|
||||
switch (action.type) {
|
||||
case "formFieldChanged":
|
||||
return setSlice(state, "form", mergePatch(state.form, action.patch));
|
||||
case "statusCheckFailed":
|
||||
return withStatus(state, { error: action.error, unavailable: true });
|
||||
case "statusChecked":
|
||||
return withStatus(state, { checking: false });
|
||||
case "validationFailed":
|
||||
case "submitFailed":
|
||||
return withStatus(state, { error: action.error });
|
||||
case "submitStarted":
|
||||
return withStatus(state, { submitting: true, error: "" });
|
||||
case "submitFinished":
|
||||
return withStatus(state, { submitting: false });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useReducer } from "react";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
@@ -11,17 +11,15 @@ import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
import { initialSetupPageState, setupPageReducer } from "./_state/setup-page.reducer";
|
||||
|
||||
export default function SetupPage() {
|
||||
const router = useRouter();
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [setupToken, setSetupToken] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checking, setChecking] = useState(true);
|
||||
const [state, dispatch] = useReducer(setupPageReducer, initialSetupPageState);
|
||||
const { password, confirm, setupToken } = state.form;
|
||||
// when the initialization state cannot be fetched, do not default to "not initialized" — that would show the setup form to an
|
||||
// instance that already has a password, and following it would overwrite the original. Close the entrance instead.
|
||||
const [unavailable, setUnavailable] = useState(false);
|
||||
const { checking, unavailable, submitting: loading, error } = state.status;
|
||||
|
||||
useEffect(() => {
|
||||
api
|
||||
@@ -30,32 +28,33 @@ export default function SetupPage() {
|
||||
if (initialized) router.replace("/login");
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : t("Unable to connect to the backend service"));
|
||||
setUnavailable(true);
|
||||
dispatch({
|
||||
type: "statusCheckFailed",
|
||||
error: err instanceof Error ? err.message : t("Unable to connect to the backend service"),
|
||||
});
|
||||
})
|
||||
.finally(() => setChecking(false));
|
||||
.finally(() => dispatch({ type: "statusChecked" }));
|
||||
}, [router]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (password !== confirm) {
|
||||
setError(t("The two passwords do not match"));
|
||||
dispatch({ type: "validationFailed", error: t("The two passwords do not match") });
|
||||
return;
|
||||
}
|
||||
if (password.length < 12) {
|
||||
setError(t("Password must be at least 12 characters"));
|
||||
dispatch({ type: "validationFailed", error: t("Password must be at least 12 characters") });
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "submitStarted" });
|
||||
try {
|
||||
const { token } = await api.initPassword(password, setupToken.trim());
|
||||
auth.setToken(token);
|
||||
router.replace("/function/tasks");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t("Initialization failed"));
|
||||
dispatch({ type: "submitFailed", error: err instanceof Error ? err.message : t("Initialization failed") });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
dispatch({ type: "submitFinished" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +107,7 @@ export default function SetupPage() {
|
||||
<Input
|
||||
id="setup-token"
|
||||
value={setupToken}
|
||||
onChange={(e) => setSetupToken(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { setupToken: e.target.value } })}
|
||||
placeholder={t("Printed in the server log at startup")}
|
||||
autoFocus
|
||||
autoComplete="off"
|
||||
@@ -120,7 +119,7 @@ export default function SetupPage() {
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { password: e.target.value } })}
|
||||
placeholder={t("At least 12 characters")}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
@@ -131,7 +130,7 @@ export default function SetupPage() {
|
||||
id="confirm"
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { confirm: e.target.value } })}
|
||||
placeholder={t("Enter the password again")}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { AccountSwitcher } from "./sidebar/account-switcher";
|
||||
import { LayoutControls } from "./sidebar/layout-controls";
|
||||
import { SearchDialog } from "./sidebar/search-dialog";
|
||||
import { ThemeSwitcher } from "./sidebar/theme-switcher";
|
||||
import { TargetGatePostureBanner } from "./target-gate-posture-banner";
|
||||
|
||||
// Task detail pages stay as-is: they bring their own header/Tabs and padding, so no extra global header or padding is stacked here.
|
||||
function isFullBleed(pathname: string) {
|
||||
@@ -99,6 +100,7 @@ export function MainContent({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
{isolationBanner}
|
||||
<TargetGatePostureBanner />
|
||||
{updateBanner}
|
||||
{children}
|
||||
</>
|
||||
@@ -108,6 +110,7 @@ export function MainContent({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
{isolationBanner}
|
||||
<TargetGatePostureBanner />
|
||||
{updateBanner}
|
||||
<header
|
||||
className={cn(
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import { t } from "@/i18n";
|
||||
import { api, TARGET_GATE_POSTURE_REFRESH_EVENT } from "@/lib/api";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { createPostureRefresher } from "@/lib/target-gate-posture";
|
||||
|
||||
type Posture = { kind: "loading" } | { kind: "unavailable" } | { kind: "ready"; ungated: number; optedOut: number };
|
||||
|
||||
// A gate change is a security decision. Read the committed DB state instead of
|
||||
// reusing the startup warning, and keep a failed read visibly unknown.
|
||||
export function TargetGatePostureBanner() {
|
||||
const [posture, setPosture] = useState<Posture>({ kind: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
const refresher = createPostureRefresher(
|
||||
(signal) => api.targetGatePosture(signal),
|
||||
(result) => {
|
||||
if (
|
||||
!Number.isSafeInteger(result.ungated_unfinished_tasks) ||
|
||||
!Number.isSafeInteger(result.explicit_opt_out_tasks) ||
|
||||
result.ungated_unfinished_tasks < 0 ||
|
||||
result.explicit_opt_out_tasks < 0 ||
|
||||
result.explicit_opt_out_tasks > result.ungated_unfinished_tasks
|
||||
) {
|
||||
setPosture({ kind: "unavailable" });
|
||||
return;
|
||||
}
|
||||
setPosture({
|
||||
kind: "ready",
|
||||
ungated: result.ungated_unfinished_tasks,
|
||||
optedOut: result.explicit_opt_out_tasks,
|
||||
});
|
||||
},
|
||||
() => setPosture({ kind: "unavailable" }),
|
||||
);
|
||||
|
||||
void refresher.refresh();
|
||||
const stop = setVisibleInterval(refresher.refresh, 15_000);
|
||||
window.addEventListener("focus", refresher.refresh);
|
||||
window.addEventListener(TARGET_GATE_POSTURE_REFRESH_EVENT, refresher.refresh);
|
||||
return () => {
|
||||
refresher.dispose();
|
||||
stop();
|
||||
window.removeEventListener("focus", refresher.refresh);
|
||||
window.removeEventListener(TARGET_GATE_POSTURE_REFRESH_EVENT, refresher.refresh);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (posture.kind === "loading" || (posture.kind === "ready" && posture.ungated === 0)) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex shrink-0 flex-wrap items-center justify-center gap-x-2 border-amber-500/40 border-b bg-amber-500/10 px-4 py-1 text-amber-900 text-xs dark:text-amber-200"
|
||||
>
|
||||
<span>
|
||||
{posture.kind === "unavailable"
|
||||
? t("Target-gate status is unavailable. Check task settings before proceeding.")
|
||||
: t(
|
||||
"Target approvals are off for {count} unfinished tasks ({optOut} explicit opt-outs). Other network controls apply separately.",
|
||||
{
|
||||
count: posture.ungated,
|
||||
optOut: posture.optedOut,
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
<Link prefetch={false} href="/function/tasks" className="font-medium underline underline-offset-2">
|
||||
{t("View tasks")}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { CONVERSATION_LIST_PAGE, chatPageReducer, initChatPageState } from "./chat-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const conv = (id, agent_key = "auto", pinned = false) => ({ id, agent_key, pinned });
|
||||
const reduce = (actions, state = initChatPageState()) => actions.reduce(chatPageReducer, state);
|
||||
const loaded = (items) => [{ type: "list/loaded", items }, { type: "list/loadFinished" }];
|
||||
|
||||
test("a started conversation is inserted above the first unpinned row", () => {
|
||||
const s = reduce([
|
||||
...loaded([conv(1, "auto", true), conv(2), conv(3)]),
|
||||
{ type: "conversationStarted", conversation: conv(9), pending: { input: "hi" } },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
s.list.items.map((c) => c.id),
|
||||
[1, 9, 2, 3],
|
||||
);
|
||||
assert.deepEqual(s.pendingByConv[9], { input: "hi" });
|
||||
});
|
||||
|
||||
test("a started conversation clears a filter that would hide it", () => {
|
||||
const s = reduce([
|
||||
{ type: "agentFilterChanged", agentFilter: "web" },
|
||||
{ type: "conversationStarted", conversation: conv(4, "auto") },
|
||||
]);
|
||||
assert.equal(s.sidebar.agentFilter, null);
|
||||
});
|
||||
|
||||
test("changing the agent filter resets paging, selection, dialog and rename", () => {
|
||||
const s = reduce([
|
||||
...loaded([conv(1), conv(2)]),
|
||||
{ type: "moreConversationsShown" },
|
||||
{ type: "selection/set", ids: [1, 2] },
|
||||
{ type: "bulkDeleteOpenChanged", open: true },
|
||||
{ type: "renameChanged", patch: { id: 1, text: "old" } },
|
||||
{ type: "agentFilterChanged", agentFilter: "auto" },
|
||||
]);
|
||||
assert.equal(s.sidebar.visibleCount, CONVERSATION_LIST_PAGE);
|
||||
assert.equal(s.selection.size, 0);
|
||||
assert.equal(s.bulkDeleteOpen, false);
|
||||
assert.equal(s.rename.id, null);
|
||||
assert.equal(s.rename.text, "old");
|
||||
});
|
||||
|
||||
test("deleting a conversation unchecks it; deleting an unchecked one keeps the state", () => {
|
||||
const s = reduce([
|
||||
{ type: "selection/set", ids: [1, 2] },
|
||||
{ type: "conversationDeleted", id: 2 },
|
||||
]);
|
||||
assert.deepEqual([...s.selection], [1]);
|
||||
assert.equal(chatPageReducer(s, { type: "conversationDeleted", id: 7 }), s);
|
||||
});
|
||||
|
||||
test("bulk delete keeps selection mode only when some deletes failed", () => {
|
||||
const base = reduce([
|
||||
{ type: "selectionModeEntered" },
|
||||
{ type: "selection/set", ids: [1, 2, 3] },
|
||||
{ type: "bulkDeleteOpenChanged", open: true },
|
||||
]);
|
||||
const partial = chatPageReducer(base, { type: "bulkDeleteSettled", deleted: [1, 2], allSucceeded: false });
|
||||
assert.deepEqual([...partial.selection], [3]);
|
||||
assert.equal(partial.selectionMode, true);
|
||||
assert.equal(partial.bulkDeleteOpen, false);
|
||||
const full = chatPageReducer(base, { type: "bulkDeleteSettled", deleted: [1, 2, 3], allSucceeded: true });
|
||||
assert.equal(full.selectionMode, false);
|
||||
assert.equal(full.selection.size, 0);
|
||||
});
|
||||
|
||||
test("an unchanged list poll keeps the same state; a changed row is updated", () => {
|
||||
const s = reduce(loaded([conv(1), conv(2)]));
|
||||
assert.equal(reduce(loaded([conv(1), conv(2)]), s), s);
|
||||
const renamed = reduce(loaded([conv(1), { ...conv(2), title: "renamed" }]), s);
|
||||
assert.equal(renamed.list.items[1].title, "renamed");
|
||||
assert.equal(renamed.list.items[0].id, 1);
|
||||
});
|
||||
|
||||
test("an empty first load still marks the list loaded", () => {
|
||||
assert.equal(reduce(loaded([])).list.loaded, true);
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
|
||||
|
||||
export const CONVERSATION_LIST_PAGE = 100;
|
||||
|
||||
export type ChatPageRequest = "bulkDelete";
|
||||
|
||||
export type PendingHandoff = { input?: string; attachments?: ChatAttachment[] };
|
||||
|
||||
export type ChatCatalog = {
|
||||
agents: Agent[];
|
||||
profiles: LLMProfile[];
|
||||
};
|
||||
|
||||
export type ChatSidebar = {
|
||||
/** null = all agents. */
|
||||
agentFilter: string | null;
|
||||
visibleCount: number;
|
||||
/**
|
||||
* Agent groups the user collapsed. Persisted to localStorage by the page and hydrated
|
||||
* after mount (not in the initial state) so the server and client render the same first pass.
|
||||
*/
|
||||
collapsedAgents: Set<string>;
|
||||
};
|
||||
|
||||
export type ChatRename = {
|
||||
id: number | null;
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type ChatPageState = {
|
||||
catalog: ChatCatalog;
|
||||
list: ListState<Conversation>;
|
||||
sidebar: ChatSidebar;
|
||||
rename: ChatRename;
|
||||
selectionMode: boolean;
|
||||
selection: Set<number>;
|
||||
bulkDeleteOpen: boolean;
|
||||
requests: Requests<ChatPageRequest>;
|
||||
/**
|
||||
* Handoffs keyed by the new conversation id, consumed once by ChatView on mount
|
||||
* (ids never repeat, so leftover entries are harmless).
|
||||
*/
|
||||
pendingByConv: Record<number, PendingHandoff>;
|
||||
};
|
||||
|
||||
export type ChatPageAction =
|
||||
| ListAction<Conversation>
|
||||
| SelectionAction<number>
|
||||
| RequestAction<ChatPageRequest>
|
||||
| { type: "catalogChanged"; patch: Partial<ChatCatalog> }
|
||||
// The selected conversation lives in the URL (?c=); these keep the list in step with it.
|
||||
| { type: "conversationStarted"; conversation: Conversation; pending?: PendingHandoff }
|
||||
| { type: "conversationDeleted"; id: number }
|
||||
// sidebar
|
||||
| { type: "agentFilterChanged"; agentFilter: string | null }
|
||||
| { type: "moreConversationsShown" }
|
||||
| { type: "agentGroupToggled"; key: string }
|
||||
| { type: "collapsedAgentsRestored"; keys: string[] }
|
||||
// rename
|
||||
| { type: "renameChanged"; patch: Partial<ChatRename> }
|
||||
// multi-select + bulk delete
|
||||
| { type: "selectionModeEntered" }
|
||||
| { type: "selectionModeExited" }
|
||||
| { type: "conversationCheckedChanged"; id: number; checked: boolean }
|
||||
| { type: "bulkDeleteOpenChanged"; open: boolean }
|
||||
| { type: "bulkDeleteSettled"; deleted: number[]; allSucceeded: boolean };
|
||||
|
||||
export function initChatPageState(): ChatPageState {
|
||||
return {
|
||||
catalog: { agents: [], profiles: [] },
|
||||
list: createList(),
|
||||
sidebar: { agentFilter: null, visibleCount: CONVERSATION_LIST_PAGE, collapsedAgents: new Set() },
|
||||
rename: { id: null, text: "" },
|
||||
selectionMode: false,
|
||||
selection: new Set(),
|
||||
bulkDeleteOpen: false,
|
||||
requests: createRequests<ChatPageRequest>(["bulkDelete"]),
|
||||
pendingByConv: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function conversationIsPinned(conversation: Conversation): boolean {
|
||||
return conversation.pinned ?? Boolean(conversation.pinned_at);
|
||||
}
|
||||
|
||||
function withoutIds(selection: Set<number>, ids: Iterable<number>): Set<number> {
|
||||
const next = new Set(selection);
|
||||
for (const id of ids) next.delete(id);
|
||||
return next.size === selection.size ? selection : next;
|
||||
}
|
||||
|
||||
// A different agent filter starts a fresh view of the rail: first page, nothing
|
||||
// checked, no open bulk-delete dialog and no rename in progress.
|
||||
function changeAgentFilter(state: ChatPageState, agentFilter: string | null): ChatPageState {
|
||||
return {
|
||||
...state,
|
||||
sidebar: { ...state.sidebar, agentFilter, visibleCount: CONVERSATION_LIST_PAGE },
|
||||
selection: state.selection.size === 0 ? state.selection : new Set(),
|
||||
bulkDeleteOpen: false,
|
||||
rename: state.rename.id === null ? state.rename : { ...state.rename, id: null },
|
||||
};
|
||||
}
|
||||
|
||||
export function chatPageReducer(state: ChatPageState, action: ChatPageAction): ChatPageState {
|
||||
if (isListAction<Conversation>(action)) {
|
||||
if (action.type === "list/loaded" && JSON.stringify(action.items) === JSON.stringify(state.list.items))
|
||||
return state;
|
||||
return setSlice(state, "list", listReducer(state.list, action));
|
||||
}
|
||||
if (isSelectionAction<number>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
if (isRequestAction<ChatPageRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "catalogChanged":
|
||||
return setSlice(state, "catalog", mergePatch(state.catalog, action.patch));
|
||||
|
||||
case "conversationStarted": {
|
||||
const c = action.conversation;
|
||||
const next =
|
||||
state.sidebar.agentFilter !== null && state.sidebar.agentFilter !== c.agent_key
|
||||
? changeAgentFilter(state, null)
|
||||
: state;
|
||||
// Insert the new conversation right away (above the first unpinned row) so the
|
||||
// pane switches to it before the next list poll reconciles titles etc.
|
||||
let list = next.list;
|
||||
if (!list.items.some((item) => item.id === c.id)) {
|
||||
const firstUnpinned = list.items.findIndex((item) => !conversationIsPinned(item));
|
||||
const insertAt = firstUnpinned < 0 ? list.items.length : firstUnpinned;
|
||||
const items = [...list.items.slice(0, insertAt), c, ...list.items.slice(insertAt)];
|
||||
list = { ...list, items, total: list.total + 1 };
|
||||
}
|
||||
return {
|
||||
...next,
|
||||
list,
|
||||
pendingByConv: action.pending ? { ...next.pendingByConv, [c.id]: action.pending } : next.pendingByConv,
|
||||
};
|
||||
}
|
||||
case "conversationDeleted":
|
||||
return setSlice(state, "selection", withoutIds(state.selection, [action.id]));
|
||||
|
||||
case "agentFilterChanged":
|
||||
return changeAgentFilter(state, action.agentFilter);
|
||||
case "moreConversationsShown":
|
||||
return {
|
||||
...state,
|
||||
sidebar: { ...state.sidebar, visibleCount: state.sidebar.visibleCount + CONVERSATION_LIST_PAGE },
|
||||
};
|
||||
case "agentGroupToggled": {
|
||||
const collapsedAgents = new Set(state.sidebar.collapsedAgents);
|
||||
if (!collapsedAgents.delete(action.key)) collapsedAgents.add(action.key);
|
||||
return { ...state, sidebar: { ...state.sidebar, collapsedAgents } };
|
||||
}
|
||||
case "collapsedAgentsRestored":
|
||||
return { ...state, sidebar: { ...state.sidebar, collapsedAgents: new Set(action.keys) } };
|
||||
|
||||
case "renameChanged":
|
||||
return setSlice(state, "rename", mergePatch(state.rename, action.patch));
|
||||
|
||||
case "selectionModeEntered":
|
||||
return state.selectionMode ? state : { ...state, selectionMode: true };
|
||||
case "selectionModeExited":
|
||||
return { ...state, selectionMode: false, selection: state.selection.size === 0 ? state.selection : new Set() };
|
||||
case "conversationCheckedChanged":
|
||||
return setSlice(
|
||||
state,
|
||||
"selection",
|
||||
selectionReducer(state.selection, { type: "selection/changed", ids: [action.id], selected: action.checked }),
|
||||
);
|
||||
case "bulkDeleteOpenChanged":
|
||||
if (action.open === state.bulkDeleteOpen) return state;
|
||||
return { ...state, bulkDeleteOpen: action.open };
|
||||
case "bulkDeleteSettled":
|
||||
// Fully successful → back to the clean list; keep selection mode on if some
|
||||
// failed so the user can retry the remaining ones.
|
||||
return {
|
||||
...state,
|
||||
selection: withoutIds(state.selection, action.deleted),
|
||||
bulkDeleteOpen: false,
|
||||
selectionMode: action.allSucceeded ? false : state.selectionMode,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { chatViewReducer, initChatViewState } from "./chat-view.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const act = (seq, kind = "text") => ({ seq, kind, ts: "" });
|
||||
const reduce = (actions, state = initChatViewState(undefined)) => actions.reduce(chatViewReducer, state);
|
||||
const seqs = (state) => state.transcript.messages.map((a) => a.seq);
|
||||
|
||||
test("latest history merges with live messages that arrived first and keeps running", () => {
|
||||
const s = reduce([
|
||||
{ type: "messagesPolled", items: [act(5), act(6)], running: true },
|
||||
{ type: "latestHistoryLoaded", items: [act(3), act(5)], hasMore: true, running: false },
|
||||
]);
|
||||
assert.deepEqual(seqs(s), [3, 5, 6]);
|
||||
assert.equal(s.transcript.running, true);
|
||||
assert.equal(s.transcript.hasMore, true);
|
||||
assert.equal(s.transcript.historyLoaded, true);
|
||||
});
|
||||
|
||||
test("an idle poll returns the same state", () => {
|
||||
const s = reduce([{ type: "transcriptChanged", patch: { running: true } }]);
|
||||
assert.equal(chatViewReducer(s, { type: "messagesPolled", items: [], running: true }), s);
|
||||
assert.equal(chatViewReducer(s, { type: "messagesPolled", items: [], running: false }).transcript.running, false);
|
||||
});
|
||||
|
||||
test("older pages prepend without duplicates", () => {
|
||||
const s = reduce([
|
||||
{ type: "latestHistoryLoaded", items: [act(10), act(11)], hasMore: true, running: false },
|
||||
{ type: "olderHistoryMerged", items: [act(8), act(10)], hasMore: false },
|
||||
]);
|
||||
assert.deepEqual(seqs(s), [8, 10, 11]);
|
||||
assert.equal(s.transcript.hasMore, false);
|
||||
assert.equal(chatViewReducer(s, { type: "olderHistoryMerged", items: [], hasMore: false }), s);
|
||||
});
|
||||
|
||||
test("send clears the composer, a failure restores it", () => {
|
||||
const att = { path: "p", name: "p", size: 1 };
|
||||
const typed = reduce([
|
||||
{ type: "composerChanged", patch: { input: "hello" } },
|
||||
{ type: "attachmentsUploaded", attachments: [att] },
|
||||
]);
|
||||
const sending = chatViewReducer(typed, { type: "messageSendStarted" });
|
||||
assert.deepEqual(sending.composer, { input: "", attachments: [] });
|
||||
assert.equal(sending.requests.send.pending, true);
|
||||
const failed = reduce(
|
||||
[
|
||||
{ type: "messageSendFailed", input: "hello", attachments: [att] },
|
||||
{ type: "request/finished", key: "send" },
|
||||
],
|
||||
sending,
|
||||
);
|
||||
assert.deepEqual(failed.composer, { input: "hello", attachments: [att] });
|
||||
assert.equal(failed.requests.send.pending, false);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { mergeActivities } from "@/lib/activity-merge";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Activity, ChatAttachment } from "@/lib/types";
|
||||
|
||||
export type ChatViewRequest = "send" | "stop" | "upload";
|
||||
|
||||
export type ChatTranscript = {
|
||||
messages: Activity[];
|
||||
running: boolean;
|
||||
historyLoaded: boolean;
|
||||
hasMore: boolean;
|
||||
};
|
||||
|
||||
export type ChatComposer = {
|
||||
input: string;
|
||||
/** Already uploaded (under sessions/conv-<id>/uploads/), sent with the next message. */
|
||||
attachments: ChatAttachment[];
|
||||
};
|
||||
|
||||
export type ChatViewState = {
|
||||
transcript: ChatTranscript;
|
||||
composer: ChatComposer;
|
||||
requests: Requests<ChatViewRequest>;
|
||||
};
|
||||
|
||||
export type ChatViewInitial = { input?: string; attachments?: ChatAttachment[] } | undefined;
|
||||
|
||||
export type ChatViewAction =
|
||||
| RequestAction<ChatViewRequest>
|
||||
// transcript
|
||||
| { type: "conversationReset" }
|
||||
| { type: "latestHistoryLoaded"; items: Activity[]; hasMore: boolean; running: boolean }
|
||||
| { type: "latestHistoryFailed" }
|
||||
| { type: "olderHistoryMerged"; items: Activity[]; hasMore: boolean }
|
||||
| { type: "messagesPolled"; items: Activity[]; running: boolean }
|
||||
| { type: "transcriptChanged"; patch: Partial<ChatTranscript> }
|
||||
// composer
|
||||
| { type: "composerChanged"; patch: Partial<ChatComposer> }
|
||||
| { type: "attachmentsUploaded"; attachments: ChatAttachment[] }
|
||||
| { type: "attachmentRemoved"; path: string }
|
||||
| { type: "messageSendStarted" }
|
||||
| { type: "messageSendFailed"; input: string; attachments: ChatAttachment[] };
|
||||
|
||||
export function initChatViewState(initial: ChatViewInitial): ChatViewState {
|
||||
return {
|
||||
transcript: { messages: [], running: false, historyLoaded: false, hasMore: false },
|
||||
composer: { input: initial?.input ?? "", attachments: initial?.attachments ?? [] },
|
||||
requests: createRequests<ChatViewRequest>(["send", "stop", "upload"]),
|
||||
};
|
||||
}
|
||||
|
||||
function patchTranscript(state: ChatViewState, patch: Partial<ChatTranscript>): ChatViewState {
|
||||
return { ...state, transcript: { ...state.transcript, ...patch } };
|
||||
}
|
||||
|
||||
export function chatViewReducer(state: ChatViewState, action: ChatViewAction): ChatViewState {
|
||||
if (isRequestAction<ChatViewRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "conversationReset": {
|
||||
const { messages, running, historyLoaded, hasMore } = state.transcript;
|
||||
if (!messages.length && !running && !historyLoaded && !hasMore) return state;
|
||||
return patchTranscript(state, { messages: [], running: false, historyLoaded: false, hasMore: false });
|
||||
}
|
||||
case "latestHistoryLoaded":
|
||||
// Live messages polled meanwhile win over the history page; a turn seen running stays running.
|
||||
return patchTranscript(state, {
|
||||
messages: mergeActivities(action.items, state.transcript.messages),
|
||||
hasMore: action.hasMore,
|
||||
running: state.transcript.running || action.running,
|
||||
historyLoaded: true,
|
||||
});
|
||||
case "latestHistoryFailed":
|
||||
if (state.transcript.historyLoaded) return state;
|
||||
return patchTranscript(state, { historyLoaded: true });
|
||||
case "olderHistoryMerged":
|
||||
if (!action.items.length && action.hasMore === state.transcript.hasMore) return state;
|
||||
return patchTranscript(state, {
|
||||
messages: action.items.length
|
||||
? mergeActivities(action.items, state.transcript.messages)
|
||||
: state.transcript.messages,
|
||||
hasMore: action.hasMore,
|
||||
});
|
||||
case "messagesPolled":
|
||||
// An idle poll (nothing new, same running flag) returns the same state.
|
||||
if (!action.items.length && action.running === state.transcript.running) return state;
|
||||
return patchTranscript(state, {
|
||||
messages: action.items.length
|
||||
? mergeActivities(state.transcript.messages, action.items)
|
||||
: state.transcript.messages,
|
||||
running: action.running,
|
||||
});
|
||||
case "transcriptChanged":
|
||||
return setSlice(state, "transcript", mergePatch(state.transcript, action.patch));
|
||||
|
||||
case "composerChanged":
|
||||
return setSlice(state, "composer", mergePatch(state.composer, action.patch));
|
||||
case "attachmentsUploaded":
|
||||
return {
|
||||
...state,
|
||||
composer: { ...state.composer, attachments: [...state.composer.attachments, ...action.attachments] },
|
||||
};
|
||||
case "attachmentRemoved":
|
||||
return {
|
||||
...state,
|
||||
composer: {
|
||||
...state.composer,
|
||||
attachments: state.composer.attachments.filter((x) => x.path !== action.path),
|
||||
},
|
||||
};
|
||||
case "messageSendStarted":
|
||||
// The composer is cleared eagerly; a failed send restores it.
|
||||
return {
|
||||
...state,
|
||||
composer: { input: "", attachments: [] },
|
||||
requests: requestReducer<ChatViewRequest>(state.requests, { type: "request/started", key: "send" }),
|
||||
};
|
||||
case "messageSendFailed":
|
||||
return { ...state, composer: { input: action.input, attachments: action.attachments } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { type AgentFilterOption, resolveDraftAgentKey } from "@/lib/chat-agent-filter";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type DraftChatRequest = "send" | "upload";
|
||||
|
||||
export type DraftChatForm = {
|
||||
agentKey: string;
|
||||
/** null = the default LLM profile. */
|
||||
llmProfileId: number | null;
|
||||
input: string;
|
||||
};
|
||||
|
||||
export type DraftChatState = {
|
||||
form: DraftChatForm;
|
||||
/**
|
||||
* `send` creates the conversation and sends the first message; `upload` creates it
|
||||
* and uploads the picked files. Both stay pending on success, because the parent
|
||||
* switches to the new conversation; only a failure finishes them.
|
||||
*/
|
||||
requests: Requests<DraftChatRequest>;
|
||||
};
|
||||
|
||||
export type DraftChatAction =
|
||||
| RequestAction<DraftChatRequest>
|
||||
| { type: "agentChanged"; agentKey: string }
|
||||
/** The agent list or the sidebar filter changed: keep, default or fall back the picked agent. */
|
||||
| {
|
||||
type: "agentDefaultsChanged";
|
||||
agents: readonly AgentFilterOption[];
|
||||
defaultAgentKey: string | null;
|
||||
filterChanged: boolean;
|
||||
}
|
||||
| { type: "llmProfileChanged"; llmProfileId: number | null }
|
||||
| { type: "inputChanged"; input: string };
|
||||
|
||||
export const initialDraftChatState: DraftChatState = {
|
||||
form: { agentKey: "", llmProfileId: null, input: "" },
|
||||
requests: createRequests<DraftChatRequest>(["send", "upload"]),
|
||||
};
|
||||
|
||||
function patchForm(state: DraftChatState, patch: Partial<DraftChatForm>): DraftChatState {
|
||||
const form = { ...state.form, ...patch };
|
||||
return (Object.keys(patch) as (keyof DraftChatForm)[]).every((k) => form[k] === state.form[k])
|
||||
? state
|
||||
: { ...state, form };
|
||||
}
|
||||
|
||||
export function draftChatReducer(state: DraftChatState, action: DraftChatAction): DraftChatState {
|
||||
if (isRequestAction<DraftChatRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "agentChanged":
|
||||
return patchForm(state, { agentKey: action.agentKey });
|
||||
case "agentDefaultsChanged":
|
||||
return patchForm(state, {
|
||||
agentKey: resolveDraftAgentKey(
|
||||
state.form.agentKey,
|
||||
action.agents,
|
||||
action.defaultAgentKey,
|
||||
action.filterChanged,
|
||||
),
|
||||
});
|
||||
case "llmProfileChanged":
|
||||
return patchForm(state, { llmProfileId: action.llmProfileId });
|
||||
case "inputChanged":
|
||||
return patchForm(state, { input: action.input });
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,6 @@ import { Spinner } from "@/components/ui/spinner";
|
||||
import { useQueryState } from "@/hooks/use-query-state";
|
||||
import { useSideQuestions } from "@/hooks/use-side-questions";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { mergeActivities } from "@/lib/activity-merge";
|
||||
import { api } from "@/lib/api";
|
||||
import { nextSelectedIdForAgentFilter, resolveDraftAgentKey } from "@/lib/chat-agent-filter";
|
||||
import { shouldSubmitOnKey, useChatSendMode } from "@/lib/chat-send-mode";
|
||||
@@ -66,11 +65,14 @@ import { isBtwCommand } from "@/lib/side-questions";
|
||||
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { chatPageReducer, conversationIsPinned, initChatPageState } from "./_state/chat-page.reducer";
|
||||
import { chatViewReducer, initChatViewState } from "./_state/chat-view.reducer";
|
||||
import { draftChatReducer, initialDraftChatState } from "./_state/draft-chat.reducer";
|
||||
|
||||
// HISTORY_PAGE is how many steps one history page loads: the latest page on open,
|
||||
// then one more page each time the user scrolls to the top. Kept modest so a long
|
||||
// thread stays snappy (only ~a page of rows is in the DOM until you scroll up).
|
||||
const HISTORY_PAGE = 200;
|
||||
const CONVERSATION_LIST_PAGE = 100;
|
||||
|
||||
// Which agent groups the user has collapsed in the left rail. Persisted so the
|
||||
// rail looks the same after a reload; unknown keys are harmless (a deleted agent
|
||||
@@ -81,10 +83,6 @@ const COLLAPSED_AGENTS_KEY = "artex.chat.collapsed-agents";
|
||||
// always lands on the empty draft view. A ?c= in the URL takes precedence.
|
||||
const LAST_CONVERSATION_KEY = "artex.chat.last-conversation";
|
||||
|
||||
function conversationIsPinned(conversation: Conversation): boolean {
|
||||
return conversation.pinned ?? Boolean(conversation.pinned_at);
|
||||
}
|
||||
|
||||
// AgentGroup is one collapsible section of the left rail: all unpinned
|
||||
// conversations of a single agent, newest activity first.
|
||||
interface AgentGroup {
|
||||
@@ -366,11 +364,13 @@ function DraftChat({
|
||||
defaultAgentKey?: string | null;
|
||||
onStarted: (c: Conversation, pending?: { input?: string; attachments?: ChatAttachment[] }) => void;
|
||||
}) {
|
||||
const [agentKey, setAgentKey] = React.useState(() => resolveDraftAgentKey("", agents, defaultAgentKey, true));
|
||||
const [llmProfileId, setLlmProfileId] = React.useState<number | null>(null);
|
||||
const [input, setInput] = React.useState("");
|
||||
const [sending, setSending] = React.useState(false);
|
||||
const [uploading, setUploading] = React.useState(false);
|
||||
const [state, dispatch] = React.useReducer(draftChatReducer, null, () => ({
|
||||
...initialDraftChatState,
|
||||
form: { ...initialDraftChatState.form, agentKey: resolveDraftAgentKey("", agents, defaultAgentKey, true) },
|
||||
}));
|
||||
const { agentKey, llmProfileId, input } = state.form;
|
||||
const sending = state.requests.send.pending;
|
||||
const uploading = state.requests.upload.pending;
|
||||
const prevDefaultAgentKey = React.useRef<string | null>(defaultAgentKey);
|
||||
|
||||
// Default to the active agent filter (falling back to Auto) on load and
|
||||
@@ -378,7 +378,7 @@ function DraftChat({
|
||||
React.useEffect(() => {
|
||||
const filterChanged = prevDefaultAgentKey.current !== defaultAgentKey;
|
||||
prevDefaultAgentKey.current = defaultAgentKey;
|
||||
setAgentKey((current) => resolveDraftAgentKey(current, agents, defaultAgentKey, filterChanged));
|
||||
dispatch({ type: "agentDefaultsChanged", agents, defaultAgentKey, filterChanged });
|
||||
}, [agents, defaultAgentKey]);
|
||||
|
||||
const agent = agents.find((a) => a.key === agentKey);
|
||||
@@ -386,14 +386,14 @@ function DraftChat({
|
||||
async function send() {
|
||||
const msg = input.trim();
|
||||
if (!msg || !agentKey || sending) return;
|
||||
setSending(true);
|
||||
dispatch({ type: "request/started", key: "send" });
|
||||
try {
|
||||
const c = await api.createConversation(agentKey, "", llmProfileId);
|
||||
await api.sendConversationMessage(c.id, msg);
|
||||
onStarted(c);
|
||||
} catch (e) {
|
||||
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
|
||||
setSending(false);
|
||||
dispatch({ type: "request/finished", key: "send" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,19 +404,19 @@ function DraftChat({
|
||||
// the ChatGPT-style lazy-create flow.
|
||||
async function pickFiles(files: File[]) {
|
||||
if (files.length === 0 || !agentKey || uploading || sending) return;
|
||||
setUploading(true);
|
||||
dispatch({ type: "request/started", key: "upload" });
|
||||
try {
|
||||
const c = await api.createConversation(agentKey, "", llmProfileId);
|
||||
const r = await api.chatUpload("session", `conv-${c.id}`, files);
|
||||
onStarted(c, { input, attachments: r.attachments });
|
||||
} catch (e) {
|
||||
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
|
||||
setUploading(false);
|
||||
dispatch({ type: "request/finished", key: "upload" });
|
||||
}
|
||||
}
|
||||
|
||||
const agentPicker = (
|
||||
<Select value={agentKey} onValueChange={setAgentKey}>
|
||||
<Select value={agentKey} onValueChange={(key) => dispatch({ type: "agentChanged", agentKey: key })}>
|
||||
<SelectTrigger className="w-full sm:w-40">
|
||||
<SelectValue placeholder={t("Select an agent…")} />
|
||||
</SelectTrigger>
|
||||
@@ -455,7 +455,7 @@ function DraftChat({
|
||||
|
||||
<Composer
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
onChange={(value) => dispatch({ type: "inputChanged", input: value })}
|
||||
onSend={send}
|
||||
disabled={sending || uploading || !agentKey}
|
||||
placeholder={t("Type a message, @ to reference records, Enter to send")}
|
||||
@@ -466,7 +466,7 @@ function DraftChat({
|
||||
<LLMProfileRow
|
||||
profiles={profiles}
|
||||
selected={llmProfileId}
|
||||
onChange={setLlmProfileId}
|
||||
onChange={(id) => dispatch({ type: "llmProfileChanged", llmProfileId: id })}
|
||||
disabled={sending || uploading}
|
||||
/>
|
||||
</>
|
||||
@@ -493,21 +493,18 @@ function ChatView({
|
||||
onTitleMaybeChanged: () => void;
|
||||
onConvUpdated: () => void;
|
||||
}) {
|
||||
const approvalFocus = useApprovalFocus({ conversationId: conv.id });
|
||||
const [messages, setMessages] = React.useState<Activity[]>([]);
|
||||
const [running, setRunning] = React.useState(false);
|
||||
const [input, setInput] = React.useState(initial?.input ?? "");
|
||||
const [sending, setSending] = React.useState(false);
|
||||
const [stopping, setStopping] = React.useState(false);
|
||||
const approvalFocus: ReturnType<typeof useApprovalFocus> = useApprovalFocus({ conversationId: conv.id });
|
||||
// Upload method 1: already-uploaded attachments (stored under sessions/conv-<id>/uploads/) are sent with the next message.
|
||||
const [attachments, setAttachments] = React.useState<ChatAttachment[]>(initial?.attachments ?? []);
|
||||
const [uploading, setUploading] = React.useState(false);
|
||||
const [state, dispatch] = React.useReducer(chatViewReducer, initial, initChatViewState);
|
||||
const { messages, running, historyLoaded, hasMore } = state.transcript;
|
||||
const { input, attachments } = state.composer;
|
||||
const sending = state.requests.send.pending;
|
||||
const stopping = state.requests.stop.pending;
|
||||
const uploading = state.requests.upload.pending;
|
||||
const cursorRef = React.useRef(0); // newest loaded id — incremental-tail anchor
|
||||
const earliestRef = React.useRef(0); // earliest loaded id — reverse-pagination anchor
|
||||
const hasMoreRef = React.useRef(false); // older history remains above the loaded window
|
||||
const loadingMoreRef = React.useRef(false); // guard: one scroll-up load at a time
|
||||
const [historyLoaded, setHistoryLoaded] = React.useState(false);
|
||||
const [hasMore, setHasMore] = React.useState(false); // drives the "load earlier" hint
|
||||
const agent = agents.find((a) => a.key === conv.agent_key);
|
||||
const currentProfileId = conv.llm_profile_id ?? null;
|
||||
const side = useSideQuestions(`/api/conversations/${conv.id}`);
|
||||
@@ -542,27 +539,21 @@ function ChatView({
|
||||
cursorRef.current = 0;
|
||||
earliestRef.current = 0;
|
||||
hasMoreRef.current = false;
|
||||
setHasMore(false);
|
||||
setMessages([]);
|
||||
setHistoryLoaded(false);
|
||||
setRunning(false);
|
||||
dispatch({ type: "conversationReset" });
|
||||
let live = true;
|
||||
api
|
||||
.conversationHistory(conv.id, 0, HISTORY_PAGE)
|
||||
.then((r) => {
|
||||
if (!live) return;
|
||||
setMessages((current) => mergeActivities(r.items, current));
|
||||
dispatch({ type: "latestHistoryLoaded", items: r.items, hasMore: r.hasMore, running: r.running });
|
||||
cursorRef.current = Math.max(cursorRef.current, r.cursor);
|
||||
earliestRef.current = r.items.length ? r.items[0].seq : 0;
|
||||
hasMoreRef.current = r.hasMore;
|
||||
setHasMore(r.hasMore);
|
||||
setRunning((current) => current || r.running);
|
||||
setHistoryLoaded(true);
|
||||
})
|
||||
.catch(() => {
|
||||
// A source link can retry history through its locator; ordinary chats
|
||||
// retain the existing usable empty state on a transient failure.
|
||||
if (live) setHistoryLoaded(true);
|
||||
if (live) dispatch({ type: "latestHistoryFailed" });
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
@@ -572,7 +563,7 @@ function ChatView({
|
||||
// A trigger or another tab may start a turn while this conversation is open.
|
||||
// A false list snapshot must not stop the tail before its final messages load.
|
||||
React.useEffect(() => {
|
||||
if (conv.running) setRunning(true);
|
||||
if (conv.running) dispatch({ type: "transcriptChanged", patch: { running: true } });
|
||||
}, [conv.running]);
|
||||
|
||||
// poll while a turn is running: pull new steps after the cursor.
|
||||
@@ -585,12 +576,9 @@ function ChatView({
|
||||
try {
|
||||
const r = await api.conversationMessages(conv.id, cursorRef.current);
|
||||
if (!live) return;
|
||||
if (r.items.length) {
|
||||
setMessages((prev) => mergeActivities(prev, r.items));
|
||||
}
|
||||
dispatch({ type: "messagesPolled", items: r.items, running: r.running });
|
||||
cursorRef.current = Math.max(cursorRef.current, r.cursor);
|
||||
keepPolling = r.running;
|
||||
setRunning(r.running);
|
||||
if (!r.running) onTitleMaybeChanged(); // first-turn auto-title landed
|
||||
} catch {
|
||||
/* transient — keep polling */
|
||||
@@ -611,12 +599,11 @@ function ChatView({
|
||||
[conv.id],
|
||||
);
|
||||
const mergeFocusPage = React.useCallback((page: { items: Activity[]; hasMore: boolean }) => {
|
||||
setMessages((prev) => mergeActivities(page.items, prev));
|
||||
dispatch({ type: "olderHistoryMerged", items: page.items, hasMore: page.hasMore });
|
||||
earliestRef.current = page.items[0]?.seq ?? earliestRef.current;
|
||||
hasMoreRef.current = page.hasMore;
|
||||
setHasMore(page.hasMore);
|
||||
}, []);
|
||||
const focusHistory = useApprovalHistory(
|
||||
const focusHistory: ReturnType<typeof useApprovalHistory> = useApprovalHistory(
|
||||
approvalFocus.state?.source,
|
||||
historyLoaded,
|
||||
messages,
|
||||
@@ -642,12 +629,9 @@ function ChatView({
|
||||
const prevTop = vp.scrollTop;
|
||||
try {
|
||||
const r = await api.conversationHistory(conv.id, earliestRef.current, HISTORY_PAGE);
|
||||
if (r.items.length) {
|
||||
setMessages((prev) => mergeActivities(r.items, prev));
|
||||
earliestRef.current = r.items[0].seq;
|
||||
}
|
||||
dispatch({ type: "olderHistoryMerged", items: r.items, hasMore: r.hasMore });
|
||||
if (r.items.length) earliestRef.current = r.items[0].seq;
|
||||
hasMoreRef.current = r.hasMore;
|
||||
setHasMore(r.hasMore);
|
||||
requestAnimationFrame(() => {
|
||||
const v = viewport();
|
||||
if (v) v.scrollTop = prevTop + (v.scrollHeight - prevH);
|
||||
@@ -719,36 +703,34 @@ function ChatView({
|
||||
// uploads/) and queues the returned metadata to send with the next message.
|
||||
async function pickFiles(files: File[]) {
|
||||
if (files.length === 0) return;
|
||||
setUploading(true);
|
||||
dispatch({ type: "request/started", key: "upload" });
|
||||
try {
|
||||
const r = await api.chatUpload("session", `conv-${conv.id}`, files);
|
||||
setAttachments((prev) => [...prev, ...r.attachments]);
|
||||
dispatch({ type: "attachmentsUploaded", attachments: r.attachments });
|
||||
} catch (e) {
|
||||
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
dispatch({ type: "request/finished", key: "upload" });
|
||||
}
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const msg = input.trim();
|
||||
const atts = attachments;
|
||||
if (side.handleCommand(msg, () => setInput(""))) return;
|
||||
if (side.handleCommand(msg, () => dispatch({ type: "composerChanged", patch: { input: "" } }))) return;
|
||||
if ((!msg && atts.length === 0) || sending || running) return;
|
||||
setSending(true);
|
||||
setInput("");
|
||||
setAttachments([]);
|
||||
dispatch({ type: "messageSendStarted" });
|
||||
try {
|
||||
await api.sendConversationMessage(conv.id, msg, atts.length ? atts : undefined);
|
||||
// The live loop pulls the persisted human turn immediately. Sharing that
|
||||
// fetch avoids racing a separate post-send request against the poller.
|
||||
setRunning(true);
|
||||
dispatch({ type: "transcriptChanged", patch: { running: true } });
|
||||
} catch (e) {
|
||||
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
|
||||
setInput(msg); // restore so the user doesn't lose their text
|
||||
setAttachments(atts); // and their attachments
|
||||
// restore so the user doesn't lose their text and attachments
|
||||
dispatch({ type: "messageSendFailed", input: msg, attachments: atts });
|
||||
} finally {
|
||||
setSending(false);
|
||||
dispatch({ type: "request/finished", key: "send" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -757,13 +739,13 @@ function ChatView({
|
||||
// affected — the agent's next queued fire still starts.
|
||||
async function stop() {
|
||||
if (stopping) return;
|
||||
setStopping(true);
|
||||
dispatch({ type: "request/started", key: "stop" });
|
||||
try {
|
||||
await api.stopConversation(conv.id);
|
||||
} catch (e) {
|
||||
toast.error(t("Stop failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setStopping(false);
|
||||
dispatch({ type: "request/finished", key: "stop" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -832,7 +814,7 @@ function ChatView({
|
||||
|
||||
<Composer
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
onChange={(value) => dispatch({ type: "composerChanged", patch: { input: value } })}
|
||||
onSend={send}
|
||||
disabled={running || sending}
|
||||
allowBtw
|
||||
@@ -846,7 +828,7 @@ function ChatView({
|
||||
stopDisabled={stopping}
|
||||
attachments={attachments}
|
||||
onPickFiles={pickFiles}
|
||||
onRemoveAttachment={(path) => setAttachments((p) => p.filter((x) => x.path !== path))}
|
||||
onRemoveAttachment={(path) => dispatch({ type: "attachmentRemoved", path })}
|
||||
uploading={uploading}
|
||||
/>
|
||||
<LLMProfileRow
|
||||
@@ -1075,10 +1057,9 @@ function AgentGroupHeader({
|
||||
}
|
||||
|
||||
export default function ChatPage() {
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
|
||||
const [convs, setConvs] = React.useState<Conversation[]>([]);
|
||||
const [agentFilter, setAgentFilter] = React.useState<string | null>(null);
|
||||
const [state, dispatch] = React.useReducer(chatPageReducer, undefined, initChatPageState);
|
||||
const { agents, profiles } = state.catalog;
|
||||
const { items: convs, loaded: convsLoaded } = state.list;
|
||||
const [conversationID] = useQueryState("c", "");
|
||||
const selectedId = /^[1-9]\d*$/.test(conversationID) ? Number(conversationID) : null;
|
||||
const setSelectedId = React.useCallback((next: React.SetStateAction<number | null>) => {
|
||||
@@ -1089,7 +1070,13 @@ export default function ChatPage() {
|
||||
}, []);
|
||||
const [approvalID] = useQueryState("approval", "");
|
||||
const sourceRequested = Boolean(approvalID);
|
||||
const [convsLoaded, setConvsLoaded] = React.useState(false);
|
||||
const { agentFilter, visibleCount: visibleConversationCount, collapsedAgents } = state.sidebar;
|
||||
const { id: renamingId, text: renameText } = state.rename;
|
||||
// selectionMode gates the multi-select UI: off by default (clean list, no
|
||||
// checkboxes); the header "Select" button turns it on, "Done" turns it off and
|
||||
// clears the selection.
|
||||
const { selectionMode, selection: selectedConversationIds, bulkDeleteOpen, pendingByConv } = state;
|
||||
const bulkDeleting = state.requests.bulkDelete.pending;
|
||||
const selectConversation = React.useCallback(
|
||||
(id: number | null) => {
|
||||
setSelectedId(id);
|
||||
@@ -1097,34 +1084,14 @@ export default function ChatPage() {
|
||||
[setSelectedId],
|
||||
);
|
||||
|
||||
const [renamingId, setRenamingId] = React.useState<number | null>(null);
|
||||
const [renameText, setRenameText] = React.useState("");
|
||||
const [selectedConversationIds, setSelectedConversationIds] = React.useState<Set<number>>(() => new Set());
|
||||
// selectionMode gates the multi-select UI: off by default (clean list, no
|
||||
// checkboxes); the header "Select" button turns it on, "Done" turns it off and
|
||||
// clears the selection.
|
||||
const [selectionMode, setSelectionMode] = React.useState(false);
|
||||
const [bulkDeleteOpen, setBulkDeleteOpen] = React.useState(false);
|
||||
const [bulkDeleting, setBulkDeleting] = React.useState(false);
|
||||
const [visibleConversationCount, setVisibleConversationCount] = React.useState(CONVERSATION_LIST_PAGE);
|
||||
// Collapsed agent groups. Hydrated from localStorage after mount (not a lazy
|
||||
// useState init) so the server and client render the same first pass.
|
||||
const [collapsedAgents, setCollapsedAgents] = React.useState<Set<string>>(() => new Set());
|
||||
// Pending text + uploaded attachments handed off from a draft that created a
|
||||
// conversation via the paperclip, keyed by the new conversation id (consumed once
|
||||
// by ChatView on mount; ids never repeat, so leftover entries are harmless).
|
||||
const [pendingByConv, setPendingByConv] = React.useState<
|
||||
Record<number, { input?: string; attachments?: ChatAttachment[] }>
|
||||
>({});
|
||||
|
||||
const conversationListSeq = React.useRef(0);
|
||||
const reloadConvs = React.useCallback(async () => {
|
||||
const seq = ++conversationListSeq.current;
|
||||
try {
|
||||
const items = await api.conversations();
|
||||
if (seq === conversationListSeq.current) {
|
||||
setConvs(items);
|
||||
setConvsLoaded(true);
|
||||
dispatch({ type: "list/loaded", items });
|
||||
dispatch({ type: "list/loadFinished" });
|
||||
}
|
||||
} catch {
|
||||
// Preserve the selected transcript and list on a transient poll failure.
|
||||
@@ -1133,13 +1100,13 @@ export default function ChatPage() {
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.agents()
|
||||
.then(setAgents)
|
||||
.then((items) => dispatch({ type: "catalogChanged", patch: { agents: items } }))
|
||||
.catch(() => {
|
||||
/* Agent metadata is optional for rendering an existing conversation. */
|
||||
});
|
||||
api
|
||||
.llmProfiles()
|
||||
.then(setProfiles)
|
||||
.then((items) => dispatch({ type: "catalogChanged", patch: { profiles: items } }))
|
||||
.catch(() => {
|
||||
/* The conversation remains usable without profile labels. */
|
||||
});
|
||||
@@ -1163,12 +1130,7 @@ export default function ChatPage() {
|
||||
}, [reloadConvs]);
|
||||
|
||||
React.useEffect(() => {
|
||||
setSelectedConversationIds((current) => {
|
||||
if (current.size === 0) return current;
|
||||
const live = new Set(convs.map((conversation) => conversation.id));
|
||||
const next = new Set([...current].filter((id) => live.has(id)));
|
||||
return next.size === current.size ? current : next;
|
||||
});
|
||||
dispatch({ type: "selection/pruned", keep: convs.map((conversation) => conversation.id) });
|
||||
}, [convs]);
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -1177,20 +1139,26 @@ export default function ChatPage() {
|
||||
try {
|
||||
const keys = JSON.parse(raw);
|
||||
if (Array.isArray(keys))
|
||||
setCollapsedAgents(new Set(keys.filter((key): key is string => typeof key === "string")));
|
||||
dispatch({
|
||||
type: "collapsedAgentsRestored",
|
||||
keys: keys.filter((key): key is string => typeof key === "string"),
|
||||
});
|
||||
} catch {
|
||||
// Corrupted entry → start with everything expanded.
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Persist only after the user toggles a group, so hydration never writes back.
|
||||
const collapsedAgentsTouched = React.useRef(false);
|
||||
const toggleAgentCollapsed = React.useCallback((key: string) => {
|
||||
setCollapsedAgents((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(key)) next.add(key);
|
||||
setLocalStorageValue(COLLAPSED_AGENTS_KEY, JSON.stringify([...next]));
|
||||
return next;
|
||||
});
|
||||
collapsedAgentsTouched.current = true;
|
||||
dispatch({ type: "agentGroupToggled", key });
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
if (collapsedAgentsTouched.current) {
|
||||
setLocalStorageValue(COLLAPSED_AGENTS_KEY, JSON.stringify([...collapsedAgents]));
|
||||
}
|
||||
}, [collapsedAgents]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
@@ -1250,14 +1218,10 @@ export default function ChatPage() {
|
||||
: `${filteredConversations.length} / ${convs.length}`;
|
||||
|
||||
function changeAgentFilter(key: string | null) {
|
||||
setAgentFilter(key);
|
||||
dispatch({ type: "agentFilterChanged", agentFilter: key });
|
||||
if (selectedId !== null && nextSelectedIdForAgentFilter(selectedId, convs, key) === null) {
|
||||
selectConversation(null);
|
||||
}
|
||||
setVisibleConversationCount(CONVERSATION_LIST_PAGE);
|
||||
setSelectedConversationIds(new Set());
|
||||
setBulkDeleteOpen(false);
|
||||
setRenamingId(null);
|
||||
}
|
||||
|
||||
const selectedConversationCount = selectedConversationIds.size;
|
||||
@@ -1269,23 +1233,16 @@ export default function ChatPage() {
|
||||
else if (someConversationsSelected) conversationHeaderChecked = "indeterminate";
|
||||
|
||||
const toggleConversationSelected = React.useCallback((id: number, checked: boolean) => {
|
||||
setSelectedConversationIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (checked) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
dispatch({ type: "conversationCheckedChanged", id, checked });
|
||||
}, []);
|
||||
|
||||
function toggleAllConversations(checked: boolean) {
|
||||
setSelectedConversationIds(
|
||||
checked ? new Set(filteredConversations.map((conversation) => conversation.id)) : new Set(),
|
||||
);
|
||||
if (checked) dispatch({ type: "selection/set", ids: filteredConversations.map((conversation) => conversation.id) });
|
||||
else dispatch({ type: "selection/cleared" });
|
||||
}
|
||||
|
||||
function exitSelectionMode() {
|
||||
setSelectionMode(false);
|
||||
setSelectedConversationIds(new Set());
|
||||
dispatch({ type: "selectionModeExited" });
|
||||
}
|
||||
|
||||
const del = React.useCallback(
|
||||
@@ -1293,12 +1250,7 @@ export default function ChatPage() {
|
||||
try {
|
||||
await api.deleteConversation(id);
|
||||
setSelectedId((current) => (current === id ? null : current));
|
||||
setSelectedConversationIds((current) => {
|
||||
if (!current.has(id)) return current;
|
||||
const next = new Set(current);
|
||||
next.delete(id);
|
||||
return next;
|
||||
});
|
||||
dispatch({ type: "conversationDeleted", id });
|
||||
void reloadConvs();
|
||||
} catch (e) {
|
||||
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
|
||||
@@ -1310,7 +1262,7 @@ export default function ChatPage() {
|
||||
async function deleteSelectedConversations() {
|
||||
const ids = [...selectedConversationIds];
|
||||
if (ids.length === 0 || bulkDeleting) return;
|
||||
setBulkDeleting(true);
|
||||
dispatch({ type: "request/started", key: "bulkDelete" });
|
||||
const deleted = new Set<number>();
|
||||
const failed: { id: number; error: string }[] = [];
|
||||
try {
|
||||
@@ -1322,11 +1274,6 @@ export default function ChatPage() {
|
||||
}
|
||||
}
|
||||
if (deleted.has(selectedId ?? -1)) selectConversation(null);
|
||||
setSelectedConversationIds((current) => {
|
||||
const next = new Set(current);
|
||||
for (const id of deleted) next.delete(id);
|
||||
return next;
|
||||
});
|
||||
if (deleted.size > 0) toast.success(t("Deleted {count} conversations", { count: deleted.size }));
|
||||
if (failed.length > 0) {
|
||||
const details = failed
|
||||
@@ -1340,16 +1287,15 @@ export default function ChatPage() {
|
||||
}),
|
||||
);
|
||||
}
|
||||
setBulkDeleteOpen(false);
|
||||
// Fully successful → return to the clean list; keep selection mode on if
|
||||
// some failed so the user can retry the remaining ones.
|
||||
if (failed.length === 0) setSelectionMode(false);
|
||||
dispatch({ type: "bulkDeleteSettled", deleted: [...deleted], allSucceeded: failed.length === 0 });
|
||||
void reloadConvs();
|
||||
} catch (error) {
|
||||
toast.error(t("Bulk delete failed: {error}", { error: (error as Error).message }));
|
||||
void reloadConvs();
|
||||
} finally {
|
||||
setBulkDeleting(false);
|
||||
dispatch({ type: "request/finished", key: "bulkDelete" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1368,13 +1314,13 @@ export default function ChatPage() {
|
||||
);
|
||||
|
||||
const startRename = React.useCallback((c: Conversation) => {
|
||||
setRenamingId(c.id);
|
||||
setRenameText(c.title || "");
|
||||
dispatch({ type: "renameChanged", patch: { id: c.id, text: c.title || "" } });
|
||||
}, []);
|
||||
const setRenameText = React.useCallback((text: string) => dispatch({ type: "renameChanged", patch: { text } }), []);
|
||||
const commitRename = React.useCallback(
|
||||
async (id: number, value: string) => {
|
||||
const title = value.trim();
|
||||
setRenamingId(null);
|
||||
dispatch({ type: "renameChanged", patch: { id: null } });
|
||||
if (!title) return;
|
||||
try {
|
||||
await api.renameConversation(id, title);
|
||||
@@ -1385,7 +1331,7 @@ export default function ChatPage() {
|
||||
},
|
||||
[reloadConvs],
|
||||
);
|
||||
const cancelRename = React.useCallback(() => setRenamingId(null), []);
|
||||
const cancelRename = React.useCallback(() => dispatch({ type: "renameChanged", patch: { id: null } }), []);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -1438,7 +1384,7 @@ export default function ChatPage() {
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={bulkDeleting}
|
||||
onClick={() => setBulkDeleteOpen(true)}
|
||||
onClick={() => dispatch({ type: "bulkDeleteOpenChanged", open: true })}
|
||||
>
|
||||
<Trash2Icon data-icon="inline-start" />
|
||||
{t("Delete")}
|
||||
@@ -1457,7 +1403,7 @@ export default function ChatPage() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground"
|
||||
onClick={() => setSelectionMode(true)}
|
||||
onClick={() => dispatch({ type: "selectionModeEntered" })}
|
||||
disabled={filteredConversations.length === 0}
|
||||
>
|
||||
<ListChecksIcon data-icon="inline-start" />
|
||||
@@ -1538,7 +1484,7 @@ export default function ChatPage() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="mt-1 w-full"
|
||||
onClick={() => setVisibleConversationCount((count) => count + CONVERSATION_LIST_PAGE)}
|
||||
onClick={() => dispatch({ type: "moreConversationsShown" })}
|
||||
>
|
||||
{t("Load more")}
|
||||
</Button>
|
||||
@@ -1569,17 +1515,10 @@ export default function ChatPage() {
|
||||
profiles={profiles}
|
||||
defaultAgentKey={agentFilter}
|
||||
onStarted={(c, pending) => {
|
||||
if (agentFilter !== null && agentFilter !== c.agent_key) changeAgentFilter(null);
|
||||
// Insert the new conversation immediately so `selected` resolves to
|
||||
// it on this render (switching to ChatView right away, before the
|
||||
// async reloadConvs lands); reloadConvs then reconciles titles etc.
|
||||
if (pending) setPendingByConv((p) => ({ ...p, [c.id]: pending }));
|
||||
setConvs((prev) => {
|
||||
if (prev.some((item) => item.id === c.id)) return prev;
|
||||
const firstUnpinned = prev.findIndex((item) => !conversationIsPinned(item));
|
||||
const insertAt = firstUnpinned < 0 ? prev.length : firstUnpinned;
|
||||
return [...prev.slice(0, insertAt), c, ...prev.slice(insertAt)];
|
||||
});
|
||||
dispatch({ type: "conversationStarted", conversation: c, pending });
|
||||
setSelectedId(c.id);
|
||||
void reloadConvs();
|
||||
}}
|
||||
@@ -1587,7 +1526,7 @@ export default function ChatPage() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
|
||||
<AlertDialog open={bulkDeleteOpen} onOpenChange={(open) => dispatch({ type: "bulkDeleteOpenChanged", open })}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { dashboardPageReducer, initialDashboardPageState } from "./dashboard-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const live = { ...initialDashboardPageState.live, findings: [{ id: 1, severity: "high" }], pending: [{ id: 9 }] };
|
||||
const system = { ...initialDashboardPageState.system, assetCounts: { domain: 3 } };
|
||||
|
||||
test("unchanged live and system polls keep the same state", () => {
|
||||
const s = [
|
||||
{ type: "liveLoaded", live },
|
||||
{ type: "systemLoaded", system },
|
||||
].reduce(dashboardPageReducer, initialDashboardPageState);
|
||||
const again = [
|
||||
{ type: "liveLoaded", live: structuredClone(live) },
|
||||
{ type: "systemLoaded", system: structuredClone(system) },
|
||||
].reduce(dashboardPageReducer, s);
|
||||
assert.equal(again, s);
|
||||
});
|
||||
|
||||
test("a poll that changes one nested field updates it", () => {
|
||||
const s = dashboardPageReducer(initialDashboardPageState, { type: "liveLoaded", live });
|
||||
const next = structuredClone(live);
|
||||
next.findings[0].severity = "low";
|
||||
assert.equal(dashboardPageReducer(s, { type: "liveLoaded", live: next }).live.findings[0].severity, "low");
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type {
|
||||
Activity,
|
||||
Agent,
|
||||
ConvTokenSummary,
|
||||
Finding,
|
||||
InterceptPending,
|
||||
LLMProfile,
|
||||
MCPServer,
|
||||
Settings,
|
||||
SkillItem,
|
||||
Stats,
|
||||
Task,
|
||||
TokenTotal,
|
||||
Tool,
|
||||
TrafficExchange,
|
||||
UsageStats,
|
||||
} from "@/lib/types";
|
||||
|
||||
export type TokenVersion = "old" | "new";
|
||||
/** "all" = every profile; a number (or null for the default bucket) = one profile. */
|
||||
export type TokenTab = number | null | "all";
|
||||
export type TokenDays = 7 | 30 | 90 | 180 | 365;
|
||||
|
||||
/** Fast-poll sources (every 5s), fetched together and applied in one dispatch. */
|
||||
export type DashboardLive = {
|
||||
findings: Finding[];
|
||||
stats: Stats | null;
|
||||
settings: Settings | null;
|
||||
pending: InterceptPending[];
|
||||
activity: Activity[];
|
||||
tokens: TokenTotal | null;
|
||||
convTokens: ConvTokenSummary[];
|
||||
};
|
||||
|
||||
/** Slow-poll sources (every 15s): traffic, assets and mostly static system config. */
|
||||
export type DashboardSystem = {
|
||||
traffic: TrafficExchange[];
|
||||
assetCounts: Record<string, number>;
|
||||
agents: Agent[];
|
||||
mcpServers: MCPServer[];
|
||||
skills: SkillItem[];
|
||||
tools: Tool[];
|
||||
llmProfiles: LLMProfile[];
|
||||
usageStats: UsageStats | null;
|
||||
};
|
||||
|
||||
export type TokenView = {
|
||||
/** Data source: old = activity (task.tokens + conversations), new = the llm_usage metering ledger. */
|
||||
version: TokenVersion;
|
||||
tab: TokenTab;
|
||||
days: TokenDays;
|
||||
};
|
||||
|
||||
export type DashboardPageState = {
|
||||
/** Polled on its own: the task list is the most expensive source. */
|
||||
tasks: Task[];
|
||||
live: DashboardLive;
|
||||
system: DashboardSystem;
|
||||
tokenView: TokenView;
|
||||
};
|
||||
|
||||
export type DashboardPageAction =
|
||||
| { type: "tasksLoaded"; tasks: Task[] }
|
||||
| { type: "liveLoaded"; live: DashboardLive }
|
||||
| { type: "systemLoaded"; system: DashboardSystem }
|
||||
| { type: "tokenViewChanged"; patch: Partial<TokenView> };
|
||||
|
||||
export const initialDashboardPageState: DashboardPageState = {
|
||||
tasks: [],
|
||||
live: {
|
||||
findings: [],
|
||||
stats: null,
|
||||
settings: null,
|
||||
pending: [],
|
||||
activity: [],
|
||||
tokens: null,
|
||||
convTokens: [],
|
||||
},
|
||||
system: {
|
||||
traffic: [],
|
||||
assetCounts: {},
|
||||
agents: [],
|
||||
mcpServers: [],
|
||||
skills: [],
|
||||
tools: [],
|
||||
llmProfiles: [],
|
||||
usageStats: null,
|
||||
},
|
||||
tokenView: { version: "old", tab: "all", days: 30 },
|
||||
};
|
||||
|
||||
export function dashboardPageReducer(state: DashboardPageState, action: DashboardPageAction): DashboardPageState {
|
||||
switch (action.type) {
|
||||
case "tasksLoaded":
|
||||
return action.tasks === state.tasks ? state : { ...state, tasks: action.tasks };
|
||||
case "liveLoaded":
|
||||
return JSON.stringify(action.live) === JSON.stringify(state.live) ? state : { ...state, live: action.live };
|
||||
case "systemLoaded":
|
||||
return JSON.stringify(action.system) === JSON.stringify(state.system)
|
||||
? state
|
||||
: { ...state, system: action.system };
|
||||
case "tokenViewChanged":
|
||||
return setSlice(state, "tokenView", mergePatch(state.tokenView, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -25,26 +25,12 @@ import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { formatTokens } from "@/lib/format";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import type {
|
||||
Activity,
|
||||
Agent,
|
||||
ConvTokenSummary,
|
||||
Finding,
|
||||
InterceptPending,
|
||||
LLMProfile,
|
||||
MCPServer,
|
||||
Settings,
|
||||
SkillItem,
|
||||
Stats,
|
||||
Task,
|
||||
TokenTotal,
|
||||
Tool,
|
||||
TrafficExchange,
|
||||
UsageStats,
|
||||
} from "@/lib/types";
|
||||
import type { Activity } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useActiveCompany } from "@/stores/company/company-store";
|
||||
|
||||
import { dashboardPageReducer, initialDashboardPageState } from "./_state/dashboard-page.reducer";
|
||||
|
||||
// ── chart constants ───────────────────────────────────────────────────────────
|
||||
|
||||
const dailyTrendConfig = {
|
||||
@@ -131,23 +117,11 @@ export default function DashboardPage() {
|
||||
// The sidebar's company switcher narrows the finding-derived panels to that
|
||||
// company (server-side `company` filter). Undefined means all companies.
|
||||
const company = useActiveCompany();
|
||||
// data state
|
||||
const [tasks, setTasks] = React.useState<Task[]>([]);
|
||||
const [findings, setFindings] = React.useState<Finding[]>([]);
|
||||
const [stats, setStats] = React.useState<Stats | null>(null);
|
||||
const [settings, setSettings] = React.useState<Settings | null>(null);
|
||||
const [pending, setPending] = React.useState<InterceptPending[]>([]);
|
||||
const [activity, setActivity] = React.useState<Activity[]>([]);
|
||||
const [tokens, setTokens] = React.useState<TokenTotal | null>(null);
|
||||
const [convTokens, setConvTokens] = React.useState<ConvTokenSummary[]>([]);
|
||||
const [usageStats, setUsageStats] = React.useState<UsageStats | null>(null);
|
||||
const [assetCounts, setAssetCounts] = React.useState<Record<string, number>>({});
|
||||
const [traffic, setTraffic] = React.useState<TrafficExchange[]>([]);
|
||||
const [agents, setAgents] = React.useState<Agent[]>([]);
|
||||
const [mcpServers, setMcpServers] = React.useState<MCPServer[]>([]);
|
||||
const [skills, setSkills] = React.useState<SkillItem[]>([]);
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [llmProfiles, setLLMProfiles] = React.useState<LLMProfile[]>([]);
|
||||
const [state, dispatch] = React.useReducer(dashboardPageReducer, initialDashboardPageState);
|
||||
const { tasks, live, system, tokenView } = state;
|
||||
const { findings, stats, settings, pending, activity, convTokens } = live;
|
||||
const { traffic, assetCounts, tools, llmProfiles, usageStats } = system;
|
||||
const { version: tokenVersion, tab: tokenTab, days: tokenDays } = tokenView;
|
||||
|
||||
// The task list is the most expensive dashboard source. Poll it independently
|
||||
// so a large history cannot hold back every other dashboard panel.
|
||||
@@ -164,7 +138,7 @@ export default function DashboardPage() {
|
||||
const nextSignature = JSON.stringify(tr.tasks);
|
||||
if (nextSignature !== signature) {
|
||||
signature = nextSignature;
|
||||
setTasks(tr.tasks);
|
||||
dispatch({ type: "tasksLoaded", tasks: tr.tasks });
|
||||
}
|
||||
} catch {
|
||||
/* transient errors — next poll retries */
|
||||
@@ -198,13 +172,18 @@ export default function DashboardPage() {
|
||||
api.conversationTokens(),
|
||||
]);
|
||||
if (!alive) return;
|
||||
setFindings(findings);
|
||||
setStats(stats);
|
||||
setSettings(settings);
|
||||
setPending(pending);
|
||||
setActivity(activity.items);
|
||||
setTokens(tokens.total ?? null);
|
||||
setConvTokens(conversationTokens);
|
||||
dispatch({
|
||||
type: "liveLoaded",
|
||||
live: {
|
||||
findings,
|
||||
stats,
|
||||
settings,
|
||||
pending,
|
||||
activity: activity.items,
|
||||
tokens: tokens.total ?? null,
|
||||
convTokens: conversationTokens,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Preserve stale data and retry on the next interval.
|
||||
} finally {
|
||||
@@ -235,14 +214,19 @@ export default function DashboardPage() {
|
||||
api.usageStats(365),
|
||||
]);
|
||||
if (!alive) return;
|
||||
setTraffic(traf.exchanges ?? []);
|
||||
setAssetCounts(counts ?? {});
|
||||
setAgents(agentList);
|
||||
setMcpServers(mcpList);
|
||||
setSkills(skillList);
|
||||
setTools(toolList);
|
||||
setLLMProfiles(profileList);
|
||||
setUsageStats(usage);
|
||||
dispatch({
|
||||
type: "systemLoaded",
|
||||
system: {
|
||||
traffic: traf.exchanges ?? [],
|
||||
assetCounts: counts ?? {},
|
||||
agents: agentList,
|
||||
mcpServers: mcpList,
|
||||
skills: skillList,
|
||||
tools: toolList,
|
||||
llmProfiles: profileList,
|
||||
usageStats: usage,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
/* transient errors */
|
||||
}
|
||||
@@ -329,13 +313,6 @@ export default function DashboardPage() {
|
||||
// tasks whose llm_profile_id is null/undefined used the active default profile
|
||||
const defaultProfileId = activeProfile ? Number(activeProfile.id) : null;
|
||||
|
||||
// Data source toggle: old = activity (task.tokens + conversations), new = the llm_usage metering ledger.
|
||||
const [tokenVersion, setTokenVersion] = React.useState<"old" | "new">("old");
|
||||
// selected profile tab: "all" = all; number = specific profile id
|
||||
const [tokenTab, setTokenTab] = React.useState<number | null | "all">("all");
|
||||
// day range for the daily bar chart
|
||||
const [tokenDays, setTokenDays] = React.useState<7 | 30 | 90 | 180 | 365>(30);
|
||||
|
||||
// profile name → id, mapping llm_usage profile_name to the existing profile tabs.
|
||||
const profileIdByName = React.useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
@@ -616,7 +593,7 @@ export default function DashboardPage() {
|
||||
<button
|
||||
type="button"
|
||||
key={v}
|
||||
onClick={() => setTokenVersion(v)}
|
||||
onClick={() => dispatch({ type: "tokenViewChanged", patch: { version: v } })}
|
||||
title={
|
||||
v === "new"
|
||||
? t(
|
||||
@@ -645,7 +622,7 @@ export default function DashboardPage() {
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTokenTab("all")}
|
||||
onClick={() => dispatch({ type: "tokenViewChanged", patch: { tab: "all" } })}
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-[10px] font-medium transition-colors",
|
||||
tokenTab === "all"
|
||||
@@ -663,7 +640,7 @@ export default function DashboardPage() {
|
||||
<button
|
||||
type="button"
|
||||
key={p.id}
|
||||
onClick={() => setTokenTab(resolvedKey)}
|
||||
onClick={() => dispatch({ type: "tokenViewChanged", patch: { tab: resolvedKey } })}
|
||||
className={cn(
|
||||
"flex items-center gap-1 rounded-md px-2.5 py-1 text-[10px] font-medium transition-colors",
|
||||
tokenTab === resolvedKey
|
||||
@@ -795,7 +772,7 @@ export default function DashboardPage() {
|
||||
<button
|
||||
type="button"
|
||||
key={days}
|
||||
onClick={() => setTokenDays(days)}
|
||||
onClick={() => dispatch({ type: "tokenViewChanged", patch: { days } })}
|
||||
className={cn(
|
||||
"rounded px-2.5 py-0.5 text-[9px] font-medium transition-colors",
|
||||
tokenDays === days
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { SharedBrowserStatus } from "@/lib/types";
|
||||
|
||||
/** The address bar: what is typed, and whether the operator is typing (so tab changes don't overwrite it). */
|
||||
export type AddressBar = {
|
||||
value: string;
|
||||
editing: boolean;
|
||||
};
|
||||
|
||||
export type SharedBrowserPageState = {
|
||||
status: SharedBrowserStatus;
|
||||
frame: string;
|
||||
connected: boolean;
|
||||
address: AddressBar;
|
||||
/** `control` covers start/stop/navigation actions; load and input errors land on it too. */
|
||||
requests: Requests<"control">;
|
||||
};
|
||||
|
||||
export type SharedBrowserPageAction =
|
||||
| RequestAction<"control">
|
||||
| { type: "statusChanged"; status: SharedBrowserStatus }
|
||||
| { type: "frameReceived"; frame: string }
|
||||
| { type: "connectionChanged"; connected: boolean }
|
||||
| { type: "addressChanged"; patch: Partial<AddressBar> };
|
||||
|
||||
/** The empty status comes from the page, which owns its defaults. */
|
||||
export function initSharedBrowserPageState(status: SharedBrowserStatus): SharedBrowserPageState {
|
||||
return {
|
||||
status,
|
||||
frame: "",
|
||||
connected: false,
|
||||
address: { value: "", editing: false },
|
||||
requests: createRequests(["control"]),
|
||||
};
|
||||
}
|
||||
|
||||
export function sharedBrowserPageReducer(
|
||||
state: SharedBrowserPageState,
|
||||
action: SharedBrowserPageAction,
|
||||
): SharedBrowserPageState {
|
||||
if (isRequestAction<"control">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
switch (action.type) {
|
||||
case "statusChanged":
|
||||
return { ...state, status: action.status };
|
||||
case "frameReceived":
|
||||
return { ...state, frame: action.frame };
|
||||
case "connectionChanged":
|
||||
return action.connected === state.connected ? state : { ...state, connected: action.connected };
|
||||
case "addressChanged":
|
||||
return setSlice(state, "address", mergePatch(state.address, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import { MOCK } from "@/lib/mock/enabled";
|
||||
import type { SharedBrowserAction, SharedBrowserInput, SharedBrowserStatus } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { initSharedBrowserPageState, sharedBrowserPageReducer } from "./_state/shared-browser-page.reducer";
|
||||
|
||||
// The shared browser: the same Chromium the agents drive through the browser MCP.
|
||||
// The page shows its viewed tab live (CDP screencast frames over SSE). Take over to
|
||||
// solve a CAPTCHA, enter an OTP or sign in; the agent's browser tools wait while
|
||||
@@ -65,13 +67,10 @@ function tabLabel(tab: { title: string; url: string }): string {
|
||||
}
|
||||
|
||||
export default function SharedBrowserPage() {
|
||||
const [status, setStatus] = React.useState<SharedBrowserStatus>(EMPTY);
|
||||
const [frame, setFrame] = React.useState<string>("");
|
||||
const [address, setAddress] = React.useState("");
|
||||
const [editingAddress, setEditingAddress] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const [connected, setConnected] = React.useState(false);
|
||||
const [state, dispatch] = React.useReducer(sharedBrowserPageReducer, EMPTY, initSharedBrowserPageState);
|
||||
const { status, frame, connected } = state;
|
||||
const { value: address, editing: editingAddress } = state.address;
|
||||
const { pending: busy, error } = state.requests.control;
|
||||
|
||||
const viewRef = React.useRef<HTMLDivElement>(null);
|
||||
const imgRef = React.useRef<HTMLImageElement>(null);
|
||||
@@ -86,7 +85,7 @@ export default function SharedBrowserPage() {
|
||||
|
||||
// Keep the address bar on the viewed tab's URL unless the operator is typing.
|
||||
React.useEffect(() => {
|
||||
if (!editingAddress) setAddress(viewedTab?.url ?? "");
|
||||
if (!editingAddress) dispatch({ type: "addressChanged", patch: { value: viewedTab?.url ?? "" } });
|
||||
}, [viewedTab?.url, editingAddress]);
|
||||
|
||||
// Live view: status and frame events.
|
||||
@@ -96,15 +95,16 @@ export default function SharedBrowserPage() {
|
||||
let closed = false;
|
||||
const open = () => {
|
||||
es = openSSE("/api/browser/stream");
|
||||
es.onopen = () => setConnected(true);
|
||||
es.onerror = () => setConnected(false); // The stream reconnects by itself.
|
||||
es.onopen = () => dispatch({ type: "connectionChanged", connected: true });
|
||||
es.onerror = () => dispatch({ type: "connectionChanged", connected: false }); // The stream reconnects by itself.
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const ev = JSON.parse(e.data) as
|
||||
| { type: "status"; status: SharedBrowserStatus }
|
||||
| { type: "frame"; data: string };
|
||||
if (ev.type === "status") setStatus({ ...ev.status, tabs: ev.status.tabs ?? [] });
|
||||
else if (ev.type === "frame") setFrame(ev.data);
|
||||
if (ev.type === "status")
|
||||
dispatch({ type: "statusChanged", status: { ...ev.status, tabs: ev.status.tabs ?? [] } });
|
||||
else if (ev.type === "frame") dispatch({ type: "frameReceived", frame: ev.data });
|
||||
} catch {
|
||||
/* ignore a malformed event */
|
||||
}
|
||||
@@ -115,10 +115,12 @@ export default function SharedBrowserPage() {
|
||||
.browserStatus()
|
||||
.then((s) => {
|
||||
if (closed) return;
|
||||
setStatus(s);
|
||||
dispatch({ type: "statusChanged", status: s });
|
||||
if (s.enabled) open();
|
||||
})
|
||||
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
|
||||
.catch((e: unknown) =>
|
||||
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) }),
|
||||
);
|
||||
return () => {
|
||||
closed = true;
|
||||
es?.close();
|
||||
@@ -126,15 +128,14 @@ export default function SharedBrowserPage() {
|
||||
}, []);
|
||||
|
||||
const run = React.useCallback(async (fn: () => Promise<SharedBrowserStatus | undefined>) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
dispatch({ type: "request/started", key: "control" });
|
||||
try {
|
||||
const s = await fn();
|
||||
if (s) setStatus({ ...s, tabs: s.tabs ?? [] });
|
||||
if (s) dispatch({ type: "statusChanged", status: { ...s, tabs: s.tabs ?? [] } });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "request/finished", key: "control" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -149,7 +150,11 @@ export default function SharedBrowserPage() {
|
||||
const events = queue.current;
|
||||
queue.current = [];
|
||||
if (!events.length) return;
|
||||
api.browserInput(events).catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
|
||||
api
|
||||
.browserInput(events)
|
||||
.catch((e: unknown) =>
|
||||
dispatch({ type: "request/failed", key: "control", error: e instanceof Error ? e.message : String(e) }),
|
||||
);
|
||||
}, []);
|
||||
const send = React.useCallback(
|
||||
(ev: SharedBrowserInput) => {
|
||||
@@ -233,7 +238,7 @@ export default function SharedBrowserPage() {
|
||||
|
||||
const submitAddress = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setEditingAddress(false);
|
||||
dispatch({ type: "addressChanged", patch: { editing: false } });
|
||||
if (address.trim()) void control("goto", address.trim());
|
||||
};
|
||||
|
||||
@@ -356,9 +361,9 @@ export default function SharedBrowserPage() {
|
||||
value={address}
|
||||
placeholder={t("Address")}
|
||||
disabled={!status.running}
|
||||
onFocus={() => setEditingAddress(true)}
|
||||
onBlur={() => setEditingAddress(false)}
|
||||
onChange={(e) => setAddress(e.target.value)}
|
||||
onFocus={() => dispatch({ type: "addressChanged", patch: { editing: true } })}
|
||||
onBlur={() => dispatch({ type: "addressChanged", patch: { editing: false } })}
|
||||
onChange={(e) => dispatch({ type: "addressChanged", patch: { value: e.target.value } })}
|
||||
/>
|
||||
</form>
|
||||
{status.tabs.length > 0 && (
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { assetsTabReducer, initialAssetsTabState } from "./assets-tab.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialAssetsTabState) => actions.reduce(assetsTabReducer, state);
|
||||
|
||||
test("tab change returns to the first page and clears the search and its error", () => {
|
||||
const s = reduce([
|
||||
{ type: "queryChanged", query: "host=x" },
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
{ type: "searchFailed", error: "bad dsl" },
|
||||
{ type: "tabChanged", tab: "ip" },
|
||||
]);
|
||||
assert.equal(s.filters.query, "");
|
||||
assert.equal(s.pagination.page, 0);
|
||||
assert.equal(s.listMeta.dslError, "");
|
||||
});
|
||||
|
||||
test("load cycle fills rows and counts; a failed search empties the rows", () => {
|
||||
const loaded = reduce([
|
||||
{ type: "list/loadStarted" },
|
||||
{ type: "assetsLoaded", rows: [{ id: 1 }], total: 7, counts: { ip: 7 } },
|
||||
{ type: "list/loadFinished" },
|
||||
]);
|
||||
assert.deepEqual(loaded.list, { items: [{ id: 1 }], total: 7, loading: false, loaded: true });
|
||||
assert.deepEqual(loaded.listMeta.counts, { ip: 7 });
|
||||
const failed = reduce([{ type: "searchFailed", error: "boom" }], loaded);
|
||||
assert.deepEqual(failed.list.items, []);
|
||||
assert.equal(failed.list.total, 0);
|
||||
assert.equal(failed.listMeta.dslError, "boom");
|
||||
assert.deepEqual(failed.listMeta.counts, { ip: 7 });
|
||||
});
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed one does not", () => {
|
||||
const loaded = { type: "assetsLoaded", rows: [{ id: 1, value: "a.example" }], total: 1, counts: { domain: 1 } };
|
||||
const s = reduce([loaded]);
|
||||
assert.equal(reduce([structuredClone(loaded)], s), s);
|
||||
assert.notEqual(reduce([{ ...loaded, counts: { domain: 2 } }], s), s);
|
||||
});
|
||||
|
||||
test("a poll that changes one nested field of one row updates that row", () => {
|
||||
const rows = [
|
||||
{ id: 1, value: "a.example", open_ports: [{ port: 80, service: "http" }] },
|
||||
{ id: 2, value: "b.example", open_ports: [] },
|
||||
];
|
||||
const s = reduce([{ type: "assetsLoaded", rows, total: 2, counts: { domain: 2 } }]);
|
||||
const next = structuredClone(rows);
|
||||
next[0].open_ports[0].service = "https";
|
||||
const updated = reduce([{ type: "assetsLoaded", rows: next, total: 2, counts: { domain: 2 } }], s);
|
||||
assert.notEqual(updated, s);
|
||||
assert.equal(updated.list.items[0].open_ports[0].service, "https");
|
||||
assert.deepEqual(updated.list.items[1], rows[1]);
|
||||
});
|
||||
|
||||
test("a successful load after a failed search clears the error and shows the rows", () => {
|
||||
const rows = [{ id: 1, value: "a.example" }];
|
||||
const s = reduce([
|
||||
{ type: "searchFailed", error: "bad dsl" },
|
||||
{ type: "assetsLoaded", rows, total: 1, counts: { domain: 1 } },
|
||||
]);
|
||||
assert.equal(s.listMeta.dslError, "");
|
||||
assert.deepEqual(s.list.items, rows);
|
||||
assert.equal(s.list.total, 1);
|
||||
});
|
||||
|
||||
test("a successful load with the same counts after a failed search still clears the error", () => {
|
||||
const counts = { domain: 3 };
|
||||
const rows = [{ id: 1, value: "a.example" }];
|
||||
const s = reduce([
|
||||
{ type: "assetsLoaded", rows, total: 1, counts },
|
||||
{ type: "searchFailed", error: "bad dsl" },
|
||||
{ type: "assetsLoaded", rows: [], total: 0, counts },
|
||||
]);
|
||||
assert.equal(s.listMeta.dslError, "");
|
||||
assert.deepEqual(s.list.items, []);
|
||||
assert.equal(s.list.total, 0);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Asset, NewAssetType } from "@/lib/types";
|
||||
|
||||
export const DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
export type AssetsFilters = {
|
||||
/** Asset type tab. */
|
||||
tab: NewAssetType;
|
||||
/** Raw DSL search box value; empty means a plain listing. */
|
||||
query: string;
|
||||
};
|
||||
|
||||
/** What comes with the asset list besides its rows. */
|
||||
export type AssetsListMeta = {
|
||||
/** Per-type asset counts shown on the tabs. */
|
||||
counts: Record<string, number>;
|
||||
/** Error from the last DSL search, shown under the search box. */
|
||||
dslError: string;
|
||||
/** Bumped to force a reload. */
|
||||
refreshKey: number;
|
||||
};
|
||||
|
||||
export type AssetsDialogs = {
|
||||
addOpen: boolean;
|
||||
/** Asset awaiting remove confirmation. */
|
||||
removeTarget: Asset | null;
|
||||
};
|
||||
|
||||
export type AssetsTabState = {
|
||||
filters: AssetsFilters;
|
||||
/** Zero-based pages. */
|
||||
pagination: Pagination;
|
||||
/**
|
||||
* `loaded` is false until the first load settles, and again after a manual refresh until that load settles
|
||||
* (shows the spinner row). Tab, page and query changes do not reset it.
|
||||
*/
|
||||
list: ListState<Asset>;
|
||||
listMeta: AssetsListMeta;
|
||||
dialogs: AssetsDialogs;
|
||||
requests: Requests<"remove">;
|
||||
};
|
||||
|
||||
export type AssetsTabAction =
|
||||
| PaginationAction
|
||||
| ListAction<Asset>
|
||||
| RequestAction<"remove">
|
||||
| { type: "tabChanged"; tab: NewAssetType }
|
||||
| { type: "queryChanged"; query: string }
|
||||
| { type: "assetsLoaded"; rows: Asset[]; total: number; counts: Record<string, number> }
|
||||
| { type: "searchFailed"; error: string }
|
||||
| { type: "refreshRequested" }
|
||||
| { type: "dialogsChanged"; patch: Partial<AssetsDialogs> };
|
||||
|
||||
export const initialAssetsTabState: AssetsTabState = {
|
||||
filters: { tab: "root_domain", query: "" },
|
||||
pagination: createPagination(DEFAULT_PAGE_SIZE),
|
||||
list: createList(),
|
||||
listMeta: { counts: {}, dslError: "", refreshKey: 0 },
|
||||
dialogs: { addOpen: false, removeTarget: null },
|
||||
requests: createRequests(["remove"]),
|
||||
};
|
||||
|
||||
export function assetsTabReducer(state: AssetsTabState, action: AssetsTabAction): AssetsTabState {
|
||||
// Page-size changes restart server pagination inside the slice.
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<Asset>(action)) return setSlice(state, "list", listReducer(state.list, action));
|
||||
if (isRequestAction<"remove">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
switch (action.type) {
|
||||
case "tabChanged":
|
||||
if (action.tab === state.filters.tab) return state;
|
||||
// DSL fields differ per type, so switching tabs also clears the search.
|
||||
return {
|
||||
...state,
|
||||
filters: { tab: action.tab, query: "" },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
listMeta: { ...state.listMeta, dslError: "" },
|
||||
};
|
||||
case "queryChanged":
|
||||
if (action.query === state.filters.query) return state;
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, query: action.query },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "assetsLoaded":
|
||||
// The tab polls every 10 s; an unchanged page returns the same state object, so React can bail out of the update.
|
||||
if (
|
||||
!state.listMeta.dslError &&
|
||||
state.list.total === action.total &&
|
||||
JSON.stringify([state.list.items, state.listMeta.counts]) === JSON.stringify([action.rows, action.counts])
|
||||
)
|
||||
return state;
|
||||
return {
|
||||
...state,
|
||||
list: listReducer(state.list, { type: "list/loaded", items: action.rows, total: action.total }),
|
||||
listMeta: { ...state.listMeta, counts: action.counts, dslError: "" },
|
||||
};
|
||||
case "searchFailed":
|
||||
return {
|
||||
...state,
|
||||
list: listReducer(state.list, { type: "list/loaded", items: [], total: 0 }),
|
||||
listMeta: { ...state.listMeta, dslError: action.error },
|
||||
};
|
||||
case "refreshRequested":
|
||||
return {
|
||||
...state,
|
||||
list: { ...state.list, loaded: false },
|
||||
listMeta: { ...state.listMeta, refreshKey: state.listMeta.refreshKey + 1 },
|
||||
};
|
||||
case "dialogsChanged":
|
||||
return setSlice(state, "dialogs", mergePatch(state.dialogs, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { CoverageGraphEdge, CoverageGraphNode } from "@/lib/types";
|
||||
|
||||
export type CoverageGraphData = {
|
||||
nodes: CoverageGraphNode[];
|
||||
edges: CoverageGraphEdge[];
|
||||
};
|
||||
|
||||
export type CoverageGraphSelection = {
|
||||
/** Asset shown in the asset detail sheet. */
|
||||
asset: CoverageGraphNode | null;
|
||||
/** Key of the fold node shown in the fold sheet. */
|
||||
foldId: string | null;
|
||||
};
|
||||
|
||||
export type CoverageGraphState = {
|
||||
/** Null until the first successful fetch; a failed refetch keeps the previous data. */
|
||||
data: CoverageGraphData | null;
|
||||
loading: boolean;
|
||||
/** Fold group id → number of children shown (groups not in the map use the default limit). */
|
||||
expanded: Map<string, number>;
|
||||
selection: CoverageGraphSelection;
|
||||
};
|
||||
|
||||
export type CoverageGraphAction =
|
||||
| { type: "fetchStarted" }
|
||||
| { type: "fetched"; data: CoverageGraphData }
|
||||
| { type: "fetchFinished" }
|
||||
| { type: "foldExpanded"; groupId: string; defaultShown: number; step: number }
|
||||
| { type: "assetSelected"; asset: CoverageGraphNode | null }
|
||||
| { type: "foldSelected"; foldId: string | null }
|
||||
| { type: "foldItemPicked"; asset: CoverageGraphNode };
|
||||
|
||||
export function initCoverageGraphState(): CoverageGraphState {
|
||||
return {
|
||||
data: null,
|
||||
loading: true,
|
||||
expanded: new Map(),
|
||||
selection: { asset: null, foldId: null },
|
||||
};
|
||||
}
|
||||
|
||||
export function coverageGraphReducer(state: CoverageGraphState, action: CoverageGraphAction): CoverageGraphState {
|
||||
switch (action.type) {
|
||||
case "fetchStarted":
|
||||
return { ...state, loading: true };
|
||||
case "fetched":
|
||||
return { ...state, data: action.data };
|
||||
case "fetchFinished":
|
||||
return { ...state, loading: false };
|
||||
case "foldExpanded": {
|
||||
const expanded = new Map(state.expanded);
|
||||
expanded.set(action.groupId, (expanded.get(action.groupId) ?? action.defaultShown) + action.step);
|
||||
return { ...state, expanded };
|
||||
}
|
||||
case "assetSelected":
|
||||
return { ...state, selection: { ...state.selection, asset: action.asset } };
|
||||
case "foldSelected":
|
||||
return { ...state, selection: { ...state.selection, foldId: action.foldId } };
|
||||
case "foldItemPicked":
|
||||
// Picking a hidden child closes the fold sheet and opens that asset.
|
||||
return { ...state, selection: { asset: action.asset, foldId: null } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { credentialsTabReducer, initialCredentialsTabState } from "./credentials-tab.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed one or a recovery does not", () => {
|
||||
const items = [{ id: 1, domain: "a.example", username: "u" }];
|
||||
const s = credentialsTabReducer(initialCredentialsTabState, { type: "listLoaded", items });
|
||||
assert.equal(credentialsTabReducer(s, { type: "listLoaded", items: structuredClone(items) }), s);
|
||||
assert.equal(credentialsTabReducer(s, { type: "listLoaded", items: [] }).items.length, 0);
|
||||
const failed = credentialsTabReducer(s, { type: "failed", error: "offline" });
|
||||
assert.equal(credentialsTabReducer(failed, { type: "listLoaded", items }).error, "");
|
||||
});
|
||||
|
||||
test("a poll that changes one field of one row updates that row", () => {
|
||||
const items = [
|
||||
{ id: 1, domain: "a.example", username: "u", note: "" },
|
||||
{ id: 2, domain: "b.example", username: "v", note: "" },
|
||||
];
|
||||
const s = credentialsTabReducer(initialCredentialsTabState, { type: "listLoaded", items });
|
||||
const next = structuredClone(items);
|
||||
next[1].note = "admin";
|
||||
const updated = credentialsTabReducer(s, { type: "listLoaded", items: next });
|
||||
assert.notEqual(updated, s);
|
||||
assert.equal(updated.items[1].note, "admin");
|
||||
assert.deepEqual(updated.items[0], items[0]);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user