diff --git a/.env.example b/.env.example index cc278d6..6ea6e3c 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,6 @@ # Docker deployment configuration (copy to .env) -# The image is built locally by `docker compose build`; there is no registry tag. +# docker-compose.yml builds the image locally. docker-compose.ghcr.yml pulls the +# released GHCR image; pin it with ARTEX_IMAGE_TAG (latest or a vX.Y.Z tag). # Address the web UI is published on. 127.0.0.1 keeps it host-local; set 0.0.0.0 # to reach it from another machine or from Windows when ARTEX runs inside WSL. ARTEX_BIND_ADDR=127.0.0.1 @@ -16,6 +17,8 @@ POSTGRES_USER=artex # because Compose reads this file that way. POSTGRES_PASSWORD=change-me-please POSTGRES_DB=artex +# Prebuilt GHCR image tag for docker-compose.ghcr.yml. Unset uses latest. +# ARTEX_IMAGE_TAG=latest # LLM (fill one or both; you can also leave empty and configure in the UI) ANTHROPIC_API_KEY= diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6fd8ce5..b0c3f78 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -73,12 +73,12 @@ jobs: with: name: pkg-${{ matrix.goos }}-${{ matrix.goarch }} path: "dist/*.zip" - # Upload raw Linux binaries separately for reuse by the docker job (avoids rebuilding the frontend + Go inside the image) - - if: matrix.goos == 'linux' + # 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 with: - name: bin-linux-${{ matrix.goarch }} - path: dist/artex-linux-${{ matrix.goarch }}/artex + name: bin-linux-amd64 + path: dist/artex-linux-amd64/artex # ③ Collect all zips → create the GitHub Release release: @@ -152,45 +152,52 @@ jobs: generate_release_notes: false body_path: ${{ runner.temp }}/release-body.md - # ④ Multi-arch image → push to Docker Hub (reuses the Linux binaries built by the - # binaries job; the image only installs tools + ships the binary; arm64 only needs - # to emulate the apt layer, so builds are much faster) - # Publishing the image needs Docker Hub credentials and a namespace we own, so the - # job stays skipped unless the repository defines DOCKERHUB_ENABLED (set it to true - # and provide DOCKERHUB_USERNAME / DOCKERHUB_TOKEN secrets plus DOCKERHUB_IMAGE). + # ④ Multi-arch image → push to GitHub Container Registry (and optionally Docker Hub + # when DOCKERHUB_ENABLED is set to 'true' alongside DOCKERHUB_IMAGE and + # DOCKERHUB_USERNAME / DOCKERHUB_TOKEN secrets). Dry runs (workflow_dispatch) + # build both platforms without logging in or pushing. docker: needs: binaries - if: ${{ vars.DOCKERHUB_ENABLED == 'true' && github.event_name == 'push' }} runs-on: ubuntu-latest + permissions: + contents: read + packages: write steps: - - uses: actions/checkout@v4 # fetch the Dockerfile and skills/ - - uses: actions/download-artifact@v4 - with: - name: bin-linux-amd64 - path: dist/amd64 - - uses: actions/download-artifact@v4 - with: - name: bin-linux-arm64 - path: dist/arm64 + - uses: actions/checkout@v4 - uses: docker/setup-qemu-action@v3 - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 + - name: Log in to GitHub Container Registry + if: github.event_name == 'push' + uses: docker/login-action@v3 + 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 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - uses: docker/metadata-action@v5 id: meta with: - images: ${{ vars.DOCKERHUB_IMAGE }} + images: | + ghcr.io/${{ github.repository }} + ${{ vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_IMAGE || '' }} tags: | type=ref,event=tag + type=semver,pattern={{version}} type=raw,value=latest - uses: docker/build-push-action@v6 with: context: . platforms: linux/amd64,linux/arm64 - push: true + push: ${{ github.event_name == 'push' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} + build-args: ARTEX_VERSION=${{ github.ref_name }} + provenance: true + sbom: true cache-from: type=gha cache-to: type=gha,mode=max diff --git a/CHANGELOG.md b/CHANGELOG.md index ed0db96..4e357ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Live log subscribers can no longer crash the process**: a client disconnect closes its log channel. The sink now delivers a line while it still holds the subscriber lock, so that close cannot land in the middle of the send. +- **Notification delivery ignores HTTP_PROXY**: the dial guard checks the address it connects to. An environment proxy made that address the proxy, so a link-local target could still be reached. Notification HTTP now connects directly. +- **Captured traffic blobs are owner-only**: HTTP and raw-stream bodies spilled out of the database are written `0600`, and their bucket directory is `0700`. An existing blob is tightened when it is seen again. +- **Asset URLs drop userinfo when parsing fails**: a URL `url.Parse` rejects is no longer stored unchanged. The `scheme://userinfo@` prefix is removed first, so a password in that prefix does not land in the asset row. +- **Hook `range` counts against the memory budget**: ranging over a body, slice, string, or map charges the iteration before the loop. A body larger than the hook budget now stops with the memory limit instead of allocating one element at a time with no check. +- **Chat upload name search stops**: choosing `name`, `name-1`, `name-2`, … now returns an error when the filesystem rejects the path or after 10000 collisions, instead of looping while `Stat` keeps failing. - **Uploads do not follow a symlink**: chat and workspace uploads `Lstat` the destination and refuse to write when it is already a symlink. A dangling link is no longer treated as a free name. - **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450). diff --git a/README.md b/README.md index 29a466a..a7f5dd2 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,9 @@ printed at startup: docker compose logs artex | grep "Setup token" ``` -> There is no prebuilt Docker image to pull: the image is always built from your checkout. -> For all installation paths (script, binaries, source, release archives), see [Installation](#installation). +> Multi-arch release images (`linux/amd64`, `linux/arm64`) are published to GitHub Container +> Registry at `ghcr.io/baarai/artex`. For pulling the prebuilt image and all other installation +> paths (script, binaries, source, release archives), see [Installation](#installation). --- @@ -331,7 +332,9 @@ The UI listens on `127.0.0.1` by default. To reach it from another machine (or f ARTEX runs inside WSL), set `ARTEX_BIND_ADDR=0.0.0.0` in `.env` (the setup token still protects the first-run claim), or keep loopback and use a reverse proxy or SSH tunnel. -### Option 2: Docker Compose (manual) +### Option 2: Docker (Compose checkout build or prebuilt GHCR image) + +Build from a checkout with Docker Compose: ```bash git clone https://github.com/BaaRai/ARTEX.git @@ -341,12 +344,73 @@ docker compose up -d --build # → http://localhost:8787 ``` -`POSTGRES_PASSWORD` is passed to ARTEX as its own variable. The server percent-encodes it into -the connection URL, so a password may contain `/`, `?`, `%`, `@`, `:` or spaces. In `.env`, quote -a value that contains `#`, and write `$$` for a literal `$`. +Each `v*` release publishes a multi-arch image (`linux/amd64`, `linux/arm64`) to GitHub +Container Registry with tags `:latest`, `:v`, and `:`. GHCR packages start +private. After the first release, maintainers should check that the `artex` package visibility +is set to Public and verify the pull below on a machine without GHCR credentials before +announcing anonymous installation. + +The standalone container requires an existing PostgreSQL database reachable from the container. +Set the `ARTEX_PG_*` variables below. The example uses Docker Desktop's +`host.docker.internal` to reach PostgreSQL on the host. On native Linux Docker Engine, add +`--add-host=host.docker.internal:host-gateway` to `docker run` for a host database, or use +the reachable hostname of your database server. + +```bash +docker pull ghcr.io/baarai/artex:latest + +mkdir -p data keys +docker run -d --name artex \ + --security-opt no-new-privileges:true \ + -p 127.0.0.1:8787:8787 \ + -p 127.0.0.1:8788:8788 \ + -e ARTEX_PG_HOST=host.docker.internal \ + -e ARTEX_PG_PORT=5432 \ + -e ARTEX_PG_USER=artex \ + -e ARTEX_PG_PASSWORD='yourpass' \ + -e ARTEX_PG_DBNAME=artex \ + -e ARTEX_PG_SSLMODE=disable \ + -e ARTEX_JWT_KEY_DIR=/app/keys \ + -v "$PWD/data:/app/data" \ + -v "$PWD/keys:/app/keys" \ + ghcr.io/baarai/artex:latest +# → http://localhost:8787 (docker logs artex | grep "Setup token") +``` + +In `docker-compose.yml` and `docker-compose.ghcr.yml`, `POSTGRES_PASSWORD` is passed to ARTEX as +its own variable. The server percent-encodes it into the connection URL, so a password may contain +`/`, `?`, `%`, `@`, `:` or spaces. In `.env`, quote a value that contains `#`, and write `$$` for a +literal `$`. The `ARTEX_PG_*` variables take the password raw; quote it in a shell. The image includes a scanner toolchain (`nmap`, `nuclei`, `httpx`, `katana`, `ffuf`, `dalfox`, -`sqlmap`, `ripgrep`, `curl`, `npm`, …); `./skills` and `./data` are persisted via bind mounts. +`sqlmap`, `ripgrep`, `curl`, `npm`, …) and built-in `/app/skills`. The GHCR Compose file below +persists `./keys` and `./data`; it does not mount a host `skills/` directory, so the image's +built-in skills are used. + +#### Compose stack from the prebuilt image + +`docker-compose.ghcr.yml` runs the same ARTEX + PostgreSQL stack from the released image, with no +checkout build. Download it and `.env.example` once: + +```bash +curl -fsSLO https://raw.githubusercontent.com/BaaRai/ARTEX/main/docker-compose.ghcr.yml +curl -fsSLO https://raw.githubusercontent.com/BaaRai/ARTEX/main/.env.example +cp .env.example .env # set POSTGRES_PASSWORD, optionally an LLM key +docker compose -f docker-compose.ghcr.yml pull +docker compose -f docker-compose.ghcr.yml up -d +# → http://localhost:8787 (docker compose -f docker-compose.ghcr.yml logs artex | grep "Setup token") +``` + +Update the stack without a git checkout: + +```bash +docker compose -f docker-compose.ghcr.yml pull +docker compose -f docker-compose.ghcr.yml up -d +``` + +Pin a version with `ARTEX_IMAGE_TAG=v0.7.1` in `.env` (or `0.7.1`); unset uses `latest`. To use +custom skills, copy them into a host directory and add `- ./skills:/app/skills` to the `artex` +volumes, which overrides the built-in `/app/skills`. For remote MCP you can choose `http` (Streamable HTTP) or `sse` (legacy SSE) in system settings. Legacy SSE servers usually establish the event stream with `GET /sse` and receive JSON-RPC over @@ -647,7 +711,7 @@ The script optionally `git pull`s, then offers **① Docker update** (`docker co `docker compose up -d artex`) or **② local build update** (rebuild the frontend static assets, then recompile `./artex`; restart the process for it to take effect). -#### Option 2: Docker Compose (manual) +#### Option 2: Docker (Compose or GHCR image) ```bash cd ARTEX @@ -657,6 +721,15 @@ docker compose up -d artex docker image prune -f # optional ``` +If running the prebuilt `ghcr.io/baarai/artex` container directly, pull the new tag (`docker pull +ghcr.io/baarai/artex:latest` or a pinned `:v`) and recreate the container with the same +`/app/data` and `/app/keys` mounts. If you run the prebuilt Compose stack, the update is: + +```bash +docker compose -f docker-compose.ghcr.yml pull +docker compose -f docker-compose.ghcr.yml up -d +``` + #### Option 3: prebuilt binaries Download the new zip, stop the old process, overwrite `artex` and `skills/` (keep `config.json` and diff --git a/agent/finding_recorder.go b/agent/finding_recorder.go index eed68d2..f5368f1 100644 --- a/agent/finding_recorder.go +++ b/agent/finding_recorder.go @@ -20,10 +20,6 @@ type TrafficCaptureChecker interface { TrafficExists(ctx context.Context, trafficID string) (bool, error) } -// Tool-use guidance is appended without replacing the user's editable prompt. -// It does not require capture or claim that unavailable traffic tools exist. -const findingTrafficGuidance = "\n\n**Vulnerability traffic evidence**: when reporting a vulnerability via report_finding, bind real HTTP request/response IDs via traffic_refs in reproduction order; domains and times are only candidate filters and do not imply association. A finding without bound traffic stays recorded and visible, but cannot close a goal via prove_goal until verified traffic matching its asset host is bound (via report_finding or bind_finding_traffic). For TCP and other non-HTTP vulnerabilities, when nothing was captured, or when there is no exact match, omit traffic_refs or pass [], keep verifiable command output and logs in evidence, and close non-HTTP goals with an observed tool_output fact. Do not guess IDs, and do not re-probe just to capture packets." - func (t *ToolSet) SetFindingRecorder(r FindingRecorder) { t.findingRecorder = r } func (w *Worker) SetFindingRecorder(r FindingRecorder) { w.findingRecorder = r } func (p *Planner) SetFindingRecorder(r FindingRecorder) { p.findingRecorder = r } diff --git a/agent/finding_recorder_source_test.go b/agent/finding_recorder_source_test.go new file mode 100644 index 0000000..71ab6d9 --- /dev/null +++ b/agent/finding_recorder_source_test.go @@ -0,0 +1,26 @@ +package agent + +import ( + "go/ast" + "go/parser" + "go/token" + "testing" +) + +func TestFindingRecorderHasNoLegacyTrafficGuidance(t *testing.T) { + // Check the declaration directly: an unused constant cannot affect prompt output. + f, err := parser.ParseFile(token.NewFileSet(), "finding_recorder.go", nil, parser.SkipObjectResolution) + if err != nil { + t.Fatal(err) + } + ast.Inspect(f, func(n ast.Node) bool { + if spec, ok := n.(*ast.ValueSpec); ok { + for _, name := range spec.Names { + if name.Name == "findingTrafficGuidance" { + t.Fatal("finding_recorder.go declares the obsolete findingTrafficGuidance constant") + } + } + } + return true + }) +} diff --git a/agent/tools.go b/agent/tools.go index d901135..5d35cbb 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -1692,7 +1692,9 @@ func factEvidenceLines(evidence string) []string { } } return out -} // factProvenance classifies one fact against the intent's recorded activity. +} + +// factProvenance classifies one fact against the intent's recorded activity. // Beyond the activity tie it checks whether the quoted bytes were captured // coming back from the target through the proxy, in which case the target // authored them and the fact is classified target_response even when the model diff --git a/db/assets.go b/db/assets.go index 7cb2d25..899cee9 100644 --- a/db/assets.go +++ b/db/assets.go @@ -165,7 +165,7 @@ func calcCSegment(ipStr string) string { func normalizeURL(raw string) string { u, err := url.Parse(raw) if err != nil { - return raw + return stripURLUserinfo(raw) } u.Scheme = strings.ToLower(u.Scheme) u.Host = strings.ToLower(u.Host) @@ -177,6 +177,25 @@ func normalizeURL(raw string) string { return s } +// stripURLUserinfo removes scheme://userinfo@ when url.Parse cannot. The +// userinfo is the span before the last @ that still sits in the authority. +func stripURLUserinfo(raw string) string { + i := strings.Index(raw, "://") + if i < 0 { + return raw + } + rest := raw[i+3:] + authEnd := len(rest) + if j := strings.IndexAny(rest, "/?#"); j >= 0 { + authEnd = j + } + at := strings.LastIndex(rest[:authEnd], "@") + if at < 0 { + return raw + } + return raw[:i+3] + rest[at+1:] +} + // parseURL extracts domain, port, service_name from a URL. func parseURL(raw string) (domain string, port int, serviceName string) { u, err := url.Parse(raw) diff --git a/db/assets_test.go b/db/assets_test.go index ff1d7ef..b216eb3 100644 --- a/db/assets_test.go +++ b/db/assets_test.go @@ -908,6 +908,7 @@ func TestNormalizeURL(t *testing.T) { {"https://user@example.com/", "https://example.com"}, {"https://u:p@example.com:8443/users/@alice?x=1", "https://example.com:8443/users/@alice?x=1"}, {"https://example.com/@me?r=http://a:b@x/", "https://example.com/@me?r=http://a:b@x/"}, + {"http://user:secret@ex ample.com/a", "http://ex ample.com/a"}, } for _, tc := range tests { got := normalizeURL(tc.raw) diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.yml new file mode 100644 index 0000000..e5e7657 --- /dev/null +++ b/docker-compose.ghcr.yml @@ -0,0 +1,79 @@ +# ARTEX from the published GHCR image, with the same PostgreSQL service as +# docker-compose.yml. Use this file to run and update without a git checkout: +# +# docker compose -f docker-compose.ghcr.yml pull +# docker compose -f docker-compose.ghcr.yml up -d +# +# Set POSTGRES_PASSWORD in .env. Pin the image with ARTEX_IMAGE_TAG=v0.7.1 in +# .env; unset uses latest. The image carries the built-in /app/skills; this file +# does not mount a host skills/ directory. To use custom skills, copy them into a +# host directory and add `- ./skills:/app/skills` to the artex volumes. +services: + postgres: + image: postgres:16-alpine + environment: + POSTGRES_USER: ${POSTGRES_USER:-artex} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env} + POSTGRES_DB: ${POSTGRES_DB:-artex} + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-artex} -d ${POSTGRES_DB:-artex}"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + + artex: + image: ghcr.io/baarai/artex:${ARTEX_IMAGE_TAG:-latest} + # Agent processes run as an unprivileged executor (-exec-uid): no setuid program + # or file capability may raise them back to root. + security_opt: + - "no-new-privileges:true" + depends_on: + postgres: + condition: service_healthy + environment: + # Parts, not a pasted URL. PostgresDSN percent-encodes the password, so a + # value with / ? % @ : or a space still connects. + ARTEX_PG_HOST: postgres + ARTEX_PG_PORT: "5432" + ARTEX_PG_USER: ${POSTGRES_USER:-artex} + ARTEX_PG_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env} + ARTEX_PG_DBNAME: ${POSTGRES_DB:-artex} + ARTEX_PG_SSLMODE: disable + ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-} + OPENAI_API_KEY: ${OPENAI_API_KEY:-} + ARTEX_LLM_PROVIDER: ${ARTEX_LLM_PROVIDER:-} + ARTEX_LLM_MODEL: ${ARTEX_LLM_MODEL:-} + ARTEX_LLM_BASE_URL: ${ARTEX_LLM_BASE_URL:-} + ARTEX_LLM_PROXY: ${ARTEX_LLM_PROXY:-} + # Exact host:port list the model-list fetch may reach on private addresses + # (e.g. host.docker.internal:11434 for Ollama). + ARTEX_LLM_PRIVATE_ENDPOINTS: ${ARTEX_LLM_PRIVATE_ENDPOINTS:-} + ARTEX_JWT_KEY_DIR: /app/keys + # Optional: key for secrets at rest; empty = keys/secret.key (generated at + # first start). + ARTEX_SECRET_KEY: ${ARTEX_SECRET_KEY:-} + ARTEX_TRUSTED_PROXIES: ${ARTEX_TRUSTED_PROXIES:-} + # Untrusted-output boundary: on by default (empty = on); set 0 to disable. + ARTEX_UNTRUSTED_BOUNDARY: ${ARTEX_UNTRUSTED_BOUNDARY:-} + ARTEX_UPDATE_CHECK: ${ARTEX_UPDATE_CHECK:-} + # Noise profile for target requests: off (default) | quiet | balanced | aggressive. + ARTEX_NOISE_PROFILE: ${ARTEX_NOISE_PROFILE:-} + ARTEX_TARGET_USER_AGENT: ${ARTEX_TARGET_USER_AGENT:-} + # Hierarchical run budgets: unset or 0 = unlimited. See README. + ARTEX_TASK_BUDGET_TOKENS: ${ARTEX_TASK_BUDGET_TOKENS:-} + ARTEX_TASK_BUDGET_TURNS: ${ARTEX_TASK_BUDGET_TURNS:-} + ARTEX_INTENT_BUDGET_TOKENS: ${ARTEX_INTENT_BUDGET_TOKENS:-} + ARTEX_INTENT_BUDGET_TURNS: ${ARTEX_INTENT_BUDGET_TURNS:-} + ports: + - "${ARTEX_BIND_ADDR:-127.0.0.1}:8787:8787" + - "127.0.0.1:8788:8788" + volumes: + - ./data:/app/data + - ./keys:/app/keys + restart: unless-stopped + +volumes: + pgdata: diff --git a/notify/http.go b/notify/http.go index 386ac93..8188af6 100644 --- a/notify/http.go +++ b/notify/http.go @@ -104,6 +104,10 @@ var notifyTransport = func() *http.Transport { return &http.Transport{} } clone := t.Clone() + // Clone keeps ProxyFromEnvironment. The dial would then be to the proxy, so + // blockInternalDial would see the proxy address and a link-local target + // could still be reached through it. Notifications go direct. + clone.Proxy = nil clone.DialContext = (&net.Dialer{Timeout: 10 * time.Second, Control: blockInternalDial}).DialContext return clone }() diff --git a/notify/transport_test.go b/notify/transport_test.go new file mode 100644 index 0000000..e85473b --- /dev/null +++ b/notify/transport_test.go @@ -0,0 +1,9 @@ +package notify + +import "testing" + +func TestNotifyTransportIgnoresEnvironmentProxy(t *testing.T) { + if notifyTransport.Proxy != nil { + t.Fatal("notification transport must dial the target, not an environment proxy") + } +} diff --git a/server/chatupload.go b/server/chatupload.go index de9edea..e2cc5ba 100644 --- a/server/chatupload.go +++ b/server/chatupload.go @@ -21,6 +21,10 @@ const ( // Allow multipart headers and boundaries in addition to the file data. chatUploadMultipartOverhead = 1 << 20 // 1 MiB chatUploadLimitMessage = "files exceed the 512 MiB upload limit" + // maxUploadNameTries bounds the name-1, name-2, … search. A Stat error that + // is not "not exist" (a component the filesystem rejects) must stop the + // search instead of spinning. + maxUploadNameTries = 10000 ) // safeChatID guards the {id} path segment against traversal — task ids are numeric, @@ -123,7 +127,11 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) { if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) { continue } - dest := uniqueUploadPath(dir, name) + dest, err := uniqueUploadPath(dir, name) + if err != nil { + writeErr(w, 500, "Save failed: "+err.Error()) + return + } if err := saveUpload(hdr, dest); err != nil { writeErr(w, 500, "Save failed: "+err.Error()) return @@ -136,19 +144,34 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) { // uniqueUploadPath returns dir/name, or dir/name-1, dir/name-2… when it already exists, // so re-uploading the same filename never clobbers a prior attachment. -func uniqueUploadPath(dir, name string) string { - dest := filepath.Join(dir, name) - if _, err := os.Lstat(dest); os.IsNotExist(err) { - return dest +func uniqueUploadPath(dir, name string) (string, error) { + if dest, ok, err := uploadPathFree(filepath.Join(dir, name)); err != nil || ok { + return dest, err } ext := filepath.Ext(name) stem := strings.TrimSuffix(name, ext) - for i := 1; ; i++ { + for i := 1; i <= maxUploadNameTries; i++ { cand := filepath.Join(dir, fmt.Sprintf("%s-%d%s", stem, i, ext)) - if _, err := os.Lstat(cand); os.IsNotExist(err) { - return cand + dest, ok, err := uploadPathFree(cand) + if err != nil || ok { + return dest, err } } + return "", fmt.Errorf("no free name for upload %q", name) +} + +// uploadPathFree reports whether path can be created. ok is false when a file +// or a symlink (including a dangling one) is already there. Any other Lstat +// error is returned so the caller stops. +func uploadPathFree(path string) (dest string, ok bool, err error) { + _, err = os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return path, true, nil + } + if err != nil { + return "", false, err + } + return "", false, nil } // composeAgentMessage appends an attachment manifest to the user's message so the agent diff --git a/server/chatupload_name_test.go b/server/chatupload_name_test.go new file mode 100644 index 0000000..5fb91e8 --- /dev/null +++ b/server/chatupload_name_test.go @@ -0,0 +1,33 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestUniqueUploadPathSuffixesCollisions(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "note.txt"), []byte("a"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "note-1.txt"), []byte("b"), 0o644); err != nil { + t.Fatal(err) + } + got, err := uniqueUploadPath(dir, "note.txt") + if err != nil { + t.Fatal(err) + } + if filepath.Base(got) != "note-2.txt" { + t.Fatalf("got %s", got) + } +} + +func TestUniqueUploadPathStopsOnUnstorableName(t *testing.T) { + dir := t.TempDir() + name := strings.Repeat("a", 300) + ".txt" + if _, err := uniqueUploadPath(dir, name); err == nil { + t.Fatal("an overlong file name must not be searched forever") + } +} diff --git a/server/logsink.go b/server/logsink.go index cff3c68..36fac4b 100644 --- a/server/logsink.go +++ b/server/logsink.go @@ -152,9 +152,15 @@ func (s *logSinkT) add(l LogLine) { s.ring = s.ring[len(s.ring)-s.cap:] } ch := s.dbCh - subs := make([]chan LogLine, 0, len(s.subs)) + // Fan-out stays under the lock. subscribe's cancel removes the channel and + // then closes it; a send on a closed channel panics even inside select, so + // the send and the close must not interleave. The send does not block: a + // full buffer drops the line. for sub := range s.subs { - subs = append(subs, sub) + select { + case sub <- l: + default: + } } s.mu.Unlock() @@ -165,13 +171,6 @@ func (s *logSinkT) add(l LogLine) { default: } } - - for _, sub := range subs { - select { - case sub <- l: - default: - } - } } // recent returns ring lines with Seq > since (capped to limit), and the latest seq. diff --git a/server/logsink_test.go b/server/logsink_test.go new file mode 100644 index 0000000..182098b --- /dev/null +++ b/server/logsink_test.go @@ -0,0 +1,23 @@ +package server + +import ( + "io" + "sync" + "testing" +) + +func TestLogSinkUnsubscribeDuringAddDoesNotPanic(t *testing.T) { + s := &logSinkT{cap: 8, subs: map[chan LogLine]struct{}{}, out: io.Discard} + var wg sync.WaitGroup + for i := 0; i < 32; i++ { + _, unsub := s.subscribe() + wg.Add(1) + go func() { + defer wg.Done() + unsub() + }() + s.add(LogLine{Text: "line"}) + } + wg.Wait() + s.add(LogLine{Text: "after"}) +} diff --git a/traffic/blob_perm_test.go b/traffic/blob_perm_test.go new file mode 100644 index 0000000..4fc5a78 --- /dev/null +++ b/traffic/blob_perm_test.go @@ -0,0 +1,38 @@ +package traffic + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestSpillBlobIsOwnerOnly(t *testing.T) { + dir := t.TempDir() + tr := &Traffic{dir: dir} + body := bytes.Repeat([]byte("a"), maxInlineBody+1) + got := tr.spill(body, "text/plain") + if got.hash == "" { + t.Fatal("expected a spilled blob") + } + blobDir := filepath.Join(dir, "_blobs", "sha256", got.hash[:2]) + blobPath := filepath.Join(blobDir, got.hash+".bin") + info, err := os.Stat(blobPath) + if err != nil { + t.Fatal(err) + } + dirInfo, err := os.Stat(blobDir) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS == "windows" { + return + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("blob mode %o, want 0600", info.Mode().Perm()) + } + if dirInfo.Mode().Perm() != 0o700 { + t.Fatalf("blob dir mode %o, want 0700", dirInfo.Mode().Perm()) + } +} diff --git a/traffic/hookvm/eval.go b/traffic/hookvm/eval.go index d96d56e..f4b22de 100644 --- a/traffic/hookvm/eval.go +++ b/traffic/hookvm/eval.go @@ -330,24 +330,30 @@ func (e *vm) execRange(s *ast.RangeStmt, sc *env) (flowSignal, any) { var items []kvPair switch x := e.eval(s.X, sc).(type) { case []byte: + e.alloc(int64(len(x)) * 16) for i, v := range x { items = append(items, kvPair{int64(i), int64(v)}) } case []any: + e.alloc(int64(len(x)) * 16) for i, v := range x { items = append(items, kvPair{int64(i), v}) } case []string: + e.alloc(int64(len(x)) * 16) for i, v := range x { items = append(items, kvPair{int64(i), v}) } case string: + e.alloc(int64(len(x)) * 16) for i, r := range x { items = append(items, kvPair{int64(i), int64(r)}) } case map[string]any: + e.alloc(int64(len(x)) * 16) items = sortedMapPairs(x) case map[string][]string: + e.alloc(int64(len(x)) * 16) items = sortedMapPairs(x) case nil: return flowNone, nil diff --git a/traffic/hookvm/vm_test.go b/traffic/hookvm/vm_test.go index 11f2113..6527774 100644 --- a/traffic/hookvm/vm_test.go +++ b/traffic/hookvm/vm_test.go @@ -204,6 +204,25 @@ func OnResponse(req *Request, resp *Response) error { } func TestResourceBoundsMemoryStepTimeoutPanicAndRegexp(t *testing.T) { + t.Run("range_over_body_stopped_by_memory_budget", func(t *testing.T) { + src := `package hook +func OnRequest(req *Request) error { + for _, b := range req.Body { + _ = b + } + return nil +}` + prog, err := Compile("request", src) + if err != nil { + t.Fatal(err) + } + body := make([]byte, 256<<10) + err = prog.RunRequest(context.Background(), &Request{Body: body}, RunOptions{MaxMemory: 64 << 10}) + if !errors.Is(err, ErrMemoryLimit) { + t.Fatalf("err = %v, want ErrMemoryLimit", err) + } + }) + t.Run("make_100MiB_stopped_by_memory_budget", func(t *testing.T) { src := `package hook func OnRequest(req *Request) error { diff --git a/traffic/raw_tcp.go b/traffic/raw_tcp.go index 5bb7a74..ace0167 100644 --- a/traffic/raw_tcp.go +++ b/traffic/raw_tcp.go @@ -63,7 +63,7 @@ func (t *Traffic) spillRawDir(data []byte, previewCap int) (preview []byte, blob sum := sha256.Sum256(data) h := hex.EncodeToString(sum[:]) blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2]) - if err := os.MkdirAll(blobDir, 0o755); err != nil { + if err := os.MkdirAll(blobDir, 0o700); err != nil { log.Printf("[traffic/socks5] failed to create blob directory: %v", err) return append([]byte(nil), data[:previewCap]...), "" } @@ -96,7 +96,7 @@ func writeBlobAtomic(blobDir, blobPath, hash string, data []byte) error { _ = tmp.Close() return err } - if err := tmp.Chmod(0o644); err != nil { + if err := tmp.Chmod(0o600); err != nil { _ = tmp.Close() return err } diff --git a/traffic/traffic.go b/traffic/traffic.go index 8eba165..8b3ae51 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -873,16 +873,21 @@ func (t *Traffic) spillAt(body []byte, contentType string, maxInline int) stored // One bucket level (256 buckets) is enough to keep any single directory small; // the store only ever holds bodies above maxInlineBody, deduplicated by hash. blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2]) - if err := os.MkdirAll(blobDir, 0o755); err != nil { + if err := os.MkdirAll(blobDir, 0o700); err != nil { log.Printf("[traffic] failed to create blob directory: %v", err) return storedBody{inline: clipBytes(body, blobPreview), index: indexText()} } + if err := os.Chmod(blobDir, 0o700); err != nil { + log.Printf("[traffic] failed to restrict blob directory: %v", err) + } blobPath := filepath.Join(blobDir, h+".bin") if _, err := os.Stat(blobPath); os.IsNotExist(err) { - if err := os.WriteFile(blobPath, body, 0o644); err != nil { + if err := os.WriteFile(blobPath, body, 0o600); err != nil { log.Printf("[traffic] failed to write blob %s: %v", h, err) return storedBody{inline: clipBytes(body, blobPreview), index: indexText()} } + } else if err := os.Chmod(blobPath, 0o600); err != nil { + log.Printf("[traffic] failed to restrict blob %s: %v", h, err) } sb := storedBody{hash: h, index: indexText()} if text {