Merge remote-tracking branch 'upstream/main' into codex/s3-archive-ui-docs

This commit is contained in:
renaesop
2026-11-20 14:21:05 +00:00
199 changed files with 11714 additions and 603 deletions
+112
View File
@@ -0,0 +1,112 @@
# ARTEX architecture (code-level companion)
The README's [Architecture](https://github.com/BaaRai/ARTEX#architecture) section has the
component diagram and the 10,000-foot view. This document records the code-level map,
the execution flow and the trust boundaries that are easy to miss when reading the
packages in isolation.
## 1. The two graphs
ARTEX keeps two linked graphs, both in PostgreSQL (`db/schema.sql`):
| Graph | Answers | Main tables | Code |
| --- | --- | --- | --- |
| **Asset graph** | *What exists?* | `companies`, `company_scope`, `assets`, `task_scope` | `db/assets.go`, `db/companies.go`, `db/company_scope.go`, `db/task_assets.go` |
| **Exploration graph** | *What was tried, with what result and why?* | `explorations`, `exploration_nodes`, `activity`, `intent_*`, `coverage_*` | `db/exploration.go`, `db/coverage_ledger.go`, `db/finding_assets.go` |
Anchors tie a finding to the assets that justify it (`db/finding_assets.go`). Traffic
snapshots are archived separately and referenced from findings
(`db/finding_traffic.go`, `db/finding_traffic_archive.go`, `traffic/archive.go`).
`db.Open` executes the idempotent `schema.sql` on every startup, then applies pending
numbered migrations from `db/migrations/*.sql`, recording name + SHA-256 in
`schema_migrations`. A published migration is never edited; fix forward with a new one.
## 2. Package map
| Package | Responsibility | Notes |
| --- | --- | --- |
| `cmd/artex` | Process entry point | Flags (`-addr`, `-data`, `-proxy`), startup config snapshot, signal handling, graceful drain |
| `config` | Resolve config file + env | `Path`, `Load`, `PostgresDSN`, `SkillDir`, `KeyDir`, `Redact`. Env wins over file |
| `db` | All persistence | `DB`, `Manager`-independent stores; AES-256-GCM secret columns in `secrets.go` |
| `agent` | LLM roles and tools | `goals`, `planner`, `worker`, `mainagent`, `retester`; `ToolSet` in `tools.go`; tool catalog in `toolcatalog.go` |
| `server` | HTTP API + orchestration | `net/http` mux (~270 routes), `Manager`, `Engine`, JWT auth, SSE broadcaster |
| `traffic` | Recording proxy | MITM proxy built on `go-mitmproxy`, replay, rewrite rules, body archive |
| `evidence` | Evidence store | Persisted request/response snapshots used by findings |
| `intercept` | Approval gate | Judge, argv grammar, target gate, pins, risk scoring (a `PreToolUse` hook) |
| `guard` | Hook wiring | Binds `intercept` decisions into Norma's hook registry; `NewTargetOnly` for planner/mainagent |
| `egress` | Noise governor | Per-host token bucket, jitter, concurrency caps, 429/503 backoff; default profile is strict passthrough |
| `llmpool` / `llmrec` | Provider pool / recorder | Rotation, health, usage + raw wire capture |
| `mcphttp` | MCP client | HTTP/SSE transport for configured MCP servers |
| `notify` | Outbound notifications | Email, webhook, Telegram, Feishu, DingTalk with masking and SSRF guards |
| `report` | Deliverables | Markdown, CSV and JSON rendering of findings |
| `sidequestion` | Operator Q&A | Asks a human mid-run and suspends intent until answered |
| `skills/` | Skill definitions | One `SKILL.md` per subdirectory, loaded from `SkillDir()` |
The frontend lives in `web/` (Next.js 16, React 19) and is embedded into the Go
binary via `server/webui_embed.go` when built with `-tags embedui`.
## 3. End-to-end flow: goal → finding with evidence
1. **Task creation.** `server.createTask` → `Manager.CreateTaskWithOptions` writes the
task, its scope and seed goals, and creates the exploration graph (`db/tasks.go`).
2. **Loop start.** `Engine.Run` (`server/engine.go`) starts a planner loop and N worker
goroutines under a task-scoped context. Nothing needs an LLM to be configured for the
loops to exist; they idle until one is.
3. **Decomposition.** The `goals` role writes goals and operation constraints through
`set_goals` / `set_constraints` (`agent/toolcatalog.go`, `agent/tools.go`).
4. **Planning.** `Planner.Plan` (`agent/planner.go`) reads the route, queries the asset
graph, judges goals and emits intents (`addOneIntent`). Every intent is an
exploration node, so it is auditable like any other activity.
5. **Execution.** `Worker.Execute` (`agent/worker.go`) claims an intent, runs tools with
the guard hooks attached and writes observed facts back to the exploration graph.
6. **Tools and traffic.** Shell and HTTP/WebFetch calls go through the recording proxy
and the egress governor. Platform-owned HTTP clients use `intercept.PinnedDialer`
and `intercept.RedirectCheck`, so a redirect or a direct retry is re-checked at
dial time. When a proxy is in the path the gate records the pin as name-only: the
proxy makes the outbound connection, so no IP binding can be claimed.
7. **Findings.** `addFinding` (`agent/tools.go`) records severity, class, confidence and
asset references; `db/findings.go` dedups and keeps the status workflow. Evidence is
linked to captured traffic (`traffic/evidence.go`, `db/finding_traffic.go`).
8. **Completion.** `prove_goal` marks a goal met; the last met goal completes the task.
`goal_met` is deliberately unbound by default because it bypasses per-goal proof.
## 4. Execution control
- **Per-task context:** pause/cancel/kill attach a named cause via
`context.WithCancelCause` so the activity trace records who initiated a stop.
- **Per-intent control:** the UI can pause/cancel one intent; `steerBox` queues a
planner course-correction that the worker's `PreToolUse` hook drains before the next
tool call, re-planning without killing the run.
- **Delete barrier:** `Engine.BeginDelete` makes installing the barrier atomic with
registering an in-flight operation; after it returns, no new task-owned writes are
admitted and the task context is cancelled once existing writers drain.
- **Quiet mode:** an unchanged open-goal fingerprint suppresses redundant planning
rounds while work is still in flight.
## 5. Trust boundaries
| Boundary | Implementation |
| --- | --- |
| Tool output → model | Norma's untrusted-output boundary: nonce-tagged markers around tool results. On by default; `ARTEX_UNTRUSTED_BOUNDARY=0` disables it. See `agent/untrusted_boundary.go` |
| Command → host | Allow rules match one Bash simple command with the exact prefix: a pipeline, redirection, wrapper (`env`, `sudo`, `xargs`, `find -exec`, a shell `-c`), substitution or expansion does not inherit an allow. Deny and ask rules also inspect every simple command inside wrappers, lists and pipelines. `ArgvPrefixOf` derives the human-readable prefix |
| URL → network | Target gate + `PinnedDialer` + `RedirectCheck`: scope decisions are re-made against a fresh DNS lookup at dial time, and without a proxy the client connects only to the addresses it compared; with a proxy the pin is name-only |
| Secrets → disk/log | `db/secrets.go` seals API keys, proxy credentials, MCP env, task credentials and captured auth headers with AES-256-GCM, nonce per value, AAD `table.column`. JWT keys live in `KeyDir()`, never in the browsable data dir. The boot snapshot logs only `config.Redact(dsn)` |
| Approval → audit | Every decision records the approver (`jwtSubject`), source and decision; history is queryable through `/api/intercept/history` and `/api/intercept/history/{id}` (with `/execution` for the audit detail). `/api/tasks/{id}/intercept-rules` manages rules, not history |
## 6. Decisions
- **ADR-001 — Nonce-tagged untrusted output.** Tool output is framed with a per-run
nonce rather than trusting the model to distinguish instructions from data.
- **ADR-002 — Pin at dial time.** A URL decision is not enough: DNS can change between
the hook and the connection, so the dialer re-resolves and connects only to compared
addresses.
- **ADR-003 — AES-GCM with per-column AAD.** Sealed values are bound to their table and
column (and settings to their key), so a ciphertext cannot be moved to another field.
## 7. Where to look next
- `docs/OPS.md` for startup, configuration precedence, backup and key rotation.
- `docs/vulnerability-traffic-evidence.md` for how a finding keeps its receipts.
- `docs/traffic-rewrite-rules.md` for the rewrite engine.
- `scripts/verify.sh` to reproduce the CI checks locally.
+93
View File
@@ -0,0 +1,93 @@
# ARTEX operations
## 1. Startup
Docker (recommended):
```bash
cp .env.example .env # set POSTGRES_PASSWORD; optionally an LLM key
docker compose up -d --build
docker compose logs artex | grep "Setup token"
```
Open `http://localhost:8787`. The first visit to `/setup` asks for the one-time setup
token printed at startup (`[auth] no admin password is set. Setup token for the /setup
page: ...` in `server/auth.go`).
From source (no embedded UI):
```bash
go run ./cmd/artex # backend only, 127.0.0.1:8787
cd web && npm run dev # UI on :5173, /api proxied to the backend
# or: ./dev.sh # both, plus the traffic proxy on :8788
```
The process prints one `[config] snapshot {...}` line at startup. It is the authoritative
record of the effective configuration: config path, DSN source and **redacted** DSN,
data/skill/key directories, listen address, proxy, noise profile, untrusted-output
boundary and trusted proxies. No password or token value is ever logged there.
## 2. Configuration precedence
| Setting | Resolution order | Code |
| --- | --- | --- |
| Config file | `ARTEX_CONFIG` → `./config.json` → `config.json` next to the binary | `config.Path` |
| PostgreSQL DSN | `ARTEX_PG_DSN` → `database.dsn` → assembled `host/port/user/password/dbname` | `config.PostgresDSN` |
| Skill directory | `ARTEX_SKILL_DIR` → `skill_dir` → `<binary dir>/skills` | `config.SkillDir` |
| JWT / secret key directory | `ARTEX_JWT_KEY_DIR` → `<binary dir>` (never the browsable data dir) | `config.KeyDir` |
| Secret encryption key | `ARTEX_SECRET_KEY` → `<key dir>/secret.key` → newly generated key file | `db.InitSecrets` |
| Noise profile | `ARTEX_NOISE_PROFILE` (`off` default; `quiet`, `balanced`, `aggressive`), also settable in UI | `egress.ProfileFromEnv` |
| Untrusted-output boundary | on by default; `ARTEX_UNTRUSTED_BOUNDARY=0\|false\|off\|no` disables it | `agent/untrusted_boundary.go` |
| Trusted proxies for login rate limit | `ARTEX_TRUSTED_PROXIES` (comma-separated IPs/CIDRs; empty trusts none) | `server.ParseTrustedProxies` |
| Target user agent | `ARTEX_TARGET_USER_AGENT` (applied by non-`off` noise profiles) | `egress.ProfileByName` |
| Budgets | `ARTEX_TASK_BUDGET_TOKENS` / `_TURNS`, `ARTEX_INTENT_BUDGET_TOKENS` / `_TURNS` | `agent/budget.go` |
| Live model judge test | `ARTEX_REVIEW_LIVE_CONFIG` (opt-in integration test only) | `server/intercept_live_test.go` |
Agent profiles, providers, notifications and other runtime settings live in the database
and are edited in **System → LLM / Settings / Notify**, not in `config.json`.
## 3. Backup and restore
```bash
scripts/backup.sh # database dump only, 14 rotations
scripts/backup.sh --with-data --keep 30 # also archive the data/ bind mount
```
The dump runs inside the `postgres` compose service, so no host `psql` is needed. Restore:
```bash
gunzip -c backups/artex-db-<ts>.sql.gz | docker compose exec -T postgres \
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"
```
Back up the key directory as well: without it, JWTs cannot be verified and sealed
secrets cannot be decrypted. Keep it outside the database backup but under the same
access controls.
## 4. Key rotation
- **`jwt.key`** — signing key for the 7-day HS256 session tokens. Replacing it
invalidates every existing session; all users must log in again. Existing key files
are never overwritten by startup (`loadOrCreateJWTKey`).
- **`secret.key`** (or `ARTEX_SECRET_KEY`) — AES-256-GCM key for API keys, MCP env,
task credentials and captured auth headers. Startup never overwrites an existing key.
If it changes, values sealed under the old key cannot be decrypted (the code returns
an error rather than leaking ciphertext as plaintext). Re-enter those secrets in the
UI, or keep the previous key available until the migration is complete.
Plan a short maintenance window for either rotation.
## 5. Diagnostics and local verification
- `GET /api/health` — liveness, build version and provider health.
- `GET /api/logs`, `GET /api/logs/stream` — live backend log sink; the UI shows it under
**System → Logs**. The startup snapshot line is here too.
- `scripts/verify.sh` — reproduces the CI checks locally (gofmt, build, vet, tests,
web type-check and unit tests, shellcheck, python checks). `--full` adds `-race` and
the web static build; `--go-only` / `--web-only` narrow the run.
- `./scripts/backup.sh --help` — backup options.
When Postgres is not configured, database-dependent tests skip themselves; that is
expected. Set `ARTEX_PG_DSN` to run them. CI uses `go test -p 1 ./...` because test
packages share a Postgres service and use suffixed per-package databases
(`SuffixTestDatabase`).
+25
View File
@@ -0,0 +1,25 @@
[Unit]
Description=ARTEX application
After=network.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=artex
Group=artex
WorkingDirectory=/opt/artex
Environment=ARTEX_JWT_KEY_DIR=/opt/artex/keys
ExecStart=/opt/artex/artex -addr 127.0.0.1:8787 -proxy 127.0.0.1:8788
Restart=on-failure
RestartSec=5s
TimeoutStopSec=30s
KillSignal=SIGTERM
KillMode=control-group
UMask=0002
StandardOutput=journal
StandardError=journal
SyslogIdentifier=artex
[Install]
WantedBy=multi-user.target
+178
View File
@@ -0,0 +1,178 @@
# Local ARTEX systemd deployment
This guide describes how to deploy ARTEX locally under `systemd` using the example unit at `docs/examples/artex.service`.
## Placeholders and defaults
The example unit uses these defaults; replace them if your host uses different paths or names:
- Install directory (`<install-dir>`): `/opt/artex` (executable at `/opt/artex/artex`).
- System user and group (`<artex-user>`): `artex` (non-root).
- PostgreSQL service unit (`<pg-unit>`): distribution-specific — for example `postgresql.service` on RHEL/Fedora/Arch or `postgresql@<pg-version>-<pg-cluster>.service` on Debian/Ubuntu (where `<pg-version>/<pg-cluster>` comes from `pg_lsclusters`, such as `18/main`).
- Configuration: `<install-dir>/config.json`, ignored by Git, owner-only mode `0600`.
- Web UI: `http://127.0.0.1:8787`; recording proxy: `127.0.0.1:8788`.
- Example unit file: `docs/examples/artex.service`; installed at `/etc/systemd/system/artex.service`.
## System user and directory permissions
Create a dedicated non-login system user and group before installing the binary:
```bash
sudo useradd --system --user-group --home-dir /opt/artex --shell /usr/sbin/nologin artex
```
Create the install, runtime data, and key directories with explicit ownership and modes:
```bash
sudo install -d -o root -g artex -m 0755 /opt/artex
sudo install -d -o artex -g artex -m 0770 /opt/artex/data
sudo install -d -o artex -g artex -m 0700 /opt/artex/keys
```
Directory ownership and modes:
- `<install-dir>` (`/opt/artex`): `root:<artex-user>`, mode `0755` (executable `/opt/artex/artex` mode `0755`).
- `<install-dir>/data` (`/opt/artex/data`): `<artex-user>:<artex-user>`, mode `0770` so the service user (and, in a root-run deployment using an executor group, that group) can write task run directories while blocking world access.
- `<install-dir>/keys` (`/opt/artex/keys`): `<artex-user>:<artex-user>`, mode `0700`. Holds `jwt.key` and `secret.key` (mode `0600`) outside the browsable `data/` directory. `docs/examples/artex.service` sets `Environment=ARTEX_JWT_KEY_DIR=/opt/artex/keys` so the non-root service writes key files here rather than into `root`-owned `/opt/artex` (if `ARTEX_JWT_KEY_DIR` were left unset, ARTEX would fall back to `<install-dir>` and fail to create `jwt.key` and `secret.key` when `<install-dir>` is `root:<artex-user>` `0755`).
- `<install-dir>/config.json` (`/opt/artex/config.json`): `<artex-user>:<artex-user>`, mode `0600`.
## Database and credentials
Install PostgreSQL on the host (or use an existing reachable PostgreSQL instance) and create a dedicated non-superuser login role and database named `artex` with no role-creation or database-creation privileges.
On Debian/Ubuntu, confirm the cluster name (`<pg-version>/<pg-cluster>`) with `pg_lsclusters`, start `<pg-unit>`, and create the role and database if absent:
```bash
sudo systemctl start <pg-unit>
sudo -u postgres createuser --pwprompt artex
sudo -u postgres createdb --owner=artex artex
```
Enter a unique password at the prompt. In `<install-dir>/config.json`, set `database.host` to `127.0.0.1`, `port` to `5432`, `user` and `dbname` to `artex`, `password` to that secret, and `sslmode` to `disable` (disabling TLS is appropriate only for loopback traffic). Preserve other settings and restrict access:
```bash
sudo chown artex:artex /opt/artex/config.json
sudo chmod 0600 /opt/artex/config.json
```
`ARTEX_PG_DSN`, if set in a systemd drop-in override, takes precedence over `config.json`. Never commit configuration, credentials, encryption/signing keys, or startup logs.
## Build and install
The binary embeds the UI when built with `-tags embedui`. To rebuild the UI from a source checkout, run `npm ci` and `npm run build:static` in `web/`, create the parent directory with `mkdir -p server/webui`, and replace `server/webui/dist` with `web/out`. Build the binary with:
```bash
CGO_ENABLED=0 go build -tags embedui -trimpath -o artex ./cmd/artex
```
Install the binary into `<install-dir>`:
```bash
sudo install -o root -g artex -m 0755 artex /opt/artex/artex
```
For a running deployment, build into a separate staging path and stop the service before replacing `/opt/artex/artex` or generated assets. Avoid rerunning `install.sh` without reviewing its prompts: it regenerates `config.json` and starts a separate process.
Review `User`, `Group`, `WorkingDirectory`, `Environment=ARTEX_JWT_KEY_DIR=...`, and `ExecStart` in `docs/examples/artex.service` before installing it on your host:
```bash
systemd-analyze verify docs/examples/artex.service
sudo install -o root -g root -m 0644 docs/examples/artex.service /etc/systemd/system/artex.service
sudo systemctl daemon-reload
```
### Database dependency and environment overrides
`docs/examples/artex.service` intentionally declares only `After=network.target` and does not hardcode a distribution-specific PostgreSQL unit (such as Debian's `postgresql@<pg-version>-<pg-cluster>.service`), so it works across Linux distributions and with remote PostgreSQL servers.
When PostgreSQL runs locally on the same host, add a systemd drop-in (`sudo systemctl edit artex.service`) so ARTEX starts after and depends on your local PostgreSQL unit:
```ini
[Unit]
Requires=<pg-unit>
After=<pg-unit>
```
For example, set `<pg-unit>` to `postgresql.service` on RHEL/Fedora/Arch, or to `postgresql@<pg-version>-<pg-cluster>.service` on Debian/Ubuntu (and verify `/etc/postgresql/<pg-version>/<pg-cluster>/start.conf` is `auto`, not `disabled`). `ARTEX_JWT_KEY_DIR=/opt/artex/keys` is already set in `docs/examples/artex.service`; override it in the drop-in only if you install ARTEX under a different `<install-dir>`. Run `sudo systemctl daemon-reload` after editing the drop-in.
### Enable and start
If ARTEX is running outside `systemd`, identify its PID/executable and send that verified process `SIGTERM`. Wait for shutdown and release of ports `8787` and `8788` before enabling the service:
```bash
ss -ltnp '( sport = :8787 or sport = :8788 )'
sudo systemctl enable --now artex.service
systemctl status artex.service --no-pager
curl --fail --silent --show-error http://127.0.0.1:8787/api/health
```
The unit runs `/opt/artex/artex` directly without an extra supervisor script. It starts after `network.target`, restarts on failure after five seconds, allows 30 seconds for graceful shutdown, logs to the journal, and uses `UMask=0002` (rather than `0077`, which would block group writes in a root-run deployment where executor privilege drop sets umask `002` for the executor group; sensitive files such as `config.json`, `keys/jwt.key`, and `keys/secret.key` are protected explicitly with `0600`/`0700` permissions). Five starts within 60 seconds trigger the start limit.
### Agent isolation
Because `docs/examples/artex.service` runs the server as the non-root `<artex-user>` (`User=artex`), the `-exec-uid`/`-exec-gid` privilege drop cannot be applied: `ResolveExecPrivilege` disables the drop when the server is not root (and errors if those flags are passed explicitly). The example unit deliberately omits `-exec-uid`/`-exec-gid`, so agents and spawned tools run under the `<artex-user>` service identity rather than a separate executor account. The root-owned run-directory layout and executor-group containment exist only when the server runs as root with explicit `-exec-uid`/`-exec-gid`; if you require unprivileged-executor containment, use the Docker deployment, which is the supported path for that isolation model.
## Web setup
On a new database, visit `http://127.0.0.1:8787/setup`, provide the one-time setup token from the private startup log or journal (`journalctl -u artex.service`), and choose a unique password of at least 12 characters. The username is `ARTEX`. Store the password in your password manager rather than in a plaintext file on disk.
## Reboot persistence verification (example)
Pre-reboot checks confirm persistent ARTEX enablement, active PostgreSQL and ARTEX services, HTTP 200 health, and initialized authentication, but do not by themselves prove survival across a reboot.
To verify reboot persistence on a host, record the current boot ID and timestamp in an ignored runtime file such as `<install-dir>/data/reboot-verification-baseline.json` before rebooting, and do not overwrite that baseline until the test is complete:
```bash
sudo -u artex python3 -c 'import json, time; from pathlib import Path; Path("/opt/artex/data/reboot-verification-baseline.json").write_text(json.dumps({"boot_id": Path("/proc/sys/kernel/random/boot_id").read_text().strip(), "ts": time.time()}))'
```
Save other work before rebooting; this disconnects local and remote sessions:
```bash
sudo systemctl reboot
```
After reconnecting, do not manually start ARTEX before checking automatic startup. Compare the current boot ID with the saved baseline and check the services:
```bash
cd /opt/artex
python3 -c 'import json; from pathlib import Path; old=json.loads(Path("data/reboot-verification-baseline.json").read_text())["boot_id"]; new=Path("/proc/sys/kernel/random/boot_id").read_text().strip(); print("PASS: a reboot occurred" if old != new else "FAIL: no reboot occurred"); raise SystemExit(0 if old != new else 1)'
systemctl is-enabled artex.service
systemctl is-active <pg-unit> artex.service
curl --fail --silent --show-error http://127.0.0.1:8787/api/health
python3 -c 'import json, urllib.request; r=json.load(urllib.request.urlopen("http://127.0.0.1:8787/api/auth/status", timeout=5)); print("Authentication initialized:", r.get("initialized")); raise SystemExit(0 if r.get("initialized") else 1)'
systemctl show artex.service --no-pager -p ActiveState -p SubState -p MainPID -p ActiveEnterTimestamp
```
Success requires a changed boot ID, enabled ARTEX, both services active without manual startup, HTTP 200, and authentication still initialized. A new PID alone is not proof of reboot. If the system has just booted, allow startup time and repeat health checks. Refresh the baseline before running a future independent reboot test.
### Example reboot verification record
Example of a completed post-reboot verification (recorded from the original Debian/PostgreSQL 18 reference deployment on 2026-11-17, without manually starting or restarting either service):
- Current boot ID differed from the saved pre-reboot baseline, confirming an actual reboot.
- `artex.service` remained enabled and was `active (running)` under its non-root service user with `NRestarts=0`.
- The local PostgreSQL cluster service was `active`.
- `/api/health` returned HTTP 200.
- `/api/auth/status` confirmed initialized authentication was preserved.
Observed timestamps, PIDs, and restart counts are host-specific examples, not fixed configuration values.
## Operations and troubleshooting
```bash
sudo systemctl restart artex.service
sudo systemctl stop artex.service
sudo systemctl start artex.service
journalctl -b -u artex.service --no-pager
journalctl -u artex.service -f
```
Treat journal output as potentially sensitive; never share unredacted setup tokens or credentials. If startup fails, check PostgreSQL status, database settings and permissions on `<install-dir>/config.json`, `<install-dir>/data`, and `<install-dir>/keys`, occupied ports (`8787`/`8788`), and the journal. After a PostgreSQL dependency failure, restart ARTEX explicitly once the database is healthy. To recover from the start limit:
```bash
sudo systemctl reset-failed artex.service
sudo systemctl start artex.service
```
Back up PostgreSQL, `<install-dir>/config.json`, `<install-dir>/data`, and `<install-dir>/keys` (`jwt.key` and `secret.key`) securely before upgrades. The application stays loopback-only; remote access requires a separately reviewed tunnel or reverse proxy.
+130
View File
@@ -0,0 +1,130 @@
# Traffic HAR 1.2 Import and Export
ARTEX supports importing and exporting captured HTTP traffic using the **HAR 1.2** JSON format so operators can bring captures from browser DevTools or external proxies into the Traffic store and export filtered subsets out of ARTEX.
Both routes require the standard administrator JWT (`Authorization: Bearer <token>`) like the rest of `/api/traffic`, and return `503` when the traffic store is unavailable.
---
## Import: `POST /api/traffic/import/har`
### Request format
Send a raw HAR 1.2 JSON document directly as the HTTP request body (`Content-Type: application/json`), capped at the standard API JSON body limit (**32 MiB**; oversized bodies return `413 Request Entity Too Large`).
```bash
curl -X POST \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data-binary @capture.har \
http://127.0.0.1:8787/api/traffic/import/har
```
The Traffic page also provides an **Import HAR** file picker (with the same 32 MiB limit) that reads a `.har` / `.json` file, posts it to this endpoint, displays loading/error state and a count summary, and refreshes the table.
### Validation & error handling
The request is rejected with `400 Bad Request` naming the reason when:
- the body is empty or malformed JSON (including trailing content after the root object),
- the `log` object is missing,
- `log.version` is not `"1.2"`,
- `log.entries` is missing or `null`,
- `log.entries` exceeds the per-import entry cap (`2000` entries).
Individual malformed entries (invalid `startedDateTime`, non-HTTP(S) URL, invalid HTTP method, header/cookie names or values containing CR/LF/NUL, out-of-range status, invalid base64 or unsupported body encoding) do **not** fail the whole import: they are counted in `failed` and reported in `errors` (up to 50 error details) while valid entries continue importing. HTTP/2 pseudo-headers starting with `:` (such as `:authority` or `:method` from browser DevTools) are skipped cleanly.
### Response
```json
{
"imported": 12,
"skipped": 3,
"failed": 1,
"truncated": false,
"errors": [
{ "index": 4, "url": "notaurl", "reason": "invalid request url \"notaurl\"" }
]
}
```
### Deterministic IDs, round-trip fidelity, & idempotence
- **ARTEX exports (`_artexExchangeId`)**: Every entry exported by ARTEX carries the HAR 1.2 custom field `_artexExchangeId` set to the exchange's stored ID. When a valid `_artexExchangeId` (`[A-Za-z0-9._:-]`, 1–128 chars) is present on import, ARTEX preserves it. This guarantees that two distinct ARTEX exchanges recorded within the same second with identical method, URL, status, and bodies do **not** collapse into one row when imported into a fresh store, and that re-importing an export into the source store stays idempotent (`skipped`).
- **External HARs (no `_artexExchangeId`)**: Each entry receives a deterministic content-based ID:
```text
har-<hex(sha256(ts_unix_seconds + NUL + METHOD + NUL + canonical_url + NUL + status + NUL + sha256(req_body) + NUL + sha256(resp_body)))>
```
`ts_unix_seconds` is `startedDateTime` parsed as RFC 3339 and truncated to UTC Unix seconds (matching `exchanges.ts`). Re-importing the same external HAR skips existing IDs (`INSERT OR IGNORE`, hot rows always win). Identical entries in the same external HAR sharing `(ts_unix_seconds, method, canonical_url, status, req_body, resp_body)` are deduplicated (the first is imported, duplicates are counted in `skipped`).
### Storage, bodies, cookies, `postData.params`, and userinfo
- **URL userinfo**: Any `user:pass@` userinfo in `request.url` is stripped before storing, indexing, listing, exporting, or reporting errors (matching ARTEX's asset store).
- `host` is derived from `URL.Hostname()` and `url_template` from `db.TemplatePath(URL.EscapedPath())`; `path` stays empty.
- **Bodies & base64**: `response.content.text` and `request.postData.text` are stored as raw UTF-8 bytes when `encoding` is empty, and decoded via standard base64 when `encoding` is `"base64"`. When `request.postData.text` is empty and `request.postData.params` is populated, ARTEX reconstructs the form body as `application/x-www-form-urlencoded` (preserving parameter order).
- **Cookies arrays**: When `request.headers` does not already include a `Cookie` header and `request.cookies` is non-empty, ARTEX synthesizes a `Cookie` header from `request.cookies`. Likewise, when `response.headers` does not already include a `Set-Cookie` header and `response.cookies` is non-empty, ARTEX synthesizes `Set-Cookie` headers from `response.cookies`. When the headers are already present, they are kept as-is without duplication.
- `req_len` and `resp_len` record the actual decoded byte lengths.
- `content_type` comes from `response.content.mimeType` (falling back to the response `Content-Type` header).
- Bodies larger than the 256 KiB inline threshold spill to the content-addressed blob store (`_blobs/sha256/...`) with `blob_refs` rows, and searchable text bodies are added to the `ex_fts` full-text index — identical to proxy capture and `ImportArchive`.
### Capture rewrite rules are NOT applied
HAR import writes directly to the traffic store without passing through the MITM capture proxy. **Capture rewrite rules are never applied to imported exchanges**, no `exchange_rewrites` rows are created, and imported rows always have `rewritten: false`.
### Import limits
| Limit | Default | Behavior when exceeded |
|---|---|---|
| Raw HTTP request body | 32 MiB | `413 Request Entity Too Large` |
| Entries per HAR | 2,000 | `400 Bad Request` |
| Total decoded request + response body bytes | 32 MiB | Stops importing remaining entries, sets `"truncated": true`, counts remaining entries in `skipped`, and appends an explanatory item in `errors`. |
---
## Export: `GET /api/traffic/export/har`
### Request & filters
Returns an `application/json` HAR 1.2 document (`Content-Disposition: attachment; filename="artex-traffic.har"`) ordered deterministically by `(ts ASC, id ASC)`.
It reuses the same filter parser and SQL predicate builder as `GET /api/traffic`, supporting:
- `host`, `method`, `path`, `status`, `q`, `body`, `rewritten` (`all` | `rewritten` | `original` | `true` | `false`), `resp_min`, `resp_max`.
### HAR 1.2 compliance & unknown placeholders
- `log.version` is `"1.2"` and `log.creator` is `{"name": "ARTEX", "version": "<build-version>"}`.
- `startedDateTime` is formatted from `exchanges.ts` as UTC RFC 3339, and `_artexExchangeId` carries the exchange's stored ID.
- Request and response headers are parsed from the stored raw heads (`req_head` / `resp_head`). ARTEX does not invent `serverIPAddress` or headers that are not present in the store.
- Required HAR 1.2 fields whose values are not recorded by ARTEX are emitted with explicit **unknown placeholders** rather than fabricated measurements:
- `entry.time`: `0`
- `entry.cache`: `{}`
- `entry.timings`: `{"send": -1, "wait": -1, "receive": -1}` (unknown/unavailable per HAR 1.2)
- `request.cookies`, `request.queryString`, `response.cookies`: `[]`
- `request.headersSize`, `response.headersSize`: `-1` (unknown per HAR 1.2)
- `response.redirectURL`: `""`
- Bodies are read in full from inline columns or spilled blobs: valid NUL-free UTF-8 bodies are emitted as plain `text`, and binary / non-UTF-8 bodies are emitted with `encoding: "base64"`.
### Export limits, import-compatibility invariant, & truncation reporting
| Limit | Default | `truncatedReason` |
|---|---|---|
| Exported entries | 1,000 | `max_entries` |
| Total raw request + response headers and bodies | 20 MiB | `max_bytes` |
| Marshaled JSON size backstop | 31 MiB | `max_bytes` |
**Cap invariant**: Every HAR produced by `GET /api/traffic/export/har` fits inside `POST /api/traffic/import/har`'s **32 MiB** HTTP body limit (and the Traffic page's 32 MiB file limit). Raw headers and bodies are capped at **20 MiB** so worst-case base64 expansion (`4/3x ≈ 26.7 MiB`) plus JSON structure stays comfortably under 32 MiB, backed by an explicit **31 MiB** marshaled-JSON cap so even heavily JSON-escaped payloads cannot trigger a `413` on re-import.
Truncation is never silent. Every export reports it in both HTTP response headers and HAR 1.2 custom (`_`-prefixed) `log` fields:
- Headers:
- `X-ARTEX-HAR-Truncated: true|false`
- `X-ARTEX-HAR-Truncated-Reason: max_entries|max_bytes` (when truncated)
- `X-ARTEX-HAR-Exported: <count>`
- `X-ARTEX-HAR-Matched: <total matching rows>`
- JSON (`log` object, omitted when not truncated):
- `_truncated: true`
- `_truncatedReason: "max_entries" | "max_bytes"`
- `_totalMatched: <total matching rows>`
+54 -5
View File
@@ -4,9 +4,11 @@ A rewrite rule matches a request or a response that goes through the capture pro
how to change it: the method, the path and query, headers, the body, the status code.
**Status: the capture proxy applies enabled rules to HTTP traffic (request and response phases),
and records what it did.** Not yet in this change: archive format, a per-replay rule toggle, the web UI,
and the proof flag. See [Application in the capture proxy](#application-in-the-capture-proxy) for
what is covered and what is not.
records what it did, tags bound evidence snapshots, supports per-replay rule opt-in, carries
rewrite provenance in traffic archive v2, exposes rewrite counters and a rewritten filter/flag on
`GET /api/traffic`, and shows the filter and badge on the Traffic page.** Not yet in this change:
the rule-management web UI. See [Application in the capture proxy](#application-in-the-capture-proxy)
for what is covered and what is not.
Rules are a convenience for the operator, not a security control: a rule that fails leaves the
message unchanged (fail open).
@@ -207,5 +209,52 @@ the slot may be converted into a tombstone if a new reservation needs the room.
### Replay
Replay goes through the recording proxy like any other traffic, so the enabled rules apply to a
replay and the resulting exchange is traced like a captured one. There is no per-replay toggle yet.
`POST /api/traffic/replay` sends the edited request through the recording proxy so the exchange is
captured in Traffic, but **bypasses capture rewrite rules by default** (`apply_rules: false`). To
run enabled capture rules against a replay and trace them like captured traffic, opt in with
`"apply_rules": true` (or check **Apply capture rewrite rules** in the Replay panel).
When `apply_rules` is false, `traffic.Replay` registers a single-use random 32-byte hex nonce in an
in-memory registry, attaches the internal header `X-ARTEX-Replay-Nonce: <nonce>`, and removes the
nonce when the call returns. The capture proxy strips `X-ARTEX-Replay-Nonce` unconditionally in the
request hook so the target never sees it; only a value matching a registered nonce bypasses both
request and response rule phases, while any forged header is stripped and ignored.
### Stats
`GET /api/traffic` includes a `rewrite` object exposing the proxy's `RewriteStats` counters since
start: `large_responses`, `capacity_refusals`, `tombstone_drops`, `conversions`, and `sweeps`.
### Traffic list
Each exchange returned by `GET /api/traffic` carries `"rewritten": true|false`, computed with an
`EXISTS` check against `exchange_rewrites` for rows with `outcome = 'applied'` (skipped or failed
rules do not mark an exchange as rewritten).
`GET /api/traffic` accepts an optional `rewritten` query parameter:
- `all` (default when omitted or unrecognized): returns all exchanges.
- `rewritten` (alias `true`): returns only exchanges with at least one applied rewrite row.
- `original` (alias `false`): returns only exchanges with no applied rewrite row.
The filter combines with `host`, `method`, `path`, `status`, `q`, `body`, `resp_min`, and
`resp_max` using `AND`, and `total` and pagination reflect the filtered set. The Traffic page shows
the filter next to the existing filters and renders a `Rewritten` badge on rewritten rows.
### Task archives (v2)
Task archives export captured traffic into `traffic/traffic.json` using **format version 2**:
- Each `ArchiveExchange` carries optional `rewritten` (`bool`) and `rewrite_rule_ids` (`[]int64`),
matching `RewriteInfo` (applied rows only, sorted ascending, distinct). Exchanges with no applied
rewrite omit both fields.
- Output stays deterministic: exchanges are ordered by `(ts, id)`, `rewrite_rule_ids` are sorted
and distinct, and `blobs` are sorted so re-exporting the same data produces a byte-identical
`traffic.json`.
- `ImportArchive` accepts versions 1 and 2 and refuses any other version. Version 1 entries import
as unrewritten with no rule IDs. Version 2 entries marked `rewritten: true` reconstruct minimal
applied rows in `exchange_rewrites` (`phase = 'archived'`, `outcome = 'applied'`,
`reason = 'archived'`, `rule_snapshot = NULL`) for each distinct rule ID (or a single `NULL`
`rule_id` row when `rewrite_rule_ids` is empty), preserving `RewriteInfo`, `traffic_get`'s
`=== REWRITTEN ===` header, evidence-binding provenance, and the traffic list filter without
fabricating a rule snapshot or request/response phase. Existing hot rows always win on import.