mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-25 17:30:56 +08:00
fix(traffic): atomic temp+rename raw TCP blob spill and document SOCKS5 proxy caveats
This commit is contained in:
+1
-1
@@ -23,7 +23,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
- **`ask_operator` target warning**: a request whose question names a host or URL outside the goal targets is tagged as containing target-derived text (#197).
|
||||
- **Opt-in update banner**: `ARTEX_UPDATE_CHECK` makes the backend check the latest GitHub release at most once per 24 hours and the UI show a banner; off by default (#202).
|
||||
- **Release provenance**: release archives carry GitHub build provenance attestations and a CycloneDX SBOM (`gh attestation verify <zip> --repo BaaRai/ARTEX`); release notes are the matching `CHANGELOG.md` section (#219, #201).
|
||||
- **Opt-in SOCKS5 inbound proxy & raw TCP recording (P4.1a)**: setting `ARTEX_SOCKS5_ENABLED=1` (loopback `127.0.0.1:1080` by default) or `ARTEX_SOCKS5_ADDR=<addr>` starts an RFC 1928 SOCKS5 `CONNECT` listener alongside the HTTP recording proxy (off by default; HTTP proxy and agent proxy env vars are unchanged). Accepts loopback no-auth and RFC 1929 username/password (without requiring credentials, carrying `artex-pace` in the username), rejects `BIND`/`UDP ASSOCIATE` with `0x07`, enforces the existing target gate (`intercept.Interceptor.DialSOCKS5` / `intercept.PinnedDialer`) and egress governor (`egress.Do`) before dialing, relays half-close-aware TCP with concurrency/byte/idle/handshake bounds, and records one row per connection in SQLite `raw_tcp_streams` with capped directional previews and `_blobs` refs without writing HTTP `exchanges` rows. See `docs/traffic-socks5.md`.
|
||||
- **Opt-in SOCKS5 inbound proxy & raw TCP recording (P4.1a)**: when traffic capture is enabled, setting `ARTEX_SOCKS5_ENABLED=1` (loopback `127.0.0.1:1080` by default) or `ARTEX_SOCKS5_ADDR=<addr>` starts an RFC 1928 SOCKS5 `CONNECT` listener alongside the HTTP recording proxy (off by default; HTTP proxy and agent proxy env vars are unchanged; listener does not start if traffic recording is disabled). Accepts loopback no-auth and RFC 1929 username/password without verifying credentials (carrying `artex-pace` in the username; binding to a non-loopback address therefore exposes an unauthenticated proxy, though the target gate and governor still apply), rejects `BIND`/`UDP ASSOCIATE` with `0x07`, enforces the existing target gate (`intercept.Interceptor.DialSOCKS5` / `intercept.PinnedDialer`) and egress governor (`egress.Do`) before dialing, relays half-close-aware TCP with concurrency/byte/idle/handshake bounds, and records one row per connection in SQLite `raw_tcp_streams` with capped directional previews and atomic (temp+rename) `_blobs` refs without writing HTTP `exchanges` rows. See `docs/traffic-socks5.md`.
|
||||
- **Opt-in worker cache-prefix split (P3.5 Phase C)**: setting `ARTEX_CACHE_PREFIX=1` (off by default) splits the `worker` system prompt at `DynamicBoundary = 1` into a sibling-shareable static prefix (`body + untrustedContentTail + workerTrafficBlock`) and a per-intent dynamic suffix (`workerArtifactSpec(runDir)` through `<available-deferred-tools>`) without reordering sections or altering the visible joined prompt text. Planner, mainagent, chat, and goals are unchanged; custom worker prompts referencing `{{.Now}}` remain volatile in the static segment. See `docs/context-telemetry.md`.
|
||||
- **Opt-in LLM context size telemetry (P3.5 Phase A)**: setting `ARTEX_CONTEXT_TELEMETRY=1` (off by default) records per-call request section byte sizes (`system_static`/`system_dynamic` split at `DynamicBoundary`, serialized `tools`, `messages` by role, `tool_result` subset, and `last_message_bytes`), tool/message counts, and token/cache usage in the new `llm_context` table (migration `0009_llm_context.sql`), with zero prompt/behavior change and zero content stored, independent of `llm_record`. `GET /api/llm/context/summary` aggregates input percentiles (`p50`/`p90`/`p99`), pro-rata section shares over real `input_tokens`, `cache_read/input` ratios by `(worker, model)`, and top tasks. See `docs/context-telemetry.md`.
|
||||
- **HAR 1.2 traffic import and export**: `POST /api/traffic/import/har` imports raw HAR 1.2 JSON captures (up to 32 MiB / 2,000 entries / 32 MiB decoded bodies) with deterministic `har-<sha256>` IDs (and `_artexExchangeId` preservation for ARTEX exports so distinct same-second exchanges round-trip without collapsing), base64 decoding, `postData.params` and `cookies` array fallbacks, URL userinfo stripping, blob spilling above 256 KiB, and full-text indexing, without applying capture rewrite rules (`exchange_rewrites` stays empty); per-entry errors are reported alongside `imported`/`skipped`/`failed` counts. `GET /api/traffic/export/har` exports filtered traffic (reusing the `GET /api/traffic` filters) as a compliant HAR 1.2 document (with explicit unknown placeholders for unrecorded timings and header sizes) in stable `(ts, id)` order, encoding UTF-8 bodies as text and binary bodies as base64, capped at 1,000 entries / 20 MiB raw headers+bodies (31 MiB JSON backstop, guaranteed under the 32 MiB import limit) with explicit truncation reporting via `X-ARTEX-HAR-*` headers and `_truncated`/`_truncatedReason`/`_totalMatched` fields. The Traffic page adds **Import HAR** and **Export HAR** controls. See `docs/traffic-har.md`.
|
||||
|
||||
@@ -10,7 +10,9 @@ ARTEX ships an opt-in **RFC 1928 SOCKS5 `CONNECT`** inbound listener in `traffic
|
||||
| `ARTEX_SOCKS5_ADDR` | `127.0.0.1:1080` | Explicit TCP bind address; setting a non-empty value also enables the listener unless `ARTEX_SOCKS5_ENABLED` is explicitly false. |
|
||||
|
||||
- **Flag off**: no SOCKS5 listener is started and the HTTP MITM recording proxy is byte-identical.
|
||||
- **Requires traffic recorder**: the server only starts the SOCKS5 listener when the traffic recorder is enabled (inside the traffic proxy block in `server/manager.go`). If traffic capture is disabled, setting `ARTEX_SOCKS5_ENABLED` / `ARTEX_SOCKS5_ADDR` does not open a listener.
|
||||
- **Agents unchanged**: workers and tools keep `HTTP_PROXY`, `HTTPS_PROXY`, and `ALL_PROXY` pointing to the existing HTTP proxy; ARTEX does not silently switch agents to SOCKS5.
|
||||
- **Non-loopback bind warning**: RFC 1929 username/password (`0x02`) accepts **any** username and password without verifying credentials (so the pace marker `artex-pace` can ride in the username). Binding `ARTEX_SOCKS5_ADDR` to a non-loopback address therefore exposes an **unauthenticated proxy** to anyone who can reach that port. The target gate and egress governor still apply to every connection, but keep the listener on loopback (`127.0.0.1`) or restrict access at the host firewall.
|
||||
|
||||
## Protocol Scope (P4.1a)
|
||||
|
||||
@@ -36,7 +38,7 @@ Each completed relayed connection writes one row to the `raw_tcp_streams` table
|
||||
- **No HTTP exchange row**: raw TCP streams never insert into `exchanges`.
|
||||
- **Preview & blob spilling**:
|
||||
- Directional payloads up to `PreviewBytes` (default `8 KiB`) stay inline in `c2s_preview` / `s2c_preview`.
|
||||
- Payloads above `PreviewBytes` keep the leading `PreviewBytes` inline and spill the captured bytes (up to `MaxBytesPerDir`) into `_blobs/sha256/` with references registered in `blob_refs` under the stream's `tcp-*` ID.
|
||||
- Payloads above `PreviewBytes` keep the leading `PreviewBytes` inline and spill the captured bytes (up to `MaxBytesPerDir`) atomically (temp file + rename) into `_blobs/sha256/` with references registered in `blob_refs` under the stream's `tcp-*` ID.
|
||||
- Exceeding `MaxBytesPerDir` sets `truncated = 1` while continuing to count exact total relayed `c2s_bytes` / `s2c_bytes`.
|
||||
|
||||
## Operational Bounds
|
||||
|
||||
+40
-1
@@ -69,7 +69,7 @@ func (t *Traffic) spillRawDir(data []byte, previewCap int) (preview []byte, blob
|
||||
}
|
||||
blobPath := filepath.Join(blobDir, h+".bin")
|
||||
if _, err := os.Stat(blobPath); os.IsNotExist(err) {
|
||||
if err := os.WriteFile(blobPath, data, 0o644); err != nil {
|
||||
if err := writeBlobAtomic(blobDir, blobPath, h, data); err != nil {
|
||||
log.Printf("[traffic/socks5] failed to write blob %s: %v", h, err)
|
||||
return append([]byte(nil), data[:previewCap]...), ""
|
||||
}
|
||||
@@ -77,6 +77,45 @@ func (t *Traffic) spillRawDir(data []byte, previewCap int) (preview []byte, blob
|
||||
return append([]byte(nil), data[:previewCap]...), h
|
||||
}
|
||||
|
||||
// writeBlobAtomic writes data to a temporary file inside blobDir and renames it
|
||||
// into place at blobPath so a crash mid-write cannot leave a partial file under
|
||||
// a content-addressed SHA-256 hash.
|
||||
func writeBlobAtomic(blobDir, blobPath, hash string, data []byte) error {
|
||||
tmp, err := os.CreateTemp(blobDir, hash+".*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
cleanup := true
|
||||
defer func() {
|
||||
if cleanup {
|
||||
_ = os.Remove(tmpPath)
|
||||
}
|
||||
}()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(0o644); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmpPath, blobPath); err != nil {
|
||||
// Another goroutine may have won the race writing the same
|
||||
// content-addressed hash (notably on Windows where Rename can fail
|
||||
// if the destination already exists).
|
||||
if _, statErr := os.Stat(blobPath); statErr == nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
cleanup = false
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordRawTCPStream persists one raw TCP connection into raw_tcp_streams and
|
||||
// registers any spilled directional blobs in blob_refs. It never writes to the
|
||||
// HTTP exchanges table.
|
||||
|
||||
@@ -7,8 +7,11 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -841,3 +844,54 @@ func TestSOCKS5ConcurrentStreamsMaxLimitAndIdleTimeout(t *testing.T) {
|
||||
t.Fatalf("want at least 2 recorded concurrent streams, got %d", len(streams))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawTCPAtomicBlobSpillConcurrent(t *testing.T) {
|
||||
tr, err := Open(t.TempDir(), "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tr.Close()
|
||||
payload := bytes.Repeat([]byte("ATOMIC-BLOB-"), 128) // 1536 bytes > 64 preview
|
||||
const workers = 8
|
||||
var wg sync.WaitGroup
|
||||
hashes := make([]string, workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
prev, h := tr.spillRawDir(payload, 64)
|
||||
if len(prev) != 64 {
|
||||
t.Errorf("worker %d preview len = %d, want 64", idx, len(prev))
|
||||
}
|
||||
hashes[idx] = h
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
wantHash := hashes[0]
|
||||
if wantHash == "" {
|
||||
t.Fatal("expected non-empty blob hash")
|
||||
}
|
||||
for i, h := range hashes {
|
||||
if h != wantHash {
|
||||
t.Fatalf("worker %d hash = %q, want %q", i, h, wantHash)
|
||||
}
|
||||
}
|
||||
blobDir := filepath.Join(tr.dir, "_blobs", "sha256", wantHash[:2])
|
||||
entries, err := os.ReadDir(blobDir)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir(%s): %v", blobDir, err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".tmp") {
|
||||
t.Fatalf("leftover temp blob file: %s", e.Name())
|
||||
}
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(blobDir, wantHash+".bin"))
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile blob: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("blob content mismatch: got %d bytes, want %d", len(got), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user