Compare commits

..
Author SHA1 Message Date
BaaRai 256e16ac16 Merge pull request #672 from BaaRai/land/correctness-stack-2026-11-28
Land the rebased correctness stack: #647, #638, #610
2026-11-28 19:42:15 +01:00
BaaRaiandshuhuNB515 a0e5eae0d7 fix(llmpool): include MaxTokens in token budget estimate (#610)
Rebased CHANGELOG.md on top of #647 and #638.

Co-authored-by: shuhuNB515 <shuhuNB515@users.noreply.github.com>
2026-11-28 19:24:53 +01:00
BaaRaiandshuhuNB515 b530669908 fix(agent): wire enrichment trigger in insert_assets (#638)
Rebased CHANGELOG.md on top of #647.

Co-authored-by: shuhuNB515 <shuhuNB515@users.noreply.github.com>
2026-11-28 19:24:53 +01:00
BaaRaiandshuhuNB515 5d6abf0437 fix(traffic): return id and ts from /api/traffic/exchange (#647)
Co-authored-by: shuhuNB515 <shuhuNB515@users.noreply.github.com>
2026-11-28 19:24:53 +01: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
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
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
32 changed files with 6973 additions and 84 deletions
+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@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.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
+3
View File
@@ -19,7 +19,10 @@ All notable changes to this project are documented in this file. The format is b
- **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`.
### Fixed
- **LLM failover charges the response budget against the context window**: the window filter sized only the prompt, so a profile whose window held the prompt but not `max_tokens` was still tried. The provider rejects that call with a 400, and a 400 never fails over (a malformed request fails identically everywhere), so the call failed outright instead of moving to a profile that can hold prompt and response. The estimate now adds the request's `max_tokens`, and a member that cannot hold both is skipped; when every member is skipped the chain head is still tried, as before.
- **Inserted assets trigger the async enrichment again**: `ToolSet.enrich` was assigned by `SetEnrich` and passed all the way from the manager, but no tool ever read it, so the enrichment engine started, was paced by the noise profile, was covered by tests, and never received a job: an inserted domain was never resolved and an inserted HTTP service was never probed. `insert_assets` now hands each written asset to the engine (domain → DNS resolve, HTTP service → probe), after the intercept gate and only for a row that was actually written. Both ingest tools call `insert_assets`, so scanned assets are covered too.
- **`GET /api/traffic/exchange` reports which capture it returned**: the response carried only the raw `req`/`resp` text and stream counters, so a caller holding an exchange id could not tell which exchange the bodies came from or when it was captured. It now also returns `id` and `ts` (Unix seconds) from the exchange's metadata row. The bench-v2 R2 check needs that timestamp to credit a finding's `traffic_ref`, and without it every referenced capture was rejected as `traffic_ref_missing_timestamp`, leaving detection rate and precision at zero for any run with traffic verification on (the default; `--skip-traffic-verify` opts out).
- **Ollama accepts the Main Agent's tools**: the `summary` pattern in the `record_fact` schema was unanchored, and Ollama refuses the whole request with HTTP 400 ("Pattern must start with '^' and end with '$'") when it turns a schema into a grammar, so the first turn failed. The pattern is now anchored and still means "contains a non-whitespace character", multi-line summaries included. A test fails on any unanchored pattern in the schema. Based on the approach in #599 by @Layfate (#595).
- **`traffic_search` host matching**: a port search such as `host:8443` matched any capture of that host whose URL quoted `host:8443` in its query string (`?next=http://host:8443/`, typical of open-redirect and SSRF probes), because the authority prefix was not anchored to the scheme. It is now anchored to `http`, `https`, `ws` and `wss`. The recorded host keeps the client's case while the search is lowercased, so a capture of `https://Mixed.Example.com/` was not found by any host search; the comparison now ignores case. A compressed body with a bad checksum or trailing garbage now keeps the text decoded before the error instead of dropping out of the index, and the store directory guard on host delete ignores case for case-insensitive filesystems.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest.
+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; \
+9 -1
View File
@@ -535,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
@@ -603,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", ""),
+96
View File
@@ -0,0 +1,96 @@
package agent
import (
"context"
"testing"
)
// fakeEnrich records the triggers the tool layer hands to the enrichment engine.
// Before insert_assets called the engine, the ToolSet field was assigned but
// never read, so no asset was ever resolved or probed (see triggerEnrichment).
type fakeEnrich struct {
resolved []string
probed []string
probeCtx []context.Context
}
func (f *fakeEnrich) ResolveDomain(id int64, host string) {
f.resolved = append(f.resolved, host)
}
func (f *fakeEnrich) ProbeSite(ctx context.Context, id int64, url string) {
f.probed = append(f.probed, url)
f.probeCtx = append(f.probeCtx, ctx)
}
// TestInsertAssetsTriggersEnrichment pins which inserted asset types start an
// async auto-completion job: a domain resolves, an HTTP service is probed, and
// everything the engine cannot act on is left alone.
func TestInsertAssetsTriggersEnrichment(t *testing.T) {
cases := []struct {
name string
typ string
item assetInputItem
wantDomain string
wantProbe string
}{
{name: "root_domain resolves", typ: "root_domain", item: assetInputItem{Domain: "example.com"}, wantDomain: "example.com"},
{name: "subdomain resolves", typ: "subdomain", item: assetInputItem{Domain: "api.example.com"}, wantDomain: "api.example.com"},
{name: "domain is trimmed", typ: "subdomain", item: assetInputItem{Domain: " api.example.com "}, wantDomain: "api.example.com"},
{name: "http service is probed", typ: "service", item: assetInputItem{URL: "https://example.com:8443/login"}, wantProbe: "https://example.com:8443/login"},
{name: "url is trimmed", typ: "service", item: assetInputItem{URL: " https://example.com/ "}, wantProbe: "https://example.com/"},
// A non-HTTP service has no url: nothing to probe.
{name: "non-http service is skipped", typ: "service", item: assetInputItem{ServiceName: "ssh", Port: 22}},
{name: "ip is skipped", typ: "ip", item: assetInputItem{IP: "203.0.113.7"}},
{name: "app is skipped", typ: "app", item: assetInputItem{AppName: "portal"}},
{name: "endpoint is skipped", typ: "endpoint", item: assetInputItem{URL: "https://example.com/api", Method: "GET"}},
{name: "blank domain is skipped", typ: "subdomain", item: assetInputItem{Domain: " "}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
enr := &fakeEnrich{}
ts := NewToolSet(nil, "worker")
ts.SetEnrich(enr)
ctx := context.Background()
ts.triggerEnrichment(ctx, tc.typ, 7, tc.item)
if tc.wantDomain != "" {
if len(enr.resolved) != 1 || enr.resolved[0] != tc.wantDomain {
t.Fatalf("resolved %v, want [%s]", enr.resolved, tc.wantDomain)
}
} else if len(enr.resolved) != 0 {
t.Fatalf("resolved %v, want no DNS job", enr.resolved)
}
if tc.wantProbe != "" {
if len(enr.probed) != 1 || enr.probed[0] != tc.wantProbe {
t.Fatalf("probed %v, want [%s]", enr.probed, tc.wantProbe)
}
// The probe must keep the caller's context: it carries the target
// scope the engine gates the dial on, so a replaced or background
// context would make the probe refuse to dial.
if len(enr.probeCtx) != 1 || enr.probeCtx[0] != ctx {
t.Fatalf("probe did not receive the caller context")
}
} else if len(enr.probed) != 0 {
t.Fatalf("probed %v, want no HTTP probe", enr.probed)
}
})
}
}
// TestEnrichmentTriggerWithoutEngineIsNoop pins that the trigger is optional:
// tool sets built outside a worker run carry no engine, and that must not panic.
func TestEnrichmentTriggerWithoutEngineIsNoop(t *testing.T) {
ts := NewToolSet(nil, "worker")
ts.triggerEnrichment(context.Background(), "root_domain", 1, assetInputItem{Domain: "example.com"})
ts.triggerEnrichment(context.Background(), "service", 2, assetInputItem{URL: "https://example.com/"})
// A write that produced no id (a no-op upsert path) must not be triggered either.
enr := &fakeEnrich{}
ts.SetEnrich(enr)
ts.triggerEnrichment(context.Background(), "root_domain", 0, assetInputItem{Domain: "example.com"})
ts.triggerEnrichment(context.Background(), "service", -1, assetInputItem{URL: "https://example.com/"})
if len(enr.resolved) != 0 || len(enr.probed) != 0 {
t.Fatalf("triggered without a persisted asset id: resolved %v probed %v", enr.resolved, enr.probed)
}
}
+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
}
+31 -1
View File
@@ -133,6 +133,33 @@ func insertAssetsRuleLoadFailure(err error) (actool.Result, bool) {
return actool.Errorf("asset intercept rules are unavailable; insertion refused"), true
}
// triggerEnrichment hands one freshly inserted asset to the async enrichment
// engine: a domain gets a DNS resolve, an HTTP service gets a probe. Only the
// types the engine can act on are triggered — an IP, app, endpoint or non-HTTP
// service has nothing to resolve or probe on its own.
//
// The trigger is best-effort by design: the engine dedups by cooldown, drops the
// job when its queue is full, resolves DNS ungated and gates the HTTP probe on
// the target scope carried by ctx (a probe without a scope dials nothing). A nil
// engine — no manager, or a tool set built outside a worker run — is a no-op.
func (t *ToolSet) triggerEnrichment(ctx context.Context, typ string, id int64, item assetInputItem) {
if t.enrich == nil || id <= 0 {
return
}
switch typ {
case "root_domain", "subdomain":
if host := strings.TrimSpace(item.Domain); host != "" {
t.enrich.ResolveDomain(id, host)
}
case "service":
// Only the HTTP branch (url set) has something to probe; a non-HTTP
// service carries no URL, so the empty check covers both.
if raw := strings.TrimSpace(item.URL); raw != "" {
t.enrich.ProbeSite(ctx, id, raw)
}
}
}
// insertAssets is the unified insert_assets agent tool.
func (t *ToolSet) insertAssets() actool.CoreTool {
return writeTool(
@@ -216,7 +243,7 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
}, "type"),
},
}, "assets"),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
if t.as == nil {
return actool.Errorf("insert_assets is not enabled: AssetStore is not initialized"), nil
}
@@ -364,6 +391,9 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
results = append(results, result{Index: i, ID: id, Type: typ})
t.writes.Assets++
t.anchorOwner(id)
// Auto-completion is triggered only for an asset that was actually
// written: a gated or failed item must not be resolved or probed.
t.triggerEnrichment(ctx, typ, id, item)
if taskID > 0 {
var sourceNodeID *int64
if t.ownerNode > 0 {
+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++
+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")
}
}
+8
View File
@@ -275,6 +275,11 @@ func trimErr(err error) string {
// estimateTokens roughly sizes a request so members whose context window clearly
// can't hold it are skipped. Deliberately crude (~3.5 chars/token) and biased to
// over-estimate slightly; it only needs to tell "fits" from "nowhere near".
//
// The response budget counts as part of the request: a provider rejects a call
// whose prompt plus max_tokens exceeds the window, and shouldFailover never
// retries a 400, so a member that can hold only the prompt is a member that
// fails the whole call.
func estimateTokens(req llm.CompletionRequest) int {
n := 0
for _, s := range req.System {
@@ -288,6 +293,9 @@ func estimateTokens(req llm.CompletionRequest) int {
// cheaply — charge a flat ~120 chars per top-level property instead.
n += len(t.Name) + len(t.Description) + len(t.InputSchema)*120
}
if req.MaxTokens > 0 {
n += req.MaxTokens * 7 / 2 // max_tokens is in tokens; n accumulates chars
}
return n * 2 / 7 // ≈ len/3.5
}
+30
View File
@@ -382,3 +382,33 @@ func TestTrimErrKeepsValidUTF8(t *testing.T) {
t.Fatalf("trimErr = %q (%d bytes), want at most 300 bytes plus …", got, len(got))
}
}
// The window filter must charge the response budget as well as the prompt. A
// profile whose window cannot hold prompt + max_tokens rejects the call with a
// 400, and shouldFailover never retries a 400, so the request would fail
// outright instead of moving to the profile that can hold it.
func TestWindowFilterChargesMaxTokens(t *testing.T) {
small, big := okProv("small", "s"), okProv("big", "b")
ms := member(1, "small", 10, small)
ms.WindowTokens = 20_000
mb := member(2, "big", 5, big)
mb.WindowTokens = 1_000_000
p := New([]*Member{ms, mb}, NewRegistry(nil, nil))
// ~16K prompt tokens (56K chars at the estimator's ~3.5 chars/token) plus an
// 8K response cap is 24K, which no 20K window can hold.
req := llm.CompletionRequest{
Messages: []llm.Message{llm.UserText(strings.Repeat("x", 56_000))},
MaxTokens: 8192,
}
got, err := drain(p.Stream(context.Background(), req))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "b" {
t.Fatalf("text=%q, want the large-window member to serve it", got)
}
if small.calls != 0 {
t.Fatalf("sent a request whose prompt+max_tokens cannot fit the window (calls=%d)", small.calls)
}
}
File diff suppressed because it is too large Load Diff
+23
View File
@@ -401,6 +401,29 @@ class BenchV2R2AndR5Tests(unittest.TestCase):
self.assertEqual(len(scores["detection_rate_wilson95"]), 2)
self.assertEqual(len(scores["precision_wilson95"]), 2)
def test_r2_reads_real_traffic_exchange_payload(self):
"""The verifier must work on what GET /api/traffic/exchange actually
returns: the raw bodies plus the exchange id and capture time. A payload
without them (the endpoint before it reported identity) is unusable, so
the producer and this consumer have to stay in sync."""
def exchange(ts=None):
body = {"req": "GET /rest/user/login HTTP/1.1\n", "resp": "HTTP/1.1 200 OK\n",
"stream_count": 0, "stream_kind": ""}
if ts is not None:
body["id"] = "1700001200-0001"
body["ts"] = ts
return body
findings = [
{"id": 1, "name": "Payload names its capture", "traffic_refs": ["1700001200-0001"]},
{"id": 2, "name": "Bodies only", "traffic_refs": ["1700001200-0002"]},
]
store = {"1700001200-0001": exchange(1700001200), "1700001200-0002": exchange()}
tv = run_bench.verify_finding_traffic_refs(findings, store.get, self.window_start, self.window_end)
self.assertEqual(tv["verified_keys"], {(int, 1)})
self.assertEqual(tv["verified_refs"][1]["timestamp"], 1700001200)
self.assertEqual(tv["rejected"][2], "traffic_ref_missing_timestamp")
def test_r2_parses_iso8601_and_millisecond_timestamps(self):
findings = [
{"id": "f-iso", "name": "ISO ts", "traffic_refs": [{"traffic_id": "ex-iso"}]},
+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)
}
}
+10 -1
View File
@@ -3808,7 +3808,16 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Printf("[traffic] stream info for %s: %v", id, err)
}
writeJSON(w, 200, map[string]any{"req": req, "resp": resp, "stream_count": count, "stream_kind": kind})
// The bodies alone do not say which exchange they belong to or when it was
// captured; the benchmark's R2 check needs both to credit a finding that
// references this exchange.
out := map[string]any{"req": req, "resp": resp, "stream_count": count, "stream_kind": kind}
if meta, merr := tr.Meta(id); merr == nil {
out["id"], out["ts"] = meta.ID, meta.TS
} else {
log.Printf("[traffic] metadata for %s: %v", id, merr)
}
writeJSON(w, 200, out)
}
// getTrafficStream returns one page of a WebSocket/SSE exchange's messages in
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"encoding/json"
"testing"
)
// TestTrafficExchangeCarriesIdentity pins the contract the bench-v2 R2 check
// reads: GET /api/traffic/exchange must name the exchange it returned and when
// it was captured. scripts/benchmark/run_bench.py credits a finding only when a
// referenced traffic_ref exists in the capture store with a timestamp inside the
// run window; with the bodies alone the timestamp lookup finds nothing and every
// verified finding is rejected as "traffic_ref_missing_timestamp".
func TestTrafficExchangeCarriesIdentity(t *testing.T) {
s, request := ingestServer(t)
db := s.m.Traffic().DB()
const ts = 1700001200
if _, err := db.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES('1700001200-0001',?,'api.example.com','GET','/login','http://api.example.com/login',200,'text/html',0,0,'')`, ts); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head) VALUES('1700001200-0001','GET /login HTTP/1.1\n','HTTP/1.1 200 OK\n')`); err != nil {
t.Fatal(err)
}
w := request("GET", "/api/traffic/exchange?id=1700001200-0001", "")
if w.Code != 200 {
t.Fatalf("GET exchange = %d %s", w.Code, w.Body)
}
var got struct {
ID string `json:"id"`
TS int64 `json:"ts"`
Req string `json:"req"`
Resp string `json:"resp"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode %s: %v", w.Body, err)
}
if got.ID != "1700001200-0001" {
t.Fatalf("id = %q, want the requested exchange id (body %s)", got.ID, w.Body)
}
if got.TS != ts {
t.Fatalf("ts = %d, want the capture time %d (body %s)", got.TS, ts, w.Body)
}
// The bodies stay exactly as before; the identity fields are additive.
if got.Req == "" || got.Resp == "" {
t.Fatalf("bodies missing: req %q resp %q", got.Req, got.Resp)
}
}
// TestTrafficExchangeUnknownID checks the 404 path still reports a missing
// exchange rather than an empty record.
func TestTrafficExchangeUnknownID(t *testing.T) {
_, request := ingestServer(t)
if w := request("GET", "/api/traffic/exchange?id=does-not-exist", ""); w.Code != 404 {
t.Fatalf("unknown exchange = %d %s, want 404", w.Code, w.Body)
}
}
+34
View File
@@ -0,0 +1,34 @@
package traffic
import "testing"
// TestMetaReturnsExchangeIdentity checks Meta reports the same id and capture
// time the exchange was stored under, so callers that only have the bodies can
// still identify the row.
func TestMetaReturnsExchangeIdentity(t *testing.T) {
tr, _ := openTraffic(t)
tr.record(newFlow("api.example.com", "GET", "/login", nil, []byte("ok")))
id := onlyExchangeID(t, tr)
m, err := tr.Meta(id)
if err != nil {
t.Fatalf("Meta(%q): %v", id, err)
}
if m.ID != id {
t.Fatalf("id = %q, want %q", m.ID, id)
}
if m.TS <= 0 {
t.Fatalf("ts = %d, want a positive capture time", m.TS)
}
if m.Host != "api.example.com" || m.Method != "GET" || m.Status != 200 {
t.Fatalf("meta = %+v, want host/method/status of the recorded flow", m)
}
}
// TestMetaUnknownID checks a missing exchange is an error rather than a zero row.
func TestMetaUnknownID(t *testing.T) {
tr, _ := openTraffic(t)
if m, err := tr.Meta("1700000000-9999"); err == nil {
t.Fatalf("Meta of unknown id = %+v, want error", m)
}
}
+14
View File
@@ -1533,6 +1533,20 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
return rows, total, rs.Err()
}
// Meta returns the metadata row of one exchange — its id, capture time, request
// line, status and sizes — without the bodies. Consumers that receive the body
// text from Get still need these fields to identify which exchange they got and
// when it was captured.
func (t *Traffic) Meta(id string) (ExchangeMeta, error) {
var m ExchangeMeta
err := t.db.QueryRow(`SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,`+rewrittenExistsSQL+` FROM exchanges WHERE id=?`, id).
Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.Rewritten)
if err != nil {
return ExchangeMeta{}, err
}
return m, nil
}
// Get returns the full request/response text of one exchange. Bodies come from
// the database; rows recorded before bodies moved into SQLite carry a non-empty
// path and are read from the legacy on-disk tree instead, so history stays
+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
+5
View File
@@ -951,6 +951,11 @@ export interface TrafficResp {
// Full raw request/response of one exchange (lazy-loaded on row select).
export interface TrafficDetail {
// Which exchange these bodies belong to, and when it was captured (Unix
// seconds). The benchmark's R2 check uses them to prove a finding references a
// capture from the run window.
id?: string;
ts?: number;
req: string;
resp: string;
// WebSocket/SSE exchanges carry their messages separately (trafficStream);