Compare commits

..
Author SHA1 Message Date
dependabot[bot] 442c48fddd deps(actions): bump actions/setup-python from 5.6.0 to 7.1.0
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5.6.0 to 7.1.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/a26af69be951a213d495a4c3e4e4022e16d87065...6d4fd22b20465ccc0f7354476588e8df7c9ca0e0)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 18:25:18 +00:00
BaaRai 3a601eb9ff Merge pull request #634 from Lusitaniae/pr/actions-sha-pins
ci: pin workflow actions to commit SHAs
2026-11-28 19:24:39 +01:00
BaaRai d32f5689ec Merge pull request #637 from zOrg1331/fix/bedrock-chat-completions
fix(llm): support Bedrock gateways that speak OpenAI chat completions
2026-11-28 19:24:27 +01:00
BaaRai b1cb08a647 Merge pull request #597 from GeospatialDaryl/fix/build-node-version-check
build: fail fast when Node < 20.9 and document the requirement
2026-11-28 19:24:15 +01:00
BaaRai 729ede9369 Merge pull request #643 from alohamonius/fix/install-postgres-loopback-bind
install: bind local-mode PostgreSQL to loopback
2026-11-28 19:24:02 +01:00
BaaRai 57db0c06d0 Merge pull request #630 from Lusitaniae/pr/bbot-hashed-lock
build: install bbot from a fully hashed requirements lock
2026-11-28 19:23:50 +01:00
BaaRai 24f01942ba Merge pull request #653 from chaitanya0305/fix/retarget-task-scope
fix(db): keep retargeted task scope in the domain column
2026-11-28 19:23:38 +01:00
BaaRai 0e8e6cd50e Merge pull request #651 from chaitanya0305/fix/finding-severity-case
fix(db): store a finding's severity in canonical lowercase
2026-11-28 19:23:26 +01:00
BaaRai e963c1f666 Merge pull request #649 from dung997tb/feat/vietnamese-locale
feat(i18n): add Vietnamese locale for the web console
2026-11-28 19:23:01 +01:00
BaaRai b165e11f5e Merge pull request #645 from chaitanya0305/fix/stateful-guard-curl-flags
fix(intercept): classify curl and wget body flags correctly in the stateful guard
2026-11-28 19:22:44 +01:00
Chaitanya Deshpande 1991644a17 fix(db): store a finding's severity in canonical lowercase
report_finding passes the model's severity text through unchanged, so a
finding reported as "High" was stored as "High". The severity
counters (severity='high') and the min_severity filter of notification
channels compare exactly, so such a finding was counted nowhere and was
never delivered to a channel with a severity threshold. Trim and
lowercase the severity in RecordFindingTx.
2026-11-28 19:53:30 +05:30
Chaitanya Deshpande 13d14c498e fix(db): keep retargeted task scope in the domain column
RetargetTask deleted host scope rows by task_scope.value and inserted
the new host into value. Host rows (root_domain/subdomain) keep the host
in domain, and coverage and list_untested_assets match on domain. The
old host stayed in the declared scope and the new host row matched
nothing. Delete and insert by domain instead.
2026-11-28 19:50:16 +05:30
dung997tb 9fa6f10c55 feat(i18n): add Vietnamese locale for the web console 2026-11-28 13:43:01 +00:00
BaaRai b8cd251395 Merge pull request #646 from BaaRai/docs/install-guide
docs: add an installation guide, issue form, and video script
2026-11-28 13:45:59 +01:00
BaaRai 486465a91e docs: add an installation guide, issue form, and video script
INSTALL.md collects the supported Docker paths, first login, remote access,
and the errors behind most installation questions. The README links it from
the nav and above the quick start. The installation issue form asks for OS,
Docker setup, version, logs and health output, and reminds reporters to strip
the setup token. The video script keeps a short demo aligned with the guide.
2026-11-28 13:32:27 +01:00
obichukandClaude Opus 4.8 a1ac0594b8 install: drop the inline comments on the loopback bind
Keep only the one-line change (-p 127.0.0.1:5432:5432); the rationale lives in
the PR description, not in the script.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-28 13:19:33 +01:00
Chaitanya Deshpande df30888fc8 fix(intercept): classify curl and wget body flags correctly in the stateful guard
The mutating-call regexes were case-insensitive, so curl -f and -D (read-only) counted as -F and -d: a first curl -f GET was refused for a missing baseline. Attached short values (-d@file, -d'{}'), --json, -T/--upload-file, --data-ascii, wget --post-data and --method were not matched, so those mutations skipped the baseline gate and lease and were recorded as the baseline.
2026-11-28 17:45:38 +05:30
obichukandClaude Opus 4.8 cdf3c1a4e4 install: bind the local-mode PostgreSQL to loopback
Local install mode (option 2) started PostgreSQL with `-p 5432:5432`, which
publishes it on every interface. Docker's iptables rules bypass host firewalls
such as UFW, so on a public VPS the database — reachable with the password the
same prompt accepts — is exposed to the internet. ARTEX itself connects on
127.0.0.1 in this mode, so binding the published port to 127.0.0.1 keeps the
install working while removing the exposure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-28 12:14:44 +01:00
BaaRai e9659c8ae1 Merge pull request #640 from BaaRai/feat/version-identity
feat: report the build identity in the UI and /health
2026-11-28 10:36:47 +01:00
Pavel NakonechnyiandCursor 97c2d38526 fix(llm): retry Bedrock chat requests as chat completions
A tool-bearing Anthropic body is rejected with HTTP 400 by OpenAI-shaped InvokeModel endpoints. Retry that call once as a chat completion and keep the shape that succeeds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-28 09:33:24 +01:00
Pavel NakonechnyiandCursor b2c7cc0275 fix(llm): accept Bedrock chat-completion replies
InvokeModel responses that use the OpenAI chat completion shape were parsed as empty Anthropic messages. Adapt them so connection tests and live sessions see the visible text, and name reasoning-only failures.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-28 09:33:24 +01:00
Pedro Gomes 517177509c ci: record full release versions in action pin comments
The major-tag comment (# v6) did not say which release the pinned
commit came from. Resolve each pinned SHA to its full version tag and use
that in the comment, e.g. docker/build-push-action@10e90e3 # v6.19.2.
2026-11-28 06:27:00 +00:00
Pedro Gomes 8def0fcbca ci: pin workflow actions to commit SHAs
Resolve all 31 tag-pinned uses: references in bot.yml, ci.yml and
release.yml to full commit SHAs, retaining the version in a comment. Add a
weekly github-actions Dependabot entry to refresh the pins.
2026-11-28 06:24:18 +00:00
Pedro Gomes bc4f09405e build: install bbot from a fully hashed requirements lock
Replace pip's unpinned bbot==$BBOT_VERSION resolution with pip
--require-hashes against requirements-bbot.lock (68 packages, 2517 hashes).
The imported bbot version is asserted against BBOT_VERSION so a version bump
without a lock refresh fails the build. The lock pins the base install only;
bbot -y --install-all-deps still resolves module extras at build time.
2026-11-28 06:08:12 +00:00
GeospatialDarylandClaude Sonnet 5.5 5ce72595d0 build: fail fast when Node < 20.9 and document the requirement
Next.js 16 needs Node >= 20.9. With older Node, build.sh ran npm ci and
then exited without a clear error. Check the version up front.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 21:32:32 -08:00
24 changed files with 7004 additions and 83 deletions
+87
View File
@@ -0,0 +1,87 @@
name: Installation help
description: Ask for help installing, starting or reaching the ARTEX console
title: "[install] "
labels: ["question"]
body:
- type: markdown
attributes:
value: |
Thanks for the report. Read [INSTALL.md](https://github.com/BaaRai/ARTEX/blob/main/INSTALL.md)
first and try the matching troubleshooting section. Remove the setup token, passwords, API
keys and target data from every output you paste.
- type: input
id: os
attributes:
label: OS and architecture
placeholder: Ubuntu 24.04 amd64, Windows 11 with Docker Desktop, macOS 15 arm64
validations:
required: true
- type: dropdown
id: setup
attributes:
label: Docker setup
options:
- Docker Desktop on Windows
- Docker Desktop on macOS
- Docker Engine on Linux
- Docker Engine inside WSL2
- No Docker, local binary or source build
- Other, explained below
validations:
required: true
- type: dropdown
id: method
attributes:
label: Installation method
options:
- ./install.sh
- docker compose up -d --build
- docker-compose.ghcr.yml
- Prebuilt release binary
- Built from source
- Other, explained below
validations:
required: true
- type: input
id: version
attributes:
label: Version shown in the top right
description: For example v0.7.1, main-abc1234, or dev.
placeholder: dev
- type: textarea
id: error
attributes:
label: What happens
description: The exact error, the command that produced it, and what you expected.
render: shell
validations:
required: true
- type: textarea
id: ps
attributes:
label: docker compose ps
description: Paste the full output.
render: shell
- type: textarea
id: logs
attributes:
label: docker compose logs --tail=120 artex
description: Remove the setup token, passwords, API keys and target data before pasting.
render: shell
validations:
required: true
- type: textarea
id: health
attributes:
label: Health check from the Docker host
description: Output of curl -sS http://127.0.0.1:8787/api/health
render: shell
- type: checkboxes
id: checks
attributes:
label: Before posting
options:
- label: I read INSTALL.md and tried the matching troubleshooting section.
required: true
- label: I removed the setup token, passwords, API keys and target data from the logs.
required: true
+9
View File
@@ -20,3 +20,12 @@ updates:
update-types: ["version-update:semver-minor", "version-update:semver-major"]
- dependency-name: "golang"
update-types: ["version-update:semver-minor", "version-update:semver-major"]
# Keep the SHA-pinned action references current. Dependabot understands the
# " # vN.N.N" comment next to a pinned commit and bumps both when a tag moves.
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
commit-message:
prefix: "deps(actions)"
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
github.actor != 'dependabot[bot]')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: triage or reply
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+10 -10
View File
@@ -69,8 +69,8 @@ jobs:
env:
ARTEX_PG_DSN: postgres://artex:testpass@localhost:5432/artextest?sslmode=disable
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with:
go-version-file: go.mod
- name: gofmt
@@ -150,8 +150,8 @@ jobs:
env:
ARTEX_PG_DSN: postgres://artex:testpass@localhost:5432/artextest?sslmode=disable
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with:
go-version: stable
- name: toolchain in use
@@ -171,7 +171,7 @@ jobs:
steps:
# The official action uses the Go version declared by go.mod and reports
# only vulnerabilities reachable from this module's packages.
- uses: golang/govulncheck-action@v1
- uses: golang/govulncheck-action@032d45514ae346b1db93c04b0c90b841c370344f # v1.1.0
with:
go-version-file: go.mod
go-package: ./...
@@ -181,7 +181,7 @@ jobs:
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.shell == 'true') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
# shellcheck is preinstalled on the ubuntu runners. -S warning: the scripts
# currently have only info-level notes (intentional A && B || C chains in
# update.sh, an unquoted glob in backup.sh's prune), so fail on warnings.
@@ -200,8 +200,8 @@ jobs:
run:
working-directory: web
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "22"
cache: npm
@@ -222,8 +222,8 @@ jobs:
if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.result != 'success' || needs.changes.outputs.python == 'true') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- run: python3 scripts/posture_check_test.py
+20 -20
View File
@@ -14,8 +14,8 @@ jobs:
frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "22"
cache: npm
@@ -24,7 +24,7 @@ jobs:
working-directory: web
- run: npm run build:static
working-directory: web
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: web-dist
path: web/out
@@ -42,12 +42,12 @@ jobs:
- { goos: darwin, goarch: arm64 }
- { goos: windows, goarch: amd64 }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
with:
go-version: "1.26"
cache: true
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: web-dist
path: server/webui/dist
@@ -69,13 +69,13 @@ jobs:
- name: Smoke test Linux amd64 binary
if: matrix.goos == 'linux' && matrix.goarch == 'amd64'
run: dist/artex-linux-amd64/artex -h
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: pkg-${{ matrix.goos }}-${{ matrix.goarch }}
path: "dist/*.zip"
# Upload the raw linux/amd64 binary separately for the release job's Syft SBOM scan
- if: matrix.goos == 'linux' && matrix.goarch == 'amd64'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: bin-linux-amd64
path: dist/artex-linux-amd64/artex
@@ -89,8 +89,8 @@ jobs:
id-token: write # Sigstore signing of the provenance attestation
attestations: write # store the attestation on the repository
steps:
- uses: actions/checkout@v4 # CHANGELOG.md and the extractor script
- uses: actions/download-artifact@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 — CHANGELOG.md and the extractor script
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: pkg-*
merge-multiple: true
@@ -100,7 +100,7 @@ jobs:
run: sha256sum *.zip > SHA256SUMS
# SBOM of what ships: the Go modules embedded in the linux/amd64 binary, plus
# the frontend lockfile and the Go module files.
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: bin-linux-amd64
path: ${{ runner.temp }}/sbom-src/bin
@@ -125,7 +125,7 @@ jobs:
- uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: dist/*.zip
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: release-metadata
path: |
@@ -142,7 +142,7 @@ jobs:
echo "::warning::CHANGELOG.md has no section [$version]; using the generic release body"
echo "Release $TAG. See CHANGELOG.md for the list of changes in this release." > "$RUNNER_TEMP/release-body.md"
fi
- uses: softprops/action-gh-release@v2
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
if: github.event_name == 'push'
with:
files: |
@@ -163,23 +163,23 @@ jobs:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Log in to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@v3
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
if: github.event_name == 'push' && vars.DOCKERHUB_ENABLED == 'true'
uses: docker/login-action@v3
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/metadata-action@v5
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
id: meta
with:
images: |
@@ -189,7 +189,7 @@ jobs:
type=ref,event=tag
type=semver,pattern={{version}}
type=raw,value=latest
- uses: docker/build-push-action@v6
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
with:
context: .
platforms: linux/amd64,linux/arm64
+10 -5
View File
@@ -232,15 +232,20 @@ RUN set -eux; \
test "$templates" -gt 10000
# bbot recursive recon orchestrator (#117): blacklanternsecurity/bbot, AGPL-3.0
# (same license as ARTEX; standalone CLI dependency, not linked code). Pinned
# version, own venv to isolate from the image python. Module dependencies are
# preinstalled (--install-all-deps) so scans never need pip at runtime, which
# would fail under a program's egress allowlist.
# (same license as ARTEX; standalone CLI dependency, not linked code). Own venv to
# isolate it from the image python, installed from a fully hashed lock
# (requirements-bbot.lock, 68 packages, generated for CPython 3.12). Module
# dependencies are preinstalled (--install-all-deps) so scans never need pip at
# runtime, which would fail under a program's egress allowlist. The lock pins the
# base install; bbot's module extras are still resolved by --install-all-deps.
ARG BBOT_VERSION=3.0.2
COPY requirements-bbot.lock /tmp/requirements-bbot.lock
# arm64: bbot's Chrome and retirejs's Node are x86-64; use native builds.
RUN set -eux; \
python -m venv /opt/bbot; \
/opt/bbot/bin/pip install --no-cache-dir "bbot==${BBOT_VERSION}"; \
/opt/bbot/bin/pip install --no-cache-dir --require-hashes -r /tmp/requirements-bbot.lock; \
/opt/bbot/bin/python -c 'import bbot, sys; assert bbot.__version__ == sys.argv[1], bbot.__version__' "$BBOT_VERSION"; \
rm -f /tmp/requirements-bbot.lock; \
ln -s /opt/bbot/bin/bbot /usr/local/bin/bbot; \
if [ "${TARGETARCH:-amd64}" = "arm64" ]; then \
apt-get update; \
+191
View File
@@ -0,0 +1,191 @@
# Install ARTEX
ARTEX is self-hosted. The supported setup is Docker Compose, which starts ARTEX and PostgreSQL
together. You need an LLM API key for exploration, but the console starts without one and you can
add it later in the UI.
| Path | Needs | Use it when |
| --- | --- | --- |
| One-click script | Docker with Compose v2, or Go 1.26 and Node 22 | You want the script to choose Docker or a local build |
| Docker Compose | Docker Engine 24+ or Docker Desktop, Compose v2, buildx | You want to see and control every step |
| Prebuilt binary or source build | Go 1.26, Node 22, an existing PostgreSQL | You cannot run Docker or want a single binary |
## Requirements
- Docker Engine with the Compose v2 plugin and the buildx plugin. Docker Desktop includes both.
The checkout build stops at `failed to parse platform` when buildx is missing.
- PostgreSQL 16 is started by the Compose files. A local binary or a standalone container needs an
existing database.
- An Anthropic or OpenAI compatible API key for exploration. It can be set in `.env` or later in
**System, LLM**.
- Ports 8787 (console) and 8788 (recording proxy) free on the host.
## Option 1: one-click script, recommended
```bash
git clone https://github.com/BaaRai/ARTEX.git
cd ARTEX
./install.sh
```
Choose **1) all-Docker**. The script creates `.env`, starts the stack and prints the URL. It can
also install Docker on supported Linux distributions.
Open <http://localhost:8787>. On the first visit, `/setup` asks for the one-time setup token printed
at startup:
```bash
docker compose logs artex | grep "Setup token"
```
## Option 2: Docker Compose manual
```bash
git clone https://github.com/BaaRai/ARTEX.git
cd ARTEX
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>, paste the setup token, then choose the console password.
Check the stack:
```bash
docker compose ps
docker compose port artex 8787
curl -sS http://127.0.0.1:8787/api/health
```
`/api/health` answers `{"ok":true}` without a session. `docker compose port` should show
`127.0.0.1:8787`.
### Docker Desktop on Windows and macOS
Docker Desktop serves host bind mounts in a way that defeats the agent isolation self-test, so the
`artex` container can restart in a loop with `self-test failed`. Layer the named-volume file:
```bash
docker compose -f docker-compose.yml -f docker-compose.desktop.yml up -d --build
```
Use the same `-f` pair for later commands (`logs`, `up -d artex`, `down`). Docker Engine inside WSL2
with the repository under `/mnt/c` has the same problem: use the overlay or move the checkout to the
WSL2 native filesystem. See the README section
[Docker Desktop on Windows and macOS](README.md#docker-desktop-on-windows-and-macos) for the
migration of an existing `keys` and `data` directory.
### Access from another machine
The console binds `127.0.0.1` by default. To reach it from Windows when ARTEX runs in WSL, from a
remote server, or from another host, either keep the loopback binding and use a tunnel:
```bash
ssh -L 8787:127.0.0.1:8787 user@server
```
then open <http://localhost:8787> on your machine, or expose it deliberately:
```bash
# .env
ARTEX_BIND_ADDR=0.0.0.0
```
```bash
docker compose up -d artex
```
Only expose it behind a firewall or a reverse proxy. The setup token protects the first-run claim,
not the console afterwards.
## Other installation paths
- Prebuilt binaries and release archives: see [Installation](README.md#installation) options 3 and 5.
- Build the binary from source: see option 4 in the same section.
- Prebuilt GHCR images: the image is published from the next tagged release. Until then,
`docker-compose.ghcr.yml` and `docker pull ghcr.io/baarai/artex` return `denied`; use the checkout
build above.
## Troubleshooting
### `http://localhost:8787` does not answer
1. `docker compose ps` must show `postgres` and `artex` as running, not restarting.
2. `docker compose port artex 8787` must show a mapping. If it prints nothing, you started the wrong
Compose file or an override removed the ports.
3. `curl -sS http://127.0.0.1:8787/api/health` on the Docker host. If it returns `{"ok":true}`, ARTEX
is up and the problem is networking or the browser.
4. Read the startup log: `docker compose logs --tail=120 artex`. Do not share the setup token.
5. If the browser is not on the Docker host, see [Access from another machine](#access-from-another-machine).
### The `artex` container restarts in a loop
Look for `self-test failed` or `crash` in the logs. On Docker Desktop, or with Docker Engine inside
WSL2 on `/mnt/c`, use the [Desktop overlay](#docker-desktop-on-windows-and-macos). On native Linux,
check that `./data`, `./keys` and `./skills` are on a filesystem that enforces POSIX ownership, not a
Windows or 9p mount.
### `docker buildx version` fails
Install the buildx plugin:
- Debian/Ubuntu: `sudo apt-get install docker-buildx-plugin`
- Fedora: `sudo dnf install docker-buildx-plugin`
- macOS with Colima: `brew install docker-buildx`
### `fork/exec /usr/bin/bash: no such file or directory`
The agent Bash tool starts `bash` before running your command, so your command never ran. This is a
host or image problem, not a command error. Inside the container or on the host:
```bash
ls -l /usr/bin/bash /bin/bash /bin/sh
file /usr/bin/bash
ldd /usr/bin/bash
```
Install bash if it is missing (`apt-get install -y bash` on Debian/Ubuntu, `apk add bash` on Alpine).
If only `/bin/bash` exists, create the expected path with `ln -s /bin/bash /usr/bin/bash` as root, or
use the official Docker image, which includes bash. Restart ARTEX after the fix.
### The top right says `dev`
`dev` means the build carried no version stamp, not a different branch. A checkout built through
`install.sh` or `update.sh` on current main stamps `ARTEX_VERSION` from `git describe` and
`ARTEX_REVISION` from `git rev-parse HEAD`. To identify an older local build, run `git describe
--tags --always --dirty` or `git rev-parse HEAD` in the checkout it was built from. If the checkout is
gone, the image ID and build date are the only remaining identifiers.
### Port 8787 or 8788 is already allocated
Stop the process using the port (`ss -ltnp | grep 8787`) or change the host side of the mapping in
`docker-compose.yml`. The container side stays 8787.
### I lost the setup token
The token is printed at startup. Read it again from the current container log:
```bash
docker compose logs artex | grep -i "setup token"
```
If the first-run setup is already complete, use the console password instead. Restarting the stack
does not reset an existing password.
### The GHCR image cannot be pulled
The release image is not published yet. Use the checkout build in [Option 2](#option-2-docker-compose-manual)
until the next tagged release.
## Update and back up
Update a checkout build with `./update.sh`, or rebuild with `docker compose up -d --build` after a
`git pull`. Back up PostgreSQL, `./data` and `./keys`: see [Backups](README.md#backups). A database
dump without `keys/secret.key` cannot restore the encrypted secrets.
## Getting help
Open an installation issue with your OS, Docker setup, installation method, `docker compose ps`,
the exact error and the last 120 log lines. Remove the setup token, passwords, API keys and target
data first. The issue form asks for these fields.
+13 -2
View File
@@ -16,7 +16,7 @@ and every finding stays bound to the assets and HTTP traffic that prove it.
[![Go](https://img.shields.io/github/go-mod/go-version/BaaRai/ARTEX?color=6b34db)](go.mod)
[![Discord](https://img.shields.io/badge/Discord-join%20the%20server-5865F2?logo=discord&logoColor=white)](https://discord.gg/VKyvMTcgXh)
[Quick start](#quick-start) · [Screenshots](#screenshots) · [How it works](#how-it-works) · [Install](#installation) · [Configuration](#configuration) · [Security](SECURITY.md)
[Quick start](#quick-start) · [Install guide](INSTALL.md) · [Screenshots](#screenshots) · [How it works](#how-it-works) · [Installation](#installation) · [Configuration](#configuration) · [Security](SECURITY.md)
[![Join us on Discord](https://img.shields.io/badge/JOIN%20US%20ON-DISCORD-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/VKyvMTcgXh)
@@ -43,6 +43,9 @@ justify it, and every autonomous action passes through scope rules, approval gat
---
> **Installing ARTEX for the first time?** [INSTALL.md](INSTALL.md) has the three-command Docker
> setup, the first login with the setup token, and fixes for the most common installation errors.
## Quick start
```bash
@@ -532,6 +535,8 @@ gh attestation verify <zip> --repo BaaRai/ARTEX # built by this repository's r
### Option 4: build the single binary from source
Requires Node.js >= 20.9 (Node 22 LTS recommended; the frontend uses Next.js 16) and Go. `./build.sh` checks the Node version up front.
```bash
cd web && npm ci && npm run build:static && cd ..
cp -r web/out server/webui/dist
@@ -600,7 +605,13 @@ bearer-token authentication. Enter the gateway's base URL (for example,
in **Bearer token**. If required, enter static headers as one `Name: Value` per line
in **Custom gateway headers**. ARTEX adds `/model/{model}/invoke` (or
`/invoke-with-response-stream`), sends `anthropic_version: bedrock-2023-05-31`,
and decodes Bedrock's binary event stream. Enter the model ID manually; this
and decodes Bedrock's binary event stream. InvokeModel may return either an
Anthropic message or an OpenAI chat completion (`choices[].message.content`,
with reasoning in `message.reasoning`); ARTEX adapts the chat completion into
the same message shape, including when it arrives as `chat.completion.chunk`
frames. If the gateway rejects the Anthropic request body with HTTP 400, ARTEX
retries once with an OpenAI chat-completion body and keeps that format for later
requests. Enter the model ID manually; this
gateway format does not have a model-list operation. The token and custom header
values are encrypted in the database and are write-only in the UI. Editing the
gateway URL requires re-entering the token, so saved credentials cannot be sent
+763 -35
View File
@@ -10,7 +10,9 @@ import (
"net/http"
"net/textproto"
"net/url"
"sort"
"strings"
"sync"
"github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream"
)
@@ -95,6 +97,9 @@ type bedrockGatewayTransport struct {
token string
model string
headers http.Header
mu sync.Mutex
chatRequest bool // endpoint rejected the Anthropic body; send chat completions
}
func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response, error) {
@@ -129,29 +134,35 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
u.Path += "-with-response-stream"
u.RawPath += "-with-response-stream"
}
q := req.Clone(req.Context())
q.URL = u
q.Host = u.Host
q.Body = io.NopCloser(bytes.NewReader(raw))
q.ContentLength = int64(len(raw))
q.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(raw)), nil }
q.Header = req.Header.Clone()
q.Header.Del("x-api-key")
q.Header.Del("anthropic-version")
q.Header.Set("Authorization", "Bearer "+t.token)
q.Header.Set("Content-Type", "application/json")
q.Header.Set("X-Amzn-Bedrock-Accept", "application/json")
q.Header.Set("Accept", "application/json")
if streaming {
q.Header.Set("Accept", "application/vnd.amazon.eventstream")
t.mu.Lock()
preferChat := t.chatRequest
t.mu.Unlock()
sentChat := false
if preferChat {
if rewritten, ok := anthropicRequestToChatCompletion(raw); ok {
raw, sentChat = rewritten, true
}
}
for name, values := range t.headers {
q.Header[name] = append([]string(nil), values...)
}
resp, err := t.base.RoundTrip(q)
resp, err := t.invoke(req, u, raw, streaming)
if err != nil {
return resp, err
}
// A tool-bearing Anthropic body is rejected by OpenAI-shaped InvokeModel
// endpoints. Retry once as a chat completion and keep that shape.
if resp.StatusCode == http.StatusBadRequest && !sentChat {
if rewritten, ok := anthropicRequestToChatCompletion(raw); ok {
_ = resp.Body.Close()
resp, err = t.invoke(req, u, rewritten, streaming)
if err != nil {
return resp, err
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
t.mu.Lock()
t.chatRequest = true
t.mu.Unlock()
}
}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// Gateways may echo authorization material in error bodies or headers.
// Keep the status for callers and retries without exposing that echo.
@@ -178,20 +189,47 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
return &copy, nil
}
if !streaming {
return resp, nil
rawBody, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, err
}
adapted, err := rewriteBedrockModelJSON(rawBody)
if err != nil {
return nil, err
}
return jsonResponse(resp, adapted), nil
}
if !strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "application/vnd.amazon.eventstream") {
resp.Body.Close()
return nil, errors.New("Bedrock gateway returned a non-eventstream response")
rawBody, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, err
}
sse, ok, err := chatCompletionToSSE(rawBody)
if err != nil {
return nil, err
}
if !ok {
return nil, &bedrockGatewayError{"Bedrock gateway returned a non-eventstream response"}
}
return sseResponse(resp, sse), nil
}
reader, writer := io.Pipe()
go func() {
defer resp.Body.Close()
defer writer.Close()
decoder := eventstream.NewDecoder()
chat := &chatChunkWriter{w: writer}
sawChat := false
for {
frame, err := decoder.Decode(resp.Body, nil)
if err == io.EOF {
if sawChat {
if err := chat.close(); err != nil {
writer.CloseWithError(err)
}
}
return
}
if err != nil {
@@ -217,32 +255,722 @@ func (t *bedrockGatewayTransport) RoundTrip(req *http.Request) (*http.Response,
return
}
}
var event struct {
Type string `json:"type"`
}
if json.Unmarshal(payload, &event) != nil || !validEventType(event.Type) {
switch bedrockPayloadKind(payload) {
case "chat":
sawChat = true
if err = chat.write(payload); err != nil {
writer.CloseWithError(err)
return
}
case "anthropic":
if sawChat {
writer.CloseWithError(errors.New("invalid Bedrock gateway event"))
return
}
var compact bytes.Buffer
if err = json.Compact(&compact, payload); err != nil {
writer.CloseWithError(err)
return
}
var event struct {
Type string `json:"type"`
}
_ = json.Unmarshal(payload, &event)
if _, err = fmt.Fprintf(writer, "event: %s\ndata: %s\n\n", event.Type, compact.Bytes()); err != nil {
return
}
default:
writer.CloseWithError(errors.New("invalid Bedrock gateway event"))
return
}
var compact bytes.Buffer
if err = json.Compact(&compact, payload); err != nil {
writer.CloseWithError(err)
return
}
if _, err = fmt.Fprintf(writer, "event: %s\ndata: %s\n\n", event.Type, compact.Bytes()); err != nil {
return
}
}
}()
copy := *resp
copy.Body = &bedrockStreamBody{PipeReader: reader, upstream: resp.Body}
copy.Header = resp.Header.Clone()
copy.Header = cloneHeader(resp.Header)
copy.Header.Set("Content-Type", "text/event-stream")
copy.Header.Del("Content-Length")
copy.ContentLength = -1
return &copy, nil
}
func jsonResponse(resp *http.Response, body []byte) *http.Response {
copy := *resp
copy.Body = io.NopCloser(bytes.NewReader(body))
copy.ContentLength = int64(len(body))
copy.Header = cloneHeader(resp.Header)
copy.Header.Set("Content-Type", "application/json")
return &copy
}
func sseResponse(resp *http.Response, sse string) *http.Response {
copy := *resp
copy.Body = io.NopCloser(strings.NewReader(sse))
copy.Header = cloneHeader(resp.Header)
copy.Header.Set("Content-Type", "text/event-stream")
copy.Header.Del("Content-Length")
copy.ContentLength = -1
return &copy
}
func cloneHeader(h http.Header) http.Header {
out := h.Clone()
if out == nil {
out = make(http.Header)
}
return out
}
func (t *bedrockGatewayTransport) invoke(req *http.Request, u *url.URL, raw []byte, streaming bool) (*http.Response, error) {
q := req.Clone(req.Context())
q.URL = u
q.Host = u.Host
q.Body = io.NopCloser(bytes.NewReader(raw))
q.ContentLength = int64(len(raw))
q.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(raw)), nil }
q.Header = req.Header.Clone()
q.Header.Del("x-api-key")
q.Header.Del("anthropic-version")
q.Header.Set("Authorization", "Bearer "+t.token)
q.Header.Set("Content-Type", "application/json")
q.Header.Set("X-Amzn-Bedrock-Accept", "application/json")
q.Header.Set("Accept", "application/json")
if streaming {
q.Header.Set("Accept", "application/vnd.amazon.eventstream")
}
for name, values := range t.headers {
q.Header[name] = append([]string(nil), values...)
}
return t.base.RoundTrip(q)
}
type anthInMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
type anthInBlock struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
ToolUseID string `json:"tool_use_id"`
Content json.RawMessage `json:"content"`
}
type oaOutMessage struct {
Role string `json:"role"`
Content string `json:"content,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCalls []oaOutCall `json:"tool_calls,omitempty"`
}
type oaOutCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
type oaOutTool struct {
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
} `json:"function"`
}
type chatInvokeRequest struct {
MaxTokens int `json:"max_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
Stop []string `json:"stop,omitempty"`
Messages []oaOutMessage `json:"messages"`
Tools []oaOutTool `json:"tools,omitempty"`
}
// anthropicRequestToChatCompletion rebuilds an Anthropic Messages body as an
// OpenAI chat completion.
func anthropicRequestToChatCompletion(raw []byte) ([]byte, bool) {
var doc struct {
MaxTokens int `json:"max_tokens"`
Temperature *float64 `json:"temperature"`
StopSequences []string `json:"stop_sequences"`
System json.RawMessage `json:"system"`
Messages []anthInMessage `json:"messages"`
Tools []struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema"`
} `json:"tools"`
}
if json.Unmarshal(raw, &doc) != nil {
return nil, false
}
var msgs []oaOutMessage
if system := jsonText(doc.System); system != "" {
msgs = append(msgs, oaOutMessage{Role: "system", Content: system})
}
for _, m := range doc.Messages {
msgs = append(msgs, openAIMessages(m)...)
}
if len(msgs) == 0 {
return nil, false
}
out := chatInvokeRequest{
MaxTokens: doc.MaxTokens,
Temperature: doc.Temperature,
Stop: doc.StopSequences,
Messages: msgs,
}
for _, tool := range doc.Tools {
if tool.Name == "" {
continue
}
params := tool.InputSchema
if len(params) == 0 || string(params) == "null" {
params = json.RawMessage(`{"type":"object"}`)
}
var ot oaOutTool
ot.Type = "function"
ot.Function.Name = tool.Name
ot.Function.Description = tool.Description
ot.Function.Parameters = params
out.Tools = append(out.Tools, ot)
}
rewritten, err := json.Marshal(out)
if err != nil {
return nil, false
}
return rewritten, true
}
func jsonStarts(raw json.RawMessage, c byte) bool {
raw = json.RawMessage(strings.TrimSpace(string(raw)))
return len(raw) > 0 && raw[0] == c
}
func openAIMessages(m anthInMessage) []oaOutMessage {
if !jsonStarts(m.Content, '[') {
text := jsonText(m.Content)
if text == "" && m.Role == "" {
return nil
}
if m.Role == "assistant" && text == "" {
text = "…"
}
if text == "" {
return nil
}
return []oaOutMessage{{Role: m.Role, Content: text}}
}
var blocks []anthInBlock
if json.Unmarshal(m.Content, &blocks) != nil {
return nil
}
if m.Role == "assistant" {
msg := oaOutMessage{Role: "assistant"}
var text strings.Builder
var reasoning strings.Builder
for _, b := range blocks {
switch b.Type {
case "text":
text.WriteString(b.Text)
case "thinking":
reasoning.WriteString(b.Thinking)
case "tool_use":
call := oaOutCall{ID: b.ID, Type: "function"}
if call.ID == "" {
call.ID = fmt.Sprintf("tool_%d", len(msg.ToolCalls))
}
call.Function.Name = b.Name
call.Function.Arguments = toolArguments(b.Input)
msg.ToolCalls = append(msg.ToolCalls, call)
}
}
msg.Content = text.String()
msg.Reasoning = reasoning.String()
if msg.Content == "" && len(msg.ToolCalls) == 0 {
msg.Content = "…"
}
return []oaOutMessage{msg}
}
var text strings.Builder
var toolMsgs []oaOutMessage
for _, b := range blocks {
switch b.Type {
case "text":
text.WriteString(b.Text)
case "tool_result":
toolMsgs = append(toolMsgs, oaOutMessage{Role: "tool", ToolCallID: b.ToolUseID, Content: jsonText(b.Content)})
}
}
if s := text.String(); s != "" {
toolMsgs = append(toolMsgs, oaOutMessage{Role: "user", Content: s})
}
return toolMsgs
}
func toolArguments(raw json.RawMessage) string {
raw = json.RawMessage(strings.TrimSpace(string(raw)))
if len(raw) == 0 || string(raw) == "null" {
return "{}"
}
if json.Valid(raw) && (raw[0] == '{' || raw[0] == '[') {
return string(raw)
}
return "{}"
}
// rewriteBedrockModelJSON passes an Anthropic Messages body through and rewrites
// an OpenAI chat.completion into that shape. The raw body is never returned in
// an error: gateways can echo the bearer token there.
func rewriteBedrockModelJSON(raw []byte) ([]byte, error) {
if isAnthropicModelJSON(raw) {
return raw, nil
}
rewritten, ok := anthropicFromChatCompletion(raw)
if !ok {
return nil, bedrockShapeError(raw)
}
return rewritten, nil
}
func isAnthropicModelJSON(raw []byte) bool {
var probe struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(raw, &probe) != nil {
return false
}
if probe.Type == "message" || probe.Type == "error" {
return true
}
return len(probe.Content) > 0 && probe.Content[0] == '['
}
// bedrockGatewayError is raised by the adapter itself. Its text never includes
// gateway-supplied values, so it is safe to show to the operator.
type bedrockGatewayError struct{ msg string }
func (e *bedrockGatewayError) Error() string { return e.msg }
func bedrockShapeError(raw []byte) error {
if !json.Valid(raw) {
return &bedrockGatewayError{"Bedrock gateway response was not JSON"}
}
var top map[string]json.RawMessage
if json.Unmarshal(raw, &top) != nil {
return &bedrockGatewayError{"Bedrock gateway response was not a JSON object"}
}
keys := make([]string, 0, len(top))
for k := range top {
keys = append(keys, k)
}
sort.Strings(keys)
if len(keys) > 8 {
keys = append(keys[:8], "…")
}
finish := ""
if c, ok := top["choices"]; ok {
var choices []struct {
FinishReason string `json:"finish_reason"`
}
_ = json.Unmarshal(c, &choices)
if len(choices) > 0 {
finish = choices[0].FinishReason
}
}
return &bedrockGatewayError{fmt.Sprintf("Bedrock gateway response was not an Anthropic message or a chat completion (object=%s, finish_reason=%s, keys=%s)", jsonStringField(top["object"]), finish, strings.Join(keys, ","))}
}
func jsonStringField(raw json.RawMessage) string {
var s string
if json.Unmarshal(raw, &s) != nil {
return ""
}
return s
}
type chatDoc struct {
Object string `json:"object"`
Choices []chatChoice `json:"choices"`
Usage chatUsageBlock `json:"usage"`
}
type chatChoice struct {
FinishReason string `json:"finish_reason"`
Message chatMessage `json:"message"`
Delta chatMessage `json:"delta"`
}
type chatMessage struct {
Content json.RawMessage `json:"content"`
Reasoning string `json:"reasoning"`
ReasoningContent string `json:"reasoning_content"`
ReasoningText string `json:"reasoning_text"`
ToolCalls []chatToolCall `json:"tool_calls"`
}
type chatToolCall struct {
Index int `json:"index"`
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
type chatUsageBlock struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
}
type anthBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Thinking string `json:"thinking,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
}
type anthMessage struct {
Type string `json:"type"`
Role string `json:"role"`
Content []anthBlock `json:"content"`
StopReason string `json:"stop_reason,omitempty"`
Usage *anthUsage `json:"usage,omitempty"`
}
type anthUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
}
func anthropicFromChatCompletion(raw []byte) ([]byte, bool) {
var doc chatDoc
if json.Unmarshal(raw, &doc) != nil || doc.Object != "chat.completion" {
return nil, false
}
msg := anthMessage{Type: "message", Role: "assistant", Content: []anthBlock{}}
if len(doc.Choices) > 0 {
ch := doc.Choices[0]
msg.Content = blocksFromMessage(ch.Message)
msg.StopReason = mapFinishReason(ch.FinishReason)
}
if doc.Usage.PromptTokens != 0 || doc.Usage.CompletionTokens != 0 {
msg.Usage = &anthUsage{InputTokens: doc.Usage.PromptTokens, OutputTokens: doc.Usage.CompletionTokens}
}
out, err := json.Marshal(msg)
if err != nil {
return nil, false
}
return out, true
}
func blocksFromMessage(m chatMessage) []anthBlock {
var blocks []anthBlock
if think := pickReasoningText(m.Reasoning, m.ReasoningContent, m.ReasoningText); think != "" {
blocks = append(blocks, anthBlock{Type: "thinking", Thinking: think})
}
if text := jsonText(m.Content); text != "" {
blocks = append(blocks, anthBlock{Type: "text", Text: text})
}
for i, tc := range m.ToolCalls {
id := tc.ID
if id == "" {
id = fmt.Sprintf("tool_%d", i)
}
name := tc.Function.Name
if name == "" {
name = "tool"
}
blocks = append(blocks, anthBlock{Type: "tool_use", ID: id, Name: name, Input: toolInput(tc.Function.Arguments)})
}
if blocks == nil {
blocks = []anthBlock{}
}
return blocks
}
func pickReasoningText(fields ...string) string {
for _, f := range fields {
if f != "" {
return f
}
}
return ""
}
func jsonText(raw json.RawMessage) string {
if len(raw) == 0 || string(raw) == "null" {
return ""
}
var s string
if json.Unmarshal(raw, &s) == nil {
return s
}
var parts []struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(raw, &parts) != nil {
return ""
}
var b strings.Builder
for _, p := range parts {
if p.Type == "" || p.Type == "text" {
b.WriteString(p.Text)
}
}
return b.String()
}
func toolInput(arguments string) json.RawMessage {
arguments = strings.TrimSpace(arguments)
if arguments != "" && json.Valid([]byte(arguments)) && (arguments[0] == '{' || arguments[0] == '[') {
return json.RawMessage(arguments)
}
return json.RawMessage(`{}`)
}
func mapFinishReason(s string) string {
switch s {
case "stop":
return "end_turn"
case "length":
return "max_tokens"
case "tool_calls":
return "tool_use"
default:
return s
}
}
// chatCompletionToSSE replays a non-streamed chat.completion as Anthropic SSE
// for a gateway that ignored the streaming request.
func chatCompletionToSSE(raw []byte) (string, bool, error) {
var doc chatDoc
if json.Unmarshal(raw, &doc) != nil || doc.Object != "chat.completion" {
return "", false, nil
}
var b strings.Builder
c := &chatChunkWriter{w: &b}
if err := c.write(raw); err != nil {
return "", true, err
}
if err := c.finish(""); err != nil {
return "", true, err
}
return b.String(), true, nil
}
func writeSSE(w io.Writer, event string, payload any) error {
b, err := json.Marshal(payload)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
return err
}
func bedrockPayloadKind(payload []byte) string {
var probe struct {
Object string `json:"object"`
Type string `json:"type"`
}
if json.Unmarshal(payload, &probe) != nil {
return "invalid"
}
switch probe.Object {
case "chat.completion", "chat.completion.chunk":
return "chat"
}
if validEventType(probe.Type) {
return "anthropic"
}
return "invalid"
}
// chatChunkWriter turns a sequence of chat.completion.chunk frames into
// Anthropic SSE. Tool-call argument fragments are forwarded as they arrive.
type chatChunkWriter struct {
w io.Writer
started bool
finished bool
input int
output int
tools map[int]*chatToolState
}
type chatToolState struct {
started bool
id string
name string
pending strings.Builder
}
func (c *chatChunkWriter) write(payload []byte) error {
var doc chatDoc
if json.Unmarshal(payload, &doc) != nil {
return errors.New("invalid Bedrock gateway event")
}
if doc.Usage.PromptTokens != 0 {
c.input = doc.Usage.PromptTokens
}
if doc.Usage.CompletionTokens != 0 {
c.output = doc.Usage.CompletionTokens
}
if len(doc.Choices) == 0 {
return nil
}
ch := doc.Choices[0]
if err := c.emitMessage(ch.Delta); err != nil {
return err
}
// A full message has no per-call index; number its calls by position.
for i := range ch.Message.ToolCalls {
ch.Message.ToolCalls[i].Index = i
}
if err := c.emitMessage(ch.Message); err != nil {
return err
}
if ch.FinishReason != "" {
return c.finish(mapFinishReason(ch.FinishReason))
}
return nil
}
func (c *chatChunkWriter) emitMessage(m chatMessage) error {
think := pickReasoningText(m.Reasoning, m.ReasoningContent, m.ReasoningText)
text := jsonText(m.Content)
if think == "" && text == "" && len(m.ToolCalls) == 0 {
return nil
}
if err := c.ensureStart(); err != nil {
return err
}
if think != "" {
if err := writeSSE(c.w, "content_block_delta", map[string]any{
"type": "content_block_delta",
"delta": map[string]string{"type": "thinking_delta", "thinking": think},
}); err != nil {
return err
}
}
if text != "" {
if err := writeSSE(c.w, "content_block_delta", map[string]any{
"type": "content_block_delta",
"delta": map[string]string{"type": "text_delta", "text": text},
}); err != nil {
return err
}
}
for _, tc := range m.ToolCalls {
if err := c.emitTool(tc); err != nil {
return err
}
}
return nil
}
func (c *chatChunkWriter) emitTool(tc chatToolCall) error {
if c.tools == nil {
c.tools = map[int]*chatToolState{}
}
st := c.tools[tc.Index]
if st == nil {
st = &chatToolState{}
c.tools[tc.Index] = st
}
if tc.ID != "" {
st.id = tc.ID
}
if tc.Function.Name != "" {
st.name = tc.Function.Name
}
if !st.started {
st.pending.WriteString(tc.Function.Arguments)
if st.name == "" {
return nil
}
if st.id == "" {
st.id = fmt.Sprintf("tool_%d", tc.Index)
}
st.started = true
if err := writeSSE(c.w, "content_block_start", map[string]any{
"type": "content_block_start",
"content_block": map[string]string{
"type": "tool_use", "id": st.id, "name": st.name,
},
}); err != nil {
return err
}
if st.pending.Len() == 0 {
return nil
}
frag := st.pending.String()
st.pending.Reset()
return writeSSE(c.w, "content_block_delta", map[string]any{
"type": "content_block_delta",
"delta": map[string]string{"type": "input_json_delta", "partial_json": frag},
})
}
if tc.Function.Arguments == "" {
return nil
}
return writeSSE(c.w, "content_block_delta", map[string]any{
"type": "content_block_delta",
"delta": map[string]string{"type": "input_json_delta", "partial_json": tc.Function.Arguments},
})
}
func (c *chatChunkWriter) ensureStart() error {
if c.started {
return nil
}
c.started = true
return writeSSE(c.w, "message_start", map[string]any{
"type": "message_start",
"message": map[string]any{"usage": map[string]int{"input_tokens": c.input, "output_tokens": 0}},
})
}
func (c *chatChunkWriter) finish(stop string) error {
if c.finished {
return nil
}
if err := c.ensureStart(); err != nil {
return err
}
c.finished = true
if stop == "" {
stop = "end_turn"
}
if err := writeSSE(c.w, "message_delta", map[string]any{
"type": "message_delta",
"delta": map[string]string{"stop_reason": stop},
"usage": map[string]int{"input_tokens": c.input, "output_tokens": c.output},
}); err != nil {
return err
}
return writeSSE(c.w, "message_stop", map[string]string{"type": "message_stop"})
}
func (c *chatChunkWriter) close() error {
if c.finished || !c.started {
return nil
}
return c.finish("end_turn")
}
func mustURLPath(raw string) string { u, _ := url.Parse(raw); return u.Path }
func validEventType(s string) bool {
+275
View File
@@ -1,6 +1,7 @@
package agent
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
@@ -8,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -216,6 +218,279 @@ func TestBedrockGatewayEscapesModelARN(t *testing.T) {
}
}
func TestBedrockGatewayChatCompletionCompleteAndStream(t *testing.T) {
const okBody = `{"choices":[{"finish_reason":"stop","index":0,"message":{"content":"OK","reasoning":"The user asked for OK.","role":"assistant"}}],"object":"chat.completion","usage":{"completion_tokens":33,"prompt_tokens":33}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.URL.Path, "response-stream") {
_, _ = w.Write([]byte(okBody))
return
}
_, _ = w.Write([]byte(okBody))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
p, err := cfg.NewProvider()
if err != nil {
t.Fatal(err)
}
msg, stop, usage, err := p.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}})
if err != nil || msg.Text() != "OK" || stop != "end_turn" || usage.InputTokens != 33 || usage.OutputTokens != 33 {
t.Fatalf("complete text=%q stop=%q usage=%+v err=%v", msg.Text(), stop, usage, err)
}
var thought string
for _, b := range msg.Content {
if b.Type == llm.BlockThinking {
thought = b.Thinking
}
}
if thought != "The user asked for OK." {
t.Fatalf("thinking = %q", thought)
}
var streamed, thoughtStream string
for ev, err := range p.Stream(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}) {
if err != nil {
t.Fatal(err)
}
switch ev.Type {
case llm.SETextDelta:
streamed += ev.Text
case llm.SEThinkingDelta:
thoughtStream += ev.Text
}
}
if streamed != "OK" || thoughtStream != "The user asked for OK." {
t.Fatalf("json stream text=%q thinking=%q", streamed, thoughtStream)
}
}
func TestBedrockGatewayChatCompletionChunkStream(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.amazon.eventstream")
enc := eventstream.NewEncoder()
for _, payload := range []string{
`{"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning":"think"},"finish_reason":null}]}`,
`{"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"OK"},"finish_reason":null}]}`,
`{"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"lookup","arguments":""}}]}}]}`,
`{"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"q\":\"x\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`,
} {
if err := enc.Encode(w, eventstream.Message{Headers: eventstream.Headers{{Name: ":message-type", Value: eventstream.StringValue("event")}, {Name: ":event-type", Value: eventstream.StringValue("chunk")}}, Payload: []byte(payload)}); err != nil {
t.Error(err)
}
}
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
p, err := cfg.NewProvider()
if err != nil {
t.Fatal(err)
}
var streamed, thought, toolName, toolInput, stop string
var usage llm.Usage
for ev, err := range p.Stream(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}) {
if err != nil {
t.Fatal(err)
}
switch ev.Type {
case llm.SETextDelta:
streamed += ev.Text
case llm.SEThinkingDelta:
thought += ev.Text
case llm.SEToolUseStart:
toolName = ev.ToolName
case llm.SEToolInputJSON:
toolInput += ev.Text
case llm.SEMessageDelta:
stop = ev.StopReason
usage = ev.Usage
}
}
if streamed != "OK" || thought != "think" || toolName != "lookup" || toolInput != `{"q":"x"}` || stop != "tool_use" || usage.InputTokens != 3 || usage.OutputTokens != 2 {
t.Fatalf("text=%q thinking=%q tool=%q %q stop=%q usage=%+v", streamed, thought, toolName, toolInput, stop, usage)
}
}
func TestBedrockGatewayChatCompletionToolCall(t *testing.T) {
const body = `{"object":"chat.completion","choices":[{"finish_reason":"tool_calls","message":{"content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{\"q\":\"x\"}"}},{"id":"call_2","type":"function","function":{"name":"fetch","arguments":"{\"u\":\"y\"}"}}]}}]}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
p, err := cfg.NewProvider()
if err != nil {
t.Fatal(err)
}
msg, stop, _, err := p.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}})
uses := msg.ToolUses()
if err != nil || stop != "tool_use" || len(uses) != 2 || uses[0].Name != "lookup" || string(uses[0].Input) != `{"q":"x"}` || uses[1].Name != "fetch" || string(uses[1].Input) != `{"u":"y"}` {
t.Fatalf("stop=%q uses=%+v err=%v", stop, uses, err)
}
// A gateway that answers a streaming request with a plain chat.completion.
var names, inputs []string
for ev, err := range p.Stream(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("hello")}}) {
if err != nil {
t.Fatal(err)
}
switch ev.Type {
case llm.SEToolUseStart:
names = append(names, ev.ToolName)
case llm.SEToolInputJSON:
inputs = append(inputs, ev.Text)
case llm.SEMessageDelta:
stop = ev.StopReason
}
}
if strings.Join(names, ",") != "lookup,fetch" || strings.Join(inputs, ",") != `{"q":"x"},{"u":"y"}` || stop != "tool_use" {
t.Fatalf("stream tools=%v inputs=%v stop=%q", names, inputs, stop)
}
}
func TestBedrockGatewayConnectionErrorIsRedacted(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
baseURL := server.URL + "/synthetic-secret-path"
server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", baseURL, "synthetic-token", "")
cfg.Stream = false
cfg.Retry.ConnectAttempts = -1
_, _, err := TestConnection(context.Background(), cfg)
if err == nil || err.Error() != "Bedrock gateway connection failed" {
t.Fatalf("error = %v", err)
}
}
func TestBedrockGatewayReasoningOnlyConnectionError(t *testing.T) {
const body = `{"choices":[{"finish_reason":"length","message":{"content":null,"reasoning":"still thinking about the reply"}}],"object":"chat.completion"}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
cfg.Stream = false
_, _, err := TestConnection(context.Background(), cfg)
if err == nil || !strings.Contains(err.Error(), "reasoning") || !strings.Contains(err.Error(), "max_tokens") || strings.Contains(err.Error(), "still thinking") {
t.Fatalf("error = %v", err)
}
}
func TestBedrockGatewayUnexpectedShapeIsStructural(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"secret":"synthetic-token","object":"weird"}`))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
cfg.Stream = false
_, _, err := TestConnection(context.Background(), cfg)
if err == nil || !strings.Contains(err.Error(), "chat completion") || !strings.Contains(err.Error(), "object=weird") || strings.Contains(err.Error(), "synthetic-token") {
t.Fatalf("error = %v", err)
}
}
func TestBedrockGatewayRetriesChatCompletionRequest(t *testing.T) {
const okBody = `{"choices":[{"finish_reason":"stop","message":{"content":"OK","role":"assistant"}}],"object":"chat.completion"}`
var mu sync.Mutex
var bodies [][]byte
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
mu.Lock()
bodies = append(bodies, append([]byte(nil), raw...))
mu.Unlock()
if bytes.Contains(raw, []byte("anthropic_version")) || bytes.Contains(raw, []byte("input_schema")) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"message":"rejected synthetic-secret"}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(okBody))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
p, err := cfg.NewProvider()
if err != nil {
t.Fatal(err)
}
req := llm.CompletionRequest{
System: []string{"sys"},
Messages: []llm.Message{llm.UserText("hi")},
Tools: []llm.ToolSchema{{Name: "lookup", Description: "d", InputSchema: map[string]any{"type": "object"}}},
MaxTokens: 100,
}
for range 2 {
msg, _, _, err := p.Complete(context.Background(), req)
if err != nil || msg.Text() != "OK" {
t.Fatalf("complete text=%q err=%v", msg.Text(), err)
}
}
mu.Lock()
defer mu.Unlock()
if len(bodies) != 3 {
t.Fatalf("calls = %d, want anthropic 400, chat retry, then a direct chat request", len(bodies))
}
if !bytes.Contains(bodies[0], []byte("input_schema")) {
t.Fatalf("first request was not an Anthropic tool body: %s", bodies[0])
}
for i, body := range bodies[1:] {
var doc struct {
AnthropicVersion string `json:"anthropic_version"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
Tools []struct {
Function struct {
Name string `json:"name"`
Parameters json.RawMessage `json:"parameters"`
} `json:"function"`
} `json:"tools"`
}
if err := json.Unmarshal(body, &doc); err != nil {
t.Fatal(err)
}
if doc.AnthropicVersion != "" || bytes.Contains(body, []byte("input_schema")) || bytes.Contains(body, []byte("synthetic-secret")) {
t.Fatalf("call %d was not a chat completion: %s", i+2, body)
}
var user string
sawSystem := false
for _, m := range doc.Messages {
if m.Role == "system" && m.Content == "sys" {
sawSystem = true
}
if m.Role == "user" {
user = m.Content
}
}
if !sawSystem || user != "hi" || len(doc.Tools) != 1 || doc.Tools[0].Function.Name != "lookup" || !bytes.Contains(doc.Tools[0].Function.Parameters, []byte("object")) {
t.Fatalf("call %d messages=%+v tools=%+v", i+2, doc.Messages, doc.Tools)
}
}
}
func TestBedrockGatewayChatRequestRejectionStaysRedacted(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"message":"rejected synthetic-secret"}`))
}))
defer server.Close()
cfg := ConfigFrom("bedrock-gateway", "test.model", server.URL, "synthetic-token", "")
p, err := cfg.NewProvider()
if err != nil {
t.Fatal(err)
}
_, _, _, err = p.Complete(context.Background(), llm.CompletionRequest{
Messages: []llm.Message{llm.UserText("hi")},
Tools: []llm.ToolSchema{{Name: "lookup", Description: "d", InputSchema: map[string]any{"type": "object"}}},
MaxTokens: 32,
})
if err == nil || !strings.Contains(err.Error(), "400") || strings.Contains(err.Error(), "synthetic-secret") {
t.Fatalf("error = %v", err)
}
}
func TestBedrockGatewayRejectsUnsafeConfig(t *testing.T) {
for _, cfg := range []Config{
ConfigFrom("bedrock-gateway", "model", "", "token", ""),
+39 -1
View File
@@ -12,6 +12,7 @@ package agent
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"iter"
@@ -710,6 +711,12 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
if len(attempts) > 0 && attempts[len(attempts)-1].Status >= 400 {
return lat, "", fmt.Errorf("Bedrock gateway returned HTTP %d", attempts[len(attempts)-1].Status)
}
// Only adapter-generated errors are shown; transport errors may carry
// gateway-supplied text.
var gwErr *bedrockGatewayError
if errors.As(err, &gwErr) {
return lat, "", gwErr
}
return lat, "", fmt.Errorf("Bedrock gateway connection failed")
}
return lat, "", err
@@ -727,16 +734,38 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
// the discrepancy this check eliminates. No visible body = fail.
reply = strings.TrimSpace(reply)
if reply == "" {
return lat, "", fmt.Errorf("the model returned no content (the request went through, but no text was returned)")
return lat, "", emptyReplyError(probe)
}
return lat, reply, nil
}
// emptyReplyError explains a completed call whose visible text was empty.
// Reasoning-only replies and a length stop are named so a thinking model that
// exhausted its budget is not reported as a transport failure.
func emptyReplyError(p *connTestProvider) error {
reason := strings.TrimSpace(p.stopReason)
if p.sawThinking {
switch reason {
case "max_tokens", "length":
return fmt.Errorf("the model returned reasoning and no visible content (finish_reason=%q); the token budget was consumed before it wrote a reply", reason)
case "":
return fmt.Errorf("the model returned reasoning and no visible content")
default:
return fmt.Errorf("the model returned reasoning and no visible content (finish_reason=%q)", reason)
}
}
if reason != "" {
return fmt.Errorf("the model returned no content (finish_reason=%q)", reason)
}
return fmt.Errorf("the model returned no content (the request went through, but no text was returned)")
}
// connTestProvider observes the raw provider response during TestConnection so
// tool-call replies and tool_calls/tool_use stop reasons are rejected (#526).
type connTestProvider struct {
inner llm.Provider
sawToolCall bool
sawThinking bool
stopReason string
}
@@ -747,6 +776,9 @@ func (p *connTestProvider) Stream(ctx context.Context, req llm.CompletionRequest
if ev.Type == llm.SEToolUseStart {
p.sawToolCall = true
}
if ev.Type == llm.SEThinkingDelta && ev.Text != "" {
p.sawThinking = true
}
if ev.StopReason != "" {
p.stopReason = ev.StopReason
}
@@ -764,6 +796,12 @@ func (p *connTestProvider) Complete(ctx context.Context, req llm.CompletionReque
if len(msg.ToolUses()) > 0 {
p.sawToolCall = true
}
for _, b := range msg.Content {
if b.Type == llm.BlockThinking && b.Thinking != "" {
p.sawThinking = true
break
}
}
if stopReason != "" {
p.stopReason = stopReason
}
+6
View File
@@ -123,6 +123,12 @@ if [ "${ARTEX_SKIP_FRONTEND:-0}" = "1" ]; then
[ -d server/webui/dist ] || die "ARTEX_SKIP_FRONTEND=1 but server/webui/dist does not exist"
else
command -v npm >/dev/null 2>&1 || die "npm not detected (building the frontend static assets requires Node.js/npm)"
# Next.js 16 requires Node >= 20.9; CI and the Dockerfile use Node 22.
node_ver="$(node --version 2>/dev/null | sed 's/^v//')"
node_major="${node_ver%%.*}"; node_rest="${node_ver#*.}"; node_minor="${node_rest%%.*}"
if [ -z "$node_major" ] || [ "$node_major" -lt 20 ] || { [ "$node_major" -eq 20 ] && [ "${node_minor:-0}" -lt 9 ]; }; then
die "Node.js >= 20.9 is required to build the frontend (found ${node_ver:-none}); Node 22 LTS recommended. Install via nvm/fnm/NodeSource, or set ARTEX_SKIP_FRONTEND=1 to reuse server/webui/dist."
fi
command -v rsync >/dev/null 2>&1 || die "rsync not detected"
info "Building frontend static assets"
if [ "${ARTEX_SKIP_NPM_CI:-0}" != "1" ]; then
+53
View File
@@ -0,0 +1,53 @@
package db
import (
"context"
"testing"
"github.com/Autumn-27/artex/notify"
)
// A model can write the severity of report_finding as "High" or " critical ".
// The finding must be stored with the canonical lowercase level, or the
// severity counters and every min_severity notification channel skip it.
func TestRecordFindingStoresCanonicalSeverity(t *testing.T) {
d := notifyTestDB(t)
ctx := context.Background()
ch := newTestChannel(t, d, notify.KindDingTalk, NotifyModeRealtime, `{"min_severity":"high"}`)
tk, err := d.CreateTask("severity case test", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(tk.ID) })
f, err := d.Exploration(tk.ExplorationID).RecordFinding(ctx, RecordFindingInput{
TaskID: tk.ID, Worker: "test", VulnClass: "SQL injection", Name: "severity case",
Severity: " High ", Summary: "summary",
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM notification_events WHERE finding_id=$1`, f.FindingID)
_, _ = d.DeleteFinding(f.FindingID)
})
var severity string
if err := d.QueryRow(`SELECT severity FROM findings WHERE id=$1`, f.FindingID).Scan(&severity); err != nil {
t.Fatal(err)
}
if severity != SeverityHigh {
t.Fatalf("stored severity = %q, want %q", severity, SeverityHigh)
}
if _, _, err := d.FanOutPendingEvents(ctx, 1000); err != nil {
t.Fatal(err)
}
var deliveries int
if err := d.QueryRow(`SELECT count(*) FROM notification_deliveries dl JOIN notification_events ev ON ev.id=dl.event_id
WHERE dl.channel_id=$1 AND ev.finding_id=$2`, ch.ID, f.FindingID).Scan(&deliveries); err != nil {
t.Fatal(err)
}
if deliveries != 1 {
t.Fatalf("a high finding must reach the min_severity=high channel, got %d deliveries", deliveries)
}
}
+4
View File
@@ -414,6 +414,10 @@ func RecordFindingTx(ctx context.Context, tx *sql.Tx, in RecordFindingInput, pre
return nil, errors.New("intent_id must be an intent of this task (intents of associated tasks are read-only)")
}
}
// The severity comes from the model as free text. Store the canonical level
// ("High" -> "high"): the severity counters and the min_severity filter of
// the notification channels compare it exactly.
in.Severity = strings.ToLower(strings.TrimSpace(in.Severity))
payload, _ := json.Marshal(map[string]any{"vulnclass": in.VulnClass, "name": in.Name, "severity": in.Severity, "summary": in.Summary, "evidence": map[string]any{"by": in.Worker, "poc": in.Evidence}})
out := &RecordedFinding{}
if err := tx.QueryRow(`INSERT INTO exploration_nodes(exploration_id,kind,payload,priority,state,origin)
+5 -3
View File
@@ -143,15 +143,17 @@ func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL
res.ConstraintsUpdated++
}
// Replace task_scope entries matching oldH with newH.
delRes, err := tx.ExecContext(ctx, `DELETE FROM task_scope WHERE task_id=$1 AND LOWER(value)=$2`, taskID, oldH)
// Replace task_scope entries matching oldH with newH. A host scope row keeps
// its host in the domain column (value is only for icp/keyword rows), and the
// coverage queries match on domain.
delRes, err := tx.ExecContext(ctx, `DELETE FROM task_scope WHERE task_id=$1 AND kind IN ('root_domain','subdomain') AND LOWER(domain)=$2`, taskID, oldH)
if err != nil {
return nil, err
}
if n, _ := delRes.RowsAffected(); n > 0 {
res.ScopesUpdated += int(n)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO task_scope(task_id, kind, value, source, reason) VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance') ON CONFLICT DO NOTHING`, taskID, newH); err != nil {
if _, err := tx.ExecContext(ctx, `INSERT INTO task_scope(task_id, kind, domain, source, reason) VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance') ON CONFLICT DO NOTHING`, taskID, newH); err != nil {
return nil, err
}
res.ScopesUpdated++
+61
View File
@@ -0,0 +1,61 @@
# Installation video script
Audience: a first-time self-hoster who has Docker but has never seen ARTEX.
Length: 75 to 90 seconds. Format: 16:9, 1080p, terminal and browser, captions, optional calm
voiceover. The commands must match [INSTALL.md](../INSTALL.md); if the guide changes, update this
script in the same pull request.
## Before recording
- Use a clean terminal, dark theme, font size 16 or larger, and a neutral prompt such as
`~/artex-demo`.
- Use the placeholder password `change-me-please`. Never show a real setup token, API key, cookie
or target data. Replace the token with `SETUP-TOKEN` in post if needed.
- Pre-pull the base images so the build does not dominate the video.
- Keep the cursor movements deliberate. Cut dead time; do not speed up text the viewer must read.
## Shot list
| Time | Visual | On-screen text | Voiceover |
| --- | --- | --- | --- |
| 0:00 to 0:08 | ARTEX logo and console screenshot | Install ARTEX in three commands | ARTEX is self-hosted and installs with Docker Compose. |
| 0:08 to 0:20 | Requirement card | Docker Desktop or Docker Engine, Compose v2, buildx. An LLM key is optional at install time. | You need Docker with Compose v2 and buildx. PostgreSQL comes with the stack. |
| 0:20 to 0:38 | Terminal: clone, enter, copy env | `git clone`, `cd ARTEX`, `cp .env.example .env` | Clone the repository and create your environment file. |
| 0:38 to 0:48 | Editor open on `.env`, cursor on `POSTGRES_PASSWORD` | Set `POSTGRES_PASSWORD` | Set a database password. Add an LLM key here or later in the UI. |
| 0:48 to 1:05 | Terminal: compose up, compose ps | `docker compose up -d --build`, `docker compose ps` | Start the stack. Two containers come up, ARTEX and PostgreSQL. |
| 1:05 to 1:20 | Terminal: log grep, then browser at localhost:8787 | `docker compose logs artex \| grep "Setup token"` | The logs print a one-time setup token. Open localhost port 8787 and paste it. |
| 1:20 to 1:28 | Browser setup screen, fake token, password form | One-time setup, then choose your console password | Choose the console password and you are in. |
| 1:28 to 1:38 | Three troubleshooting cards | Cannot open: check `docker compose port artex 8787`. Docker Desktop: add the desktop overlay. Version says `dev`: run `./update.sh`. | If localhost does not answer, check the port mapping. On Docker Desktop use the overlay file. |
| 1:38 to 1:45 | End card | INSTALL.md, Discord | The full guide and troubleshooting are in INSTALL.md. Questions go to Discord. |
## Commands to record
```bash
git clone https://github.com/BaaRai/ARTEX.git
cd ARTEX
cp .env.example .env
# edit .env: POSTGRES_PASSWORD=change-me-please
docker compose up -d --build
docker compose ps
docker compose logs artex | grep "Setup token"
# open http://localhost:8787
```
Docker Desktop alternative for the troubleshooting card:
```bash
docker compose -f docker-compose.yml -f docker-compose.desktop.yml up -d --build
```
## Caption style
- Commands in monospace, one per line, no wrapping in the middle of a flag.
- Say "localhost port 8787" instead of reading the URL character by character.
- Use "one-time setup token", not "password", for the token.
- No meme captions or hype. The tone is a short, accurate setup demo.
## What not to show
- A real setup token, database password, API key or JWT.
- Real target names or captured traffic.
- A terminal history or shell prompt containing a username you do not want published.
+1 -1
View File
@@ -171,7 +171,7 @@ install_local(){
2)
ensure_docker
local pw; pw="$(ask 'Postgres password (press Enter for random)' "$(rand)")"
docker run -d --name artex-pg -p 5432:5432 \
docker run -d --name artex-pg -p 127.0.0.1:5432:5432 \
-e POSTGRES_USER=artex -e POSTGRES_PASSWORD="$pw" -e POSTGRES_DB=artex \
-v artex-pg:/var/lib/postgresql/data postgres:16-alpine
DB_HOST=127.0.0.1 DB_PORT=5432 DB_USER=artex DB_PASS="$pw" DB_NAME=artex DB_SSL=disable ;;
+7 -2
View File
@@ -476,8 +476,13 @@ func (g *StatefulTargetGuard) ReleaseIntent(taskID string, intentID int64) {
}
var (
mutatingMethodFlagRe = regexp.MustCompile(`(?i)(?:^|\s)(?:-X|--request)\s*=*\s*["']?(POST|PUT|PATCH|DELETE)\b`)
mutatingBodyFlagRe = regexp.MustCompile(`(?i)(?:^|\s)(?:-d|--data|--data-raw|--data-binary|--data-urlencode|-F|--form)(?:\s|=)`)
// Flags are case-sensitive: curl -x is the proxy, -f fails on HTTP errors
// and -D dumps headers; none of them sends a body. --method is wget's.
mutatingMethodFlagRe = regexp.MustCompile(`(?:^|\s)(?:-X|--request|--method)\s*=*\s*\\?["']?(?i:POST|PUT|PATCH|DELETE)\b`)
// A short flag takes its value attached or separate (-d@body.json, -d'{}').
// --json, curl -T/--upload-file and wget's --post-data/--post-file send a
// body too. -T is read only after curl: wget -T is a timeout.
mutatingBodyFlagRe = regexp.MustCompile(`(?:^|\s)(?:-d|-F|--data[\w-]*|--json|--form[\w-]*|--upload-file|--post-data|--post-file)(?:[\s=@'"{\\]|$)|\bcurl\b[^;&|]*\s-T(?:\s|$)`)
mutatingScriptCallRe = regexp.MustCompile(`(?i)(?:\.(?:post|put|patch|delete)\s*\(|http\.Post|method\s*[=:]\s*["'](?:POST|PUT|PATCH|DELETE)["']|urlopen\s*\([^)]*data\s*=)`)
scriptURLRe = regexp.MustCompile(`(?i)https?://[^\s"'<>\\)\]]+`)
)
+49
View File
@@ -361,3 +361,52 @@ func TestLeaseStatusesSortingAndStaleFlag(t *testing.T) {
t.Fatalf("expected filtered z.example.test, got %+v", filtered)
}
}
// Read-only curl flags (-f, -D) do not make a call mutating, and the body
// forms curl and wget accept (attached -d values, --json, -T, --post-data,
// --method) do.
func TestClassifyHTTPActionCommandFlags(t *testing.T) {
cases := []struct {
command string
mutating bool
}{
{`curl -f https://target.lab.local/health`, false},
{`curl -s -D - https://target.lab.local/`, false},
{`wget -T 10 https://target.lab.local/`, false},
{`curl -X POST https://target.lab.local/api -d 'a=1'`, true},
{`curl --request=put https://target.lab.local/api/1`, true},
{`curl -d@payload.json https://target.lab.local/api/users`, true},
{`curl -d'{"role":"admin"}' https://target.lab.local/api/users`, true},
{`curl --json '{"role":"admin"}' https://target.lab.local/api/users`, true},
{`curl -T shell.php https://target.lab.local/upload/`, true},
{`curl --upload-file shell.php https://target.lab.local/upload/`, true},
{`curl --data-ascii a=1 https://target.lab.local/api`, true},
{`wget --post-data 'a=1' https://target.lab.local/api`, true},
{`wget --method=DELETE https://target.lab.local/api/1`, true},
}
for _, c := range cases {
input, _ := json.Marshal(map[string]string{"command": c.command})
hosts, mutating := ClassifyHTTPAction("Bash", input, "", "")
if len(hosts) != 1 || hosts[0] != "target.lab.local" {
t.Errorf("%s: hosts = %v, want [target.lab.local]", c.command, hosts)
}
if mutating != c.mutating {
t.Errorf("%s: mutating = %v, want %v", c.command, mutating, c.mutating)
}
}
}
// A first read-only curl -f call is not refused for a missing baseline, and it
// records the baseline.
func TestStatefulGuardAllowsCurlFailFlagWithoutBaseline(t *testing.T) {
g := NewStatefulTargetGuard()
ctx := WithStatefulActor(WithStatefulGuard(context.Background(), g), "task-1", 1)
input := json.RawMessage(`{"command":"curl -f https://target.lab.local/health"}`)
if err := CheckStatefulTool(ctx, "Bash", input, "", ""); err != nil {
t.Fatalf("read-only curl -f refused: %v", err)
}
RecordStatefulReadOnly(ctx, "Bash", input, "", "")
if !g.HasBaseline("task-1", "target.lab.local") {
t.Fatal("read-only curl -f did not record a baseline")
}
}
File diff suppressed because it is too large Load Diff
+16
View File
@@ -78,4 +78,20 @@ func TestRetargetTaskUpdatesGoalConstraintsScopeAndStopsStaleIntents(t *testing.
if staleNode.State != "stopped" || keepNode.State != "open" {
t.Fatalf("intent states mismatch: stale=%s keep=%s", staleNode.State, keepNode.State)
}
scopes, err := m.Assets().ListTaskScope(mustTaskID(t, task.ID))
if err != nil {
t.Fatal(err)
}
var newScoped bool
for _, sc := range scopes {
if sc.Domain == "old-0c3f.ctf.local" {
t.Fatalf("old host is still in task scope after retarget: %+v", scopes)
}
if sc.Kind == "subdomain" && sc.Domain == "new-4791.ctf.local" {
newScoped = true
}
}
if !newScoped {
t.Fatalf("new host has no subdomain scope row after retarget: %+v", scopes)
}
}
+6 -2
View File
@@ -5,8 +5,8 @@ components, module constants, toasts and non-React helpers; missing keys fall ba
to English. Keep keys, `{name}` placeholders, HTML formatting tags, Go template
actions and literal command/API examples intact when adding translations.
The registered locales are English (`en`), Turkish (`tr`) and Simplified Chinese
(`zh-CN`). The Preferences language control renders `LOCALES` directly. A saved
The registered locales are English (`en`), Turkish (`tr`), Simplified Chinese
(`zh-CN`) and Vietnamese (`vi`). The Preferences language control renders `LOCALES` directly. A saved
`artex.locale` browser preference takes priority over browser language detection;
otherwise an exact language tag, then its base language, is matched. Chinese
browser variants use the available Simplified Chinese dictionary. Static export
@@ -27,3 +27,7 @@ repository's parent of commit `e233c02` (the English translation migration), wit
additional translations for current functionality and normalized UI terminology.
This only localizes interface text; backend data, user content, model responses,
protocol identifiers and tool output are not rewritten.
The Vietnamese dictionary was translated from the English source keys by a
native Vietnamese speaker, with terminology normalized to the terms Vietnamese
security practitioners use. It has the same interface-only scope.
+5 -1
View File
@@ -12,8 +12,9 @@
import tr from "./locales/tr.json";
import zhCN from "./locales/zh-CN.json";
import vi from "./locales/vi.json";
export type Locale = "tr" | "en" | "zh-CN";
export type Locale = "tr" | "en" | "zh-CN" | "vi";
// Used when nothing is saved and the browser language is not one of LOCALES,
// and for the static prerender, which has no browser.
@@ -23,6 +24,7 @@ export const LOCALES: { code: Locale; label: string }[] = [
{ code: "tr", label: "Türkçe" },
{ code: "en", label: "English" },
{ code: "zh-CN", label: "简体中文" },
{ code: "vi", label: "Tiếng Việt" },
];
const STORAGE_KEY = "artex.locale";
@@ -31,12 +33,14 @@ const DICTIONARIES: Record<Locale, Record<string, string>> = {
tr: tr as Record<string, string>,
en: {},
"zh-CN": zhCN as Record<string, string>,
vi: vi as Record<string, string>,
};
const INTL_LOCALES: Record<Locale, string> = {
tr: "tr-TR",
en: "en-US",
"zh-CN": "zh-CN",
vi: "vi-VN",
};
function detectLocale(): Locale {
File diff suppressed because it is too large Load Diff