diff --git a/.env.example b/.env.example index e7d31dc..539f280 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,8 @@ # 本仓库发布的 Docker Hub 镜像地址;参见 README 的部署说明。 ARTEX_IMAGE=ruoji6/artex ARTEX_TAG=latest +# 全流量透明代理网关镜像 +ARTEX_GATEWAY_IMAGE=ruoji6/artex-gateway POSTGRES_USER=artex POSTGRES_PASSWORD=change-me-please POSTGRES_DB=artex @@ -29,3 +31,32 @@ ARTEX_TOOL_MEMORY_LIMIT_MB=2048 ARTEX_TOOL_TIMEOUT_S=120 # 单条命令的进程/线程数上限(仅在 Linux cgroup v2 可委托时生效,默认 256;设为 0 关闭) ARTEX_TOOL_PIDS_LIMIT=256 + +# 沙箱容器隔离(推荐 docker;单机无 Docker 可改为 local) +ARTEX_SANDBOX_MODE=docker +ARTEX_SANDBOX_IMAGE=ruoji6/artex-sandbox:latest +ARTEX_SANDBOX_NETWORK=artex-sandbox +# 必填(Docker 部署时):宿主机上 ./data 目录的绝对路径,用于给兄弟沙箱容器精确挂载单个任务目录 +ARTEX_HOST_DATA_DIR=/path/to/ARTEX/data +# 可选:切换沙箱容器运行时(留空用默认 runc;填 runsc 可启用 gVisor 内核级隔离) +ARTEX_SANDBOX_RUNTIME= +# 单沙箱容器资源限额与自动停机策略 +ARTEX_SANDBOX_MEMORY_MB=2048 +ARTEX_SANDBOX_CPUS=2 +ARTEX_SANDBOX_PIDS_LIMIT=256 +ARTEX_SANDBOX_SHM_MB=512 +ARTEX_SANDBOX_AUTO_STOP=true +ARTEX_SANDBOX_SESSION_IDLE_MIN=20 +# 允许沙箱中经 file-cap (cap_net_raw+ep) 授权的 nmap / nping / ping 发起 SYN/UDP/ICMP 探测(所有 SUID/SGID 已剥离); +# 如使用不受信任的第三方自定义镜像,请设为 false 以强制 no-new-privileges:true +ARTEX_SANDBOX_ALLOW_NET_RAW=true +# 抓包代理 SSRF 防护:本机/云元数据/ARTEX 自身与 postgres 网段始终禁止;设为 true 时额外拦截其他私有网段(内网渗透保持 false) +ARTEX_PROXY_BLOCK_PRIVATE=false +# 宿主机自己的局域网 IP(可逗号分隔)。这些地址上的 :8787/:8788 会被代理拒绝,其他端口仍可当作扫描目标 +ARTEX_PROXY_PROTECT_IPS= +# 全流量透明代理网关(#218 Phase 3):开启后自动将沙箱容器的裸 TCP / UDP / DNS 全部收口到 artex-gateway +ARTEX_SANDBOX_TRANSPARENT=true +# artex 与 artex-gateway 之间的内部鉴权密钥(建议设为随机长字符串) +ARTEX_GATEWAY_TOKEN= +# 可选:覆盖沙箱容器默认 DNS(留空时自动使用 artex-sandbox 网桥网关 IP) +ARTEX_SANDBOX_DNS= diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4e8620b..f255a33 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -257,10 +257,11 @@ jobs: jq -e --arg version "${RELEASE_TAG#v}" '.version == $version' /tmp/artex-version.json curl --fail http://127.0.0.1:8787/ > /tmp/artex-index.html grep -qi ' /tmp/artex-manifest.json jq -e '[.manifests[].platform | select(.os == "linux") | .architecture] | index("amd64") != null and index("arm64") != null' /tmp/artex-manifest.json + + # 2. Transparent gateway image + docker buildx imagetools create \ + --tag "$IMAGE-gateway:$RELEASE_TAG" --tag "$IMAGE-gateway:latest" \ + "$IMAGE-gateway:$RELEASE_TAG-amd64" "$IMAGE-gateway:$RELEASE_TAG-arm64" + + # 3. Sandbox worker image + docker buildx imagetools create \ + --tag "$IMAGE-sandbox:$RELEASE_TAG" --tag "$IMAGE-sandbox:latest" \ + "$IMAGE-sandbox:$RELEASE_TAG-amd64" "$IMAGE-sandbox:$RELEASE_TAG-arm64" diff --git a/.gitignore b/.gitignore index c9a7436..6b378b0 100644 --- a/.gitignore +++ b/.gitignore @@ -50,9 +50,9 @@ Thumbs.db # JWT 签名密钥(运行时生成,存项目根,绝不提交) /jwt.key -# Docker 部署生成的本地环境(含密码/密钥,不提交) +# Docker 部署生成的本地环境与升级回滚快照(含密码/密钥/数据库备份,绝不提交) .env - +.artex-deploy/ # 调度器运行/模拟产生的事件日志(测试产物,不提交) *-events.csv diff --git a/Dockerfile b/Dockerfile index a3db2e0..93af71a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,25 +10,12 @@ # cp -r web/out server/webui/dist # CGO_ENABLED=0 GOARCH=amd64 go build -tags embedui -o dist/amd64/artex ./cmd/artex # docker build -t artex:local . -FROM python:3.12-slim-bookworm +FROM debian:bookworm-slim ARG TARGETARCH -# 常用工具:ripgrep / curl / vim,加一批 recon 常备件(按需增删)。 -# Node 从 NodeSource 装 22.x,与前端构建使用的主版本一致。 +# 主服务镜像只保留运行 ARTEX Go 控制面所需的最小基础依赖; +# 渗透工具链与 Playwright/Chromium 已拆入独立沙箱镜像(Dockerfile.sandbox)。 RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates ripgrep curl wget vim git jq unzip \ - tzdata \ - dnsutils iputils-ping netcat-openbsd inetutils-telnet whois nmap \ - && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ - && apt-get install -y --no-install-recommends nodejs \ - && rm -rf /var/lib/apt/lists/* -# 预装 Playwright MCP 与 CLI(全局),运行时优先直接调用 playwright-mcp,无需 npx 联网下载。 -# 必须通过 playwright-mcp 自身的 install-browser 安装对应版本的 chromium 及其系统依赖, -# 避免全局 playwright 与 @playwright/mcp 内置 playwright-core 版本不一致导致找不到浏览器可执行文件。 -RUN npm install -g @playwright/mcp@latest @playwright/cli@latest \ - && playwright-mcp --version \ - && playwright-cli --help \ - && playwright-mcp install-browser --with-deps chromium \ - && playwright-cli install-browser chromium \ + ca-certificates curl tzdata \ && rm -rf /var/lib/apt/lists/* WORKDIR /app ENV TZ=Asia/Shanghai diff --git a/Dockerfile.gateway b/Dockerfile.gateway new file mode 100644 index 0000000..00ab23f --- /dev/null +++ b/Dockerfile.gateway @@ -0,0 +1,19 @@ +# syntax=docker/dockerfile:1 +# +# ARTEX 沙箱全流量透明代理网关镜像(#218 Phase 3): +# 仅本轻量容器持有 CAP_NET_ADMIN + network_mode: host,负责接管 artex-sandbox 网桥的 +# 全量 TCP / DNS / UDP 流量,消除环境变量绕过;沙箱容器继续保持非 root + CapDrop: ALL。 +FROM golang:1.26-bookworm AS builder +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/artex-gateway ./cmd/artex-gateway + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates iptables iproute2 tzdata \ + && rm -rf /var/lib/apt/lists/* +ENV TZ=Asia/Shanghai +COPY --from=builder /out/artex-gateway /usr/local/bin/artex-gateway +ENTRYPOINT ["/usr/local/bin/artex-gateway"] diff --git a/Dockerfile.sandbox b/Dockerfile.sandbox new file mode 100644 index 0000000..9597178 --- /dev/null +++ b/Dockerfile.sandbox @@ -0,0 +1,64 @@ +# syntax=docker/dockerfile:1 +# +# ARTEX Worker / Chat Sandbox 镜像: +# 承载所有不受信任的工具执行(Bash / Python 脚本 / 扫描工具 / Playwright 浏览器), +# 不含 ARTEX 主服务、不含 LLM Key、不含数据库凭据,以非 root 用户运行。 +# +# 本地构建: +# docker build -f Dockerfile.sandbox -t ruoji6/artex-sandbox:latest . +FROM python:3.12-slim-bookworm + +ENV TZ=Asia/Shanghai \ + DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates ripgrep curl wget vim git jq unzip \ + tzdata procps libcap2-bin \ + dnsutils iputils-ping netcat-openbsd inetutils-telnet whois nmap \ + && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ + && apt-get install -y --no-install-recommends nodejs \ + && rm -rf /var/lib/apt/lists/* + +# 预装 Playwright MCP 与 CLI 及 Chromium(直接装到全局路径供非 root 用户运行, +# 浏览器访问目标站点完全隔离在沙箱容器内)。 +# 国内构建可传 --build-arg PLAYWRIGHT_DOWNLOAD_HOST=https://npmmirror.com/mirrors/playwright 加速。 +ARG PLAYWRIGHT_DOWNLOAD_HOST="" +ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \ + PLAYWRIGHT_DOWNLOAD_HOST=${PLAYWRIGHT_DOWNLOAD_HOST} \ + SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \ + CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \ + REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt \ + NODE_EXTRA_CA_CERTS=/etc/artex/ca.crt \ + NMAP_PRIVILEGED=1 +RUN mkdir -p /ms-playwright /workspace /etc/artex /usr/local/share/ca-certificates \ + && npm install -g @playwright/mcp@latest @playwright/cli@latest \ + && playwright-mcp --version \ + && playwright-cli --help \ + && playwright-mcp install-browser --with-deps chromium \ + && playwright-cli install-browser chromium \ + && chmod -R a+rX /ms-playwright \ + && rm -rf /var/lib/apt/lists/* +# 常用渗透/脚本 Python 依赖 +RUN pip install --no-cache-dir requests httpx beautifulsoup4 pyyaml + +# 可选系统 CA 刷新辅助脚本(默认运行模式下由主服务直接只读挂载合并后的 +# /etc/ssl/certs/ca-certificates.crt,无需容器内 root 权限;若以 root 调试 +# 或自定义镜像启动,可运行此脚本通过 update-ca-certificates 注入 /etc/artex/ca.crt)。 +RUN printf '#!/bin/sh\nif [ -f /etc/artex/ca.crt ] && [ -w /usr/local/share/ca-certificates ]; then\n cp /etc/artex/ca.crt /usr/local/share/ca-certificates/artex-mitm-ca.crt\n update-ca-certificates >/dev/null 2>&1 || true\nfi\n' > /usr/local/bin/artex-update-ca.sh \ + && chmod +x /usr/local/bin/artex-update-ca.sh + +# 非 root 运行用户(UID/GID 1000,与 ARTEX_SANDBOX_USER 默认值对齐)。 +RUN groupadd -g 1000 sandbox \ + && useradd -u 1000 -g 1000 -m -s /bin/bash sandbox \ + && chown -R 1000:1000 /workspace +# 剥离所有 SUID/SGID 位防止提权,仅授予 nmap / nping / ping 最小必需的 cap_net_raw+ep +# 文件能力(注意仅 +ep 而非 +eip,确保子进程/NSE os.execute 不继承任何 capability), +# 使非 root 沙箱用户(uid 1000)无需 sudo 即可执行 nmap -sU/-sS、nping 与 ping, +# 同时普通脚本与进程依然保持 CapEff=0。 +RUN find / -xdev -perm /6000 -type f -exec chmod a-s {} + 2>/dev/null || true \ + && setcap cap_net_raw+ep /usr/bin/nmap \ + && (setcap cap_net_raw+ep /usr/bin/nping 2>/dev/null || true) \ + && (setcap cap_net_raw+ep /usr/bin/ping 2>/dev/null || setcap cap_net_raw+ep /bin/ping 2>/dev/null || true) +USER 1000:1000 +WORKDIR /workspace +CMD ["sleep", "infinity"] diff --git a/README.md b/README.md index d8e2cd4..9593d6d 100644 --- a/README.md +++ b/README.md @@ -113,11 +113,16 @@ cd ARTEX ./install.sh ``` -脚本会:检测 / 自动安装 Docker → 让你选 **① 全部 Docker** 或 **② 本地编译运行**: +脚本提供 Docker 部署与本地编译两种方式: -- **① 全部 Docker**:填一个 Postgres 密码(可回车随机)→ 自动写 `.env` → `docker compose up -d`。 +- **① Docker 部署(推荐)**:对应 `docker-compose.yml`,包含 `postgres` + `docker-socket-proxy` + `artex` + `artex-gateway`(TUN/netstack 透明网关)+ 动态拉起的 `artex-sandbox` 非 root 沙箱容器。脚本会自动填写 `ARTEX_HOST_DATA_DIR`、`ARTEX_GATEWAY_TOKEN` 与随机 `POSTGRES_PASSWORD`。 - **② 本地运行**:选数据库(连已有 / 用 Docker 起一个)→ 生成 `config.json` → `go` 编译内嵌单二进制 → 启动。 +也支持非交互参数直接安装: +```bash +./install.sh --docker --yes +``` + 装好后打开 **http://localhost:8787**(首次进入 `/setup` 设置管理员密码)。 ### 方式二:Docker Compose(手动) @@ -125,15 +130,12 @@ cd ARTEX ```bash git clone https://github.com/RuoJi6/ARTEX.git cd ARTEX -cp .env.example .env # 填 POSTGRES_PASSWORD、可选 ANTHROPIC_API_KEY -docker compose up -d # 拉取 ruoji6/artex 镜像 + postgres +cp .env.example .env # 填 POSTGRES_PASSWORD、ARTEX_HOST_DATA_DIR、ARTEX_GATEWAY_TOKEN +docker compose up -d # 启动 postgres + docker-socket-proxy + artex + artex-gateway # → http://localhost:8787 ``` -镜像已含常用工具(ripgrep/curl/vim/npm/nmap…);`./skills` 与 `./data` 以绑定挂载持久化。 - -`.env` 中默认 `ARTEX_IMAGE=ruoji6/artex`,`ARTEX_TAG=latest` 使用最新镜像,也可固定为 `v0.3.17`(完整镜像地址 `ruoji6/artex:v0.3.17`)。镜像支持 `linux/amd64` 和 `linux/arm64`,Docker 会自动选择与宿主机匹配的架构,ARM64 Kali 无需自行编译。初次部署请修改 `POSTGRES_PASSWORD`;运行服务无需配置 Docker Hub 发布 Token。 - +镜像均支持 `linux/amd64` 与 `linux/arm64`:`ruoji6/artex:` + `ruoji6/artex-gateway:` + `ruoji6/artex-sandbox:`(默认 `latest`)。 #### 内存与进程保护 - **Compose 容器**:`artex` 默认最多使用 **4 GiB 内存、512 个进程/线程**,并禁用容器 swap;PostgreSQL 不受这两个上限限制。通过 `.env` 的 `ARTEX_MEMORY_LIMIT`、`ARTEX_PIDS_LIMIT` 调整。小内存 VPS 应调低内存上限,给宿主机、数据库和其他服务留出余量。更新 Compose 或 `.env` 后,运行 `docker compose up -d artex` 重建容器;只热更新程序不会改变容器限制。 @@ -273,29 +275,39 @@ curl --fail http://127.0.0.1:8787/api/health 这会保留现有数据库、data 和 skills 挂载。登录系统配置页检查更新源与版本。容器内替换的程序仍属于容器可写层,删除或重建容器会丢失替换结果;需要重建时应使用包含本仓库程序的镜像。程序回滚不回退数据库迁移,升级前请备份数据库和 data。 -### 方式二:一键更新脚本 +### 方式二:一键升级与回滚脚本(推荐) ```bash cd ARTEX ./update.sh ``` -脚本先可选 `git pull` 拉取最新代码,再让你选 **① Docker 更新** 或 **② 本地编译更新**(与 `install.sh` 对应): +脚本会在**每次升级前自动生成回滚快照**(保存在 `.artex-deploy/snapshots//`,包含 `.env`、当前镜像精确 ID 的本地回滚标签 `artex-rollback/*` 及 PostgreSQL 逻辑备份 `postgres.sql.gz`): -- **① Docker**:可指定目标镜像 tag(回车沿用 `.env` 的 `ARTEX_TAG`,缺省 `latest`)→ `docker compose pull` → `docker compose up -d`(换新镜像重启即自动迁移)。 -- **② 本地**:重建前端静态产物 → 重新编译 `./artex`(完成后重启进程生效)。 +- **升级 Docker 部署**: + ```bash + ./update.sh --upgrade # 升级到最新镜像 + ./update.sh --upgrade --tag v0.3.33 # 指定版本升级 + ``` + 保留原 `pgdata` 数据卷、`./data`、`./skills`,自动补齐 `.env` 中的 `ARTEX_HOST_DATA_DIR` / `ARTEX_GATEWAY_TOKEN`,并安全校准既有 `./data/tasks`、`./data/sessions` 与 `./data/ephemeral` 的非 root 写权限(跳过符号链接)。若新版健康检查未通过,自动回滚回升级前快照。 +- **回滚到历史快照**: + ```bash + ./update.sh --list-snapshots # 查看所有可用快照 + ./update.sh --rollback # 回滚到最近一次快照 + ./update.sh --rollback # 回滚到指定快照 + ./update.sh --rollback --restore-db # 同时用快照中的 postgres.sql.gz 恢复数据库 + ``` + > 回滚优先使用本地固定的精确镜像 ID(`artex-rollback/*`),即便 `:latest` 已被覆盖或宿主机离线也能准确恢复。数据库结构前向与后向兼容,常规回滚无需覆盖数据库。 + > 注意:Docker 下页面内「一键更新 / 回滚」仅作用于 `artex` 主控二进制,不会同步切换 `artex-gateway` 与 `artex-sandbox` 镜像,整套升级与回滚请使用 `./update.sh`。 ### 方式三:Docker Compose(手动) ```bash cd ARTEX git pull # 更新 compose / 脚本(可选) -# 指定版本:在 .env 设 ARTEX_TAG=v0.3.17;不设则用 latest -docker compose pull artex -docker compose up -d artex # 换新镜像重启 → 自动迁移 schema -docker image prune -f # 清理旧镜像(可选) +docker compose pull && docker pull "${ARTEX_SANDBOX_IMAGE:-ruoji6/artex-sandbox:latest}" +docker compose up -d --remove-orphans ``` - ### 方式四:预编译二进制(Releases) 到 [Releases](https://github.com/RuoJi6/ARTEX/releases) 下载新版本 zip,停掉旧进程后覆盖 `artex` 与 `skills/`(保留你的 `config.json` 与 `data/`),重启即可: diff --git a/agent/chat.go b/agent/chat.go index ac9d9ee..e64ede4 100644 --- a/agent/chat.go +++ b/agent/chat.go @@ -9,6 +9,8 @@ import ( "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/guard" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" "github.com/Autumn-27/norma/agentcore" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/permission" @@ -111,9 +113,20 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin ws.Enabled = false } + sbMgr := sandbox.Default() + sandboxActive := sbMgr != nil && sbMgr.Enabled() + sbTarget := sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: sessionID} + if preset, ok := sandbox.TargetFrom(ctx); ok && preset.Valid() { + sbTarget = preset + } + // Per-session working directory: /sessions// - // Isolates file writes across conversations, mirroring how workers use i/. + // When bound to a task sandbox (e.g. task-scoped reporter screenshots), use + // that task's workspace root so screenshots land directly in tasks//. sessionWorkDir := filepath.Join(c.workDir, "sessions", sessionID) + if sandboxActive && sbTarget.Scope == sandbox.ScopeTask { + sessionWorkDir = sbMgr.Config().LocalRootFor(sbTarget) + } _ = os.MkdirAll(sessionWorkDir, 0o755) ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir) @@ -121,15 +134,43 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin // visible skills/MCP and lets the DB tools table filter/override. DefaultTools // have no tools-table rows, so they always pass through. base := guardedDefaultTools() + displayWorkDir := sessionWorkDir + displayDataDir := c.workDir + if sandboxActive { + sbMgr.Acquire(sbTarget) + defer sbMgr.Release(sbTarget) + ctx = sandbox.WithTarget(ctx, sbTarget) + hostRoot := sbMgr.Config().LocalRootFor(sbTarget) + base = wrapSandboxFileTools(base, hostRoot, "") + displayWorkDir = sandbox.ContainerWorkDir + displayDataDir = sandbox.ContainerWorkDir + } ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID, WorkDir: sessionWorkDir}) tools, def, cleanup := AugmentTools(ctx, agentKey, base) defer cleanup() - system, boundary := deferredSystem(chatSystem(agentKey, c.workDir, sessionWorkDir), def) + system, boundary := deferredSystem(chatSystem(agentKey, displayDataDir, displayWorkDir), def) proxyAddr := c.proxyAddr if c.proxyAddrFn != nil { proxyAddr = c.proxyAddrFn() } + srcID := traffic.SourceIdentity{ + Scope: string(sbTarget.Scope), + OwnerID: sbTarget.OwnerID, + SessionID: sessionID, + } + webFetchProxy := proxyAddr + if c.proxyCACert != "" && proxyAddr != "" { + webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID) + } + bashEnv := proxyEnv(webFetchProxy, c.proxyCACert) + if sandboxActive { + if proxyAddr != "" && c.proxyCACert != "" && sbMgr.Config().ProxyURL != "" { + bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID)) + } else { + bashEnv = sbMgr.ProxyEnv(proxyAddr != "") + } + } opts := agentcore.Options{ Provider: c.prov, SystemPrompt: system, @@ -139,18 +180,16 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin UnlockSet: def.Unlock, PermissionMode: permission.ModeBypass, EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书 - WebFetchProxy: proxyAddr, + WebFetchProxy: webFetchProxy, WebFetchCACert: c.proxyCACert, - // 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。 // WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。 EnableWebSearch: ws.Enabled && ws.Backend != "deepseek", WebSearchBackend: ws.Backend, BraveSearchAPIKey: ws.BraveKey, TavilySearchAPIKey: ws.TavilyKey, WebSearchProxy: ws.Proxy, - BashEnv: proxyEnv(proxyAddr, c.proxyCACert), // Bash 子命令默认走代理+信任 CA + BashEnv: bashEnv, // Bash 子命令默认走代理+信任 CA WorkingDir: sessionWorkDir, - MaxTurns: maxTurns, MaxDuration: maxDuration, Compaction: compactionConfig(c.window), Todos: actool.NewTodoStore(), diff --git a/agent/mainagent.go b/agent/mainagent.go index 6ab9e4f..6301a53 100644 --- a/agent/mainagent.go +++ b/agent/mainagent.go @@ -3,9 +3,12 @@ package agent import ( "context" "fmt" + "strconv" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" "github.com/Autumn-27/norma/agentcore" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/permission" @@ -131,14 +134,44 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. // 本任务的工作目录 /tasks/,先建好。 mainDir := ensureRunDir(m.workDir, taskID, 0) ctx = intercept.WithReviewWorkingDirectory(ctx, mainDir) + displayWorkDir := mainDir + displayDataDir := m.workDir + sbMgr := sandbox.Default() + sandboxActive := sbMgr != nil && sbMgr.Enabled() && taskID > 0 + if sandboxActive { + sbTarget := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)} + sbMgr.Acquire(sbTarget) + defer sbMgr.Release(sbTarget) + ctx = sandbox.WithTarget(ctx, sbTarget) + hostRoot := sbMgr.Config().LocalRootFor(sbTarget) + base = wrapSandboxFileTools(base, hostRoot, "") + displayWorkDir = sandbox.ContainerWorkDir + displayDataDir = sandbox.ContainerWorkDir + } ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), WorkDir: mainDir}) tools, def, cleanup := AugmentTools(ctx, "mainagent", base) defer cleanup() - system, boundary := deferredSystem(mainAgentSystem(goal, m.workDir, mainDir), def) + system, boundary := deferredSystem(mainAgentSystem(goal, displayDataDir, displayWorkDir), def) proxyAddr := m.proxyAddr if m.proxyAddrFn != nil { proxyAddr = m.proxyAddrFn() } + srcID := traffic.SourceIdentity{ + Scope: "task", + OwnerID: strconv.FormatInt(taskID, 10), + } + webFetchProxy := proxyAddr + if m.proxyCACert != "" && proxyAddr != "" && taskID > 0 { + webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID) + } + bashEnv := proxyEnv(webFetchProxy, m.proxyCACert) + if sandboxActive { + if proxyAddr != "" && m.proxyCACert != "" && sbMgr.Config().ProxyURL != "" { + bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID)) + } else { + bashEnv = sbMgr.ProxyEnv(proxyAddr != "") + } + } opts := agentcore.Options{ Provider: m.prov, SystemPrompt: system, @@ -148,19 +181,18 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. UnlockSet: def.Unlock, PermissionMode: permission.ModeBypass, EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书 - WebFetchProxy: proxyAddr, + WebFetchProxy: webFetchProxy, WebFetchCACert: m.proxyCACert, - // 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。 // WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。 EnableWebSearch: m.webSearch.Enabled && m.webSearch.Backend != "deepseek", WebSearchBackend: m.webSearch.Backend, BraveSearchAPIKey: m.webSearch.BraveKey, TavilySearchAPIKey: m.webSearch.TavilyKey, WebSearchProxy: m.webSearch.Proxy, - BashEnv: proxyEnv(proxyAddr, m.proxyCACert), // Bash 子命令默认走代理+信任 CA - WorkingDir: mainDir, // 本任务工作目录 /tasks/ + BashEnv: bashEnv, // Bash 子命令默认走代理+信任 CA + WorkingDir: mainDir, // 本任务工作目录 /tasks/ ToolOutputDir: cmdOutDir(mainDir), - MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management) + MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management) Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the window Todos: actool.NewTodoStore(), // 会话级临时待办(TodoWrite),纯规划用,退出即丢 // 命中预算(步数)→ SDK 跑收尾:向用户输出一句进展总结。Prompt 与收尾轮数可后台编辑(默认 10 轮)。 diff --git a/agent/planner.go b/agent/planner.go index d2e71c2..8061c5e 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -4,11 +4,13 @@ import ( "context" "encoding/json" "fmt" + "strconv" "strings" "sync" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/traffic" "github.com/Autumn-27/norma/agentcore" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/permission" @@ -408,6 +410,13 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts if p.proxyAddrFn != nil { proxyAddr = p.proxyAddrFn() } + webFetchProxy := proxyAddr + if p.proxyCACert != "" && proxyAddr != "" && taskID > 0 { + webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, traffic.SourceIdentity{ + Scope: "task", + OwnerID: strconv.FormatInt(taskID, 10), + }) + } opts := agentcore.Options{ Provider: p.prov, SystemPrompt: system, @@ -417,18 +426,17 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts UnlockSet: def.Unlock, PermissionMode: permission.ModeBypass, EnableWebFetch: true, // 走记录代理留痕;载入代理 CA 验证 MITM 重签的 HTTPS 证书 - WebFetchProxy: proxyAddr, + WebFetchProxy: webFetchProxy, WebFetchCACert: p.proxyCACert, // 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。 - // WebSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。 + // WebSearchProxy 是独立的出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。 EnableWebSearch: p.webSearch.Enabled && p.webSearch.Backend != "deepseek", WebSearchBackend: p.webSearch.Backend, BraveSearchAPIKey: p.webSearch.BraveKey, TavilySearchAPIKey: p.webSearch.TavilyKey, WebSearchProxy: p.webSearch.Proxy, - BashEnv: proxyEnv(proxyAddr, p.proxyCACert), // Bash 子命令默认走代理+信任 CA - WorkingDir: taskDir, // 本任务工作目录 /tasks/ - ToolOutputDir: cmdOutDir(taskDir), + BashEnv: proxyEnv(webFetchProxy, p.proxyCACert), // Bash 子命令默认走代理+信任 CA + WorkingDir: taskDir, // 本任务工作目录 /tasks/ MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management) MaxDuration: maxDur, // 0=不限;有 deadline 时=距 deadline 剩余 Compaction: compactionConfig(p.compactionWindow()), diff --git a/agent/sandbox_tools.go b/agent/sandbox_tools.go new file mode 100644 index 0000000..599fee8 --- /dev/null +++ b/agent/sandbox_tools.go @@ -0,0 +1,134 @@ +package agent + +import ( + "context" + "encoding/json" + "fmt" + "path/filepath" + "strings" + + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/norma/llm" + actool "github.com/Autumn-27/norma/tool" +) + +// wrapSandboxFileTools confines norma's built-in filesystem tools (Read, Write, +// Edit, MultiEdit, LS, Glob, Grep) to hostRoot and translates paths between +// the container view (/workspace/...) and the host directory, enforcing symlink +// escape protection on every call. +func wrapSandboxFileTools(tools []actool.CoreTool, hostRoot, defaultSubdir string) []actool.CoreTool { + out := make([]actool.CoreTool, len(tools)) + for i, t := range tools { + switch t.Name() { + case "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep": + out[i] = &sandboxFileTool{ + CoreTool: t, + hostRoot: filepath.Clean(hostRoot), + defaultSubdir: defaultSubdir, + } + default: + out[i] = t + } + } + return out +} + +type sandboxFileTool struct { + actool.CoreTool + hostRoot string + defaultSubdir string +} + +func (s *sandboxFileTool) Call(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + rewritten, err := s.rewriteInput(in) + if err != nil { + return actool.Errorf("Error: " + err.Error()), nil + } + // Adjust ToolContext.WorkingDir to the confined default directory on host so + // relative operations (LS/Glob/Grep without explicit path) never escape hostRoot. + subTC := tc + if tc != nil { + cp := *tc + if s.defaultSubdir != "" { + cp.WorkingDir = filepath.Join(s.hostRoot, s.defaultSubdir) + } else { + cp.WorkingDir = s.hostRoot + } + subTC = &cp + } + res, err := s.CoreTool.Call(ctx, rewritten, subTC) + if err != nil { + return res, err + } + return s.rewriteResult(res), nil +} + +func (s *sandboxFileTool) rewriteInput(in json.RawMessage) (json.RawMessage, error) { + var m map[string]any + if err := json.Unmarshal(in, &m); err != nil { + return in, nil + } + changed := false + for _, key := range []string{"file_path", "path"} { + rawVal, exists := m[key] + if !exists { + continue + } + strVal, ok := rawVal.(string) + if !ok { + continue + } + if strings.TrimSpace(strVal) == "" && (s.Name() == "LS" || s.Name() == "Glob" || s.Name() == "Grep") { + if s.defaultSubdir != "" { + m[key] = filepath.Join(s.hostRoot, s.defaultSubdir) + } else { + m[key] = s.hostRoot + } + changed = true + continue + } + resolved, allowed := sandbox.ResolveConfined(s.hostRoot, s.defaultSubdir, strVal) + if !allowed { + return nil, fmt.Errorf("path %q is outside sandbox workspace (%s)", strVal, sandbox.ContainerWorkDir) + } + m[key] = resolved + changed = true + } + // If LS/Glob/Grep omitted path entirely, anchor it inside the sandbox root. + if !changed && (s.Name() == "LS" || s.Name() == "Glob" || s.Name() == "Grep") { + if _, hasPath := m["path"]; !hasPath { + if s.defaultSubdir != "" { + m["path"] = filepath.Join(s.hostRoot, s.defaultSubdir) + } else { + m["path"] = s.hostRoot + } + changed = true + } + } + if !changed { + return in, nil + } + b, err := json.Marshal(m) + if err != nil { + return in, err + } + return b, nil +} + +func (s *sandboxFileTool) rewriteResult(res actool.Result) actool.Result { + rootReal, err := filepath.EvalSymlinks(s.hostRoot) + if err != nil { + rootReal = s.hostRoot + } + for i := range res.Content { + if res.Content[i].Type == llm.BlockText && res.Content[i].Text != "" { + txt := res.Content[i].Text + txt = strings.ReplaceAll(txt, rootReal, sandbox.ContainerWorkDir) + if s.hostRoot != rootReal { + txt = strings.ReplaceAll(txt, s.hostRoot, sandbox.ContainerWorkDir) + } + res.Content[i].Text = txt + } + } + return res +} diff --git a/agent/worker.go b/agent/worker.go index a2bfef1..a770075 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -12,6 +12,8 @@ import ( "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" "github.com/Autumn-27/norma/agentcore" "github.com/Autumn-27/norma/harness" "github.com/Autumn-27/norma/llm" @@ -372,6 +374,18 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. base = append(base, defaultToolsExcept("MultiEdit", "Glob", "Grep")...) // 本次意图的专属工作目录 /tasks//i,引擎侧先建好。 runDir := ensureRunDir(w.workDir, taskID, intent.ID) + displayRunDir := runDir + sbMgr := sandbox.Default() + sandboxActive := sbMgr != nil && sbMgr.Enabled() + if sandboxActive { + sbTarget := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)} + sbMgr.Acquire(sbTarget) + defer sbMgr.Release(sbTarget) + ctx = sandbox.WithTarget(ctx, sbTarget) + hostRoot := sbMgr.Config().LocalRootFor(sbTarget) + base = wrapSandboxFileTools(base, hostRoot, fmt.Sprintf("i%d", intent.ID)) + displayRunDir = sandbox.HostToContainerPath(hostRoot, runDir) + } // The run-wide intent is not the current tool action. Do not forward it or // inherit a parent run's background into the action reviewer. ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{}) @@ -379,22 +393,38 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. tools, def, cleanup := AugmentTools(ctx, "worker", base) defer cleanup() - // 意图是 worker 的【唯一职责、贯穿整个 run 的不变量】→ 连同启动指令、意图锚定的目标资产 - // 原始数据一起放进 system prompt:system 每次 run 都重新拼一遍、绝不会被 compaction 压掉, - // 长 run 里意图永远在场,续跑时也不依赖 transcript 历史是否留住那条首消息。代价是 system - // 混入 per-intent 易变数据、失去跨意图缓存复用;这是刻意的取舍(意图丢失比省 token 严重得多)。 - // 与 planner「态势块放 user turn」分叉是有意的:planner 本身是产意图的那个、没有单一 mandate, - // worker 有。仅【全局态势 overview】留在启动 user 消息里——它可降级、容忍 stale,压掉无碍。 overview := renderWorkerGraphOverview(tsx.graphOverviewData()) proxyAddr := w.proxyAddr if w.proxyAddrFn != nil { proxyAddr = w.proxyAddrFn() } - sysBody := workerSystem(proxyAddr, w.proxyCACert, w.workDir, runDir) + sysProxyAddr, sysCACert, sysDataDir := proxyAddr, w.proxyCACert, w.workDir + srcID := traffic.SourceIdentity{ + Scope: "task", + OwnerID: strconv.FormatInt(taskID, 10), + IntentID: intent.ID, + } + webFetchProxy := proxyAddr + if w.proxyCACert != "" && proxyAddr != "" { + webFetchProxy = traffic.FormatProxyContextURL(proxyAddr, srcID) + } + bashEnv := proxyEnv(webFetchProxy, w.proxyCACert) + if sandboxActive { + if proxyAddr != "" && sbMgr.Config().ProxyURL != "" { + sysProxyAddr = sbMgr.Config().ProxyURL + sysCACert = sandbox.ContainerCACertPath + } + sysDataDir = sandbox.ContainerWorkDir + if proxyAddr != "" && w.proxyCACert != "" && sbMgr.Config().ProxyURL != "" { + bashEnv = sbMgr.ProxyEnvWithURL(traffic.FormatProxyContextURL(sbMgr.Config().ProxyURL, srcID)) + } else { + bashEnv = sbMgr.ProxyEnv(proxyAddr != "") + } + } + sysBody := workerSystem(sysProxyAddr, sysCACert, sysDataDir, displayRunDir) if w.wantConstraints() { sysBody += constraintBlock(ts) // 操作约束(若有)注入系统提示,worker 执行时严格遵守 } - // 意图块 → 意图锚定资产块 → 启动指令,依次追加到 system 尾部(与 constraintBlock 同一套追加法)。 sysBody += renderIntentTask(intent) if as != nil { if ids := intentAssetIDs(intent); len(ids) > 0 { @@ -434,9 +464,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. // WebFetch 走记录代理,其 HTTP 与 curl 一样被留痕;载入代理 CA 让经 MITM // 重签的 HTTPS 证书能【正常校验通过】(而非关掉校验)。proxy 空则直连。 EnableWebFetch: true, - WebFetchProxy: proxyAddr, + WebFetchProxy: webFetchProxy, WebFetchCACert: w.proxyCACert, - // 联网搜索(可选)。ddgs 无需 key;brave-free 需 BraveKey;tavily 需 TavilyKey。 // WebSearchProxy 是独立的出口代理(http/https/socks5),与记录流量的 MITM 代理无关;空则直连。 EnableWebSearch: w.webSearch.Enabled && w.webSearch.Backend != "deepseek", WebSearchBackend: w.webSearch.Backend, @@ -444,9 +473,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. TavilySearchAPIKey: w.webSearch.TavilyKey, WebSearchProxy: w.webSearch.Proxy, // Bash 子命令的 HTTP 默认走记录代理 + 信任其 CA(工具无需 -x/-k)。 - BashEnv: proxyEnv(proxyAddr, w.proxyCACert), + BashEnv: bashEnv, WorkingDir: runDir, - MaxTurns: w.maxTurns, // 0 = unlimited (configurable in agent management) // 墙钟预算,轮边界判,不打断半路;0 = 不限。有任务级 deadline 时夹逼到 min(自身预算, // 距 deadline 剩余),让本 run 在任务到点时自然进收尾(见 taskclock.go)。 MaxDuration: maxDur, diff --git a/cmd/artex-gateway/iptables_linux.go b/cmd/artex-gateway/iptables_linux.go new file mode 100644 index 0000000..48b8880 --- /dev/null +++ b/cmd/artex-gateway/iptables_linux.go @@ -0,0 +1,253 @@ +//go:build linux + +package main + +import ( + "fmt" + "log" + "net" + "os/exec" + "strconv" + "strings" + "time" +) + +const ( + chainNAT = "ARTEX_GW_NAT" + chainMangle = "ARTEX_GW_MANGLE" + chainFwd = "ARTEX_GW_FWD" + chainInput = "ARTEX_GW_INPUT" + tproxyMark = "0x218" + tproxyTable = "218" +) + +type iptablesConfig struct { + Subnet string + GatewayIP string + TCPPort int + UDPPort int + DNSPort int + ProxyPort int // explicit MITM proxy port (8788) allowed direct to artex + AdminPort int // admin UI/API port (8787) explicitly rejected from sandbox + BridgeName string +} + +// discoverSandboxBridge finds the Linux bridge interface owning gatewayIP or +// subnet (e.g. br-xxxxxxxxxxxx for artex-sandbox). +func discoverSandboxBridge(subnet, gatewayIP string, wait time.Duration) (string, error) { + _, cidr, _ := net.ParseCIDR(strings.TrimSpace(subnet)) + gwIP := net.ParseIP(strings.TrimSpace(gatewayIP)) + if gwIP != nil { + gwIP = gwIP.To4() + } + + deadline := time.Now().Add(wait) + for { + ifaces, err := net.Interfaces() + if err == nil { + for _, iface := range ifaces { + addrs, aerr := iface.Addrs() + if aerr != nil { + continue + } + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok || ipnet.IP == nil { + continue + } + v4 := ipnet.IP.To4() + if v4 == nil { + continue + } + if gwIP != nil && v4.Equal(gwIP) { + return iface.Name, nil + } + if cidr != nil && cidr.Contains(v4) { + return iface.Name, nil + } + } + } + } + if time.Now().After(deadline) { + break + } + time.Sleep(1 * time.Second) + } + return "", fmt.Errorf("sandbox bridge interface not found for subnet=%q gateway=%q", subnet, gatewayIP) +} + +func runCmd(name string, args ...string) error { + out, err := exec.Command(name, args...).CombinedOutput() + if err != nil { + return fmt.Errorf("%s %s: %w (%s)", name, strings.Join(args, " "), err, strings.TrimSpace(string(out))) + } + return nil +} + +func runCmdIgnoreErr(name string, args ...string) { + _ = exec.Command(name, args...).Run() +} + +func ensureJump(table, parent, chain string, matchArgs ...string) error { + checkArgs := append([]string{"-t", table, "-C", parent}, matchArgs...) + checkArgs = append(checkArgs, "-j", chain) + if exec.Command("iptables", checkArgs...).Run() == nil { + return nil + } + insArgs := append([]string{"-t", table, "-I", parent, "1"}, matchArgs...) + insArgs = append(insArgs, "-j", chain) + return runCmd("iptables", insArgs...) +} + +func ensureChain(table, chain string) error { + _ = exec.Command("iptables", "-t", table, "-N", chain).Run() + return runCmd("iptables", "-t", table, "-F", chain) +} + +// applyIPTables installs transparent TCP/DNS/UDP interception and anti-bypass +// egress lockdown rules scoped strictly to the sandbox bridge interface. +func applyIPTables(cfg iptablesConfig) error { + br := cfg.BridgeName + if br == "" { + return fmt.Errorf("bridge name is empty") + } + subnet := strings.TrimSpace(cfg.Subnet) + if subnet == "" { + subnet = "172.30.0.0/16" + } + + // 1. Policy routing for UDP TPROXY (fwmark 0x218 -> local table 218). + if cfg.UDPPort > 0 { + runCmdIgnoreErr("ip", "rule", "del", "fwmark", tproxyMark, "lookup", tproxyTable) + if err := runCmd("ip", "rule", "add", "fwmark", tproxyMark, "lookup", tproxyTable); err != nil { + log.Printf("[gateway] warn: ip rule for UDP TPROXY failed (TCP/DNS still active): %v", err) + } else { + if err := runCmd("ip", "route", "replace", "local", "0.0.0.0/0", "dev", "lo", "table", tproxyTable); err != nil { + log.Printf("[gateway] warn: ip route local for UDP TPROXY failed: %v", err) + } + } + } + + // 2. NAT PREROUTING: redirect ALL DNS (UDP/TCP 53) and ALL non-sandbox TCP to gateway. + if err := ensureChain("nat", chainNAT); err != nil { + return err + } + // Allow explicit HTTP MITM proxy traffic straight to ARTEX (:8788) inside the sandbox subnet + // so Phase 2 Proxy-Authorization tags and SNAT-free attribution keep working. + if cfg.ProxyPort > 0 { + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.ProxyPort), "-j", "RETURN"); err != nil { + return err + } + } + // Never redirect :8787 admin traffic (explicitly rejected by INPUT / DOCKER-USER). + if cfg.AdminPort > 0 { + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "RETURN"); err != nil { + return err + } + } + // Intercept ALL DNS queries (both to bridge gateway and to external DNS like 8.8.8.8:53). + if cfg.DNSPort > 0 { + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-p", "udp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil { + return err + } + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-p", "tcp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil { + return err + } + } + // Intercept ALL external TCP traffic (HTTP, HTTPS, SSH, MySQL, Redis, nmap -sT, nc, raw sockets). + if cfg.TCPPort > 0 { + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-p", "tcp", "!", "-d", subnet, "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.TCPPort)); err != nil { + return err + } + } + if err := ensureJump("nat", "PREROUTING", chainNAT, "-i", br); err != nil { + return err + } + + // 3. MANGLE PREROUTING: TPROXY all non-DNS external UDP packets to gateway UDP listener. + if cfg.UDPPort > 0 { + if err := ensureChain("mangle", chainMangle); err != nil { + log.Printf("[gateway] warn: create mangle chain failed: %v", err) + } else { + _ = runCmd("iptables", "-t", "mangle", "-A", chainMangle, "-d", subnet, "-j", "RETURN") + _ = runCmd("iptables", "-t", "mangle", "-A", chainMangle, "-p", "udp", "--dport", "53", "-j", "RETURN") + if err := runCmd("iptables", "-t", "mangle", "-A", chainMangle, + "-p", "udp", "-j", "TPROXY", "--on-port", strconv.Itoa(cfg.UDPPort), + "--on-ip", "127.0.0.1", "--tproxy-mark", tproxyMark+"/"+tproxyMark); err != nil { + log.Printf("[gateway] warn: UDP TPROXY rule failed (TCP/DNS unaffected): %v", err) + } else { + _ = ensureJump("mangle", "PREROUTING", chainMangle, "-i", br) + } + } + } + + // 4. INPUT: allow redirected gateway listeners on sandbox bridge, reject :8787 admin port. + if err := ensureChain("filter", chainInput); err != nil { + return err + } + if cfg.AdminPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT") + } + if cfg.TCPPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.TCPPort), "-j", "ACCEPT") + } + if cfg.DNSPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT") + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT") + } + if cfg.UDPPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.UDPPort), "-j", "ACCEPT") + } + if err := ensureJump("filter", "INPUT", chainInput, "-i", br); err != nil { + return err + } + + // 5. DOCKER-USER: hard anti-bypass kill switch. Any packet from the sandbox bridge + // trying to leave to another interface (direct NAT egress, artex-internal, metadata) + // is REJECTED so sandbox containers can NEVER bypass the transparent gateway. + if err := ensureChain("filter", chainFwd); err != nil { + return err + } + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-d", "169.254.169.254/32", "-j", "REJECT") + if cfg.AdminPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT") + } + // Reject any packet leaving the sandbox bridge to the outside / other Docker networks. + if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-o", br, "-j", "REJECT"); err != nil { + return err + } + if err := ensureJump("filter", "DOCKER-USER", chainFwd, "-i", br); err != nil { + log.Printf("[gateway] warn: attach DOCKER-USER failed (chain may not exist yet): %v", err) + } + + log.Printf("[gateway] iptables transparent interception active on bridge=%s subnet=%s tcp=:%d dns=:%d udp=:%d", + br, subnet, cfg.TCPPort, cfg.DNSPort, cfg.UDPPort) + return nil +} + +// cleanupIPTables removes all gateway-owned iptables jumps and chains on shutdown. +func cleanupIPTables(cfg iptablesConfig) { + br := cfg.BridgeName + if br != "" { + runCmdIgnoreErr("iptables", "-t", "nat", "-D", "PREROUTING", "-i", br, "-j", chainNAT) + runCmdIgnoreErr("iptables", "-t", "mangle", "-D", "PREROUTING", "-i", br, "-j", chainMangle) + runCmdIgnoreErr("iptables", "-t", "filter", "-D", "INPUT", "-i", br, "-j", chainInput) + runCmdIgnoreErr("iptables", "-t", "filter", "-D", "DOCKER-USER", "-i", br, "-j", chainFwd) + } + for _, tc := range [][2]string{ + {"nat", chainNAT}, + {"mangle", chainMangle}, + {"filter", chainInput}, + {"filter", chainFwd}, + } { + runCmdIgnoreErr("iptables", "-t", tc[0], "-F", tc[1]) + runCmdIgnoreErr("iptables", "-t", tc[0], "-X", tc[1]) + } + runCmdIgnoreErr("ip", "rule", "del", "fwmark", tproxyMark, "lookup", tproxyTable) + runCmdIgnoreErr("ip", "route", "flush", "table", tproxyTable) +} diff --git a/cmd/artex-gateway/iptables_other.go b/cmd/artex-gateway/iptables_other.go new file mode 100644 index 0000000..4cc21d1 --- /dev/null +++ b/cmd/artex-gateway/iptables_other.go @@ -0,0 +1,29 @@ +//go:build !linux + +package main + +import ( + "fmt" + "time" +) + +type iptablesConfig struct { + Subnet string + GatewayIP string + TCPPort int + UDPPort int + DNSPort int + ProxyPort int + AdminPort int + BridgeName string +} + +func discoverSandboxBridge(_, _ string, _ time.Duration) (string, error) { + return "", fmt.Errorf("iptables bridge discovery is only supported on Linux") +} + +func applyIPTables(_ iptablesConfig) error { + return fmt.Errorf("iptables transparent interception is only supported on Linux") +} + +func cleanupIPTables(_ iptablesConfig) {} diff --git a/cmd/artex-gateway/main.go b/cmd/artex-gateway/main.go new file mode 100644 index 0000000..e8e6a9b --- /dev/null +++ b/cmd/artex-gateway/main.go @@ -0,0 +1,315 @@ +// Command artex-gateway runs the dedicated transparent proxy gateway for ARTEX +// sandbox containers (#218 Phase 3). Only this lightweight container holds +// CAP_NET_ADMIN; sandbox containers remain non-root with CapDrop: ALL. +// +// In default TUN mode (ARTEX_GATEWAY_MODE=tun), all non-sandbox-subnet traffic +// from artex-sandbox is policy-routed into artex-tun0 and processed by gVisor +// netstack with deferred TCP handshakes so nmap/nc observe accurate open, +// closed (RST), and filtered (timeout) port states with zero false positives. +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "runtime" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/Autumn-27/artex/traffic" +) + +func envStr(key, def string) string { + if v := strings.TrimSpace(os.Getenv(key)); v != "" { + return v + } + return def +} + +func envInt(key string, def int) int { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return def + } + n, err := strconv.Atoi(raw) + if err != nil { + return def + } + return n +} + +func envBool(key string, def bool) bool { + raw := strings.ToLower(strings.TrimSpace(os.Getenv(key))) + if raw == "" { + return def + } + return raw == "1" || raw == "true" || raw == "yes" +} + +type eventBuffer struct { + mu sync.Mutex + netFlows []traffic.NetFlowRecord + dnsQueries []traffic.DNSQueryRecord + blockEvents []traffic.EgressBlockEvent +} + +func (b *eventBuffer) addFlow(r traffic.NetFlowRecord) { + b.mu.Lock() + if len(b.netFlows) < 2048 { + b.netFlows = append(b.netFlows, r) + } + b.mu.Unlock() +} + +func (b *eventBuffer) addDNS(r traffic.DNSQueryRecord) { + b.mu.Lock() + if len(b.dnsQueries) < 2048 { + b.dnsQueries = append(b.dnsQueries, r) + } + b.mu.Unlock() +} + +func (b *eventBuffer) addBlock(ev traffic.EgressBlockEvent) { + b.mu.Lock() + if len(b.blockEvents) < 512 { + b.blockEvents = append(b.blockEvents, ev) + } + b.mu.Unlock() +} + +func (b *eventBuffer) drain(gatewayID string) (traffic.GatewayEventBatch, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if len(b.netFlows) == 0 && len(b.dnsQueries) == 0 && len(b.blockEvents) == 0 { + return traffic.GatewayEventBatch{}, false + } + batch := traffic.GatewayEventBatch{ + GatewayID: gatewayID, + NetFlows: b.netFlows, + DNSQueries: b.dnsQueries, + BlockEvents: b.blockEvents, + } + b.netFlows = nil + b.dnsQueries = nil + b.blockEvents = nil + return batch, true +} + +func main() { + controlURL := strings.TrimRight(envStr("ARTEX_GATEWAY_CONTROL_URL", "http://127.0.0.1:8787"), "/") + mitmAddr := envStr("ARTEX_GATEWAY_MITM_ADDR", "127.0.0.1:8788") + token := envStr("ARTEX_GATEWAY_TOKEN", "") + subnet := envStr("ARTEX_SANDBOX_SUBNET", "172.30.0.0/16") + gatewayIP := envStr("ARTEX_SANDBOX_GATEWAY", "172.30.0.1") + mode := strings.ToLower(envStr("ARTEX_GATEWAY_MODE", "tun")) + tcpPort := envInt("ARTEX_GATEWAY_TCP_PORT", 15001) + udpPort := envInt("ARTEX_GATEWAY_UDP_PORT", 15002) + dnsPort := envInt("ARTEX_GATEWAY_DNS_PORT", 15053) + proxyPort := envInt("ARTEX_GATEWAY_MITM_PORT", 8788) + adminPort := envInt("ARTEX_GATEWAY_ADMIN_PORT", 8787) + dialTimeoutSec := envInt("ARTEX_GATEWAY_DIAL_TIMEOUT_S", 5) + applyRules := envBool("ARTEX_GATEWAY_APPLY_IPTABLES", runtime.GOOS == "linux") + gatewayID, _ := os.Hostname() + if gatewayID == "" { + gatewayID = "artex-gateway" + } + + buf := &eventBuffer{} + state := traffic.NewRemotePolicyState(token, buf.addFlow, buf.addDNS, buf.addBlock) + + httpClient := &http.Client{Timeout: 5 * time.Second} + syncPolicy := func() { + req, err := http.NewRequest(http.MethodGet, controlURL+"/api/internal/gateway/policy?gateway_id="+gatewayID, nil) + if err != nil { + return + } + if token != "" { + req.Header.Set("X-Artex-Gateway-Token", token) + } + resp, err := httpClient.Do(req) + if err != nil { + log.Printf("[gateway] policy sync failed: %v", err) + return + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + log.Printf("[gateway] policy sync HTTP %d", resp.StatusCode) + return + } + var snap traffic.GatewayPolicySnapshot + if err := json.NewDecoder(resp.Body).Decode(&snap); err != nil { + log.Printf("[gateway] policy decode failed: %v", err) + return + } + state.Apply(snap) + } + + flushEvents := func() { + batch, ok := buf.drain(gatewayID) + if !ok { + return + } + payload, err := json.Marshal(batch) + if err != nil { + return + } + req, err := http.NewRequest(http.MethodPost, controlURL+"/api/internal/gateway/events", bytes.NewReader(payload)) + if err != nil { + return + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("X-Artex-Gateway-Token", token) + } + resp, err := httpClient.Do(req) + if err != nil { + log.Printf("[gateway] flush events failed: %v", err) + return + } + _ = resp.Body.Close() + } + + // Initial policy fetch (best effort; retries continuously in background). + syncPolicy() + + var ( + gw *traffic.TransparentGateway + netstackGW *traffic.NetstackGateway + iptCfg iptablesConfig + tunModeActive bool + iptablesApplied bool + ) + + if mode == "tun" && runtime.GOOS == "linux" { + tunDev, tunErr := openTUN(tunDeviceName) + if tunErr != nil { + log.Printf("[gateway] warn: open TUN failed (%v); falling back to iptables REDIRECT mode", tunErr) + mode = "redirect" + } else { + ns, nsErr := traffic.NewNetstackGateway(tunDev, traffic.NetstackConfig{ + MITMProxyAddr: mitmAddr, + DialTimeout: time.Duration(dialTimeoutSec) * time.Second, + AllowedSrcCIDR: subnet, + DeniedSrcIPs: []string{gatewayIP}, + }, state) + if nsErr != nil { + _ = tunDev.Close() + log.Fatalf("[gateway] init netstack failed: %v", nsErr) + } + netstackGW = ns + tunModeActive = true + + // Also listen on DNS port (:15053) for bridge-gateway DNS queries (172.30.0.1:53). + gw = traffic.NewTransparentGateway(traffic.TransparentConfig{ + DNSAddr: fmt.Sprintf("0.0.0.0:%d", dnsPort), + MITMProxyAddr: mitmAddr, + }, state) + if err := gw.Start(); err != nil { + _ = netstackGW.Close() + log.Fatalf("[gateway] start dns listener failed: %v", err) + } + log.Printf("[gateway] mode=tun (gVisor netstack deferred-handshake) tun=%s dns=:%d mitm=%s control=%s", + tunDeviceName, dnsPort, mitmAddr, controlURL) + } + } + + if !tunModeActive { + gw = traffic.NewTransparentGateway(traffic.TransparentConfig{ + TCPAddr: fmt.Sprintf("0.0.0.0:%d", tcpPort), + DNSAddr: fmt.Sprintf("0.0.0.0:%d", dnsPort), + UDPAddr: fmt.Sprintf("0.0.0.0:%d", udpPort), + MITMProxyAddr: mitmAddr, + DialTimeout: time.Duration(dialTimeoutSec) * time.Second, + }, state) + if err := gw.Start(); err != nil { + log.Fatalf("[gateway] start failed: %v", err) + } + log.Printf("[gateway] mode=redirect listeners active tcp=:%d dns=:%d udp=:%d mitm=%s control=%s", + tcpPort, dnsPort, udpPort, mitmAddr, controlURL) + } + + if applyRules { + iptCfg = iptablesConfig{ + Subnet: subnet, + GatewayIP: gatewayIP, + TCPPort: tcpPort, + UDPPort: udpPort, + DNSPort: dnsPort, + ProxyPort: proxyPort, + AdminPort: adminPort, + } + br, err := discoverSandboxBridge(subnet, gatewayIP, 30*time.Second) + if err != nil { + log.Printf("[gateway] warn: %v (listeners running; check ARTEX_SANDBOX_SUBNET)", err) + } else { + iptCfg.BridgeName = br + if tunModeActive { + if err := applyTunRouting(iptCfg); err != nil { + log.Printf("[gateway] warn: apply TUN routing failed: %v", err) + } else { + iptablesApplied = true + } + } else { + if err := applyIPTables(iptCfg); err != nil { + log.Printf("[gateway] warn: apply iptables failed: %v", err) + } else { + iptablesApplied = true + } + } + } + } + // Start netstack TUN packet pumps AFTER applyTunRouting brings artex-tun0 UP. + if netstackGW != nil { + netstackGW.Start() + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + policyTicker := time.NewTicker(2 * time.Second) + flushTicker := time.NewTicker(500 * time.Millisecond) + routeTicker := time.NewTicker(15 * time.Second) + defer policyTicker.Stop() + defer flushTicker.Stop() + defer routeTicker.Stop() + + for { + select { + case <-ctx.Done(): + log.Println("[gateway] shutting down...") + if iptablesApplied { + if tunModeActive { + cleanupTunRouting(iptCfg) + } else { + cleanupIPTables(iptCfg) + } + } + if netstackGW != nil { + _ = netstackGW.Close() + } + if gw != nil { + _ = gw.Close() + } + flushEvents() + return + case <-policyTicker.C: + syncPolicy() + case <-flushTicker.C: + flushEvents() + case <-routeTicker.C: + if applyRules && tunModeActive { + if reconcileTunRouting(&iptCfg) { + iptablesApplied = true + } + } + } + } +} diff --git a/cmd/artex-gateway/tun_linux.go b/cmd/artex-gateway/tun_linux.go new file mode 100644 index 0000000..f31402e --- /dev/null +++ b/cmd/artex-gateway/tun_linux.go @@ -0,0 +1,299 @@ +//go:build linux + +package main + +import ( + "fmt" + "io" + "log" + "os" + "os/exec" + "strconv" + "strings" + "time" + "unsafe" + + "golang.org/x/sys/unix" +) + +const ( + tunDeviceName = "artex-tun0" + tunRouteTable = "218" + tunRulePrio = "218" + tunLinkIP = "198.18.0.1/32" +) + +type ifReq struct { + Name [unix.IFNAMSIZ]byte + Flags uint16 + _ [22]byte +} + +// openTUN creates a Linux TUN interface (IFF_TUN | IFF_NO_PI) named devName. +// Perform open + TUNSETIFF + SetNonblock(true) BEFORE wrapping with os.NewFile +// so Go's netpoller registers the fd AFTER the TUN device is bound and keeps +// O_NONBLOCK enabled (calling os.File.Fd() clears O_NONBLOCK and breaks epoll +// readiness on /dev/net/tun). +func openTUN(devName string) (io.ReadWriteCloser, error) { + fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_CLOEXEC, 0) + if err != nil { + return nil, fmt.Errorf("open /dev/net/tun: %w", err) + } + var req ifReq + copy(req.Name[:], devName) + req.Flags = unix.IFF_TUN | unix.IFF_NO_PI + _, _, errno := unix.Syscall( + unix.SYS_IOCTL, + uintptr(fd), + uintptr(unix.TUNSETIFF), + uintptr(unsafe.Pointer(&req)), + ) + if errno != 0 { + _ = unix.Close(fd) + return nil, fmt.Errorf("ioctl TUNSETIFF %s: %w", devName, errno) + } + if err := unix.SetNonblock(fd, true); err != nil { + _ = unix.Close(fd) + return nil, fmt.Errorf("setnonblock %s: %w", devName, err) + } + return os.NewFile(uintptr(fd), "/dev/net/tun"), nil +} + +// applyTunRouting configures policy routing and minimal anti-bypass iptables +// rules so ALL non-sandbox-subnet traffic from bridge br enters artex-tun0 +// without SNAT/MASQUERADE (preserving real sandbox container source IPs) and +// without TCP REDIRECT (preserving deferred-handshake open/closed/filtered semantics). +func applyTunRouting(cfg iptablesConfig) error { + br := cfg.BridgeName + if br == "" { + return fmt.Errorf("bridge name is empty") + } + subnet := strings.TrimSpace(cfg.Subnet) + if subnet == "" { + subnet = "172.30.0.0/16" + } + gwIP := strings.TrimSpace(cfg.GatewayIP) + if gwIP == "" { + gwIP = "172.30.0.1" + } + + // Clean any stale redirect/mangle rules from a prior gateway mode first. + cleanupIPTables(cfg) + + // 1. Bring up TUN interface and disable rp_filter so gVisor-spoofed reply + // packets from external IPs back to sandbox containers are never dropped. + if err := runCmd("ip", "link", "set", "dev", tunDeviceName, "mtu", "1500", "up"); err != nil { + return err + } + _ = runCmd("ip", "addr", "replace", tunLinkIP, "dev", tunDeviceName) + _ = os.WriteFile("/proc/sys/net/ipv4/conf/"+tunDeviceName+"/rp_filter", []byte("0\n"), 0o644) + _ = os.WriteFile("/proc/sys/net/ipv4/conf/"+br+"/rp_filter", []byte("0\n"), 0o644) + _ = os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1\n"), 0o644) + + // 2. Policy routing table 218: keep sandbox-subnet traffic on bridge, route + // everything else from sandbox bridge into artex-tun0. + if err := runCmd("ip", "route", "replace", subnet, "dev", br, "table", tunRouteTable); err != nil { + return err + } + if err := runCmd("ip", "route", "replace", "default", "dev", tunDeviceName, "table", tunRouteTable); err != nil { + return err + } + runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio) + if err := runCmd("ip", "rule", "add", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio); err != nil { + return err + } + + // 2b. Docker 28+ adds `raw PREROUTING ! -i
-d -j DROP` + // for every running container on a bridge. Reply packets written back by + // gVisor on artex-tun0 arrive with iif=artex-tun0 (!= br) destined for the + // sandbox subnet, so accept them at the top of raw PREROUTING. + if exec.Command("iptables", "-t", "raw", "-C", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT").Run() != nil { + if err := runCmd("iptables", "-t", "raw", "-I", "PREROUTING", "1", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT"); err != nil { + return err + } + } + // 3. Exempt artex-tun0 from Docker's NAT POSTROUTING MASQUERADE rule so + // packets entering netstack retain each sandbox container's real source IP. + if exec.Command("iptables", "-t", "nat", "-C", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT").Run() != nil { + if err := runCmd("iptables", "-t", "nat", "-I", "POSTROUTING", "1", "-o", tunDeviceName, "-j", "ACCEPT"); err != nil { + return err + } + } + + // 4. NAT PREROUTING: ONLY redirect DNS queries addressed directly to the + // bridge gateway IP (Docker embedded DNS 127.0.0.11 -> 172.30.0.1:53) to + // our DNS listener (:15053). External DNS (@8.8.8.8) and all external TCP/UDP + // flow natively into artex-tun0 without REDIRECT. + if cfg.DNSPort > 0 { + if err := ensureChain("nat", chainNAT); err != nil { + return err + } + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-d", gwIP+"/32", "-p", "udp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil { + return err + } + if err := runCmd("iptables", "-t", "nat", "-A", chainNAT, + "-d", gwIP+"/32", "-p", "tcp", "--dport", "53", "-j", "REDIRECT", "--to-ports", strconv.Itoa(cfg.DNSPort)); err != nil { + return err + } + if err := ensureJump("nat", "PREROUTING", chainNAT, "-i", br); err != nil { + return err + } + } + + // 5. INPUT: block :8787 admin port from sandbox bridge, accept bridge DNS (:15053). + if err := ensureChain("filter", chainInput); err != nil { + return err + } + // Anti-spoofing: reject packets from the sandbox bridge claiming a source IP + // outside the sandbox subnet or impersonating the bridge gateway IP. + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "!", "-s", subnet, "-j", "DROP") + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-s", gwIP+"/32", "-j", "DROP") + if cfg.AdminPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT") + } + if cfg.DNSPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "udp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT") + _ = runCmd("iptables", "-t", "filter", "-A", chainInput, "-p", "tcp", "--dport", strconv.Itoa(cfg.DNSPort), "-j", "ACCEPT") + } + if err := ensureJump("filter", "INPUT", chainInput, "-i", br); err != nil { + return err + } + + // 6. DOCKER-USER: allow br <-> artex-tun0 and explicit proxy :8788; reject + // spoofed source IPs (CAP_NET_RAW mitigation), cloud metadata, :8787, and any + // direct NAT bypass off the sandbox bridge. + if err := ensureChain("filter", chainFwd); err != nil { + return err + } + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-s", subnet, "-j", "DROP") + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-s", gwIP+"/32", "-j", "DROP") + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-d", "169.254.169.254/32", "-j", "REJECT") + if cfg.AdminPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-p", "tcp", "--dport", strconv.Itoa(cfg.AdminPort), "-j", "REJECT") + } + if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", tunDeviceName, "-j", "ACCEPT"); err != nil { + return err + } + if cfg.ProxyPort > 0 { + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", br, "-d", subnet, "-p", "tcp", "--dport", strconv.Itoa(cfg.ProxyPort), "-j", "ACCEPT") + _ = runCmd("iptables", "-t", "filter", "-A", chainFwd, "-o", br, "-s", subnet, "-m", "conntrack", "--ctstate", "ESTABLISHED,RELATED", "-j", "ACCEPT") + } + if err := runCmd("iptables", "-t", "filter", "-A", chainFwd, "!", "-o", br, "-j", "REJECT"); err != nil { + return err + } + // Ensure reply packets from artex-tun0 back to sandbox containers are accepted before DOCKER-ISOLATION. + if exec.Command("iptables", "-t", "filter", "-C", "DOCKER-USER", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT").Run() != nil { + _ = runCmd("iptables", "-t", "filter", "-I", "DOCKER-USER", "1", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT") + } + if err := ensureJump("filter", "DOCKER-USER", chainFwd, "-i", br); err != nil { + log.Printf("[gateway] warn: attach DOCKER-USER failed: %v", err) + } + + log.Printf("[gateway] TUN + gVisor netstack routing active bridge=%s tun=%s subnet=%s dns=:%d", + br, tunDeviceName, subnet, cfg.DNSPort) + return nil +} + +// rawPreroutingTopAcceptsTun reports whether the first rule in raw PREROUTING +// (immediately after the chain policy) accepts inbound artex-tun0 packets for subnet. +func rawPreroutingTopAcceptsTun(rawRules, tunDev, subnet string) bool { + for _, line := range strings.Split(rawRules, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "-P ") || strings.HasPrefix(line, "#") { + continue + } + return strings.HasPrefix(line, "-A PREROUTING ") && + strings.Contains(line, "-i "+tunDev+" ") && + strings.Contains(line, "-d "+subnet+" ") && + strings.HasSuffix(line, "-j ACCEPT") + } + return false +} + +// reconcileTunRouting verifies policy routing and critical anti-drop iptables +// rules stay intact while the gateway is running (guarding against systemd-networkd +// / netplan rule flushes or Docker inserting raw PREROUTING DROP rules above us). +// Returns true when routing is active for cfg.BridgeName. +func reconcileTunRouting(cfg *iptablesConfig) bool { + if cfg == nil { + return false + } + subnet := strings.TrimSpace(cfg.Subnet) + if subnet == "" { + subnet = "172.30.0.0/16" + } + gwIP := strings.TrimSpace(cfg.GatewayIP) + if gwIP == "" { + gwIP = "172.30.0.1" + } + if curBr, err := discoverSandboxBridge(subnet, gwIP, 2*time.Second); err == nil && curBr != "" && curBr != cfg.BridgeName { + log.Printf("[gateway] sandbox bridge changed %q -> %q; reapplying TUN routing", cfg.BridgeName, curBr) + if cfg.BridgeName != "" { + cleanupTunRouting(*cfg) + } + cfg.BridgeName = curBr + if err := applyTunRouting(*cfg); err != nil { + log.Printf("[gateway] warn: reapply TUN routing failed: %v", err) + return false + } + return true + } + br := cfg.BridgeName + if br == "" { + return false + } + + // 1. Ensure policy rule priority 218 and route table 218 still exist. + ruleOut, _ := exec.Command("ip", "rule", "show", "priority", tunRulePrio).Output() + if !strings.Contains(string(ruleOut), "iif "+br) || !strings.Contains(string(ruleOut), "lookup "+tunRouteTable) { + _ = runCmd("ip", "link", "set", "dev", tunDeviceName, "mtu", "1500", "up") + _ = runCmd("ip", "addr", "replace", tunLinkIP, "dev", tunDeviceName) + _ = os.WriteFile("/proc/sys/net/ipv4/conf/"+tunDeviceName+"/rp_filter", []byte("0\n"), 0o644) + _ = os.WriteFile("/proc/sys/net/ipv4/conf/"+br+"/rp_filter", []byte("0\n"), 0o644) + _ = runCmd("ip", "route", "replace", subnet, "dev", br, "table", tunRouteTable) + _ = runCmd("ip", "route", "replace", "default", "dev", tunDeviceName, "table", tunRouteTable) + runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio) + if err := runCmd("ip", "rule", "add", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio); err != nil { + log.Printf("[gateway] warn: restore ip rule %s failed: %v", tunRulePrio, err) + } else { + log.Printf("[gateway] restored missing policy routing rule priority=%s bridge=%s", tunRulePrio, br) + } + } + + // 2. Ensure raw PREROUTING top rule still accepts artex-tun0 -> subnet replies. + rawOut, err := exec.Command("iptables", "-t", "raw", "-S", "PREROUTING").Output() + if err == nil && !rawPreroutingTopAcceptsTun(string(rawOut), tunDeviceName, subnet) { + runCmdIgnoreErr("iptables", "-t", "raw", "-D", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT") + if err := runCmd("iptables", "-t", "raw", "-I", "PREROUTING", "1", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT"); err != nil { + log.Printf("[gateway] warn: restore raw PREROUTING rule failed: %v", err) + } else { + log.Printf("[gateway] restored raw PREROUTING top ACCEPT for %s -> %s", tunDeviceName, subnet) + } + } + + // 3. Ensure nat POSTROUTING exemption and DOCKER-USER reply accept exist. + if exec.Command("iptables", "-t", "nat", "-C", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT").Run() != nil { + _ = runCmd("iptables", "-t", "nat", "-I", "POSTROUTING", "1", "-o", tunDeviceName, "-j", "ACCEPT") + } + if exec.Command("iptables", "-t", "filter", "-C", "DOCKER-USER", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT").Run() != nil { + _ = runCmd("iptables", "-t", "filter", "-I", "DOCKER-USER", "1", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT") + } + return true +} + +func cleanupTunRouting(cfg iptablesConfig) { + br := cfg.BridgeName + if br != "" { + runCmdIgnoreErr("ip", "rule", "del", "iif", br, "lookup", tunRouteTable, "priority", tunRulePrio) + runCmdIgnoreErr("iptables", "-t", "filter", "-D", "DOCKER-USER", "-i", tunDeviceName, "-o", br, "-j", "ACCEPT") + } + runCmdIgnoreErr("ip", "route", "flush", "table", tunRouteTable) + runCmdIgnoreErr("iptables", "-t", "nat", "-D", "POSTROUTING", "-o", tunDeviceName, "-j", "ACCEPT") + subnet := strings.TrimSpace(cfg.Subnet) + if subnet == "" { + subnet = "172.30.0.0/16" + } + runCmdIgnoreErr("iptables", "-t", "raw", "-D", "PREROUTING", "-i", tunDeviceName, "-d", subnet, "-j", "ACCEPT") + cleanupIPTables(cfg) +} diff --git a/cmd/artex-gateway/tun_linux_test.go b/cmd/artex-gateway/tun_linux_test.go new file mode 100644 index 0000000..6e1a040 --- /dev/null +++ b/cmd/artex-gateway/tun_linux_test.go @@ -0,0 +1,31 @@ +//go:build linux + +package main + +import "testing" + +func TestRawPreroutingTopAcceptsTun(t *testing.T) { + topOK := `-P PREROUTING ACCEPT +-A PREROUTING -d 172.30.0.0/16 -i artex-tun0 -j ACCEPT +-A PREROUTING -d 172.30.0.2/32 ! -i br-25277657432c -j DROP +` + if !rawPreroutingTopAcceptsTun(topOK, "artex-tun0", "172.30.0.0/16") { + t.Fatal("expected top ACCEPT rule to be recognized") + } + + dropAbove := `# Warning: iptables-legacy tables present +-P PREROUTING ACCEPT +-A PREROUTING -d 172.30.0.3/32 ! -i br-25277657432c -j DROP +-A PREROUTING -d 172.30.0.0/16 -i artex-tun0 -j ACCEPT +` + if rawPreroutingTopAcceptsTun(dropAbove, "artex-tun0", "172.30.0.0/16") { + t.Fatal("expected DROP rule above ACCEPT to fail top check") + } + + missing := `-P PREROUTING ACCEPT +-A PREROUTING -d 172.30.0.2/32 ! -i br-25277657432c -j DROP +` + if rawPreroutingTopAcceptsTun(missing, "artex-tun0", "172.30.0.0/16") { + t.Fatal("expected missing rule to fail top check") + } +} diff --git a/cmd/artex-gateway/tun_other.go b/cmd/artex-gateway/tun_other.go new file mode 100644 index 0000000..5454be3 --- /dev/null +++ b/cmd/artex-gateway/tun_other.go @@ -0,0 +1,20 @@ +//go:build !linux + +package main + +import ( + "fmt" + "io" +) + +const tunDeviceName = "artex-tun0" + +func openTUN(_ string) (io.ReadWriteCloser, error) { + return nil, fmt.Errorf("TUN interface is only supported on Linux") +} + +func applyTunRouting(_ iptablesConfig) error { + return fmt.Errorf("TUN policy routing is only supported on Linux") +} +func reconcileTunRouting(_ *iptablesConfig) bool { return false } +func cleanupTunRouting(_ iptablesConfig) {} diff --git a/db/chat_mentions.go b/db/chat_mentions.go index f37f030..a0ceedd 100644 --- a/db/chat_mentions.go +++ b/db/chat_mentions.go @@ -34,7 +34,7 @@ type chatMentionCursor struct { func ValidChatMentionKind(kind string) bool { switch kind { - case "finding", "company", "asset", "endpoint", "ip", "app", "root_domain", "subdomain", "service": + case "task", "schedule", "finding", "company", "asset", "endpoint", "ip", "app", "root_domain", "subdomain", "service": return true } return false @@ -68,6 +68,29 @@ func (d *DB) SearchChatMentionsPage(ctx context.Context, kind, query, cursor str pattern := "%" + strings.NewReplacer(`\`, `\\`, "%", `\%`, "_", `\_`).Replace(query) + "%" rows, err := d.QueryContext(ctx, ` SELECT kind, id, left(label, 160), left(description, 240) FROM ( + (SELECT 'task' AS kind, id, + COALESCE(NULLIF(name,''), NULLIF(description,''), '任务 #'||id::text) AS label, + concat_ws(' · ', status, NULLIF(left(goal, 160), ''), NULLIF(left(description, 120), '')) AS description + FROM tasks WHERE deleted_at IS NULL AND ($1='' OR $1='task') AND + ($2='' OR id::text=$2 OR concat_ws(' ', name, description, goal, remark) ILIKE $3) + AND ($4::bigint=0 OR (id::text=$2)<$6 OR ((id::text=$2)=$6 AND (id<$4 OR (id=$4 AND 'task'>$5)))) + ORDER BY (id::text=$2) DESC, id DESC LIMIT 21) + UNION ALL + (SELECT 'schedule' AS kind, id, + COALESCE(NULLIF(name,''), '计划任务 #'||id::text) AS label, + concat_ws(' · ', + status, + CASE WHEN schedule_type='once' + THEN concat_ws(' ~ ', to_char(run_date,'YYYY-MM-DD'), to_char(end_date,'YYYY-MM-DD')) + ELSE 'weekly:'||weekdays END, + to_char(start_time,'HH24:MI') || CASE WHEN end_time IS NOT NULL THEN '-'||to_char(end_time,'HH24:MI') ELSE '+' END, + NULLIF(left(remark, 120), '') + ) AS description + FROM task_schedules WHERE ($1='' OR $1='schedule') AND + ($2='' OR id::text=$2 OR concat_ws(' ', name, remark, schedule_type, status) ILIKE $3) + AND ($4::bigint=0 OR (id::text=$2)<$6 OR ((id::text=$2)=$6 AND (id<$4 OR (id=$4 AND 'schedule'>$5)))) + ORDER BY (id::text=$2) DESC, id DESC LIMIT 21) + UNION ALL (SELECT 'finding' AS kind, id, COALESCE(NULLIF(name,''), vulnclass) AS label, concat_ws(' · ', severity, status, left(summary, 160)) AS description FROM findings WHERE ($1='' OR $1='finding') AND diff --git a/db/conversation.go b/db/conversation.go index 48ede2a..40ad19d 100644 --- a/db/conversation.go +++ b/db/conversation.go @@ -50,14 +50,16 @@ GROUP BY c.id`) // Conversation is one ChatGPT-style chat thread bound to an agent key. It lives // independent of the pentest exploration graph — see schema.sql §I. type Conversation struct { - ID int64 `json:"id"` - AgentKey string `json:"agent_key"` - Title string `json:"title"` - LLMProfileID *int64 `json:"llm_profile_id,omitempty"` - Pinned bool `json:"pinned"` - PinnedAt *time.Time `json:"pinned_at,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID int64 `json:"id"` + AgentKey string `json:"agent_key"` + Title string `json:"title"` + LLMProfileID *int64 `json:"llm_profile_id,omitempty"` + Pinned bool `json:"pinned"` + PinnedAt *time.Time `json:"pinned_at,omitempty"` + SandboxScope string `json:"sandbox_scope"` + SandboxOwnerID string `json:"sandbox_owner_id"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // ConversationPatch updates only the fields whose pointers are non-nil. @@ -66,12 +68,12 @@ type ConversationPatch struct { Pinned *bool } -const convCols = `id, agent_key, title, llm_profile_id, pinned_at, created_at, updated_at` +const convCols = `id, agent_key, title, llm_profile_id, pinned_at, created_at, updated_at, sandbox_scope, sandbox_owner_id` func scanConv(row interface{ Scan(...any) error }) (Conversation, error) { var c Conversation var pinnedAt sql.NullTime - err := row.Scan(&c.ID, &c.AgentKey, &c.Title, &c.LLMProfileID, &pinnedAt, &c.CreatedAt, &c.UpdatedAt) + err := row.Scan(&c.ID, &c.AgentKey, &c.Title, &c.LLMProfileID, &pinnedAt, &c.CreatedAt, &c.UpdatedAt, &c.SandboxScope, &c.SandboxOwnerID) if pinnedAt.Valid { c.Pinned = true c.PinnedAt = &pinnedAt.Time @@ -206,6 +208,46 @@ WHERE id=$1 AND title IN ('', '新对话', $3)`, id, title, initial) return err } +// SetConversationSandbox records which sandbox container this conversation's +// commands actually run in. scope is "task" or "session". +func (d *DB) SetConversationSandbox(id int64, scope, ownerID string) error { + _, err := d.Exec(`UPDATE conversations SET sandbox_scope=$2, sandbox_owner_id=$3 WHERE id=$1`, id, scope, ownerID) + return err +} + +// ReportTaskSandboxFallbacks maps a conversation to the single task that owns +// every finding whose report was written in that conversation. Conversations +// with no such finding, a null task, or more than one task are omitted. +func (d *DB) ReportTaskSandboxFallbacks(convIDs []int64) (map[int64]int64, error) { + out := map[int64]int64{} + if len(convIDs) == 0 { + return out, nil + } + rows, err := d.Query(` +SELECT report_conversation_id, + COUNT(DISTINCT task_id) FILTER (WHERE task_id IS NOT NULL), + COUNT(*) FILTER (WHERE task_id IS NULL), + MIN(task_id) FILTER (WHERE task_id IS NOT NULL) +FROM findings +WHERE report_conversation_id = ANY($1::bigint[]) +GROUP BY report_conversation_id`, convIDs) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var convID, distinctTasks, nullTasks int64 + var taskID sql.NullInt64 + if err := rows.Scan(&convID, &distinctTasks, &nullTasks, &taskID); err != nil { + return nil, err + } + if distinctTasks == 1 && nullTasks == 0 && taskID.Valid && taskID.Int64 > 0 { + out[convID] = taskID.Int64 + } + } + return out, rows.Err() +} + // TouchConversation bumps updated_at so the thread floats to the top of the list. func (d *DB) TouchConversation(id int64) error { _, err := d.Exec(`UPDATE conversations SET updated_at=now() WHERE id=$1`, id) diff --git a/db/conversation_sandbox_test.go b/db/conversation_sandbox_test.go new file mode 100644 index 0000000..de0c011 --- /dev/null +++ b/db/conversation_sandbox_test.go @@ -0,0 +1,105 @@ +package db + +import ( + "strconv" + "testing" +) + +func TestConversationSandboxBindingAndFindingFallback(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + t.Skipf("postgres unavailable (%v) — skipping", err) + } + defer d.Close() + + taskA, err := d.CreateTask("sandbox-fallback-a", "goal", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + taskB, err := d.CreateTask("sandbox-fallback-b", "goal", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + reporter, err := d.CreateConversation("reporter", "single-task report", nil) + if err != nil { + t.Fatal(err) + } + mixed, err := d.CreateConversation("reporter", "mixed-task report", nil) + if err != nil { + t.Fatal(err) + } + plain, err := d.CreateConversation("auto", "plain chat", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = d.Exec(`DELETE FROM findings WHERE task_id IN ($1,$2)`, taskA.ID, taskB.ID) + _, _ = d.Exec(`DELETE FROM conversations WHERE id IN ($1,$2,$3)`, reporter.ID, mixed.ID, plain.ID) + _ = d.DeleteTask(taskA.ID) + _ = d.DeleteTask(taskB.ID) + }) + + if reporter.SandboxScope != "" || reporter.SandboxOwnerID != "" { + t.Fatalf("new conversation should not have a sandbox binding: %+v", reporter) + } + if err := d.SetConversationSandbox(plain.ID, "session", "conv-"+strconv.FormatInt(plain.ID, 10)); err != nil { + t.Fatal(err) + } + got, err := d.GetConversation(plain.ID) + if err != nil || got == nil { + t.Fatal(err) + } + if got.SandboxScope != "session" || got.SandboxOwnerID != "conv-"+strconv.FormatInt(plain.ID, 10) { + t.Fatalf("stored session binding = %+v", got) + } + + add := func(taskID, convID int64) { + t.Helper() + fid, err := d.AddFinding(taskID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := d.SetFindingReportConversationID(fid, convID); err != nil { + t.Fatal(err) + } + } + add(taskA.ID, reporter.ID) + add(taskA.ID, reporter.ID) + add(taskA.ID, mixed.ID) + add(taskB.ID, mixed.ID) + + fallbacks, err := d.ReportTaskSandboxFallbacks([]int64{reporter.ID, mixed.ID, plain.ID}) + if err != nil { + t.Fatal(err) + } + if fallbacks[reporter.ID] != taskA.ID { + t.Fatalf("single-task report fallback = %d, want %d", fallbacks[reporter.ID], taskA.ID) + } + if _, ok := fallbacks[mixed.ID]; ok { + t.Fatalf("mixed tasks must not bind to one task: %+v", fallbacks) + } + if _, ok := fallbacks[plain.ID]; ok { + t.Fatalf("conversation without findings must not fall back: %+v", fallbacks) + } + + nullConv, err := d.CreateConversation("reporter", "null-task report", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM conversations WHERE id=$1`, nullConv.ID) }) + fid, err := d.AddFinding(0, 0, "xss", "name", "low", "summary", "evidence", "worker", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = d.DeleteFinding(fid) }) + if err := d.SetFindingReportConversationID(fid, nullConv.ID); err != nil { + t.Fatal(err) + } + fallbacks, err = d.ReportTaskSandboxFallbacks([]int64{nullConv.ID}) + if err != nil { + t.Fatal(err) + } + if _, ok := fallbacks[nullConv.ID]; ok { + t.Fatalf("null task_id must not fall back: %+v", fallbacks) + } +} diff --git a/db/schedules.go b/db/schedules.go index be0871e..cabe42c 100644 --- a/db/schedules.go +++ b/db/schedules.go @@ -24,6 +24,9 @@ type TaskSchedule struct { StartTime string `json:"start_time"` EndTime string `json:"end_time,omitempty"` StartImmediately bool `json:"start_immediately"` + ProxyMode string `json:"proxy_mode,omitempty"` + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` Status string `json:"status"` LastWindowKey string `json:"last_window_key,omitempty"` LastTransitionAt *time.Time `json:"last_transition_at,omitempty"` @@ -44,13 +47,16 @@ type TaskScheduleInput struct { StartTime string EndTime string StartImmediately bool + ProxyMode string + ProxyPoolID string + ProxyURL string TaskIDs []int64 } const scheduleCols = `id,name,remark,enabled,timezone_mode,schedule_type, COALESCE(to_char(run_date,'YYYY-MM-DD'),''),weekdays,to_char(start_time,'HH24:MI:SS'), COALESCE(to_char(end_date,'YYYY-MM-DD'),''), -COALESCE(to_char(end_time,'HH24:MI:SS'),''),start_immediately,status,last_window_key, +COALESCE(to_char(end_time,'HH24:MI:SS'),''),start_immediately,proxy_mode,proxy_pool_id,proxy_url,status,last_window_key, last_transition_at,last_error,created_at,updated_at` func marshalWeekdays(days []int) string { @@ -66,6 +72,7 @@ func scanSchedule(sc interface{ Scan(...any) error }) (*TaskSchedule, error) { var rawDays string if err := sc.Scan(&s.ID, &s.Name, &s.Remark, &s.Enabled, &s.TimezoneMode, &s.ScheduleType, &s.RunDate, &rawDays, &s.StartTime, &s.EndDate, &s.EndTime, &s.StartImmediately, + &s.ProxyMode, &s.ProxyPoolID, &s.ProxyURL, &s.Status, &s.LastWindowKey, &s.LastTransitionAt, &s.LastError, &s.CreatedAt, &s.UpdatedAt); err != nil { return nil, err @@ -144,6 +151,19 @@ func normalizeScheduleInput(in TaskScheduleInput) (TaskScheduleInput, error) { if len(in.TaskIDs) > 100 { return in, fmt.Errorf("最多选择100个任务") } + in.ProxyMode = strings.ToLower(strings.TrimSpace(in.ProxyMode)) + if in.ProxyMode == "" { + in.ProxyMode = "inherit" + } + if in.ProxyMode != "inherit" && in.ProxyMode != "direct" && in.ProxyMode != "pool" && in.ProxyMode != "proxy" { + return in, fmt.Errorf("计划任务代理模式无效") + } + in.ProxyPoolID = strings.TrimSpace(in.ProxyPoolID) + in.ProxyURL = strings.TrimSpace(in.ProxyURL) + if in.ProxyMode != "proxy" { + in.ProxyPoolID = "" + in.ProxyURL = "" + } return in, nil } @@ -172,9 +192,9 @@ func createTaskScheduleTxCommit(tx *sql.Tx, in TaskScheduleInput) (*TaskSchedule } func insertTaskSchedule(tx *sql.Tx, in TaskScheduleInput) (*TaskSchedule, error) { - row := tx.QueryRow(`INSERT INTO task_schedules(name,enabled,timezone_mode,schedule_type,run_date,end_date,weekdays,start_time,end_time,start_immediately) -VALUES ($1,$2,$3,$4,NULLIF($5,'')::date,NULLIF($6,'')::date,$7,$8::time,NULLIF($9,'')::time,$10) RETURNING `+scheduleCols, - in.Name, in.Enabled, in.TimezoneMode, in.ScheduleType, in.RunDate, in.EndDate, marshalWeekdays(in.Weekdays), in.StartTime, in.EndTime, in.StartImmediately) + row := tx.QueryRow(`INSERT INTO task_schedules(name,enabled,timezone_mode,schedule_type,run_date,end_date,weekdays,start_time,end_time,start_immediately,proxy_mode,proxy_pool_id,proxy_url) +VALUES ($1,$2,$3,$4,NULLIF($5,'')::date,NULLIF($6,'')::date,$7,$8::time,NULLIF($9,'')::time,$10,$11,$12,$13) RETURNING `+scheduleCols, + in.Name, in.Enabled, in.TimezoneMode, in.ScheduleType, in.RunDate, in.EndDate, marshalWeekdays(in.Weekdays), in.StartTime, in.EndTime, in.StartImmediately, in.ProxyMode, in.ProxyPoolID, in.ProxyURL) s, err := scanSchedule(row) if err != nil { return nil, err @@ -208,8 +228,8 @@ func (d *DB) UpdateTaskSchedule(id int64, in TaskScheduleInput) (*TaskSchedule, return nil, err } defer tx.Rollback() - row := tx.QueryRow(`UPDATE task_schedules SET name=$2,enabled=$3,timezone_mode=$4,schedule_type=$5,run_date=NULLIF($6,'')::date,end_date=NULLIF($7,'')::date,weekdays=$8,start_time=$9::time,end_time=NULLIF($10,'')::time,start_immediately=$11,status=CASE WHEN $3 THEN CASE WHEN status='completed' THEN 'waiting' ELSE status END ELSE 'paused' END,last_error='',last_window_key='' WHERE id=$1 RETURNING `+scheduleCols, - id, in.Name, in.Enabled, in.TimezoneMode, in.ScheduleType, in.RunDate, in.EndDate, marshalWeekdays(in.Weekdays), in.StartTime, in.EndTime, in.StartImmediately) + row := tx.QueryRow(`UPDATE task_schedules SET name=$2,enabled=$3,timezone_mode=$4,schedule_type=$5,run_date=NULLIF($6,'')::date,end_date=NULLIF($7,'')::date,weekdays=$8,start_time=$9::time,end_time=NULLIF($10,'')::time,start_immediately=$11,proxy_mode=$12,proxy_pool_id=$13,proxy_url=$14,status=CASE WHEN $3 THEN CASE WHEN status='completed' THEN 'waiting' ELSE status END ELSE 'paused' END,last_error='',last_window_key='' WHERE id=$1 RETURNING `+scheduleCols, + id, in.Name, in.Enabled, in.TimezoneMode, in.ScheduleType, in.RunDate, in.EndDate, marshalWeekdays(in.Weekdays), in.StartTime, in.EndTime, in.StartImmediately, in.ProxyMode, in.ProxyPoolID, in.ProxyURL) s, err := scanSchedule(row) if err != nil { return nil, err diff --git a/db/schema.sql b/db/schema.sql index c3b9321..4514fd6 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -987,10 +987,15 @@ CREATE TABLE IF NOT EXISTS conversations ( title TEXT NOT NULL DEFAULT '', llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL, pinned_at TIMESTAMPTZ, + -- 这条对话实际执行命令时使用的沙箱。空表示尚未写入,读取时再按漏洞报告回退。 + sandbox_scope TEXT NOT NULL DEFAULT '', + sandbox_owner_id TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); ALTER TABLE conversations ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ; +ALTER TABLE conversations ADD COLUMN IF NOT EXISTS sandbox_scope TEXT NOT NULL DEFAULT ''; +ALTER TABLE conversations ADD COLUMN IF NOT EXISTS sandbox_owner_id TEXT NOT NULL DEFAULT ''; CREATE INDEX IF NOT EXISTS idx_conversations_llm_profile ON conversations(llm_profile_id) WHERE llm_profile_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_conversations_pinned ON conversations(pinned_at DESC) WHERE pinned_at IS NOT NULL; DROP TRIGGER IF EXISTS trg_conversations_upd ON conversations; @@ -1088,6 +1093,9 @@ CREATE TABLE IF NOT EXISTS task_schedules ( CREATE INDEX IF NOT EXISTS idx_task_schedules_enabled ON task_schedules(enabled, id); ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS end_date DATE; ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS remark TEXT NOT NULL DEFAULT ''; +ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS proxy_mode TEXT NOT NULL DEFAULT 'inherit'; +ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS proxy_pool_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS proxy_url TEXT NOT NULL DEFAULT ''; DROP TRIGGER IF EXISTS trg_task_schedules_upd ON task_schedules; CREATE TRIGGER trg_task_schedules_upd BEFORE UPDATE ON task_schedules FOR EACH ROW EXECUTE FUNCTION set_updated_at(); diff --git a/docker-compose.yml b/docker-compose.yml index a15e18e..4905162 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,6 +7,8 @@ services: POSTGRES_DB: ${POSTGRES_DB:-artex} volumes: - pgdata:/var/lib/postgresql/data + networks: + - artex-internal healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-artex} -d ${POSTGRES_DB:-artex}"] interval: 5s @@ -14,16 +16,39 @@ services: retries: 10 restart: unless-stopped + # 收敛宿主机 Docker API 权限:只暴露沙箱容器管理所需的接口,不把完整宿主机 docker.sock 直接交给主服务。 + docker-socket-proxy: + image: ${ARTEX_DOCKER_PROXY_IMAGE:-tecnativa/docker-socket-proxy:latest} + environment: + CONTAINERS: 1 + EXEC: 1 + IMAGES: 1 + NETWORKS: 1 + INFO: 1 + PING: 1 + POST: 1 + ALLOW_START: 1 + ALLOW_STOP: 1 + ALLOW_RESTARTS: 1 + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + networks: + - artex-internal + restart: unless-stopped + artex: image: ${ARTEX_IMAGE:-ruoji6/artex}:${ARTEX_TAG:-latest} depends_on: postgres: condition: service_healthy + docker-socket-proxy: + condition: service_started environment: TZ: Asia/Shanghai ARTEX_PG_DSN: postgres://${POSTGRES_USER:-artex}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-artex}?sslmode=disable ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-} OPENAI_API_KEY: ${OPENAI_API_KEY:-} + GEMINI_API_KEY: ${GEMINI_API_KEY:-} ARTEX_LLM_PROVIDER: ${ARTEX_LLM_PROVIDER:-} ARTEX_LLM_MODEL: ${ARTEX_LLM_MODEL:-} ARTEX_LLM_BASE_URL: ${ARTEX_LLM_BASE_URL:-} @@ -32,9 +57,34 @@ services: ARTEX_TOOL_MEMORY_LIMIT_MB: ${ARTEX_TOOL_MEMORY_LIMIT_MB:-} ARTEX_TOOL_TIMEOUT_S: ${ARTEX_TOOL_TIMEOUT_S:-} ARTEX_TOOL_PIDS_LIMIT: ${ARTEX_TOOL_PIDS_LIMIT:-} + # 沙箱容器隔离配置(子 Agent 的 Bash / 文件 / 脚本 / Playwright 在独立容器内执行) + ARTEX_SANDBOX_MODE: ${ARTEX_SANDBOX_MODE:-docker} + ARTEX_DOCKER_HOST: ${ARTEX_DOCKER_HOST:-http://docker-socket-proxy:2375} + ARTEX_SANDBOX_IMAGE: ${ARTEX_SANDBOX_IMAGE:-ruoji6/artex-sandbox:latest} + ARTEX_SANDBOX_NETWORK: ${ARTEX_SANDBOX_NETWORK:-artex-sandbox} + ARTEX_SANDBOX_RUNTIME: ${ARTEX_SANDBOX_RUNTIME:-} + # auto 自动探测 artex-sandbox 网桥网关地址(如 http://172.30.0.1:8788),兼容 enable_icc=false + ARTEX_SANDBOX_PROXY_URL: ${ARTEX_SANDBOX_PROXY_URL:-auto} + ARTEX_HOST_DATA_DIR: ${ARTEX_HOST_DATA_DIR:?请在 .env 设置宿主机 ./data 绝对路径 ARTEX_HOST_DATA_DIR} + ARTEX_SANDBOX_MEMORY_MB: ${ARTEX_SANDBOX_MEMORY_MB:-2048} + ARTEX_SANDBOX_CPUS: ${ARTEX_SANDBOX_CPUS:-2} + ARTEX_SANDBOX_PIDS_LIMIT: ${ARTEX_SANDBOX_PIDS_LIMIT:-256} + ARTEX_SANDBOX_SHM_MB: ${ARTEX_SANDBOX_SHM_MB:-512} + ARTEX_SANDBOX_AUTO_STOP: ${ARTEX_SANDBOX_AUTO_STOP:-true} + ARTEX_SANDBOX_SESSION_IDLE_MIN: ${ARTEX_SANDBOX_SESSION_IDLE_MIN:-20} + # 允许沙箱内经 file-cap 授权的 nmap/nping/ping 使用 CAP_NET_RAW(普通进程 CapEff=0); + # 若运行不受信任的自定义镜像可设为 false 以强制开启 no-new-privileges:true + ARTEX_SANDBOX_ALLOW_NET_RAW: ${ARTEX_SANDBOX_ALLOW_NET_RAW:-true} + ARTEX_PROXY_BLOCK_PRIVATE: ${ARTEX_PROXY_BLOCK_PRIVATE:-false} + # 宿主机局域网地址。这些地址上的其他端口仍可扫描;:8787 / :8788 由抓包代理拒绝,避免沙箱借代理回连管理口。 + ARTEX_PROXY_PROTECT_IPS: ${ARTEX_PROXY_PROTECT_IPS:-} + # 全流量透明代理网关配置(#218 Phase 3:与 artex-gateway 共享鉴权令牌) + ARTEX_SANDBOX_TRANSPARENT: ${ARTEX_SANDBOX_TRANSPARENT:-true} + ARTEX_SANDBOX_DNS: ${ARTEX_SANDBOX_DNS:-} + ARTEX_GATEWAY_TOKEN: ${ARTEX_GATEWAY_TOKEN:-} ports: - "8787:8787" - - "127.0.0.1:8788:8788" + - "8788:8788" volumes: # 把数据目录(含 jwt.key、SQLite 等)绑定到项目根目录的 data/, # 方便在宿主机直接查看/备份,容器重建也不丢。 @@ -42,12 +92,68 @@ services: # 把项目根目录的 skills 挂进容器(覆盖镜像内置的 /app/skills); # 改 skill 无需重建镜像,容器读的就是宿主机这份。 - ./skills:/app/skills - # 容器级内存/进程上限,防止单个重工具(如 innoextract/7z/playwright/ffuf)打满宿主机内存并触发 swap 抖动。 - # memswap_limit 与 mem_limit 保持一致以禁止容器吃宿主机 swap;可通过 .env 中的 ARTEX_MEMORY_LIMIT / ARTEX_PIDS_LIMIT 调整。 - mem_limit: ${ARTEX_MEMORY_LIMIT:-4g} - memswap_limit: ${ARTEX_MEMORY_LIMIT:-4g} + networks: + - artex-internal + # 直接接入 artex-sandbox 二层网段以消除网桥 SNAT,让抓包代理拿到真实沙箱容器源 IP(#218)。 + # 需配合 scripts/artex-sandbox-firewall.sh 仅放行沙箱网桥到本容器 :8788,并阻断 :8787 管理口。 + - artex-sandbox + # 主服务已剥离重工具链,资源上限主要用于控制面进程 + mem_limit: ${ARTEX_MEMORY_LIMIT:-2g} + memswap_limit: ${ARTEX_MEMORY_LIMIT:-2g} pids_limit: ${ARTEX_PIDS_LIMIT:-512} restart: unless-stopped + # 独立透明代理网关(#218 Phase 3):仅本容器持有 CAP_NET_ADMIN,接管 artex-sandbox 网桥的 + # 全部 TCP / DNS / UDP 流量并阻断直连外网 NAT,沙箱容器继续保持非 root + CapDrop: ALL。 + artex-gateway: + image: ${ARTEX_GATEWAY_IMAGE:-ruoji6/artex-gateway}:${ARTEX_TAG:-latest} + build: + context: . + dockerfile: Dockerfile.gateway + depends_on: + artex: + condition: service_started + network_mode: host + cap_add: + - NET_ADMIN + - NET_RAW + devices: + - /dev/net/tun:/dev/net/tun + environment: + TZ: Asia/Shanghai + ARTEX_GATEWAY_CONTROL_URL: http://127.0.0.1:8787 + ARTEX_GATEWAY_MITM_ADDR: 127.0.0.1:8788 + ARTEX_GATEWAY_TOKEN: ${ARTEX_GATEWAY_TOKEN:-} + ARTEX_GATEWAY_MODE: ${ARTEX_GATEWAY_MODE:-tun} + ARTEX_SANDBOX_SUBNET: ${ARTEX_SANDBOX_SUBNET:-172.30.0.0/16} + ARTEX_SANDBOX_GATEWAY: ${ARTEX_SANDBOX_GATEWAY:-172.30.0.1} + ARTEX_GATEWAY_TCP_PORT: ${ARTEX_GATEWAY_TCP_PORT:-15001} + ARTEX_GATEWAY_UDP_PORT: ${ARTEX_GATEWAY_UDP_PORT:-15002} + ARTEX_GATEWAY_DNS_PORT: ${ARTEX_GATEWAY_DNS_PORT:-15053} + ARTEX_GATEWAY_APPLY_IPTABLES: ${ARTEX_GATEWAY_APPLY_IPTABLES:-true} + ulimits: + nofile: + soft: 65536 + hard: 65536 + mem_limit: 256m + pids_limit: 128 + restart: unless-stopped + +networks: + artex-internal: + driver: bridge + artex-sandbox: + name: ${ARTEX_SANDBOX_NETWORK:-artex-sandbox} + driver: bridge + ipam: + config: + - subnet: ${ARTEX_SANDBOX_SUBNET:-172.30.0.0/16} + gateway: ${ARTEX_SANDBOX_GATEWAY:-172.30.0.1} + driver_opts: + # 关闭沙箱容器间互通,防止被反制的任务容器横向攻击其他任务容器。 + # 沙箱经网桥网关访问宿主机上发布的 :8788 抓包代理。 + # 宿主机还需执行 scripts/artex-sandbox-firewall.sh,丢掉沙箱网桥到 :8787、 + # 内部网络(postgres / docker-socket-proxy)和 169.254.169.254 的直连。 + com.docker.network.bridge.enable_icc: "false" volumes: pgdata: diff --git a/go.mod b/go.mod index 35623da..d74a23a 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,9 @@ require ( github.com/projectdiscovery/dnsx v1.2.3 golang.org/x/crypto v0.58.0 golang.org/x/net v0.61.0 + golang.org/x/sys v0.49.0 golang.org/x/text v0.43.0 + gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 modernc.org/sqlite v1.52.0 mvdan.cc/sh/v3 v3.10.0 ) @@ -26,13 +28,13 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/gaissmai/bart v0.26.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/google/btree v1.1.2 // indirect github.com/gorilla/css v1.0.1 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - github.com/kr/pretty v0.3.1 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect @@ -43,18 +45,16 @@ require ( github.com/projectdiscovery/utils v0.7.3 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d // indirect - github.com/satori/go.uuid v1.2.0 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.2.0 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39 // indirect - go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect + golang.org/x/time v0.12.0 // indirect golang.org/x/tools v0.51.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.72.3 // indirect diff --git a/go.sum b/go.sum index 5058fdc..40a2b36 100644 --- a/go.sum +++ b/go.sum @@ -6,7 +6,6 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -16,12 +15,16 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/gaissmai/bart v0.26.0 h1:xOZ57E9hJLBiQaSyeZa9wgWhGuzfGACgqp4BE77OkO0= github.com/gaissmai/bart v0.26.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c= +github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= +github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -58,7 +61,6 @@ github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -76,13 +78,10 @@ github.com/projectdiscovery/utils v0.7.3 h1:kX+77AA58yK6EZgkTRJEnK9V/7AZYzlXdcu/ github.com/projectdiscovery/utils v0.7.3/go.mod h1:uDdQ3/VWomai98l+a3Ye/srDXdJ4xUIar/mSXlQ9gBM= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d h1:hrujxIzL1woJ7AwssoOcM/tq5JjjG2yYOc8odClEiXA= github.com/saintfish/chardet v0.0.0-20230101081208-5e3ef4b5456d/go.mod h1:uugorj2VCxiV1x+LzaIdVa9b4S4qGAcH6cbhh4qVxOU= -github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -102,39 +101,25 @@ github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39 h1:Bz/zV github.com/weppos/publicsuffix-go v0.40.3-0.20250408071509-6074bbe7fd39/go.mod h1:2oFzEwGYI7lhiqG0YkkcKa6VcpjVinQbWxaPzytDmLA= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= -golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA= golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= -golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs= -golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= -golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= -golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -143,6 +128,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 h1:Zy8IV/+FMLxy6j6p87vk/vQGKcdnbprwjTxc8UiUtsA= +gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8/go.mod h1:QkHjoMIBaYtpVufgwv3keYAbln78mBoCuShZrPrer1Q= modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY= modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ= diff --git a/install.sh b/install.sh index d23ae0b..4ee5576 100755 --- a/install.sh +++ b/install.sh @@ -1,14 +1,17 @@ #!/usr/bin/env bash -# ARTEX 安装脚本:① 全部 Docker ② 本地编译运行 +# ARTEX 安装脚本: +# 1) Docker 部署(推荐:独立沙箱容器 + 全流量透明网关 + 出口代理控制) +# 2) 本地编译运行(Go 编译) +# +# 非交互用法示例: +# ./install.sh --docker --yes +# ./install.sh --docker --tag v0.3.33 --yes +# ./install.sh --local set -euo pipefail cd "$(cd "$(dirname "$0")" && pwd)" -info(){ printf '\033[36m[*]\033[0m %s\n' "$*"; } -ok(){ printf '\033[32m[+]\033[0m %s\n' "$*"; } -warn(){ printf '\033[33m[!]\033[0m %s\n' "$*"; } -die(){ printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; } -ask(){ local p="$1" d="${2:-}" a; read -rp "$p${d:+ [$d]}: " a; echo "${a:-$d}"; } -rand(){ head -c 18 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 24; } +# shellcheck source=scripts/deploy-lib.sh +. ./scripts/deploy-lib.sh # ── docker 环境检测 / 自动安装 ─────────────────── ensure_docker(){ @@ -30,27 +33,32 @@ ensure_docker(){ esac } -# ── ① 全部 Docker ─────────────────────────────── +# ── ① Docker 部署 ─────────────────────────────────────────────── install_docker(){ + local tag="${1:-}" ensure_docker + preflight_docker + umask 077 - if [ ! -f .env ]; then - cp .env.example .env 2>/dev/null || true - local pw key - pw="$(ask 'Postgres 密码(回车随机生成)' "$(rand)")" + local is_fresh=0 + [ -f .env ] || is_fresh=1 + + prepare_env_for_docker "$tag" .env + + if [ "$is_fresh" -eq 1 ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then + local key key="$(ask 'ANTHROPIC_API_KEY(可留空,后续在 UI 配)' '')" - sed -i.bak "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${pw}|" .env - sed -i.bak "s|^ANTHROPIC_API_KEY=.*|ANTHROPIC_API_KEY=${key}|" .env - rm -f .env.bak - ok "已生成 .env(POSTGRES_PASSWORD 已设置)" - else - info "沿用已存在的 .env" + [ -n "$key" ] && env_set ANTHROPIC_API_KEY "$key" .env fi - info "拉取镜像并启动…" - docker compose pull - docker compose up -d + + pull_docker_images + info "启动服务(${COMPOSE_FILE})…" + docker compose -f "$COMPOSE_FILE" up -d --remove-orphans + wait_for_health "$COMPOSE_FILE" || warn "服务仍在启动中,请执行 docker compose -f ${COMPOSE_FILE} logs -f artex 观察" + ok "启动完成 → http://localhost:8787" - info "查看日志:docker compose logs -f artex" + info "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex" + info "后续升级 / 回滚:./update.sh" } # ── ② 本地编译运行 ────────────────────────────── @@ -75,7 +83,6 @@ install_local(){ DB_SSL="$(ask 'sslmode (disable/require)' disable)" ;; esac - # 生成 config.json cat > config.json </dev/null 2>&1 || die "未检测到 Go,请先安装 Go(>=1.26):https://go.dev/dl/" ok "Go: $(go version)" - # 内嵌前端需要 node 出静态产物 if command -v npm >/dev/null 2>&1; then info "构建前端静态产物…" ( cd web && npm ci && npm run build:static ) @@ -108,16 +113,57 @@ JSON ok "编译完成 → ./artex" info "启动…(Ctrl-C 退出)" - ./artex + ./start.sh } -echo "==============================" -echo " ARTEX 安装" -echo " 1) 全部 Docker 安装" -echo " 2) 本地运行(go 编译)" -echo "==============================" +usage(){ + cat <<'USAGE' +用法: ./install.sh [选项] + +选项: + --docker 直接执行 Docker 部署(docker-compose.yml) + --tag 指定镜像版本 tag(如 v0.3.33 / latest) + --local 使用本地 Go 编译运行 + --skip-pull 跳过镜像拉取(适用于本地已构建镜像) + -y, --yes 非交互模式(自动填充默认值) + -h, --help 显示本帮助 +USAGE +} + +OPT_DOCKER=0 +OPT_TAG="" +OPT_LOCAL=0 + +while [ "$#" -gt 0 ]; do + case "$1" in + --docker) OPT_DOCKER=1 ;; + --tag) shift; [ "$#" -gt 0 ] || die "--tag 需要参数"; OPT_TAG="$1" ;; + --local) OPT_LOCAL=1 ;; + --skip-pull) export ARTEX_SKIP_PULL=1 ;; + -y|--yes) export ARTEX_NONINTERACTIVE=1 ;; + -h|--help) usage; exit 0 ;; + *) die "未知参数:$1(使用 --help 查看帮助)" ;; + esac + shift +done + +if [ "$OPT_LOCAL" -eq 1 ]; then + install_local + exit 0 +fi + +if [ "$OPT_DOCKER" -eq 1 ]; then + install_docker "$OPT_TAG" + exit 0 +fi + +echo "==========================================" +echo " ARTEX 安装部署" +echo " 1) Docker 部署(推荐:独立沙箱 + 全流量网关)" +echo " 2) 本地运行(Go 编译)" +echo "==========================================" case "$(ask '选择' 1)" in - 1) install_docker ;; + 1) install_docker "$OPT_TAG" ;; 2) install_local ;; *) die "无效选择" ;; esac diff --git a/internal/sandbox/docker_client.go b/internal/sandbox/docker_client.go new file mode 100644 index 0000000..a38240d --- /dev/null +++ b/internal/sandbox/docker_client.go @@ -0,0 +1,529 @@ +package sandbox + +import ( + "bufio" + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +const dockerAPIVersion = "/v1.43" + +// dockerClient is a minimal, zero-dependency Docker Engine HTTP client supporting +// both Unix domain sockets (unix:///var/run/docker.sock) and TCP endpoints +// (http://docker-socket-proxy:2375 or tcp://host:2375). +type dockerClient struct { + scheme string // "unix" or "tcp" + address string // socket path or host:port + http *http.Client +} + +func newDockerClient(dockerHost string) (*dockerClient, error) { + raw := strings.TrimSpace(dockerHost) + if raw == "" { + raw = "unix:///var/run/docker.sock" + } + dc := &dockerClient{} + switch { + case strings.HasPrefix(raw, "unix://"): + dc.scheme = "unix" + dc.address = strings.TrimPrefix(raw, "unix://") + case strings.HasPrefix(raw, "tcp://"): + dc.scheme = "tcp" + dc.address = strings.TrimPrefix(raw, "tcp://") + case strings.HasPrefix(raw, "http://"): + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("invalid docker host %q: %w", raw, err) + } + dc.scheme = "tcp" + dc.address = u.Host + default: + return nil, fmt.Errorf("unsupported docker host scheme: %q", raw) + } + tr := &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + if dc.scheme == "unix" { + return d.DialContext(ctx, "unix", dc.address) + } + return d.DialContext(ctx, "tcp", dc.address) + }, + MaxIdleConns: 16, + IdleConnTimeout: 60 * time.Second, + DisableCompression: true, + ResponseHeaderTimeout: 30 * time.Second, + } + dc.http = &http.Client{Transport: tr} + return dc, nil +} + +func (c *dockerClient) dialRaw(ctx context.Context) (net.Conn, error) { + var d net.Dialer + if c.scheme == "unix" { + return d.DialContext(ctx, "unix", c.address) + } + return d.DialContext(ctx, "tcp", c.address) +} + +func (c *dockerClient) doJSON(ctx context.Context, method, path string, reqBody, out any) (int, []byte, error) { + var bodyReader io.Reader + if reqBody != nil { + b, err := json.Marshal(reqBody) + if err != nil { + return 0, nil, err + } + bodyReader = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerAPIVersion+path, bodyReader) + if err != nil { + return 0, nil, err + } + if reqBody != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := c.http.Do(req) + if err != nil { + return 0, nil, err + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err != nil { + return resp.StatusCode, nil, err + } + if resp.StatusCode >= 400 { + var derr struct { + Message string `json:"message"` + } + _ = json.Unmarshal(data, &derr) + msg := strings.TrimSpace(derr.Message) + if msg == "" { + msg = strings.TrimSpace(string(data)) + } + return resp.StatusCode, data, &dockerAPIError{Status: resp.StatusCode, Message: msg} + } + if out != nil && len(data) > 0 { + if err := json.Unmarshal(data, out); err != nil { + return resp.StatusCode, data, err + } + } + return resp.StatusCode, data, nil +} + +type dockerAPIError struct { + Status int + Message string +} + +func (e *dockerAPIError) Error() string { + return fmt.Sprintf("docker api %d: %s", e.Status, e.Message) +} + +func isDockerNotFound(err error) bool { + var de *dockerAPIError + return errors.As(err, &de) && de.Status == http.StatusNotFound +} + +func isDockerNotModified(err error) bool { + var de *dockerAPIError + return errors.As(err, &de) && de.Status == http.StatusNotModified +} + +func (c *dockerClient) Ping(ctx context.Context) error { + _, _, err := c.doJSON(ctx, http.MethodGet, "/_ping", nil, nil) + return err +} + +// dockerNetworkInspect holds the subset of network fields we inspect. +type dockerNetworkInspect struct { + ID string `json:"Id"` + Name string `json:"Name"` + IPAM struct { + Config []struct { + Subnet string `json:"Subnet"` + Gateway string `json:"Gateway"` + } `json:"Config"` + } `json:"IPAM"` +} + +func (c *dockerClient) InspectNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) { + var out dockerNetworkInspect + _, _, err := c.doJSON(ctx, http.MethodGet, "/networks/"+url.PathEscape(name), nil, &out) + if err != nil { + return nil, err + } + return &out, nil +} + +// EnsureNetwork ensures the isolated sandbox bridge network exists with ICC disabled. +func (c *dockerClient) EnsureNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) { + if info, err := c.InspectNetwork(ctx, name); err == nil { + return info, nil + } else if !isDockerNotFound(err) { + return nil, err + } + payload := map[string]any{ + "Name": name, + "CheckDuplicate": true, + "Driver": "bridge", + "Options": map[string]string{ + "com.docker.network.bridge.enable_icc": "false", + }, + "Labels": map[string]string{ + "artex.managed": "true", + }, + } + if _, _, err := c.doJSON(ctx, http.MethodPost, "/networks/create", payload, nil); err != nil { + if info, err2 := c.InspectNetwork(ctx, name); err2 == nil { + return info, nil + } + return nil, err + } + return c.InspectNetwork(ctx, name) +} + +type dockerContainerInspect struct { + ID string `json:"Id"` + Name string `json:"Name"` + Created string `json:"Created"` + State struct { + Status string `json:"Status"` + Running bool `json:"Running"` + Paused bool `json:"Paused"` + StartedAt string `json:"StartedAt"` + ExitCode int `json:"ExitCode"` + } `json:"State"` + Config struct { + Image string `json:"Image"` + Labels map[string]string `json:"Labels"` + } `json:"Config"` + HostConfig struct { + Runtime string `json:"Runtime"` + NetworkMode string `json:"NetworkMode"` + Memory int64 `json:"Memory"` + } `json:"HostConfig"` + NetworkSettings struct { + Networks map[string]struct { + IPAddress string `json:"IPAddress"` + } `json:"Networks"` + } `json:"NetworkSettings"` +} + +func (i *dockerContainerInspect) IPOnNetwork(network string) string { + if i == nil { + return "" + } + if nw, ok := i.NetworkSettings.Networks[network]; ok && strings.TrimSpace(nw.IPAddress) != "" { + return strings.TrimSpace(nw.IPAddress) + } + for _, nw := range i.NetworkSettings.Networks { + if strings.TrimSpace(nw.IPAddress) != "" { + return strings.TrimSpace(nw.IPAddress) + } + } + return "" +} + +func (c *dockerClient) InspectContainer(ctx context.Context, idOrName string) (*dockerContainerInspect, error) { + var out dockerContainerInspect + _, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/json", nil, &out) + if err != nil { + return nil, err + } + return &out, nil +} + +type dockerContainerListItem struct { + ID string `json:"Id"` + Names []string `json:"Names"` + Image string `json:"Image"` + State string `json:"State"` + Status string `json:"Status"` + Created int64 `json:"Created"` + Labels map[string]string `json:"Labels"` + NetworkSettings struct { + Networks map[string]struct { + IPAddress string `json:"IPAddress"` + } `json:"Networks"` + } `json:"NetworkSettings"` +} + +func (i *dockerContainerListItem) IPOnNetwork(network string) string { + if i == nil { + return "" + } + if nw, ok := i.NetworkSettings.Networks[network]; ok && strings.TrimSpace(nw.IPAddress) != "" { + return strings.TrimSpace(nw.IPAddress) + } + for _, nw := range i.NetworkSettings.Networks { + if strings.TrimSpace(nw.IPAddress) != "" { + return strings.TrimSpace(nw.IPAddress) + } + } + return "" +} +func (c *dockerClient) ListContainersByLabel(ctx context.Context, labels map[string]string) ([]dockerContainerListItem, error) { + labelList := make([]string, 0, len(labels)) + for k, v := range labels { + if v == "" { + labelList = append(labelList, k) + } else { + labelList = append(labelList, k+"="+v) + } + } + filtersJSON, _ := json.Marshal(map[string][]string{"label": labelList}) + path := "/containers/json?all=true&filters=" + url.QueryEscape(string(filtersJSON)) + var out []dockerContainerListItem + _, _, err := c.doJSON(ctx, http.MethodGet, path, nil, &out) + return out, err +} + +func (c *dockerClient) CreateContainer(ctx context.Context, name string, spec map[string]any) (string, error) { + var resp struct { + ID string `json:"Id"` + } + _, _, err := c.doJSON(ctx, http.MethodPost, "/containers/create?name="+url.QueryEscape(name), spec, &resp) + return resp.ID, err +} + +func (c *dockerClient) StartContainer(ctx context.Context, idOrName string) error { + _, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(idOrName)+"/start", nil, nil) + if isDockerNotModified(err) { + return nil + } + return err +} + +func (c *dockerClient) StopContainer(ctx context.Context, idOrName string, timeoutSec int) error { + if timeoutSec <= 0 { + timeoutSec = 5 + } + path := fmt.Sprintf("/containers/%s/stop?t=%d", url.PathEscape(idOrName), timeoutSec) + _, _, err := c.doJSON(ctx, http.MethodPost, path, nil, nil) + if isDockerNotModified(err) || isDockerNotFound(err) { + return nil + } + return err +} + +func (c *dockerClient) RemoveContainer(ctx context.Context, idOrName string) error { + path := "/containers/" + url.PathEscape(idOrName) + "?force=true&v=true" + _, _, err := c.doJSON(ctx, http.MethodDelete, path, nil, nil) + if isDockerNotFound(err) { + return nil + } + return err +} + +type dockerStats struct { + CPUPercent float64 + MemUsageBytes uint64 + MemLimitBytes uint64 + PidsCurrent uint64 +} + +func (c *dockerClient) ContainerStats(ctx context.Context, idOrName string) (dockerStats, error) { + var raw struct { + CPUStats struct { + CPUUsage struct { + TotalUsage uint64 `json:"total_usage"` + } `json:"cpu_usage"` + SystemCPUUsage uint64 `json:"system_cpu_usage"` + OnlineCPUs uint32 `json:"online_cpus"` + } `json:"cpu_stats"` + PreCPUStats struct { + CPUUsage struct { + TotalUsage uint64 `json:"total_usage"` + } `json:"cpu_usage"` + SystemCPUUsage uint64 `json:"system_cpu_usage"` + } `json:"precpu_stats"` + MemoryStats struct { + Usage uint64 `json:"usage"` + Limit uint64 `json:"limit"` + Stats map[string]uint64 `json:"stats"` + } `json:"memory_stats"` + PidsStats struct { + Current uint64 `json:"current"` + } `json:"pids_stats"` + } + _, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/stats?stream=false", nil, &raw) + if err != nil { + return dockerStats{}, err + } + cpuDelta := float64(0) + if raw.CPUStats.CPUUsage.TotalUsage > raw.PreCPUStats.CPUUsage.TotalUsage { + cpuDelta = float64(raw.CPUStats.CPUUsage.TotalUsage - raw.PreCPUStats.CPUUsage.TotalUsage) + } + sysDelta := float64(0) + if raw.CPUStats.SystemCPUUsage > raw.PreCPUStats.SystemCPUUsage { + sysDelta = float64(raw.CPUStats.SystemCPUUsage - raw.PreCPUStats.SystemCPUUsage) + } + cpus := float64(raw.CPUStats.OnlineCPUs) + if cpus == 0 { + cpus = 1 + } + cpuPct := 0.0 + if sysDelta > 0 && cpuDelta > 0 { + cpuPct = (cpuDelta / sysDelta) * cpus * 100.0 + } + memUsage := raw.MemoryStats.Usage + if inactive := raw.MemoryStats.Stats["inactive_file"]; inactive > 0 && memUsage > inactive { + memUsage -= inactive + } + return dockerStats{ + CPUPercent: cpuPct, + MemUsageBytes: memUsage, + MemLimitBytes: raw.MemoryStats.Limit, + PidsCurrent: raw.PidsStats.Current, + }, nil +} + +type dockerExecCreateReq struct { + AttachStdin bool `json:"AttachStdin"` + AttachStdout bool `json:"AttachStdout"` + AttachStderr bool `json:"AttachStderr"` + Tty bool `json:"Tty"` + Env []string `json:"Env,omitempty"` + Cmd []string `json:"Cmd"` + WorkingDir string `json:"WorkingDir,omitempty"` + User string `json:"User,omitempty"` +} + +func (c *dockerClient) ExecCreate(ctx context.Context, containerID string, req dockerExecCreateReq) (string, error) { + var resp struct { + ID string `json:"Id"` + } + _, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(containerID)+"/exec", req, &resp) + return resp.ID, err +} + +type dockerExecInspect struct { + ID string `json:"ID"` + Running bool `json:"Running"` + ExitCode int `json:"ExitCode"` + Pid int `json:"Pid"` +} + +func (c *dockerClient) ExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) { + var out dockerExecInspect + _, _, err := c.doJSON(ctx, http.MethodGet, "/exec/"+url.PathEscape(execID)+"/json", nil, &out) + return out, err +} + +// ExecStartStream hijacks a raw HTTP/1.1 connection to POST /exec//start +// and demultiplexes Docker's 8-byte framed stdout/stderr stream while keeping +// the connection writable for stdin. +func (c *dockerClient) ExecStartStream(ctx context.Context, execID string) (*hijackedExec, error) { + conn, err := c.dialRaw(ctx) + if err != nil { + return nil, err + } + body := `{"Detach":false,"Tty":false}` + reqStr := fmt.Sprintf( + "POST %s/exec/%s/start HTTP/1.1\r\nHost: docker\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s", + dockerAPIVersion, url.PathEscape(execID), len(body), body, + ) + if _, err := io.WriteString(conn, reqStr); err != nil { + conn.Close() + return nil, err + } + br := bufio.NewReaderSize(conn, 64*1024) + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost}) + if err != nil { + conn.Close() + return nil, err + } + if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK { + errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + conn.Close() + return nil, fmt.Errorf("docker exec start failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(errBody))) + } + + stdoutR, stdoutW := io.Pipe() + stderrR, stderrW := io.Pipe() + done := make(chan error, 1) + + go func() { + err := demuxDockerStream(br, stdoutW, stderrW) + _ = stdoutW.Close() + _ = stderrW.Close() + done <- err + }() + + return &hijackedExec{ + conn: conn, + stdout: stdoutR, + stderr: stderrR, + done: done, + }, nil +} + +type hijackedExec struct { + conn net.Conn + stdout io.ReadCloser + stderr io.ReadCloser + done chan error + closeOnce sync.Once +} + +func (h *hijackedExec) Write(p []byte) (int, error) { + return h.conn.Write(p) +} + +func (h *hijackedExec) CloseWrite() error { + if cw, ok := h.conn.(interface{ CloseWrite() error }); ok { + return cw.CloseWrite() + } + return nil +} + +func (h *hijackedExec) Close() error { + var err error + h.closeOnce.Do(func() { + err = h.conn.Close() + }) + return err +} + +// demuxDockerStream parses Docker's non-TTY multiplexed stream protocol: +// each frame has an 8-byte header [streamType, 0, 0, 0, len(uint32 BE)]. +func demuxDockerStream(r io.Reader, stdout, stderr io.Writer) error { + var hdr [8]byte + for { + _, err := io.ReadFull(r, hdr[:]) + if err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { + return nil + } + return err + } + n := int64(binary.BigEndian.Uint32(hdr[4:8])) + var dst io.Writer + switch hdr[0] { + case 1: + dst = stdout + case 2: + dst = stderr + default: + dst = io.Discard + } + if n > 0 { + if _, err := io.CopyN(dst, r, n); err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return err + } + } + } +} diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go new file mode 100644 index 0000000..7d4827d --- /dev/null +++ b/internal/sandbox/manager.go @@ -0,0 +1,1541 @@ +package sandbox + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + labelManaged = "artex.managed" + labelInstance = "artex.instance" + labelScope = "artex.scope" + labelOwnerID = "artex.owner_id" + + defaultMaxExecOutput = 1 << 20 // 1 MiB + statsCacheTTL = 10 * time.Second +) + +// Manager owns the lifecycle of all sandbox containers and exposes exec/stream +// operations for Worker, ChatAgent, CustomTool, and Stdio MCP callers. +type Manager struct { + mu sync.RWMutex + cfg Config + docker *dockerClient + + // Per-target serialization lock prevents concurrent Workers from racing + // container creation/start/stop for the same task or session. + targetLocks sync.Map // target.Key() -> *sync.Mutex + + // Active run tracking prevents auto-stop while any worker, settlement, + // human follow-up, or intercept approval is in flight. + stateMu sync.Mutex + states map[string]*targetState + + // Cached container stats (short TTL) so UI polling doesn't hammer Docker. + statsMu sync.Mutex + statsCache map[string]cachedStats + statsInFlight map[string]struct{} + // Detected sandbox network CIDRs & bridge gateway IP. + netCIDRMu sync.RWMutex + netCIDRs []*net.IPNet + gatewayIP string + + // Real-time container IP -> sandbox owner identity map for SNAT-free traffic attribution (#218). + ipMu sync.RWMutex + ipMap map[string]ContainerIdentity + stopReaper context.CancelFunc + reaperWG sync.WaitGroup +} + +type targetState struct { + activeRuns int + lastActive time.Time + stopWhenIdle bool +} + +type cachedStats struct { + at time.Time + stats dockerStats +} + +var defaultMgr atomic.Pointer[Manager] + +// Default returns the process-wide sandbox Manager (may be nil in tests / before init). +func Default() *Manager { return defaultMgr.Load() } + +// SetDefault installs the process-wide sandbox Manager. +func SetDefault(m *Manager) { defaultMgr.Store(m) } + +// New creates a Manager. In ModeLocal it requires no Docker daemon. +func New(cfg Config) (*Manager, error) { + m := &Manager{ + cfg: cfg, + states: map[string]*targetState{}, + statsCache: map[string]cachedStats{}, + statsInFlight: map[string]struct{}{}, + ipMap: map[string]ContainerIdentity{}, + } + if cfg.Mode == ModeDocker { + dc, err := newDockerClient(cfg.DockerHost) + if err != nil { + return nil, err + } + m.docker = dc + } + return m, nil +} + +// Enabled reports whether Docker sandbox isolation is active. +func (m *Manager) Enabled() bool { + if m == nil { + return false + } + m.mu.RLock() + defer m.mu.RUnlock() + return m.cfg.Mode == ModeDocker && m.docker != nil +} + +// Config returns a copy of the current sandbox configuration. +func (m *Manager) Config() Config { + if m == nil { + return Config{Mode: ModeLocal} + } + m.mu.RLock() + defer m.mu.RUnlock() + return m.cfg +} + +// ApplyOverrides updates mutable runtime config fields (typically loaded from DB settings). +func (m *Manager) ApplyOverrides(o RuntimeOverrides) { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + if o.Image != nil && strings.TrimSpace(*o.Image) != "" { + m.cfg.Image = strings.TrimSpace(*o.Image) + } + if o.MemoryMB != nil && *o.MemoryMB >= 256 { + m.cfg.MemoryMB = *o.MemoryMB + } + if o.CPUs != nil && *o.CPUs >= 0.25 { + m.cfg.CPUs = *o.CPUs + } + if o.PidsLimit != nil && *o.PidsLimit >= 32 { + m.cfg.PidsLimit = *o.PidsLimit + } + if o.ShmSizeMB != nil && *o.ShmSizeMB >= 64 { + m.cfg.ShmSizeMB = *o.ShmSizeMB + } + if o.Runtime != nil { + m.cfg.Runtime = strings.TrimSpace(*o.Runtime) + } + if o.AutoStopOnComplete != nil { + m.cfg.AutoStopOnComplete = *o.AutoStopOnComplete + } + if o.SessionIdleMinutes != nil && *o.SessionIdleMinutes >= 1 { + m.cfg.SessionIdleMinutes = *o.SessionIdleMinutes + } +} + +// SetProxyConfig updates the proxy URL and CA cert path exposed to sandbox containers. +func (m *Manager) SetProxyConfig(proxyURL, caCertPath string) { + if m == nil { + return + } + m.mu.Lock() + defer m.mu.Unlock() + if strings.TrimSpace(proxyURL) != "" { + m.cfg.ProxyURL = strings.TrimSpace(proxyURL) + } + if strings.TrimSpace(caCertPath) != "" { + m.cfg.CACertPath = strings.TrimSpace(caCertPath) + } +} + +// SetSystemCABundlePath sets the host path to the merged system + ARTEX MITM CA +// bundle mounted read-only into sandbox containers at /etc/ssl/certs/ca-certificates.crt. +func (m *Manager) SetSystemCABundlePath(bundlePath string) { + if m == nil { + return + } + m.mu.Lock() + m.cfg.SystemCABundlePath = strings.TrimSpace(bundlePath) + m.mu.Unlock() +} + +// GatewayIP returns the detected bridge gateway IP of the sandbox network (e.g. "172.30.0.1"). +func (m *Manager) GatewayIP() string { + if m == nil { + return "" + } + m.netCIDRMu.RLock() + defer m.netCIDRMu.RUnlock() + return m.gatewayIP +} + +// ContainerIPSnapshot returns a copy of the live container IP -> identity map +// for transparent gateway policy sync (#218 Phase 3). +func (m *Manager) ContainerIPSnapshot() map[string]ContainerIdentity { + if m == nil { + return nil + } + m.ipMu.RLock() + defer m.ipMu.RUnlock() + out := make(map[string]ContainerIdentity, len(m.ipMap)) + for k, v := range m.ipMap { + out[k] = v + } + return out +} + +// ProxyEnv returns HTTP(S)_PROXY + CA cert environment variables for processes +// running inside a sandbox container. Empty when capture/proxy is disabled. +func (m *Manager) ProxyEnv(proxyActive bool) []string { + if m == nil || !proxyActive { + return nil + } + return m.ProxyEnvWithURL(m.Config().ProxyURL) +} + +// ProxyEnvWithURL returns HTTP(S)_PROXY + CA cert environment variables for +// processes inside a sandbox container using an explicit proxy URL (e.g. a +// Proxy-Authorization tagged recording proxy URL for per-intent attribution). +func (m *Manager) ProxyEnvWithURL(proxyURL string) []string { + if m == nil { + return nil + } + proxyURL = strings.TrimSpace(proxyURL) + if proxyURL == "" { + return nil + } + cfg := m.Config() + env := []string{ + "HTTP_PROXY=" + proxyURL, + "HTTPS_PROXY=" + proxyURL, + "http_proxy=" + proxyURL, + "https_proxy=" + proxyURL, + "ALL_PROXY=" + proxyURL, + "all_proxy=" + proxyURL, + "NODE_USE_ENV_PROXY=1", + } + caBundle := "" + if cfg.SystemCABundlePath != "" { + if _, err := os.Stat(cfg.SystemCABundlePath); err == nil { + caBundle = ContainerSystemCABundlePath + } + } + if cfg.CACertPath != "" { + if _, err := os.Stat(cfg.CACertPath); err == nil { + if caBundle == "" { + caBundle = ContainerCACertPath + } + env = append(env, + "SSL_CERT_FILE="+caBundle, + "CURL_CA_BUNDLE="+caBundle, + "REQUESTS_CA_BUNDLE="+caBundle, + "GIT_SSL_CAINFO="+caBundle, + "NODE_EXTRA_CA_CERTS="+ContainerCACertPath, + ) + } + } + return env +} + +// IsSandboxSourceIP reports whether remoteAddr belongs to the isolated sandbox +// Docker network (used to block sandbox containers from calling :8787 admin API). +func (m *Manager) IsSandboxSourceIP(remoteAddr string) bool { + if m == nil || !m.Enabled() { + return false + } + host := remoteAddr + if h, _, err := net.SplitHostPort(remoteAddr); err == nil { + host = h + } + ip := net.ParseIP(strings.TrimSpace(host)) + if ip == nil { + return false + } + m.netCIDRMu.RLock() + defer m.netCIDRMu.RUnlock() + for _, n := range m.netCIDRs { + if n.Contains(ip) { + return true + } + } + return false +} + +// SandboxSubnets returns the detected sandbox bridge subnets (e.g. ["172.28.0.0/16"]). +func (m *Manager) SandboxSubnets() []*net.IPNet { + if m == nil { + return nil + } + m.netCIDRMu.RLock() + defer m.netCIDRMu.RUnlock() + out := make([]*net.IPNet, len(m.netCIDRs)) + copy(out, m.netCIDRs) + return out +} + +func (m *Manager) lockFor(t Target) *sync.Mutex { + v, _ := m.targetLocks.LoadOrStore(t.Key(), &sync.Mutex{}) + return v.(*sync.Mutex) +} + +// Acquire increments the active run counter for target and clears any pending +// stop-when-idle flag. Every Acquire must be paired with Release. +func (m *Manager) Acquire(t Target) { + if m == nil || !t.Valid() { + return + } + m.stateMu.Lock() + defer m.stateMu.Unlock() + st := m.states[t.Key()] + if st == nil { + st = &targetState{} + m.states[t.Key()] = st + } + st.activeRuns++ + st.lastActive = time.Now() + st.stopWhenIdle = false +} + +// Release decrements activeRuns. If activeRuns hits 0 and MarkIdleStop was +// requested (e.g. task paused/completed while finishing settlement), it stops +// the container asynchronously. +func (m *Manager) Release(t Target) { + if m == nil || !t.Valid() { + return + } + var shouldStop bool + m.stateMu.Lock() + st := m.states[t.Key()] + if st != nil { + if st.activeRuns > 0 { + st.activeRuns-- + } + st.lastActive = time.Now() + if st.activeRuns == 0 && st.stopWhenIdle { + shouldStop = true + st.stopWhenIdle = false + } + } + m.stateMu.Unlock() + if shouldStop && m.Enabled() && m.Config().AutoStopOnComplete { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if err := m.Stop(ctx, t); err != nil { + log.Printf("[sandbox] auto-stop %s failed: %v", t.Key(), err) + } + }() + } +} + +// ActiveRuns returns the number of active executions currently using target. +func (m *Manager) ActiveRuns(t Target) int { + if m == nil || !t.Valid() { + return 0 + } + m.stateMu.Lock() + defer m.stateMu.Unlock() + if st := m.states[t.Key()]; st != nil { + return st.activeRuns + } + return 0 +} + +// RequestIdleStop stops target immediately if no active run holds it; otherwise +// schedules an automatic stop the moment the last active run releases it. +func (m *Manager) RequestIdleStop(t Target) { + if m == nil || !m.Enabled() || !t.Valid() { + return + } + if !m.Config().AutoStopOnComplete { + return + } + var stopNow bool + m.stateMu.Lock() + st := m.states[t.Key()] + if st == nil || st.activeRuns == 0 { + stopNow = true + } else { + st.stopWhenIdle = true + } + m.stateMu.Unlock() + if stopNow { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if err := m.Stop(ctx, t); err != nil { + log.Printf("[sandbox] idle-stop %s failed: %v", t.Key(), err) + } + }() + } +} + +// ClearIdleStop cancels any pending deferred stop when a task resumes. +func (m *Manager) ClearIdleStop(t Target) { + if m == nil || !t.Valid() { + return + } + m.stateMu.Lock() + defer m.stateMu.Unlock() + if st := m.states[t.Key()]; st != nil { + st.stopWhenIdle = false + } +} + +// StartBackgroundReaper periodically stops idle session containers. +func (m *Manager) StartBackgroundReaper(parent context.Context) { + if m == nil || !m.Enabled() { + return + } + ctx, cancel := context.WithCancel(parent) + m.stopReaper = cancel + m.reaperWG.Add(1) + go func() { + defer m.reaperWG.Done() + ticker := time.NewTicker(1 * time.Minute) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + m.reapIdleSessions(ctx) + } + } + }() +} + +func (m *Manager) reapIdleSessions(ctx context.Context) { + idleLimit := time.Duration(m.Config().SessionIdleMinutes) * time.Minute + if idleLimit <= 0 { + idleLimit = 20 * time.Minute + } + now := time.Now() + var victims []Target + m.stateMu.Lock() + for key, st := range m.states { + if !strings.HasPrefix(key, string(ScopeSession)+":") { + continue + } + if st.activeRuns == 0 && !st.lastActive.IsZero() && now.Sub(st.lastActive) >= idleLimit { + victims = append(victims, Target{ + Scope: ScopeSession, + OwnerID: strings.TrimPrefix(key, string(ScopeSession)+":"), + }) + } + } + m.stateMu.Unlock() + for _, t := range victims { + sctx, cancel := context.WithTimeout(ctx, 15*time.Second) + if info, err := m.Inspect(sctx, t, false); err == nil && info.State == "running" { + log.Printf("[sandbox] stopping idle session container %s", t.OwnerID) + _ = m.Stop(sctx, t) + } + cancel() + } +} + +// ReconcileOnStartup verifies Docker connectivity, ensures the isolated network +// exists (with ICC disabled), removes orphan containers whose tasks/sessions no +// longer exist in DB, and stops leftover running containers from a prior crash. +func (m *Manager) ReconcileOnStartup(ctx context.Context, validTaskIDs, validSessionIDs map[string]bool) error { + if m == nil || !m.Enabled() { + return nil + } + cfg := m.Config() + if err := m.docker.Ping(ctx); err != nil { + return fmt.Errorf("docker ping failed (%s): %w", cfg.DockerHost, err) + } + netInfo, err := m.docker.EnsureNetwork(ctx, cfg.Network) + if err != nil { + return fmt.Errorf("ensure sandbox network %q: %w", cfg.Network, err) + } + m.recordNetworkCIDRs(netInfo) + + items, err := m.docker.ListContainersByLabel(ctx, map[string]string{ + labelManaged: "true", + labelInstance: cfg.InstanceID, + }) + if err != nil { + return fmt.Errorf("list managed containers: %w", err) + } + for _, item := range items { + scope := Scope(item.Labels[labelScope]) + ownerID := item.Labels[labelOwnerID] + orphan := false + switch scope { + case ScopeTask: + orphan = validTaskIDs != nil && !validTaskIDs[ownerID] + case ScopeSession: + orphan = validSessionIDs != nil && !validSessionIDs[ownerID] + case ScopeEphemeral: + orphan = true + } + if orphan { + log.Printf("[sandbox] removing orphan container %s (%s:%s)", shortID(item.ID), scope, ownerID) + _ = m.docker.RemoveContainer(ctx, item.ID) + continue + } + if item.State == "running" { + log.Printf("[sandbox] stopping leftover running container %s (%s:%s)", shortID(item.ID), scope, ownerID) + _ = m.docker.StopContainer(ctx, item.ID, 5) + } + } + return nil +} + +// Shutdown stops the background reaper and gracefully stops all running managed +// containers (preserving stopped containers + mounted workspaces across restarts). +func (m *Manager) Shutdown(ctx context.Context) { + if m == nil || !m.Enabled() { + return + } + if m.stopReaper != nil { + m.stopReaper() + m.reaperWG.Wait() + } + cfg := m.Config() + items, err := m.docker.ListContainersByLabel(ctx, map[string]string{ + labelManaged: "true", + labelInstance: cfg.InstanceID, + }) + if err != nil { + return + } + for _, item := range items { + if Scope(item.Labels[labelScope]) == ScopeEphemeral { + _ = m.docker.RemoveContainer(ctx, item.ID) + } else if item.State == "running" { + _ = m.docker.StopContainer(ctx, item.ID, 5) + } + } +} + +func (m *Manager) recordNetworkCIDRs(netInfo *dockerNetworkInspect) { + if netInfo == nil { + return + } + var cidrs []*net.IPNet + var gateway string + for _, c := range netInfo.IPAM.Config { + if _, ipnet, err := net.ParseCIDR(strings.TrimSpace(c.Subnet)); err == nil { + cidrs = append(cidrs, ipnet) + } + if gateway == "" && strings.TrimSpace(c.Gateway) != "" { + gateway = strings.TrimSpace(c.Gateway) + } + } + m.netCIDRMu.Lock() + m.netCIDRs = cidrs + if gateway != "" { + m.gatewayIP = gateway + } + m.netCIDRMu.Unlock() + // attached directly to artex-sandbox (eliminates bridge SNAT so the proxy + // observes each sandbox container's real source IP). Fall back to the + // bridge gateway on single-network setups. + proxyHost := detectLocalIPInSubnets(cidrs) + if proxyHost == "" { + proxyHost = gateway + } + if proxyHost != "" { + m.mu.Lock() + if m.cfg.ProxyURL == "" || strings.EqualFold(m.cfg.ProxyURL, "auto") { + m.cfg.ProxyURL = "http://" + proxyHost + ":8788" + } + m.mu.Unlock() + } +} + +func detectLocalIPInSubnets(cidrs []*net.IPNet) string { + if len(cidrs) == 0 { + return "" + } + addrs, err := net.InterfaceAddrs() + if err != nil { + return "" + } + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok || ipnet.IP == nil { + continue + } + ip := ipnet.IP.To4() + if ip == nil { + continue + } + for _, sub := range cidrs { + if sub.Contains(ip) { + return ip.String() + } + } + } + return "" +} + +// ResolveContainerByIP returns the managed sandbox container owning srcIP. +func (m *Manager) ResolveContainerByIP(srcIP string) (ContainerIdentity, bool) { + if m == nil { + return ContainerIdentity{}, false + } + raw := strings.TrimSpace(srcIP) + if h, _, err := net.SplitHostPort(raw); err == nil { + raw = h + } + ip := net.ParseIP(strings.Trim(raw, "[]")) + if ip == nil { + return ContainerIdentity{}, false + } + if v4 := ip.To4(); v4 != nil { + ip = v4 + } + m.ipMu.RLock() + id, ok := m.ipMap[ip.String()] + m.ipMu.RUnlock() + return id, ok +} + +func (m *Manager) registerContainerIP(ip string, id ContainerIdentity) { + parsed := net.ParseIP(strings.TrimSpace(ip)) + if parsed == nil { + return + } + if v4 := parsed.To4(); v4 != nil { + parsed = v4 + } + ipStr := parsed.String() + id.IP = ipStr + m.ipMu.Lock() + // Evict stale IP entries for the same container name/id first. + for k, existing := range m.ipMap { + if k != ipStr && ((id.ContainerName != "" && existing.ContainerName == id.ContainerName) || (id.ContainerID != "" && existing.ContainerID == id.ContainerID)) { + delete(m.ipMap, k) + } + } + m.ipMap[ipStr] = id + m.ipMu.Unlock() +} + +func (m *Manager) evictContainerIP(name string) { + if name == "" { + return + } + m.ipMu.Lock() + for k, existing := range m.ipMap { + if existing.ContainerName == name { + delete(m.ipMap, k) + } + } + m.ipMu.Unlock() +} + +// Ensure guarantees that target's sandbox container exists and is running. +func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) { + if !m.Enabled() { + return "", errors.New("sandbox docker mode is not enabled") + } + if !t.Valid() { + return "", errors.New("invalid sandbox target") + } + mu := m.lockFor(t) + mu.Lock() + defer mu.Unlock() + + cfg := m.Config() + name := cfg.ContainerName(t) + + // Ensure host-side workspace directory exists with sandbox-writable perms + // BEFORE mounting so Docker never auto-creates a root-owned directory. + localRoot := cfg.LocalRootFor(t) + if err := ensureWritableDir(localRoot, cfg.User); err != nil { + return "", fmt.Errorf("prepare sandbox workspace: %w", err) + } + + if info, err := m.docker.InspectContainer(ctx, name); err == nil { + if !info.State.Running { + if err := m.docker.StartContainer(ctx, info.ID); err != nil { + return "", fmt.Errorf("start sandbox container %s: %w", name, err) + } + if refreshed, ierr := m.docker.InspectContainer(ctx, info.ID); ierr == nil { + info = refreshed + } + } + if ip := info.IPOnNetwork(cfg.Network); ip != "" { + m.registerContainerIP(ip, ContainerIdentity{ + Scope: t.Scope, + OwnerID: t.OwnerID, + ContainerID: info.ID, + ShortID: shortID(info.ID), + ContainerName: name, + }) + } + return info.ID, nil + } else if !isDockerNotFound(err) { + return "", fmt.Errorf("inspect sandbox container %s: %w", name, err) + } + + netInfo, err := m.docker.EnsureNetwork(ctx, cfg.Network) + if err != nil { + return "", fmt.Errorf("ensure network %s: %w", cfg.Network, err) + } + m.recordNetworkCIDRs(netInfo) + + hostRoot := cfg.MapDataPathToHost(localRoot) + binds := []string{hostRoot + ":" + ContainerWorkDir + ":rw"} + baseEnv := []string{ + "HOME=/tmp", + "TERM=dumb", + "ARTEX_SANDBOX=1", + "ARTEX_WORKSPACE=" + ContainerWorkDir, + } + if cfg.AllowNetRaw { + baseEnv = append(baseEnv, "NMAP_PRIVILEGED=1") + } + if cfg.CACertPath != "" { + if _, err := os.Stat(cfg.CACertPath); err == nil { + hostCA := cfg.MapDataPathToHost(cfg.CACertPath) + binds = append(binds, hostCA+":"+ContainerCACertPath+":ro") + baseEnv = append(baseEnv, "NODE_EXTRA_CA_CERTS="+ContainerCACertPath) + } + } + if cfg.SystemCABundlePath != "" { + if _, err := os.Stat(cfg.SystemCABundlePath); err == nil { + hostBundle := cfg.MapDataPathToHost(cfg.SystemCABundlePath) + binds = append(binds, hostBundle+":"+ContainerSystemCABundlePath+":ro") + baseEnv = append(baseEnv, + "SSL_CERT_FILE="+ContainerSystemCABundlePath, + "CURL_CA_BUNDLE="+ContainerSystemCABundlePath, + "REQUESTS_CA_BUNDLE="+ContainerSystemCABundlePath, + "GIT_SSL_CAINFO="+ContainerSystemCABundlePath, + ) + } + } + + memBytes := int64(cfg.MemoryMB) << 20 + shmBytes := int64(cfg.ShmSizeMB) << 20 + nanoCPUs := int64(cfg.CPUs * 1e9) + pidsLimit := int64(cfg.PidsLimit) + + hostCfg := map[string]any{ + "Binds": binds, + "NetworkMode": cfg.Network, + "Memory": memBytes, + "MemorySwap": memBytes, // disable swap thrashing + "NanoCpus": nanoCPUs, + "PidsLimit": pidsLimit, + "ShmSize": shmBytes, + "CapDrop": []string{"ALL"}, + "Init": true, // tini/docker-init reaps zombies inside container + "Tmpfs": map[string]string{"/tmp": fmt.Sprintf("rw,nosuid,nodev,size=%dm", cfg.TmpSizeMB)}, + "Sysctls": map[string]string{"net.ipv4.ping_group_range": "0 2147483647"}, + "RestartPolicy": map[string]any{"Name": "no"}, + } + if cfg.AllowNetRaw { + // Permit CAP_NET_RAW in the bounding set ONLY (paired with file-cap cap_net_raw+ep + // on /usr/bin/nmap, /usr/bin/nping, and /usr/bin/ping in Dockerfile.sandbox, with + // all SUID/SGID bits stripped). Ordinary non-root processes keep CapEff=0. + hostCfg["CapAdd"] = []string{"NET_RAW"} + } else { + // Strict lockdown for untrusted custom images that may contain SUID binaries. + hostCfg["SecurityOpt"] = []string{"no-new-privileges:true"} + } + // Route container DNS through the sandbox gateway IP when transparent mode is enabled + // so Docker's embedded DNS forwards queries across the sandbox bridge with real container src_ip. + if cfg.TransparentGateway { + dnsIP := strings.TrimSpace(cfg.GatewayDNSIP) + if dnsIP == "" { + dnsIP = m.GatewayIP() + } + if dnsIP != "" { + hostCfg["Dns"] = []string{dnsIP} + } + } + if cfg.Runtime != "" { + hostCfg["Runtime"] = cfg.Runtime + } + + spec := map[string]any{ + "Image": cfg.Image, + "Hostname": sanitizeToken(string(t.Scope) + "-" + t.OwnerID), + "User": cfg.User, + "WorkingDir": ContainerWorkDir, + "Cmd": []string{"sleep", "infinity"}, + "AttachStdin": false, + "AttachStdout": false, + "AttachStderr": false, + "Tty": false, + "Env": baseEnv, + "Labels": map[string]string{ + labelManaged: "true", + labelInstance: cfg.InstanceID, + labelScope: string(t.Scope), + labelOwnerID: t.OwnerID, + }, + "HostConfig": hostCfg, + } + + id, err := m.docker.CreateContainer(ctx, name, spec) + if err != nil { + return "", fmt.Errorf("create sandbox container %s (image %s): %w", name, cfg.Image, err) + } + if err := m.docker.StartContainer(ctx, id); err != nil { + _ = m.docker.RemoveContainer(ctx, id) + return "", fmt.Errorf("start sandbox container %s: %w", name, err) + } + if info, ierr := m.docker.InspectContainer(ctx, id); ierr == nil { + if ip := info.IPOnNetwork(cfg.Network); ip != "" { + m.registerContainerIP(ip, ContainerIdentity{ + Scope: t.Scope, + OwnerID: t.OwnerID, + ContainerID: id, + ShortID: shortID(id), + ContainerName: name, + }) + } + } + log.Printf("[sandbox] created & started %s (%s, image=%s, mem=%dMiB, cpus=%.2f)", name, shortID(id), cfg.Image, cfg.MemoryMB, cfg.CPUs) + return id, nil +} + +// Stop stops target's container (releasing CPU/memory while retaining container + workspace). +func (m *Manager) Stop(ctx context.Context, t Target) error { + if !m.Enabled() || !t.Valid() { + return nil + } + mu := m.lockFor(t) + mu.Lock() + defer mu.Unlock() + name := m.Config().ContainerName(t) + if err := m.docker.StopContainer(ctx, name, 5); err != nil { + return err + } + m.dropStatsCache(name) + m.evictContainerIP(name) + return nil +} + +// Remove force-removes target's container (leaving host workspace files to caller). +func (m *Manager) Remove(ctx context.Context, t Target) error { + if !m.Enabled() || !t.Valid() { + return nil + } + mu := m.lockFor(t) + mu.Lock() + defer mu.Unlock() + name := m.Config().ContainerName(t) + if err := m.docker.RemoveContainer(ctx, name); err != nil { + return err + } + m.dropStatsCache(name) + m.evictContainerIP(name) + m.stateMu.Lock() + delete(m.states, t.Key()) + m.stateMu.Unlock() + return nil +} + +// Recreate deletes target's existing container (optionally clearing workspace) +// and creates + starts a fresh container using the latest Config. +func (m *Manager) Recreate(ctx context.Context, t Target, clearWorkspace bool) (ContainerInfo, error) { + if !m.Enabled() || !t.Valid() { + return ContainerInfo{}, errors.New("sandbox docker mode is not enabled") + } + if err := m.Remove(ctx, t); err != nil { + return ContainerInfo{}, err + } + if clearWorkspace { + root := m.Config().LocalRootFor(t) + entries, err := os.ReadDir(root) + if err == nil { + for _, e := range entries { + _ = os.RemoveAll(filepath.Join(root, e.Name())) + } + } + } + if _, err := m.Ensure(ctx, t); err != nil { + return ContainerInfo{}, err + } + return m.Inspect(ctx, t, false) +} + +// PruneStopped removes stopped/exited managed containers (and any ephemeral containers). +func (m *Manager) PruneStopped(ctx context.Context) (int, error) { + if !m.Enabled() { + return 0, nil + } + cfg := m.Config() + items, err := m.docker.ListContainersByLabel(ctx, map[string]string{ + labelManaged: "true", + labelInstance: cfg.InstanceID, + }) + if err != nil { + return 0, err + } + removed := 0 + for _, item := range items { + if item.State != "running" { + if err := m.docker.RemoveContainer(ctx, item.ID); err == nil { + removed++ + } + } + } + return removed, nil +} + +// Inspect returns current container metadata and optional cached CPU/memory stats. +func (m *Manager) Inspect(ctx context.Context, t Target, withStats bool) (ContainerInfo, error) { + cfg := m.Config() + base := ContainerInfo{ + Scope: t.Scope, + OwnerID: t.OwnerID, + Name: cfg.ContainerName(t), + Image: cfg.Image, + State: "local", + ActiveRuns: m.ActiveRuns(t), + WorkDirContainer: ContainerWorkDir, + Network: cfg.Network, + Runtime: cfg.Runtime, + } + if !m.Enabled() { + return base, nil + } + info, err := m.docker.InspectContainer(ctx, base.Name) + if err != nil { + if isDockerNotFound(err) { + base.State = "missing" + base.StatusText = "not created" + return base, nil + } + base.State = "error" + base.Error = err.Error() + return base, err + } + base.ContainerID = info.ID + base.ShortID = shortID(info.ID) + base.Image = info.Config.Image + base.State = info.State.Status + base.StatusText = info.State.Status + base.CreatedAt = info.Created + if info.State.Running { + base.StartedAt = info.State.StartedAt + } + base.Runtime = info.HostConfig.Runtime + base.Network = info.HostConfig.NetworkMode + if info.HostConfig.Memory > 0 { + base.MemLimitBytes = uint64(info.HostConfig.Memory) + } + if withStats && info.State.Running { + if st, err := m.cachedContainerStats(ctx, base.Name); err == nil { + base.CPUPercent = st.CPUPercent + base.MemUsageBytes = st.MemUsageBytes + if st.MemLimitBytes > 0 { + base.MemLimitBytes = st.MemLimitBytes + } + base.PidsCurrent = st.PidsCurrent + } + } + return base, nil +} + +// Status returns global sandbox status plus all managed containers (using cached stats only). +func (m *Manager) Status(ctx context.Context) GlobalStatus { + return m.StatusWithStats(ctx, false) +} + +// StatusWithStats returns global sandbox status plus all managed containers. +// When withStats is true, live CPU/memory/PID stats are concurrently fetched +// (with short caching) for every running container. +func (m *Manager) StatusWithStats(ctx context.Context, withStats bool) GlobalStatus { + cfg := m.Config() + out := GlobalStatus{ + Mode: cfg.Mode, + Enabled: m.Enabled(), + Available: !m.Enabled(), // local mode is always available + Image: cfg.Image, + Network: cfg.Network, + Runtime: cfg.Runtime, + MemoryMB: cfg.MemoryMB, + CPUs: cfg.CPUs, + PidsLimit: cfg.PidsLimit, + ShmSizeMB: cfg.ShmSizeMB, + AutoStopOnComplete: cfg.AutoStopOnComplete, + SessionIdleMinutes: cfg.SessionIdleMinutes, + Containers: []ContainerInfo{}, + } + if !m.Enabled() { + return out + } + items, err := m.docker.ListContainersByLabel(ctx, map[string]string{ + labelManaged: "true", + labelInstance: cfg.InstanceID, + }) + if err != nil { + out.Available = false + out.Error = err.Error() + return out + } + out.Available = true + var staleRunning []string + for _, item := range items { + t := Target{ + Scope: Scope(item.Labels[labelScope]), + OwnerID: item.Labels[labelOwnerID], + } + name := "" + if len(item.Names) > 0 { + name = strings.TrimPrefix(item.Names[0], "/") + } + ipAddr := item.IPOnNetwork(cfg.Network) + ci := ContainerInfo{ + Scope: t.Scope, + OwnerID: t.OwnerID, + Name: name, + ContainerID: item.ID, + ShortID: shortID(item.ID), + IPAddress: ipAddr, + Image: item.Image, + State: item.State, + StatusText: item.Status, + CreatedAt: time.Unix(item.Created, 0).UTC().Format(time.RFC3339), + ActiveRuns: m.ActiveRuns(t), + WorkDirContainer: ContainerWorkDir, + Network: cfg.Network, + Runtime: cfg.Runtime, + } + if item.State == "running" && ipAddr != "" { + m.registerContainerIP(ipAddr, ContainerIdentity{ + Scope: t.Scope, + OwnerID: t.OwnerID, + ContainerID: item.ID, + ShortID: shortID(item.ID), + ContainerName: name, + }) + } + if item.State == "running" { + if st, fresh, ok := m.peekStatsCacheAny(name); ok { + ci.CPUPercent = st.CPUPercent + ci.MemUsageBytes = st.MemUsageBytes + ci.MemLimitBytes = st.MemLimitBytes + ci.PidsCurrent = st.PidsCurrent + if !fresh { + staleRunning = append(staleRunning, name) + } + } else if name != "" { + staleRunning = append(staleRunning, name) + } + } + out.Containers = append(out.Containers, ci) + } + if withStats { + var wg sync.WaitGroup + sem := make(chan struct{}, 8) + for i := range out.Containers { + if out.Containers[i].State != "running" || out.Containers[i].Name == "" { + continue + } + wg.Add(1) + sem <- struct{}{} + go func(idx int) { + defer wg.Done() + defer func() { <-sem }() + name := out.Containers[idx].Name + if st, err := m.cachedContainerStats(ctx, name); err == nil { + out.Containers[idx].CPUPercent = st.CPUPercent + out.Containers[idx].MemUsageBytes = st.MemUsageBytes + if st.MemLimitBytes > 0 { + out.Containers[idx].MemLimitBytes = st.MemLimitBytes + } + out.Containers[idx].PidsCurrent = st.PidsCurrent + } + }(i) + } + wg.Wait() + } else if len(staleRunning) > 0 { + m.triggerStatsRefresh(staleRunning) + } + sort.Slice(out.Containers, func(i, j int) bool { + if out.Containers[i].State != out.Containers[j].State { + return out.Containers[i].State == "running" + } + return out.Containers[i].Name < out.Containers[j].Name + }) + return out +} + +func (m *Manager) cachedContainerStats(ctx context.Context, name string) (dockerStats, error) { + if st, ok := m.peekStatsCache(name); ok { + return st, nil + } + sctx, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + st, err := m.docker.ContainerStats(sctx, name) + if err != nil { + return dockerStats{}, err + } + m.statsMu.Lock() + m.statsCache[name] = cachedStats{at: time.Now(), stats: st} + m.statsMu.Unlock() + return st, nil +} + +func (m *Manager) peekStatsCache(name string) (dockerStats, bool) { + st, fresh, ok := m.peekStatsCacheAny(name) + return st, ok && fresh +} + +func (m *Manager) peekStatsCacheAny(name string) (dockerStats, bool, bool) { + m.statsMu.Lock() + defer m.statsMu.Unlock() + c, ok := m.statsCache[name] + if !ok { + return dockerStats{}, false, false + } + return c.stats, time.Since(c.at) <= statsCacheTTL, true +} + +// triggerStatsRefresh asynchronously refreshes stale container stats in the +// background with per-container single-flight deduplication so non-blocking +// status calls stay sub-20ms while keeping stats warm. +func (m *Manager) triggerStatsRefresh(names []string) { + for _, name := range names { + if name == "" { + continue + } + m.statsMu.Lock() + if _, busy := m.statsInFlight[name]; busy { + m.statsMu.Unlock() + continue + } + m.statsInFlight[name] = struct{}{} + m.statsMu.Unlock() + + go func(containerName string) { + defer func() { + m.statsMu.Lock() + delete(m.statsInFlight, containerName) + m.statsMu.Unlock() + }() + sctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + if st, err := m.docker.ContainerStats(sctx, containerName); err == nil { + m.statsMu.Lock() + m.statsCache[containerName] = cachedStats{at: time.Now(), stats: st} + m.statsMu.Unlock() + } + }(name) + } +} +func (m *Manager) dropStatsCache(name string) { + m.statsMu.Lock() + delete(m.statsCache, name) + m.statsMu.Unlock() +} + +// Exec runs a command inside target's sandbox container, capturing combined +// stdout+stderr up to MaxOutput bytes, enforcing Timeout, and explicitly killing +// the container process group on timeout or context cancellation. +func (m *Manager) Exec(ctx context.Context, t Target, spec ExecSpec) ExecResult { + if !m.Enabled() { + return ExecResult{ExitCode: -1, Err: errors.New("sandbox docker mode not enabled")} + } + containerID, err := m.Ensure(ctx, t) + if err != nil { + return ExecResult{ExitCode: -1, Err: err} + } + m.Acquire(t) + defer m.Release(t) + + workDir := strings.TrimSpace(spec.WorkDir) + if workDir == "" { + workDir = ContainerWorkDir + } + // Ensure nested working dir (e.g. /workspace/i42) exists on host side. + if workDir != ContainerWorkDir { + if localSub, ok := ResolveConfined(m.Config().LocalRootFor(t), "", workDir); ok { + _ = ensureWritableDir(localSub, m.Config().User) + } + } + + maxOut := spec.MaxOutput + if maxOut <= 0 { + maxOut = defaultMaxExecOutput + } + + runCtx := ctx + var cancel context.CancelFunc + if spec.Timeout > 0 { + runCtx, cancel = context.WithTimeout(ctx, spec.Timeout) + defer cancel() + } + + cmd := spec.Cmd + var pgidFile string + if spec.KillOnAbort && len(cmd) > 0 { + pgidFile = "/tmp/.artex-pgid-" + randomToken(8) + cmd = wrapPGIDCommand(pgidFile, spec.Cmd) + } + + execID, err := m.docker.ExecCreate(runCtx, containerID, dockerExecCreateReq{ + AttachStdin: len(spec.Stdin) > 0, + AttachStdout: true, + AttachStderr: true, + Tty: false, + Env: spec.Env, + Cmd: cmd, + WorkingDir: workDir, + User: m.Config().User, + }) + if err != nil { + return ExecResult{ExitCode: -1, Err: err} + } + + stream, err := m.docker.ExecStartStream(runCtx, execID) + if err != nil { + return ExecResult{ExitCode: -1, Err: err} + } + defer stream.Close() + + if len(spec.Stdin) > 0 { + go func() { + _, _ = stream.Write(spec.Stdin) + _ = stream.CloseWrite() + }() + } + + outBuf := newCappedBuffer(maxOut) + var readWG sync.WaitGroup + readWG.Add(2) + go func() { + defer readWG.Done() + _, _ = io.Copy(outBuf, stream.stdout) + }() + go func() { + defer readWG.Done() + _, _ = io.Copy(outBuf, stream.stderr) + }() + + doneCh := make(chan error, 1) + go func() { + err := <-stream.done + readWG.Wait() + doneCh <- err + }() + + var timedOut bool + var runErr error + select { + case runErr = <-doneCh: + case <-runCtx.Done(): + timedOut = errors.Is(runCtx.Err(), context.DeadlineExceeded) + runErr = runCtx.Err() + _ = stream.Close() + if pgidFile != "" { + m.killProcessGroup(containerID, pgidFile) + } + select { + case <-doneCh: + case <-time.After(2 * time.Second): + } + } + + res := ExecResult{ + Output: outBuf.String(), + OutputTruncated: outBuf.Truncated(), + ExitCode: -1, + TimedOut: timedOut, + Err: runErr, + } + if !timedOut && ctx.Err() == nil { + inspectCtx, icancel := context.WithTimeout(context.Background(), 5*time.Second) + defer icancel() + if info, ierr := m.waitExecInspect(inspectCtx, execID); ierr == nil { + if info.Running { + if pgidFile != "" { + m.killProcessGroup(containerID, pgidFile) + } + if res.Err == nil { + res.Err = errors.New("sandbox exec stream closed prematurely while command was still running") + } + } else { + res.ExitCode = info.ExitCode + if info.ExitCode != 0 && res.Err == nil { + res.Err = fmt.Errorf("exit status %d", info.ExitCode) + } + } + } + } + return res +} + +// ExecStream opens a bidirectional stdio session inside target's sandbox +// container (used by stdio MCP servers like playwright-mcp and background tasks). +func (m *Manager) ExecStream(ctx context.Context, t Target, spec ExecSpec) (*StreamSession, error) { + if !m.Enabled() { + return nil, errors.New("sandbox docker mode not enabled") + } + containerID, err := m.Ensure(ctx, t) + if err != nil { + return nil, err + } + m.Acquire(t) + + workDir := strings.TrimSpace(spec.WorkDir) + if workDir == "" { + workDir = ContainerWorkDir + } + if workDir != ContainerWorkDir { + if localSub, ok := ResolveConfined(m.Config().LocalRootFor(t), "", workDir); ok { + _ = ensureWritableDir(localSub, m.Config().User) + } + } + + pgidFile := "/tmp/.artex-stream-" + randomToken(8) + cmd := wrapPGIDCommand(pgidFile, spec.Cmd) + + execID, err := m.docker.ExecCreate(ctx, containerID, dockerExecCreateReq{ + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + Tty: false, + Env: spec.Env, + Cmd: cmd, + WorkingDir: workDir, + User: m.Config().User, + }) + if err != nil { + m.Release(t) + return nil, err + } + + stream, err := m.docker.ExecStartStream(ctx, execID) + if err != nil { + m.Release(t) + return nil, err + } + + var releaseOnce sync.Once + release := func() { + releaseOnce.Do(func() { + m.Release(t) + }) + } + + stdinWriter := &hijackedWriteCloser{h: stream} + return &StreamSession{ + Stdin: stdinWriter, + Stdout: stream.stdout, + Stderr: stream.stderr, + waitFn: func() (int, error) { + err := <-stream.done + release() + inspectCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if info, ierr := m.docker.ExecInspect(inspectCtx, execID); ierr == nil { + return info.ExitCode, err + } + return -1, err + }, + closeFn: func() error { + err := stream.Close() + m.killProcessGroup(containerID, pgidFile) + release() + return err + }, + }, nil +} + +// wrapPGIDCommand records the exec process PID before replacing the shell with +// the target command. Docker's runc already places every exec process into its +// own session and process group (PID == PGID == SID), so we must NOT invoke +// util-linux `setsid` (which without `--wait` forks when PID == PGID and exits +// 0 immediately, causing containerd to cut off stdout/stderr at ~2s and masking +// non-zero exit codes). +func wrapPGIDCommand(pgidFile string, cmd []string) []string { + wrapped := fmt.Sprintf(`echo $$ > %q; exec "$@"`, pgidFile) + return append([]string{"sh", "-c", wrapped, "--"}, cmd...) +} + +// waitExecInspect polls Docker ExecInspect briefly after the stdio stream closes +// so containerd's final Running->false transition settles before reading ExitCode. +func (m *Manager) waitExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) { + var ( + info dockerExecInspect + err error + ) + backoffs := []time.Duration{0, 15 * time.Millisecond, 40 * time.Millisecond, 100 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond} + for _, d := range backoffs { + if d > 0 { + select { + case <-ctx.Done(): + return info, ctx.Err() + case <-time.After(d): + } + } + info, err = m.docker.ExecInspect(ctx, execID) + if err != nil || !info.Running { + return info, err + } + } + return info, err +} + +type hijackedWriteCloser struct { + h *hijackedExec +} + +func (w *hijackedWriteCloser) Write(p []byte) (int, error) { return w.h.Write(p) } +func (w *hijackedWriteCloser) Close() error { return w.h.CloseWrite() } + +// killProcessGroup sends SIGTERM then SIGKILL to the tracked process group +// inside containerID so cancelled/timed-out tools never linger. +func (m *Manager) killProcessGroup(containerID, pgidFile string) { + kctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + script := fmt.Sprintf( + `if [ -f %q ]; then p=$(cat %q 2>/dev/null); rm -f %q; if [ -n "$p" ]; then kill -TERM -- -"$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null || true; sleep 1; kill -KILL -- -"$p" 2>/dev/null || kill -KILL "$p" 2>/dev/null || true; fi; fi`, + pgidFile, pgidFile, pgidFile, + ) + execID, err := m.docker.ExecCreate(kctx, containerID, dockerExecCreateReq{ + AttachStdout: true, + AttachStderr: true, + Cmd: []string{"sh", "-c", script}, + User: m.Config().User, + }) + if err != nil { + return + } + s, err := m.docker.ExecStartStream(kctx, execID) + if err != nil { + return + } + defer s.Close() + go io.Copy(io.Discard, s.stdout) + go io.Copy(io.Discard, s.stderr) + select { + case <-s.done: + case <-kctx.Done(): + } +} + +func ensureWritableDir(dir, userSpec string) error { + if err := os.MkdirAll(dir, 0o777); err != nil { + return err + } + uid, gid := -1, -1 + if os.Geteuid() == 0 && userSpec != "" { + uid, gid = parseUIDGID(userSpec) + } + // Best-effort chmod + chown on dir AND pre-existing non-symlink entries so + // workspaces migrated from root-owned standalone deployments remain writable + // by the non-root sandbox user without ever following symlinks. + _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if d.Type()&os.ModeSymlink != 0 { + return nil + } + if d.IsDir() { + _ = os.Chmod(p, 0o777) + } else if info, err := d.Info(); err == nil { + // Preserve execute bits while ensuring non-root sandbox user can write. + _ = os.Chmod(p, info.Mode().Perm()|0o666) + } + if uid >= 0 { + _ = os.Lchown(p, uid, gid) + } + return nil + }) + return nil +} + +func parseUIDGID(spec string) (int, int) { + parts := strings.Split(strings.TrimSpace(spec), ":") + uid, err := strconv.Atoi(parts[0]) + if err != nil { + return -1, -1 + } + gid := uid + if len(parts) > 1 { + if g, err := strconv.Atoi(parts[1]); err == nil { + gid = g + } + } + return uid, gid +} + +func shortID(id string) string { + if len(id) > 12 { + return id[:12] + } + return id +} + +func randomToken(n int) string { + b := make([]byte, n) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +type cappedBuffer struct { + mu sync.Mutex + buf bytes.Buffer + limit int + truncated bool +} + +func newCappedBuffer(limit int) *cappedBuffer { return &cappedBuffer{limit: limit} } + +func (b *cappedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + n := len(p) + if b.limit <= 0 { + _, _ = b.buf.Write(p) + return n, nil + } + rem := b.limit - b.buf.Len() + if rem <= 0 { + b.truncated = true + return n, nil + } + if len(p) > rem { + _, _ = b.buf.Write(p[:rem]) + b.truncated = true + return n, nil + } + _, _ = b.buf.Write(p) + return n, nil +} + +func (b *cappedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func (b *cappedBuffer) Truncated() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.truncated +} diff --git a/internal/sandbox/path.go b/internal/sandbox/path.go new file mode 100644 index 0000000..9b7a1b2 --- /dev/null +++ b/internal/sandbox/path.go @@ -0,0 +1,224 @@ +package sandbox + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// ResolveConfined maps candidate (which may be relative to root, relative to +// defaultSubdir, or rooted at ContainerWorkDir "/workspace") to an absolute +// path inside root, verifying that neither lexical traversal ("..") nor any +// existing symlink component escapes root. +func ResolveConfined(root, defaultSubdir, candidate string) (string, bool) { + rootClean := filepath.Clean(root) + if rootClean == "" || rootClean == "." { + return "", false + } + rootReal, err := evalDeepest(rootClean) + if err != nil { + return "", false + } + + raw := strings.TrimSpace(candidate) + var joined string + switch { + case raw == "" || raw == ".": + if defaultSubdir != "" { + joined = filepath.Join(rootClean, defaultSubdir) + } else { + joined = rootClean + } + case raw == ContainerWorkDir || strings.HasPrefix(raw, ContainerWorkDir+"/"): + rel := strings.TrimPrefix(raw, ContainerWorkDir) + rel = strings.TrimPrefix(rel, "/") + joined = filepath.Join(rootClean, filepath.FromSlash(rel)) + case filepath.IsAbs(raw): + cleaned := filepath.Clean(raw) + if !isWithin(rootClean, cleaned) && !isWithin(rootReal, cleaned) { + return "", false + } + joined = cleaned + default: + if defaultSubdir != "" { + joined = filepath.Join(rootClean, defaultSubdir, filepath.FromSlash(raw)) + } else { + joined = filepath.Join(rootClean, filepath.FromSlash(raw)) + } + } + + joined = filepath.Clean(joined) + if !isWithin(rootClean, joined) && !isWithin(rootReal, joined) { + return "", false + } + + resolved, err := evalDeepest(joined) + if err != nil { + return "", false + } + if !isWithin(rootReal, resolved) { + return "", false + } + return resolved, true +} + +// CheckPathWithinRoot verifies an already-resolved host path stays within root +// after resolving symlinks (blocking symlink escape attacks from sandbox containers). +func CheckPathWithinRoot(root, candidate string) (string, bool) { + rootClean := filepath.Clean(root) + rootReal, err := evalDeepest(rootClean) + if err != nil { + return "", false + } + resolved, err := evalDeepest(filepath.Clean(candidate)) + if err != nil { + return "", false + } + if !isWithin(rootReal, resolved) { + return "", false + } + return resolved, true +} + +// HostToContainerPath maps a host path under targetRoot to its container-visible +// "/workspace/..." path. Returns ContainerWorkDir if hostPath equals targetRoot. +func HostToContainerPath(targetRoot, hostPath string) string { + rootClean := filepath.Clean(targetRoot) + hostClean := filepath.Clean(hostPath) + rel, err := filepath.Rel(rootClean, hostClean) + if err != nil || rel == "." || strings.HasPrefix(rel, "..") { + return ContainerWorkDir + } + return ContainerWorkDir + "/" + filepath.ToSlash(rel) +} + +// MapDataPathToHost translates a path inside artex's local DataDir to the +// corresponding host filesystem path for Docker bind mounts. +func (c Config) MapDataPathToHost(localPath string) string { + localClean := filepath.Clean(localPath) + dataClean := filepath.Clean(c.DataDir) + hostClean := filepath.Clean(c.HostDataDir) + if dataClean == hostClean { + return localClean + } + if localClean == dataClean { + return hostClean + } + rel, err := filepath.Rel(dataClean, localClean) + if err != nil || strings.HasPrefix(rel, "..") { + return localClean + } + return filepath.Join(hostClean, rel) +} + +// LocalRootFor returns the local filesystem directory backing a Target inside DataDir. +func (c Config) LocalRootFor(t Target) string { + switch t.Scope { + case ScopeTask: + return filepath.Join(c.DataDir, "tasks", t.OwnerID) + case ScopeSession: + return filepath.Join(c.DataDir, "sessions", t.OwnerID) + case ScopeEphemeral: + return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID)) + default: + return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID)) + } +} + +// CopyRegularFileSafe copies a regular file (refusing symlinks, sockets, FIFOs, +// and directories) from srcPath (confined to srcRoot) into dstDir under dstRoot, +// choosing a unique non-clobbering filename. Returns the relative path inside dstRoot. +func CopyRegularFileSafe(srcRoot, srcPath, dstRoot, dstSubdir string) (string, error) { + resolvedSrc, ok := ResolveConfined(srcRoot, "", srcPath) + if !ok { + return "", errors.New("source path escapes allowed root") + } + lfi, err := os.Lstat(resolvedSrc) + if err != nil { + return "", err + } + if !lfi.Mode().IsRegular() { + return "", fmt.Errorf("refusing non-regular file: %s", filepath.Base(resolvedSrc)) + } + + dstDir := filepath.Join(filepath.Clean(dstRoot), dstSubdir) + if err := os.MkdirAll(dstDir, 0o777); err != nil { + return "", err + } + if _, ok := CheckPathWithinRoot(dstRoot, dstDir); !ok { + return "", errors.New("destination escapes allowed root") + } + + base := filepath.Base(resolvedSrc) + ext := filepath.Ext(base) + stem := strings.TrimSuffix(base, ext) + dstPath := filepath.Join(dstDir, base) + for i := 1; ; i++ { + if _, err := os.Lstat(dstPath); os.IsNotExist(err) { + break + } + dstPath = filepath.Join(dstDir, fmt.Sprintf("%s-%d%s", stem, i, ext)) + } + + in, err := os.Open(resolvedSrc) + if err != nil { + return "", err + } + defer in.Close() + + out, err := os.OpenFile(dstPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o666) + if err != nil { + return "", err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + _ = os.Remove(dstPath) + return "", err + } + if err := out.Close(); err != nil { + _ = os.Remove(dstPath) + return "", err + } + rel, err := filepath.Rel(filepath.Clean(dstRoot), dstPath) + if err != nil { + return "", err + } + return filepath.ToSlash(rel), nil +} + +// evalDeepest resolves symlinks for the deepest existing ancestor of p and +// re-attaches any non-existent trailing path components. +func evalDeepest(p string) (string, error) { + p = filepath.Clean(p) + if real, err := filepath.EvalSymlinks(p); err == nil { + return real, nil + } + var tail []string + cur := p + for { + parent := filepath.Dir(cur) + if parent == cur { + return p, nil + } + tail = append([]string{filepath.Base(cur)}, tail...) + cur = parent + if real, err := filepath.EvalSymlinks(cur); err == nil { + parts := append([]string{real}, tail...) + return filepath.Clean(filepath.Join(parts...)), nil + } + } +} + +func isWithin(root, candidate string) bool { + if candidate == root { + return true + } + sep := string(os.PathSeparator) + if strings.HasSuffix(root, sep) { + return strings.HasPrefix(candidate, root) + } + return strings.HasPrefix(candidate, root+sep) +} diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go new file mode 100644 index 0000000..157125a --- /dev/null +++ b/internal/sandbox/sandbox_test.go @@ -0,0 +1,254 @@ +package sandbox + +import ( + "bytes" + "encoding/binary" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestResolveConfinedBlocksTraversalAndSymlinkEscape(t *testing.T) { + tmp := t.TempDir() + root := filepath.Join(tmp, "tasks", "42") + outside := filepath.Join(tmp, "secret.txt") + if err := os.MkdirAll(filepath.Join(root, "i10"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(outside, []byte("top-secret"), 0o600); err != nil { + t.Fatal(err) + } + // Symlink inside workspace pointing outside + escapeLink := filepath.Join(root, "i10", "evil.txt") + if err := os.Symlink(outside, escapeLink); err != nil { + t.Fatal(err) + } + // Symlink directory pointing outside + escapeDir := filepath.Join(root, "escape-dir") + if err := os.Symlink(tmp, escapeDir); err != nil { + t.Fatal(err) + } + + // Valid container paths + got, ok := ResolveConfined(root, "i10", "/workspace/i10/out.txt") + if !ok { + t.Fatalf("expected valid container path to resolve") + } + wantReal, _ := filepath.EvalSymlinks(filepath.Join(root, "i10")) + if got != filepath.Join(wantReal, "out.txt") { + t.Fatalf("got %q, want %q", got, filepath.Join(wantReal, "out.txt")) + } + + // Relative path resolves under defaultSubdir + gotRel, ok := ResolveConfined(root, "i10", "notes.md") + if !ok || gotRel != filepath.Join(wantReal, "notes.md") { + t.Fatalf("relative resolve got (%q, %v)", gotRel, ok) + } + + // Blocked cases: traversal, outside abs path, symlink file, symlink dir + new leaf + for _, bad := range []string{ + "../../secret.txt", + "/etc/passwd", + outside, + "/workspace/i10/evil.txt", + "evil.txt", + "/workspace/escape-dir/secret.txt", + "/workspace/escape-dir/new-file.txt", + } { + if p, ok := ResolveConfined(root, "i10", bad); ok { + t.Fatalf("expected %q to be rejected, got %q", bad, p) + } + } +} + +func TestCopyRegularFileSafeSkipsSymlinksAndDeduplicates(t *testing.T) { + tmp := t.TempDir() + srcRoot := filepath.Join(tmp, "sessions", "conv-1") + dstRoot := filepath.Join(tmp, "tasks", "99") + if err := os.MkdirAll(filepath.Join(srcRoot, "uploads"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(dstRoot, 0o755); err != nil { + t.Fatal(err) + } + srcFile := filepath.Join(srcRoot, "uploads", "targets.txt") + if err := os.WriteFile(srcFile, []byte("example.com\n"), 0o644); err != nil { + t.Fatal(err) + } + outside := filepath.Join(tmp, "jwt.key") + if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil { + t.Fatal(err) + } + sym := filepath.Join(srcRoot, "uploads", "link.txt") + if err := os.Symlink(outside, sym); err != nil { + t.Fatal(err) + } + + rel1, err := CopyRegularFileSafe(srcRoot, "/workspace/uploads/targets.txt", dstRoot, "uploads") + if err != nil || rel1 != "uploads/targets.txt" { + t.Fatalf("first copy = (%q, %v)", rel1, err) + } + rel2, err := CopyRegularFileSafe(srcRoot, "uploads/targets.txt", dstRoot, "uploads") + if err != nil || rel2 != "uploads/targets-1.txt" { + t.Fatalf("dedup copy = (%q, %v)", rel2, err) + } + if _, err := CopyRegularFileSafe(srcRoot, "uploads/link.txt", dstRoot, "uploads"); err == nil { + t.Fatalf("expected symlink copy to be rejected") + } +} + +func TestDemuxDockerStream(t *testing.T) { + var raw bytes.Buffer + writeFrame := func(kind byte, msg string) { + var hdr [8]byte + hdr[0] = kind + binary.BigEndian.PutUint32(hdr[4:8], uint32(len(msg))) + raw.Write(hdr[:]) + raw.WriteString(msg) + } + writeFrame(1, "hello ") + writeFrame(2, "warn!") + writeFrame(1, "world") + + var stdout, stderr bytes.Buffer + if err := demuxDockerStream(&raw, &stdout, &stderr); err != nil { + t.Fatal(err) + } + if stdout.String() != "hello world" || stderr.String() != "warn!" { + t.Fatalf("stdout=%q stderr=%q", stdout.String(), stderr.String()) + } +} + +func TestHostToContainerAndDataPathMapping(t *testing.T) { + cfg := Config{ + DataDir: "/app/data", + HostDataDir: "/srv/artex/data", + } + if got := cfg.MapDataPathToHost("/app/data/tasks/12"); got != "/srv/artex/data/tasks/12" { + t.Fatalf("MapDataPathToHost = %q", got) + } + if got := HostToContainerPath("/app/data/tasks/12", "/app/data/tasks/12/i7"); got != "/workspace/i7" { + t.Fatalf("HostToContainerPath = %q", got) + } + if got := HostToContainerPath("/app/data/tasks/12", "/app/data/tasks/12"); got != "/workspace" { + t.Fatalf("HostToContainerPath root = %q", got) + } +} + +func TestManagerContainerIPMap(t *testing.T) { + m := &Manager{ipMap: map[string]ContainerIdentity{}} + m.registerContainerIP("172.28.0.5", ContainerIdentity{ + Scope: ScopeTask, + OwnerID: "12", + ContainerID: "abc123def456", + ContainerName: "artex-sbx-inst-task-12", + IP: "172.28.0.5", + }) + got, ok := m.ResolveContainerByIP("172.28.0.5:54321") + if !ok || got.Scope != ScopeTask || got.OwnerID != "12" || got.ContainerID != "abc123def456" { + t.Fatalf("ResolveContainerByIP failed: ok=%v got=%+v", ok, got) + } + // Re-registering same container with a new IP must evict the stale IP. + m.registerContainerIP("172.28.0.9", ContainerIdentity{ + Scope: ScopeTask, + OwnerID: "12", + ContainerID: "new999888777", + ContainerName: "artex-sbx-inst-task-12", + IP: "172.28.0.9", + }) + if _, stale := m.ResolveContainerByIP("172.28.0.5"); stale { + t.Fatalf("stale IP 172.28.0.5 should have been evicted") + } + if got2, ok2 := m.ResolveContainerByIP("172.28.0.9"); !ok2 || got2.ContainerID != "new999888777" { + t.Fatalf("new IP 172.28.0.9 lookup failed: ok=%v got=%+v", ok2, got2) + } + // Explicit eviction by container name. + m.evictContainerIP("artex-sbx-inst-task-12") + if _, ok3 := m.ResolveContainerByIP("172.28.0.9"); ok3 { + t.Fatalf("evicted container IP should no longer resolve") + } +} + +func TestConfigFromEnvAllowNetRaw(t *testing.T) { + t.Setenv("ARTEX_SANDBOX_ALLOW_NET_RAW", "") + if cfg := ConfigFromEnv(t.TempDir(), ""); !cfg.AllowNetRaw { + t.Fatalf("AllowNetRaw should default to true") + } + t.Setenv("ARTEX_SANDBOX_ALLOW_NET_RAW", "false") + if cfg := ConfigFromEnv(t.TempDir(), ""); cfg.AllowNetRaw { + t.Fatalf("AllowNetRaw should respect ARTEX_SANDBOX_ALLOW_NET_RAW=false") + } +} + +func TestEnsureWritableDirMigratesNestedFilesWithoutFollowingSymlinks(t *testing.T) { + tmp := t.TempDir() + outside := filepath.Join(tmp, "outside-secret.txt") + if err := os.WriteFile(outside, []byte("secret"), 0o400); err != nil { + t.Fatal(err) + } + + ws := filepath.Join(tmp, "tasks", "99") + nestedDir := filepath.Join(ws, "findings") + nestedFile := filepath.Join(nestedDir, "note.txt") + if err := os.MkdirAll(nestedDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(nestedFile, []byte("migrated"), 0o444); err != nil { + t.Fatal(err) + } + if err := os.Chmod(nestedDir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(nestedDir, 0o755) }) + + if err := os.Symlink(outside, filepath.Join(ws, "escape-link")); err != nil { + t.Fatal(err) + } + + if err := ensureWritableDir(ws, "1000:1000"); err != nil { + t.Fatalf("ensureWritableDir: %v", err) + } + + fi, err := os.Stat(nestedFile) + if err != nil { + t.Fatalf("stat nestedFile: %v", err) + } + if fi.Mode().Perm()&0o222 != 0o222 { + t.Fatalf("nested migrated file should be writable, got mode=%o", fi.Mode().Perm()) + } + outInfo, err := os.Stat(outside) + if err != nil { + t.Fatalf("stat outside: %v", err) + } + if outInfo.Mode().Perm() != 0o400 { + t.Fatalf("symlink target outside workspace must stay 0400, got %o", outInfo.Mode().Perm()) + } +} + +func TestWrapPGIDCommandDoesNotDetachAndPropagatesExitCode(t *testing.T) { + pgidFile := filepath.Join(t.TempDir(), "test.pgid") + cmd := wrapPGIDCommand(pgidFile, []string{"sh", "-c", "echo hi; exit 42"}) + if len(cmd) == 0 || cmd[0] == "setsid" { + t.Fatalf("wrapPGIDCommand must not wrap with detaching setsid, got %v", cmd) + } + if runtime.GOOS == "windows" { + return + } + c := exec.Command(cmd[0], cmd[1:]...) + out, err := c.CombinedOutput() + if strings.TrimSpace(string(out)) != "hi" { + t.Fatalf("expected output 'hi', got %q (err=%v)", string(out), err) + } + var exitErr *exec.ExitError + if !errors.As(err, &exitErr) || exitErr.ExitCode() != 42 { + t.Fatalf("expected exit code 42, got err=%v", err) + } + pidBytes, rerr := os.ReadFile(pgidFile) + if rerr != nil || strings.TrimSpace(string(pidBytes)) == "" { + t.Fatalf("expected pgid file to contain PID, got %q err=%v", string(pidBytes), rerr) + } +} diff --git a/internal/sandbox/types.go b/internal/sandbox/types.go new file mode 100644 index 0000000..a7c6b87 --- /dev/null +++ b/internal/sandbox/types.go @@ -0,0 +1,333 @@ +package sandbox + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +// Mode controls whether agent execution runs locally or inside isolated Docker containers. +type Mode string + +const ( + ModeLocal Mode = "local" + ModeDocker Mode = "docker" +) + +// Scope identifies what owns a sandbox container. +type Scope string + +const ( + ScopeTask Scope = "task" + ScopeSession Scope = "session" + ScopeEphemeral Scope = "ephemeral" +) + +// ContainerWorkDir is the canonical workspace mount point inside every sandbox container. +const ContainerWorkDir = "/workspace" + +// ContainerCACertPath is where the recording MITM proxy CA cert is mounted read-only. +const ContainerCACertPath = "/etc/artex/ca.crt" + +// ContainerSystemCABundlePath is where the merged system + ARTEX MITM CA bundle +// is mounted read-only so static Go binaries and system TLS libraries trust the +// recording proxy without needing root or runtime update-ca-certificates (#218 Phase 3). +const ContainerSystemCABundlePath = "/etc/ssl/certs/ca-certificates.crt" +// Target identifies a logical sandbox instance. +type Target struct { + Scope Scope + OwnerID string +} + +func (t Target) Valid() bool { + return t.Scope != "" && strings.TrimSpace(t.OwnerID) != "" +} + +func (t Target) Key() string { + return string(t.Scope) + ":" + t.OwnerID +} + +// Config configures the sandbox manager. Env vars supply startup defaults; +// persisted DB settings can override mutable runtime fields via ApplyOverrides. +type Config struct { + Mode Mode + DockerHost string + Image string + Network string + Runtime string + DataDir string + HostDataDir string + ProxyURL string + CACertPath string + SystemCABundlePath string + TransparentGateway bool + GatewayDNSIP string + MemoryMB int + CPUs float64 + PidsLimit int + ShmSizeMB int + TmpSizeMB int + User string + AllowNetRaw bool + AutoStopOnComplete bool + SessionIdleMinutes int + InstanceID string +} + +// RuntimeOverrides carries settings editable from the Settings UI / API. +type RuntimeOverrides struct { + Image *string `json:"image,omitempty"` + MemoryMB *int `json:"memory_mb,omitempty"` + CPUs *float64 `json:"cpus,omitempty"` + PidsLimit *int `json:"pids_limit,omitempty"` + ShmSizeMB *int `json:"shm_size_mb,omitempty"` + Runtime *string `json:"runtime,omitempty"` + AutoStopOnComplete *bool `json:"auto_stop_on_complete,omitempty"` + SessionIdleMinutes *int `json:"session_idle_minutes,omitempty"` +} + +// ConfigFromEnv builds a Config from environment variables with safe defaults. +func ConfigFromEnv(dataDir, caCertPath string) Config { + mode := Mode(strings.ToLower(strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_MODE")))) + if mode != ModeDocker { + mode = ModeLocal + } + dockerHost := strings.TrimSpace(os.Getenv("ARTEX_DOCKER_HOST")) + if dockerHost == "" { + dockerHost = strings.TrimSpace(os.Getenv("DOCKER_HOST")) + } + if dockerHost == "" { + dockerHost = "unix:///var/run/docker.sock" + } + hostDataDir := strings.TrimSpace(os.Getenv("ARTEX_HOST_DATA_DIR")) + if hostDataDir == "" { + hostDataDir = dataDir + } + image := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_IMAGE")) + if image == "" { + image = "ruoji6/artex-sandbox:latest" + } + network := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_NETWORK")) + if network == "" { + network = "artex-sandbox" + } + user := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_USER")) + if user == "" { + user = "1000:1000" + } + instanceID := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_INSTANCE")) + if instanceID == "" { + sum := sha256.Sum256([]byte(filepath.Clean(hostDataDir))) + instanceID = hex.EncodeToString(sum[:4]) + } + return Config{ + Mode: mode, + DockerHost: dockerHost, + Image: image, + Network: network, + Runtime: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_RUNTIME")), + DataDir: filepath.Clean(dataDir), + HostDataDir: filepath.Clean(hostDataDir), + ProxyURL: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_PROXY_URL")), + CACertPath: strings.TrimSpace(caCertPath), + TransparentGateway: envBool("ARTEX_SANDBOX_TRANSPARENT", true), + GatewayDNSIP: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_DNS")), + MemoryMB: envInt("ARTEX_SANDBOX_MEMORY_MB", 2048, 256), + CPUs: envFloat("ARTEX_SANDBOX_CPUS", 2.0, 0.25), + PidsLimit: envInt("ARTEX_SANDBOX_PIDS_LIMIT", 256, 32), + ShmSizeMB: envInt("ARTEX_SANDBOX_SHM_MB", 512, 64), + TmpSizeMB: envInt("ARTEX_SANDBOX_TMP_MB", 512, 64), + User: user, + AllowNetRaw: envBool("ARTEX_SANDBOX_ALLOW_NET_RAW", true), + AutoStopOnComplete: envBool("ARTEX_SANDBOX_AUTO_STOP", true), + SessionIdleMinutes: envInt("ARTEX_SANDBOX_SESSION_IDLE_MIN", 20, 1), + InstanceID: instanceID, + } +} + +func envInt(key string, def, min int) int { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return def + } + v, err := strconv.Atoi(raw) + if err != nil || v < min { + return def + } + return v +} + +func envFloat(key string, def, min float64) float64 { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return def + } + v, err := strconv.ParseFloat(raw, 64) + if err != nil || v < min { + return def + } + return v +} + +func envBool(key string, def bool) bool { + raw := strings.ToLower(strings.TrimSpace(os.Getenv(key))) + switch raw { + case "1", "true", "yes", "on": + return true + case "0", "false", "no", "off": + return false + default: + return def + } +} + +// ContainerInfo describes one sandbox container for API/UI reporting. +type ContainerIdentity struct { + Scope Scope `json:"scope"` + OwnerID string `json:"owner_id"` + ContainerID string `json:"container_id"` + ShortID string `json:"short_id"` + ContainerName string `json:"container_name"` + IP string `json:"ip"` +} + +type ContainerInfo struct { + Scope Scope `json:"scope"` + OwnerID string `json:"owner_id"` + OwnerTitle string `json:"owner_title,omitempty"` + TaskRunning bool `json:"task_running,omitempty"` + Name string `json:"name"` + ContainerID string `json:"container_id,omitempty"` + ShortID string `json:"short_id,omitempty"` + IPAddress string `json:"ip_address,omitempty"` + Image string `json:"image"` + State string `json:"state"` // running | exited | created | missing | local | error + StatusText string `json:"status_text,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + StartedAt string `json:"started_at,omitempty"` + ActiveRuns int `json:"active_runs"` + CPUPercent float64 `json:"cpu_percent,omitempty"` + MemUsageBytes uint64 `json:"mem_usage_bytes,omitempty"` + MemLimitBytes uint64 `json:"mem_limit_bytes,omitempty"` + PidsCurrent uint64 `json:"pids_current,omitempty"` + WorkDirContainer string `json:"work_dir_container"` + Network string `json:"network,omitempty"` + Runtime string `json:"runtime,omitempty"` + Error string `json:"error,omitempty"` +} + +// GlobalStatus is returned by GET /api/sandbox/status. +type GlobalStatus struct { + Mode Mode `json:"mode"` + Enabled bool `json:"enabled"` + Available bool `json:"available"` + Error string `json:"error,omitempty"` + Image string `json:"image"` + Network string `json:"network"` + Runtime string `json:"runtime"` + MemoryMB int `json:"memory_mb"` + CPUs float64 `json:"cpus"` + PidsLimit int `json:"pids_limit"` + ShmSizeMB int `json:"shm_size_mb"` + AutoStopOnComplete bool `json:"auto_stop_on_complete"` + SessionIdleMinutes int `json:"session_idle_minutes"` + Containers []ContainerInfo `json:"containers"` +} + +// ExecSpec describes one command invocation inside a sandbox container. +type ExecSpec struct { + Cmd []string + WorkDir string // container path; defaults to ContainerWorkDir + Env []string + Stdin []byte + Timeout time.Duration + MaxOutput int + KillOnAbort bool // wrap with PGID tracking so cancel/timeout kills child tree +} + +// ExecResult captures the result of a foreground sandbox Exec. +type ExecResult struct { + Output string + OutputTruncated bool + ExitCode int + TimedOut bool + Err error +} + +// StreamSession represents a live bidirectional stdio exec inside a sandbox. +type StreamSession struct { + Stdin io.WriteCloser + Stdout io.ReadCloser + Stderr io.ReadCloser + + waitFn func() (int, error) + closeFn func() error +} + +func (s *StreamSession) Wait() (int, error) { + if s == nil || s.waitFn == nil { + return 0, nil + } + return s.waitFn() +} + +func (s *StreamSession) Close() error { + if s == nil || s.closeFn == nil { + return nil + } + return s.closeFn() +} + +type targetCtxKey struct{} + +// WithTarget attaches a sandbox Target to ctx. +func WithTarget(ctx context.Context, t Target) context.Context { + if !t.Valid() { + return ctx + } + return context.WithValue(ctx, targetCtxKey{}, t) +} + +// TargetFrom extracts the sandbox Target from ctx, if present. +func TargetFrom(ctx context.Context) (Target, bool) { + if ctx == nil { + return Target{}, false + } + t, ok := ctx.Value(targetCtxKey{}).(Target) + if !ok || !t.Valid() { + return Target{}, false + } + return t, true +} + +// ContainerName returns a deterministic, Docker-safe container name for target. +func (c Config) ContainerName(t Target) string { + cleanID := sanitizeToken(t.OwnerID) + return fmt.Sprintf("artex-sbx-%s-%s-%s", c.InstanceID, string(t.Scope), cleanID) +} + +func sanitizeToken(s string) string { + var b strings.Builder + for _, r := range strings.ToLower(strings.TrimSpace(s)) { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { + b.WriteRune(r) + } else { + b.WriteByte('-') + } + } + out := strings.Trim(b.String(), "-") + if out == "" { + return "0" + } + if len(out) > 48 { + out = out[:48] + } + return out +} diff --git a/internal/toolguard/background.go b/internal/toolguard/background.go index c7149cb..cca4297 100644 --- a/internal/toolguard/background.go +++ b/internal/toolguard/background.go @@ -3,25 +3,31 @@ package toolguard import ( "context" "fmt" + "io" "os" "os/exec" + "os/signal" "runtime" "strconv" "strings" + "sync" + "syscall" "time" + "github.com/Autumn-27/artex/internal/sandbox" actool "github.com/Autumn-27/norma/tool" ) - const ( - backgroundArg = "--artex-internal-background-tool" - backgroundExe = "_ARTEX_BG_EXE" - backgroundCommand = "_ARTEX_BG_COMMAND" - backgroundTimeout = "_ARTEX_BG_TIMEOUT" - backgroundCgroup = "_ARTEX_BG_CGROUP" - outputLimitNote = "\n\n[output truncated at capture limit]" + backgroundArg = "--artex-internal-background-tool" + backgroundExe = "_ARTEX_BG_EXE" + backgroundCommand = "_ARTEX_BG_COMMAND" + backgroundTimeout = "_ARTEX_BG_TIMEOUT" + backgroundCgroup = "_ARTEX_BG_CGROUP" + backgroundSandboxScope = "_ARTEX_BG_SANDBOX_SCOPE" + backgroundSandboxOwner = "_ARTEX_BG_SANDBOX_OWNER" + backgroundSandboxWorkDir = "_ARTEX_BG_SANDBOX_WORKDIR" + outputLimitNote = "\n\n[output truncated at capture limit]" ) - // The SDK's task manager only accepts a shell command, not an exec hook. Its // shell execs this binary in a lightweight helper mode, keeping the manager's // task ID, streaming output, notifications, and cancellation semantics. @@ -89,7 +95,13 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) { } command, dir := os.Getenv(backgroundCommand), os.Getenv(backgroundCgroup) timeout, err := time.ParseDuration(os.Getenv(backgroundTimeout)) - for _, name := range []string{backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup} { + sbScope := os.Getenv(backgroundSandboxScope) + sbOwner := os.Getenv(backgroundSandboxOwner) + sbWorkDir := os.Getenv(backgroundSandboxWorkDir) + for _, name := range []string{ + backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup, + backgroundSandboxScope, backgroundSandboxOwner, backgroundSandboxWorkDir, + } { _ = os.Unsetenv(name) } if command == "" || err != nil || timeout <= 0 { @@ -98,6 +110,9 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) { } cfg := FromEnv() cfg.MaxOutputBytes -= 4096 // leave room for the error note below norma's task-file cap + if sbScope != "" && sbOwner != "" { + return runBackgroundHelperSandbox(cfg, sandbox.Target{Scope: sandbox.Scope(sbScope), OwnerID: sbOwner}, sbWorkDir, command, timeout), true + } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() shell, flags := platformShellCmd() @@ -124,3 +139,142 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) { return 1, true } } + +func runGuardedBashBackgroundSandbox(tc *actool.ToolContext, mgr *sandbox.Manager, target sandbox.Target, containerWorkDir string, cfg Config, command string, timeout time.Duration) (actool.Result, error) { + exe, err := os.Executable() + if err != nil { + return actool.Errorf("Error: failed to locate background helper: " + err.Error()), nil + } + sbCfg := mgr.Config() + env := append([]string{}, tc.Env...) + env = append(env, + backgroundExe+"="+exe, + backgroundCommand+"="+command, + backgroundTimeout+"="+timeout.String(), + backgroundSandboxScope+"="+string(target.Scope), + backgroundSandboxOwner+"="+target.OwnerID, + backgroundSandboxWorkDir+"="+containerWorkDir, + "ARTEX_SANDBOX_MODE=docker", + "ARTEX_DOCKER_HOST="+sbCfg.DockerHost, + "ARTEX_SANDBOX_IMAGE="+sbCfg.Image, + "ARTEX_SANDBOX_NETWORK="+sbCfg.Network, + "ARTEX_SANDBOX_RUNTIME="+sbCfg.Runtime, + "ARTEX_SANDBOX_USER="+sbCfg.User, + "ARTEX_SANDBOX_INSTANCE="+sbCfg.InstanceID, + "ARTEX_HOST_DATA_DIR="+sbCfg.HostDataDir, + "_ARTEX_BG_DATA_DIR="+sbCfg.DataDir, + EnvToolMemoryLimitMB+"="+strconv.Itoa(cfg.MemoryLimitMB), + EnvToolPidsLimit+"="+strconv.Itoa(cfg.PidsLimit), + ) + trampoline := `exec "$` + backgroundExe + `" ` + backgroundArg + if runtime.GOOS == "windows" { + trampoline = `& $env:` + backgroundExe + ` '` + backgroundArg + `'; exit $LASTEXITCODE` + } + desc := strings.TrimSpace(strings.ReplaceAll(command, "\n", " ")) + if len(desc) > 60 { + desc = desc[:57] + "..." + } + mgrTasks := tc.Tasks + t, err := mgrTasks.Spawn(actool.SpawnSpec{ + Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir, + Description: desc, Env: env, + }) + if err != nil { + return actool.Errorf("Error: failed to start background command: " + err.Error()), nil + } + mgrTasks.Background(t.ID) + return actool.Text(fmt.Sprintf( + "Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.", + t.ID, t.OutputPath, t.ID)), nil +} + +func runBackgroundHelperSandbox(cfg Config, target sandbox.Target, workDir, command string, timeout time.Duration) int { + dataDir := os.Getenv("_ARTEX_BG_DATA_DIR") + _ = os.Unsetenv("_ARTEX_BG_DATA_DIR") + sbCfg := sandbox.ConfigFromEnv(dataDir, "") + mgr, err := sandbox.New(sbCfg) + if err != nil { + fmt.Fprintf(os.Stderr, "[sandbox init failed: %v]\n", err) + return 1 + } + sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + ctx, cancel := context.WithTimeout(sigCtx, timeout) + defer cancel() + + // Pass proxy env vars only (avoid leaking host env vars into container). + var passEnv []string + for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "NODE_USE_ENV_PROXY", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS"} { + if v := os.Getenv(k); v != "" { + passEnv = append(passEnv, k+"="+v) + } + } + stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{ + Cmd: []string{"bash", "-c", command}, + WorkDir: workDir, + Env: passEnv, + }) + if err != nil { + fmt.Fprintf(os.Stderr, "[sandbox exec failed: %v]\n", err) + return 1 + } + var outMu sync.Mutex + written := 0 + truncated := false + writeCapped := func(r io.Reader) { + buf := make([]byte, 16*1024) + for { + n, rerr := r.Read(buf) + if n > 0 { + outMu.Lock() + if cfg.MaxOutputBytes > 0 && written >= cfg.MaxOutputBytes { + truncated = true + } else { + chunk := buf[:n] + if cfg.MaxOutputBytes > 0 && written+len(chunk) > cfg.MaxOutputBytes { + chunk = chunk[:cfg.MaxOutputBytes-written] + truncated = true + } + _, _ = os.Stdout.Write(chunk) + written += len(chunk) + } + outMu.Unlock() + } + if rerr != nil { + return + } + } + } + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); writeCapped(stream.Stdout) }() + go func() { defer wg.Done(); writeCapped(stream.Stderr) }() + + doneCh := make(chan int, 1) + go func() { + code, _ := stream.Wait() + wg.Wait() + doneCh <- code + }() + + select { + case code := <-doneCh: + if truncated { + fmt.Fprintln(os.Stderr, outputLimitNote) + } + if code < 0 { + return 1 + } + return code + case <-ctx.Done(): + _ = stream.Close() + select { + case <-doneCh: + case <-time.After(3 * time.Second): + } + if ctx.Err() == context.DeadlineExceeded { + fmt.Fprintln(os.Stderr, timeoutNote(timeout)) + } + return 1 + } +} diff --git a/internal/toolguard/bash.go b/internal/toolguard/bash.go index 2e87881..5922b2d 100644 --- a/internal/toolguard/bash.go +++ b/internal/toolguard/bash.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/norma/permission" actool "github.com/Autumn-27/norma/tool" ) @@ -57,6 +58,9 @@ func runGuardedBash(ctx context.Context, input json.RawMessage, tc *actool.ToolC } cfg := FromEnv() timeout := cfg.ResolveTimeout(in.TimeoutMS) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + return runGuardedBashSandbox(ctx, mgr, tc, cfg, in.Command, timeout, in.RunInBackground) + } if in.RunInBackground && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() { return runGuardedBashBackground(tc, cfg, in.Command, timeout) } @@ -122,3 +126,59 @@ func mergedEnv(extra []string) []string { func timeoutNote(limit time.Duration) string { return fmt.Sprintf("\n\n[command timed out (configured limit %s)]", limit) } + +func runGuardedBashSandbox(ctx context.Context, mgr *sandbox.Manager, tc *actool.ToolContext, cfg Config, command string, timeout time.Duration, background bool) (actool.Result, error) { + target, ok := sandbox.TargetFrom(ctx) + ephemeral := false + if !ok { + target = sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("bash-%d", time.Now().UnixNano())} + ephemeral = true + defer func() { + rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = mgr.Remove(rctx, target) + }() + } + containerWorkDir := sandbox.ContainerWorkDir + if tc != nil && tc.WorkingDir != "" { + containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), tc.WorkingDir) + } + if background && !ephemeral && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() { + return runGuardedBashBackgroundSandbox(tc, mgr, target, containerWorkDir, cfg, command, timeout) + } + var extraEnv []string + if tc != nil && len(tc.Env) > 0 { + extraEnv = append(extraEnv, tc.Env...) + } + res := mgr.Exec(ctx, target, sandbox.ExecSpec{ + Cmd: []string{"bash", "-c", command}, + WorkDir: containerWorkDir, + Env: extraEnv, + Timeout: timeout, + MaxOutput: cfg.MaxOutputBytes, + KillOnAbort: true, + }) + out := actool.Capture(tc, res.Output) + if res.OutputTruncated { + out += outputLimitNote + } + if res.TimedOut { + return actool.Errorf(out + timeoutNote(timeout)), nil + } + if ctx.Err() != nil { + return actool.Errorf("Error: " + ctx.Err().Error()), nil + } + if res.Err != nil { + if res.ExitCode >= 0 { + if strings.TrimSpace(out) == "" { + out = "(no output)" + } + return actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, res.ExitCode)), nil + } + return actool.Errorf(fmt.Sprintf("%s\n\n[failed to run in sandbox: %v]", out, res.Err)), nil + } + if strings.TrimSpace(out) == "" { + out = "(command produced no output)" + } + return actool.Text(out), nil +} diff --git a/scripts/artex-sandbox-firewall.sh b/scripts/artex-sandbox-firewall.sh new file mode 100755 index 0000000..01fe9f4 --- /dev/null +++ b/scripts/artex-sandbox-firewall.sh @@ -0,0 +1,119 @@ +#!/bin/sh +# Close the host paths a sandbox container can use to reach ARTEX itself. +# The recording proxy already refuses loopback, metadata, postgres and the +# admin port. This script covers traffic that never enters the proxy: +# - packets from the sandbox bridge to the host's published :8787 +# - packets routed from the sandbox bridge into the compose internal network +# (postgres, docker-socket-proxy, the ARTEX container) +# - packets toward the cloud metadata address +# +# Run on the Docker host after the networks exist. Safe to repeat. +# Pass --cleanup to remove ARTEX sandbox firewall and residual gateway rules +# (used on teardown or rollback). +set -eu + +sandbox_net="${ARTEX_SANDBOX_NETWORK:-artex-sandbox}" +tun_dev="${ARTEX_GATEWAY_TUN:-artex-tun0}" +tun_table="${ARTEX_GATEWAY_ROUTE_TABLE:-218}" +tun_prio="${ARTEX_GATEWAY_RULE_PRIO:-218}" +sandbox_subnet="${ARTEX_SANDBOX_SUBNET:-172.30.0.0/16}" + +if [ "${1:-}" = "--cleanup" ]; then + # Best-effort removal of residual gateway chains, policy routing, and DOCKER-USER rules. + sandbox_br="" + if docker network inspect "$sandbox_net" >/dev/null 2>&1; then + id=$(docker network inspect "$sandbox_net" --format '{{.Id}}') + sandbox_br=$(printf 'br-%.12s\n' "$id") + fi + if command -v ip >/dev/null 2>&1; then + if [ -n "$sandbox_br" ]; then + ip rule del iif "$sandbox_br" lookup "$tun_table" priority "$tun_prio" 2>/dev/null || true + fi + ip rule del lookup "$tun_table" priority "$tun_prio" 2>/dev/null || true + ip route flush table "$tun_table" 2>/dev/null || true + ip link del "$tun_dev" 2>/dev/null || true + fi + if command -v iptables >/dev/null 2>&1; then + iptables -t raw -D PREROUTING -i "$tun_dev" -d "$sandbox_subnet" -j ACCEPT 2>/dev/null || true + iptables -t nat -D POSTROUTING -o "$tun_dev" -j ACCEPT 2>/dev/null || true + if [ -n "$sandbox_br" ]; then + iptables -t filter -D DOCKER-USER -i "$tun_dev" -o "$sandbox_br" -j ACCEPT 2>/dev/null || true + iptables -t filter -D DOCKER-USER -i "$sandbox_br" -o "$tun_dev" -j ACCEPT 2>/dev/null || true + iptables -t filter -D DOCKER-USER -i "$sandbox_br" ! -o "$sandbox_br" -j REJECT 2>/dev/null || true + iptables -t filter -D DOCKER-USER -i "$sandbox_br" -d 169.254.169.254/32 -j REJECT 2>/dev/null || true + iptables -t filter -D INPUT -i "$sandbox_br" -p tcp --dport 8787 -j REJECT 2>/dev/null || true + iptables -t filter -D DOCKER-USER -i "$sandbox_br" -j ARTEX_GW_FWD 2>/dev/null || true + iptables -t filter -D INPUT -i "$sandbox_br" -j ARTEX_GW_INPUT 2>/dev/null || true + iptables -t nat -D PREROUTING -i "$sandbox_br" -j ARTEX_GW_NAT 2>/dev/null || true + iptables -t mangle -D PREROUTING -i "$sandbox_br" -j ARTEX_GW_MANGLE 2>/dev/null || true + fi + for pair in "filter:ARTEX_GW_FWD" "filter:ARTEX_GW_INPUT" "nat:ARTEX_GW_NAT" "mangle:ARTEX_GW_MANGLE"; do + tbl="${pair%%:*}" + ch="${pair##*:}" + iptables -t "$tbl" -F "$ch" 2>/dev/null || true + iptables -t "$tbl" -X "$ch" 2>/dev/null || true + done + fi + echo "sandbox firewall & gateway rules cleaned up" + exit 0 +fi +bridge_for() { + id=$(docker network inspect "$1" --format '{{.Id}}') + printf 'br-%.12s\n' "$id" +} + +ensure() { + chain=$1 + shift + if iptables -C "$chain" "$@" 2>/dev/null; then + return 0 + fi + iptables -I "$chain" "$@" +} + +if ! docker network inspect "$sandbox_net" >/dev/null 2>&1; then + echo "sandbox network $sandbox_net not found" >&2 + exit 1 +fi + +sandbox_br=$(bridge_for "$sandbox_net") +ensure INPUT -i "$sandbox_br" -p tcp --dport 8787 -j REJECT + +# If the ARTEX control-plane container is directly attached to artex-sandbox +# (SNAT-free source IP attribution, #218), allow ONLY sandbox -> ARTEX :8788 +# (plus established return packets) while keeping enable_icc=false between +# sandbox containers and explicitly rejecting :8787. +artex_ct=$(docker ps --filter "network=$sandbox_net" --format '{{.Names}}' | awk '/artex/ && !/artex-sbx-/ {print; exit}') +if [ -n "$artex_ct" ]; then + artex_sbx_ip=$(docker inspect "$artex_ct" --format "{{with index .NetworkSettings.Networks \"$sandbox_net\"}}{{.IPAddress}}{{end}}") + if [ -n "$artex_sbx_ip" ]; then + ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -d "$artex_sbx_ip/32" -p tcp --dport 8787 -j REJECT + ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -s "$artex_sbx_ip/32" -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT + ensure DOCKER-USER -i "$sandbox_br" -o "$sandbox_br" -d "$artex_sbx_ip/32" -p tcp --dport 8788 -j ACCEPT + fi +fi + +# Compose prefixes the internal network with the project name. +internal_net=$(docker network ls --format '{{.Name}}' | awk '/artex-internal$/ {print; exit}') +if [ -n "$internal_net" ]; then + internal_cidr=$(docker network inspect "$internal_net" --format '{{(index .IPAM.Config 0).Subnet}}') + if [ -n "$internal_cidr" ]; then + # Published :8788 is DNATed onto the ARTEX container, which lives in this + # subnet. Let only that port through, then refuse postgres, the Docker + # socket proxy, and the admin port. + ensure DOCKER-USER -i "$sandbox_br" -d "$internal_cidr" -j REJECT + ensure DOCKER-USER -i "$sandbox_br" -d "$internal_cidr" -p tcp --dport 8788 -j RETURN + fi +fi + +ensure DOCKER-USER -i "$sandbox_br" -d 169.254.169.254/32 -j REJECT + +# Optional transparent gateway mode (#218 Phase 3): allow traffic routed into +# artex-tun0 (gVisor netstack) and reject any direct outbound NAT bypass. +if [ "${ARTEX_SANDBOX_TRANSPARENT:-false}" = "true" ] || [ "${ARTEX_SANDBOX_TRANSPARENT:-0}" = "1" ]; then + ensure DOCKER-USER -i "$sandbox_br" ! -o "$sandbox_br" -j REJECT + ensure DOCKER-USER -i "$sandbox_br" -o artex-tun0 -j ACCEPT + ensure DOCKER-USER -i artex-tun0 -o "$sandbox_br" -j ACCEPT +fi + +echo "sandbox firewall applied on $sandbox_br" diff --git a/scripts/deploy-lib.sh b/scripts/deploy-lib.sh new file mode 100755 index 0000000..99aa705 --- /dev/null +++ b/scripts/deploy-lib.sh @@ -0,0 +1,605 @@ +#!/usr/bin/env bash +# ARTEX Docker 部署、平滑升级与安全回滚公共库。 +# 由 install.sh 与 update.sh 加载,兼容 macOS Bash 3.2 与 Linux Bash 4/5。 + +DEPLOY_STATE_DIR="${ARTEX_DEPLOY_STATE_DIR:-.artex-deploy}" +DEPLOY_SNAP_DIR="${DEPLOY_STATE_DIR}/snapshots" +DEPLOY_MAX_SNAPSHOTS="${ARTEX_DEPLOY_MAX_SNAPSHOTS:-10}" +COMPOSE_FILE="${ARTEX_COMPOSE_FILE:-docker-compose.yml}" +HEALTH_CHECK_URL="${ARTEX_HEALTH_URL:-http://127.0.0.1:8787/api/health}" +HEALTH_CHECK_TIMEOUT="${ARTEX_HEALTH_TIMEOUT:-60}" + +info(){ printf '\033[36m[*]\033[0m %s\n' "$*"; } +ok(){ printf '\033[32m[+]\033[0m %s\n' "$*"; } +warn(){ printf '\033[33m[!]\033[0m %s\n' "$*" >&2; } +die(){ printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; } +ask(){ + local p="$1" d="${2:-}" a="" + if [ "${ARTEX_NONINTERACTIVE:-0}" = "1" ]; then + echo "$d" + return 0 + fi + read -rp "$p${d:+ [$d]}: " a + echo "${a:-$d}" +} +rand(){ + local n="${1:-24}" + LC_ALL=C tr -dc 'A-Za-z0-9' = 2) { + c1 = substr(found, 1, 1) + c2 = substr(found, length(found), 1) + if ((c1 == "\"" && c2 == "\"") || (c1 == "\x27" && c2 == "\x27")) { + found = substr(found, 2, length(found) - 2) + } + } + print found + } + ' "$file" +} + +env_set(){ + local key="$1" val="$2" file="${3:-.env}" tmp + umask 077 + [ -f "$file" ] || : > "$file" + tmp="${file}.tmp.$$" + awk -v k="$key" -v v="$val" ' + BEGIN { done = 0 } + index($0, k "=") == 1 { + if (!done) { + print k "=" v + done = 1 + } + next + } + { print } + END { + if (!done) { + print k "=" v + } + } + ' "$file" > "$tmp" + mv "$tmp" "$file" +} + +env_ensure(){ + local key="$1" def="$2" file="${3:-.env}" cur + cur="$(env_get "$key" "$file")" + if [ -z "$cur" ]; then + env_set "$key" "$def" "$file" + fi +} + +# ── 版本标签与容器查询 ─────────────────────────────────────────────────── +normalize_tag(){ + local tag="${1:-}" + if [ -z "$tag" ] || [ "$tag" = "standalone" ]; then + echo "latest" + return 0 + fi + case "$tag" in + *-standalone) + echo "${tag%-standalone}" + ;; + *) + echo "$tag" + ;; + esac +} + +# 从 compose 文件中查找服务容器 ID。 +find_service_cid(){ + local svc="$1" file="${2:-$COMPOSE_FILE}" cid="" + if [ -n "$file" ] && [ -f "$file" ]; then + cid="$(docker compose -f "$file" ps -a -q "$svc" 2>/dev/null | head -n 1 || true)" + [ -n "$cid" ] && { echo "$cid"; return 0; } + fi + return 0 +} + +# ── .env 初始化与迁移补齐 ──────────────────────────────────────────────── +init_base_env(){ + local file="${1:-.env}" + umask 077 + if [ ! -f "$file" ]; then + if [ -f .env.example ]; then + cp .env.example "$file" + else + : > "$file" + fi + fi + local cur_pw + cur_pw="$(env_get POSTGRES_PASSWORD "$file")" + if [ -z "$cur_pw" ] || [ "$cur_pw" = "change-me-please" ]; then + local pw + pw="$(ask 'Postgres 密码(回车随机生成)' "$(rand 24)")" + env_set POSTGRES_PASSWORD "$pw" "$file" + fi + mkdir -p ./data ./skills +} + +is_rollback_image_ref(){ + case "${1:-}" in + artex-rollback/*) return 0 ;; + *) return 1 ;; + esac +} + +is_snapshot_tag(){ + case "${1:-}" in + [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]-*) return 0 ;; + *) return 1 ;; + esac +} + +# 从回滚固定镜像(artex-rollback/*)恢复为上游镜像仓库/标签,确保回滚后再次执行 +# ./update.sh --upgrade 时不会尝试向 Docker Hub 拉取本地 artex-rollback/* 标签。 +unpin_rollback_env(){ + local file="${1:-.env}" cur up + cur="$(env_get ARTEX_IMAGE "$file")" + if is_rollback_image_ref "$cur"; then + up="$(env_get ARTEX_UPSTREAM_IMAGE "$file")" + env_set ARTEX_IMAGE "${up:-ruoji6/artex}" "$file" + fi + cur="$(env_get ARTEX_GATEWAY_IMAGE "$file")" + if is_rollback_image_ref "$cur"; then + up="$(env_get ARTEX_UPSTREAM_GATEWAY_IMAGE "$file")" + env_set ARTEX_GATEWAY_IMAGE "${up:-ruoji6/artex-gateway}" "$file" + fi + cur="$(env_get ARTEX_SANDBOX_IMAGE "$file")" + if is_rollback_image_ref "$cur"; then + up="$(env_get ARTEX_UPSTREAM_SANDBOX_IMAGE "$file")" + env_set ARTEX_SANDBOX_IMAGE "${up:-ruoji6/artex-sandbox:latest}" "$file" + fi + cur="$(env_get ARTEX_TAG "$file")" + if is_snapshot_tag "$cur"; then + up="$(env_get ARTEX_UPSTREAM_TAG "$file")" + env_set ARTEX_TAG "${up:-latest}" "$file" + fi +} + +prepare_env_for_docker(){ + local tag="${1:-}" file="${2:-.env}" + init_base_env "$file" + unpin_rollback_env "$file" + env_ensure ARTEX_IMAGE "ruoji6/artex" "$file" + env_ensure ARTEX_GATEWAY_IMAGE "ruoji6/artex-gateway" "$file" + env_ensure ARTEX_SANDBOX_IMAGE "ruoji6/artex-sandbox:latest" "$file" + env_set ARTEX_SANDBOX_MODE "docker" "$file" + env_ensure ARTEX_SANDBOX_TRANSPARENT "true" "$file" + env_ensure ARTEX_SANDBOX_ALLOW_NET_RAW "true" "$file" + + local cur_data abs_data + cur_data="$(env_get ARTEX_HOST_DATA_DIR "$file")" + abs_data="$(pwd)/data" + if [ -z "$cur_data" ] || [ "$cur_data" = "/path/to/ARTEX/data" ]; then + env_set ARTEX_HOST_DATA_DIR "$abs_data" "$file" + ok "已设置 ARTEX_HOST_DATA_DIR=${abs_data}" + fi + + local cur_tok + cur_tok="$(env_get ARTEX_GATEWAY_TOKEN "$file")" + if [ -z "$cur_tok" ]; then + env_set ARTEX_GATEWAY_TOKEN "$(rand 32)" "$file" + ok "已自动生成 ARTEX_GATEWAY_TOKEN" + fi + + if [ -n "$tag" ]; then + local norm + norm="$(normalize_tag "$tag")" + env_set ARTEX_TAG "$norm" "$file" + ok "已将 ARTEX_TAG 设为 ${norm}" + else + local cur_tag + cur_tag="$(env_get ARTEX_TAG "$file")" + case "$cur_tag" in + ""|standalone|*-standalone) + env_set ARTEX_TAG "$(normalize_tag "$cur_tag")" "$file" + ;; + esac + fi +} + +# 从旧版 root 容器升级到非 root(uid 1000)沙箱时,为既有工作区补足写权限。 +# 严格跳过符号链接,防止符号链接越界修改宿主机文件。 +prepare_migrated_workspaces(){ + local data_dir="${1:-./data}" d use_sudo=0 + if [ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then + use_sudo=1 + fi + for d in "${data_dir}/tasks" "${data_dir}/sessions" "${data_dir}/ephemeral"; do + [ -d "$d" ] || continue + info "校准迁移目录写权限(跳过符号链接):${d}" + if [ "$use_sudo" -eq 1 ]; then + sudo find "$d" ! -type l -type d -exec chmod 0777 {} + 2>/dev/null || true + sudo find "$d" ! -type l -type f -exec chmod a+rw {} + 2>/dev/null || true + sudo find "$d" ! -type l -exec chown -h 1000:1000 {} + 2>/dev/null || true + else + find "$d" ! -type l -type d -exec chmod 0777 {} + 2>/dev/null || true + find "$d" ! -type l -type f -exec chmod a+rw {} + 2>/dev/null || true + if [ "$(id -u)" -eq 0 ]; then + find "$d" ! -type l -exec chown -h 1000:1000 {} + 2>/dev/null || true + fi + fi + done +} + +# Docker 部署环境预检(Linux /dev/net/tun 等) +preflight_docker(){ + local os_name + os_name="$(uname -s)" + if [ "$os_name" != "Linux" ]; then + warn "检测到当前宿主机为 ${os_name}(非 Linux)。透明网关(artex-gateway)需要 Linux 宿主机网络栈与 /dev/net/tun。" + if [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then + [ "$(ask '仍继续部署? (y/n)' n)" = "y" ] || die "已取消部署" + fi + return 0 + fi + if [ ! -e /dev/net/tun ]; then + warn "宿主机未发现 /dev/net/tun:artex-gateway 启动时可能无法开启 TUN 模式(请确认内核加载 tun 模块)。" + fi +} + +# ── 运行态管理:停止沙箱容器、透明网关与清理宿主机规则 ────────────────── +stop_sandbox_runtime(){ + local sbx_cids="" + if command -v docker >/dev/null 2>&1; then + sbx_cids="$(docker ps -q --filter "label=artex.sandbox.managed=true" 2>/dev/null || true)" + if [ -n "$sbx_cids" ]; then + info "停止运行中的沙箱任务/会话容器…" + # shellcheck disable=SC2086 + docker stop -t 10 $sbx_cids >/dev/null 2>&1 || true + fi + if [ -f "$COMPOSE_FILE" ]; then + local gw_cid + gw_cid="$(find_service_cid artex-gateway "$COMPOSE_FILE")" + if [ -n "$gw_cid" ]; then + info "优雅停止透明代理网关 artex-gateway(自动清理 TUN 与 iptables 规则)…" + docker compose -f "$COMPOSE_FILE" stop -t 15 artex-gateway >/dev/null 2>&1 || true + fi + fi + fi + + # 兜底清理可能残留的宿主机路由/iptables 规则(如网关曾被强制 kill)。 + if [ -x scripts/artex-sandbox-firewall.sh ]; then + if [ "$(id -u)" -eq 0 ]; then + ./scripts/artex-sandbox-firewall.sh --cleanup >/dev/null 2>&1 || true + elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then + sudo ./scripts/artex-sandbox-firewall.sh --cleanup >/dev/null 2>&1 || true + elif command -v ip >/dev/null 2>&1 && ip link show artex-tun0 >/dev/null 2>&1; then + warn "检测到宿主机残留 artex-tun0 / 策略路由,如需清理请执行:sudo ./scripts/artex-sandbox-firewall.sh --cleanup" + fi + fi +} + +# ── 服务健康检查 ───────────────────────────────────────────────────────── +wait_for_health(){ + local compose_file="$1" timeout_s="${2:-$HEALTH_CHECK_TIMEOUT}" url="${3:-$HEALTH_CHECK_URL}" + local elapsed=0 cid="" state="" + if [ "${ARTEX_SKIP_HEALTH:-0}" = "1" ]; then + return 0 + fi + info "等待服务就绪(${url},超时 ${timeout_s}s)…" + while [ "$elapsed" -lt "$timeout_s" ]; do + if command -v curl >/dev/null 2>&1 && curl -fsS --max-time 3 "$url" >/dev/null 2>&1; then + ok "健康检查通过:${url}" + return 0 + fi + cid="$(find_service_cid artex "$compose_file")" + if [ -n "$cid" ]; then + state="$(docker inspect --format '{{.State.Status}}' "$cid" 2>/dev/null || true)" + if [ "$state" = "exited" ] || [ "$state" = "dead" ]; then + warn "artex 容器异常退出(state=${state})" + return 1 + fi + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + warn "等待 ${url} 就绪超时(${timeout_s}s)" + return 1 +} + +# ── 快照与回滚引擎 ─────────────────────────────────────────────────────── +snapshot_tag_image(){ + local img_id="$1" rb_tag="$2" + [ -n "$img_id" ] || return 1 + if docker image inspect "$img_id" >/dev/null 2>&1; then + docker tag "$img_id" "$rb_tag" >/dev/null 2>&1 && return 0 + fi + return 1 +} + +prune_old_snapshots(){ + local max="${1:-$DEPLOY_MAX_SNAPSHOTS}" count=0 dir="" snap_id="" + [ -d "$DEPLOY_SNAP_DIR" ] || return 0 + # 按时间倒序保留最新 $max 份,清理更早快照及其本地回滚标签 + for dir in $(ls -1dt "${DEPLOY_SNAP_DIR}"/*/ 2>/dev/null || true); do + count=$((count + 1)) + if [ "$count" -gt "$max" ]; then + snap_id="$(basename "$dir")" + docker rmi "artex-rollback/artex:${snap_id}" "artex-rollback/gateway:${snap_id}" "artex-rollback/sandbox:${snap_id}" >/dev/null 2>&1 || true + rm -rf "$dir" + fi + done +} + +# 记录当前部署状态(.env、运行镜像精确 ID + 固定回滚标签、PG 逻辑备份) +# 仅向 stdout 输出 snapshot ID,便于调用方捕获。 +create_deploy_snapshot(){ + local reason="${1:-upgrade}" skip_db="${2:-0}" + local ts snap_id snap_dir artex_cid gw_cid pg_cid + local artex_ref="" artex_id="" artex_rb="" + local gw_ref="" gw_id="" gw_rb="" + local sbx_ref="" sbx_id="" sbx_rb="" + local has_pg_dump="0" + + umask 077 + mkdir -p "$DEPLOY_SNAP_DIR" + ts="$(date +%Y%m%d-%H%M%S)" + snap_id="${ts}-${reason}" + snap_dir="${DEPLOY_SNAP_DIR}/${snap_id}" + mkdir -p "$snap_dir" + + [ -f .env ] && cp .env "${snap_dir}/dot.env" + + if command -v docker >/dev/null 2>&1; then + artex_cid="$(find_service_cid artex)" + if [ -n "$artex_cid" ]; then + artex_ref="$(docker inspect --format '{{.Config.Image}}' "$artex_cid" 2>/dev/null || true)" + artex_id="$(docker inspect --format '{{.Image}}' "$artex_cid" 2>/dev/null || true)" + if snapshot_tag_image "$artex_id" "artex-rollback/artex:${snap_id}"; then + artex_rb="artex-rollback/artex:${snap_id}" + fi + fi + + gw_cid="$(find_service_cid artex-gateway "$COMPOSE_FILE")" + if [ -n "$gw_cid" ]; then + gw_ref="$(docker inspect --format '{{.Config.Image}}' "$gw_cid" 2>/dev/null || true)" + gw_id="$(docker inspect --format '{{.Image}}' "$gw_cid" 2>/dev/null || true)" + if snapshot_tag_image "$gw_id" "artex-rollback/gateway:${snap_id}"; then + gw_rb="artex-rollback/gateway:${snap_id}" + fi + fi + + sbx_ref="$(env_get ARTEX_SANDBOX_IMAGE .env)" + [ -n "$sbx_ref" ] || sbx_ref="ruoji6/artex-sandbox:latest" + if docker image inspect "$sbx_ref" >/dev/null 2>&1; then + sbx_id="$(docker image inspect --format '{{.Id}}' "$sbx_ref" 2>/dev/null || true)" + if snapshot_tag_image "$sbx_id" "artex-rollback/sandbox:${snap_id}"; then + sbx_rb="artex-rollback/sandbox:${snap_id}" + fi + fi + if [ "$skip_db" != "1" ]; then + pg_cid="$(find_service_cid postgres)" + if [ -n "$pg_cid" ] && [ "$(docker inspect --format '{{.State.Running}}' "$pg_cid" 2>/dev/null || true)" = "true" ]; then + local pg_user pg_db + pg_user="$(env_get POSTGRES_USER .env)"; [ -n "$pg_user" ] || pg_user="artex" + pg_db="$(env_get POSTGRES_DB .env)"; [ -n "$pg_db" ] || pg_db="artex" + if docker exec "$pg_cid" pg_dump -U "$pg_user" -d "$pg_db" 2>/dev/null | gzip > "${snap_dir}/postgres.sql.gz"; then + if [ -s "${snap_dir}/postgres.sql.gz" ]; then + has_pg_dump="1" + else + rm -f "${snap_dir}/postgres.sql.gz" + fi + else + rm -f "${snap_dir}/postgres.sql.gz" + fi + fi + fi + fi + + cat > "${snap_dir}/meta.env" < "${DEPLOY_STATE_DIR}/latest" + prune_old_snapshots "$DEPLOY_MAX_SNAPSHOTS" + echo "$snap_id" +} + +list_deploy_snapshots(){ + if [ ! -d "$DEPLOY_SNAP_DIR" ]; then + info "暂无部署快照(升级前会自动生成)" + return 0 + fi + local found=0 dir snap_id img pg reason + for dir in $(ls -1dt "${DEPLOY_SNAP_DIR}"/*/ 2>/dev/null || true); do + [ -f "${dir}/meta.env" ] || continue + found=1 + snap_id="$(env_get SNAP_ID "${dir}/meta.env")" + img="$(env_get ARTEX_IMAGE_REF "${dir}/meta.env")" + pg="$(env_get HAS_PG_DUMP "${dir}/meta.env")" + reason="$(env_get SNAP_REASON "${dir}/meta.env")" + printf ' - %s [镜像: %s] [DB备份: %s] [来源: %s]\n' \ + "$snap_id" "${img:-unknown}" "$([ "$pg" = "1" ] && echo "有" || echo "无")" "${reason:-?}" + done + if [ "$found" -eq 0 ]; then + info "暂无部署快照" + fi +} + +# 将快照中的本地回滚镜像还原到对应目标标签,确保即便 :latest 已被覆盖或离线也能 100% 精准回滚。 +restore_snapshot_images(){ + local meta="$1" + local artex_rb artex_ref gw_rb gw_ref sbx_rb sbx_ref + artex_rb="$(env_get ARTEX_ROLLBACK_TAG "$meta")" + artex_ref="$(env_get ARTEX_IMAGE_REF "$meta")" + gw_rb="$(env_get GATEWAY_ROLLBACK_TAG "$meta")" + gw_ref="$(env_get GATEWAY_IMAGE_REF "$meta")" + sbx_rb="$(env_get SANDBOX_ROLLBACK_TAG "$meta")" + sbx_ref="$(env_get SANDBOX_IMAGE_REF "$meta")" + + # 先保存非回滚上游仓库与标签,确保回滚后再次执行 ./update.sh --upgrade 能正确切回上游镜像。 + local orig_img orig_tag orig_gw orig_sbx + orig_img="$(env_get ARTEX_IMAGE .env)" + orig_tag="$(env_get ARTEX_TAG .env)" + orig_gw="$(env_get ARTEX_GATEWAY_IMAGE .env)" + orig_sbx="$(env_get ARTEX_SANDBOX_IMAGE .env)" + if [ -n "$orig_img" ] && ! is_rollback_image_ref "$orig_img"; then + env_set ARTEX_UPSTREAM_IMAGE "$orig_img" .env + fi + if [ -n "$orig_tag" ] && ! is_snapshot_tag "$orig_tag"; then + env_set ARTEX_UPSTREAM_TAG "$orig_tag" .env + fi + if [ -n "$orig_gw" ] && ! is_rollback_image_ref "$orig_gw"; then + env_set ARTEX_UPSTREAM_GATEWAY_IMAGE "$orig_gw" .env + fi + if [ -n "$orig_sbx" ] && ! is_rollback_image_ref "$orig_sbx"; then + env_set ARTEX_UPSTREAM_SANDBOX_IMAGE "$orig_sbx" .env + fi + + if [ -n "$artex_rb" ] && docker image inspect "$artex_rb" >/dev/null 2>&1; then + if [ -n "$artex_ref" ] && ! is_rollback_image_ref "$artex_ref"; then + docker tag "$artex_rb" "$artex_ref" >/dev/null 2>&1 || true + fi + env_set ARTEX_IMAGE "${artex_rb%:*}" .env + env_set ARTEX_TAG "${artex_rb##*:}" .env + ok "已绑定本地精确回滚镜像:${artex_rb}(原镜像:${artex_ref:-unknown})" + elif [ -n "$artex_ref" ]; then + local repo="${artex_ref%:*}" tag="${artex_ref##*:}" + if [ "$repo" != "$artex_ref" ] && [ -n "$tag" ]; then + env_set ARTEX_IMAGE "$repo" .env + env_set ARTEX_TAG "$tag" .env + fi + fi + + local cur_tag + cur_tag="$(env_get ARTEX_TAG .env)" + if [ -n "$gw_rb" ] && docker image inspect "$gw_rb" >/dev/null 2>&1; then + if [ -n "$gw_ref" ] && ! is_rollback_image_ref "$gw_ref"; then + docker tag "$gw_rb" "$gw_ref" >/dev/null 2>&1 || true + fi + env_set ARTEX_GATEWAY_IMAGE "${gw_rb%:*}" .env + # artex-rollback/artex 与 artex-rollback/gateway 共享同一个 : 标签,互不冲突。 + if [ -n "$cur_tag" ] && [ "$cur_tag" != "${gw_rb##*:}" ]; then + docker tag "$gw_rb" "${gw_rb%:*}:${cur_tag}" >/dev/null 2>&1 || true + fi + elif is_snapshot_tag "$cur_tag"; then + local fallback_gw="${orig_gw:-ruoji6/artex-gateway}:latest" + if docker image inspect "$fallback_gw" >/dev/null 2>&1; then + docker tag "$fallback_gw" "artex-rollback/gateway:${cur_tag}" >/dev/null 2>&1 || true + env_set ARTEX_GATEWAY_IMAGE "artex-rollback/gateway" .env + fi + fi + + if [ -n "$sbx_rb" ] && docker image inspect "$sbx_rb" >/dev/null 2>&1; then + if [ -n "$sbx_ref" ] && ! is_rollback_image_ref "$sbx_ref"; then + docker tag "$sbx_rb" "$sbx_ref" >/dev/null 2>&1 || true + fi + env_set ARTEX_SANDBOX_IMAGE "$sbx_rb" .env + fi +} + +restore_postgres_dump(){ + local dump_gz="$1" compose_file="$2" + [ -f "$dump_gz" ] || die "快照中不存在数据库备份:${dump_gz}" + local pg_cid pg_user pg_db + pg_cid="$(find_service_cid postgres "$compose_file")" + [ -n "$pg_cid" ] || die "未找到运行中的 postgres 容器,无法恢复数据库备份" + pg_user="$(env_get POSTGRES_USER .env)"; [ -n "$pg_user" ] || pg_user="artex" + pg_db="$(env_get POSTGRES_DB .env)"; [ -n "$pg_db" ] || pg_db="artex" + + info "停止 artex 并恢复 PostgreSQL 快照(${dump_gz})…" + docker compose -f "$compose_file" stop artex >/dev/null 2>&1 || true + docker exec "$pg_cid" psql -U "$pg_user" -d postgres -v ON_ERROR_STOP=1 \ + -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${pg_db}' AND pid <> pg_backend_pid();" >/dev/null 2>&1 || true + docker exec "$pg_cid" psql -U "$pg_user" -d "$pg_db" -v ON_ERROR_STOP=1 \ + -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" >/dev/null + gzip -dc "$dump_gz" | docker exec -i "$pg_cid" psql -U "$pg_user" -d "$pg_db" -v ON_ERROR_STOP=1 >/dev/null + ok "PostgreSQL 快照恢复完成" +} + +rollback_to_snapshot(){ + local snap_id="${1:-}" restore_db="${2:-0}" + if [ -z "$snap_id" ]; then + [ -f "${DEPLOY_STATE_DIR}/latest" ] || die "未找到可回滚的部署快照(${DEPLOY_STATE_DIR}/latest 不存在)" + snap_id="$(cat "${DEPLOY_STATE_DIR}/latest")" + fi + local snap_dir="${DEPLOY_SNAP_DIR}/${snap_id}" + local meta="${snap_dir}/meta.env" + [ -f "$meta" ] || die "快照不存在:${snap_id}(可用 ./update.sh --list-snapshots 查看)" + + info "开始回滚到快照 ${snap_id}…" + + stop_sandbox_runtime + + if [ -f .env ]; then + cp .env "${DEPLOY_STATE_DIR}/env.before-rollback.$(date +%Y%m%d-%H%M%S)" 2>/dev/null || true + fi + if [ -f "${snap_dir}/dot.env" ]; then + cp "${snap_dir}/dot.env" .env + chmod 600 .env 2>/dev/null || true + fi + + env_set ARTEX_SANDBOX_MODE "docker" .env + restore_snapshot_images "$meta" + + if [ "$restore_db" = "1" ]; then + docker compose -f "$COMPOSE_FILE" up -d postgres + restore_postgres_dump "${snap_dir}/postgres.sql.gz" "$COMPOSE_FILE" + fi + + info "启动服务(${COMPOSE_FILE} --remove-orphans)…" + docker compose -f "$COMPOSE_FILE" up -d --remove-orphans + + if wait_for_health "$COMPOSE_FILE"; then + ok "回滚完成 → http://localhost:8787" + else + die "回滚后健康检查未通过,请执行 docker compose -f ${COMPOSE_FILE} logs --tail=80 artex 排查" + fi +} + +# ── 拉取并启动服务 ─────────────────────────────────────────────────────── +pull_docker_images(){ + local sbx_img + if [ "${ARTEX_SKIP_PULL:-0}" = "1" ]; then + info "已跳过镜像拉取(ARTEX_SKIP_PULL=1)" + return 0 + fi + info "拉取镜像(artex / artex-gateway / docker-socket-proxy / postgres)…" + docker compose -f "$COMPOSE_FILE" pull + sbx_img="$(env_get ARTEX_SANDBOX_IMAGE .env)" + [ -n "$sbx_img" ] || sbx_img="ruoji6/artex-sandbox:latest" + info "拉取沙箱执行镜像(${sbx_img})…" + docker pull "$sbx_img" +} + +deploy_with_rollback(){ + local snap_id="${1:-}" + + pull_docker_images + info "启动服务(${COMPOSE_FILE})…" + if ! docker compose -f "$COMPOSE_FILE" up -d --remove-orphans || ! wait_for_health "$COMPOSE_FILE"; then + warn "新版本启动或健康检查失败!" + if [ -n "$snap_id" ] && [ -f "${DEPLOY_SNAP_DIR}/${snap_id}/meta.env" ]; then + warn "正在自动回滚到操作前快照 ${snap_id}…" + rollback_to_snapshot "$snap_id" 0 + die "已自动回滚到 ${snap_id},请排查失败原因后重试" + fi + die "启动失败,请查看日志:docker compose -f ${COMPOSE_FILE} logs --tail=80 artex" + fi +} diff --git a/scripts/deploy_test.sh b/scripts/deploy_test.sh new file mode 100755 index 0000000..a2e905e --- /dev/null +++ b/scripts/deploy_test.sh @@ -0,0 +1,261 @@ +#!/usr/bin/env bash +# Automated regression tests for Docker deployment, upgrade from legacy .env, +# snapshot creation, manual rollback, DB restore, post-rollback upstream unpinning, +# and automatic rollback on failed health check. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +TMP_DIR="$(mktemp -d)" +trap 'chmod -R u+w "$TMP_DIR" 2>/dev/null || true; rm -rf "$TMP_DIR"' EXIT + +pass() { printf 'PASS: %s\n' "$*"; } +fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; } +assert_eq() { + local got="$1" want="$2" msg="$3" + [ "$got" = "$want" ] || fail "${msg}: got='${got}' want='${want}'" +} +assert_contains() { + local file="$1" needle="$2" msg="$3" + grep -Fq -- "$needle" "$file" || fail "${msg}: '${needle}' not found in ${file}" +} + +# 1. Syntax check all deployment scripts +bash -n "$REPO_ROOT/scripts/deploy-lib.sh" +bash -n "$REPO_ROOT/install.sh" +bash -n "$REPO_ROOT/update.sh" +sh -n "$REPO_ROOT/scripts/artex-sandbox-firewall.sh" +pass "shell syntax checks" + +# 2. Unit-test tag normalization & env helpers +( + cd "$TMP_DIR" + # shellcheck source=scripts/deploy-lib.sh + . "$REPO_ROOT/scripts/deploy-lib.sh" + assert_eq "$(normalize_tag "")" "latest" "empty tag -> latest" + assert_eq "$(normalize_tag "standalone")" "latest" "legacy standalone -> latest" + assert_eq "$(normalize_tag "v0.3.33-standalone")" "v0.3.33" "strips legacy -standalone suffix" + assert_eq "$(normalize_tag "v0.3.33")" "v0.3.33" "keeps semver tag" + + env_set FOO "/a/b|c&d" "$TMP_DIR/t.env" + assert_eq "$(env_get FOO "$TMP_DIR/t.env")" "/a/b|c&d" "env_set/get preserves special chars" + env_set FOO "second" "$TMP_DIR/t.env" + assert_eq "$(env_get FOO "$TMP_DIR/t.env")" "second" "env_set updates idempotently" + assert_eq "$(grep -c '^FOO=' "$TMP_DIR/t.env")" "1" "env_set writes single key" +) +pass "tag normalization and env helpers" + +# 3. End-to-end workflow test with stubbed docker & curl in isolated workspace +WORK="$TMP_DIR/work" +BIN_STUB="$TMP_DIR/bin" +STATE_STUB="$TMP_DIR/stub-state" +mkdir -p "$WORK/scripts" "$BIN_STUB" "$STATE_STUB/images" +cp "$REPO_ROOT/install.sh" "$REPO_ROOT/update.sh" "$REPO_ROOT/.env.example" \ + "$REPO_ROOT/docker-compose.yml" "$WORK/" +cp "$REPO_ROOT/scripts/deploy-lib.sh" "$REPO_ROOT/scripts/artex-sandbox-firewall.sh" "$WORK/scripts/" +chmod +x "$WORK/install.sh" "$WORK/update.sh" "$WORK/scripts/deploy-lib.sh" "$WORK/scripts/artex-sandbox-firewall.sh" + +# Seed mock docker image store (existing installation before upgrade) +printf 'sha256:old0332artex\n' > "$STATE_STUB/images/sha256_old0332artex" +printf 'sha256:old0332artex\n' > "$STATE_STUB/images/ruoji6_artex_v0.3.32" +printf 'sha256:old0332gw\n' > "$STATE_STUB/images/sha256_old0332gw" +printf 'sha256:old0332gw\n' > "$STATE_STUB/images/ruoji6_artex-gateway_latest" +printf 'sha256:old0332sbx\n' > "$STATE_STUB/images/sha256_old0332sbx" +printf 'sha256:old0332sbx\n' > "$STATE_STUB/images/ruoji6_artex-sandbox_latest" +printf 'ruoji6/artex:v0.3.32\n' > "$STATE_STUB/artex_image_ref" +printf 'sha256:old0332artex\n' > "$STATE_STUB/artex_image_id" +printf 'ok\n' > "$STATE_STUB/health_mode" + +cat > "$BIN_STUB/docker" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +STATE="$ARTEX_TEST_STUB_STATE" +LOG="$STATE/docker.log" +printf '%s\n' "$*" >> "$LOG" + +norm_key() { printf '%s' "$1" | tr '/:' '__'; } + +case "${1:-}" in + compose) + shift + cfile="" + if [ "${1:-}" = "-f" ]; then cfile="$2"; shift 2; fi + sub="${1:-}"; shift || true + case "$sub" in + version) echo "Docker Compose version v2.29.0"; exit 0 ;; + ps) + svc="${!#}" + case "$svc" in + artex) echo "cid-artex" ;; + postgres) echo "cid-pg" ;; + artex-gateway) echo "cid-gw" ;; + docker-socket-proxy) echo "cid-dsp" ;; + esac + exit 0 ;; + pull) + exit 0 ;; + stop) + exit 0 ;; + up) + if [ "$cfile" = "docker-compose.yml" ]; then + printf 'ruoji6/artex:latest\n' > "$STATE/artex_image_ref" + printf 'sha256:new0333artex\n' > "$STATE/artex_image_id" + printf 'sha256:new0333artex\n' > "$STATE/images/sha256_new0333artex" + printf 'sha256:new0333gw\n' > "$STATE/images/sha256_new0333gw" + printf 'sha256:new0333sbx\n' > "$STATE/images/ruoji6_artex-sandbox_latest" + fi + exit 0 ;; + esac ;; + ps) + echo "cid-sbx-1" + exit 0 ;; + stop|pull|rmi) + exit 0 ;; + tag) + src="$2"; dst="$3" + sk="$(norm_key "$src")"; dk="$(norm_key "$dst")" + if [ -f "$STATE/images/$sk" ]; then + cp "$STATE/images/$sk" "$STATE/images/$dk" + exit 0 + fi + exit 1 ;; + image) + if [ "${2:-}" = "inspect" ]; then + ref="${!#}" + k="$(norm_key "$ref")" + if [ -f "$STATE/images/$k" ]; then + cat "$STATE/images/$k" + exit 0 + fi + exit 1 + fi ;; + inspect) + fmt="$3"; cid="$4" + case "$cid:$fmt" in + cid-artex:*Config.Image*) cat "$STATE/artex_image_ref" ;; + cid-artex:*.Image*) cat "$STATE/artex_image_id" ;; + cid-artex:*State.Status*) echo "running" ;; + cid-gw:*Config.Image*) echo "ruoji6/artex-gateway:latest" ;; + cid-gw:*.Image*) echo "sha256:old0332gw" ;; + cid-pg:*State.Running*) echo "true" ;; + esac + exit 0 ;; + exec) + shift + [ "${1:-}" = "-i" ] && shift + shift # cid + cmd="${1:-}" + if [ "$cmd" = "pg_dump" ]; then + echo "-- mock pg_dump snapshot" + echo "CREATE TABLE test_ok(id int);" + elif [ "$cmd" = "psql" ]; then + cat >/dev/null || true + fi + exit 0 ;; +esac +exit 0 +STUB +chmod +x "$BIN_STUB/docker" + +cat > "$BIN_STUB/curl" <<'STUB' +#!/usr/bin/env bash +STATE="$ARTEX_TEST_STUB_STATE" +mode="$(cat "$STATE/health_mode")" +if [ "$mode" = "fail-once" ]; then + printf 'ok\n' > "$STATE/health_mode" + exit 22 +fi +[ "$mode" = "ok" ] && { echo '{"ok":true}'; exit 0; } +exit 22 +STUB +chmod +x "$BIN_STUB/curl" + +# Create legacy .env (no ARTEX_HOST_DATA_DIR, no ARTEX_GATEWAY_TOKEN) +cat > "$WORK/.env" <<'ENV' +ARTEX_IMAGE=ruoji6/artex +ARTEX_TAG=v0.3.32 +POSTGRES_USER=artex +POSTGRES_PASSWORD=legacy-secret-pw +POSTGRES_DB=artex +ENV + +# Create simulated legacy workspace with read-only file + external symlink target +OUTSIDE_FILE="$TMP_DIR/outside-secret.txt" +echo "secret" > "$OUTSIDE_FILE" +chmod 0400 "$OUTSIDE_FILE" +mkdir -p "$WORK/data/tasks/5/findings" +echo "old finding" > "$WORK/data/tasks/5/findings/note.txt" +chmod 0555 "$WORK/data/tasks/5/findings" +chmod 0444 "$WORK/data/tasks/5/findings/note.txt" +ln -s "$OUTSIDE_FILE" "$WORK/data/tasks/5/escape-link" + +export PATH="$BIN_STUB:$PATH" +export ARTEX_TEST_STUB_STATE="$STATE_STUB" +export ARTEX_HEALTH_TIMEOUT=2 + +# 3a. Upgrade legacy .env -> current Docker topology +( + cd "$WORK" + ./update.sh --upgrade --tag v0.3.33 --skip-git-pull --yes +) +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_TAG .env)" "v0.3.33" "ARTEX_TAG updated" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_SANDBOX_MODE .env)" "docker" "ARTEX_SANDBOX_MODE set to docker" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_HOST_DATA_DIR .env)" "$WORK/data" "ARTEX_HOST_DATA_DIR populated" +[ -n "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_GATEWAY_TOKEN .env)" ] || fail "ARTEX_GATEWAY_TOKEN not generated" +[ -w "$WORK/data/tasks/5/findings/note.txt" ] || fail "migrated task file not writable" +# Outside symlink target must still be 0400 +outside_perm="$(stat -f '%Lp' "$OUTSIDE_FILE" 2>/dev/null || stat -c '%a' "$OUTSIDE_FILE")" +assert_eq "$outside_perm" "400" "symlink target permissions must not be modified" +snap_upg="$(cat "$WORK/.artex-deploy/latest")" +assert_contains "$WORK/.artex-deploy/snapshots/$snap_upg/meta.env" "ARTEX_IMAGE_REF=ruoji6/artex:v0.3.32" "upgrade snapshot records v0.3.32 image" +assert_contains "$WORK/.artex-deploy/snapshots/$snap_upg/meta.env" "HAS_PG_DUMP=1" "upgrade snapshot includes PG dump" +assert_contains "$STATE_STUB/docker.log" "compose -f docker-compose.yml up -d --remove-orphans" "started compose" +pass "upgrade + legacy workspace permission migration" + +# 3b. Manual rollback (including --restore-db) +( + cd "$WORK" + ./update.sh --rollback "$snap_upg" --restore-db --yes +) +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_IMAGE .env)" "artex-rollback/artex" "rollback pinned local image repo" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_TAG .env)" "$snap_upg" "rollback pinned local image tag" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_GATEWAY_IMAGE .env)" "artex-rollback/gateway" "rollback pinned local gateway repo" +assert_contains "$STATE_STUB/docker.log" "stop -t 10 cid-sbx-1" "stopped running sandbox container on rollback" +assert_contains "$STATE_STUB/docker.log" "compose -f docker-compose.yml stop -t 15 artex-gateway" "gracefully stopped artex-gateway on rollback" +assert_contains "$STATE_STUB/docker.log" "exec -i cid-pg psql" "restored PG dump when --restore-db passed" +pass "manual rollback + DB restore" + +# 3c. Post-rollback upgrade unpins artex-rollback/* back to upstream +printf 'ok\n' > "$STATE_STUB/health_mode" +( + cd "$WORK" + ./update.sh --upgrade --tag v0.3.34 --skip-git-pull --yes +) +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_IMAGE .env)" "ruoji6/artex" "post-rollback upgrade unpinned artex-rollback/* image" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_GATEWAY_IMAGE .env)" "ruoji6/artex-gateway" "post-rollback upgrade unpinned gateway image" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_TAG .env)" "v0.3.34" "post-rollback upgrade applied requested tag" +pass "post-rollback upstream unpinning" + +# 3d. Failed upgrade triggers automatic rollback +printf 'fail-once\n' > "$STATE_STUB/health_mode" +if ( cd "$WORK" && ./update.sh --upgrade --tag v0.3.35 --skip-git-pull --yes ); then + fail "upgrade with failing health check should exit non-zero after auto-rollback" +fi +snap_auto="$(cat "$WORK/.artex-deploy/latest")" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_IMAGE .env)" "artex-rollback/artex" "auto-rollback pinned previous image" +assert_eq "$(cd "$WORK" && . ./scripts/deploy-lib.sh && env_get ARTEX_TAG .env)" "$snap_auto" "auto-rollback pinned snapshot tag" +pass "auto-rollback on failed upgrade health check" + +# 3e. Fresh install +FRESH="$TMP_DIR/fresh" +mkdir -p "$FRESH/scripts" +cp "$REPO_ROOT/install.sh" "$REPO_ROOT/.env.example" "$REPO_ROOT/docker-compose.yml" "$FRESH/" +cp "$REPO_ROOT/scripts/deploy-lib.sh" "$REPO_ROOT/scripts/artex-sandbox-firewall.sh" "$FRESH/scripts/" +chmod +x "$FRESH/install.sh" "$FRESH/scripts/deploy-lib.sh" +printf 'ok\n' > "$STATE_STUB/health_mode" +( cd "$FRESH" && ./install.sh --docker --yes ) +assert_eq "$(cd "$FRESH" && . ./scripts/deploy-lib.sh && env_get ARTEX_SANDBOX_MODE .env)" "docker" "fresh install sets ARTEX_SANDBOX_MODE=docker" +assert_eq "$(cd "$FRESH" && . ./scripts/deploy-lib.sh && env_get ARTEX_HOST_DATA_DIR .env)" "$FRESH/data" "fresh install sets ARTEX_HOST_DATA_DIR" +[ -n "$(cd "$FRESH" && . ./scripts/deploy-lib.sh && env_get ARTEX_GATEWAY_TOKEN .env)" ] || fail "fresh install sets ARTEX_GATEWAY_TOKEN" +pass "fresh install.sh" + +echo "ALL DEPLOY/UPGRADE/ROLLBACK TESTS PASSED" diff --git a/server/asset_intercept.go b/server/asset_intercept.go index b685325..ed4f266 100644 --- a/server/asset_intercept.go +++ b/server/asset_intercept.go @@ -49,6 +49,7 @@ func (s *Server) assetInterceptCreateRule(w http.ResponseWriter, r *http.Request writeErr(w, 500, err.Error()) return } + s.syncEgressBlacklist() writeJSON(w, 200, rule) } @@ -76,6 +77,7 @@ func (s *Server) assetInterceptUpdateRule(w http.ResponseWriter, r *http.Request writeErr(w, 500, err.Error()) return } + s.syncEgressBlacklist() writeJSON(w, 200, rule) } @@ -93,6 +95,7 @@ func (s *Server) assetInterceptDeleteRule(w http.ResponseWriter, r *http.Request writeErr(w, 500, err.Error()) return } + s.syncEgressBlacklist() writeJSON(w, 200, map[string]any{"deleted": id}) } @@ -117,6 +120,7 @@ func (s *Server) assetInterceptToggleRule(w http.ResponseWriter, r *http.Request writeErr(w, 500, err.Error()) return } + s.syncEgressBlacklist() writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled}) } diff --git a/server/auth.go b/server/auth.go index 701b3be..144cfb1 100644 --- a/server/auth.go +++ b/server/auth.go @@ -120,7 +120,7 @@ func extractToken(r *http.Request) string { func (s *Server) requireAuth(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := r.URL.Path - if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" || p == "/api/basic-auth/check" { + if strings.HasPrefix(p, "/api/auth/") || strings.HasPrefix(p, "/api/internal/gateway/") || p == "/api/health" || p == "/api/basic-auth/check" { h.ServeHTTP(w, r) return } diff --git a/server/browser_mcp_test.go b/server/browser_mcp_test.go index 7f89a67..7f4c534 100644 --- a/server/browser_mcp_test.go +++ b/server/browser_mcp_test.go @@ -12,8 +12,8 @@ import ( "strings" "testing" "time" - "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/internal/sandbox" ) func TestEnsureBrowserMCPArgs(t *testing.T) { @@ -178,3 +178,72 @@ func TestDefaultEnabledSettingsAndScreenshotTimestampHeader(t *testing.T) { t.Fatal("expected X-Report-Screenshot-Timestamp header when setting is unset (default true)") } } + +func TestAdaptSandboxMCPArgsAndEnv(t *testing.T) { + // 1. Loopback --proxy-server (split and =) rewritten to sandbox-reachable proxy URL. + in := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://127.0.0.1:8788"} + got := adaptSandboxMCPArgs(in, "http://172.30.0.2:8788") + want := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://172.30.0.2:8788"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("adaptSandboxMCPArgs(split) = %v, want %v", got, want) + } + + inEq := []string{"--headless", "--proxy-server=http://localhost:8788"} + gotEq := adaptSandboxMCPArgs(inEq, "http://172.30.0.2:8788") + wantEq := []string{"--headless", "--proxy-server=http://172.30.0.2:8788"} + if !reflect.DeepEqual(gotEq, wantEq) { + t.Fatalf("adaptSandboxMCPArgs(=) = %v, want %v", gotEq, wantEq) + } + + // 2. Empty sandboxProxyURL strips unusable loopback proxy flag cleanly. + gotStrip := adaptSandboxMCPArgs(in, "") + wantStrip := []string{"--browser", "chromium", "--headless", "--no-sandbox"} + if !reflect.DeepEqual(gotStrip, wantStrip) { + t.Fatalf("adaptSandboxMCPArgs(strip) = %v, want %v", gotStrip, wantStrip) + } + + // 3. Explicit non-loopback user proxy passes through untouched. + inCustom := []string{"--headless", "--proxy-server", "http://10.0.0.5:8080"} + gotCustom := adaptSandboxMCPArgs(inCustom, "http://172.30.0.2:8788") + if !reflect.DeepEqual(gotCustom, inCustom) { + t.Fatalf("adaptSandboxMCPArgs(custom) = %v, want %v", gotCustom, inCustom) + } + + // 4. stripURLCredentials drops userinfo so Chromium accepts --proxy-server. + if got := stripURLCredentials("http://artexctx_sc=task:x@172.30.0.2:8788"); got != "http://172.30.0.2:8788" { + t.Fatalf("stripURLCredentials = %q", got) + } + + // 5. buildSandboxMCPEnv never lets host CA path clobber /etc/artex/ca.crt. + caFile := filepath.Join(t.TempDir(), "mitmproxy-ca-cert.pem") + if err := os.WriteFile(caFile, []byte("FAKE-CA"), 0o644); err != nil { + t.Fatal(err) + } + mgr, err := sandbox.New(sandbox.Config{ + Mode: sandbox.ModeLocal, + ProxyURL: "http://172.30.0.2:8788", + CACertPath: caFile, + }) + if err != nil { + t.Fatal(err) + } + env := buildSandboxMCPEnv(mgr, map[string]string{ + "NODE_EXTRA_CA_CERTS": "/app/data/traffic/_ca/mitmproxy-ca-cert.pem", + "CUSTOM_KEY": "custom-val", + }) + envMap := map[string]string{} + for _, kv := range env { + if k, v, ok := strings.Cut(kv, "="); ok { + envMap[k] = v + } + } + if envMap["NODE_EXTRA_CA_CERTS"] != sandbox.ContainerCACertPath { + t.Fatalf("NODE_EXTRA_CA_CERTS = %q, want %q", envMap["NODE_EXTRA_CA_CERTS"], sandbox.ContainerCACertPath) + } + if envMap["CUSTOM_KEY"] != "custom-val" { + t.Fatalf("CUSTOM_KEY = %q, want custom-val", envMap["CUSTOM_KEY"]) + } + if envMap["HTTP_PROXY"] != "http://172.30.0.2:8788" { + t.Fatalf("HTTP_PROXY = %q, want http://172.30.0.2:8788", envMap["HTTP_PROXY"]) + } +} diff --git a/server/calendar_schedule.go b/server/calendar_schedule.go index 543f63d..c1c1047 100644 --- a/server/calendar_schedule.go +++ b/server/calendar_schedule.go @@ -272,6 +272,9 @@ func (sc *Scheduler) fireTaskSchedulesAt(now time.Time) { for _, item := range items { w := windows[item.ID] errors := []string{} + if w.active { + sc.s.applyScheduleProxyToTasks(item) + } for _, id := range item.TaskIDs { if seen[id] { continue diff --git a/server/chat_mentions.go b/server/chat_mentions.go index 6adf61d..24cecb2 100644 --- a/server/chat_mentions.go +++ b/server/chat_mentions.go @@ -1,6 +1,7 @@ package server import ( + "database/sql" "encoding/json" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "time" "unicode/utf8" "github.com/Autumn-27/artex/db" @@ -17,11 +19,11 @@ const maxChatMentions = 10 // The visible token survives drafts, uploads, retries and conversation history. // Labels are only for display: the server trusts only the type and numeric ID. -var chatMentionPattern = regexp.MustCompile(`@\[(finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`) +var chatMentionPattern = regexp.MustCompile(`@\[(schedule|task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|计划任务|计划|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`) var chatMentionKinds = map[string]string{ - "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint", + "任务": "task", "计划任务": "schedule", "计划": "schedule", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint", "IP": "ip", "应用": "app", "域名": "root_domain", "子域名": "subdomain", "服务": "service", - "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint", + "task": "task", "schedule": "schedule", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint", "ip": "ip", "app": "app", "root_domain": "root_domain", "subdomain": "subdomain", "service": "service", } @@ -140,6 +142,55 @@ func composeChatMentionMessage(pg *db.DB, message string) (string, error) { func loadChatMention(pg *db.DB, ref chatMentionRef) (any, error) { switch ref.Kind { + case "task": + t, err := pg.GetTask(ref.ID) + if err != nil || t == nil { + return nil, err + } + route := map[string]any{"mode": "inherit"} + if raw, ok, _ := pg.GetSetting(settingContainerProxyRoutes); ok && strings.TrimSpace(raw) != "" { + var list []ContainerProxyRoute + if json.Unmarshal([]byte(raw), &list) == nil { + targetOwner := strconv.FormatInt(t.ID, 10) + for _, r := range list { + if r.Scope == "task" && r.OwnerID == targetOwner { + route = map[string]any{ + "mode": r.Mode, + "proxy_pool_id": r.ProxyPoolID, + "proxy_url": maskSecrets(r.ProxyURL), + "note": r.Note, + } + break + } + } + } + } + return map[string]any{"task": t, "proxy_route": route}, nil + case "schedule": + item, err := pg.GetTaskSchedule(ref.ID) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, err + } + if item == nil { + return nil, nil + } + safe := *item + safe.ProxyURL = maskSecrets(safe.ProxyURL) + out := map[string]any{ + "schedule": safe, + "timezone": scheduleLocation(item.TimezoneMode).String(), + "server_time": time.Now().Format(time.RFC3339), + } + if stats, err := pg.ScheduleRunStats(item.ID); err == nil { + out["run_count"] = stats.RunCount + if stats.LastRunAt != nil { + out["last_run_at"] = stats.LastRunAt + } + } + return out, nil case "finding": f, err := pg.GetFinding(ref.ID) if err != nil || f == nil { diff --git a/server/conversation_sandbox.go b/server/conversation_sandbox.go new file mode 100644 index 0000000..bbf7600 --- /dev/null +++ b/server/conversation_sandbox.go @@ -0,0 +1,128 @@ +package server + +import ( + "context" + "log" + "strconv" + "strings" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/internal/sandbox" +) + +// sandboxTargetForTrigger matches the container a triggered run actually executes +// in. A reporter bound to one task reuses that task's sandbox. Merged multi-task +// runs and every other agent keep a session container. +func sandboxTargetForTrigger(agentKey string, taskID int64, multiTask bool, convID int64) sandbox.Target { + if agentKey == "reporter" && taskID > 0 && !multiTask { + return sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)} + } + return sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: "conv-" + strconv.FormatInt(convID, 10)} +} + +func storedConversationSandbox(c *db.Conversation) (string, string, bool) { + if c == nil { + return "", "", false + } + scope := strings.TrimSpace(c.SandboxScope) + owner := strings.TrimSpace(c.SandboxOwnerID) + if (scope == string(sandbox.ScopeTask) || scope == string(sandbox.ScopeSession)) && owner != "" { + return scope, owner, true + } + return "", "", false +} + +// resolveConversationSandbox prefers a binding already saved on the conversation. +// fallbackTaskID is used only when nothing is saved and every linked finding +// belongs to that one task. hasFallback distinguishes "no row" from task 0. +func resolveConversationSandbox(c *db.Conversation, fallbackTaskID int64, hasFallback bool) (string, string) { + if scope, owner, ok := storedConversationSandbox(c); ok { + return scope, owner + } + if c == nil { + return "", "" + } + if hasFallback && fallbackTaskID > 0 { + return string(sandbox.ScopeTask), strconv.FormatInt(fallbackTaskID, 10) + } + return string(sandbox.ScopeSession), "conv-" + strconv.FormatInt(c.ID, 10) +} + +// fillConversationSandboxes writes the sandbox the chat badge should query. +// Saved bindings win. Older reporter threads that never stored one fall back to +// the single task that owns their findings. +func (s *Server) fillConversationSandboxes(cs []*db.Conversation) { + if len(cs) == 0 || s == nil || s.m == nil || s.m.pg == nil { + return + } + pending := make([]int64, 0, len(cs)) + for _, c := range cs { + if _, _, ok := storedConversationSandbox(c); !ok && c != nil { + pending = append(pending, c.ID) + } + } + fallbacks := map[int64]int64{} + if len(pending) > 0 { + got, err := s.m.pg.ReportTaskSandboxFallbacks(pending) + if err != nil { + log.Printf("[conv] sandbox fallback: %v", err) + } else if got != nil { + fallbacks = got + } + } + for _, c := range cs { + if c == nil { + continue + } + taskID, ok := fallbacks[c.ID] + scope, owner := resolveConversationSandbox(c, taskID, ok) + c.SandboxScope = scope + c.SandboxOwnerID = owner + } +} + +func (s *Server) fillConversationSandbox(c *db.Conversation) { + if c == nil { + return + } + s.fillConversationSandboxes([]*db.Conversation{c}) +} + +// ensureConversationSandbox binds a live turn to the conversation's sandbox. +// A trigger may already have placed the target on ctx; that value wins so the +// turn cannot drift back to a session container. Local mode leaves the context +// alone because there is no container to select. +func (s *Server) ensureConversationSandbox(ctx context.Context, c *db.Conversation) context.Context { + if mgr := sandbox.Default(); mgr == nil || !mgr.Enabled() { + return ctx + } + if preset, ok := sandbox.TargetFrom(ctx); ok && preset.Valid() { + return ctx + } + if c == nil || s == nil || s.m == nil || s.m.pg == nil { + return ctx + } + scope, owner, stored := storedConversationSandbox(c) + if !stored { + fallbacks, err := s.m.pg.ReportTaskSandboxFallbacks([]int64{c.ID}) + if err != nil { + log.Printf("[conv %d] sandbox fallback: %v", c.ID, err) + fallbacks = nil + } + taskID, ok := fallbacks[c.ID] + scope, owner = resolveConversationSandbox(c, taskID, ok) + if err == nil && scope != "" && owner != "" { + if saveErr := s.m.pg.SetConversationSandbox(c.ID, scope, owner); saveErr != nil { + log.Printf("[conv %d] save sandbox binding: %v", c.ID, saveErr) + } else { + c.SandboxScope = scope + c.SandboxOwnerID = owner + } + } + } + target := sandbox.Target{Scope: sandbox.Scope(scope), OwnerID: owner} + if !target.Valid() { + return ctx + } + return sandbox.WithTarget(ctx, target) +} diff --git a/server/conversation_sandbox_test.go b/server/conversation_sandbox_test.go new file mode 100644 index 0000000..21fd3f9 --- /dev/null +++ b/server/conversation_sandbox_test.go @@ -0,0 +1,129 @@ +package server + +import ( + "encoding/json" + "net/http" + "strconv" + "testing" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/internal/sandbox" +) + +func TestSandboxTargetForTrigger(t *testing.T) { + task := sandboxTargetForTrigger("reporter", 5, false, 18) + if task.Scope != sandbox.ScopeTask || task.OwnerID != "5" { + t.Fatalf("reporter task = %+v", task) + } + merged := sandboxTargetForTrigger("reporter", 5, true, 19) + if merged.Scope != sandbox.ScopeSession || merged.OwnerID != "conv-19" { + t.Fatalf("multi-task reporter = %+v", merged) + } + other := sandboxTargetForTrigger("auto", 5, false, 20) + if other.Scope != sandbox.ScopeSession || other.OwnerID != "conv-20" { + t.Fatalf("non-reporter = %+v", other) + } + noTask := sandboxTargetForTrigger("reporter", 0, false, 21) + if noTask.Scope != sandbox.ScopeSession || noTask.OwnerID != "conv-21" { + t.Fatalf("reporter without task = %+v", noTask) + } +} + +func TestResolveConversationSandbox(t *testing.T) { + savedTask := &db.Conversation{ID: 18, SandboxScope: "task", SandboxOwnerID: "5"} + scope, owner := resolveConversationSandbox(savedTask, 9, true) + if scope != "task" || owner != "5" { + t.Fatalf("stored task binding must win, got %s %s", scope, owner) + } + + savedSession := &db.Conversation{ID: 19, SandboxScope: "session", SandboxOwnerID: "conv-19"} + scope, owner = resolveConversationSandbox(savedSession, 5, true) + if scope != "session" || owner != "conv-19" { + t.Fatalf("stored session binding must win over findings, got %s %s", scope, owner) + } + + historical := &db.Conversation{ID: 20} + scope, owner = resolveConversationSandbox(historical, 7, true) + if scope != "task" || owner != "7" { + t.Fatalf("historical finding fallback = %s %s", scope, owner) + } + + plain := &db.Conversation{ID: 21} + scope, owner = resolveConversationSandbox(plain, 0, false) + if scope != "session" || owner != "conv-21" { + t.Fatalf("plain conversation = %s %s", scope, owner) + } +} + +func TestConversationListReturnsSandboxTarget(t *testing.T) { + s, _ := newRetestServer(t) + pg := s.m.pg + task, err := pg.CreateTask("conversation sandbox api", "goal", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + reporter, err := pg.CreateConversation("reporter", "historical report", nil) + if err != nil { + t.Fatal(err) + } + merged, err := pg.CreateConversation("reporter", "merged report", nil) + if err != nil { + t.Fatal(err) + } + plain, err := pg.CreateConversation("auto", "plain", nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = pg.Exec(`DELETE FROM findings WHERE report_conversation_id IN ($1,$2)`, reporter.ID, merged.ID) + _, _ = pg.Exec(`DELETE FROM conversations WHERE id IN ($1,$2,$3)`, reporter.ID, merged.ID, plain.ID) + _ = pg.DeleteTask(task.ID) + }) + + fid, err := pg.AddFinding(task.ID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := pg.SetFindingReportConversationID(fid, reporter.ID); err != nil { + t.Fatal(err) + } + mergedFinding, err := pg.AddFinding(task.ID, 0, "xss", "name", "high", "summary", "evidence", "worker", nil) + if err != nil { + t.Fatal(err) + } + if err := pg.SetFindingReportConversationID(mergedFinding, merged.ID); err != nil { + t.Fatal(err) + } + if err := pg.SetConversationSandbox(merged.ID, "session", "conv-"+strconv.FormatInt(merged.ID, 10)); err != nil { + t.Fatal(err) + } + + w := retestRequest(s.pgListConversations, http.MethodGet, 0, "") + if w.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", w.Code, w.Body) + } + var body struct { + Conversations []conversationListItem `json:"conversations"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + found := map[int64]conversationListItem{} + for _, item := range body.Conversations { + if item.ID == reporter.ID || item.ID == merged.ID || item.ID == plain.ID { + found[item.ID] = item + } + } + if len(found) != 3 { + t.Fatalf("found %d conversations", len(found)) + } + if found[reporter.ID].SandboxScope != "task" || found[reporter.ID].SandboxOwnerID != strconv.FormatInt(task.ID, 10) { + t.Fatalf("historical reporter = %+v", found[reporter.ID].Conversation) + } + if found[merged.ID].SandboxScope != "session" || found[merged.ID].SandboxOwnerID != "conv-"+strconv.FormatInt(merged.ID, 10) { + t.Fatalf("stored multi-task session = %+v", found[merged.ID].Conversation) + } + if found[plain.ID].SandboxScope != "session" || found[plain.ID].SandboxOwnerID != "conv-"+strconv.FormatInt(plain.ID, 10) { + t.Fatalf("plain conversation = %+v", found[plain.ID].Conversation) + } +} diff --git a/server/conversations.go b/server/conversations.go index 442eadc..3efa74b 100644 --- a/server/conversations.go +++ b/server/conversations.go @@ -16,6 +16,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/sidequestion" "github.com/Autumn-27/norma/llm" ) @@ -62,6 +63,7 @@ func (s *Server) pgListConversations(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, err.Error()) return } + s.fillConversationSandboxes(cs) items := make([]conversationListItem, 0, len(cs)) s.chatMu.Lock() for _, c := range cs { @@ -125,6 +127,7 @@ func (s *Server) pgCreateConversation(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, err.Error()) return } + s.fillConversationSandbox(c) writeJSON(w, 200, c) } @@ -216,6 +219,7 @@ func (s *Server) pgRenameConversation(w http.ResponseWriter, r *http.Request) { writeErr(w, 404, "conversation not found") return } + s.fillConversationSandbox(updated) writeJSON(w, 200, updated) } @@ -230,6 +234,13 @@ func (s *Server) pgDeleteConversation(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, err.Error()) return } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + go func(sessionID string) { + rctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + _ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: sessionID}) + }(s.convBusyKey(c.ID)) + } writeJSON(w, 200, map[string]any{"deleted": c.ID}) } @@ -291,6 +302,16 @@ func (s *Server) pgDeleteConversationsBatch(w http.ResponseWriter, r *http.Reque writeErr(w, http.StatusInternalServerError, err.Error()) return } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && len(deleted) > 0 { + deletedCopy := append([]int64(nil), deleted...) + go func() { + rctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + for _, id := range deletedCopy { + _ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: s.convBusyKey(id)}) + } + }() + } deletedSet := make(map[int64]struct{}, len(deleted)) for _, id := range deleted { deletedSet[id] = struct{}{} @@ -512,11 +533,13 @@ func (s *Server) pgSendConversationMessage(w http.ResponseWriter, r *http.Reques } _ = pg.TouchConversation(c.ID) - // Append the uploaded files' ABSOLUTE paths so the ChatAgent opens them with its - // Read/Bash tools. baseDir = the agent's per-session CWD (/sessions/ - // conv-/), matching chatUpload's landing dir and agent/chat.go's sessionWorkDir - // — busyKey == convBusyKey(c.ID) == "conv-" == that session id. + // Append the uploaded files' paths so the ChatAgent opens them with its + // Read/Bash tools. In Docker sandbox mode the session directory is mounted + // at /workspace, so emit container paths (/workspace/uploads/...). baseDir := filepath.Join(s.m.dir, "sessions", busyKey) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + baseDir = sandbox.ContainerWorkDir + } s.runConversation(c, composeAgentMessage(agentMessage, req.Attachments, baseDir), busyKey, msg) writeJSON(w, 202, map[string]any{"status": "accepted"}) } @@ -549,8 +572,11 @@ func (s *Server) runConversation(c *db.Conversation, msg, busyKey string, userMe // run ends (clearing busyKey). runConversation wraps it in a goroutine for the // fire-and-forget chat path; the P3 trigger queue calls it directly so it can wait // for completion before starting the next queued fire for the same agent. -func (s *Server) runConversationSync(c *db.Conversation, msg, busyKey string) { +func (s *Server) runConversationSync(c *db.Conversation, msg, busyKey string, presetTarget ...sandbox.Target) { ctx, cancel := s.conversationRunContext(c.ID, busyKey) + if len(presetTarget) > 0 && presetTarget[0].Valid() { + ctx = sandbox.WithTarget(ctx, presetTarget[0]) + } s.runConversationTurn(ctx, cancel, c, msg, busyKey) } @@ -654,6 +680,7 @@ func (s *Server) runConversationTurn(ctx context.Context, cancel context.CancelC webSearch = a.WebSearch } sessionID := s.convBusyKey(c.ID) // "conv-" transcript session + ctx = s.ensureConversationSandbox(ctx, c) emit := func(rec db.Activity) { if _, err := pg.AppendConvActivity(c.ID, rec); err != nil { log.Printf("[conv %d] append activity failed: %v", c.ID, err) @@ -918,6 +945,7 @@ func mergeAllRuns(items []triggeredRun) triggeredRun { message: b.String(), taskID: first.taskID, mergeable: true, + multiTask: len(order) > 1, // taskDesc/taskGoal left empty: per-task headers already embedded above. } } @@ -958,6 +986,25 @@ func (s *Server) runTriggeredRun(item triggeredRun) { s.chatMu.Lock() s.chatBusy[busyKey] = true s.chatMu.Unlock() + target := sandboxTargetForTrigger(item.agentKey, item.taskID, item.multiTask, c.ID) + if err := pg.SetConversationSandbox(c.ID, string(target.Scope), target.OwnerID); err != nil { + log.Printf("[trigger] save sandbox binding for conv %d failed: %v", c.ID, err) + } else { + c.SandboxScope = string(target.Scope) + c.SandboxOwnerID = target.OwnerID + } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && target.Valid() { + s.runConversationSync(c, msg, busyKey, target) + if target.Scope == sandbox.ScopeTask { + if t, ok := s.m.Task(target.OwnerID); !ok || s.resolvedTaskStatus(t) != "running" { + mgr.RequestIdleStop(target) + } + } else { + // Triggered one-shot sessions (no bound task) do not need to sit idle for 20m. + mgr.RequestIdleStop(target) + } + return + } s.runConversationSync(c, msg, busyKey) } diff --git a/server/customtool.go b/server/customtool.go index d3f189e..566db87 100644 --- a/server/customtool.go +++ b/server/customtool.go @@ -20,6 +20,7 @@ import ( "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/internal/httpidentity" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/internal/toolguard" "github.com/Autumn-27/norma/permission" actool "github.com/Autumn-27/norma/tool" @@ -163,6 +164,18 @@ func (s *Server) pgTestCustomTool(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) defer cancel() tc := &actool.ToolContext{WorkingDir: s.m.dir} // run in the project dir, like a real call + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && (req.Kind == "command" || req.Kind == "script") { + ephemeralTarget := sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("dryrun-%d", time.Now().UnixNano())} + ctx = sandbox.WithTarget(ctx, ephemeralTarget) + tc.WorkingDir = mgr.Config().LocalRootFor(ephemeralTarget) + tc.Env = mgr.ProxyEnv(s.m.traffic != nil) + defer func() { + rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second) + defer rcancel() + _ = mgr.Remove(rctx, ephemeralTarget) + _ = os.RemoveAll(mgr.Config().LocalRootFor(ephemeralTarget)) + }() + } var res actool.Result switch req.Kind { case "command": @@ -356,10 +369,6 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw if strings.TrimSpace(spec.Code) == "" { return actool.Errorf("script code 为空"), nil } - interp := s.pythonInterpreter() - if interp == "" { - return actool.Errorf("未配置且未检测到 python 解释器(在系统配置里设置)"), nil - } workDir := s.m.dir var sessionEnv []string if tc != nil { @@ -368,7 +377,20 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw } sessionEnv = tc.Env } - body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs)) + timeout := toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs) + var ( + body string + err error + ) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + body, err = execPythonSandbox(ctx, mgr, key, spec.Code, params, workDir, sessionEnv, timeout) + } else { + interp := s.pythonInterpreter() + if interp == "" { + return actool.Errorf("未配置且未检测到 python 解释器(在系统配置里设置)"), nil + } + body, err = execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeout) + } if err != nil { out := actool.Capture(tc, body) if out != "" { @@ -428,6 +450,70 @@ func execPython(ctx context.Context, interp, key, code string, params map[string return body, nil } +func execPythonSandbox(ctx context.Context, mgr *sandbox.Manager, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration) (string, error) { + target, ok := sandbox.TargetFrom(ctx) + if !ok { + target = sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("script-%d", time.Now().UnixNano())} + defer func() { + rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = mgr.Remove(rctx, target) + _ = os.RemoveAll(mgr.Config().LocalRootFor(target)) + }() + } + hostRoot := mgr.Config().LocalRootFor(target) + if _, within := sandbox.CheckPathWithinRoot(hostRoot, workDir); !within { + workDir = hostRoot + } + toolsDir := filepath.Join(workDir, ".tools") + if err := os.MkdirAll(toolsDir, 0o777); err != nil { + return "", err + } + f, err := os.CreateTemp(toolsDir, key+"-*.py") + if err != nil { + return "", err + } + tmp := f.Name() + defer os.Remove(tmp) + if _, err := f.WriteString(code); err != nil { + f.Close() + return "", err + } + f.Close() + _ = os.Chmod(tmp, 0o644) + + env := append([]string{}, sessionEnv...) + for k, v := range params { + if sv, ok := scalarStr(v); ok { + env = append(env, "TOOL_"+strings.ToUpper(k)+"="+sv) + } + } + pj, _ := json.Marshal(params) + containerWorkDir := sandbox.HostToContainerPath(hostRoot, workDir) + containerScript := sandbox.HostToContainerPath(hostRoot, tmp) + + res := mgr.Exec(ctx, target, sandbox.ExecSpec{ + Cmd: []string{"python3", containerScript}, + WorkDir: containerWorkDir, + Env: env, + Stdin: pj, + Timeout: timeout, + MaxOutput: toolguard.FromEnv().MaxOutputBytes, + KillOnAbort: true, + }) + body := res.Output + if res.OutputTruncated { + body += "\n\n[output truncated at capture limit]" + } + if res.TimedOut { + return body, fmt.Errorf("[command timed out (configured limit %s)]", timeout) + } + if res.Err != nil { + return body, fmt.Errorf("[exit: %w]", res.Err) + } + return body, nil +} + // ---------- http:原生请求 + 代理 ---------- func (s *Server) runHTTPTool(ctx context.Context, execRaw json.RawMessage, params map[string]any, tc *actool.ToolContext) (actool.Result, error) { diff --git a/server/dto.go b/server/dto.go index d89509c..4dc3ed0 100644 --- a/server/dto.go +++ b/server/dto.go @@ -78,6 +78,7 @@ type TaskDTO struct { NoResultMinFindings int `json:"no_result_min_findings"` NoResultMinSeverity string `json:"no_result_min_severity"` StopReason string `json:"stop_reason"` + ProxyRoute *TaskProxyRouteDTO `json:"proxy_route,omitempty"` } type ProxyReconnectDTO struct { @@ -96,6 +97,14 @@ type FindingSeverityDTO struct { Low int `json:"low"` } +// TaskProxyRouteDTO summarizes a task container's effective proxy route override. +type TaskProxyRouteDTO struct { + Mode string `json:"mode"` + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` + EffectiveProxy string `json:"effective_proxy"` +} + func applyTaskArchiveBlocker(dto *TaskDTO, blockers map[int64]int64) { if dto == nil || len(blockers) == 0 { return @@ -191,28 +200,40 @@ func completedRFC(unix int64) string { // ---- TrafficExchange (frontend "TrafficExchange") ---- ts as RFC3339. type TrafficExchangeDTO struct { - ID string `json:"id"` - TS string `json:"ts"` - Host string `json:"host"` - Method string `json:"method"` - URL string `json:"url"` - Status int `json:"status"` - ContentType string `json:"content_type"` - RespLen int `json:"resp_len"` + ID string `json:"id"` + TS string `json:"ts"` + Host string `json:"host"` + Method string `json:"method"` + URL string `json:"url"` + Status int `json:"status"` + ContentType string `json:"content_type"` + RespLen int `json:"resp_len"` + SandboxScope string `json:"sandbox_scope,omitempty"` + SandboxOwnerID string `json:"sandbox_owner_id,omitempty"` + ContainerID string `json:"container_id,omitempty"` + SessionID string `json:"session_id,omitempty"` + IntentID int64 `json:"intent_id,omitempty"` + SrcIP string `json:"src_ip,omitempty"` } func trafficDTOs(ex []traffic.ExchangeMeta) []TrafficExchangeDTO { out := make([]TrafficExchangeDTO, 0, len(ex)) for _, e := range ex { out = append(out, TrafficExchangeDTO{ - ID: e.ID, - TS: rfc3339(time.Unix(e.TS, 0)), - Host: e.Host, - Method: e.Method, - URL: e.URL, - Status: e.Status, - ContentType: e.ContentType, - RespLen: e.RespLen, + ID: e.ID, + TS: rfc3339(time.Unix(e.TS, 0)), + Host: e.Host, + Method: e.Method, + URL: e.URL, + Status: e.Status, + ContentType: e.ContentType, + RespLen: e.RespLen, + SandboxScope: e.SandboxScope, + SandboxOwnerID: e.SandboxOwnerID, + ContainerID: e.ContainerID, + SessionID: e.SessionID, + IntentID: e.IntentID, + SrcIP: e.SrcIP, }) } return out diff --git a/server/egress_blacklist.go b/server/egress_blacklist.go new file mode 100644 index 0000000..7e3fb74 --- /dev/null +++ b/server/egress_blacklist.go @@ -0,0 +1,410 @@ +package server + +import ( + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/traffic" +) + +const ( + settingEgressBlacklistRules = "egress_blacklist_rules_json" + settingEgressBlacklistSync = "egress_blacklist_sync_asset_intercept" +) + +func (s *Server) loadCustomEgressBlacklist() []traffic.EgressBlacklistRule { + if s.m.pg == nil { + return []traffic.EgressBlacklistRule{} + } + raw, ok, err := s.m.pg.GetSetting(settingEgressBlacklistRules) + if err != nil || !ok || strings.TrimSpace(raw) == "" { + return []traffic.EgressBlacklistRule{} + } + var rules []traffic.EgressBlacklistRule + if err := json.Unmarshal([]byte(raw), &rules); err != nil { + return []traffic.EgressBlacklistRule{} + } + if rules == nil { + return []traffic.EgressBlacklistRule{} + } + for i := range rules { + rules[i].Source = "custom" + } + return rules +} + +func (s *Server) saveCustomEgressBlacklist(rules []traffic.EgressBlacklistRule) error { + if s.m.pg == nil { + return fmt.Errorf("database unavailable") + } + if rules == nil { + rules = []traffic.EgressBlacklistRule{} + } + b, err := json.Marshal(rules) + if err != nil { + return err + } + return s.m.pg.SetSetting(settingEgressBlacklistRules, string(b)) +} + +func (s *Server) egressBlacklistSyncAssetEnabled() bool { + if s.m.pg == nil { + return false + } + return s.m.pg.GetBool(settingEgressBlacklistSync, false) +} + +// translateAssetInterceptRules converts enabled global asset_intercept_rules +// into network-layer egress blacklist rules. Rules that only match URL paths +// without a concrete host are skipped because network-layer checks operate on +// destination host/IP/CIDR. +func translateAssetInterceptRules(in []db.AssetInterceptRule) []traffic.EgressBlacklistRule { + out := make([]traffic.EgressBlacklistRule, 0, len(in)) + for _, r := range in { + if !r.Enabled { + continue + } + pat := strings.TrimSpace(r.Pattern) + if pat == "" { + continue + } + var kind, normalized string + switch r.Kind { + case "exact_domain": + kind = "domain" + normalized = pat + case "fuzzy_domain": + kind = "suffix" + normalized = pat + case "exact_ip": + kind = "ip" + normalized = pat + case "cidr": + kind = "cidr" + normalized = pat + case "exact_url", "fuzzy_url": + raw := pat + if !strings.Contains(raw, "://") { + raw = "http://" + raw + } + u, err := url.Parse(raw) + if err != nil || strings.TrimSpace(u.Hostname()) == "" { + continue + } + h := u.Hostname() + if net.ParseIP(h) != nil { + kind = "ip" + normalized = h + } else if r.Kind == "fuzzy_url" { + kind = "suffix" + normalized = h + } else { + kind = "domain" + normalized = h + } + default: + continue + } + er := traffic.EgressBlacklistRule{ + ID: fmt.Sprintf("asset-%d", r.ID), + Enabled: true, + Kind: kind, + Pattern: normalized, + Note: r.Note, + Source: "asset_intercept", + } + if err := traffic.NormalizeEgressRule(&er); err != nil { + continue + } + out = append(out, er) + } + return out +} + +// syncEgressBlacklist compiles and hot-loads custom egress blacklist rules plus +// optionally synced global asset_intercept_rules into the recording proxy. +func (s *Server) syncEgressBlacklist() { + if s.m.traffic == nil { + return + } + custom := s.loadCustomEgressBlacklist() + effective := make([]traffic.EgressBlacklistRule, 0, len(custom)) + effective = append(effective, custom...) + if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil { + if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil { + effective = append(effective, translateAssetInterceptRules(assetRules)...) + } + } + s.m.traffic.SetEgressBlacklist(effective) +} + +// GET /api/proxy/blacklist +func (s *Server) getEgressBlacklist(w http.ResponseWriter, r *http.Request) { + custom := s.loadCustomEgressBlacklist() + syncOn := s.egressBlacklistSyncAssetEnabled() + synced := []traffic.EgressBlacklistRule{} + if s.m.pg != nil { + if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil { + synced = translateAssetInterceptRules(assetRules) + } + } + events := []traffic.EgressBlockEvent{} + if s.m.traffic != nil { + events = s.m.traffic.BlockEvents(100) + } + writeJSON(w, 200, map[string]any{ + "rules": custom, + "synced_rules": synced, + "sync_asset_intercept": syncOn, + "events": events, + }) +} + +// PUT /api/proxy/blacklist/settings +func (s *Server) updateEgressBlacklistSettings(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + var req struct { + SyncAssetIntercept bool `json:"sync_asset_intercept"` + } + if err := decode(r, &req); err != nil { + writeErr(w, 400, err.Error()) + return + } + val := "false" + if req.SyncAssetIntercept { + val = "true" + } + if err := pg.SetSetting(settingEgressBlacklistSync, val); err != nil { + writeErr(w, 500, err.Error()) + return + } + s.syncEgressBlacklist() + s.getEgressBlacklist(w, r) +} + +// POST /api/proxy/blacklist/rules +func (s *Server) createEgressBlacklistRule(w http.ResponseWriter, r *http.Request) { + var req struct { + Enabled *bool `json:"enabled"` + Kind string `json:"kind"` + Pattern string `json:"pattern"` + Port int `json:"port"` + Note string `json:"note"` + } + if err := decode(r, &req); err != nil { + writeErr(w, 400, err.Error()) + return + } + enabled := true + if req.Enabled != nil { + enabled = *req.Enabled + } + now := time.Now().UTC().Format(time.RFC3339) + rule := traffic.EgressBlacklistRule{ + ID: fmt.Sprintf("eb-%d", time.Now().UnixNano()), + Enabled: enabled, + Kind: req.Kind, + Pattern: req.Pattern, + Port: req.Port, + Note: req.Note, + Source: "custom", + CreatedAt: now, + UpdatedAt: now, + } + if err := traffic.NormalizeEgressRule(&rule); err != nil { + writeErr(w, 400, err.Error()) + return + } + rules := s.loadCustomEgressBlacklist() + for _, existing := range rules { + if existing.Kind == rule.Kind && existing.Pattern == rule.Pattern && existing.Port == rule.Port { + writeErr(w, 409, "相同规则已存在") + return + } + } + rules = append([]traffic.EgressBlacklistRule{rule}, rules...) + if err := s.saveCustomEgressBlacklist(rules); err != nil { + writeErr(w, 500, err.Error()) + return + } + s.syncEgressBlacklist() + writeJSON(w, 200, rule) +} + +// PUT /api/proxy/blacklist/rules/{id} +func (s *Server) updateEgressBlacklistRule(w http.ResponseWriter, r *http.Request) { + id := strings.TrimSpace(r.PathValue("id")) + if id == "" { + writeErr(w, 400, "invalid rule id") + return + } + var req struct { + Enabled *bool `json:"enabled"` + Kind *string `json:"kind"` + Pattern *string `json:"pattern"` + Port *int `json:"port"` + Note *string `json:"note"` + } + if err := decode(r, &req); err != nil { + writeErr(w, 400, err.Error()) + return + } + rules := s.loadCustomEgressBlacklist() + idx := -1 + for i := range rules { + if rules[i].ID == id { + idx = i + break + } + } + if idx < 0 { + writeErr(w, 404, "规则不存在") + return + } + updated := rules[idx] + if req.Enabled != nil { + updated.Enabled = *req.Enabled + } + if req.Kind != nil { + updated.Kind = *req.Kind + } + if req.Pattern != nil { + updated.Pattern = *req.Pattern + } + if req.Port != nil { + updated.Port = *req.Port + } + if req.Note != nil { + updated.Note = *req.Note + } + updated.Source = "custom" + updated.UpdatedAt = time.Now().UTC().Format(time.RFC3339) + if err := traffic.NormalizeEgressRule(&updated); err != nil { + writeErr(w, 400, err.Error()) + return + } + rules[idx] = updated + if err := s.saveCustomEgressBlacklist(rules); err != nil { + writeErr(w, 500, err.Error()) + return + } + s.syncEgressBlacklist() + writeJSON(w, 200, updated) +} + +// DELETE /api/proxy/blacklist/rules/{id} +func (s *Server) deleteEgressBlacklistRule(w http.ResponseWriter, r *http.Request) { + id := strings.TrimSpace(r.PathValue("id")) + if id == "" { + writeErr(w, 400, "invalid rule id") + return + } + rules := s.loadCustomEgressBlacklist() + next := make([]traffic.EgressBlacklistRule, 0, len(rules)) + found := false + for _, rule := range rules { + if rule.ID == id { + found = true + continue + } + next = append(next, rule) + } + if !found { + writeErr(w, 404, "规则不存在") + return + } + if err := s.saveCustomEgressBlacklist(next); err != nil { + writeErr(w, 500, err.Error()) + return + } + s.syncEgressBlacklist() + writeJSON(w, 200, map[string]any{"deleted": id}) +} + +// DELETE /api/proxy/blacklist/events +func (s *Server) clearEgressBlockEvents(w http.ResponseWriter, _ *http.Request) { + if s.m.traffic != nil { + s.m.traffic.ClearBlockEvents() + } + writeJSON(w, 200, map[string]any{"cleared": true}) +} + +type cachedTaskEgressRules struct { + block []traffic.EgressBlacklistRule + allow []traffic.EgressBlacklistRule + fetchedAt time.Time +} + +var taskEgressRulesCache sync.Map // int64(taskID) -> cachedTaskEgressRules + +const taskEgressCacheTTL = 3 * time.Second + +// checkTaskEgressBlacklist evaluates task-scoped task_intercept_rules at the +// recording proxy egress boundary (#218 Phase 2). Built-in SSRF guard is always +// evaluated before this callback and cannot be bypassed by task allow rules. +func (s *Server) checkTaskEgressBlacklist(taskIDStr, rawHost, scheme string) (string, string) { + if s == nil || s.m == nil || s.m.Assets() == nil { + return "", "" + } + taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64) + if err != nil || taskID <= 0 { + return "", "" + } + var entry cachedTaskEgressRules + if v, ok := taskEgressRulesCache.Load(taskID); ok { + if c, ok2 := v.(cachedTaskEgressRules); ok2 && time.Since(c.fetchedAt) < taskEgressCacheTTL { + entry = c + } + } + if entry.fetchedAt.IsZero() { + blockRaw, allowRaw, err := s.m.Assets().TaskInterceptRulesSplit(taskID) + if err != nil { + return "", "" + } + entry = cachedTaskEgressRules{ + block: translateAssetInterceptRules(blockRaw), + allow: translateAssetInterceptRules(allowRaw), + fetchedAt: time.Now(), + } + taskEgressRulesCache.Store(taskID, entry) + } + if len(entry.block) == 0 { + return "", "" + } + if len(entry.allow) > 0 { + if reason, _ := traffic.MatchEgressRules(entry.allow, rawHost, scheme); reason != "" { + return "", "" + } + } + if reason, pat := traffic.MatchEgressRules(entry.block, rawHost, scheme); reason != "" { + return fmt.Sprintf("task #%d intercept rule: %s", taskID, reason), pat + } + return "", "" +} + +// loadTaskEgressRules returns translated block rules for one task (used for gateway sync). +func (s *Server) loadTaskEgressRules(taskIDStr string) []traffic.EgressBlacklistRule { + if s == nil || s.m == nil || s.m.Assets() == nil { + return nil + } + taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64) + if err != nil || taskID <= 0 { + return nil + } + blockRaw, _, err := s.m.Assets().TaskInterceptRulesSplit(taskID) + if err != nil || len(blockRaw) == 0 { + return nil + } + return translateAssetInterceptRules(blockRaw) +} diff --git a/server/egress_blacklist_test.go b/server/egress_blacklist_test.go new file mode 100644 index 0000000..fafd230 --- /dev/null +++ b/server/egress_blacklist_test.go @@ -0,0 +1,38 @@ +package server + +import ( + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestTranslateAssetInterceptRules(t *testing.T) { + in := []db.AssetInterceptRule{ + {ID: 1, Enabled: true, Kind: "exact_domain", Pattern: "Admin.Example.com", Note: "prod"}, + {ID: 2, Enabled: true, Kind: "fuzzy_domain", Pattern: "gov.cn", Note: "gov"}, + {ID: 3, Enabled: true, Kind: "exact_ip", Pattern: "198.51.100.9"}, + {ID: 4, Enabled: true, Kind: "cidr", Pattern: "203.0.113.0/24"}, + {ID: 5, Enabled: true, Kind: "exact_url", Pattern: "https://pay.example.org:8443/checkout"}, + {ID: 6, Enabled: false, Kind: "exact_domain", Pattern: "disabled.example.com"}, + {ID: 7, Enabled: true, Kind: "fuzzy_url", Pattern: "/admin/delete"}, + } + got := translateAssetInterceptRules(in) + if len(got) != 5 { + t.Fatalf("translated %d rules, want 5: %+v", len(got), got) + } + want := []struct { + kind string + pattern string + }{ + {"domain", "admin.example.com"}, + {"suffix", "*.gov.cn"}, + {"ip", "198.51.100.9"}, + {"cidr", "203.0.113.0/24"}, + {"domain", "pay.example.org"}, + } + for i, w := range want { + if got[i].Kind != w.kind || got[i].Pattern != w.pattern || got[i].Source != "asset_intercept" { + t.Fatalf("rule[%d] = %+v, want kind=%s pattern=%s source=asset_intercept", i, got[i], w.kind, w.pattern) + } + } +} diff --git a/server/engine.go b/server/engine.go index 3ac9f02..1c2a17c 100644 --- a/server/engine.go +++ b/server/engine.go @@ -14,6 +14,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/norma/harness" "github.com/Autumn-27/norma/llm" "github.com/jackc/pgx/v5/pgconn" @@ -190,6 +191,9 @@ func (e *Engine) nextPlannerRound(taskID string) int { func (e *Engine) Pause(taskID string, cause error) { e.paused.Store(taskID, true) e.cancelExec(taskID, cause) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID}) + } } // BeginDelete installs an execution barrier before task data/files are removed. @@ -205,9 +209,13 @@ func (e *Engine) BeginDelete(taskID string) bool { e.paused.Store(taskID, true) e.deleteMu.Unlock() e.cancelExec(taskID, agent.AbortTaskDeleted) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + _ = mgr.Stop(sctx, sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID}) + cancel() + } return true } - func (e *Engine) AbortDelete(taskID string, keepPaused bool) { e.deleteMu.Lock() if !e.IsDeleting(taskID) { @@ -306,11 +314,15 @@ func (e *Engine) StopTask(taskID string) { } return true }) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + rctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + _ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID}) + cancel() + } e.deleteMu.Lock() e.deleting.Delete(taskID) e.deleteMu.Unlock() } - // cancelExec cancels a task's current per-task exec context (any in-flight // planner.Plan / worker.Execute), if present. Shared by Pause and the settle // sequence's hard-drain backstop. @@ -336,10 +348,12 @@ func (e *Engine) Resume(t *Task) { if e.IsDeleting(t.ID) { return } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + mgr.ClearIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}) + } e.paused.Delete(t.ID) t.Notify() } - // execContextFor returns a live per-task context derived from parent, recreating // it if a prior pause cancelled it. func (e *Engine) execContextFor(parent context.Context, taskID string) context.Context { diff --git a/server/gateway_api.go b/server/gateway_api.go new file mode 100644 index 0000000..782adce --- /dev/null +++ b/server/gateway_api.go @@ -0,0 +1,211 @@ +package server + +import ( + "crypto/subtle" + "encoding/json" + "log" + "net" + "net/http" + "os" + "strings" + "time" + + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" +) + +// authorizeGatewayRequest authenticates internal requests from artex-gateway. +// When ARTEX_GATEWAY_TOKEN is configured, X-Artex-Gateway-Token must match +// exactly (constant-time). When unset, only loopback callers are permitted. +func (s *Server) authorizeGatewayRequest(r *http.Request) bool { + expected := strings.TrimSpace(os.Getenv("ARTEX_GATEWAY_TOKEN")) + if expected != "" { + got := strings.TrimSpace(r.Header.Get("X-Artex-Gateway-Token")) + return len(got) == len(expected) && subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1 + } + host := r.RemoteAddr + if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { + host = h + } + ip := net.ParseIP(strings.Trim(strings.TrimSpace(host), "[]")) + return ip != nil && ip.IsLoopback() +} + +// GET /api/internal/gateway/policy +func (s *Server) getGatewayPolicy(w http.ResponseWriter, r *http.Request) { + if !s.authorizeGatewayRequest(r) { + writeErr(w, http.StatusUnauthorized, "unauthorized gateway request") + return + } + rt := s.ensureRouteRuntime() + gwID := strings.TrimSpace(r.URL.Query().Get("gateway_id")) + rt.mu.Lock() + rt.gwLastSeen = time.Now() + if gwID != "" { + rt.gwID = gwID + } + gs := rt.gwSettings + routesCopy := make(map[string]ContainerProxyRoute, len(rt.routes)) + for k, v := range rt.routes { + routesCopy[k] = v + } + rt.mu.Unlock() + + snap := traffic.GatewayPolicySnapshot{ + GlobalUpstreamURL: strings.TrimSpace(s.m.GlobalProxy()), + ContainerRoutes: make(map[string]traffic.GatewayContainerRoute, len(routesCopy)), + UDPPolicy: traffic.NormalizeUDPPolicy(gs.UDPPolicy), + DNSUpstream: gs.DNSUpstream, + StoreErrorTraffic: gs.StoreErrorTraffic, + } + + if s.m.traffic != nil { + if ssrf := s.m.traffic.SSRFGuardConfigSnapshot(); ssrf != nil && ssrf.Enabled { + gp := &traffic.GatewaySSRFPolicy{ + Enabled: true, + BlockPrivate: ssrf.BlockPrivate, + BlockedHosts: ssrf.BlockedHosts, + } + for _, c := range ssrf.BlockedCIDRs { + if c != nil { + gp.BlockedCIDRs = append(gp.BlockedCIDRs, c.String()) + } + } + for _, ip := range ssrf.InfraIPs { + if ip != nil { + gp.InfraIPs = append(gp.InfraIPs, ip.String()) + } + } + snap.SSRF = gp + } + snap.PassthroughHosts = s.m.traffic.PassthroughHosts() + } + + // Global + synced egress blacklist rules. + rules := s.loadCustomEgressBlacklist() + if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil { + if globalAssets, err := s.m.pg.ListAssetInterceptRules(); err == nil { + rules = append(rules, translateAssetInterceptRules(globalAssets)...) + } + } + snap.BlacklistRules = rules + + // Active sandbox container IP map + task-level asset intercept rules. + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + ipSnap := mgr.ContainerIPSnapshot() + snap.ContainerIPs = make(map[string]traffic.SourceIdentity, len(ipSnap)) + taskIDs := map[string]struct{}{} + for ip, ci := range ipSnap { + snap.ContainerIPs[ip] = traffic.SourceIdentity{ + Scope: string(ci.Scope), + OwnerID: ci.OwnerID, + ContainerID: ci.ContainerID, + SrcIP: ip, + } + if ci.Scope == sandbox.ScopeTask && ci.OwnerID != "" { + taskIDs[ci.OwnerID] = struct{}{} + } + } + if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil && len(taskIDs) > 0 { + snap.TaskRules = make(map[string][]traffic.EgressBlacklistRule, len(taskIDs)) + for tid := range taskIDs { + if tr := s.loadTaskEgressRules(tid); len(tr) > 0 { + snap.TaskRules[tid] = tr + } + } + } + } + + for key, route := range routesCopy { + snap.ContainerRoutes[key] = traffic.GatewayContainerRoute{ + Scope: route.Scope, + OwnerID: route.OwnerID, + Mode: route.Mode, + ProxyPoolID: route.ProxyPoolID, + ProxyURL: maskSecrets(route.ProxyURL), + EffectiveURL: s.resolveRouteEffectiveRawURL(route), + Note: route.Note, + UpdatedAt: route.UpdatedAt, + } + } + + writeJSON(w, 200, snap) +} + +// POST /api/internal/gateway/events +func (s *Server) postGatewayEvents(w http.ResponseWriter, r *http.Request) { + if !s.authorizeGatewayRequest(r) { + writeErr(w, http.StatusUnauthorized, "unauthorized gateway request") + return + } + var batch traffic.GatewayEventBatch + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)).Decode(&batch); err != nil { + writeErr(w, http.StatusBadRequest, "invalid batch payload") + return + } + rt := s.ensureRouteRuntime() + rt.mu.Lock() + rt.gwLastSeen = time.Now() + if strings.TrimSpace(batch.GatewayID) != "" { + rt.gwID = strings.TrimSpace(batch.GatewayID) + } + rt.mu.Unlock() + + tr := s.m.Traffic() + if tr == nil { + writeJSON(w, 200, map[string]any{"ingested": 0}) + return + } + ingested := 0 + for _, nf := range batch.NetFlows { + if err := tr.RecordNetFlow(nf); err == nil { + ingested++ + } + } + for _, dq := range batch.DNSQueries { + if err := tr.RecordDNSQuery(dq); err == nil { + ingested++ + } + } + for _, ev := range batch.BlockEvents { + tr.RecordBlockEvent(ev) + ingested++ + } + writeJSON(w, 200, map[string]any{"ingested": ingested}) +} + +// startEmbeddedTransparentGatewayIfConfigured optionally launches an in-process +// TransparentGateway when bare-metal Linux operators set ARTEX_EMBEDDED_TRANSPARENT_TCP +// / ARTEX_EMBEDDED_TRANSPARENT_DNS / ARTEX_EMBEDDED_TRANSPARENT_UDP directly on artex. +func (s *Server) startEmbeddedTransparentGatewayIfConfigured() { + if s.m.traffic == nil { + return + } + tcpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_TCP")) + dnsAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_DNS")) + udpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_UDP")) + if tcpAddr == "" && dnsAddr == "" && udpAddr == "" { + return + } + mitmAddr := strings.TrimSpace(s.m.ProxyAddr()) + if strings.HasPrefix(mitmAddr, ":") { + mitmAddr = "127.0.0.1" + mitmAddr + } + gw := traffic.NewTransparentGateway(traffic.TransparentConfig{ + TCPAddr: tcpAddr, + DNSAddr: dnsAddr, + UDPAddr: udpAddr, + MITMProxyAddr: mitmAddr, + }, traffic.LocalTransparentBackend{T: s.m.traffic}) + if err := gw.Start(); err != nil { + log.Printf("[gateway] embedded transparent gateway start failed: %v", err) + return + } + rt := s.ensureRouteRuntime() + rt.mu.Lock() + rt.embeddedGW = gw + rt.gwID = "embedded" + rt.gwLastSeen = time.Now() + rt.mu.Unlock() + log.Printf("[gateway] embedded transparent gateway started tcp=%q dns=%q udp=%q", tcpAddr, dnsAddr, udpAddr) +} diff --git a/server/gateway_api_test.go b/server/gateway_api_test.go new file mode 100644 index 0000000..5d3d8a2 --- /dev/null +++ b/server/gateway_api_test.go @@ -0,0 +1,279 @@ +package server + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Autumn-27/artex/traffic" +) + +func TestGatewaySyncAndNonHTTPTrafficAPIs(t *testing.T) { + t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-218") + + tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + s := &Server{ + m: &Manager{ + traffic: tr, + tasks: map[string]*Task{}, + }, + } + s.initProxyRoutesAndGateway() + + // 1. Unauthorized gateway policy request must be rejected with 401. + reqUnauth := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil) + recUnauth := httptest.NewRecorder() + s.getGatewayPolicy(recUnauth, reqUnauth) + if recUnauth.Code != http.StatusUnauthorized { + t.Fatalf("expected 401 for missing token, got %d", recUnauth.Code) + } + + // 2. Configure per-container proxy route + gateway settings. + putRouteBody := `{"mode":"proxy","proxy_url":"socks5://127.0.0.1:1080","note":"task 5 socks5"}` + reqRoute := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(putRouteBody)) + reqRoute.SetPathValue("scope", "task") + reqRoute.SetPathValue("owner_id", "5") + recRoute := httptest.NewRecorder() + s.putProxyRoute(recRoute, reqRoute) + if recRoute.Code != http.StatusOK { + t.Fatalf("putProxyRoute failed: %d %s", recRoute.Code, recRoute.Body.String()) + } + + reqGW := httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"block","dns_upstream":"1.1.1.1:53"}`)) + recGW := httptest.NewRecorder() + s.updateGatewaySettings(recGW, reqGW) + if recGW.Code != http.StatusOK { + t.Fatalf("updateGatewaySettings failed: %d %s", recGW.Code, recGW.Body.String()) + } + + // 3. Authorized gateway policy fetch returns route & settings. + reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-test", nil) + reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218") + recPol := httptest.NewRecorder() + s.getGatewayPolicy(recPol, reqPol) + if recPol.Code != http.StatusOK { + t.Fatalf("getGatewayPolicy failed: %d %s", recPol.Code, recPol.Body.String()) + } + var snap traffic.GatewayPolicySnapshot + if err := json.Unmarshal(recPol.Body.Bytes(), &snap); err != nil { + t.Fatalf("decode policy snapshot: %v", err) + } + if snap.UDPPolicy != traffic.UDPPolicyBlock || snap.DNSUpstream != "1.1.1.1:53" { + t.Fatalf("unexpected gateway policy: %+v", snap) + } + if r, ok := snap.ContainerRoutes["task:5"]; !ok || r.EffectiveURL != "socks5://127.0.0.1:1080" { + t.Fatalf("expected task:5 route in snapshot, got %+v", snap.ContainerRoutes) + } + + // 4. Ingest gateway events (net_flows + dns_queries + block_events). + batch := traffic.GatewayEventBatch{ + GatewayID: "gw-test", + NetFlows: []traffic.NetFlowRecord{{ + ID: "nf-test-1", + TS: time.Now().Unix(), + Protocol: "tcp", + DstIP: "10.0.0.8", + DstPort: 3306, + DstHost: "db.target.local", + Action: "allow", + BytesTX: 64, + BytesRX: 128, + TXPreview: []byte("SELECT 1"), + RXPreview: []byte("5.7.40-mysql"), + SandboxScope: "task", + SandboxOwnerID: "5", + SrcIP: "172.30.0.5", + }}, + DNSQueries: []traffic.DNSQueryRecord{{ + ID: "dns-test-1", + TS: time.Now().Unix(), + QName: "db.target.local", + QType: "A", + RCode: "NOERROR", + Answers: []string{"10.0.0.8"}, + Action: "allow", + Upstream: "direct:1.1.1.1:53", + SandboxScope: "task", + SandboxOwnerID: "5", + SrcIP: "172.30.0.5", + }}, + } + rawBatch, _ := json.Marshal(batch) + reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch)) + reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218") + recEv := httptest.NewRecorder() + s.postGatewayEvents(recEv, reqEv) + if recEv.Code != http.StatusOK { + t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String()) + } + + // 5. Query flows + flow detail + DNS via public API handlers. + recFlows := httptest.NewRecorder() + s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?protocol=tcp", nil)) + if recFlows.Code != http.StatusOK { + t.Fatalf("getTrafficFlows: %d %s", recFlows.Code, recFlows.Body.String()) + } + var flowsResp struct { + Total int `json:"total"` + Flows []traffic.NetFlowRecord `json:"flows"` + } + _ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp) + if flowsResp.Total != 1 || len(flowsResp.Flows) != 1 || flowsResp.Flows[0].DstPort != 3306 { + t.Fatalf("unexpected flowsResp: %+v", flowsResp) + } + + reqDet := httptest.NewRequest(http.MethodGet, "/api/traffic/flows/nf-test-1", nil) + reqDet.SetPathValue("id", "nf-test-1") + recDet := httptest.NewRecorder() + s.getTrafficFlowDetail(recDet, reqDet) + if recDet.Code != http.StatusOK || !bytes.Contains(recDet.Body.Bytes(), []byte("SELECT 1")) { + t.Fatalf("unexpected flow detail: %d %s", recDet.Code, recDet.Body.String()) + } + + recDNS := httptest.NewRecorder() + s.getTrafficDNS(recDNS, httptest.NewRequest(http.MethodGet, "/api/traffic/dns?q=db.target", nil)) + if recDNS.Code != http.StatusOK { + t.Fatalf("getTrafficDNS: %d %s", recDNS.Code, recDNS.Body.String()) + } + var dnsResp struct { + Total int `json:"total"` + Queries []traffic.DNSQueryRecord `json:"queries"` + } + _ = json.Unmarshal(recDNS.Body.Bytes(), &dnsResp) + if dnsResp.Total != 1 || len(dnsResp.Queries) != 1 || dnsResp.Queries[0].QName != "db.target.local" { + t.Fatalf("unexpected dnsResp: %+v", dnsResp) + } + + // 6. GET /api/proxy/routes reflects gateway connected=true and task:5 override. + recRoutes := httptest.NewRecorder() + s.getProxyRoutes(recRoutes, httptest.NewRequest(http.MethodGet, "/api/proxy/routes", nil)) + if recRoutes.Code != http.StatusOK { + t.Fatalf("getProxyRoutes: %d %s", recRoutes.Code, recRoutes.Body.String()) + } + body := recRoutes.Body.String() + if !bytes.Contains([]byte(body), []byte(`"connected":true`)) || !bytes.Contains([]byte(body), []byte(`"socks5://127.0.0.1:1080"`)) { + t.Fatalf("unexpected getProxyRoutes body: %s", body) + } + if bytes.Contains([]byte(body), []byte("全局")) { + t.Fatalf("getProxyRoutes must not hardcode Chinese labels in API response: %s", body) + } +} + +func TestStoreErrorTrafficPolicyPartialUpdateAndIngestion(t *testing.T) { + t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-err") + + tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + s := &Server{ + m: &Manager{ + traffic: tr, + tasks: map[string]*Task{}, + }, + } + s.initProxyRoutesAndGateway() + + // Set UDP & DNS first; store_error_traffic remains default false. + recSet := httptest.NewRecorder() + s.updateGatewaySettings(recSet, httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"direct","dns_upstream":"9.9.9.9:53"}`))) + if recSet.Code != http.StatusOK { + t.Fatalf("updateGatewaySettings initial failed: %d %s", recSet.Code, recSet.Body.String()) + } + + // Ingest an error flow & an allow flow while store_error_traffic=false. + rawBatch, _ := json.Marshal(traffic.GatewayEventBatch{ + GatewayID: "gw-err", + NetFlows: []traffic.NetFlowRecord{ + {ID: "nf-ok", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.1", DstPort: 80, Action: "allow"}, + {ID: "nf-err-1", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 81, Action: "error", Error: "refused"}, + }, + DNSQueries: []traffic.DNSQueryRecord{ + {ID: "dns-ok", TS: time.Now().Unix(), QName: "ok.test", QType: "A", Action: "allow"}, + {ID: "dns-err-1", TS: time.Now().Unix(), QName: "err.test", QType: "A", Action: "error", RCode: "SERVFAIL"}, + }, + }) + reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch)) + reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err") + recEv := httptest.NewRecorder() + s.postGatewayEvents(recEv, reqEv) + if recEv.Code != http.StatusOK { + t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String()) + } + + // Verify only non-error rows were persisted and GET /api/traffic/flows reports store_error_traffic=false. + recFlows := httptest.NewRecorder() + s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows", nil)) + var flowsResp struct { + StoreErrorTraffic bool `json:"store_error_traffic"` + Total int `json:"total"` + Flows []traffic.NetFlowRecord `json:"flows"` + } + _ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp) + if flowsResp.StoreErrorTraffic || flowsResp.Total != 1 || flowsResp.Flows[0].ID != "nf-ok" { + t.Fatalf("expected store_error_traffic=false and 1 allow flow, got %+v", flowsResp) + } + + // Partial update from Traffic UI toggling only store_error_traffic=true must preserve udp_policy & dns_upstream. + recToggle := httptest.NewRecorder() + s.updateGatewaySettings(recToggle, httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"store_error_traffic":true}`))) + if recToggle.Code != http.StatusOK { + t.Fatalf("partial toggle failed: %d %s", recToggle.Code, recToggle.Body.String()) + } + var updated GatewaySettings + _ = json.Unmarshal(recToggle.Body.Bytes(), &updated) + if !updated.StoreErrorTraffic || updated.UDPPolicy != traffic.UDPPolicyDirect || updated.DNSUpstream != "9.9.9.9:53" { + t.Fatalf("partial update clobbered fields: %+v", updated) + } + + // Gateway policy snapshot reflects store_error_traffic=true. + reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil) + reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err") + recPol := httptest.NewRecorder() + s.getGatewayPolicy(recPol, reqPol) + var snap traffic.GatewayPolicySnapshot + _ = json.Unmarshal(recPol.Body.Bytes(), &snap) + if !snap.StoreErrorTraffic { + t.Fatalf("expected gateway policy snapshot store_error_traffic=true, got %+v", snap) + } + + // Subsequent error flow & DNS query are persisted. + rawBatch2, _ := json.Marshal(traffic.GatewayEventBatch{ + GatewayID: "gw-err", + NetFlows: []traffic.NetFlowRecord{ + {ID: "nf-err-2", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 81, Action: "error", Error: "refused"}, + }, + DNSQueries: []traffic.DNSQueryRecord{ + {ID: "dns-err-2", TS: time.Now().Unix(), QName: "err.test", QType: "A", Action: "error", RCode: "SERVFAIL"}, + }, + }) + reqEv2 := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch2)) + reqEv2.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err") + recEv2 := httptest.NewRecorder() + s.postGatewayEvents(recEv2, reqEv2) + if recEv2.Code != http.StatusOK { + t.Fatalf("postGatewayEvents 2 failed: %d %s", recEv2.Code, recEv2.Body.String()) + } + + recFlows2 := httptest.NewRecorder() + s.getTrafficFlows(recFlows2, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?action=error", nil)) + var flowsResp2 struct { + StoreErrorTraffic bool `json:"store_error_traffic"` + Total int `json:"total"` + Flows []traffic.NetFlowRecord `json:"flows"` + } + _ = json.Unmarshal(recFlows2.Body.Bytes(), &flowsResp2) + if !flowsResp2.StoreErrorTraffic || flowsResp2.Total != 1 || flowsResp2.Flows[0].ID != "nf-err-2" { + t.Fatalf("expected error flow stored after toggle, got %+v", flowsResp2) + } +} diff --git a/server/manager.go b/server/manager.go index ddbd9ae..3d861ef 100644 --- a/server/manager.go +++ b/server/manager.go @@ -21,6 +21,7 @@ import ( "github.com/Autumn-27/artex/enrich" "github.com/Autumn-27/artex/guard" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/traffic" actool "github.com/Autumn-27/norma/tool" ) @@ -2052,12 +2053,16 @@ func (m *Manager) SetTaskStatusGuardedReason(id, status, reason string) (won boo }) } m.mu.Unlock() + if pgdb.IsTerminal(status) { + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: id}) + } + } if err := m.syncTaskRuntime(id, n); err != nil { return true, err } return true, nil } - // SetTaskStatus persists a task's lifecycle status (e.g. "done") and reflects it // on the in-memory handle so the derived DTO status shows it without a reload. func (m *Manager) SetTaskStatus(id, status string) error { @@ -2097,12 +2102,19 @@ func (m *Manager) SetTaskStatus(id, status string) error { }) } m.mu.Unlock() + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: id} + if pgdb.IsTerminal(status) { + mgr.RequestIdleStop(target) + } else { + mgr.ClearIdleStop(target) + } + } if err := m.syncTaskRuntime(id, n); err != nil { return err } return nil } - // DeleteTask removes a task and optionally its related global data. Traffic has // no task-id column, so related exchanges are resolved by exact hosts from the // task's asset rows. Files are staged before the database operation; traffic is @@ -2169,6 +2181,13 @@ func (m *Manager) DeleteTask(id string, opts DeleteTaskOptions) (DeleteTaskResul finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize traffic deletion: %w", err)) } } + if opts.DeleteTraffic && m.traffic != nil { + if deletedNonHTTP, err := m.traffic.DeleteNonHTTPByOwner("task", id); err != nil { + finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize non-http traffic deletion: %w", err)) + } else { + result.TrafficDeleted += deletedNonHTTP + } + } if fileStage != nil { if err := fileStage.commit(); err != nil { finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize task file deletion: %w", err)) diff --git a/server/mcpdiscover.go b/server/mcpdiscover.go index 355cb48..26a7815 100644 --- a/server/mcpdiscover.go +++ b/server/mcpdiscover.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/mcphttp" actool "github.com/Autumn-27/norma/tool" ) @@ -52,6 +53,16 @@ func resolveStdioMCPCommand(command string, args []string) (string, []string) { if pkgIdx < 0 { return command, out } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + rest := make([]string, 0, len(out)-1) + for i, arg := range out { + if i == pkgIdx || (i < pkgIdx && (arg == "-y" || arg == "--yes")) { + continue + } + rest = append(rest, arg) + } + return "playwright-mcp", rest + } if bin, err := lookPath("playwright-mcp"); err == nil && strings.TrimSpace(bin) != "" { rest := make([]string, 0, len(out)-1) for i, arg := range out { @@ -97,7 +108,20 @@ func connectMCP(ctx context.Context, m *db.MCPServer, workDir string) (mcpClient // discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool // names to mcp_tools_cache so the UI shows them without a live connection. func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error { - cl, err := connectMCP(ctx, m, s.m.dir) + workDir := s.m.dir + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && m.Transport == "stdio" { + if _, hasTarget := sandbox.TargetFrom(ctx); !hasTarget { + ephemeral := sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("mcp-discover-%d", time.Now().UnixNano())} + ctx = sandbox.WithTarget(ctx, ephemeral) + workDir = mgr.Config().LocalRootFor(ephemeral) + defer func() { + rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = mgr.Remove(rctx, ephemeral) + }() + } + } + cl, err := connectMCP(ctx, m, workDir) if err != nil { return err } diff --git a/server/mcpstdio.go b/server/mcpstdio.go index 29208e0..97e6778 100644 --- a/server/mcpstdio.go +++ b/server/mcpstdio.go @@ -8,11 +8,14 @@ import ( "errors" "fmt" "io" + "net" + "net/url" "os" "os/exec" + "sort" "strings" "sync" - + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/mcp" "github.com/Autumn-27/norma/permission" @@ -93,14 +96,45 @@ type stdioMCPClient struct { pending map[int]chan stdioRPCResponse closeCh chan struct{} once sync.Once - - cmd *exec.Cmd - stdin io.Closer - stderr *tailBuffer - closeOnce sync.Once + cmd *exec.Cmd + stream *sandbox.StreamSession + stdin io.Closer + stderr *tailBuffer + releaseSlot func() + closeOnce sync.Once } +const maxSandboxBrowserMCPPerTarget = 2 + +var ( + sandboxBrowserSlotsMu sync.Mutex + sandboxBrowserSlots = map[string]chan struct{}{} +) + +func acquireSandboxBrowserSlot(ctx context.Context, targetKey string) (func(), error) { + sandboxBrowserSlotsMu.Lock() + ch, ok := sandboxBrowserSlots[targetKey] + if !ok { + ch = make(chan struct{}, maxSandboxBrowserMCPPerTarget) + sandboxBrowserSlots[targetKey] = ch + } + sandboxBrowserSlotsMu.Unlock() + select { + case ch <- struct{}{}: + var once sync.Once + return func() { + once.Do(func() { <-ch }) + }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} func newStdioMCPClient(ctx context.Context, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) { + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + if target, ok := sandbox.TargetFrom(ctx); ok { + return newSandboxStdioMCPClient(ctx, mgr, target, server, workDir, command, env, args...) + } + } cmd := exec.Command(command, args...) if strings.TrimSpace(workDir) != "" { cmd.Dir = workDir @@ -141,6 +175,180 @@ func newStdioMCPClient(ctx context.Context, server, workDir, command string, env return c, nil } +func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target sandbox.Target, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) { + var releaseSlot func() + if server == browserMCPName && target.Scope == sandbox.ScopeTask { + rel, err := acquireSandboxBrowserSlot(ctx, target.Key()) + if err != nil { + return nil, fmt.Errorf("wait browser sandbox slot for %s: %w", target.Key(), err) + } + releaseSlot = rel + } + containerWorkDir := sandbox.ContainerWorkDir + if strings.TrimSpace(workDir) != "" { + containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), workDir) + } + sandboxProxyURL := "" + if mgr != nil { + sandboxProxyURL = stripURLCredentials(mgr.Config().ProxyURL) + } + adaptedArgs := adaptSandboxMCPArgs(args, sandboxProxyURL) + envSlice := buildSandboxMCPEnv(mgr, env) + stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{ + Cmd: append([]string{command}, adaptedArgs...), + WorkDir: containerWorkDir, + Env: envSlice, + }) + if err != nil { + if releaseSlot != nil { + releaseSlot() + } + return nil, err + } + stderr := newTailBuffer(4096) + go func() { _, _ = io.Copy(stderr, stream.Stderr) }() + c := &stdioMCPClient{ + server: server, + w: stream.Stdin, + pending: map[int]chan stdioRPCResponse{}, + closeCh: make(chan struct{}), + stream: stream, + stdin: stream.Stdin, + stderr: stderr, + releaseSlot: releaseSlot, + } + go c.readLoop(stream.Stdout) + if err := c.initialize(ctx); err != nil { + _ = c.Close() + return nil, err + } + return c, nil +} + +// adaptSandboxMCPArgs rewrites loopback --proxy-server flags (such as +// http://127.0.0.1:8788 persisted for local mode by syncBrowserMCPProxy) to the +// sandbox-reachable recording proxy URL (e.g. http://172.30.0.2:8788). +// Chromium rejects inline credentials in --proxy-server, so sandboxProxyURL must +// be credential-free; Layer-1 container source IP provides attribution. +func adaptSandboxMCPArgs(args []string, sandboxProxyURL string) []string { + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + arg := args[i] + if arg == "--proxy-server" && i+1 < len(args) { + val := args[i+1] + i++ + if isLoopbackProxyTarget(val) { + if sandboxProxyURL != "" { + out = append(out, "--proxy-server", sandboxProxyURL) + } + continue + } + out = append(out, "--proxy-server", val) + continue + } + if strings.HasPrefix(arg, "--proxy-server=") { + val := strings.TrimPrefix(arg, "--proxy-server=") + if isLoopbackProxyTarget(val) { + if sandboxProxyURL != "" { + out = append(out, "--proxy-server="+sandboxProxyURL) + } + continue + } + out = append(out, arg) + continue + } + out = append(out, arg) + } + return out +} + +func isLoopbackProxyTarget(raw string) bool { + raw = strings.TrimSpace(raw) + if raw == "" { + return false + } + if !strings.Contains(raw, "://") { + raw = "http://" + raw + } + u, err := url.Parse(raw) + if err != nil { + return false + } + h := strings.ToLower(strings.Trim(strings.TrimSpace(u.Hostname()), "[]")) + if h == "localhost" || h == "0.0.0.0" || h == "::" { + return true + } + if ip := net.ParseIP(h); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) { + return true + } + return false +} + +func stripURLCredentials(raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + u, err := url.Parse(raw) + if err != nil { + return raw + } + u.User = nil + return u.String() +} + +// buildSandboxMCPEnv merges MCP-configured env vars with sandbox proxy/CA env +// vars so host-side CA paths (like /app/data/traffic/_ca/mitmproxy-ca-cert.pem) +// never clobber the in-container mounted CA path (/etc/artex/ca.crt). +func buildSandboxMCPEnv(mgr *sandbox.Manager, userEnv map[string]string) []string { + merged := make(map[string]string, len(userEnv)+12) + hostCA := "" + if mgr != nil { + hostCA = strings.TrimSpace(mgr.Config().CACertPath) + } + for k, v := range userEnv { + if isHostCAPathOverride(k, v, hostCA) { + continue + } + merged[k] = v + } + if mgr != nil { + for _, kv := range mgr.ProxyEnv(true) { + if k, v, ok := strings.Cut(kv, "="); ok { + merged[k] = v + } + } + } + keys := make([]string, 0, len(merged)) + for k := range merged { + keys = append(keys, k) + } + sort.Strings(keys) + out := make([]string, 0, len(keys)) + for _, k := range keys { + out = append(out, k+"="+merged[k]) + } + return out +} + +func isHostCAPathOverride(key, val, hostCA string) bool { + switch key { + case "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO": + v := strings.TrimSpace(val) + if v == "" { + return true + } + if hostCA != "" && v == hostCA { + return true + } + // Persisted control-plane paths do not exist inside sandbox containers. + if strings.HasPrefix(v, "/app/data/") || strings.Contains(v, "mitmproxy-ca-cert.pem") { + return true + } + } + return false +} + func (c *stdioMCPClient) readLoop(r io.Reader) { br := bufio.NewReaderSize(r, 64*1024) for { @@ -287,10 +495,16 @@ func (c *stdioMCPClient) Close() error { if c.stdin != nil { _ = c.stdin.Close() } + if c.stream != nil { + _ = c.stream.Close() + } if c.cmd != nil && c.cmd.Process != nil { _ = c.cmd.Process.Kill() _ = c.cmd.Wait() } + if c.releaseSlot != nil { + c.releaseSlot() + } }) return nil } diff --git a/server/orchestration.go b/server/orchestration.go index 7a49fb1..ca22838 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -79,9 +79,16 @@ func (s *Server) orchestrationTools() []actool.CoreTool { s.toolListWorkerTraces(), s.toolSearchWorkerTraces(), s.toolGetTaskNodeDetail(), + s.toolReadTaskFile(), s.toolUpdateFindingReport(), s.toolGetFindingTraffic(), s.toolBindFindingTraffic(), + s.toolListProxyPool(), + s.toolSetTaskProxy(), + s.toolListTaskSchedules(), + s.toolCreateTaskSchedule(), + s.toolUpdateTaskSchedule(), + s.toolDeleteTaskSchedule(), }, s.findingCaseTools()...) } @@ -273,6 +280,10 @@ func (s *Server) toolSpawnTask() actool.CoreTool { "timeout_seconds": map[string]any{"type": "integer", "description": "可选:任务级超时(秒)。到点后触发优雅收尾并进入 timeout 终态;留空或 0 = 不限时"}, "plan_heartbeat_seconds": map[string]any{"type": "integer", "description": "可选:planner 心跳触发间隔(秒)。距上轮规划结束/任务开始满该值且期间无触发 → 触发一轮规划(兜底死锁 + 唤醒去监督飞行中的 worker)。留空或 0 = 默认 600(10min);"}, "seed_first_intent": map[string]any{"type": "boolean", "description": "可选:对于简单任务可开启,创建时直接下发一条种子意图(内容=描述+目标)让 worker 免等首轮 planner 直接开跑测试;默认 false(走标准先规划再执行)。"}, + "attachments": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:要从当前对话工作区附带到新任务工作区(/workspace/uploads/)的文件路径列表,如 [\"uploads/targets.txt\"]。"}, + "proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:任务容器出口代理模式(inherit=继承全局,direct=直连,pool=代理池自动轮换,proxy=指定节点或自定义 URL)"}, + "proxy_pool_id": strParam("可选(proxy_mode=proxy 时):代理池节点 ID 或名称"), + "proxy_url": strParam("可选(proxy_mode=proxy 且未指定 proxy_pool_id 时):自定义代理 URL"), }, "description", "goal"), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { var a struct { @@ -287,8 +298,14 @@ func (s *Server) toolSpawnTask() actool.CoreTool { TimeoutSeconds int `json:"timeout_seconds"` PlanHeartbeatSeconds int `json:"plan_heartbeat_seconds"` SeedFirstIntent bool `json:"seed_first_intent"` + Attachments []string `json:"attachments"` + ProxyMode string `json:"proxy_mode"` + ProxyPoolID string `json:"proxy_pool_id"` + ProxyURL string `json:"proxy_url"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil } - _ = json.Unmarshal(in, &a) if strings.TrimSpace(a.Description) == "" { a.Description = "未命名任务" } @@ -331,6 +348,28 @@ func (s *Server) toolSpawnTask() actool.CoreTool { if pin != nil { llmIDs = []int64{*pin} } + var validatedProxy *ProxyRouteInput + if strings.TrimSpace(a.ProxyMode) != "" || strings.TrimSpace(a.ProxyPoolID) != "" || strings.TrimSpace(a.ProxyURL) != "" { + pm := strings.TrimSpace(a.ProxyMode) + if pm == "" { + pm = "proxy" + } + norm, perr := s.validateAndNormalizeProxyRoute(ProxyRouteInput{ + Mode: pm, + ProxyPoolID: a.ProxyPoolID, + ProxyURL: a.ProxyURL, + }, nil) + if perr != nil { + return actool.Errorf("任务代理配置无效: " + perr.Error()), nil + } + if norm.Mode != "inherit" { + validatedProxy = &ProxyRouteInput{ + Mode: norm.Mode, + ProxyPoolID: norm.ProxyPoolID, + ProxyURL: norm.ProxyURL, + } + } + } name := "" autoTitleEnabled := s.m.pg.GetBool(db.SettingTaskAutoTitle, false) if autoTitleEnabled { @@ -380,6 +419,21 @@ func (s *Server) toolSpawnTask() actool.CoreTool { _ = s.m.PG().SetParentRef(id, a.ParentRef) } } + if sessID := agent.RunInfoFrom(ctx).SessionID; sessID != "" { + newDesc, newGoal, copied := transferSessionAttachmentsToTask(s.m.dir, sessID, t.ID, a.Attachments, a.Description, a.Goal) + if copied > 0 { + a.Description, a.Goal = newDesc, newGoal + t.Description, t.Goal = newDesc, newGoal + if id, e := strconv.ParseInt(t.ID, 10, 64); e == nil && s.m.pg != nil { + _, _ = s.m.pg.Exec(`UPDATE tasks SET description=$2, goal=$3 WHERE id=$1`, id, newDesc, newGoal) + } + } + } + if validatedProxy != nil { + if _, perr := s.setContainerProxyRoute("task", t.ID, *validatedProxy); perr != nil { + log.Printf("[spawn_task] 任务 #%s 应用代理路由失败: %v", t.ID, perr) + } + } // 共享的建后流程,与 HTTP 建任务(server.go createTask)复用同一段 launchTask: // seed + 后台可见地做目标分解(第0轮/LLM步骤/逐条goal) + engine.Run。 // seed_first_intent 默认 false(标准先规划再执行);简单任务可开启直接下发一 work 测试。 @@ -618,6 +672,10 @@ func defaultOrchestrationToolBindings(name string) json.RawMessage { switch { case name == "resume_task": return json.RawMessage(`["auto","mainagent"]`) + case name == "list_proxy_pool" || name == "set_task_proxy" || + name == "list_task_schedules" || name == "create_task_schedule" || + name == "update_task_schedule" || name == "delete_task_schedule": + return json.RawMessage(`["auto","mainagent","pentest"]`) case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records": return json.RawMessage(`["reporter"]`) default: @@ -640,6 +698,8 @@ func (s *Server) seedOrchestrationTools() { s.refreshBuiltinToolSchemas() s.seedAutoDefaultBindings() s.seedTaskReopenBindings() + s.seedProxyToolBindings() + s.seedScheduleToolBindings() s.seedPlannerDefaultBindings() s.seedPlannerListAssetsBinding() s.seedCompanyScopeRebind() @@ -731,7 +791,7 @@ func (s *Server) migrateReporterWorkflow() { // reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag. // Bump the flag whenever these tools' schemas/descriptions change in code. func (s *Server) refreshBuiltinToolSchemas() { - const flag = "tool_schema_refresh_v9_task_reopen_tools" + const flag = "tool_schema_refresh_v11_schedule_tools" if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { return } @@ -1144,11 +1204,11 @@ func (s *Server) seedWorkerReadbackRebind() { // before Auto existed still give Auto its default toolset — without re-adding it // after a user deliberately unbinds. func (s *Server) seedAutoDefaultBindings() { - const flag = "auto_default_bindings_v3" // v3: 替换旧资产工具名,加入 insert_assets/add_company_scope + const flag = "auto_default_bindings_v4" // v4: 加入 read_task_file 只读跨容器产物查看工具 if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { return } - keys := make([]string, 0, len(platformToolKeys)+12) + keys := make([]string, 0, len(platformToolKeys)+13) for _, t := range s.orchestrationTools() { keys = append(keys, t.Name()) } diff --git a/server/orchestration_test.go b/server/orchestration_test.go new file mode 100644 index 0000000..30c55d9 --- /dev/null +++ b/server/orchestration_test.go @@ -0,0 +1,47 @@ +package server + +import ( + "context" + "encoding/json" + "strings" + "testing" +) + +func TestToolSpawnTaskUnmarshalsInput(t *testing.T) { + s := &Server{m: &Manager{tasks: map[string]*Task{}}} + tool := s.toolSpawnTask() + + t.Run("missing goal rejected", func(t *testing.T) { + res, err := tool.Call(context.Background(), json.RawMessage(`{"description":"端口探测"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError || !strings.Contains(res.Flatten(), "goal 为必填") { + t.Fatalf("expected goal required error, got isError=%v text=%q", res.IsError, res.Flatten()) + } + }) + + t.Run("invalid json rejected", func(t *testing.T) { + res, err := tool.Call(context.Background(), json.RawMessage(`{invalid`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError || !strings.Contains(res.Flatten(), "参数无效") { + t.Fatalf("expected invalid json error, got isError=%v text=%q", res.IsError, res.Flatten()) + } + }) + + t.Run("valid goal parsed past required check", func(t *testing.T) { + res, err := tool.Call(context.Background(), json.RawMessage(`{ + "description": "47.116.200.74 端口探测", + "goal": "仅对 47.116.200.74 做端口探测", + "source_task_ids": ["99999"] + }`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError || !strings.Contains(res.Flatten(), "关联任务 #99999 不存在") { + t.Fatalf("expected source_task_ids check after parsing goal, got isError=%v text=%q", res.IsError, res.Flatten()) + } + }) +} diff --git a/server/proxy_pool.go b/server/proxy_pool.go index b65f640..4a20add 100644 --- a/server/proxy_pool.go +++ b/server/proxy_pool.go @@ -259,6 +259,34 @@ func (m *Manager) proxyPoolEntries() []proxyPoolEntry { return append([]proxyPoolEntry(nil), m.proxyPool.entries...) } +// ActivePoolRawURL returns the active (or first available enabled) proxy pool entry ID and raw URL. +func (m *Manager) ActivePoolRawURL() (string, string) { + if m == nil || m.proxyPool == nil { + return "", "" + } + m.proxyPool.mu.Lock() + defer m.proxyPool.mu.Unlock() + if len(m.proxyPool.entries) == 0 { + return "", "" + } + for _, e := range m.proxyPool.entries { + if e.ID == m.proxyPool.active && e.Enabled && strings.TrimSpace(e.RawURL) != "" { + return e.ID, strings.TrimSpace(e.RawURL) + } + } + for _, e := range m.proxyPool.entries { + if e.Enabled && e.Health != "unhealthy-cooling" && strings.TrimSpace(e.RawURL) != "" { + return e.ID, strings.TrimSpace(e.RawURL) + } + } + for _, e := range m.proxyPool.entries { + if e.Enabled && strings.TrimSpace(e.RawURL) != "" { + return e.ID, strings.TrimSpace(e.RawURL) + } + } + return "", "" +} + func (m *Manager) setProxyPoolEntries(entries []proxyPoolEntry, active string) error { if m.proxyPool == nil { m.proxyPool = &proxyPoolState{} diff --git a/server/proxy_routes.go b/server/proxy_routes.go new file mode 100644 index 0000000..be6445b --- /dev/null +++ b/server/proxy_routes.go @@ -0,0 +1,636 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + "sync" + "time" + + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" +) + +const ( + settingContainerProxyRoutes = "proxy_container_routes_json" + settingGatewayPolicy = "proxy_gateway_settings_json" +) + +// ContainerProxyRoute persists a per-sandbox-owner upstream proxy override (#218 Phase 4). +type ContainerProxyRoute struct { + Scope string `json:"scope"` // task, session + OwnerID string `json:"owner_id"` // task ID or session ID + Mode string `json:"mode"` // inherit, direct, pool, proxy + ProxyPoolID string `json:"proxy_pool_id,omitempty"` // optional proxy pool entry ID + ProxyURL string `json:"proxy_url,omitempty"` // raw custom URL in storage; masked in API output + Note string `json:"note,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// ProxyRouteInput is the shared request payload for setting a container/task/schedule proxy route. +type ProxyRouteInput struct { + Mode string `json:"mode"` + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` + Note string `json:"note,omitempty"` +} + +// GatewaySettings persists transparent gateway runtime policy knobs. +type GatewaySettings struct { + UDPPolicy string `json:"udp_policy"` + DNSUpstream string `json:"dns_upstream"` + StoreErrorTraffic bool `json:"store_error_traffic"` +} + +type proxyRouteRuntime struct { + mu sync.RWMutex + routes map[string]ContainerProxyRoute // key: "scope:owner_id" + gwSettings GatewaySettings + gwID string + gwLastSeen time.Time + embeddedGW *traffic.TransparentGateway +} + +func (s *Server) ensureRouteRuntime() *proxyRouteRuntime { + s.cfgMu.Lock() + defer s.cfgMu.Unlock() + if s.proxyRoutes == nil { + s.proxyRoutes = &proxyRouteRuntime{ + routes: map[string]ContainerProxyRoute{}, + gwSettings: GatewaySettings{ + UDPPolicy: traffic.UDPPolicyBlockOnProxy, + }, + } + } + return s.proxyRoutes +} + +func (s *Server) initProxyRoutesAndGateway() { + rt := s.ensureRouteRuntime() + // Load persisted per-container proxy routes. + if s.m.pg != nil { + if raw, ok, err := s.m.pg.GetSetting(settingContainerProxyRoutes); err == nil && ok && strings.TrimSpace(raw) != "" { + var list []ContainerProxyRoute + if json.Unmarshal([]byte(raw), &list) == nil { + rt.mu.Lock() + for _, r := range list { + if r.Scope != "" && r.OwnerID != "" { + rt.routes[r.Scope+":"+r.OwnerID] = r + } + } + rt.mu.Unlock() + } + } + if raw, ok, err := s.m.pg.GetSetting(settingGatewayPolicy); err == nil && ok && strings.TrimSpace(raw) != "" { + var gs GatewaySettings + if json.Unmarshal([]byte(raw), &gs) == nil { + gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy) + gs.DNSUpstream = strings.TrimSpace(gs.DNSUpstream) + rt.mu.Lock() + rt.gwSettings = gs + rt.mu.Unlock() + } + } + } + + if s.m.traffic != nil { + rt.mu.RLock() + gs := rt.gwSettings + rt.mu.RUnlock() + s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream) + s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic) + s.m.traffic.SetUpstreamResolver(s.resolveContainerUpstream) + } +} + +func (s *Server) storeErrorTrafficEnabled() bool { + rt := s.ensureRouteRuntime() + rt.mu.RLock() + defer rt.mu.RUnlock() + return rt.gwSettings.StoreErrorTraffic +} + +func (s *Server) resolvePoolEntryByIDOrName(ref string) (string, string) { + ref = strings.TrimSpace(ref) + if ref == "" { + return "", "" + } + entries := s.m.proxyPoolEntries() + for _, e := range entries { + if e.ID == ref { + return e.ID, strings.TrimSpace(e.RawURL) + } + } + for _, e := range entries { + if name := strings.TrimSpace(e.Name); name != "" && strings.EqualFold(name, ref) { + return e.ID, strings.TrimSpace(e.RawURL) + } + } + return "", "" +} + +func (s *Server) resolvePoolEntryRawURL(poolID string) string { + _, raw := s.resolvePoolEntryByIDOrName(poolID) + return raw +} + +func (s *Server) resolveRouteEffectiveRawURL(r ContainerProxyRoute) string { + switch strings.ToLower(strings.TrimSpace(r.Mode)) { + case "pool": + _, raw := s.m.ActivePoolRawURL() + return raw + case "proxy": + if r.ProxyPoolID != "" { + if raw := s.resolvePoolEntryRawURL(r.ProxyPoolID); raw != "" { + return raw + } + } + return strings.TrimSpace(r.ProxyURL) + default: + return "" + } +} + +func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, bool) { + if src.Scope == "" || src.OwnerID == "" { + return nil, false + } + rt := s.ensureRouteRuntime() + rt.mu.RLock() + r, ok := rt.routes[src.Scope+":"+src.OwnerID] + rt.mu.RUnlock() + if !ok { + return nil, false + } + switch strings.ToLower(strings.TrimSpace(r.Mode)) { + case "direct": + return nil, true + case "pool", "proxy": + raw := s.resolveRouteEffectiveRawURL(r) + if raw == "" { + return nil, false + } + u, err := traffic.ValidateProxyURL(raw) + if err != nil { + return nil, false + } + return u, true + default: + return nil, false + } +} + +type proxyRouteValidationError struct { + code string + msg string + params map[string]any +} + +func (e *proxyRouteValidationError) Error() string { return e.msg } + +func writeProxyRouteErr(w http.ResponseWriter, status int, err error) { + if verr, ok := err.(*proxyRouteValidationError); ok && verr.code != "" { + writeProductError(w, status, verr.code, verr.msg, verr.params) + return + } + writeErr(w, status, err.Error()) +} +func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *ContainerProxyRoute) (ContainerProxyRoute, error) { + mode := strings.ToLower(strings.TrimSpace(req.Mode)) + if mode == "" { + mode = "inherit" + } + if mode != "inherit" && mode != "direct" && mode != "pool" && mode != "proxy" { + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_mode", + msg: "mode must be inherit, direct, pool, or proxy", + } + } + route := ContainerProxyRoute{ + Mode: mode, + ProxyPoolID: strings.TrimSpace(req.ProxyPoolID), + ProxyURL: strings.TrimSpace(req.ProxyURL), + Note: strings.TrimSpace(req.Note), + UpdatedAt: time.Now().UTC().Format(time.RFC3339), + } + switch mode { + case "inherit", "direct": + route.ProxyPoolID = "" + route.ProxyURL = "" + case "pool": + if _, raw := s.m.ActivePoolRawURL(); raw == "" { + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_pool_no_available_nodes", + msg: "代理池暂无可用节点,请先在代理设置中添加并启用节点", + } + } + route.ProxyPoolID = "" + route.ProxyURL = "" + case "proxy": + if route.ProxyPoolID != "" { + id, raw := s.resolvePoolEntryByIDOrName(route.ProxyPoolID) + if raw == "" { + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_pool_node_not_found", + msg: fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID), + params: map[string]any{"id": route.ProxyPoolID}, + } + } + route.ProxyPoolID = id + route.ProxyURL = "" + } else { + // If user left masked placeholder unchanged, preserve existing raw URL. + if strings.Contains(route.ProxyURL, "***") && prev != nil && prev.ProxyURL != "" { + route.ProxyURL = prev.ProxyURL + } + if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil { + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_url", + msg: err.Error(), + params: map[string]any{"detail": err.Error()}, + } + } + } + } + return route, nil +} + +func (s *Server) setContainerProxyRoute(scope, ownerID string, req ProxyRouteInput) (ContainerProxyRoute, error) { + scope = strings.ToLower(strings.TrimSpace(scope)) + ownerID = strings.TrimSpace(ownerID) + if (scope != "task" && scope != "session") || ownerID == "" { + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_target", + msg: "invalid scope or owner_id (scope must be task or session)", + } + } + rt := s.ensureRouteRuntime() + key := scope + ":" + ownerID + rt.mu.RLock() + var prevPtr *ContainerProxyRoute + if prev, ok := rt.routes[key]; ok { + cp := prev + prevPtr = &cp + } + rt.mu.RUnlock() + + route, err := s.validateAndNormalizeProxyRoute(req, prevPtr) + if err != nil { + return ContainerProxyRoute{}, err + } + route.Scope = scope + route.OwnerID = ownerID + + if route.Mode == "inherit" { + rt.mu.Lock() + delete(rt.routes, key) + err := s.saveContainerProxyRoutesLocked(rt) + rt.mu.Unlock() + if err != nil { + return ContainerProxyRoute{}, err + } + return ContainerProxyRoute{Scope: scope, OwnerID: ownerID, Mode: "inherit"}, nil + } + + rt.mu.Lock() + rt.routes[key] = route + err = s.saveContainerProxyRoutesLocked(rt) + rt.mu.Unlock() + if err != nil { + return ContainerProxyRoute{}, err + } + return s.maskedRouteView(route), nil +} + +func (s *Server) effectiveProxyDisplay(route *ContainerProxyRoute) (effective string, globalDisplay string) { + globalRaw := strings.TrimSpace(s.m.GlobalProxy()) + globalDisplay = "direct" + if globalRaw != "" { + globalDisplay = maskSecrets(globalRaw) + } + if route == nil || route.Mode == "" || route.Mode == "inherit" { + return globalDisplay, globalDisplay + } + if route.Mode == "direct" { + return "direct", globalDisplay + } + if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" { + return maskSecrets(raw), globalDisplay + } + if route.Mode == "pool" { + return "direct", globalDisplay + } + return globalDisplay, globalDisplay +} + +func (s *Server) containerProxyRouteView(scope, ownerID string) (containerRouteStatusItem, string) { + scope = strings.ToLower(strings.TrimSpace(scope)) + ownerID = strings.TrimSpace(ownerID) + rt := s.ensureRouteRuntime() + rt.mu.RLock() + existing, ok := rt.routes[scope+":"+ownerID] + rt.mu.RUnlock() + item := containerRouteStatusItem{ + Scope: scope, + OwnerID: ownerID, + Mode: "inherit", + } + var rPtr *ContainerProxyRoute + if ok { + cp := existing + rPtr = &cp + item.Mode = existing.Mode + item.ProxyPoolID = existing.ProxyPoolID + item.ProxyURL = maskSecrets(existing.ProxyURL) + item.Note = existing.Note + item.UpdatedAt = existing.UpdatedAt + } + eff, globalDisplay := s.effectiveProxyDisplay(rPtr) + item.EffectiveProxy = eff + return item, globalDisplay +} + +func (s *Server) saveContainerProxyRoutesLocked(rt *proxyRouteRuntime) error { + if s.m.pg == nil { + return nil + } + list := make([]ContainerProxyRoute, 0, len(rt.routes)) + for _, r := range rt.routes { + list = append(list, r) + } + sort.Slice(list, func(i, j int) bool { + if list[i].Scope != list[j].Scope { + return list[i].Scope < list[j].Scope + } + return list[i].OwnerID < list[j].OwnerID + }) + b, err := json.Marshal(list) + if err != nil { + return err + } + return s.m.pg.SetSetting(settingContainerProxyRoutes, string(b)) +} + +func (s *Server) maskedRouteView(r ContainerProxyRoute) ContainerProxyRoute { + out := r + if out.ProxyURL != "" { + out.ProxyURL = maskSecrets(out.ProxyURL) + } + return out +} + +type containerRouteStatusItem struct { + Scope string `json:"scope"` + OwnerID string `json:"owner_id"` + ContainerName string `json:"container_name,omitempty"` + ContainerID string `json:"container_id,omitempty"` + State string `json:"state,omitempty"` + IP string `json:"ip,omitempty"` + Mode string `json:"mode"` // inherit, direct, pool, proxy + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` + EffectiveProxy string `json:"effective_proxy"` + Note string `json:"note,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// GET /api/proxy/routes +func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) { + rt := s.ensureRouteRuntime() + rt.mu.RLock() + routesMap := make(map[string]ContainerProxyRoute, len(rt.routes)) + for k, v := range rt.routes { + routesMap[k] = v + } + gs := rt.gwSettings + gwID := rt.gwID + gwLast := rt.gwLastSeen + embedded := rt.embeddedGW != nil + rt.mu.RUnlock() + + globalRaw := strings.TrimSpace(s.m.GlobalProxy()) + globalDisplay := "direct" + if globalRaw != "" { + globalDisplay = maskSecrets(globalRaw) + } + + effectiveFor := func(route *ContainerProxyRoute) string { + if route == nil || route.Mode == "" || route.Mode == "inherit" { + return globalDisplay + } + if route.Mode == "direct" { + return "direct" + } + if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" { + return maskSecrets(raw) + } + return globalDisplay + } + + seen := map[string]bool{} + items := make([]containerRouteStatusItem, 0, len(routesMap)+4) + + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + st := mgr.StatusWithStats(ctx, false) + cancel() + ipSnap := mgr.ContainerIPSnapshot() + ipByName := map[string]string{} + for ip, id := range ipSnap { + ipByName[id.ContainerName] = ip + } + for _, c := range st.Containers { + key := string(c.Scope) + ":" + c.OwnerID + seen[key] = true + var rPtr *ContainerProxyRoute + mode := "inherit" + var poolID, proxyURL, note, updatedAt string + if existing, ok := routesMap[key]; ok { + cp := existing + rPtr = &cp + mode = existing.Mode + poolID = existing.ProxyPoolID + proxyURL = maskSecrets(existing.ProxyURL) + note = existing.Note + updatedAt = existing.UpdatedAt + } + items = append(items, containerRouteStatusItem{ + Scope: string(c.Scope), + OwnerID: c.OwnerID, + ContainerName: c.Name, + ContainerID: c.ShortID, + State: c.State, + IP: ipByName[c.Name], + Mode: mode, + ProxyPoolID: poolID, + ProxyURL: proxyURL, + EffectiveProxy: effectiveFor(rPtr), + Note: note, + UpdatedAt: updatedAt, + }) + } + } + + // Include persisted route rules for tasks/sessions without a currently present container. + for key, route := range routesMap { + if seen[key] { + continue + } + cp := route + items = append(items, containerRouteStatusItem{ + Scope: route.Scope, + OwnerID: route.OwnerID, + State: "inactive", + Mode: route.Mode, + ProxyPoolID: route.ProxyPoolID, + ProxyURL: maskSecrets(route.ProxyURL), + EffectiveProxy: effectiveFor(&cp), + Note: route.Note, + UpdatedAt: route.UpdatedAt, + }) + } + sort.Slice(items, func(i, j int) bool { + if items[i].Scope != items[j].Scope { + return items[i].Scope < items[j].Scope + } + return items[i].OwnerID < items[j].OwnerID + }) + + routesList := make([]ContainerProxyRoute, 0, len(routesMap)) + for _, route := range routesMap { + routesList = append(routesList, s.maskedRouteView(route)) + } + sort.Slice(routesList, func(i, j int) bool { + if routesList[i].Scope != routesList[j].Scope { + return routesList[i].Scope < routesList[j].Scope + } + return routesList[i].OwnerID < routesList[j].OwnerID + }) + + connected := embedded || (!gwLast.IsZero() && time.Since(gwLast) < 15*time.Second) + var lastSeenStr string + if !gwLast.IsZero() { + lastSeenStr = gwLast.UTC().Format(time.RFC3339) + } + + writeJSON(w, 200, map[string]any{ + "global_proxy": globalDisplay, + "routes": routesList, + "containers": items, + "gateway": map[string]any{ + "connected": connected, + "embedded": embedded, + "gateway_id": gwID, + "last_seen": lastSeenStr, + "udp_policy": traffic.NormalizeUDPPolicy(gs.UDPPolicy), + "dns_upstream": gs.DNSUpstream, + "store_error_traffic": gs.StoreErrorTraffic, + }, + }) +} + +// GET /api/proxy/routes/{scope}/{owner_id} +func (s *Server) getProxyRoute(w http.ResponseWriter, r *http.Request) { + scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope"))) + ownerID := strings.TrimSpace(r.PathValue("owner_id")) + if (scope != "task" && scope != "session") || ownerID == "" { + writeProductError(w, http.StatusBadRequest, "proxy_route_invalid_target", "invalid scope or owner_id (scope must be task or session)", nil) + return + } + item, globalDisplay := s.containerProxyRouteView(scope, ownerID) + writeJSON(w, 200, map[string]any{ + "scope": item.Scope, + "owner_id": item.OwnerID, + "mode": item.Mode, + "proxy_pool_id": item.ProxyPoolID, + "proxy_url": item.ProxyURL, + "effective_proxy": item.EffectiveProxy, + "global_proxy": globalDisplay, + "note": item.Note, + "updated_at": item.UpdatedAt, + }) +} + +// PUT /api/proxy/routes/{scope}/{owner_id} +func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) { + scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope"))) + ownerID := strings.TrimSpace(r.PathValue("owner_id")) + var req ProxyRouteInput + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeErr(w, http.StatusBadRequest, "invalid JSON body") + return + } + route, err := s.setContainerProxyRoute(scope, ownerID, req) + if err != nil { + if _, ok := err.(*proxyRouteValidationError); ok { + writeProxyRouteErr(w, http.StatusBadRequest, err) + return + } + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, 200, route) +} + +// DELETE /api/proxy/routes/{scope}/{owner_id} +func (s *Server) deleteProxyRoute(w http.ResponseWriter, r *http.Request) { + scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope"))) + ownerID := strings.TrimSpace(r.PathValue("owner_id")) + if scope == "" || ownerID == "" { + writeErr(w, http.StatusBadRequest, "missing scope or owner_id") + return + } + rt := s.ensureRouteRuntime() + rt.mu.Lock() + delete(rt.routes, scope+":"+ownerID) + err := s.saveContainerProxyRoutesLocked(rt) + rt.mu.Unlock() + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"deleted": scope + ":" + ownerID}) +} + +// PUT /api/proxy/gateway/settings +func (s *Server) updateGatewaySettings(w http.ResponseWriter, r *http.Request) { + var req struct { + UDPPolicy *string `json:"udp_policy"` + DNSUpstream *string `json:"dns_upstream"` + StoreErrorTraffic *bool `json:"store_error_traffic"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeErr(w, http.StatusBadRequest, "invalid JSON body") + return + } + rt := s.ensureRouteRuntime() + rt.mu.Lock() + gs := rt.gwSettings + if req.UDPPolicy != nil { + gs.UDPPolicy = traffic.NormalizeUDPPolicy(*req.UDPPolicy) + } else { + gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy) + } + if req.DNSUpstream != nil { + gs.DNSUpstream = strings.TrimSpace(*req.DNSUpstream) + } + if req.StoreErrorTraffic != nil { + gs.StoreErrorTraffic = *req.StoreErrorTraffic + } + rt.gwSettings = gs + rt.mu.Unlock() + if s.m.pg != nil { + if b, err := json.Marshal(gs); err == nil { + _ = s.m.pg.SetSetting(settingGatewayPolicy, string(b)) + } + } + if s.m.traffic != nil { + s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream) + s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic) + } + writeJSON(w, 200, gs) +} diff --git a/server/proxy_routes_feature_test.go b/server/proxy_routes_feature_test.go new file mode 100644 index 0000000..7d65c05 --- /dev/null +++ b/server/proxy_routes_feature_test.go @@ -0,0 +1,496 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "time" + "os" + "strconv" + + "github.com/Autumn-27/artex/db" + "sync/atomic" + "testing" + + "github.com/Autumn-27/artex/traffic" +) + +func TestContainerProxyPoolModeAndRotation(t *testing.T) { + t.Setenv("ARTEX_GATEWAY_TOKEN", "gw-tok-pool-test") + + m := &Manager{ + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{ + active: "node-a", + entries: []proxyPoolEntry{ + { + ProxyPoolEntry: ProxyPoolEntry{ID: "node-a", Name: "HK-1", URL: "http://127.0.0.1:18081", Enabled: true, Health: "healthy"}, + RawURL: "http://127.0.0.1:18081", + }, + { + ProxyPoolEntry: ProxyPoolEntry{ID: "node-b", Name: "SG-2", URL: "http://127.0.0.1:18082", Enabled: true, Health: "healthy"}, + RawURL: "http://127.0.0.1:18082", + }, + }, + }, + globalProxy: "http://127.0.0.1:18081", + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + // 1. Set task:5 to mode=pool. + req := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(`{"mode":"pool"}`)) + req.SetPathValue("scope", "task") + req.SetPathValue("owner_id", "5") + rec := httptest.NewRecorder() + s.putProxyRoute(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("putProxyRoute pool failed: %d %s", rec.Code, rec.Body.String()) + } + + // 2. Pin session:conv-9 to node-a by name. + reqPin := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/session/conv-9", bytes.NewBufferString(`{"mode":"proxy","proxy_pool_id":"HK-1"}`)) + reqPin.SetPathValue("scope", "session") + reqPin.SetPathValue("owner_id", "conv-9") + recPin := httptest.NewRecorder() + s.putProxyRoute(recPin, reqPin) + if recPin.Code != http.StatusOK { + t.Fatalf("putProxyRoute pin failed: %d %s", recPin.Code, recPin.Body.String()) + } + + // 3. Force task:8 direct. + reqDir := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/8", bytes.NewBufferString(`{"mode":"direct"}`)) + reqDir.SetPathValue("scope", "task") + reqDir.SetPathValue("owner_id", "8") + recDir := httptest.NewRecorder() + s.putProxyRoute(recDir, reqDir) + if recDir.Code != http.StatusOK { + t.Fatalf("putProxyRoute direct failed: %d %s", recDir.Code, recDir.Body.String()) + } + + fetchSnap := func() traffic.GatewayPolicySnapshot { + polReq := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-1", nil) + polReq.Header.Set("X-Artex-Gateway-Token", "gw-tok-pool-test") + polRec := httptest.NewRecorder() + s.getGatewayPolicy(polRec, polReq) + if polRec.Code != http.StatusOK { + t.Fatalf("getGatewayPolicy: %d %s", polRec.Code, polRec.Body.String()) + } + var snap traffic.GatewayPolicySnapshot + if err := json.Unmarshal(polRec.Body.Bytes(), &snap); err != nil { + t.Fatalf("unmarshal snapshot: %v", err) + } + return snap + } + + state := traffic.NewRemotePolicyState("gw-tok-pool-test", nil, nil, nil) + state.Apply(fetchSnap()) + + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "5"}); u == nil || u.String() != "http://127.0.0.1:18081" { + t.Fatalf("expected task:5 pool -> node-a, got %v", u) + } + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "session", OwnerID: "conv-9"}); u == nil || u.String() != "http://127.0.0.1:18081" { + t.Fatalf("expected session:conv-9 pin -> node-a, got %v", u) + } + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "8"}); u != nil { + t.Fatalf("expected task:8 direct -> nil, got %v", u) + } + + // 4. Rotate proxy pool active entry to node-b. + m.proxyPool.mu.Lock() + m.proxyPool.active = "node-b" + m.proxyPool.mu.Unlock() + m.mu.Lock() + m.globalProxy = "http://127.0.0.1:18082" + m.mu.Unlock() + + state.Apply(fetchSnap()) + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "5"}); u == nil || u.String() != "http://127.0.0.1:18082" { + t.Fatalf("expected task:5 pool to follow rotation to node-b, got %v", u) + } + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "session", OwnerID: "conv-9"}); u == nil || u.String() != "http://127.0.0.1:18081" { + t.Fatalf("expected session:conv-9 pin to stay on node-a after rotation, got %v", u) + } + if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "8"}); u != nil { + t.Fatalf("expected task:8 direct to stay direct after rotation, got %v", u) + } + + // 5. Verify GET /api/proxy/routes/{scope}/{owner_id} reflects rotated effective proxy. + getReq := httptest.NewRequest(http.MethodGet, "/api/proxy/routes/task/5", nil) + getReq.SetPathValue("scope", "task") + getReq.SetPathValue("owner_id", "5") + getRec := httptest.NewRecorder() + s.getProxyRoute(getRec, getReq) + if getRec.Code != http.StatusOK { + t.Fatalf("getProxyRoute failed: %d %s", getRec.Code, getRec.Body.String()) + } + var view map[string]any + if err := json.Unmarshal(getRec.Body.Bytes(), &view); err != nil { + t.Fatalf("decode getProxyRoute: %v", err) + } + if view["mode"] != "pool" || view["effective_proxy"] != "http://127.0.0.1:18082" { + t.Fatalf("unexpected getProxyRoute view: %+v", view) + } +} + +func TestChatProxyToolsListAndSetTaskProxy(t *testing.T) { + m := &Manager{ + tasks: map[string]*Task{ + "12": {ID: "12", Name: "Demo Task"}, + }, + proxyPool: &proxyPoolState{ + active: "p1", + entries: []proxyPoolEntry{ + { + ProxyPoolEntry: ProxyPoolEntry{ID: "p1", Name: "JP-Node", URL: "socks5://127.0.0.1:1081", Enabled: true, Health: "healthy"}, + RawURL: "socks5://127.0.0.1:1081", + }, + }, + }, + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + setTool := s.toolSetTaskProxy() + res, err := setTool.Call(context.Background(), json.RawMessage(`{"task_id":12,"mode":"pool","note":"chat requested"}`), nil) + if err != nil || res.IsError { + t.Fatalf("set_task_proxy pool failed: err=%v res=%+v", err, res) + } + text1 := "" + for _, b := range res.Content { + text1 += b.Text + } + if !strings.Contains(text1, `"mode":"pool"`) || !strings.Contains(text1, `socks5://127.0.0.1:1081`) { + t.Fatalf("unexpected set_task_proxy output: %s", text1) + } + + // Pin by node Name instead of ID. + res, err = setTool.Call(context.Background(), json.RawMessage(`{"task_id":"12","mode":"proxy","proxy_pool_id":"JP-Node"}`), nil) + if err != nil || res.IsError { + t.Fatalf("set_task_proxy by name failed: err=%v res=%+v", err, res) + } + text2 := "" + for _, b := range res.Content { + text2 += b.Text + } + if !strings.Contains(text2, `"proxy_pool_id":"p1"`) { + t.Fatalf("expected canonical pool id p1, got: %s", text2) + } + + listTool := s.toolListProxyPool() + listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil) + if err != nil || listRes.IsError { + t.Fatalf("list_proxy_pool failed: err=%v res=%+v", err, listRes) + } + text3 := "" + for _, b := range listRes.Content { + text3 += b.Text + } + if !strings.Contains(text3, `"JP-Node"`) || !strings.Contains(text3, `"owner_id":"12"`) { + t.Fatalf("unexpected list_proxy_pool output: %s", text3) + } + + // Non-existent task must error. + badRes, err := setTool.Call(context.Background(), json.RawMessage(`{"task_id":"999","mode":"direct"}`), nil) + if err != nil || !badRes.IsError { + t.Fatalf("expected error for missing task, got err=%v res=%+v", err, badRes) + } +} + +func TestChatMentionTaskParsing(t *testing.T) { + refs, err := parseChatMentions("请给 @[任务#5 官网渗透] 和 @[task#5 重复] 以及 @[task#19 API审计] 设置代理池") + if err != nil { + t.Fatalf("parseChatMentions error: %v", err) + } + if len(refs) != 2 || refs[0].Kind != "task" || refs[0].ID != 5 || refs[1].Kind != "task" || refs[1].ID != 19 { + t.Fatalf("unexpected task mention refs: %+v", refs) + } +} + +func TestRealHTTPProxyRoutingPerContainer(t *testing.T) { + var targetHits, proxyAHits, proxyBHits atomic.Int32 + + targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + targetHits.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("DIRECT_ORIGIN")) + })) + defer targetSrv.Close() + + makeProxy := func(tag string, counter *atomic.Int32) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + counter.Add(1) + if r.Method == http.MethodConnect { + hj, ok := w.(http.Hijacker) + if !ok { + http.Error(w, "hijack unsupported", 500) + return + } + conn, _, err := hj.Hijack() + if err != nil { + return + } + defer conn.Close() + _, _ = conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) + buf := make([]byte, 4096) + _, _ = conn.Read(buf) + body := "VIA_" + tag + _, _ = fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("VIA_" + tag)) + })) + } + proxyA := makeProxy("PROXY_A", &proxyAHits) + defer proxyA.Close() + proxyB := makeProxy("PROXY_B", &proxyBHits) + defer proxyB.Close() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("alloc free port: %v", err) + } + proxyAddr := ln.Addr().String() + _ = ln.Close() + + tr, err := traffic.Open(t.TempDir(), proxyAddr) + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + go func() { _ = tr.Start() }() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if c, derr := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond); derr == nil { + _ = c.Close() + break + } + time.Sleep(25 * time.Millisecond) + } + + m := &Manager{ + traffic: tr, + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{ + active: "pa", + entries: []proxyPoolEntry{ + {ProxyPoolEntry: ProxyPoolEntry{ID: "pa", Name: "A", URL: proxyA.URL, Enabled: true, Health: "healthy"}, RawURL: proxyA.URL}, + {ProxyPoolEntry: ProxyPoolEntry{ID: "pb", Name: "B", URL: proxyB.URL, Enabled: true, Health: "healthy"}, RawURL: proxyB.URL}, + }, + }, + globalProxy: proxyA.URL, + } + _ = tr.SetUpstreamProxy(proxyA.URL) + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + if _, err := s.setContainerProxyRoute("task", "1", ProxyRouteInput{Mode: "pool"}); err != nil { + t.Fatalf("set task 1 pool: %v", err) + } + if _, err := s.setContainerProxyRoute("task", "2", ProxyRouteInput{Mode: "proxy", ProxyPoolID: "pb"}); err != nil { + t.Fatalf("set task 2 pb: %v", err) + } + if _, err := s.setContainerProxyRoute("task", "3", ProxyRouteInput{Mode: "direct"}); err != nil { + t.Fatalf("set task 3 direct: %v", err) + } + + callAsTask := func(taskID string) string { + t.Helper() + tagged := traffic.FormatProxyContextURL("http://"+proxyAddr, traffic.SourceIdentity{Scope: "task", OwnerID: taskID}) + pu, err := url.Parse(tagged) + if err != nil { + t.Fatalf("parse tagged proxy url: %v", err) + } + client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}} + defer client.CloseIdleConnections() + resp, err := client.Get(targetSrv.URL + "/check") + if err != nil { + t.Fatalf("request as task %s failed: %v", taskID, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return string(body) + } + + if got := callAsTask("1"); got != "VIA_PROXY_A" { + t.Fatalf("task 1 (pool active=pa) expected VIA_PROXY_A, got %q", got) + } + if got := callAsTask("2"); got != "VIA_PROXY_B" { + t.Fatalf("task 2 (pinned pb) expected VIA_PROXY_B, got %q", got) + } + if got := callAsTask("3"); got != "DIRECT_ORIGIN" { + t.Fatalf("task 3 (direct) expected DIRECT_ORIGIN, got %q", got) + } + + // Rotate pool active to pb and re-verify task 1 follows the rotation! + m.proxyPool.mu.Lock() + m.proxyPool.active = "pb" + m.proxyPool.mu.Unlock() + if got := callAsTask("1"); got != "VIA_PROXY_B" { + t.Fatalf("task 1 (pool rotated to pb) expected VIA_PROXY_B, got %q", got) + } + if proxyAHits.Load() == 0 || proxyBHits.Load() < 2 || targetHits.Load() == 0 { + t.Fatalf("unexpected hit counts: proxyA=%d proxyB=%d direct=%d", proxyAHits.Load(), proxyBHits.Load(), targetHits.Load()) + } +} + +func TestProxyScheduleAndTaskMentionWithPostgres(t *testing.T) { + dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) + if dsn == "" { + t.Skip("requires ARTEX_PG_DSN") + } + pg, err := db.Open(dsn) + if err != nil { + t.Fatalf("open pg: %v", err) + } + defer pg.Close() + + m := &Manager{ + pg: pg, + dir: t.TempDir(), + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{ + active: "pg-node-1", + entries: []proxyPoolEntry{ + { + ProxyPoolEntry: ProxyPoolEntry{ID: "pg-node-1", Name: "PG-Node-1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"}, + RawURL: "http://127.0.0.1:19801", + }, + }, + }, + globalProxy: "http://127.0.0.1:19801", + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + task, err := m.CreateTask("proxy-e2e-task", "verify proxy schedule and mention", nil, 0, 0) + if err != nil { + t.Fatalf("CreateTask: %v", err) + } + taskID, _ := strconv.ParseInt(task.ID, 10, 64) + + // 1. Create schedule with custom authenticated proxy URL -> applied to bound task & masked in response. + body := fmt.Sprintf(`{"name":"proxy-sched","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"09:00","proxy_mode":"proxy","proxy_url":"http://alice:topsecret@127.0.0.1:19802","task_ids":[%d]}`, taskID) + req := httptest.NewRequest(http.MethodPost, "/api/schedules", bytes.NewBufferString(body)) + rec := httptest.NewRecorder() + s.createSchedule(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("createSchedule failed: %d %s", rec.Code, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "topsecret") { + t.Fatalf("createSchedule leaked raw proxy password: %s", rec.Body.String()) + } + var schedResp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &schedResp); err != nil { + t.Fatalf("decode schedule: %v", err) + } + schedID := int64(schedResp["id"].(float64)) + + view, _ := s.containerProxyRouteView("task", task.ID) + if view.Mode != "proxy" || !strings.Contains(view.EffectiveProxy, "127.0.0.1:19802") { + t.Fatalf("expected schedule proxy applied to bound task, got %+v", view) + } + + // 2. Update schedule to mode=pool -> bound task immediately switches to pool mode. + updBody := fmt.Sprintf(`{"name":"proxy-sched","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"09:00","proxy_mode":"pool","task_ids":[%d]}`, taskID) + updReq := httptest.NewRequest(http.MethodPatch, fmt.Sprintf("/api/schedules/%d", schedID), bytes.NewBufferString(updBody)) + updReq.SetPathValue("id", strconv.FormatInt(schedID, 10)) + updRec := httptest.NewRecorder() + s.updateSchedule(updRec, updReq) + if updRec.Code != http.StatusOK { + t.Fatalf("updateSchedule failed: %d %s", updRec.Code, updRec.Body.String()) + } + view, _ = s.containerProxyRouteView("task", task.ID) + if view.Mode != "pool" || view.EffectiveProxy != "http://127.0.0.1:19801" { + t.Fatalf("expected updated schedule pool mode applied to task, got %+v", view) + } + + // 3. @task mention search & context snapshot injection. + page, err := pg.SearchChatMentionsPage(context.Background(), "task", "proxy-e2e-task", "") + if err != nil { + t.Fatalf("SearchChatMentionsPage: %v", err) + } + found := false + for _, item := range page.Items { + if item.Kind == "task" && item.ID == taskID { + found = true + break + } + } + if !found { + t.Fatalf("expected task #%d in @task mention search, got %+v", taskID, page.Items) + } + injected, err := composeChatMentionMessage(pg, fmt.Sprintf("给 @[task#%d proxy-e2e-task] 设置代理池", taskID)) + if err != nil { + t.Fatalf("composeChatMentionMessage: %v", err) + } + if !strings.Contains(injected, "proxy-e2e-task") || !strings.Contains(injected, `"mode":"pool"`) { + t.Fatalf("expected task snapshot with proxy_route in mention message, got: %s", injected) + } +} + +func TestValidateScheduleProxyUnchangedAndErrorCodes(t *testing.T) { + m := &Manager{ + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{entries: nil}, + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + // 1. Existing schedule with proxy_mode=pool can still be rescheduled/updated when pool has no active nodes. + existingPool := &db.TaskSchedule{ID: 9, Name: "nightly", ProxyMode: "pool"} + inUnchanged := db.TaskScheduleInput{Name: "nightly", ProxyMode: "pool"} + if err := s.validateScheduleProxy(&inUnchanged, existingPool); err != nil { + t.Fatalf("expected unchanged pool schedule update to succeed with empty pool, got: %v", err) + } + if inUnchanged.ProxyMode != "pool" || inUnchanged.ProxyPoolID != "" || inUnchanged.ProxyURL != "" { + t.Fatalf("unexpected normalized unchanged pool input: %+v", inUnchanged) + } + + // 2. Existing schedule with masked custom proxy URL keeps raw secret when unchanged. + existingURL := &db.TaskSchedule{ID: 10, Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:secret@127.0.0.1:8080"} + inMasked := db.TaskScheduleInput{Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:***@127.0.0.1:8080"} + if err := s.validateScheduleProxy(&inMasked, existingURL); err != nil { + t.Fatalf("expected unchanged masked proxy URL update to succeed, got: %v", err) + } + if inMasked.ProxyURL != existingURL.ProxyURL { + t.Fatalf("expected raw proxy URL preserved, got %q", inMasked.ProxyURL) + } + + // 3. Newly selecting mode=pool with empty pool fails with structured error code. + existingInherit := &db.TaskSchedule{ID: 11, Name: "inherit", ProxyMode: "inherit"} + inSwitchToPool := db.TaskScheduleInput{Name: "inherit", ProxyMode: "pool"} + err := s.validateScheduleProxy(&inSwitchToPool, existingInherit) + verr, ok := err.(*proxyRouteValidationError) + if !ok || verr.code != "proxy_pool_no_available_nodes" { + t.Fatalf("expected proxy_pool_no_available_nodes error, got %T %v", err, err) + } + + // 4. HTTP PUT /api/proxy/routes/task/5 returns structured code for i18n clients. + req := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(`{"mode":"pool"}`)) + req.SetPathValue("scope", "task") + req.SetPathValue("owner_id", "5") + rec := httptest.NewRecorder() + s.putProxyRoute(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d %s", rec.Code, rec.Body.String()) + } + var payload struct { + Error string `json:"error"` + Code string `json:"code"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil { + t.Fatalf("decode error payload: %v", err) + } + if payload.Code != "proxy_pool_no_available_nodes" || payload.Error == "" { + t.Fatalf("unexpected error payload: %+v", payload) + } +} diff --git a/server/proxy_tools.go b/server/proxy_tools.go new file mode 100644 index 0000000..00acabe --- /dev/null +++ b/server/proxy_tools.go @@ -0,0 +1,152 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strconv" + "strings" + + actool "github.com/Autumn-27/norma/tool" +) + +func parseTaskIDArg(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var s string + if json.Unmarshal(raw, &s) == nil { + return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "#")) + } + var n int64 + if json.Unmarshal(raw, &n) == nil && n > 0 { + return strconv.FormatInt(n, 10) + } + return "" +} + +func (s *Server) toolListProxyPool() actool.CoreTool { + return roTool("list_proxy_pool", + "查看当前全局出口代理、代理池节点列表(含 ID、名称、健康状态、出口 IP)以及所有任务/会话容器的自定义代理路由。", + objSchema(map[string]any{}), + func(context.Context, json.RawMessage) (actool.Result, error) { + entries, activeID, _ := s.m.ProxyPoolSnapshot() + rt := s.ensureRouteRuntime() + rt.mu.RLock() + routesCopy := make([]ContainerProxyRoute, 0, len(rt.routes)) + for _, r := range rt.routes { + routesCopy = append(routesCopy, r) + } + rt.mu.RUnlock() + + globalRaw := strings.TrimSpace(s.m.GlobalProxy()) + globalDisplay := "direct" + if globalRaw != "" { + globalDisplay = maskSecrets(globalRaw) + } + routes := make([]map[string]any, 0, len(routesCopy)) + for _, r := range routesCopy { + cp := r + eff, _ := s.effectiveProxyDisplay(&cp) + routes = append(routes, map[string]any{ + "scope": r.Scope, + "owner_id": r.OwnerID, + "mode": r.Mode, + "proxy_pool_id": r.ProxyPoolID, + "proxy_url": maskSecrets(r.ProxyURL), + "effective_proxy": eff, + "note": r.Note, + "updated_at": r.UpdatedAt, + }) + } + return jsonResult(map[string]any{ + "global_proxy": globalDisplay, + "active_pool_id": activeID, + "entries": entries, + "routes": routes, + }) + }) +} + +func (s *Server) toolSetTaskProxy() actool.CoreTool { + return wrTool("set_task_proxy", + "为指定任务的沙箱容器设置出口代理或代理池(保存并立即对透明网关与抓包代理热生效)。\n"+ + "- mode=pool:使用代理池自动轮换(跟随当前健康活跃节点)\n"+ + "- mode=proxy:绑定代理池指定节点(传 proxy_pool_id,支持节点 ID 或名称)或自定义代理(传 proxy_url)\n"+ + "- mode=direct:强制直连(绕过全局代理/代理池)\n"+ + "- mode=inherit:恢复继承全局出口代理设置", + objSchema(map[string]any{ + "task_id": strParam("目标任务 ID(如 \"5\")"), + "mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "代理模式:pool=代理池自动轮换,proxy=指定节点或自定义 URL,direct=直连,inherit=继承全局"}, + "proxy_pool_id": strParam("可选(mode=proxy 时):代理池节点 ID 或名称,可用 list_proxy_pool 查看"), + "proxy_url": strParam("可选(mode=proxy 且未传 proxy_pool_id 时):自定义代理 URL,如 socks5://host:1080 或 http://user:pass@host:8080"), + "note": strParam("可选:路由备注"), + }, "task_id", "mode"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + var a struct { + TaskID json.RawMessage `json:"task_id"` + Mode string `json:"mode"` + ProxyPoolID string `json:"proxy_pool_id"` + ProxyURL string `json:"proxy_url"` + Note string `json:"note"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + taskID := parseTaskIDArg(a.TaskID) + if taskID == "" { + return actool.Errorf("task_id 不能为空"), nil + } + t, ok := s.m.Task(taskID) + if !ok { + return actool.Errorf(fmt.Sprintf("任务 #%s 不存在", taskID)), nil + } + mode := strings.ToLower(strings.TrimSpace(a.Mode)) + if mode == "" { + if strings.TrimSpace(a.ProxyPoolID) != "" || strings.TrimSpace(a.ProxyURL) != "" { + mode = "proxy" + } else { + return actool.Errorf("mode 不能为空"), nil + } + } + route, err := s.setContainerProxyRoute("task", t.ID, ProxyRouteInput{ + Mode: mode, + ProxyPoolID: a.ProxyPoolID, + ProxyURL: a.ProxyURL, + Note: a.Note, + }) + if err != nil { + return actool.Errorf("设置任务代理失败: " + err.Error()), nil + } + view, globalDisplay := s.containerProxyRouteView("task", t.ID) + return jsonResult(map[string]any{ + "task_id": t.ID, + "task_name": t.lifecycleSnapshot().Name, + "scope": route.Scope, + "owner_id": route.OwnerID, + "mode": view.Mode, + "proxy_pool_id": view.ProxyPoolID, + "proxy_url": view.ProxyURL, + "effective_proxy": view.EffectiveProxy, + "global_proxy": globalDisplay, + "note": view.Note, + }) + }) +} + +// seedProxyToolBindings adds list_proxy_pool and set_task_proxy bindings ONCE +// on existing DBs so chat agents can manage task proxies immediately. +func (s *Server) seedProxyToolBindings() { + const flag = "proxy_tool_bindings_v1" + if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { + return + } + for _, agentKey := range []string{"auto", "mainagent", "pentest"} { + if err := s.m.pg.AddAgentToToolBinding(agentKey, []string{"list_proxy_pool", "set_task_proxy"}); err != nil { + log.Printf("[%s] 代理工具默认绑定失败: %v", agentKey, err) + return + } + } + _ = s.m.pg.SetSetting(flag, "true") +} diff --git a/server/sandbox_api.go b/server/sandbox_api.go new file mode 100644 index 0000000..aae55a1 --- /dev/null +++ b/server/sandbox_api.go @@ -0,0 +1,517 @@ +package server + +import ( + "context" + "encoding/json" + "log" + "net" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/artex/internal/sandbox" + "github.com/Autumn-27/artex/traffic" +) + +const settingSandboxOverrides = "sandbox_settings_json" + +// initSandbox wires the global sandbox manager, applies persisted UI overrides, +// reconciles orphan containers on startup, starts the idle session reaper, and +// configures the recording proxy SSRF guard. +func (s *Server) initSandbox() { + caCert := "" + if s.m.traffic != nil { + caCert = s.m.traffic.CACertPath() + } + cfg := sandbox.ConfigFromEnv(s.dataDir, caCert) + mgr, err := sandbox.New(cfg) + if err != nil { + log.Printf("[sandbox] init failed (falling back to local): %v", err) + cfg.Mode = sandbox.ModeLocal + mgr, _ = sandbox.New(cfg) + } + if s.m.pg != nil { + if raw, ok, _ := s.m.pg.GetSetting(settingSandboxOverrides); ok && strings.TrimSpace(raw) != "" { + var ov sandbox.RuntimeOverrides + if json.Unmarshal([]byte(raw), &ov) == nil { + mgr.ApplyOverrides(ov) + } + } + } + sandbox.SetDefault(mgr) + // Build merged system + MITM CA bundle so sandbox containers trust the recording + // proxy at the system CA store level (/etc/ssl/certs/ca-certificates.crt) without root. + if s.m.traffic != nil { + if bundle := s.m.traffic.EnsureSystemCABundle(); bundle != "" { + mgr.SetSystemCABundlePath(bundle) + } + s.m.traffic.SetGatewayToken(os.Getenv("ARTEX_GATEWAY_TOKEN")) + } + // Always load persisted egress blacklist rules, per-container proxy routes, + // gateway settings, and task-level egress checker (works in both local & Docker modes). + s.syncEgressBlacklist() + s.initProxyRoutesAndGateway() + if s.m.traffic != nil { + s.m.traffic.SetTaskBlacklistChecker(s.checkTaskEgressBlacklist) + } + s.startEmbeddedTransparentGatewayIfConfigured() + if !mgr.Enabled() { + log.Printf("[sandbox] mode=local (set ARTEX_SANDBOX_MODE=docker to enable container isolation)") + return + } + validTasks := map[string]bool{} + for _, t := range s.m.List() { + validTasks[t.ID] = true + } + var validSessions map[string]bool + if s.m.pg != nil { + if convs, err := s.m.pg.ListConversations(); err == nil { + validSessions = make(map[string]bool, len(convs)) + for _, c := range convs { + validSessions[s.convBusyKey(c.ID)] = true + } + } + } + rctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) + defer cancel() + if err := mgr.ReconcileOnStartup(rctx, validTasks, validSessions); err != nil { + log.Printf("[sandbox] startup reconcile warning: %v", err) + } else { + log.Printf("[sandbox] mode=docker image=%s network=%s runtime=%q mem=%dMiB cpus=%.2f", + mgr.Config().Image, mgr.Config().Network, mgr.Config().Runtime, mgr.Config().MemoryMB, mgr.Config().CPUs) + } + mgr.StartBackgroundReaper(s.ctx) + + // Enable SSRF guard on the recording proxy so sandbox containers cannot pivot + // through :8788 to reach :8787, postgres, docker-socket-proxy, or cloud metadata. + if s.m.traffic != nil { + blockedHosts := []string{"artex", "postgres", "docker-socket-proxy"} + if pgHost := parsePGHostFromEnv(); pgHost != "" { + blockedHosts = append(blockedHosts, pgHost) + } + blockPrivate := strings.EqualFold(strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")), "true") || + strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")) == "1" + s.m.traffic.EnableSSRFGuard(traffic.SSRFGuardConfig{ + Enabled: true, + BlockPrivate: blockPrivate, + BlockedHosts: blockedHosts, + BlockedCIDRs: mgr.SandboxSubnets(), + InfraIPs: parseProtectIPs(os.Getenv("ARTEX_PROXY_PROTECT_IPS")), + }) + s.m.traffic.SetSourceResolver(func(srcIP string) (traffic.SourceIdentity, bool) { + id, ok := mgr.ResolveContainerByIP(srcIP) + if !ok { + return traffic.SourceIdentity{}, false + } + return traffic.SourceIdentity{ + Scope: string(id.Scope), + OwnerID: id.OwnerID, + ContainerID: id.ContainerID, + SrcIP: srcIP, + }, true + }) + } +} + +func parseProtectIPs(raw string) []net.IP { + var out []net.IP + for _, part := range strings.FieldsFunc(raw, func(r rune) bool { + return r == ',' || r == ';' || r == ' ' || r == '\n' || r == '\t' + }) { + if ip := net.ParseIP(strings.TrimSpace(part)); ip != nil { + out = append(out, ip) + } + } + return out +} + +func parsePGHostFromEnv() string { + dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) + if dsn == "" { + return "" + } + if u, err := url.Parse(dsn); err == nil && u.Hostname() != "" { + return u.Hostname() + } + return "" +} + +// blockSandboxAdminAccess rejects HTTP requests to :8787 coming from inside the +// isolated sandbox Docker network. +func (s *Server) blockSandboxAdminAccess(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if mgr := sandbox.Default(); mgr != nil && mgr.IsSandboxSourceIP(r.RemoteAddr) { + http.Error(w, "forbidden: sandbox container cannot access ARTEX management API", http.StatusForbidden) + return + } + next.ServeHTTP(w, r) + }) +} + +func (s *Server) enrichSandboxContainer(ci *sandbox.ContainerInfo) { + if ci == nil { + return + } + if ci.Scope == sandbox.ScopeTask { + if t, ok := s.m.Task(ci.OwnerID); ok { + title := strings.TrimSpace(t.Name) + if title == "" { + title = strings.TrimSpace(t.Description) + } + ci.OwnerTitle = title + ci.TaskRunning = s.resolvedTaskStatus(t) == "running" + } + } +} + +// GET /api/sandbox/status +func (s *Server) sandboxStatus(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil { + writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}}) + return + } + withStats := r.URL.Query().Get("stats") == "1" + ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) + defer cancel() + st := mgr.StatusWithStats(ctx, withStats) + for i := range st.Containers { + s.enrichSandboxContainer(&st.Containers[i]) + } + writeJSON(w, 200, st) +} + +// PUT /api/sandbox/settings +func (s *Server) updateSandboxSettings(w http.ResponseWriter, r *http.Request) { + var ov sandbox.RuntimeOverrides + if err := json.NewDecoder(r.Body).Decode(&ov); err != nil { + writeErr(w, 400, "bad json: "+err.Error()) + return + } + if ov.MemoryMB != nil && (*ov.MemoryMB < 256 || *ov.MemoryMB > 65536) { + writeErr(w, 400, "内存上限必须在 256 到 65536 MiB 之间") + return + } + if ov.CPUs != nil && (*ov.CPUs < 0.25 || *ov.CPUs > 64) { + writeErr(w, 400, "CPU 上限必须在 0.25 到 64 之间") + return + } + if ov.PidsLimit != nil && (*ov.PidsLimit < 32 || *ov.PidsLimit > 8192) { + writeErr(w, 400, "进程数上限必须在 32 到 8192 之间") + return + } + if ov.ShmSizeMB != nil && (*ov.ShmSizeMB < 64 || *ov.ShmSizeMB > 8192) { + writeErr(w, 400, "共享内存上限必须在 64 到 8192 MiB 之间") + return + } + if ov.SessionIdleMinutes != nil && (*ov.SessionIdleMinutes < 1 || *ov.SessionIdleMinutes > 1440) { + writeErr(w, 400, "对话空闲停机时间必须在 1 到 1440 分钟之间") + return + } + if mgr := sandbox.Default(); mgr != nil { + mgr.ApplyOverrides(ov) + if s.m.pg != nil { + cfg := mgr.Config() + persisted := sandbox.RuntimeOverrides{ + Image: &cfg.Image, + MemoryMB: &cfg.MemoryMB, + CPUs: &cfg.CPUs, + PidsLimit: &cfg.PidsLimit, + ShmSizeMB: &cfg.ShmSizeMB, + Runtime: &cfg.Runtime, + AutoStopOnComplete: &cfg.AutoStopOnComplete, + SessionIdleMinutes: &cfg.SessionIdleMinutes, + } + if b, err := json.Marshal(persisted); err == nil { + _ = s.m.pg.SetSetting(settingSandboxOverrides, string(b)) + } + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + writeJSON(w, 200, mgr.Status(ctx)) + return + } + writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}}) +} + +// POST /api/sandbox/prune +func (s *Server) pruneSandboxContainers(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeJSON(w, 200, map[string]any{"removed": 0}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + removed, err := mgr.PruneStopped(ctx) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"removed": removed}) +} +// GET /api/sandbox/containers/{scope}/{id} +func (s *Server) getSandboxContainer(w http.ResponseWriter, r *http.Request) { + target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} + if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { + writeErr(w, 400, "无效的沙箱目标") + return + } + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeJSON(w, 200, sandbox.ContainerInfo{ + Scope: target.Scope, + OwnerID: target.OwnerID, + State: "local", + WorkDirContainer: sandbox.ContainerWorkDir, + }) + return + } + withStats := r.URL.Query().Get("stats") != "0" + ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) + defer cancel() + info, _ := mgr.Inspect(ctx, target, withStats) + s.enrichSandboxContainer(&info) + writeJSON(w, 200, info) +} + +// POST /api/sandbox/containers/{scope}/{id}/start +func (s *Server) startSandboxContainer(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} + if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { + writeErr(w, 400, "无效的沙箱目标") + return + } + mgr.ClearIdleStop(target) + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + if _, err := mgr.Ensure(ctx, target); err != nil { + writeErr(w, 500, err.Error()) + return + } + info, _ := mgr.Inspect(ctx, target, true) + s.enrichSandboxContainer(&info) + writeJSON(w, 200, info) +} + +// POST /api/sandbox/containers/{scope}/{id}/recreate +func (s *Server) recreateSandboxContainer(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} + if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { + writeErr(w, 400, "无效的沙箱目标") + return + } + var req struct { + PauseTask bool `json:"pause_task"` + ClearWorkspace bool `json:"clear_workspace"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + if target.Scope == sandbox.ScopeTask { + if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { + if !req.PauseTask { + writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器") + return + } + _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) + } + } + mgr.ClearIdleStop(target) + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + info, err := mgr.Recreate(ctx, target, req.ClearWorkspace) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + s.enrichSandboxContainer(&info) + writeJSON(w, 200, info) +} + +// POST /api/sandbox/containers/{scope}/{id}/stop +func (s *Server) stopSandboxContainer(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} + if !target.Valid() { + writeErr(w, 400, "无效的沙箱目标") + return + } + if target.Scope == sandbox.ScopeTask { + if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { + _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) + } + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if err := mgr.Stop(ctx, target); err != nil { + writeErr(w, 500, err.Error()) + return + } + info, _ := mgr.Inspect(ctx, target, false) + s.enrichSandboxContainer(&info) + writeJSON(w, 200, info) +} + +// DELETE /api/sandbox/containers/{scope}/{id} +func (s *Server) removeSandboxContainer(w http.ResponseWriter, r *http.Request) { + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} + if !target.Valid() { + writeErr(w, 400, "无效的沙箱目标") + return + } + if target.Scope == sandbox.ScopeTask { + if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { + _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) + } + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if err := mgr.Remove(ctx, target); err != nil { + writeErr(w, 500, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"removed": target.Key()}) +} + +// GET /api/tasks/{id}/sandbox +func (s *Server) getTaskSandbox(w http.ResponseWriter, r *http.Request) { + t, ok := s.m.Task(r.PathValue("id")) + if !ok { + writeErr(w, 404, "task not found") + return + } + mgr := sandbox.Default() + target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} + if mgr == nil || !mgr.Enabled() { + writeJSON(w, 200, sandbox.ContainerInfo{ + Scope: sandbox.ScopeTask, + OwnerID: t.ID, + State: "local", + WorkDirContainer: sandbox.ContainerWorkDir, + }) + return + } + withStats := r.URL.Query().Get("stats") != "0" + ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) + defer cancel() + info, _ := mgr.Inspect(ctx, target, withStats) + writeJSON(w, 200, info) +} + +// POST /api/tasks/{id}/sandbox/start +func (s *Server) startTaskSandbox(w http.ResponseWriter, r *http.Request) { + t, ok := s.m.Task(r.PathValue("id")) + if !ok { + writeErr(w, 404, "task not found") + return + } + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} + mgr.ClearIdleStop(target) + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + if _, err := mgr.Ensure(ctx, target); err != nil { + writeErr(w, 500, err.Error()) + return + } + info, _ := mgr.Inspect(ctx, target, true) + writeJSON(w, 200, info) +} + +// POST /api/tasks/{id}/sandbox/stop +func (s *Server) stopTaskSandbox(w http.ResponseWriter, r *http.Request) { + t, ok := s.m.Task(r.PathValue("id")) + if !ok { + writeErr(w, 404, "task not found") + return + } + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + var req struct { + PauseTask bool `json:"pause_task"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + + status := s.resolvedTaskStatus(t) + if status == "running" { + if !req.PauseTask { + writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再停止容器") + return + } + _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) + } + target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if err := mgr.Stop(ctx, target); err != nil { + writeErr(w, 500, err.Error()) + return + } + info, _ := mgr.Inspect(ctx, target, false) + writeJSON(w, 200, info) +} + +// POST /api/tasks/{id}/sandbox/recreate +func (s *Server) recreateTaskSandbox(w http.ResponseWriter, r *http.Request) { + t, ok := s.m.Task(r.PathValue("id")) + if !ok { + writeErr(w, 404, "task not found") + return + } + mgr := sandbox.Default() + if mgr == nil || !mgr.Enabled() { + writeErr(w, 400, "沙箱容器模式未开启") + return + } + var req struct { + PauseTask bool `json:"pause_task"` + ClearWorkspace bool `json:"clear_workspace"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + + if s.resolvedTaskStatus(t) == "running" { + if !req.PauseTask { + writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器") + return + } + _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) + } + target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} + mgr.ClearIdleStop(target) + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + info, err := mgr.Recreate(ctx, target, req.ClearWorkspace) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + writeJSON(w, 200, info) +} diff --git a/server/sandbox_attachments.go b/server/sandbox_attachments.go new file mode 100644 index 0000000..f602c9d --- /dev/null +++ b/server/sandbox_attachments.go @@ -0,0 +1,205 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + "github.com/Autumn-27/artex/internal/sandbox" + actool "github.com/Autumn-27/norma/tool" +) + +var ( + reDraftUploadPath = regexp.MustCompile(`(?:[^\s"'\x60<>()]*?/)?drafts/([A-Za-z0-9_-]+)/uploads/([^\s"'\x60<>()(),,;;]+)`) + reSessionUploadPath = regexp.MustCompile(`(?:[^\s"'\x60<>()]*?/)?sessions/([A-Za-z0-9_-]+)/([^\s"'\x60<>()(),,;;]+)`) + reContainerFilePath = regexp.MustCompile(`/workspace/([^\s"'\x60<>()(),,;;]+)`) +) + +// transferDraftUploadsToTask copies any pre-task staged uploads referenced in +// description/goal from /drafts//uploads/ into the newly +// created task's /tasks//uploads/ and rewrites their paths so +// sandboxed task containers can access them under /workspace/uploads/. +func transferDraftUploadsToTask(dataDir, taskID, description, goal string) (string, string, int) { + if strings.TrimSpace(taskID) == "" { + return description, goal, 0 + } + taskRoot := filepath.Join(dataDir, "tasks", taskID) + sandboxOn := sandbox.Default() != nil && sandbox.Default().Enabled() + + copied := 0 + rewritten := map[string]string{} + rewriteText := func(text string) string { + return reDraftUploadPath.ReplaceAllStringFunc(text, func(match string) string { + if prev, ok := rewritten[match]; ok { + return prev + } + sub := reDraftUploadPath.FindStringSubmatch(match) + if len(sub) != 3 { + return match + } + draftRoot := filepath.Join(dataDir, "drafts", sub[1]) + relDst, err := sandbox.CopyRegularFileSafe(draftRoot, filepath.Join("uploads", sub[2]), taskRoot, "uploads") + if err != nil { + return match + } + copied++ + var targetPath string + if sandboxOn { + targetPath = sandbox.ContainerWorkDir + "/" + relDst + } else { + targetPath = filepath.Join(taskRoot, filepath.FromSlash(relDst)) + } + rewritten[match] = targetPath + return targetPath + }) + } + return rewriteText(description), rewriteText(goal), copied +} + +// transferSessionAttachmentsToTask copies attachments from an auto/chat session +// into a newly spawned task's uploads/ directory — handling both explicit +// attachments passed to spawn_task AND fallback path references in description/goal. +func transferSessionAttachmentsToTask(dataDir, sessionID, taskID string, explicit []string, description, goal string) (string, string, int) { + if strings.TrimSpace(taskID) == "" || strings.TrimSpace(sessionID) == "" { + return description, goal, 0 + } + sessionRoot := filepath.Join(dataDir, "sessions", sessionID) + taskRoot := filepath.Join(dataDir, "tasks", taskID) + sandboxOn := sandbox.Default() != nil && sandbox.Default().Enabled() + + formatTarget := func(relDst string) string { + if sandboxOn { + return sandbox.ContainerWorkDir + "/" + relDst + } + return filepath.Join(taskRoot, filepath.FromSlash(relDst)) + } + + copied := 0 + copiedByRel := map[string]string{} // normalized session-relative path -> new target path + + copyOne := func(candidate string) (string, bool) { + norm := strings.TrimSpace(candidate) + if norm == "" { + return "", false + } + if prev, ok := copiedByRel[norm]; ok { + return prev, true + } + relDst, err := sandbox.CopyRegularFileSafe(sessionRoot, norm, taskRoot, "uploads") + if err != nil { + return "", false + } + copied++ + outPath := formatTarget(relDst) + copiedByRel[norm] = outPath + return outPath, true + } + + var explicitManifest []string + for _, raw := range explicit { + if targetPath, ok := copyOne(raw); ok { + explicitManifest = append(explicitManifest, targetPath) + } + } + + rewriteText := func(text string) string { + text = reSessionUploadPath.ReplaceAllStringFunc(text, func(match string) string { + sub := reSessionUploadPath.FindStringSubmatch(match) + if len(sub) != 3 || sub[1] != sessionID { + return match + } + if targetPath, ok := copyOne(sub[2]); ok { + return targetPath + } + return match + }) + text = reContainerFilePath.ReplaceAllStringFunc(text, func(match string) string { + sub := reContainerFilePath.FindStringSubmatch(match) + if len(sub) != 2 { + return match + } + if targetPath, ok := copyOne(sub[1]); ok { + return targetPath + } + return match + }) + return text + } + + newDesc := rewriteText(description) + newGoal := rewriteText(goal) + if len(explicitManifest) > 0 { + var missing []string + for _, p := range explicitManifest { + if !strings.Contains(newDesc, p) && !strings.Contains(newGoal, p) { + missing = append(missing, p) + } + } + if len(missing) > 0 { + var b strings.Builder + b.WriteString(newDesc) + b.WriteString("\n\n【随任务附带的文件】(位于任务工作目录,可用 Read/Bash 直接打开):") + for _, p := range missing { + fmt.Fprintf(&b, "\n- %s", p) + } + newDesc = b.String() + } + } + return newDesc, newGoal, copied +} + +// toolReadTaskFile lets orchestration agents (e.g. auto) safely inspect a +// specific regular file inside a task's workspace without mounting all tasks/ +// into the chat sandbox container. +func (s *Server) toolReadTaskFile() actool.CoreTool { + return roTool("read_task_file", + "只读查看指定任务工作目录中的某个文本文件(最多返回 64KB)。用于编排 agent 在容器隔离模式下安全查看子任务产物。", + objSchema(map[string]any{ + "task_id": strParam("目标任务 id"), + "path": strParam("任务工作目录内的相对路径或 /workspace/... 路径,如 i12/result.txt 或 uploads/targets.txt"), + }, "task_id", "path"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + var a struct { + TaskID string `json:"task_id"` + Path string `json:"path"` + } + _ = json.Unmarshal(in, &a) + t, ok := s.lookupTask(a.TaskID) + if !ok { + return actool.Errorf("任务不存在: " + a.TaskID), nil + } + taskRoot := filepath.Join(s.m.dir, "tasks", t.ID) + resolved, allowed := sandbox.ResolveConfined(taskRoot, "", a.Path) + if !allowed { + return actool.Errorf("非法路径:不允许越出任务工作目录"), nil + } + lfi, err := os.Lstat(resolved) + if err != nil { + return actool.Errorf("文件不存在或无法读取: " + err.Error()), nil + } + if !lfi.Mode().IsRegular() { + return actool.Errorf("仅支持读取普通文件"), nil + } + const maxRead = 64 << 10 + f, err := os.Open(resolved) + if err != nil { + return actool.Errorf("打开文件失败: " + err.Error()), nil + } + defer f.Close() + buf := make([]byte, maxRead+1) + n, _ := f.Read(buf) + truncated := n > maxRead + if truncated { + n = maxRead + } + out := string(buf[:n]) + if truncated { + out += "\n\n[内容已截断,仅展示前 64KB]" + } + return actool.Text(out), nil + }) +} diff --git a/server/sandbox_attachments_test.go b/server/sandbox_attachments_test.go new file mode 100644 index 0000000..48262d9 --- /dev/null +++ b/server/sandbox_attachments_test.go @@ -0,0 +1,112 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Autumn-27/artex/internal/sandbox" +) + +func TestTransferDraftAndSessionAttachmentsToTask(t *testing.T) { + tmp := t.TempDir() + // Simulate Docker sandbox enabled for path rewriting to /workspace/uploads/... + mgr, err := sandbox.New(sandbox.Config{ + Mode: sandbox.ModeDocker, + DockerHost: "unix:///nonexistent.sock", + DataDir: tmp, + HostDataDir: tmp, + }) + if err != nil { + t.Fatal(err) + } + prev := sandbox.Default() + sandbox.SetDefault(mgr) + defer sandbox.SetDefault(prev) + + // 1. Draft staging upload handoff + draftDir := filepath.Join(tmp, "drafts", "draft-abc", "uploads") + if err := os.MkdirAll(draftDir, 0o755); err != nil { + t.Fatal(err) + } + draftFile := filepath.Join(draftDir, "scope.txt") + if err := os.WriteFile(draftFile, []byte("https://example.com\n"), 0o644); err != nil { + t.Fatal(err) + } + desc := "请测试以下附件中的目标:\n- " + draftFile + newDesc, newGoal, copied := transferDraftUploadsToTask(tmp, "101", desc, "扫描全部目标") + if copied != 1 { + t.Fatalf("draft copied = %d, want 1", copied) + } + if !strings.Contains(newDesc, "/workspace/uploads/scope.txt") { + t.Fatalf("rewritten draft desc = %q", newDesc) + } + if newGoal != "扫描全部目标" { + t.Fatalf("unexpected goal change: %q", newGoal) + } + if b, err := os.ReadFile(filepath.Join(tmp, "tasks", "101", "uploads", "scope.txt")); err != nil || string(b) != "https://example.com\n" { + t.Fatalf("copied draft file check failed: %q, %v", string(b), err) + } + + // 2. Auto/chat session -> spawn_task handoff (explicit + inline reference) + sessDir := filepath.Join(tmp, "sessions", "conv-7", "uploads") + if err := os.MkdirAll(sessDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sessDir, "api.yaml"), []byte("openapi: 3.0.0\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sessDir, "creds.txt"), []byte("user:pass\n"), 0o644); err != nil { + t.Fatal(err) + } + desc2, goal2, copied2 := transferSessionAttachmentsToTask( + tmp, "conv-7", "202", + []string{"uploads/creds.txt"}, + "分析接口文档 /workspace/uploads/api.yaml", + "测试所有鉴权接口", + ) + if copied2 != 2 { + t.Fatalf("session copied = %d, want 2", copied2) + } + if !strings.Contains(desc2, "/workspace/uploads/api.yaml") || !strings.Contains(desc2, "/workspace/uploads/creds.txt") { + t.Fatalf("rewritten session desc = %q", desc2) + } + if goal2 != "测试所有鉴权接口" { + t.Fatalf("unexpected goal2: %q", goal2) + } + for _, fn := range []string{"api.yaml", "creds.txt"} { + if _, err := os.Stat(filepath.Join(tmp, "tasks", "202", "uploads", fn)); err != nil { + t.Fatalf("expected %s in task 202 uploads: %v", fn, err) + } + } +} + +func TestAcquireSandboxBrowserSlotCapsConcurrencyAndHonorsCancel(t *testing.T) { + key := "task:browser-slot-test" + rel1, err := acquireSandboxBrowserSlot(t.Context(), key) + if err != nil { + t.Fatalf("slot 1: %v", err) + } + defer rel1() + rel2, err := acquireSandboxBrowserSlot(t.Context(), key) + if err != nil { + t.Fatalf("slot 2: %v", err) + } + // Third concurrent browser for the same task must block until timeout/release. + cctx, cancel := context.WithTimeout(t.Context(), 40*time.Millisecond) + defer cancel() + if _, err := acquireSandboxBrowserSlot(cctx, key); err == nil { + t.Fatalf("expected 3rd slot to block and fail on context deadline") + } + // Releasing slot 2 immediately allows a new acquisition (idempotent double-release safe). + rel2() + rel2() + rel3, err := acquireSandboxBrowserSlot(t.Context(), key) + if err != nil { + t.Fatalf("slot after release: %v", err) + } + rel3() +} diff --git a/server/schedule_tools.go b/server/schedule_tools.go new file mode 100644 index 0000000..836618a --- /dev/null +++ b/server/schedule_tools.go @@ -0,0 +1,343 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strconv" + "strings" + "time" + actool "github.com/Autumn-27/norma/tool" +) + +func parseInt64Flexible(raw json.RawMessage) (int64, bool) { + if len(raw) == 0 { + return 0, false + } + var n int64 + if json.Unmarshal(raw, &n) == nil && n > 0 { + return n, true + } + var s string + if json.Unmarshal(raw, &s) == nil { + s = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "#")) + if v, err := strconv.ParseInt(s, 10, 64); err == nil && v > 0 { + return v, true + } + } + return 0, false +} + +func parseInt64SliceFlexible(raws []json.RawMessage) ([]int64, error) { + out := make([]int64, 0, len(raws)) + seen := map[int64]bool{} + for _, r := range raws { + id, ok := parseInt64Flexible(r) + if !ok { + return nil, fmt.Errorf("无效的任务 ID: %s", string(r)) + } + if !seen[id] { + seen[id] = true + out = append(out, id) + } + } + return out, nil +} + +func serverClockMeta(now time.Time) (string, string, int) { + _, offsetSec := now.Zone() + return now.Format(time.RFC3339), time.Local.String(), offsetSec / 60 +} + +func (s *Server) toolListTaskSchedules() actool.CoreTool { + return roTool("list_task_schedules", + "查看所有定时日历计划任务(包含当前服务器时间与时区、规则类型、起止时间、关联任务、代理配置、状态与下次触发时间)。", + objSchema(map[string]any{}), + func(context.Context, json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + items, err := s.m.pg.ListTaskSchedules() + if err != nil { + return actool.Errorf("查询计划任务失败: " + err.Error()), nil + } + dtos := make([]map[string]any, 0, len(items)) + for _, item := range items { + dtos = append(dtos, s.scheduleDTO(item)) + } + srvTime, srvTZ, srvOffset := serverClockMeta(time.Now()) + return jsonResult(map[string]any{ + "server_time": srvTime, + "server_timezone": srvTZ, + "server_utc_offset_minutes": srvOffset, + "schedules": dtos, + }) + }) +} + +func (s *Server) toolCreateTaskSchedule() actool.CoreTool { + return wrTool("create_task_schedule", + "创建一个定时日历计划任务,按指定日历时间窗口自动控制一个或多个任务的运行与暂停(并可选绑定出口代理/代理池)。\n"+ + "- schedule_type=weekly:按周重复,weekdays 填 1-7(1=周一…7=周日),start_time 必填(HH:MM),end_time 可选(留空表示开始后持续运行;早于 start_time 表示跨午夜到次日)。\n"+ + "- schedule_type=once:一次性或跨多天区间,run_date 必填(YYYY-MM-DD),end_date 可选(YYYY-MM-DD),start_time 必填,end_time 可选。\n"+ + "- 创建前可先用 list_task_schedules 查看当前 server_time,或用 list_tasks 查看任务 ID。", + objSchema(map[string]any{ + "name": strParam("计划名称(必填)"), + "schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "规则类型:once=一次性,weekly=按周重复"}, + "start_time": strParam("开始时间,格式 HH:MM(如 18:00)"), + "end_time": strParam("结束时间,格式 HH:MM(可选;留空=持续运行,小于 start_time=次日结束)"), + "run_date": strParam("开始日期 YYYY-MM-DD(schedule_type=once 时必填)"), + "end_date": strParam("结束日期 YYYY-MM-DD(可选,仅 schedule_type=once 跨多天时使用)"), + "weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "按周重复的星期列表 1-7(1=周一…7=周日;schedule_type=weekly 时必填)"}, + "timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "时区模式:beijing=北京时间(默认),system=服务器当前时区"}, + "enabled": map[string]any{"type": "boolean", "description": "是否启用,默认 true"}, + "start_immediately": map[string]any{"type": "boolean", "description": "保存后是否立即运行关联任务,默认 false"}, + "task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "关联的任务 ID 列表(可传数字或字符串)"}, + "proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:计划触发时应用到关联任务的代理模式"}, + "proxy_pool_id": strParam("可选(proxy_mode=proxy 时):代理池节点 ID 或名称"), + "proxy_url": strParam("可选(proxy_mode=proxy 且未指定 proxy_pool_id 时):自定义代理 URL"), + }, "name", "schedule_type", "start_time"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + Name string `json:"name"` + Enabled *bool `json:"enabled"` + TimezoneMode string `json:"timezone_mode"` + ScheduleType string `json:"schedule_type"` + RunDate string `json:"run_date"` + EndDate string `json:"end_date"` + Weekdays []int `json:"weekdays"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + StartImmediately bool `json:"start_immediately"` + TaskIDs []json.RawMessage `json:"task_ids"` + ProxyMode string `json:"proxy_mode"` + ProxyPoolID string `json:"proxy_pool_id"` + ProxyURL string `json:"proxy_url"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + taskIDs, err := parseInt64SliceFlexible(a.TaskIDs) + if err != nil { + return actool.Errorf(err.Error()), nil + } + enabled := true + if a.Enabled != nil { + enabled = *a.Enabled + } + req := scheduleRequest{ + Name: a.Name, + Enabled: &enabled, + TimezoneMode: a.TimezoneMode, + ScheduleType: a.ScheduleType, + RunDate: a.RunDate, + EndDate: a.EndDate, + Weekdays: a.Weekdays, + StartTime: a.StartTime, + EndTime: a.EndTime, + StartImmediately: a.StartImmediately, + ProxyMode: a.ProxyMode, + ProxyPoolID: a.ProxyPoolID, + ProxyURL: a.ProxyURL, + TaskIDs: taskIDs, + } + input := s.scheduleInput(req, nil) + if err := s.validateScheduleProxy(&input, nil); err != nil { + return actool.Errorf("代理配置无效: " + err.Error()), nil + } + item, err := s.m.pg.CreateTaskSchedule(input) + if err != nil { + return actool.Errorf("创建计划任务失败: " + err.Error()), nil + } + s.applyScheduleProxyToTasks(item) + if req.StartImmediately && item.Enabled { + s.runScheduleTasks(item) + } + return jsonResult(s.scheduleDTO(item)) + }) +} + +func (s *Server) toolUpdateTaskSchedule() actool.CoreTool { + return wrTool("update_task_schedule", + "修改已有定时日历计划任务(仅需传要变更的字段,未传字段保持原值)。可修改时间窗、星期、关联任务、启停状态或代理/代理池配置。", + objSchema(map[string]any{ + "schedule_id": strParam("要修改的计划任务 ID(必填)"), + "name": strParam("可选:新名称"), + "enabled": map[string]any{"type": "boolean", "description": "可选:启用或暂停该计划"}, + "schedule_type": map[string]any{"type": "string", "enum": []string{"once", "weekly"}, "description": "可选:规则类型"}, + "timezone_mode": map[string]any{"type": "string", "enum": []string{"beijing", "system"}, "description": "可选:时区模式"}, + "run_date": strParam("可选:开始日期 YYYY-MM-DD"), + "end_date": strParam("可选:结束日期 YYYY-MM-DD(传空字符串清除)"), + "weekdays": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "可选:星期列表 1-7"}, + "start_time": strParam("可选:开始时间 HH:MM"), + "end_time": strParam("可选:结束时间 HH:MM(传空字符串表示持续运行)"), + "start_immediately": map[string]any{"type": "boolean", "description": "可选:是否立即运行"}, + "task_ids": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:替换关联任务 ID 列表"}, + "proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:代理模式"}, + "proxy_pool_id": strParam("可选:代理池节点 ID 或名称"), + "proxy_url": strParam("可选:自定义代理 URL"), + }, "schedule_id"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + ScheduleID json.RawMessage `json:"schedule_id"` + Name *string `json:"name"` + Enabled *bool `json:"enabled"` + TimezoneMode *string `json:"timezone_mode"` + ScheduleType *string `json:"schedule_type"` + RunDate *string `json:"run_date"` + EndDate *string `json:"end_date"` + Weekdays *[]int `json:"weekdays"` + StartTime *string `json:"start_time"` + EndTime *string `json:"end_time"` + StartImmediately *bool `json:"start_immediately"` + TaskIDs *[]json.RawMessage `json:"task_ids"` + ProxyMode *string `json:"proxy_mode"` + ProxyPoolID *string `json:"proxy_pool_id"` + ProxyURL *string `json:"proxy_url"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + id, ok := parseInt64Flexible(a.ScheduleID) + if !ok { + return actool.Errorf("schedule_id 无效"), nil + } + old, err := s.m.pg.GetTaskSchedule(id) + if err != nil { + return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil + } + trimClock := func(v string) string { + if len(v) >= 5 { + return v[:5] + } + return v + } + req := scheduleRequest{ + Name: old.Name, + Enabled: &old.Enabled, + TimezoneMode: old.TimezoneMode, + ScheduleType: old.ScheduleType, + RunDate: old.RunDate, + EndDate: old.EndDate, + Weekdays: old.Weekdays, + StartTime: trimClock(old.StartTime), + EndTime: trimClock(old.EndTime), + StartImmediately: old.StartImmediately, + ProxyMode: old.ProxyMode, + ProxyPoolID: old.ProxyPoolID, + ProxyURL: old.ProxyURL, + TaskIDs: old.TaskIDs, + } + if a.Name != nil { + req.Name = *a.Name + } + if a.Enabled != nil { + req.Enabled = a.Enabled + } + if a.TimezoneMode != nil { + req.TimezoneMode = *a.TimezoneMode + } + if a.ScheduleType != nil { + req.ScheduleType = *a.ScheduleType + } + if a.RunDate != nil { + req.RunDate = *a.RunDate + } + if a.EndDate != nil { + req.EndDate = *a.EndDate + } + if a.Weekdays != nil { + req.Weekdays = *a.Weekdays + } + if a.StartTime != nil { + req.StartTime = *a.StartTime + } + if a.EndTime != nil { + req.EndTime = *a.EndTime + } + if a.StartImmediately != nil { + req.StartImmediately = *a.StartImmediately + } + if a.TaskIDs != nil { + ids, perr := parseInt64SliceFlexible(*a.TaskIDs) + if perr != nil { + return actool.Errorf(perr.Error()), nil + } + req.TaskIDs = ids + } + if a.ProxyMode != nil { + req.ProxyMode = *a.ProxyMode + } + if a.ProxyPoolID != nil { + req.ProxyPoolID = *a.ProxyPoolID + } + if a.ProxyURL != nil { + req.ProxyURL = *a.ProxyURL + } + + input := s.scheduleInput(req, old) + if err := s.validateScheduleProxy(&input, old); err != nil { + return actool.Errorf("代理配置无效: " + err.Error()), nil + } + item, err := s.m.pg.UpdateTaskSchedule(id, input) + if err != nil { + return actool.Errorf("更新计划任务失败: " + err.Error()), nil + } + s.applyScheduleProxyToTasks(item) + return jsonResult(s.scheduleDTO(item)) + }) +} + +func (s *Server) toolDeleteTaskSchedule() actool.CoreTool { + return wrTool("delete_task_schedule", + "删除指定的定时日历计划任务(不会删除其关联的任务本身)。", + objSchema(map[string]any{ + "schedule_id": strParam("要删除的计划任务 ID(必填)"), + }, "schedule_id"), + func(_ context.Context, in json.RawMessage) (actool.Result, error) { + if s.m.pg == nil { + return actool.Errorf("数据库未初始化"), nil + } + var a struct { + ScheduleID json.RawMessage `json:"schedule_id"` + } + if err := json.Unmarshal(in, &a); err != nil { + return actool.Errorf("参数无效: " + err.Error()), nil + } + id, ok := parseInt64Flexible(a.ScheduleID) + if !ok { + return actool.Errorf("schedule_id 无效"), nil + } + if _, err := s.m.pg.GetTaskSchedule(id); err != nil { + return actool.Errorf(fmt.Sprintf("计划任务 #%d 不存在", id)), nil + } + if err := s.m.pg.DeleteTaskSchedule(id); err != nil { + return actool.Errorf("删除计划任务失败: " + err.Error()), nil + } + return jsonResult(map[string]any{"deleted": true, "schedule_id": id}) + }) +} + +// seedScheduleToolBindings binds calendar schedule tools to chat agents ONCE +// on existing DBs so users can create/manage calendar schedules from chat. +func (s *Server) seedScheduleToolBindings() { + const flag = "schedule_tool_bindings_v1" + if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { + return + } + keys := []string{"list_task_schedules", "create_task_schedule", "update_task_schedule", "delete_task_schedule"} + for _, agentKey := range []string{"auto", "mainagent", "pentest"} { + if err := s.m.pg.AddAgentToToolBinding(agentKey, keys); err != nil { + log.Printf("[%s] 日历计划工具默认绑定失败: %v", agentKey, err) + return + } + } + _ = s.m.pg.SetSetting(flag, "true") +} diff --git a/server/schedule_tools_test.go b/server/schedule_tools_test.go new file mode 100644 index 0000000..9dc2a70 --- /dev/null +++ b/server/schedule_tools_test.go @@ -0,0 +1,169 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) +func TestChatMentionScheduleParsing(t *testing.T) { + refs, err := parseChatMentions("请修改 @[计划任务#3 夜间扫描] 和 @[schedule#3 重复] 以及 @[schedule#9 应急复测] 和 @[计划#12 周末巡检]") + if err != nil { + t.Fatalf("parseChatMentions error: %v", err) + } + if len(refs) != 3 { + t.Fatalf("expected 3 deduplicated schedule refs, got %+v", refs) + } + for i, wantID := range []int64{3, 9, 12} { + if refs[i].Kind != "schedule" || refs[i].ID != wantID { + t.Fatalf("ref[%d] = %+v, want schedule #%d", i, refs[i], wantID) + } + } +} + + +func TestChatScheduleToolsAndServerClock(t *testing.T) { + dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) + if dsn == "" { + t.Skip("requires ARTEX_PG_DSN") + } + pg, err := db.Open(dsn) + if err != nil { + t.Fatalf("open pg: %v", err) + } + defer pg.Close() + + m := &Manager{ + pg: pg, + dir: t.TempDir(), + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{ + active: "pool-1", + entries: []proxyPoolEntry{ + { + ProxyPoolEntry: ProxyPoolEntry{ID: "pool-1", Name: "Node1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"}, + RawURL: "http://127.0.0.1:19801", + }, + }, + }, + globalProxy: "http://127.0.0.1:19801", + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + task, err := m.CreateTask("calendar-chat-task", "test calendar creation from chat", nil, 0, 0) + if err != nil { + t.Fatalf("CreateTask: %v", err) + } + + // 1. Create schedule from chat tool with proxy_mode=pool. + createTool := s.toolCreateTaskSchedule() + in := fmt.Sprintf(`{"name":"工作日夜间扫描","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"18:00","end_time":"23:00","task_ids":[%q],"proxy_mode":"pool"}`, task.ID) + res, err := createTool.Call(context.Background(), json.RawMessage(in), nil) + if err != nil || res.IsError { + t.Fatalf("create_task_schedule failed: err=%v res=%+v", err, res) + } + text := "" + for _, b := range res.Content { + text += b.Text + } + var created map[string]any + if err := json.Unmarshal([]byte(text), &created); err != nil { + t.Fatalf("decode create_task_schedule: %v (%s)", err, text) + } + schedID := int64(created["id"].(float64)) + if created["proxy_mode"] != "pool" { + t.Fatalf("expected proxy_mode=pool, got %+v", created) + } + + // Verify bound task inherited proxy_mode=pool immediately. + view, _ := s.containerProxyRouteView("task", task.ID) + if view.Mode != "pool" { + t.Fatalf("expected task route mode=pool after create_task_schedule, got %+v", view) + } + + // 2. List schedules via HTTP GET /api/schedules -> verify top-level server_time & offset. + rec := httptest.NewRecorder() + s.listSchedules(rec, httptest.NewRequest(http.MethodGet, "/api/schedules", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("listSchedules: %d %s", rec.Code, rec.Body.String()) + } + var listResp map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &listResp); err != nil { + t.Fatalf("decode listSchedules: %v", err) + } + if listResp["server_time"] == "" || listResp["server_timezone"] == "" || listResp["server_utc_offset_minutes"] == nil { + t.Fatalf("expected server clock metadata in /api/schedules, got %+v", listResp) + } + + // 3. Update schedule via chat tool (partial update). + updTool := s.toolUpdateTaskSchedule() + updIn := fmt.Sprintf(`{"schedule_id":%d,"end_time":"23:45"}`, schedID) + updRes, err := updTool.Call(context.Background(), json.RawMessage(updIn), nil) + if err != nil || updRes.IsError { + t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes) + } + updText := "" + // 2b. Search schedule mentions via DB and compose @[schedule#ID] snapshot. + page, err := pg.SearchChatMentionsPage(context.Background(), "schedule", "工作日", "") + if err != nil { + t.Fatalf("SearchChatMentionsPage(schedule): %v", err) + } + foundMention := false + for _, item := range page.Items { + if item.Kind == "schedule" && item.ID == schedID { + foundMention = true + if !strings.Contains(item.Description, "18:00-23:45") { + t.Fatalf("expected schedule time window in mention description, got %+v", item) + } + } + } + if !foundMention { + t.Fatalf("expected schedule #%d in SearchChatMentionsPage results, got %+v", schedID, page.Items) + } + injected, err := composeChatMentionMessage(pg, fmt.Sprintf("把 @[schedule#%d 工作日夜间扫描] 改成 23:45 结束", schedID)) + if err != nil { + t.Fatalf("composeChatMentionMessage(schedule): %v", err) + } + if !strings.Contains(injected, "工作日夜间扫描") || !strings.Contains(injected, `"proxy_mode":"pool"`) || !strings.Contains(injected, `"server_time"`) { + t.Fatalf("unexpected injected schedule snapshot: %s", injected) + } + + for _, b := range updRes.Content { + updText += b.Text + } + if !strings.Contains(updText, "23:45") || !strings.Contains(updText, "工作日夜间扫描") { + t.Fatalf("unexpected update_task_schedule output: %s", updText) + } + + // 4. List via chat tool. + listTool := s.toolListTaskSchedules() + listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil) + if err != nil || listRes.IsError { + t.Fatalf("list_task_schedules failed: err=%v res=%+v", err, listRes) + } + listText := "" + for _, b := range listRes.Content { + listText += b.Text + } + if !strings.Contains(listText, `"server_time"`) || !strings.Contains(listText, "工作日夜间扫描") { + t.Fatalf("unexpected list_task_schedules output: %s", listText) + } + + // 5. Delete via chat tool. + delTool := s.toolDeleteTaskSchedule() + delRes, err := delTool.Call(context.Background(), json.RawMessage(fmt.Sprintf(`{"schedule_id":%d}`, schedID)), nil) + if err != nil || delRes.IsError { + t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes) + } + // Verify deleted schedule mention returns a clean input error. + if _, err := composeChatMentionMessage(pg, fmt.Sprintf("查看 @[schedule#%d 已删]", schedID)); err == nil { + t.Fatalf("expected error for deleted schedule mention") + } +} diff --git a/server/schedules.go b/server/schedules.go index aa6c972..af93552 100644 --- a/server/schedules.go +++ b/server/schedules.go @@ -23,6 +23,9 @@ type scheduleRequest struct { StartTime string `json:"start_time"` EndTime string `json:"end_time"` StartImmediately bool `json:"start_immediately"` + ProxyMode string `json:"proxy_mode,omitempty"` + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` TaskIDs []int64 `json:"task_ids"` } @@ -33,9 +36,105 @@ func (s *Server) scheduleInput(req scheduleRequest, existing *db.TaskSchedule) d } else if existing != nil { enabled = existing.Enabled } + proxyMode := strings.ToLower(strings.TrimSpace(req.ProxyMode)) + proxyPoolID := strings.TrimSpace(req.ProxyPoolID) + proxyURL := strings.TrimSpace(req.ProxyURL) + if proxyMode == "" { + if existing != nil && existing.ProxyMode != "" { + proxyMode = existing.ProxyMode + if proxyPoolID == "" && proxyURL == "" { + proxyPoolID = existing.ProxyPoolID + proxyURL = existing.ProxyURL + } + } else { + proxyMode = "inherit" + } + } return db.TaskScheduleInput{Name: req.Name, Enabled: enabled, TimezoneMode: req.TimezoneMode, ScheduleType: req.ScheduleType, RunDate: req.RunDate, EndDate: req.EndDate, Weekdays: req.Weekdays, StartTime: req.StartTime, EndTime: req.EndTime, - StartImmediately: req.StartImmediately, TaskIDs: req.TaskIDs} + StartImmediately: req.StartImmediately, ProxyMode: proxyMode, ProxyPoolID: proxyPoolID, ProxyURL: proxyURL, TaskIDs: req.TaskIDs} +} + +func (s *Server) validateScheduleProxy(in *db.TaskScheduleInput, existing *db.TaskSchedule) error { + inMode := strings.ToLower(strings.TrimSpace(in.ProxyMode)) + if inMode == "" { + inMode = "inherit" + } + inPoolID := strings.TrimSpace(in.ProxyPoolID) + inURL := strings.TrimSpace(in.ProxyURL) + + var prev *ContainerProxyRoute + if existing != nil { + oldMode := strings.ToLower(strings.TrimSpace(existing.ProxyMode)) + if oldMode == "" { + oldMode = "inherit" + } + oldPoolID := strings.TrimSpace(existing.ProxyPoolID) + oldURL := strings.TrimSpace(existing.ProxyURL) + prev = &ContainerProxyRoute{ + Mode: oldMode, + ProxyPoolID: oldPoolID, + ProxyURL: oldURL, + } + // Allow editing/rescheduling an existing plan without re-validating unchanged proxy routes + // (e.g. dragging a schedule whose proxy_mode is already "pool" when the live pool is temporarily empty). + if inMode == oldMode { + switch oldMode { + case "inherit", "direct", "pool": + in.ProxyMode = oldMode + in.ProxyPoolID = "" + in.ProxyURL = "" + return nil + case "proxy": + if oldPoolID != "" && inPoolID == oldPoolID && inURL == "" { + in.ProxyMode = "proxy" + in.ProxyPoolID = oldPoolID + in.ProxyURL = "" + return nil + } + if oldPoolID == "" && inPoolID == "" && oldURL != "" && (inURL == oldURL || strings.Contains(inURL, "***")) { + in.ProxyMode = "proxy" + in.ProxyPoolID = "" + in.ProxyURL = oldURL + return nil + } + } + } + } + norm, err := s.validateAndNormalizeProxyRoute(ProxyRouteInput{ + Mode: inMode, + ProxyPoolID: inPoolID, + ProxyURL: inURL, + }, prev) + if err != nil { + return err + } + in.ProxyMode = norm.Mode + in.ProxyPoolID = norm.ProxyPoolID + in.ProxyURL = norm.ProxyURL + return nil +} + +func (s *Server) applyScheduleProxyToTasks(item *db.TaskSchedule) { + if item == nil || len(item.TaskIDs) == 0 { + return + } + mode := strings.ToLower(strings.TrimSpace(item.ProxyMode)) + if mode == "" || mode == "inherit" { + return + } + req := ProxyRouteInput{ + Mode: mode, + ProxyPoolID: item.ProxyPoolID, + ProxyURL: item.ProxyURL, + Note: fmt.Sprintf("schedule #%d", item.ID), + } + for _, taskID := range item.TaskIDs { + if taskID <= 0 { + continue + } + _, _ = s.setContainerProxyRoute("task", strconv.FormatInt(taskID, 10), req) + } } func parseScheduleID(r *http.Request) (int64, error) { @@ -43,9 +142,23 @@ func parseScheduleID(r *http.Request) (int64, error) { } func (s *Server) scheduleDTO(item *db.TaskSchedule) map[string]any { - raw, _ := json.Marshal(item) + safe := *item + if safe.ProxyURL != "" { + safe.ProxyURL = maskSecrets(safe.ProxyURL) + } + raw, _ := json.Marshal(&safe) var dto map[string]any _ = json.Unmarshal(raw, &dto) + var routePtr *ContainerProxyRoute + if item.ProxyMode != "" && item.ProxyMode != "inherit" { + routePtr = &ContainerProxyRoute{ + Mode: item.ProxyMode, + ProxyPoolID: item.ProxyPoolID, + ProxyURL: item.ProxyURL, + } + } + eff, _ := s.effectiveProxyDisplay(routePtr) + dto["effective_proxy"] = eff window := evaluateScheduleWindow(item, time.Now()) if stats, err := s.m.pg.ScheduleRunStats(item.ID); err == nil { dto["run_count"] = stats.RunCount @@ -71,7 +184,13 @@ func (s *Server) listSchedules(w http.ResponseWriter, r *http.Request) { for _, item := range items { dtos = append(dtos, s.scheduleDTO(item)) } - writeJSON(w, 200, map[string]any{"schedules": dtos}) + srvTime, srvTZ, srvOffset := serverClockMeta(time.Now()) + writeJSON(w, 200, map[string]any{ + "schedules": dtos, + "server_time": srvTime, + "server_timezone": srvTZ, + "server_utc_offset_minutes": srvOffset, + }) } func (s *Server) getSchedule(w http.ResponseWriter, r *http.Request) { @@ -113,15 +232,21 @@ func (s *Server) createSchedule(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - item, err := s.m.pg.CreateTaskSchedule(s.scheduleInput(req, nil)) + input := s.scheduleInput(req, nil) + if err := s.validateScheduleProxy(&input, nil); err != nil { + writeProxyRouteErr(w, 400, err) + return + } + item, err := s.m.pg.CreateTaskSchedule(input) if err != nil { writeErr(w, 400, err.Error()) return } + s.applyScheduleProxyToTasks(item) if req.StartImmediately && item.Enabled { s.runScheduleTasks(item) } - writeJSON(w, 201, item) + writeJSON(w, 201, s.scheduleDTO(item)) } func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) { @@ -140,12 +265,18 @@ func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - item, err := s.m.pg.UpdateTaskSchedule(id, s.scheduleInput(req, old)) + input := s.scheduleInput(req, old) + if err := s.validateScheduleProxy(&input, old); err != nil { + writeProxyRouteErr(w, 400, err) + return + } + item, err := s.m.pg.UpdateTaskSchedule(id, input) if err != nil { writeErr(w, 400, err.Error()) return } - writeJSON(w, 200, item) + s.applyScheduleProxyToTasks(item) + writeJSON(w, 200, s.scheduleDTO(item)) } func (s *Server) deleteSchedule(w http.ResponseWriter, r *http.Request) { @@ -217,6 +348,7 @@ func (s *Server) runScheduleTasksNow(item *db.TaskSchedule) (int, []string) { } func (s *Server) startScheduleTasks(item *db.TaskSchedule, forceManualPause bool) (int, []string) { + s.applyScheduleProxyToTasks(item) started := 0 errors := []string{} for _, taskID := range item.TaskIDs { diff --git a/server/server.go b/server/server.go index 404e07c..f37817a 100644 --- a/server/server.go +++ b/server/server.go @@ -24,6 +24,7 @@ import ( "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/intercept/jev" + "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/llmpool" "github.com/Autumn-27/artex/llmrec" "github.com/Autumn-27/artex/report" @@ -143,8 +144,9 @@ type Server struct { proxyPoolTickMu sync.Mutex // proxyProbe is injectable for deterministic reconnect race tests. Production // servers leave it nil and use probeEgress directly. - proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult - side *sideQuestionState + proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult + proxyRoutes *proxyRouteRuntime + side *sideQuestionState } // provEntry is a cached provider + its config for one LLM profile id. @@ -169,6 +171,7 @@ type triggeredRun struct { taskDesc string // 任务描述(任务级,同任务相同);合并时只渲染一次 taskGoal string // 任务目标(任务级,同任务相同);合并时只渲染一次 mergeable bool // true for finding/goal event triggers (merge by taskID) + multiTask bool // true when mergeAllRuns combined events from multiple distinct tasks } func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDir string) *Server { @@ -282,9 +285,6 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi // 漏洞 IM 推送投递引擎。与 Scheduler 并列但独立:推送的实时性要求(3s) // 与触发器的业务节奏不同,且两者失败互不牵连——推送卡住不该影响 agent 触发。 go newNotifier(s).Run(s.ctx) - // Fill the tool cache for any enabled MCP that has none yet (notably the - // seeded browser MCP on first run). Async so it never blocks startup. - go s.discoverEmptyMCPsOnStartup() logSink.SetDB(ctx, m.pg) // restore last 100 log rows and enable async persistence } // precedence: persisted DB config > env. @@ -304,6 +304,12 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi log.Printf("[engine] no LLM provider configured — engine idle until set via /api/llm or env") } s.restoreTaskRuntimes() + s.initSandbox() + if m.pg != nil { + // Fill the tool cache for any enabled MCP (notably browser MCP) AFTER + // initSandbox so stdio discovery runs inside the sandbox container. + go s.discoverEmptyMCPsOnStartup() + } s.ensureProxySupervisor() s.proxyPoolWG.Add(1) go func() { defer s.proxyPoolWG.Done(); s.runProxyPoolSupervisor(s.ctx) }() @@ -323,13 +329,26 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi return s } -// Close waits for proxy pool supervision to stop before Manager closes the DB. +// Close waits for proxy pool supervision to stop and stops running sandboxes before DB close. func (s *Server) Close() { if s != nil { s.proxyPoolWG.Wait() + if s.proxyRoutes != nil { + s.proxyRoutes.mu.Lock() + gw := s.proxyRoutes.embeddedGW + s.proxyRoutes.embeddedGW = nil + s.proxyRoutes.mu.Unlock() + if gw != nil { + _ = gw.Close() + } + } + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + mgr.Shutdown(sctx) + cancel() + } } } - // Restored deadline and worker loops must inherit the same context as new tasks, // including the side-question checkpoint publisher installed during startup. func (s *Server) restoreTaskRuntimes() { @@ -989,6 +1008,11 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("DELETE /api/traffic/all", s.deleteAllTraffic) mux.HandleFunc("GET /api/traffic/exchange", s.getTrafficExchange) mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob) + mux.HandleFunc("GET /api/traffic/flows", s.getTrafficFlows) + mux.HandleFunc("GET /api/traffic/flows/{id}", s.getTrafficFlowDetail) + mux.HandleFunc("DELETE /api/traffic/flows", s.deleteTrafficFlows) + mux.HandleFunc("GET /api/traffic/dns", s.getTrafficDNS) + mux.HandleFunc("DELETE /api/traffic/dns", s.deleteTrafficDNS) mux.HandleFunc("GET /api/commands", s.pgListCommands) mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // 按工具聚合调用次数 mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords) @@ -1034,8 +1058,20 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("DELETE /api/settings/proxy-pool/{id}", s.deleteProxyPool) mux.HandleFunc("POST /api/settings/proxy-pool/{id}/test", s.testProxyPoolEntry) mux.HandleFunc("POST /api/settings/proxy-pool/test-all", s.testAllProxyPool) + mux.HandleFunc("GET /api/proxy/blacklist", s.getEgressBlacklist) + mux.HandleFunc("PUT /api/proxy/blacklist/settings", s.updateEgressBlacklistSettings) + mux.HandleFunc("POST /api/proxy/blacklist/rules", s.createEgressBlacklistRule) + mux.HandleFunc("PUT /api/proxy/blacklist/rules/{id}", s.updateEgressBlacklistRule) + mux.HandleFunc("DELETE /api/proxy/blacklist/rules/{id}", s.deleteEgressBlacklistRule) + mux.HandleFunc("DELETE /api/proxy/blacklist/events", s.clearEgressBlockEvents) + mux.HandleFunc("GET /api/proxy/routes", s.getProxyRoutes) + mux.HandleFunc("GET /api/proxy/routes/{scope}/{owner_id}", s.getProxyRoute) + mux.HandleFunc("PUT /api/proxy/routes/{scope}/{owner_id}", s.putProxyRoute) + mux.HandleFunc("DELETE /api/proxy/routes/{scope}/{owner_id}", s.deleteProxyRoute) + mux.HandleFunc("PUT /api/proxy/gateway/settings", s.updateGatewaySettings) + mux.HandleFunc("GET /api/internal/gateway/policy", s.getGatewayPolicy) + mux.HandleFunc("POST /api/internal/gateway/events", s.postGatewayEvents) mux.HandleFunc("POST /api/settings/proxy-pool/{id}/activate", s.activateProxyPool) - mux.HandleFunc("POST /api/tasks/{id}/proxy/test", s.testTaskProxy) mux.HandleFunc("GET /api/report", s.getReport) mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions) mux.HandleFunc("POST /api/chat", s.chat) @@ -1167,6 +1203,20 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("PUT /api/intercept/judge", s.interceptSetJudgeConfig) mux.HandleFunc("GET /api/intercept/judge/usage", s.interceptJudgeUsage) // 兜底审批累计 token 用量 + // 沙箱容器隔离状态、配置与启停管理 + mux.HandleFunc("GET /api/sandbox/status", s.sandboxStatus) + mux.HandleFunc("PUT /api/sandbox/settings", s.updateSandboxSettings) + mux.HandleFunc("POST /api/sandbox/prune", s.pruneSandboxContainers) + mux.HandleFunc("GET /api/sandbox/containers/{scope}/{id}", s.getSandboxContainer) + mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/start", s.startSandboxContainer) + mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/stop", s.stopSandboxContainer) + mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/recreate", s.recreateSandboxContainer) + mux.HandleFunc("DELETE /api/sandbox/containers/{scope}/{id}", s.removeSandboxContainer) + mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.getTaskSandbox) + mux.HandleFunc("POST /api/tasks/{id}/sandbox/start", s.startTaskSandbox) + mux.HandleFunc("POST /api/tasks/{id}/sandbox/stop", s.stopTaskSandbox) + mux.HandleFunc("POST /api/tasks/{id}/sandbox/recreate", s.recreateTaskSandbox) + // /api/* goes through CORS + JWT; everything else is served by the embedded // frontend (no JWT required; the optional Basic Auth gate wraps both). With the // no-embed build the webui handler just 404s (run `next dev` separately). @@ -1180,9 +1230,8 @@ func (s *Server) Handler() http.Handler { top := http.NewServeMux() top.HandleFunc(mcpEndpointPath, s.serveMCP) top.Handle("/", s.requireBasicAuth(root)) - return top + return s.blockSandboxAdminAccess(top) } - // --- handlers --- // health requires the optional Basic Auth gate but no admin JWT, and exposes no application fingerprints. @@ -1296,6 +1345,7 @@ func (s *Server) listTasks(w http.ResponseWriter, r *http.Request) { dto := taskDTO(t, s.resolvedTaskStatus(t)) dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t) applyTaskArchiveBlocker(&dto, archiveBlockers) + s.applyTaskProxyDTO(&dto) metric := metrics[t.ExpID] dto.Tokens = tokenTotalDTO(metric.Tokens) // prefer the live in-memory heartbeat (fresher) and fall back to the @@ -1775,6 +1825,7 @@ type createTaskReq struct { WorkerCount int `json:"worker_count,omitempty"` // 本任务 Worker 数;0/省略=用全局默认;上限50 // InterceptRules 任务级资产拦截/允许规则(创建时录入,存 task_intercept_rules,不进全局表)。 InterceptRules []taskInterceptRuleReq `json:"intercept_rules,omitempty"` + ProxyRoute *ProxyRouteInput `json:"proxy_route,omitempty"` // 任务容器出口代理配置(inherit/direct/pool/proxy) } // taskCreateError is a rejected task creation: an HTTP-style status plus a @@ -1782,6 +1833,8 @@ type createTaskReq struct { type taskCreateError struct { Status int Msg string + Code string + Params map[string]any } func (s *Server) createTask(w http.ResponseWriter, r *http.Request) { @@ -1792,10 +1845,16 @@ func (s *Server) createTask(w http.ResponseWriter, r *http.Request) { } t, cerr := s.createTaskFromRequest(req) if cerr != nil { - writeErr(w, cerr.Status, cerr.Msg) + if cerr.Code != "" { + writeProductError(w, cerr.Status, cerr.Code, cerr.Msg, cerr.Params) + } else { + writeErr(w, cerr.Status, cerr.Msg) + } return } - writeJSON(w, 201, taskDTO(t, s.resolvedTaskStatus(t))) + dto := taskDTO(t, s.resolvedTaskStatus(t)) + s.applyTaskProxyDTO(&dto) + writeJSON(w, 201, dto) } // createTaskFromRequest validates a creation request, stores the task and @@ -1809,57 +1868,92 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr req.LLMProfileIDs = []int64{*req.LLMProfileID} } if err := s.validateTaskProfileIDs(req.LLMProfileIDs); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if err := db.NormalizeNoResultOptions(&db.TaskCreateOptions{NoResultSeconds: req.NoResultSeconds, NoResultMinFindings: req.NoResultMinFindings, NoResultMinSeverity: req.NoResultMinSeverity}); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if req.TimeoutSeconds < 0 { req.TimeoutSeconds = 0 } if len(req.SourceTaskIDs) > db.MaxTaskSourceCount { - return nil, &taskCreateError{400, fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)} } sourceIDs := make([]int64, 0, len(req.SourceTaskIDs)) seenSources := map[int64]bool{} for _, raw := range req.SourceTaskIDs { id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) if err != nil || id <= 0 || seenSources[id] { - return nil, &taskCreateError{400, "关联任务 id 无效或重复"} + return nil, &taskCreateError{Status: 400, Msg: "关联任务 id 无效或重复"} } if _, ok := s.m.Task(strconv.FormatInt(id, 10)); !ok { - return nil, &taskCreateError{400, fmt.Sprintf("关联任务 #%d 不存在", id)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务 #%d 不存在", id)} } seenSources[id] = true sourceIDs = append(sourceIDs, id) } companyIDs, err := db.NormalizeTaskCompanyIDs(req.CompanyIDs) if err != nil { - return nil, &taskCreateError{400, fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)} } req.CompanyIDs = companyIDs interceptRules, err := buildTaskInterceptRules(req.InterceptRules) if err != nil { - return nil, &taskCreateError{400, "任务级拦截规则无效:" + err.Error()} + return nil, &taskCreateError{Status: 400, Msg: "任务级拦截规则无效:" + err.Error()} } var schedule *db.TaskScheduleInput if req.Schedule != nil { input := s.scheduleInput(*req.Schedule, nil) input.TaskIDs = nil if err := db.ValidateTaskScheduleInput(input); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} + } + if err := s.validateScheduleProxy(&input, nil); err != nil { + if verr, ok := err.(*proxyRouteValidationError); ok { + return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params} + } + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } schedule = &input } + var validatedProxy *ProxyRouteInput + if req.ProxyRoute != nil { + norm, err := s.validateAndNormalizeProxyRoute(*req.ProxyRoute, nil) + if err != nil { + if verr, ok := err.(*proxyRouteValidationError); ok { + return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params} + } + return nil, &taskCreateError{Status: 400, Msg: "任务代理配置无效:" + err.Error()} + } + if norm.Mode != "inherit" { + validatedProxy = &ProxyRouteInput{ + Mode: norm.Mode, + ProxyPoolID: norm.ProxyPoolID, + ProxyURL: norm.ProxyURL, + Note: norm.Note, + } + } + } else if schedule != nil && schedule.ProxyMode != "" && schedule.ProxyMode != "inherit" { + validatedProxy = &ProxyRouteInput{ + Mode: schedule.ProxyMode, + ProxyPoolID: schedule.ProxyPoolID, + ProxyURL: schedule.ProxyURL, + } + } + if validatedProxy != nil && schedule != nil && (schedule.ProxyMode == "" || schedule.ProxyMode == "inherit") { + schedule.ProxyMode = validatedProxy.Mode + schedule.ProxyPoolID = validatedProxy.ProxyPoolID + schedule.ProxyURL = validatedProxy.ProxyURL + } remark, err := normalizeRemark(req.Remark) if err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if req.WorkerCount < 0 { - return nil, &taskCreateError{400, "Worker 运行数量不能为负数"} + return nil, &taskCreateError{Status: 400, Msg: "Worker 运行数量不能为负数"} } if req.WorkerCount > db.MaxTaskWorkerCount { - return nil, &taskCreateError{400, fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)} } t, err := s.m.CreateTaskWithOptions(req.Description, req.Goal, db.TaskCreateOptions{ Schedule: schedule, @@ -1875,12 +1969,24 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr }) if err != nil { if errors.Is(err, db.ErrTaskCategoryInvalid) || errors.Is(err, db.ErrTaskCategoryNotFound) { - return nil, &taskCreateError{400, "任务分类不存在或无效"} + return nil, &taskCreateError{Status: 400, Msg: "任务分类不存在或无效"} } if errors.Is(err, db.ErrTaskCompanyIDsInvalid) || errors.Is(err, db.ErrTaskCompanyNotFound) { - return nil, &taskCreateError{400, "关联企业不存在或无效"} + return nil, &taskCreateError{Status: 400, Msg: "关联企业不存在或无效"} + } + return nil, &taskCreateError{Status: 500, Msg: err.Error()} + } + if newDesc, newGoal, copied := transferDraftUploadsToTask(s.m.dir, t.ID, req.Description, req.Goal); copied > 0 { + req.Description, req.Goal = newDesc, newGoal + t.Description, t.Goal = newDesc, newGoal + if id, e := strconv.ParseInt(t.ID, 10, 64); e == nil && s.m.pg != nil { + _, _ = s.m.pg.Exec(`UPDATE tasks SET description=$2, goal=$3 WHERE id=$1`, id, newDesc, newGoal) + } + } + if validatedProxy != nil { + if _, err := s.setContainerProxyRoute("task", t.ID, *validatedProxy); err != nil { + log.Printf("[task] 新建任务 #%s 应用代理路由失败: %v", t.ID, err) } - return nil, &taskCreateError{500, err.Error()} } log.Printf("[task] 新建任务 #%s «%s» 目标: %s", t.ID, req.Description, req.Goal) // 共享的建后流程(seed + 种子意图 + 后台目标分解 + engine.Run),与 spawn_task 复用同一段。 @@ -2097,9 +2203,23 @@ func (s *Server) getTask(w http.ResponseWriter, r *http.Request) { dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t) archiveBlockers, _ := s.m.PG().TaskArchiveBlockers() applyTaskArchiveBlocker(&dto, archiveBlockers) + s.applyTaskProxyDTO(&dto) writeJSON(w, 200, dto) } +func (s *Server) applyTaskProxyDTO(dto *TaskDTO) { + if dto == nil || dto.ID == "" { + return + } + item, _ := s.containerProxyRouteView("task", dto.ID) + dto.ProxyRoute = &TaskProxyRouteDTO{ + Mode: item.Mode, + ProxyPoolID: item.ProxyPoolID, + ProxyURL: item.ProxyURL, + EffectiveProxy: item.EffectiveProxy, + } +} + // taskCoverage returns a task's rough asset test coverage (denominator/tested/backlog). func (s *Server) taskCoverage(w http.ResponseWriter, r *http.Request) { t, ok := s.m.Task(r.PathValue("id")) @@ -3681,15 +3801,16 @@ func taskActivityDetail(t *Task, seq int64) (string, error) { func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) { tr := s.m.Traffic() if tr == nil { - writeJSON(w, 200, map[string]any{"enabled": false, "exchanges": []any{}}) + writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "exchanges": []any{}}) return } q := r.URL.Query() page := atoiDefault(q.Get("page"), 0) size := atoiDefault(q.Get("size"), 100) var taskHosts []string + var rawTaskID string taskScoped := false - if rawTaskID := strings.TrimSpace(q.Get("task_id")); rawTaskID != "" { + if rawTaskID = strings.TrimSpace(q.Get("task_id")); rawTaskID != "" { taskScoped = true taskID, err := strconv.ParseInt(rawTaskID, 10, 64) if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil { @@ -3702,25 +3823,25 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) { return } } - if taskScoped && len(taskHosts) == 0 { - writeJSON(w, 200, map[string]any{ - "enabled": s.m.TrafficEnabled(), "proxy": s.m.ProxyAddr(), "count": 0, - "total": 0, "page": page, "size": size, "exchanges": []any{}, - }) - return - } + intentID, _ := strconv.ParseInt(strings.TrimSpace(q.Get("intent_id")), 10, 64) pageQuery := traffic.PageQuery{ - Hosts: taskHosts, - Host: q.Get("host"), - Method: q.Get("method"), - Query: q.Get("q"), - Body: q.Get("body"), - Path: q.Get("path"), - Status: q.Get("status"), - RespMin: int64(atoiDefault(q.Get("resp_min"), -1)), - RespMax: int64(atoiDefault(q.Get("resp_max"), -1)), - Sort: q.Get("sort"), - Order: q.Get("order"), + Hosts: taskHosts, + OwnerTaskID: rawTaskID, + SandboxScope: q.Get("scope"), + SandboxOwnerID: q.Get("owner_id"), + ContainerID: q.Get("container_id"), + SessionID: q.Get("session_id"), + IntentID: intentID, + Host: q.Get("host"), + Method: q.Get("method"), + Query: q.Get("q"), + Body: q.Get("body"), + Path: q.Get("path"), + Status: q.Get("status"), + RespMin: int64(atoiDefault(q.Get("resp_min"), -1)), + RespMax: int64(atoiDefault(q.Get("resp_max"), -1)), + Sort: q.Get("sort"), + Order: q.Get("order"), } ex, matched, _ := tr.Page(pageQuery, page, size) count, _ := tr.Count() // global total, for the stat card @@ -3731,6 +3852,7 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) { } writeJSON(w, 200, map[string]any{ "enabled": s.m.TrafficEnabled(), // reflect the capture toggle + "store_error_traffic": s.storeErrorTrafficEnabled(), "proxy": s.m.ProxyAddr(), "count": count, // total recorded (unfiltered) "total": matched, // rows matching the current filter (for pagination) @@ -3749,7 +3871,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) { return } var hosts []string - if rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id")); rawTaskID != "" { + rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id")) + if rawTaskID != "" { taskID, err := strconv.ParseInt(rawTaskID, 10, 64) if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil { writeErr(w, http.StatusNotFound, "task not found") @@ -3763,10 +3886,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) { } var result []traffic.HostCount var err error - if len(hosts) > 0 { - result, err = tr.HostsForScope(hosts) - } else if r.URL.Query().Get("task_id") != "" { - result = []traffic.HostCount{} + if rawTaskID != "" { + result, err = tr.HostsForTask(rawTaskID, hosts) } else { result, err = tr.Hosts() } @@ -4616,12 +4737,18 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) { // 把上传附件的【绝对路径】清单拼进发给 agent 的消息,它据此用 Read/Bash 打开文件。 // taskDir = agent 的工作目录(CWD),与 chatUpload 落盘、ensureRunDir 一致。 taskDir := filepath.Join(s.m.dir, "tasks", t.ID) - agentMsg := composeAgentMessage(agentMessage, req.Attachments, taskDir) + attachDir := taskDir + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { + attachDir = sandbox.ContainerWorkDir + } + agentMsg := composeAgentMessage(agentMessage, req.Attachments, attachDir) s.engine.BeginLLMCall(t.ID) _, err := ma.Chat(ctx, maTaskID, mainSeg, s.m.Assets(), t.Store, t.Goal, agentMsg, emit, t.Notify, resume, t.NotifyGoal, t.NotifyHint) s.engine.EndLLMCall(t.ID) + if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && s.resolvedTaskStatus(t) != "running" { + mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}) + } if err != nil && ctx.Err() == nil { - s.engine.emitActivity(t, db.Activity{Worker: "mainagent", Kind: "text", IsError: true, Summary: "(主 Agent 出错:" + err.Error() + ")", MainSeg: segPtr}) } }() writeJSON(w, 202, map[string]any{"status": "accepted", "mode": "llm"}) diff --git a/server/task_intercept.go b/server/task_intercept.go index 73b209e..81f2ade 100644 --- a/server/task_intercept.go +++ b/server/task_intercept.go @@ -101,6 +101,7 @@ func (s *Server) taskInterceptCreateRule(w http.ResponseWriter, r *http.Request) writeErr(w, 500, err.Error()) return } + taskEgressRulesCache.Delete(taskID) writeJSON(w, 200, rule) } @@ -133,6 +134,7 @@ func (s *Server) taskInterceptUpdateRule(w http.ResponseWriter, r *http.Request) writeErr(w, 500, err.Error()) return } + taskEgressRulesCache.Delete(taskID) writeJSON(w, 200, rule) } @@ -156,6 +158,7 @@ func (s *Server) taskInterceptDeleteRule(w http.ResponseWriter, r *http.Request) writeErr(w, 500, err.Error()) return } + taskEgressRulesCache.Delete(taskID) writeJSON(w, 200, map[string]any{"deleted": deleted}) } @@ -185,5 +188,6 @@ func (s *Server) taskInterceptToggleRule(w http.ResponseWriter, r *http.Request) writeErr(w, 500, err.Error()) return } + taskEgressRulesCache.Delete(taskID) writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled}) } diff --git a/server/traffic_flows.go b/server/traffic_flows.go new file mode 100644 index 0000000..d865203 --- /dev/null +++ b/server/traffic_flows.go @@ -0,0 +1,159 @@ +package server + +import ( + "net/http" + "strings" + + "github.com/Autumn-27/artex/traffic" +) + +// GET /api/traffic/flows +func (s *Server) getTrafficFlows(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "flows": []any{}, "total": 0, "count": 0}) + return + } + q := r.URL.Query() + page := atoiDefault(q.Get("page"), 0) + size := atoiDefault(q.Get("size"), 100) + rawTaskID := strings.TrimSpace(q.Get("task_id")) + if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil { + writeErr(w, http.StatusNotFound, "task not found") + return + } + rows, total, err := tr.PageNetFlows(traffic.NetFlowQuery{ + Protocol: q.Get("protocol"), + Action: q.Get("action"), + OwnerTaskID: rawTaskID, + SandboxScope: q.Get("scope"), + SandboxOwnerID: q.Get("owner_id"), + ContainerID: q.Get("container_id"), + Query: q.Get("q"), + }, page, size) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + count, _ := tr.CountNetFlows() + if rawTaskID != "" { + count = total + } + writeJSON(w, 200, map[string]any{ + "enabled": s.m.TrafficEnabled(), + "store_error_traffic": s.storeErrorTrafficEnabled(), + "count": count, + "total": total, + "page": page, + "size": size, + "flows": rows, + }) +} + +// GET /api/traffic/flows/{id} +func (s *Server) getTrafficFlowDetail(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeErr(w, http.StatusNotFound, "traffic disabled") + return + } + id := strings.TrimSpace(r.PathValue("id")) + if id == "" { + writeErr(w, http.StatusBadRequest, "missing id") + return + } + flow, err := tr.GetNetFlow(id) + if err != nil { + writeErr(w, http.StatusNotFound, err.Error()) + return + } + writeJSON(w, 200, flow) +} + +// DELETE /api/traffic/flows +func (s *Server) deleteTrafficFlows(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeErr(w, http.StatusNotFound, "traffic disabled") + return + } + q := r.URL.Query() + scope := strings.TrimSpace(q.Get("scope")) + ownerID := strings.TrimSpace(q.Get("owner_id")) + if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" { + scope = "task" + ownerID = tid + } + n, err := tr.DeleteNetFlows(scope, ownerID) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"deleted": n}) +} + +// GET /api/traffic/dns +func (s *Server) getTrafficDNS(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "queries": []any{}, "total": 0, "count": 0}) + return + } + q := r.URL.Query() + page := atoiDefault(q.Get("page"), 0) + size := atoiDefault(q.Get("size"), 100) + rawTaskID := strings.TrimSpace(q.Get("task_id")) + if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil { + writeErr(w, http.StatusNotFound, "task not found") + return + } + rows, total, err := tr.PageDNSQueries(traffic.DNSQueryFilter{ + QType: q.Get("qtype"), + RCode: q.Get("rcode"), + Action: q.Get("action"), + OwnerTaskID: rawTaskID, + SandboxScope: q.Get("scope"), + SandboxOwnerID: q.Get("owner_id"), + ContainerID: q.Get("container_id"), + Query: q.Get("q"), + }, page, size) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + count, _ := tr.CountDNSQueries() + if rawTaskID != "" { + count = total + } + writeJSON(w, 200, map[string]any{ + "enabled": s.m.TrafficEnabled(), + "store_error_traffic": s.storeErrorTrafficEnabled(), + "count": count, + "total": total, + "page": page, + "size": size, + "queries": rows, + }) +} + +// DELETE /api/traffic/dns +func (s *Server) deleteTrafficDNS(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeErr(w, http.StatusNotFound, "traffic disabled") + return + } + q := r.URL.Query() + scope := strings.TrimSpace(q.Get("scope")) + ownerID := strings.TrimSpace(q.Get("owner_id")) + if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" { + scope = "task" + ownerID = tid + } + n, err := tr.DeleteDNSQueries(scope, ownerID) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"deleted": n}) +} diff --git a/server/update_settings.go b/server/update_settings.go index 56f1c05..46b771a 100644 --- a/server/update_settings.go +++ b/server/update_settings.go @@ -25,6 +25,9 @@ func (cfg *updateSettings) validate() error { func (s *Server) loadUpdateSettings() (updateSettings, error) { cfg := updateSettings{} + if s.m == nil || s.m.pg == nil { + return cfg, nil + } raw, ok, err := s.m.pg.GetSetting(updateSettingsKey) if err != nil { return cfg, fmt.Errorf("读取更新网络设置失败: %w", err) diff --git a/server/workspace.go b/server/workspace.go index 74b99bf..82a583f 100644 --- a/server/workspace.go +++ b/server/workspace.go @@ -10,8 +10,9 @@ import ( "sort" "strings" "time" -) + "github.com/Autumn-27/artex/internal/sandbox" +) // Workspace file manager — browse / view / edit / download / upload / delete the // shared work dir (s.m.dir), where all agents write their artifacts. Every path is // confined to the work dir root (traversal via ".." is neutralised). All routes sit @@ -33,7 +34,12 @@ func (s *Server) wsResolve(rel string) (string, bool) { if abs != base && !strings.HasPrefix(abs, base+string(os.PathSeparator)) { return "", false } - return abs, true + // Block symlink escapes planted by a compromised sandbox container. + resolved, ok := sandbox.CheckPathWithinRoot(base, abs) + if !ok { + return "", false + } + return resolved, true } // wsRel renders an absolute path back as a workspace-relative path (forward slashes). @@ -226,9 +232,11 @@ func (s *Server) wsPreview(w http.ResponseWriter, r *http.Request) { if filepath.IsAbs(rawPath) { base := filepath.Clean(s.m.dir) candidate := filepath.Clean(rawPath) - ok = candidate == base || strings.HasPrefix(candidate, base+string(os.PathSeparator)) - if ok { - abs = candidate + if resolved, within := sandbox.CheckPathWithinRoot(base, candidate); within { + abs = resolved + ok = true + } else { + ok = false } } if !ok { diff --git a/traffic/attribution.go b/traffic/attribution.go new file mode 100644 index 0000000..38236f3 --- /dev/null +++ b/traffic/attribution.go @@ -0,0 +1,292 @@ +package traffic + +import ( + "crypto/subtle" + "encoding/base64" + "net" + "net/http" + "net/url" + "strconv" + "strings" + + mproxy "github.com/lqqyt2423/go-mitmproxy/proxy" +) +// SourceIdentity identifies which sandbox container / task / chat / intent +// originated a proxied request (#218 Phase 2). +type SourceIdentity struct { + Scope string `json:"sandbox_scope,omitempty"` + OwnerID string `json:"sandbox_owner_id,omitempty"` + ContainerID string `json:"container_id,omitempty"` + SessionID string `json:"session_id,omitempty"` + IntentID int64 `json:"intent_id,omitempty"` + SrcIP string `json:"src_ip,omitempty"` +} + +// SourceResolver maps an unforgeable client source IP to its sandbox identity. +type SourceResolver func(srcIP string) (SourceIdentity, bool) + +// TaskBlacklistChecker evaluates task-scoped egress rules for a attributed task. +// Returning a non-empty reason blocks the request. +type TaskBlacklistChecker func(taskID, rawHost, scheme string) (reason, pattern string) + +const proxyContextUserPrefix = "artexctx_" + +// FormatProxyContextURL embeds a fine-grained observability tag (session_id / +// intent_id / host-side scope+owner) as HTTP Basic Proxy-Authorization userinfo. +// The recording proxy parses and strips this header before forwarding upstream +// so it never reaches target servers. +func FormatProxyContextURL(baseProxyURL string, id SourceIdentity) string { + baseProxyURL = strings.TrimSpace(baseProxyURL) + if baseProxyURL == "" { + return "" + } + u, err := url.Parse(baseProxyURL) + if err != nil { + return baseProxyURL + } + // Preserve any pre-existing proxy auth; only tag untagged local/sandbox URLs. + if u.User != nil { + return baseProxyURL + } + q := url.Values{} + if id.Scope != "" { + q.Set("sc", id.Scope) + } + if id.OwnerID != "" { + q.Set("ow", id.OwnerID) + } + if id.SessionID != "" { + q.Set("sid", id.SessionID) + } + if id.IntentID > 0 { + q.Set("iid", strconv.FormatInt(id.IntentID, 10)) + } + if len(q) == 0 { + return baseProxyURL + } + u.User = url.UserPassword(proxyContextUserPrefix+q.Encode(), "x") + return u.String() +} + +// parseAndStripProxyContext extracts our internal Proxy-Authorization context +// tag (if present) and deletes the header so it is never forwarded to targets. +func parseAndStripProxyContext(h http.Header) (SourceIdentity, string, bool) { + if h == nil { + return SourceIdentity{}, "", false + } + raw := strings.TrimSpace(h.Get("Proxy-Authorization")) + if raw == "" { + return SourceIdentity{}, "", false + } + if !strings.HasPrefix(strings.ToLower(raw), "basic ") { + return SourceIdentity{}, "", false + } + dec, err := base64.StdEncoding.DecodeString(strings.TrimSpace(raw[6:])) + if err != nil { + return SourceIdentity{}, "", false + } + user, pwd, ok := strings.Cut(string(dec), ":") + if !ok || !strings.HasPrefix(user, proxyContextUserPrefix) { + return SourceIdentity{}, "", false + } + // Strip our internal observability header before forwarding upstream. + h.Del("Proxy-Authorization") + vals, err := url.ParseQuery(strings.TrimPrefix(user, proxyContextUserPrefix)) + if err != nil { + return SourceIdentity{}, "", false + } + var id SourceIdentity + id.Scope = strings.TrimSpace(vals.Get("sc")) + id.OwnerID = strings.TrimSpace(vals.Get("ow")) + id.ContainerID = strings.TrimSpace(vals.Get("cid")) + id.SrcIP = normalizeIPString(vals.Get("sip")) + id.SessionID = strings.TrimSpace(vals.Get("sid")) + if rawIID := strings.TrimSpace(vals.Get("iid")); rawIID != "" { + if n, err := strconv.ParseInt(rawIID, 10, 64); err == nil && n > 0 { + id.IntentID = n + } + } + return id, pwd, true +} + +// SetSourceResolver installs a real-time container source IP -> SourceIdentity +// lookup function on the recording proxy. +func (t *Traffic) SetSourceResolver(fn SourceResolver) { + if t == nil { + return + } + t.attrMu.Lock() + t.sourceResolver = fn + t.attrMu.Unlock() +} + +// SetTaskBlacklistChecker installs an optional per-task egress rule evaluator +// consulted when a request is hard-attributed to a task container. +func (t *Traffic) SetTaskBlacklistChecker(fn TaskBlacklistChecker) { + if t == nil { + return + } + t.attrMu.Lock() + t.taskBlacklistFn = fn + t.attrMu.Unlock() +} + +// resolveSource combines Layer 1 (unforgeable container source IP) with Layer 2 +// (stripped Proxy-Authorization observability tags). Security boundary: when +// srcIP maps to a sandbox container, Scope/OwnerID/ContainerID come strictly +// from the source IP; Proxy-Authorization can only enrich SessionID/IntentID. +// For loopback host-process callers (WebFetch/enrich), Scope/OwnerID from the +// tag are accepted as well. +func (t *Traffic) resolveSource(srcIP string, h http.Header) SourceIdentity { + return t.resolveSourceWithTag(srcIP, h, SourceIdentity{}, "", false) +} + +type connAttrEntry struct { + tag SourceIdentity + pwd string +} + +func (t *Traffic) resolveSourceForConn(remoteAddr string, h http.Header) SourceIdentity { + tag, pwd, hasTag := parseAndStripProxyContext(h) + if hasTag && remoteAddr != "" && t != nil { + t.connAttr.Store(remoteAddr, connAttrEntry{tag: tag, pwd: pwd}) + } else if !hasTag && remoteAddr != "" && t != nil { + if v, ok := t.connAttr.Load(remoteAddr); ok { + switch saved := v.(type) { + case connAttrEntry: + tag = saved.tag + pwd = saved.pwd + hasTag = true + case SourceIdentity: + tag = saved + hasTag = true + } + } + } + return t.resolveSourceWithTag(remoteAddr, nil, tag, pwd, hasTag) +} + +func (t *Traffic) resolveSourceWithTag(rawRemote string, h http.Header, tag SourceIdentity, pwd string, hasTag bool) SourceIdentity { + srcIP := normalizeIPString(rawRemote) + if h != nil { + if parsed, parsedPwd, ok := parseAndStripProxyContext(h); ok { + tag = parsed + pwd = parsedPwd + hasTag = true + } + } + + var out SourceIdentity + out.SrcIP = srcIP + + if t != nil && srcIP != "" { + t.attrMu.RLock() + resolver := t.sourceResolver + gwTok := t.gatewayToken + t.attrMu.RUnlock() + if resolver != nil { + if hard, ok := resolver(srcIP); ok { + out.Scope = hard.Scope + out.OwnerID = hard.OwnerID + out.ContainerID = hard.ContainerID + if hasTag { + out.SessionID = tag.SessionID + out.IntentID = tag.IntentID + } + return out + } + } + // Transparent gateway forwarding (loopback OR via docker-proxy bridge IP + // when authenticated by ARTEX_GATEWAY_TOKEN): trust forwarded SrcIP/ContainerID + // so transparent HTTP/TLS keeps exact sandbox container attribution. + gwAuthed := gwTok != "" && len(pwd) == len(gwTok) && subtle.ConstantTimeCompare([]byte(pwd), []byte(gwTok)) == 1 + if hasTag && tag.SrcIP != "" && (gwAuthed || (gwTok == "" && isLoopbackIPString(srcIP))) { + out.SrcIP = tag.SrcIP + if resolver != nil { + if hard, ok := resolver(tag.SrcIP); ok { + out.Scope = hard.Scope + out.OwnerID = hard.OwnerID + out.ContainerID = hard.ContainerID + out.SessionID = tag.SessionID + out.IntentID = tag.IntentID + return out + } + } + out.Scope = tag.Scope + out.OwnerID = tag.OwnerID + out.ContainerID = tag.ContainerID + out.SessionID = tag.SessionID + out.IntentID = tag.IntentID + return out + } + } + // Host-process loopback callers (e.g. WebFetch) may supply full tags. + if hasTag && isLoopbackIPString(srcIP) { + out.Scope = tag.Scope + out.OwnerID = tag.OwnerID + out.ContainerID = tag.ContainerID + if tag.SrcIP != "" { + out.SrcIP = tag.SrcIP + } + out.SessionID = tag.SessionID + out.IntentID = tag.IntentID + } + return out +} + +func flowClientAddr(f *mproxy.Flow) string { + if f == nil { + return "" + } + return connClientAddr(f.ConnContext) +} + +func connClientAddr(connCtx *mproxy.ConnContext) string { + if connCtx == nil || connCtx.ClientConn == nil || connCtx.ClientConn.Conn == nil || connCtx.ClientConn.Conn.RemoteAddr() == nil { + return "" + } + return connCtx.ClientConn.Conn.RemoteAddr().String() +} + +func normalizeIPString(raw string) string { + h, _ := splitHostAndPort(raw) + h = strings.Trim(strings.TrimSpace(h), "[]") + if ip := net.ParseIP(h); ip != nil { + return normalizeIP(ip).String() + } + return h +} + +func isLoopbackIPString(raw string) bool { + if raw == "" { + return true + } + ip := net.ParseIP(raw) + return ip != nil && ip.IsLoopback() +} + +// checkOutboundForSource runs built-in SSRF guard, global/synced egress +// blacklist, and (when attributed to a task) task-scoped egress rules. +func (t *Traffic) checkOutboundForSource(rawHost, scheme string, src SourceIdentity) *blockMatch { + if m := t.checkOutboundDestination(rawHost, scheme); m != nil { + return m + } + if t == nil || src.Scope != "task" || src.OwnerID == "" { + return nil + } + t.attrMu.RLock() + fn := t.taskBlacklistFn + t.attrMu.RUnlock() + if fn == nil { + return nil + } + if reason, pat := fn(src.OwnerID, rawHost, scheme); reason != "" { + return &blockMatch{ + Reason: reason, + RuleKind: "task_intercept", + Pattern: pat, + Source: "asset_intercept", + } + } + return nil +} diff --git a/traffic/attribution_test.go b/traffic/attribution_test.go new file mode 100644 index 0000000..c5a22db --- /dev/null +++ b/traffic/attribution_test.go @@ -0,0 +1,296 @@ +package traffic + +import ( + "database/sql" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestFormatAndStripProxyContext(t *testing.T) { + tagged := FormatProxyContextURL("http://127.0.0.1:8788", SourceIdentity{ + Scope: "task", + OwnerID: "42", + SessionID: "conv-9", + IntentID: 123, + }) + u, err := url.Parse(tagged) + if err != nil { + t.Fatalf("parse tagged url: %v", err) + } + if u.User == nil || !strings.HasPrefix(u.User.Username(), proxyContextUserPrefix) { + t.Fatalf("expected artexctx userinfo, got %v", u.User) + } + // Pre-existing proxy auth must be preserved untouched. + preAuth := "http://alice:secret@127.0.0.1:8788" + if got := FormatProxyContextURL(preAuth, SourceIdentity{Scope: "task", OwnerID: "1"}); got != preAuth { + t.Fatalf("expected pre-auth URL unchanged, got %q", got) + } + + req, _ := http.NewRequest("GET", "http://example.com/", nil) + req.SetBasicAuth(u.User.Username(), "x") + req.Header.Set("Proxy-Authorization", req.Header.Get("Authorization")) + req.Header.Del("Authorization") + + id, _, ok := parseAndStripProxyContext(req.Header) + if !ok { + t.Fatalf("expected parseAndStripProxyContext ok=true") + } + if req.Header.Get("Proxy-Authorization") != "" { + t.Fatalf("Proxy-Authorization should be stripped, got %q", req.Header.Get("Proxy-Authorization")) + } + if id.Scope != "task" || id.OwnerID != "42" || id.SessionID != "conv-9" || id.IntentID != 123 { + t.Fatalf("unexpected parsed identity: %+v", id) + } + + // Unrelated Proxy-Authorization must NOT be stripped. + h2 := http.Header{"Proxy-Authorization": []string{"Basic dXNlcjpwYXNz"}} + if _, _, ok := parseAndStripProxyContext(h2); ok { + t.Fatalf("non-artexctx header should not parse as context") + } + if h2.Get("Proxy-Authorization") == "" { + t.Fatalf("non-artexctx Proxy-Authorization must not be stripped") + } +} + +func TestResolveSourceSecurityBoundary(t *testing.T) { + tr := &Traffic{} + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.28.0.5" { + return SourceIdentity{ + Scope: "task", + OwnerID: "42", + ContainerID: "abcdef123456", + SrcIP: srcIP, + }, true + } + return SourceIdentity{}, false + }) + + // Sandbox container attempting to forge OwnerID=99 via Proxy-Authorization. + tagged := FormatProxyContextURL("http://172.28.0.1:8788", SourceIdentity{ + Scope: "session", + OwnerID: "99", + SessionID: "sess-1", + IntentID: 77, + }) + u, _ := url.Parse(tagged) + r, _ := http.NewRequest("GET", "http://example.com/", nil) + r.SetBasicAuth(u.User.Username(), "x") + r.Header.Set("Proxy-Authorization", r.Header.Get("Authorization")) + + got := tr.resolveSource("172.28.0.5:54321", r.Header) + if got.Scope != "task" || got.OwnerID != "42" || got.ContainerID != "abcdef123456" { + t.Fatalf("sandbox container IP must enforce hard identity, got %+v", got) + } + if got.IntentID != 77 || got.SessionID != "sess-1" { + t.Fatalf("observability fields should still be enriched, got %+v", got) + } + if got.SrcIP != "172.28.0.5" { + t.Fatalf("expected normalized src_ip 172.28.0.5, got %q", got.SrcIP) + } + + // Host loopback caller may supply full scope+owner tags. + r2, _ := http.NewRequest("GET", "http://example.com/", nil) + r2.SetBasicAuth(u.User.Username(), "x") + r2.Header.Set("Proxy-Authorization", r2.Header.Get("Authorization")) + gotHost := tr.resolveSource("127.0.0.1:41234", r2.Header) + if gotHost.Scope != "session" || gotHost.OwnerID != "99" || gotHost.IntentID != 77 { + t.Fatalf("loopback host caller should accept full tag, got %+v", gotHost) + } +} + +func TestProxyAttributionAndTaskIsolationLive(t *testing.T) { + var seenProxyAuth string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenProxyAuth = r.Header.Get("Proxy-Authorization") + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte("hello-target")) + })) + defer upstream.Close() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + proxyAddr := ln.Addr().String() + _ = ln.Close() + + tr, err := Open(t.TempDir(), proxyAddr) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer tr.Close() + + tr.SetTaskBlacklistChecker(func(taskID, rawHost, scheme string) (string, string) { + if taskID == "10" && strings.Contains(rawHost, "blocked-task10.example") { + return "task #10 intercept rule: blocked", "blocked-task10.example" + } + return "", "" + }) + + go func() { _ = tr.Start() }() + // Wait until proxy accepts connections. + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + c, err := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond) + if err == nil { + _ = c.Close() + break + } + time.Sleep(25 * time.Millisecond) + } + + sendThrough := func(id SourceIdentity, targetURL string) *http.Response { + pURLStr := FormatProxyContextURL("http://"+proxyAddr, id) + pURL, _ := url.Parse(pURLStr) + client := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(pURL)}, + Timeout: 5 * time.Second, + } + resp, err := client.Get(targetURL) + if err != nil { + t.Fatalf("GET %s via proxy: %v", targetURL, err) + } + return resp + } + + // 1. Task 10 request -> recorded with attribution, Proxy-Authorization stripped before reaching target. + resp1 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 55}, upstream.URL+"/t10") + _, _ = io.ReadAll(resp1.Body) + _ = resp1.Body.Close() + if resp1.StatusCode != 200 { + t.Fatalf("expected 200 for task 10, got %d", resp1.StatusCode) + } + if seenProxyAuth != "" { + t.Fatalf("target server must never receive internal Proxy-Authorization, got %q", seenProxyAuth) + } + + // 2. Task 20 request to the SAME target host -> must NOT leak into Task 10's query! + resp2 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "20", IntentID: 88}, upstream.URL+"/t20") + _, _ = io.ReadAll(resp2.Body) + _ = resp2.Body.Close() + + // 3. Task 10 blocked by per-task intercept rule -> 403 + block event attributed to task 10. + resp3 := sendThrough(SourceIdentity{Scope: "task", OwnerID: "10", IntentID: 56}, "http://blocked-task10.example/secret") + body3, _ := io.ReadAll(resp3.Body) + _ = resp3.Body.Close() + if resp3.StatusCode != http.StatusForbidden { + t.Fatalf("expected 403 for task 10 blocked host, got %d (%s)", resp3.StatusCode, string(body3)) + } + + events := tr.BlockEvents(10) + if len(events) == 0 || events[0].Scope != "task" || events[0].OwnerID != "10" || events[0].RuleKind != "task_intercept" { + t.Fatalf("expected task 10 block event, got %+v", events) + } + + // 4. Insert a legacy unattributed row for the same host to verify backward compatibility. + uParsed, _ := url.Parse(upstream.URL) + targetHost := uParsed.Hostname() + _, err = tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) VALUES('legacy-1', 100, ?, 'GET', '/old', ?, 200, 'text/plain', 0, 5, '')`, targetHost, upstream.URL+"/old") + if err != nil { + t.Fatalf("insert legacy row: %v", err) + } + + // Query Task 10 with shared targetHost in scope: must see Task 10 + legacy, NOT Task 20! + rows10, total10, err := tr.Page(PageQuery{ + OwnerTaskID: "10", + Hosts: []string{targetHost}, + RespMin: -1, + RespMax: -1, + }, 0, 50) + if err != nil { + t.Fatalf("Page task 10: %v", err) + } + if total10 != 2 { + t.Fatalf("expected 2 rows for task 10 (task10 + legacy, excluding task20), got %d: %+v", total10, rows10) + } + for _, r := range rows10 { + if r.SandboxOwnerID == "20" { + t.Fatalf("task 20 traffic leaked into task 10 query: %+v", r) + } + if strings.HasSuffix(r.URL, "/t10") { + if r.SandboxScope != "task" || r.SandboxOwnerID != "10" || r.IntentID != 55 || r.SrcIP != "127.0.0.1" { + t.Fatalf("unexpected attribution on /t10: %+v", r) + } + } + } + + // Query Task 10 with EMPTY host scope (e.g. before assets are discovered): still returns Task 10's attributed traffic! + rows10NoScope, totalNoScope, err := tr.Page(PageQuery{ + OwnerTaskID: "10", + RespMin: -1, + RespMax: -1, + }, 0, 50) + if err != nil || totalNoScope != 1 || len(rows10NoScope) != 1 || rows10NoScope[0].SandboxOwnerID != "10" { + t.Fatalf("expected 1 attributed row with empty host scope, got total=%d rows=%+v err=%v", totalNoScope, rows10NoScope, err) + } + + // HostsForTask returns attributed host even with empty scope. + hosts10, err := tr.HostsForTask("10", nil) + if err != nil || len(hosts10) != 1 || hosts10[0].Host != targetHost { + t.Fatalf("HostsForTask expected [%s], got %+v err=%v", targetHost, hosts10, err) + } +} + +func TestAttributionMigrationOnLegacyDB(t *testing.T) { + dir := t.TempDir() + idxDir := filepath.Join(dir, "_index") + if err := os.MkdirAll(idxDir, 0o755); err != nil { + t.Fatal(err) + } + dbPath := filepath.Join(idxDir, "index.sqlite") + rawDB, err := sql.Open("sqlite", dbPath) + if err != nil { + t.Fatal(err) + } + _, err = rawDB.Exec(`CREATE TABLE exchanges ( + id TEXT PRIMARY KEY, + ts INTEGER, + host TEXT, + method TEXT, + url_template TEXT, + url TEXT, + status INTEGER, + content_type TEXT, + req_len INTEGER, + resp_len INTEGER, + path TEXT + ); + INSERT INTO exchanges VALUES ('old-1', 123, 'example.com', 'GET', '/', 'http://example.com/', 200, 'text/html', 0, 10, '');`) + if err != nil { + t.Fatal(err) + } + _ = rawDB.Close() + + tr, err := Open(dir, "127.0.0.1:0") + if err != nil { + t.Fatalf("Open legacy DB failed: %v", err) + } + defer tr.Close() + + rows, total, err := tr.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 10) + if err != nil { + t.Fatalf("Page after migration failed: %v", err) + } + if total != 1 || len(rows) != 1 || rows[0].ID != "old-1" { + t.Fatalf("unexpected rows after migration: total=%d rows=%+v", total, rows) + } + // Verify new attribution insert works on migrated DB. + if _, err := tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path,sandbox_scope,sandbox_owner_id,container_id,session_id,intent_id,src_ip) VALUES('new-1', 456, 'example.com', 'GET', '/new', 'http://example.com/new', 200, 'text/plain', 0, 4, '', 'task', '7', 'cid123456789', '', 3, '172.28.0.9')`); err != nil { + t.Fatalf("insert attributed row after migration failed: %v", err) + } + filtered, tot, err := tr.Page(PageQuery{ContainerID: "cid123", RespMin: -1, RespMax: -1}, 0, 10) + if err != nil || tot != 1 || len(filtered) != 1 || filtered[0].SrcIP != "172.28.0.9" { + t.Fatalf("container filter failed: tot=%d rows=%+v err=%v", tot, filtered, err) + } + _ = fmt.Sprintf("migrated ok") +} diff --git a/traffic/ca_bundle.go b/traffic/ca_bundle.go new file mode 100644 index 0000000..f110f77 --- /dev/null +++ b/traffic/ca_bundle.go @@ -0,0 +1,68 @@ +package traffic + +import ( + "bytes" + "os" + "path/filepath" +) + +var systemCABundleCandidates = []string{ + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/cert.pem", +} + +// SystemCABundlePath returns the path to the merged CA bundle (system roots + +// ARTEX MITM CA) maintained under /_ca/ca-certificates.crt. +func (t *Traffic) SystemCABundlePath() string { + if t == nil { + return "" + } + return filepath.Join(t.dir, "_ca", "ca-certificates.crt") +} + +// EnsureSystemCABundle builds a merged CA bundle combining the host/container +// system root store with ARTEX's MITM CA cert so sandbox containers can mount +// it read-only at /etc/ssl/certs/ca-certificates.crt without requiring root or +// runtime update-ca-certificates (#218 Phase 3). Returns the bundle path if +// built, or empty string if no base system bundle or MITM CA is present. +func (t *Traffic) EnsureSystemCABundle() string { + if t == nil { + return "" + } + mitmPEM, err := os.ReadFile(t.CACertPath()) + if err != nil || len(bytes.TrimSpace(mitmPEM)) == 0 { + return "" + } + var sysPEM []byte + for _, p := range systemCABundleCandidates { + if b, err := os.ReadFile(p); err == nil && len(bytes.TrimSpace(b)) > 0 { + sysPEM = b + break + } + } + if len(sysPEM) == 0 { + return "" + } + var merged bytes.Buffer + merged.Write(sysPEM) + if !bytes.HasSuffix(sysPEM, []byte("\n")) { + merged.WriteByte('\n') + } + merged.WriteString("# ARTEX Recording Proxy MITM CA\n") + merged.Write(mitmPEM) + if !bytes.HasSuffix(mitmPEM, []byte("\n")) { + merged.WriteByte('\n') + } + + dest := t.SystemCABundlePath() + tmp := dest + ".tmp" + if err := os.WriteFile(tmp, merged.Bytes(), 0o644); err != nil { + return "" + } + if err := os.Rename(tmp, dest); err != nil { + _ = os.Remove(tmp) + return "" + } + return dest +} diff --git a/traffic/egress_blacklist.go b/traffic/egress_blacklist.go new file mode 100644 index 0000000..c0d6e17 --- /dev/null +++ b/traffic/egress_blacklist.go @@ -0,0 +1,393 @@ +package traffic + +import ( + "fmt" + "net" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +// EgressBlacklistRule defines one network-layer outbound block rule enforced at +// the recording proxy dial/request boundary (both local and Docker sandbox modes). +type EgressBlacklistRule struct { + ID string `json:"id"` + Enabled bool `json:"enabled"` + Kind string `json:"kind"` // domain | suffix | ip | cidr + Pattern string `json:"pattern"` // exact domain, suffix (*.example.com / .example.com), IP, or CIDR + Port int `json:"port,omitempty"` // optional; 0 matches all ports + Note string `json:"note,omitempty"` + Source string `json:"source,omitempty"` // custom | asset_intercept + CreatedAt string `json:"created_at,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// EgressBlockEvent captures one outbound connection/request rejected by either +// the built-in SSRF guard or an egress blacklist rule. +type EgressBlockEvent struct { + At time.Time `json:"at"` + Host string `json:"host"` + Port string `json:"port,omitempty"` + Method string `json:"method,omitempty"` + URL string `json:"url,omitempty"` + SrcIP string `json:"src_ip,omitempty"` + Scope string `json:"scope,omitempty"` + OwnerID string `json:"owner_id,omitempty"` + Reason string `json:"reason"` + RuleKind string `json:"rule_kind,omitempty"` // ssrf | domain | suffix | ip | cidr + RuleID string `json:"rule_id,omitempty"` + Pattern string `json:"pattern,omitempty"` + Source string `json:"source,omitempty"` // ssrf_guard | custom | asset_intercept +} + +type blockMatch struct { + Reason string + RuleKind string + RuleID string + Pattern string + Source string +} + +type compiledRule struct { + rule EgressBlacklistRule + domain string // normalized lowercase domain / suffix (no leading dot or wildcard) + ip net.IP // normalized IP for kind=ip + cidr *net.IPNet // parsed CIDR for kind=cidr + port string // "" = any port +} + +type egressBlacklist struct { + domainRules []compiledRule + suffixRules []compiledRule + ipRules []compiledRule + cidrRules []compiledRule +} + +// NormalizeEgressRule validates and normalizes a rule's kind and pattern. +func NormalizeEgressRule(r *EgressBlacklistRule) error { + r.Kind = strings.ToLower(strings.TrimSpace(r.Kind)) + r.Pattern = strings.TrimSpace(r.Pattern) + r.Note = strings.TrimSpace(r.Note) + if r.Port < 0 || r.Port > 65535 { + return fmt.Errorf("端口必须在 0 到 65535 之间") + } + if r.Pattern == "" { + return fmt.Errorf("规则匹配内容不能为空") + } + switch r.Kind { + case "domain": + h := normalizeDomainPattern(r.Pattern) + if h == "" || strings.ContainsAny(h, " /\\*?@") { + return fmt.Errorf("无效的精确域名:%q", r.Pattern) + } + if net.ParseIP(h) != nil { + return fmt.Errorf("IP 地址请使用 ip 类型规则:%q", r.Pattern) + } + r.Pattern = h + case "suffix": + raw := strings.ToLower(strings.TrimSpace(r.Pattern)) + raw = strings.TrimPrefix(raw, "*.") + raw = strings.TrimPrefix(raw, ".") + raw = strings.TrimSuffix(raw, ".") + if raw == "" || strings.ContainsAny(raw, " /\\*?@") { + return fmt.Errorf("无效的域名后缀/泛域名:%q", r.Pattern) + } + r.Pattern = "*." + raw + case "ip": + ip := net.ParseIP(strings.Trim(r.Pattern, "[]")) + if ip == nil { + return fmt.Errorf("无效的 IP 地址:%q", r.Pattern) + } + r.Pattern = normalizeIP(ip).String() + case "cidr": + _, ipnet, err := net.ParseCIDR(r.Pattern) + if err != nil { + return fmt.Errorf("无效的 CIDR 网段:%q", r.Pattern) + } + r.Pattern = ipnet.String() + default: + return fmt.Errorf("不支持的规则类型 %q(支持 domain / suffix / ip / cidr)", r.Kind) + } + return nil +} + +func normalizeDomainPattern(raw string) string { + s := strings.ToLower(strings.TrimSpace(raw)) + if strings.Contains(s, "://") { + if u, err := url.Parse(s); err == nil && u.Hostname() != "" { + s = strings.ToLower(u.Hostname()) + } + } + if h, _, err := net.SplitHostPort(s); err == nil { + s = h + } + s = strings.Trim(s, "[]") + s = strings.TrimSuffix(s, ".") + return s +} + +func newEgressBlacklist(rules []EgressBlacklistRule) *egressBlacklist { + b := &egressBlacklist{} + for _, r := range rules { + if !r.Enabled { + continue + } + cp := r + if err := NormalizeEgressRule(&cp); err != nil { + continue + } + cr := compiledRule{rule: cp} + if cp.Port > 0 { + cr.port = strconv.Itoa(cp.Port) + } + switch cp.Kind { + case "domain": + cr.domain = cp.Pattern + b.domainRules = append(b.domainRules, cr) + case "suffix": + cr.domain = strings.TrimPrefix(cp.Pattern, "*.") + b.suffixRules = append(b.suffixRules, cr) + case "ip": + cr.ip = normalizeIP(net.ParseIP(cp.Pattern)) + if cr.ip != nil { + b.ipRules = append(b.ipRules, cr) + } + case "cidr": + if _, ipnet, err := net.ParseCIDR(cp.Pattern); err == nil { + cr.cidr = ipnet + b.cidrRules = append(b.cidrRules, cr) + } + } + } + if len(b.domainRules) == 0 && len(b.suffixRules) == 0 && len(b.ipRules) == 0 && len(b.cidrRules) == 0 { + return nil + } + return b +} + +func (b *egressBlacklist) Check(rawHost, scheme string) *blockMatch { + if b == nil { + return nil + } + host, port := splitHostAndPort(rawHost) + host = strings.ToLower(strings.TrimSpace(host)) + host = strings.TrimPrefix(host, "[") + host = strings.TrimSuffix(host, "]") + host = strings.TrimSuffix(host, ".") + if host == "" { + return nil + } + if port == "" { + switch strings.ToLower(scheme) { + case "https": + port = "443" + case "http": + port = "80" + } + } + + // 1. Exact domain rules + for _, cr := range b.domainRules { + if cr.port != "" && cr.port != port { + continue + } + if host == cr.domain { + return ruleMatch(cr.rule, fmt.Sprintf("domain %q matches egress blacklist %q", host, cr.rule.Pattern)) + } + } + // 2. Suffix / wildcard domain rules + for _, cr := range b.suffixRules { + if cr.port != "" && cr.port != port { + continue + } + if host == cr.domain || strings.HasSuffix(host, "."+cr.domain) { + return ruleMatch(cr.rule, fmt.Sprintf("domain %q matches egress blacklist %q", host, cr.rule.Pattern)) + } + } + // 3. Literal IP rules & CIDR rules + if len(b.ipRules) == 0 && len(b.cidrRules) == 0 { + return nil + } + if ip := net.ParseIP(host); ip != nil { + return b.checkIP(ip, port, "") + } + // 4. DNS-resolved IPs (prevents domain -> blacklisted IP bypass / rebinding) + ips, err := net.LookupIP(host) + if err != nil { + return nil + } + for _, ip := range ips { + if m := b.checkIP(ip, port, host); m != nil { + return m + } + } + return nil +} + +func (b *egressBlacklist) checkIP(ip net.IP, port, resolvedFrom string) *blockMatch { + ip = normalizeIP(ip) + if ip == nil { + return nil + } + suffix := "" + if resolvedFrom != "" { + suffix = fmt.Sprintf(" (resolved from %s)", resolvedFrom) + } + for _, cr := range b.ipRules { + if cr.port != "" && cr.port != port { + continue + } + if cr.ip.Equal(ip) { + return ruleMatch(cr.rule, fmt.Sprintf("IP %s%s matches egress blacklist %s", ip.String(), suffix, cr.rule.Pattern)) + } + } + for _, cr := range b.cidrRules { + if cr.port != "" && cr.port != port { + continue + } + if cr.cidr.Contains(ip) { + return ruleMatch(cr.rule, fmt.Sprintf("IP %s%s matches egress blacklist %s", ip.String(), suffix, cr.rule.Pattern)) + } + } + return nil +} + +func ruleMatch(r EgressBlacklistRule, reason string) *blockMatch { + src := r.Source + if src == "" { + src = "custom" + } + return &blockMatch{ + Reason: reason, + RuleKind: r.Kind, + RuleID: r.ID, + Pattern: r.Pattern, + Source: src, + } +} + +const maxBlockEvents = 200 + +type blockEventLog struct { + mu sync.Mutex + events []EgressBlockEvent +} + +func (l *blockEventLog) Record(ev EgressBlockEvent) { + if l == nil { + return + } + if ev.At.IsZero() { + ev.At = time.Now().UTC() + } + l.mu.Lock() + defer l.mu.Unlock() + // Deduplicate back-to-back identical events triggered at both CONNECT and + // Requestheaders within a short window so one blocked request logs once. + if n := len(l.events); n > 0 { + last := l.events[n-1] + if last.Host == ev.Host && last.Port == ev.Port && last.SrcIP == ev.SrcIP && + last.Reason == ev.Reason && ev.At.Sub(last.At) < 150*time.Millisecond { + return + } + } + l.events = append(l.events, ev) + if len(l.events) > maxBlockEvents { + l.events = append([]EgressBlockEvent(nil), l.events[len(l.events)-maxBlockEvents:]...) + } +} + +func (l *blockEventLog) List(limit int) []EgressBlockEvent { + if l == nil { + return []EgressBlockEvent{} + } + l.mu.Lock() + defer l.mu.Unlock() + n := len(l.events) + if n == 0 { + return []EgressBlockEvent{} + } + if limit <= 0 || limit > n { + limit = n + } + out := make([]EgressBlockEvent, 0, limit) + for i := n - 1; i >= n-limit; i-- { + out = append(out, l.events[i]) + } + return out +} + +func (l *blockEventLog) Clear() { + if l == nil { + return + } + l.mu.Lock() + l.events = nil + l.mu.Unlock() +} + +// SetEgressBlacklist hot-reloads the network-layer outbound blacklist on the +// recording proxy. Passing an empty slice clears all custom/synced rules. +func (t *Traffic) SetEgressBlacklist(rules []EgressBlacklistRule) { + if t == nil { + return + } + t.blacklist.Store(newEgressBlacklist(rules)) +} + +// BlockEvents returns recent outbound block events (newest first). +func (t *Traffic) BlockEvents(limit int) []EgressBlockEvent { + if t == nil || t.blockLog == nil { + return []EgressBlockEvent{} + } + return t.blockLog.List(limit) +} + +// ClearBlockEvents clears the in-memory recent block event ring buffer. +func (t *Traffic) ClearBlockEvents() { + if t == nil || t.blockLog == nil { + return + } + t.blockLog.Clear() +} + +// checkOutboundDestination evaluates both the built-in SSRF guard and the +// dynamic egress blacklist. +func (t *Traffic) checkOutboundDestination(rawHost, scheme string) *blockMatch { + if t == nil || strings.TrimSpace(rawHost) == "" { + return nil + } + if g := t.ssrf.Load(); g != nil { + if reason := g.Check(rawHost); reason != "" { + return &blockMatch{ + Reason: reason, + RuleKind: "ssrf", + Source: "ssrf_guard", + } + } + } + if bl := t.blacklist.Load(); bl != nil { + if m := bl.Check(rawHost, scheme); m != nil { + return m + } + } + return nil +} + +// MatchEgressRules compiles a slice of EgressBlacklistRule and checks a single +// outbound destination against it. Used for on-demand task-level intercept checks. +func MatchEgressRules(rules []EgressBlacklistRule, rawHost, scheme string) (reason, pattern string) { + if len(rules) == 0 || strings.TrimSpace(rawHost) == "" { + return "", "" + } + bl := newEgressBlacklist(rules) + if bl == nil { + return "", "" + } + if m := bl.Check(rawHost, scheme); m != nil { + return m.Reason, m.Pattern + } + return "", "" +} diff --git a/traffic/egress_blacklist_test.go b/traffic/egress_blacklist_test.go new file mode 100644 index 0000000..da327c5 --- /dev/null +++ b/traffic/egress_blacklist_test.go @@ -0,0 +1,122 @@ +package traffic + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" +) + +func TestEgressBlacklistRuleMatching(t *testing.T) { + bl := newEgressBlacklist([]EgressBlacklistRule{ + {ID: "r1", Enabled: true, Kind: "domain", Pattern: "Exact.Example.COM"}, + {ID: "r2", Enabled: true, Kind: "suffix", Pattern: "*.gov.cn"}, + {ID: "r3", Enabled: true, Kind: "ip", Pattern: "203.0.113.5"}, + {ID: "r4", Enabled: true, Kind: "cidr", Pattern: "198.51.100.0/24"}, + {ID: "r5", Enabled: true, Kind: "domain", Pattern: "port-only.example", Port: 8443}, + {ID: "r6", Enabled: false, Kind: "domain", Pattern: "disabled.example"}, + }) + if bl == nil { + t.Fatal("expected compiled blacklist") + } + + blocked := []struct { + host string + scheme string + wantID string + }{ + {"exact.example.com:443", "https", "r1"}, + {"gov.cn", "https", "r2"}, + {"sub.dept.gov.cn:80", "http", "r2"}, + {"203.0.113.5:8080", "http", "r3"}, + {"198.51.100.42:443", "https", "r4"}, + {"port-only.example:8443", "https", "r5"}, + } + for _, tc := range blocked { + m := bl.Check(tc.host, tc.scheme) + if m == nil || m.RuleID != tc.wantID { + t.Fatalf("Check(%q, %q) = %+v, want rule %s", tc.host, tc.scheme, m, tc.wantID) + } + } + + allowed := []struct { + host string + scheme string + }{ + {"other.exact.example.com:443", "https"}, + {"notgov.cn:443", "https"}, + {"203.0.113.6:80", "http"}, + {"198.51.101.1:80", "http"}, + {"port-only.example:443", "https"}, + {"disabled.example:443", "https"}, + } + for _, tc := range allowed { + if m := bl.Check(tc.host, tc.scheme); m != nil { + t.Fatalf("Check(%q, %q) unexpectedly blocked: %+v", tc.host, tc.scheme, m) + } + } +} + +func TestProxyEnforcesEgressBlacklistInLocalModeAndLogsEvents(t *testing.T) { + // Target HTTP server on loopback (SSRF guard intentionally OFF to verify + // egress blacklist works independently in local mode). + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("REACHED")) + })) + defer target.Close() + + tr, addr := startProxy(t, false) + + proxyURL, err := url.Parse("http://" + addr) + if err != nil { + t.Fatal(err) + } + client := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, + Timeout: 5 * time.Second, + } + + // 1. Allowed before adding rule + resp, err := client.Get(target.URL) + if err != nil { + t.Fatalf("initial GET: %v", err) + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != 200 || string(body) != "REACHED" { + t.Fatalf("initial GET = %d %q", resp.StatusCode, string(body)) + } + + // 2. Hot-reload blacklist blocking 127.0.0.1 -> must return 403 + log block event + tr.SetEgressBlacklist([]EgressBlacklistRule{ + {ID: "blk-1", Enabled: true, Kind: "ip", Pattern: "127.0.0.1", Source: "custom"}, + }) + resp2, err := client.Get(target.URL) + if err != nil { + t.Fatalf("blocked GET error: %v", err) + } + body2, _ := io.ReadAll(resp2.Body) + resp2.Body.Close() + if resp2.StatusCode != http.StatusForbidden || !strings.Contains(string(body2), "blocked by ARTEX egress blacklist") { + t.Fatalf("blocked GET = %d %q", resp2.StatusCode, string(body2)) + } + + events := tr.BlockEvents(10) + if len(events) == 0 || events[0].RuleID != "blk-1" || events[0].Source != "custom" { + t.Fatalf("expected recorded block event, got %+v", events) + } + + // 3. Clearing blacklist immediately restores connectivity + tr.SetEgressBlacklist(nil) + resp3, err := client.Get(target.URL) + if err != nil { + t.Fatalf("post-clear GET: %v", err) + } + resp3.Body.Close() + if resp3.StatusCode != 200 { + t.Fatalf("post-clear GET = %d, want 200", resp3.StatusCode) + } +} diff --git a/traffic/gateway_protocol.go b/traffic/gateway_protocol.go new file mode 100644 index 0000000..f36248c --- /dev/null +++ b/traffic/gateway_protocol.go @@ -0,0 +1,302 @@ +package traffic + +import ( + "net" + "net/url" + "strings" + "sync" +) + +// GatewaySSRFPolicy is the JSON-serializable form of SSRFGuardConfig synced to artex-gateway. +type GatewaySSRFPolicy struct { + Enabled bool `json:"enabled"` + BlockPrivate bool `json:"block_private"` + BlockedHosts []string `json:"blocked_hosts,omitempty"` + BlockedCIDRs []string `json:"blocked_cidrs,omitempty"` + InfraIPs []string `json:"infra_ips,omitempty"` +} + +// GatewayContainerRoute describes one per-owner upstream proxy override. +type GatewayContainerRoute struct { + Scope string `json:"scope"` + OwnerID string `json:"owner_id"` + Mode string `json:"mode"` // inherit, direct, pool, proxy + ProxyPoolID string `json:"proxy_pool_id,omitempty"` + ProxyURL string `json:"proxy_url,omitempty"` + EffectiveURL string `json:"effective_url,omitempty"` // resolved raw URL (only in internal gateway sync) + Note string `json:"note,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} + +// GatewayPolicySnapshot is returned by GET /api/internal/gateway/policy so the +// standalone artex-gateway enforces the exact same real-time SSRF guard, egress +// blacklist, task rules, container IP attribution, and per-container proxy routing +// as the main ARTEX control plane. +type GatewayPolicySnapshot struct { + SSRF *GatewaySSRFPolicy `json:"ssrf,omitempty"` + BlacklistRules []EgressBlacklistRule `json:"blacklist_rules,omitempty"` + TaskRules map[string][]EgressBlacklistRule `json:"task_rules,omitempty"` + ContainerIPs map[string]SourceIdentity `json:"container_ips,omitempty"` + GlobalUpstreamURL string `json:"global_upstream_url,omitempty"` + ContainerRoutes map[string]GatewayContainerRoute `json:"container_routes,omitempty"` // key: "scope:owner_id" + PassthroughHosts []string `json:"passthrough_hosts,omitempty"` + UDPPolicy string `json:"udp_policy"` + DNSUpstream string `json:"dns_upstream,omitempty"` + StoreErrorTraffic bool `json:"store_error_traffic"` +} + +// GatewayEventBatch is posted by artex-gateway to POST /api/internal/gateway/events. +type GatewayEventBatch struct { + GatewayID string `json:"gateway_id,omitempty"` + NetFlows []NetFlowRecord `json:"net_flows,omitempty"` + DNSQueries []DNSQueryRecord `json:"dns_queries,omitempty"` + BlockEvents []EgressBlockEvent `json:"block_events,omitempty"` +} + +// RemotePolicyState holds an in-memory compiled snapshot of GatewayPolicySnapshot +// and implements the read side of TransparentBackend for cmd/artex-gateway. +type RemotePolicyState struct { + mu sync.RWMutex + ssrf *ssrfGuard + blacklist *egressBlacklist + taskRules map[string]*egressBlacklist + containerIPs map[string]SourceIdentity + globalUpstream *url.URL + containerRoutes map[string]*url.URL // key -> nil (direct) or *url.URL (proxy) + passthroughHosts map[string]struct{} + udpPolicy string + dnsUpstream string + storeErrorTraffic bool + dnsCache *dnsReverseCache + gatewayToken string + onNetFlow func(NetFlowRecord) + onDNSQuery func(DNSQueryRecord) + onBlockEvent func(EgressBlockEvent) +} + +// NewRemotePolicyState creates a RemotePolicyState wired to event callbacks. +func NewRemotePolicyState(token string, onFlow func(NetFlowRecord), onDNS func(DNSQueryRecord), onBlock func(EgressBlockEvent)) *RemotePolicyState { + return &RemotePolicyState{ + taskRules: map[string]*egressBlacklist{}, + containerIPs: map[string]SourceIdentity{}, + containerRoutes: map[string]*url.URL{}, + passthroughHosts: map[string]struct{}{}, + udpPolicy: UDPPolicyBlockOnProxy, + dnsCache: newDNSReverseCache(), + gatewayToken: strings.TrimSpace(token), + onNetFlow: onFlow, + onDNSQuery: onDNS, + onBlockEvent: onBlock, + } +} + +// Apply atomically replaces the compiled policy from snap. +func (s *RemotePolicyState) Apply(snap GatewayPolicySnapshot) { + var ssrf *ssrfGuard + if snap.SSRF != nil && snap.SSRF.Enabled { + var cidrs []*net.IPNet + for _, c := range snap.SSRF.BlockedCIDRs { + if _, n, err := net.ParseCIDR(strings.TrimSpace(c)); err == nil { + cidrs = append(cidrs, n) + } + } + var infraIPs []net.IP + for _, raw := range snap.SSRF.InfraIPs { + if ip := net.ParseIP(strings.TrimSpace(raw)); ip != nil { + infraIPs = append(infraIPs, ip) + } + } + ssrf = newSSRFGuard(SSRFGuardConfig{ + Enabled: true, + BlockPrivate: snap.SSRF.BlockPrivate, + BlockedHosts: snap.SSRF.BlockedHosts, + BlockedCIDRs: cidrs, + InfraIPs: infraIPs, + HostNetworkMode: true, + }) + } + bl := newEgressBlacklist(snap.BlacklistRules) + + taskBL := make(map[string]*egressBlacklist, len(snap.TaskRules)) + for tid, rules := range snap.TaskRules { + if len(rules) > 0 { + taskBL[tid] = newEgressBlacklist(rules) + } + } + + ipMap := make(map[string]SourceIdentity, len(snap.ContainerIPs)) + for ip, id := range snap.ContainerIPs { + norm := normalizeIPString(ip) + if norm != "" { + id.SrcIP = norm + ipMap[norm] = id + } + } + + var globalUp *url.URL + if strings.TrimSpace(snap.GlobalUpstreamURL) != "" { + if u, err := ValidateProxyURL(snap.GlobalUpstreamURL); err == nil { + globalUp = u + } + } + + routes := make(map[string]*url.URL, len(snap.ContainerRoutes)) + for key, r := range snap.ContainerRoutes { + switch strings.ToLower(strings.TrimSpace(r.Mode)) { + case "direct": + routes[key] = nil + case "proxy", "pool": + raw := strings.TrimSpace(r.EffectiveURL) + if raw == "" { + raw = strings.TrimSpace(r.ProxyURL) + } + if u, err := ValidateProxyURL(raw); err == nil { + routes[key] = u + } + } + } + + pass := make(map[string]struct{}, len(snap.PassthroughHosts)) + for _, h := range snap.PassthroughHosts { + if h = hostOnly(h); h != "" { + pass[h] = struct{}{} + } + } + + s.mu.Lock() + s.ssrf = ssrf + s.blacklist = bl + s.taskRules = taskBL + s.containerIPs = ipMap + s.globalUpstream = globalUp + s.containerRoutes = routes + s.passthroughHosts = pass + s.udpPolicy = NormalizeUDPPolicy(snap.UDPPolicy) + s.dnsUpstream = strings.TrimSpace(snap.DNSUpstream) + s.storeErrorTraffic = snap.StoreErrorTraffic + s.mu.Unlock() +} + +func (s *RemotePolicyState) ResolveSource(srcIP string) SourceIdentity { + norm := normalizeIPString(srcIP) + s.mu.RLock() + id, ok := s.containerIPs[norm] + s.mu.RUnlock() + if ok { + id.SrcIP = norm + return id + } + return SourceIdentity{SrcIP: norm} +} + +func (s *RemotePolicyState) CheckOutbound(rawHost, scheme string, src SourceIdentity) *BlockDecision { + s.mu.RLock() + ssrf := s.ssrf + bl := s.blacklist + var taskBL *egressBlacklist + if src.Scope == "task" && src.OwnerID != "" { + taskBL = s.taskRules[src.OwnerID] + } + s.mu.RUnlock() + + if ssrf != nil { + if reason := ssrf.Check(rawHost); reason != "" { + return &BlockDecision{Reason: reason, RuleKind: "ssrf_guard", Source: "ssrf_guard"} + } + } + if bl != nil { + if m := bl.Check(rawHost, scheme); m != nil { + return &BlockDecision{ + Reason: m.Reason, + RuleKind: m.RuleKind, + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: m.Source, + } + } + } + if taskBL != nil { + if m := taskBL.Check(rawHost, scheme); m != nil { + return &BlockDecision{ + Reason: m.Reason, + RuleKind: "task_intercept", + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: "asset_intercept", + } + } + } + return nil +} + +func (s *RemotePolicyState) ResolveUpstream(src SourceIdentity) *url.URL { + s.mu.RLock() + defer s.mu.RUnlock() + if src.Scope != "" && src.OwnerID != "" { + if u, ok := s.containerRoutes[src.Scope+":"+src.OwnerID]; ok { + return u // nil means explicit direct + } + } + return s.globalUpstream +} + +func (s *RemotePolicyState) IsPassthrough(host string) bool { + s.mu.RLock() + _, ok := s.passthroughHosts[hostOnly(host)] + s.mu.RUnlock() + return ok +} + +func (s *RemotePolicyState) LookupDNSReverse(ip string) string { + return s.dnsCache.Lookup(ip) +} + +func (s *RemotePolicyState) RememberDNS(ip, domain string) { + s.dnsCache.Set(ip, domain) +} + +func (s *RemotePolicyState) RecordNetFlow(rec NetFlowRecord) { + if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { + return + } + if s.onNetFlow != nil { + s.onNetFlow(rec) + } +} + +func (s *RemotePolicyState) RecordDNSQuery(rec DNSQueryRecord) { + if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { + return + } + if s.onDNSQuery != nil { + s.onDNSQuery(rec) + } +} + +func (s *RemotePolicyState) RecordBlockEvent(ev EgressBlockEvent) { + if s.onBlockEvent != nil { + s.onBlockEvent(ev) + } +} + +func (s *RemotePolicyState) UDPPolicy() string { + s.mu.RLock() + defer s.mu.RUnlock() + return s.udpPolicy +} + +func (s *RemotePolicyState) DNSUpstream() string { + s.mu.RLock() + defer s.mu.RUnlock() + return s.dnsUpstream +} + +func (s *RemotePolicyState) StoreErrorTraffic() bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.storeErrorTraffic +} + +func (s *RemotePolicyState) GatewayToken() string { + return s.gatewayToken +} diff --git a/traffic/netflow_store.go b/traffic/netflow_store.go new file mode 100644 index 0000000..5ea763d --- /dev/null +++ b/traffic/netflow_store.go @@ -0,0 +1,716 @@ +package traffic + +import ( + "context" + "database/sql" + "encoding/hex" + "encoding/json" + "fmt" + "log" + "strings" + "sync" + "sync/atomic" + "time" + "unicode/utf8" +) + +const netFlowSchema = ` +CREATE TABLE IF NOT EXISTS net_flows ( + id TEXT PRIMARY KEY, + ts INTEGER NOT NULL, + ended_at INTEGER NOT NULL DEFAULT 0, + duration_ms INTEGER NOT NULL DEFAULT 0, + protocol TEXT NOT NULL, + dst_ip TEXT NOT NULL DEFAULT '', + dst_port INTEGER NOT NULL DEFAULT 0, + dst_host TEXT NOT NULL DEFAULT '', + sni TEXT NOT NULL DEFAULT '', + action TEXT NOT NULL DEFAULT 'allow', + block_reason TEXT NOT NULL DEFAULT '', + upstream_proxy TEXT NOT NULL DEFAULT '', + bytes_tx INTEGER NOT NULL DEFAULT 0, + bytes_rx INTEGER NOT NULL DEFAULT 0, + tx_preview BLOB, + rx_preview BLOB, + sandbox_scope TEXT NOT NULL DEFAULT '', + sandbox_owner_id TEXT NOT NULL DEFAULT '', + container_id TEXT NOT NULL DEFAULT '', + session_id TEXT NOT NULL DEFAULT '', + intent_id INTEGER NOT NULL DEFAULT 0, + src_ip TEXT NOT NULL DEFAULT '', + src_port INTEGER NOT NULL DEFAULT 0, + error TEXT NOT NULL DEFAULT '' +); +CREATE INDEX IF NOT EXISTS idx_nf_ts ON net_flows(ts); +CREATE INDEX IF NOT EXISTS idx_nf_proto ON net_flows(protocol, ts); +CREATE INDEX IF NOT EXISTS idx_nf_owner ON net_flows(sandbox_scope, sandbox_owner_id, ts); +CREATE INDEX IF NOT EXISTS idx_nf_dst ON net_flows(dst_host, dst_ip, dst_port); +CREATE INDEX IF NOT EXISTS idx_nf_action ON net_flows(action, ts); + +CREATE TABLE IF NOT EXISTS dns_queries ( + id TEXT PRIMARY KEY, + ts INTEGER NOT NULL, + duration_ms INTEGER NOT NULL DEFAULT 0, + qname TEXT NOT NULL, + qtype TEXT NOT NULL DEFAULT 'A', + rcode TEXT NOT NULL DEFAULT 'NOERROR', + answers_json TEXT NOT NULL DEFAULT '[]', + action TEXT NOT NULL DEFAULT 'allow', + block_reason TEXT NOT NULL DEFAULT '', + upstream TEXT NOT NULL DEFAULT '', + sandbox_scope TEXT NOT NULL DEFAULT '', + sandbox_owner_id TEXT NOT NULL DEFAULT '', + container_id TEXT NOT NULL DEFAULT '', + session_id TEXT NOT NULL DEFAULT '', + intent_id INTEGER NOT NULL DEFAULT 0, + src_ip TEXT NOT NULL DEFAULT '', + error TEXT NOT NULL DEFAULT '' +); +CREATE INDEX IF NOT EXISTS idx_dns_ts ON dns_queries(ts); +CREATE INDEX IF NOT EXISTS idx_dns_qname ON dns_queries(qname, ts); +CREATE INDEX IF NOT EXISTS idx_dns_owner ON dns_queries(sandbox_scope, sandbox_owner_id, ts); +CREATE INDEX IF NOT EXISTS idx_dns_action ON dns_queries(action, ts); +` + +const ( + // maxFlowPreviewBytes caps per-direction payload previews persisted in SQLite + // so port scans and large binary transfers cannot bloat index.sqlite. + maxFlowPreviewBytes = 4096 + // maxNetFlowRows / maxDNSQueryRows bound rolling retention for non-HTTP logs. + maxNetFlowRows = 50000 + maxDNSQueryRows = 50000 + trimCheckEvery = 500 + dnsCacheMax = 4096 + dnsCacheTTL = 10 * time.Minute +) + +// NetFlowRecord captures one non-HTTP L4 flow (raw TCP, TLS passthrough, UDP) +// or blocked outbound connection observed by the transparent gateway (#218 Phase 3/4). +type NetFlowRecord struct { + ID string `json:"id"` + TS int64 `json:"ts"` + EndedAt int64 `json:"ended_at,omitempty"` + DurationMS int64 `json:"duration_ms"` + Protocol string `json:"protocol"` // tcp, tls, udp + DstIP string `json:"dst_ip"` + DstPort int `json:"dst_port"` + DstHost string `json:"dst_host,omitempty"` + SNI string `json:"sni,omitempty"` + Action string `json:"action"` // allow, block, error, passthrough + BlockReason string `json:"block_reason,omitempty"` + UpstreamProxy string `json:"upstream_proxy,omitempty"` + BytesTX int64 `json:"bytes_tx"` + BytesRX int64 `json:"bytes_rx"` + TXPreview []byte `json:"tx_preview,omitempty"` + RXPreview []byte `json:"rx_preview,omitempty"` + TXPreviewText string `json:"tx_preview_text,omitempty"` + TXPreviewHex string `json:"tx_preview_hex,omitempty"` + TXBinary bool `json:"tx_binary,omitempty"` + RXPreviewText string `json:"rx_preview_text,omitempty"` + RXPreviewHex string `json:"rx_preview_hex,omitempty"` + RXBinary bool `json:"rx_binary,omitempty"` + SandboxScope string `json:"sandbox_scope,omitempty"` + SandboxOwnerID string `json:"sandbox_owner_id,omitempty"` + ContainerID string `json:"container_id,omitempty"` + SessionID string `json:"session_id,omitempty"` + IntentID int64 `json:"intent_id,omitempty"` + SrcIP string `json:"src_ip,omitempty"` + SrcPort int `json:"src_port,omitempty"` + Error string `json:"error,omitempty"` +} + +// NetFlowQuery filters paged net_flows queries. +type NetFlowQuery struct { + Protocol string + Action string + SandboxScope string + SandboxOwnerID string + ContainerID string + OwnerTaskID string + Query string // matches dst_host, dst_ip, sni, src_ip, block_reason +} + +// DNSQueryRecord captures one intercepted DNS query and its answer/block decision. +type DNSQueryRecord struct { + ID string `json:"id"` + TS int64 `json:"ts"` + DurationMS int64 `json:"duration_ms"` + QName string `json:"qname"` + QType string `json:"qtype"` + RCode string `json:"rcode"` + Answers []string `json:"answers"` + Action string `json:"action"` // allow, block, error + BlockReason string `json:"block_reason,omitempty"` + Upstream string `json:"upstream,omitempty"` + SandboxScope string `json:"sandbox_scope,omitempty"` + SandboxOwnerID string `json:"sandbox_owner_id,omitempty"` + ContainerID string `json:"container_id,omitempty"` + SessionID string `json:"session_id,omitempty"` + IntentID int64 `json:"intent_id,omitempty"` + SrcIP string `json:"src_ip,omitempty"` + Error string `json:"error,omitempty"` +} + +// DNSQueryFilter filters paged dns_queries queries. +type DNSQueryFilter struct { + QType string + RCode string + Action string + SandboxScope string + SandboxOwnerID string + ContainerID string + OwnerTaskID string + Query string // matches qname, answers_json, src_ip, block_reason +} + +type dnsCacheEntry struct { + domain string + expiresAt time.Time +} + +// dnsReverseCache maps recently resolved IPs back to their queried domain name +// so subsequent raw TCP/UDP connections to that IP carry dst_host attribution +// and domain-based egress blacklist enforcement. +type dnsReverseCache struct { + mu sync.RWMutex + entries map[string]dnsCacheEntry +} + +func newDNSReverseCache() *dnsReverseCache { + return &dnsReverseCache{entries: make(map[string]dnsCacheEntry, 128)} +} + +func (c *dnsReverseCache) Set(ip, domain string) { + if c == nil { + return + } + ip = normalizeIPString(ip) + domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".") + if ip == "" || domain == "" { + return + } + now := time.Now() + c.mu.Lock() + if len(c.entries) >= dnsCacheMax { + for k, v := range c.entries { + if now.After(v.expiresAt) { + delete(c.entries, k) + } + } + if len(c.entries) >= dnsCacheMax { + // Evict a small slice so writes stay O(1) amortized. + dropped := 0 + for k := range c.entries { + delete(c.entries, k) + dropped++ + if dropped >= 256 { + break + } + } + } + } + c.entries[ip] = dnsCacheEntry{domain: domain, expiresAt: now.Add(dnsCacheTTL)} + c.mu.Unlock() +} + +func (c *dnsReverseCache) Lookup(ip string) string { + if c == nil { + return "" + } + ip = normalizeIPString(ip) + if ip == "" { + return "" + } + c.mu.RLock() + e, ok := c.entries[ip] + c.mu.RUnlock() + if !ok || time.Now().After(e.expiresAt) { + return "" + } + return e.domain +} + +// RememberDNS records an ip -> domain mapping in the reverse DNS cache. +func (t *Traffic) RememberDNS(ip, domain string) { + if t == nil || t.dnsCache == nil { + return + } + t.dnsCache.Set(ip, domain) +} + +// LookupDNSReverse returns the most recently resolved domain for ip, if cached. +func (t *Traffic) LookupDNSReverse(ip string) string { + if t == nil || t.dnsCache == nil { + return "" + } + return t.dnsCache.Lookup(ip) +} + +func ensureNetFlowSchema(ctx context.Context, conn *sql.Conn) error { + _, err := conn.ExecContext(ctx, netFlowSchema) + return err +} + +// FormatPayloadPreview converts raw preview bytes into a display-safe UTF-8 text +// preview and hex dump when binary bytes are present. +func FormatPayloadPreview(b []byte) (text string, hexStr string, binary bool) { + if len(b) == 0 { + return "", "", false + } + if len(b) > maxFlowPreviewBytes { + b = b[:maxFlowPreviewBytes] + } + binary = isBinaryPayload(b) + if binary { + capHex := b + if len(capHex) > 1024 { + capHex = capHex[:1024] + } + return sanitizeASCIIPreview(b), hex.EncodeToString(capHex), true + } + return string(b), "", false +} + +func isBinaryPayload(b []byte) bool { + if len(b) == 0 { + return false + } + if !utf8.Valid(b) { + return true + } + ctrl := 0 + for _, c := range b { + if c == 0 { + return true + } + if c < 0x20 && c != '\n' && c != '\r' && c != '\t' { + ctrl++ + } + } + return ctrl*10 > len(b) +} + +func sanitizeASCIIPreview(b []byte) string { + var sb strings.Builder + sb.Grow(len(b)) + for _, c := range b { + if (c >= 0x20 && c < 0x7f) || c == '\n' || c == '\r' || c == '\t' { + sb.WriteByte(c) + } else { + sb.WriteByte('.') + } + } + return sb.String() +} + +// RecordNetFlow persists a non-HTTP flow record into SQLite with bounded +// payload previews and rolling row-count retention. +func (t *Traffic) RecordNetFlow(rec NetFlowRecord) error { + if t == nil || t.db == nil { + return nil + } + now := time.Now() + if rec.TS <= 0 { + rec.TS = now.Unix() + } + if rec.ID == "" { + n := t.seq.Add(1) + rec.ID = fmt.Sprintf("nf-%d-%04d", rec.TS, n%10000) + } + rec.Protocol = strings.ToLower(strings.TrimSpace(rec.Protocol)) + if rec.Protocol == "" { + rec.Protocol = "tcp" + } + rec.Action = strings.ToLower(strings.TrimSpace(rec.Action)) + if rec.Action == "" { + rec.Action = "allow" + } + if rec.Action == "error" && !t.StoreErrorTraffic() { + return nil + } + if len(rec.TXPreview) > maxFlowPreviewBytes { + rec.TXPreview = rec.TXPreview[:maxFlowPreviewBytes] + } + if len(rec.RXPreview) > maxFlowPreviewBytes { + rec.RXPreview = rec.RXPreview[:maxFlowPreviewBytes] + } + + t.wmu.Lock() + defer t.wmu.Unlock() + _, err := t.db.Exec(`INSERT OR REPLACE INTO net_flows( + id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni, + action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview, + sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error +) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + rec.ID, rec.TS, rec.EndedAt, rec.DurationMS, rec.Protocol, rec.DstIP, rec.DstPort, rec.DstHost, rec.SNI, + rec.Action, rec.BlockReason, rec.UpstreamProxy, rec.BytesTX, rec.BytesRX, rec.TXPreview, rec.RXPreview, + rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.SrcPort, rec.Error, + ) + if err != nil { + log.Printf("[traffic] 记录 net_flow %s 失败:%v", rec.ID, err) + return err + } + if t.nfWrites.Add(1)%trimCheckEvery == 0 { + t.trimTableLocked("net_flows", maxNetFlowRows) + } + return nil +} + +// RecordDNSQuery persists an intercepted DNS query record into SQLite. +func (t *Traffic) RecordDNSQuery(rec DNSQueryRecord) error { + if t == nil || t.db == nil { + return nil + } + now := time.Now() + if rec.TS <= 0 { + rec.TS = now.Unix() + } + if rec.ID == "" { + n := t.seq.Add(1) + rec.ID = fmt.Sprintf("dns-%d-%04d", rec.TS, n%10000) + } + rec.QName = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(rec.QName)), ".") + if rec.QType == "" { + rec.QType = "A" + } + rec.Action = strings.ToLower(strings.TrimSpace(rec.Action)) + if rec.Action == "" { + rec.Action = "allow" + } + if rec.Action == "error" && !t.StoreErrorTraffic() { + return nil + } + answers := rec.Answers + if answers == nil { + answers = []string{} + } + answersJSON, _ := json.Marshal(answers) + + t.wmu.Lock() + defer t.wmu.Unlock() + _, err := t.db.Exec(`INSERT OR REPLACE INTO dns_queries( + id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream, + sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error +) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + rec.ID, rec.TS, rec.DurationMS, rec.QName, rec.QType, rec.RCode, string(answersJSON), rec.Action, rec.BlockReason, rec.Upstream, + rec.SandboxScope, rec.SandboxOwnerID, rec.ContainerID, rec.SessionID, rec.IntentID, rec.SrcIP, rec.Error, + ) + if err != nil { + log.Printf("[traffic] 记录 dns_query %s 失败:%v", rec.ID, err) + return err + } + if t.dnsWrites.Add(1)%trimCheckEvery == 0 { + t.trimTableLocked("dns_queries", maxDNSQueryRows) + } + return nil +} + +func (t *Traffic) trimTableLocked(table string, maxRows int) { + var count int + if err := t.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count <= maxRows { + return + } + excess := count - maxRows + if _, err := t.db.Exec( + `DELETE FROM `+table+` WHERE id IN (SELECT id FROM `+table+` ORDER BY ts ASC, rowid ASC LIMIT ?)`, + excess, + ); err != nil { + log.Printf("[traffic] 滚动清理 %s 失败:%v", table, err) + return + } + t.reclaim() +} + +// PageNetFlows returns a filtered, newest-first page of non-HTTP flow records. +func (t *Traffic) PageNetFlows(q NetFlowQuery, page, size int) ([]NetFlowRecord, int, error) { + if t == nil || t.db == nil { + return []NetFlowRecord{}, 0, nil + } + if page < 0 { + page = 0 + } + if size <= 0 || size > 500 { + size = 100 + } + var conds []string + var args []any + if p := strings.ToLower(strings.TrimSpace(q.Protocol)); p != "" && p != "all" { + conds = append(conds, `protocol=?`) + args = append(args, p) + } + if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" { + conds = append(conds, `action=?`) + args = append(args, a) + } + if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" { + conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`) + args = append(args, taskID) + } + if sc := strings.TrimSpace(q.SandboxScope); sc != "" { + conds = append(conds, `sandbox_scope=?`) + args = append(args, sc) + } + if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" { + conds = append(conds, `sandbox_owner_id=?`) + args = append(args, ow) + } + if cid := strings.TrimSpace(q.ContainerID); cid != "" { + conds = append(conds, `(container_id=? OR container_id LIKE ?)`) + args = append(args, cid, cid+"%") + } + if kw := strings.TrimSpace(q.Query); kw != "" { + like := "%" + kw + "%" + conds = append(conds, `(dst_host LIKE ? OR dst_ip LIKE ? OR sni LIKE ? OR src_ip LIKE ? OR block_reason LIKE ? OR CAST(dst_port AS TEXT)=?)`) + args = append(args, like, like, like, like, like, kw) + } + where := "" + if len(conds) > 0 { + where = " WHERE " + strings.Join(conds, " AND ") + } + + var total int + if err := t.db.QueryRow(`SELECT count(*) FROM net_flows`+where, args...).Scan(&total); err != nil { + return nil, 0, err + } + if total == 0 { + return []NetFlowRecord{}, 0, nil + } + + queryArgs := append(append([]any{}, args...), size, page*size) + rows, err := t.db.Query(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni, + action, block_reason, upstream_proxy, bytes_tx, bytes_rx, + sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error +FROM net_flows`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + out := make([]NetFlowRecord, 0, size) + for rows.Next() { + var r NetFlowRecord + if err := rows.Scan( + &r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI, + &r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX, + &r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error, + ); err != nil { + return nil, 0, err + } + out = append(out, r) + } + return out, total, rows.Err() +} + +// GetNetFlow fetches one flow record including its TX/RX payload previews. +func (t *Traffic) GetNetFlow(id string) (*NetFlowRecord, error) { + if t == nil || t.db == nil { + return nil, sql.ErrNoRows + } + var r NetFlowRecord + err := t.db.QueryRow(`SELECT id, ts, ended_at, duration_ms, protocol, dst_ip, dst_port, dst_host, sni, + action, block_reason, upstream_proxy, bytes_tx, bytes_rx, tx_preview, rx_preview, + sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, src_port, error +FROM net_flows WHERE id=?`, strings.TrimSpace(id)).Scan( + &r.ID, &r.TS, &r.EndedAt, &r.DurationMS, &r.Protocol, &r.DstIP, &r.DstPort, &r.DstHost, &r.SNI, + &r.Action, &r.BlockReason, &r.UpstreamProxy, &r.BytesTX, &r.BytesRX, &r.TXPreview, &r.RXPreview, + &r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.SrcPort, &r.Error, + ) + if err != nil { + return nil, err + } + r.TXPreviewText, r.TXPreviewHex, r.TXBinary = FormatPayloadPreview(r.TXPreview) + r.RXPreviewText, r.RXPreviewHex, r.RXBinary = FormatPayloadPreview(r.RXPreview) + r.TXPreview = nil + r.RXPreview = nil + return &r, nil +} + +// PageDNSQueries returns a filtered, newest-first page of DNS query records. +func (t *Traffic) PageDNSQueries(q DNSQueryFilter, page, size int) ([]DNSQueryRecord, int, error) { + if t == nil || t.db == nil { + return []DNSQueryRecord{}, 0, nil + } + if page < 0 { + page = 0 + } + if size <= 0 || size > 500 { + size = 100 + } + var conds []string + var args []any + if qt := strings.ToUpper(strings.TrimSpace(q.QType)); qt != "" && qt != "ALL" { + conds = append(conds, `qtype=?`) + args = append(args, qt) + } + if rc := strings.ToUpper(strings.TrimSpace(q.RCode)); rc != "" && rc != "ALL" { + conds = append(conds, `rcode=?`) + args = append(args, rc) + } + if a := strings.ToLower(strings.TrimSpace(q.Action)); a != "" && a != "all" { + conds = append(conds, `action=?`) + args = append(args, a) + } + if taskID := strings.TrimSpace(q.OwnerTaskID); taskID != "" { + conds = append(conds, `(sandbox_scope='task' AND sandbox_owner_id=?)`) + args = append(args, taskID) + } + if sc := strings.TrimSpace(q.SandboxScope); sc != "" { + conds = append(conds, `sandbox_scope=?`) + args = append(args, sc) + } + if ow := strings.TrimSpace(q.SandboxOwnerID); ow != "" { + conds = append(conds, `sandbox_owner_id=?`) + args = append(args, ow) + } + if cid := strings.TrimSpace(q.ContainerID); cid != "" { + conds = append(conds, `(container_id=? OR container_id LIKE ?)`) + args = append(args, cid, cid+"%") + } + if kw := strings.TrimSpace(q.Query); kw != "" { + like := "%" + kw + "%" + conds = append(conds, `(qname LIKE ? OR answers_json LIKE ? OR src_ip LIKE ? OR block_reason LIKE ?)`) + args = append(args, like, like, like, like) + } + where := "" + if len(conds) > 0 { + where = " WHERE " + strings.Join(conds, " AND ") + } + + var total int + if err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`+where, args...).Scan(&total); err != nil { + return nil, 0, err + } + if total == 0 { + return []DNSQueryRecord{}, 0, nil + } + + queryArgs := append(append([]any{}, args...), size, page*size) + rows, err := t.db.Query(`SELECT id, ts, duration_ms, qname, qtype, rcode, answers_json, action, block_reason, upstream, + sandbox_scope, sandbox_owner_id, container_id, session_id, intent_id, src_ip, error +FROM dns_queries`+where+` ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`, queryArgs...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + out := make([]DNSQueryRecord, 0, size) + for rows.Next() { + var r DNSQueryRecord + var answersRaw string + if err := rows.Scan( + &r.ID, &r.TS, &r.DurationMS, &r.QName, &r.QType, &r.RCode, &answersRaw, &r.Action, &r.BlockReason, &r.Upstream, + &r.SandboxScope, &r.SandboxOwnerID, &r.ContainerID, &r.SessionID, &r.IntentID, &r.SrcIP, &r.Error, + ); err != nil { + return nil, 0, err + } + if answersRaw != "" { + _ = json.Unmarshal([]byte(answersRaw), &r.Answers) + } + if r.Answers == nil { + r.Answers = []string{} + } + out = append(out, r) + } + return out, total, rows.Err() +} + +// CountNetFlows returns total stored rows in net_flows. +func (t *Traffic) CountNetFlows() (int, error) { + if t == nil || t.db == nil { + return 0, nil + } + var n int + err := t.db.QueryRow(`SELECT count(*) FROM net_flows`).Scan(&n) + return n, err +} + +// CountDNSQueries returns total stored rows in dns_queries. +func (t *Traffic) CountDNSQueries() (int, error) { + if t == nil || t.db == nil { + return 0, nil + } + var n int + err := t.db.QueryRow(`SELECT count(*) FROM dns_queries`).Scan(&n) + return n, err +} + +// DeleteNetFlows deletes net_flows rows, optionally restricted to one sandbox owner. +func (t *Traffic) DeleteNetFlows(scope, ownerID string) (int64, error) { + if t == nil || t.db == nil { + return 0, nil + } + t.wmu.Lock() + defer t.wmu.Unlock() + var ( + res sql.Result + err error + ) + if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" { + res, err = t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID)) + } else { + res, err = t.db.Exec(`DELETE FROM net_flows`) + } + if err != nil { + return 0, err + } + n, _ := res.RowsAffected() + if n > 0 { + t.reclaim() + } + return n, nil +} + +// DeleteDNSQueries deletes dns_queries rows, optionally restricted to one sandbox owner. +func (t *Traffic) DeleteDNSQueries(scope, ownerID string) (int64, error) { + if t == nil || t.db == nil { + return 0, nil + } + t.wmu.Lock() + defer t.wmu.Unlock() + var ( + res sql.Result + err error + ) + if strings.TrimSpace(scope) != "" && strings.TrimSpace(ownerID) != "" { + res, err = t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, strings.TrimSpace(scope), strings.TrimSpace(ownerID)) + } else { + res, err = t.db.Exec(`DELETE FROM dns_queries`) + } + if err != nil { + return 0, err + } + n, _ := res.RowsAffected() + if n > 0 { + t.reclaim() + } + return n, nil +} + +// DeleteNonHTTPByOwner deletes both net_flows and dns_queries attributed to one +// sandbox owner (used when deleting a task with DeleteTraffic enabled). +func (t *Traffic) DeleteNonHTTPByOwner(scope, ownerID string) (int64, error) { + if t == nil || t.db == nil || strings.TrimSpace(scope) == "" || strings.TrimSpace(ownerID) == "" { + return 0, nil + } + t.wmu.Lock() + defer t.wmu.Unlock() + var total int64 + if res, err := t.db.Exec(`DELETE FROM net_flows WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil { + n, _ := res.RowsAffected() + total += n + } else { + return 0, err + } + if res, err := t.db.Exec(`DELETE FROM dns_queries WHERE sandbox_scope=? AND sandbox_owner_id=?`, scope, ownerID); err == nil { + n, _ := res.RowsAffected() + total += n + } else { + return total, err + } + if total > 0 { + t.reclaim() + } + return total, nil +} + +var _ = atomic.Int64{} diff --git a/traffic/netstack.go b/traffic/netstack.go new file mode 100644 index 0000000..2ae8576 --- /dev/null +++ b/traffic/netstack.go @@ -0,0 +1,1378 @@ +package traffic + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "net/url" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "github.com/miekg/dns" + "gvisor.dev/gvisor/pkg/buffer" + "gvisor.dev/gvisor/pkg/tcpip" + "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet" + "gvisor.dev/gvisor/pkg/tcpip/header" + "gvisor.dev/gvisor/pkg/tcpip/link/channel" + "gvisor.dev/gvisor/pkg/tcpip/network/ipv4" + "gvisor.dev/gvisor/pkg/tcpip/network/ipv6" + "gvisor.dev/gvisor/pkg/tcpip/stack" + "gvisor.dev/gvisor/pkg/tcpip/transport/icmp" + "gvisor.dev/gvisor/pkg/tcpip/transport/tcp" + "gvisor.dev/gvisor/pkg/tcpip/transport/udp" + "gvisor.dev/gvisor/pkg/waiter" +) + +const ( + netstackNICID tcpip.NICID = 1 + netstackDefaultMTU uint32 = 1500 + netstackMaxInFlightTCP = 8192 + netstackMaxPendingDials = 4096 + netstackDefaultDialTTL = 2500 * time.Millisecond +) + +// NetstackConfig configures the gVisor user-space TCP/IP stack attached to a +// TUN device (or in-memory packet pipe in tests). +type NetstackConfig struct { + MTU uint32 + MITMProxyAddr string + PeekTimeout time.Duration + DialTimeout time.Duration + MaxPendingDials int + // Optional L3 anti-spoofing guard: when set, drop inbound IPv4 packets whose + // source IP is outside AllowedSrcCIDR or matches any DeniedSrcIPs entry. + AllowedSrcCIDR string + DeniedSrcIPs []string + // Optional hooks for unit tests to override upstream TCP dialing / ICMP echo. + DialFunc func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) + ICMPPingFunc func(ctx context.Context, dstIP net.IP, seq uint16, payload []byte) ([]byte, error) +} + +// NetstackGateway implements full-traffic transparent interception over a TUN +// interface using gVisor netstack with DEFERRED TCP HANDSHAKES: +// +// - On incoming TCP SYN, no SYN-ACK is sent until SSRF/blacklist checks pass +// AND the real remote target (or upstream proxy) accepts the connection. +// - Remote ECONNREFUSED => sends genuine TCP RST (nmap reports "closed"). +// - Remote dial timeout => silently drops SYN (nmap reports "filtered"). +// - Remote dial success => completes 3-way handshake (nmap reports "open"), +// sniffs HTTP/TLS for go-mitmproxy MITM decryption, or reuses the already +// established remote socket directly for raw TCP L4 relay + net_flows capture. +// - External TCP/53 => uses the same deferred handshake to the real dstIP:53, +// then inspects/logs DNS-over-TCP frames (never hijacked to host DNS). +// - External UDP/53 => forwarded to dstIP:53 (or via upstream proxy to dstIP:53). +// - Non-DNS UDP => subject to SSRF/blacklist and OPSEC UDPPolicy + net_flows. +type NetstackGateway struct { + cfg NetstackConfig + gw *TransparentGateway + backend TransparentBackend + + allowedNet *net.IPNet + deniedSrcIP map[string]struct{} + + dev io.ReadWriteCloser + ep *channel.Endpoint + stk *stack.Stack + dialCh chan struct{} + icmpID atomic.Uint32 + + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +// NewNetstackGateway creates a gVisor netstack gateway reading/writing raw L3 +// IP packets on dev (a Linux TUN fd or test packet pipe). +func NewNetstackGateway(dev io.ReadWriteCloser, cfg NetstackConfig, backend TransparentBackend) (*NetstackGateway, error) { + if dev == nil { + return nil, errors.New("netstack device is nil") + } + if cfg.MTU == 0 { + cfg.MTU = netstackDefaultMTU + } + if cfg.PeekTimeout <= 0 { + cfg.PeekTimeout = 200 * time.Millisecond + } + if cfg.DialTimeout <= 0 { + cfg.DialTimeout = netstackDefaultDialTTL + } + if cfg.MaxPendingDials <= 0 { + cfg.MaxPendingDials = netstackMaxPendingDials + } + + ep := channel.New(2048, cfg.MTU, "") + s := stack.New(stack.Options{ + NetworkProtocols: []stack.NetworkProtocolFactory{ + ipv4.NewProtocol, + ipv6.NewProtocol, + }, + TransportProtocols: []stack.TransportProtocolFactory{ + tcp.NewProtocol, + udp.NewProtocol, + icmp.NewProtocol4, + icmp.NewProtocol6, + }, + }) + + sackOpt := tcpip.TCPSACKEnabled(true) + _ = s.SetTransportProtocolOption(tcp.ProtocolNumber, &sackOpt) + + if err := s.CreateNIC(netstackNICID, ep); err != nil { + return nil, fmt.Errorf("netstack create NIC: %v", err) + } + if err := s.SetPromiscuousMode(netstackNICID, true); err != nil { + s.Destroy() + return nil, fmt.Errorf("netstack set promiscuous: %v", err) + } + if err := s.SetSpoofing(netstackNICID, true); err != nil { + s.Destroy() + return nil, fmt.Errorf("netstack set spoofing: %v", err) + } + s.SetRouteTable([]tcpip.Route{ + {Destination: header.IPv4EmptySubnet, NIC: netstackNICID}, + {Destination: header.IPv6EmptySubnet, NIC: netstackNICID}, + }) + + var allowedNet *net.IPNet + if cidr := strings.TrimSpace(cfg.AllowedSrcCIDR); cidr != "" { + if _, parsed, err := net.ParseCIDR(cidr); err == nil { + allowedNet = parsed + } + } + deniedSrc := make(map[string]struct{}, len(cfg.DeniedSrcIPs)) + for _, raw := range cfg.DeniedSrcIPs { + if ip := normalizeIPString(raw); ip != "" { + deniedSrc[ip] = struct{}{} + } + } + + ctx, cancel := context.WithCancel(context.Background()) + ng := &NetstackGateway{ + cfg: cfg, + gw: NewTransparentGateway(TransparentConfig{ + MITMProxyAddr: cfg.MITMProxyAddr, + PeekTimeout: cfg.PeekTimeout, + DialTimeout: cfg.DialTimeout, + }, backend), + backend: backend, + allowedNet: allowedNet, + deniedSrcIP: deniedSrc, + dev: dev, + ep: ep, + stk: s, + dialCh: make(chan struct{}, cfg.MaxPendingDials), + ctx: ctx, + cancel: cancel, + } + tcpFwd := tcp.NewForwarder(s, 0, netstackMaxInFlightTCP, ng.handleTCPForward) + s.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpFwd.HandlePacket) + + udpFwd := udp.NewForwarder(s, ng.handleUDPForward) + s.SetTransportProtocolHandler(udp.ProtocolNumber, udpFwd.HandlePacket) + + return ng, nil +} + +// Start begins pumping L3 IP packets between the TUN device and gVisor netstack. +func (n *NetstackGateway) Start() { + n.wg.Add(2) + go func() { + defer n.wg.Done() + n.pumpInbound() + }() + go func() { + defer n.wg.Done() + n.pumpOutbound() + }() +} + +// Close tears down the TUN packet pumps and gVisor stack. +func (n *NetstackGateway) Close() error { + n.cancel() + _ = n.dev.Close() + n.ep.Close() + n.stk.Destroy() + _ = n.gw.Close() + n.wg.Wait() + return nil +} + +func (n *NetstackGateway) pumpInbound() { + buf := make([]byte, int(n.cfg.MTU)+64) + var lastErrLog time.Time + for { + nr, err := n.dev.Read(buf) + if err != nil { + select { + case <-n.ctx.Done(): + return + default: + } + if errors.Is(err, io.EOF) { + return + } + if time.Since(lastErrLog) > 5*time.Second { + log.Printf("[netstack] tun read error: %v", err) + lastErrLog = time.Now() + } + time.Sleep(25 * time.Millisecond) + continue + } + if nr < 1 { + continue + } + var proto tcpip.NetworkProtocolNumber + var isIPv4Echo bool + switch header.IPVersion(buf[:nr]) { + case header.IPv4Version: + if nr < header.IPv4MinimumSize { + continue + } + ip4 := header.IPv4(buf[:nr]) + if n.allowedNet != nil || len(n.deniedSrcIP) > 0 { + srcAddr := ip4.SourceAddress() + srcIP := net.IP(srcAddr.AsSlice()) + if n.allowedNet != nil && !n.allowedNet.Contains(srcIP) { + continue + } + if _, denied := n.deniedSrcIP[srcIP.String()]; denied { + continue + } + } + ihl := int(ip4.HeaderLength()) + if ip4.Protocol() == uint8(header.ICMPv4ProtocolNumber) && ihl >= header.IPv4MinimumSize && nr >= ihl+header.ICMPv4MinimumSize { + if header.ICMPv4(buf[ihl:nr]).Type() == header.ICMPv4Echo { + isIPv4Echo = true + } + } + proto = header.IPv4ProtocolNumber + case header.IPv6Version: + if nr < header.IPv6MinimumSize { + continue + } + if n.allowedNet != nil || len(n.deniedSrcIP) > 0 { + srcAddr := header.IPv6(buf[:nr]).SourceAddress() + srcIP := net.IP(srcAddr.AsSlice()) + if n.allowedNet != nil && !n.allowedNet.Contains(srcIP) { + continue + } + if _, denied := n.deniedSrcIP[srcIP.String()]; denied { + continue + } + } + proto = header.IPv6ProtocolNumber + default: + continue + } + pktData := make([]byte, nr) + copy(pktData, buf[:nr]) + if isIPv4Echo { + // Intercept ICMPv4 Echo BEFORE gVisor's promiscuous stack can synthesize + // a fake local Echo Reply for dead or blocked targets. + select { + case n.dialCh <- struct{}{}: + go func(raw []byte) { + defer func() { <-n.dialCh }() + n.handleICMPv4Echo(raw) + }(pktData) + default: + } + continue + } + pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{ + Payload: buffer.MakeWithData(pktData), + }) + n.ep.InjectInbound(proto, pkt) + pkt.DecRef() + } +} + +func (n *NetstackGateway) pumpOutbound() { + var lastErrLog time.Time + for { + pkt := n.ep.ReadContext(n.ctx) + if pkt == nil { + return + } + view := pkt.ToView() + _, err := n.dev.Write(view.AsSlice()) + view.Release() + pkt.DecRef() + if err != nil { + select { + case <-n.ctx.Done(): + return + default: + } + if time.Since(lastErrLog) > 5*time.Second { + log.Printf("[netstack] tun write error: %v", err) + lastErrLog = time.Now() + } + } + } +} + +// handleTCPForward implements deferred-handshake TCP interception: +// the remote target is checked and dialed BEFORE completing the 3-way handshake +// with the sandbox container so nmap/nc accurately observe open/closed/filtered. +func (n *NetstackGateway) handleTCPForward(r *tcp.ForwarderRequest) { + id := r.ID() + srcIP := normalizeIP(net.IP(id.RemoteAddress.AsSlice())).String() + srcPort := int(id.RemotePort) + dstIP := normalizeIP(net.IP(id.LocalAddress.AsSlice())).String() + dstPort := int(id.LocalPort) + + // Guard against SYN flood / full-port-scan goroutine exhaustion. + // Drop silently (sendReset=false) when saturated so scanners back off and + // retry instead of falsely classifying open/filtered ports as "closed". + select { + case n.dialCh <- struct{}{}: + default: + r.Complete(false) + return + } + + go func() { + released := false + releaseSlot := func() { + if !released { + released = true + <-n.dialCh + } + } + defer releaseSlot() + n.processTCPForward(r, srcIP, srcPort, dstIP, dstPort, releaseSlot) + }() +} + +func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP string, srcPort int, dstIP string, dstPort int, releaseDialSlot func()) { + start := time.Now() + src := n.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + + dstHost := n.backend.LookupDNSReverse(dstIP) + if dstHost == "" { + dstHost = dstIP + } + + // Pre-dial SSRF guard + egress blacklist check (IP & reverse-DNS hostname). + targetIPPort := net.JoinHostPort(dstIP, strconv.Itoa(dstPort)) + targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + var blocked *BlockDecision + if dstHost != dstIP { + blocked = n.backend.CheckOutbound(targetHostPort, "tcp", src) + } + if blocked == nil { + blocked = n.backend.CheckOutbound(targetIPPort, "tcp", src) + } + if blocked != nil { + r.Complete(true) // immediate TCP RST + n.recordTCPBlock(start, "tcp", src, srcPort, dstIP, dstHost, dstPort, "", blocked) + return + } + + // Deferred handshake: dial real destination (direct or via upstream proxy) BEFORE + // sending SYN-ACK to the sandbox container! + upstream := n.backend.ResolveUpstream(src) + upstreamLabel := MaskProxyURL(upstream) + dialTarget := targetIPPort + if upstream != nil && dstHost != "" && dstHost != dstIP { + dialTarget = targetHostPort + } + + dialTimeout := n.cfg.DialTimeout + if upstream != nil && dialTimeout < 5*time.Second { + dialTimeout = 5 * time.Second + } + dialCtx, cancel := context.WithTimeout(n.ctx, dialTimeout) + dialFn := n.cfg.DialFunc + if dialFn == nil { + dialFn = dialTCPThroughUpstream + } + dstConn, err := dialFn(dialCtx, upstream, dialTarget, dialTimeout) + cancel() + // Dial phase finished: free the pending-dial slot immediately so long-lived + // established connections do not starve new outbound dials or port scans. + if releaseDialSlot != nil { + releaseDialSlot() + } + if err != nil { + // Distinguish closed/refused (send RST -> nmap "closed") from timeout/drop + // (drop silently -> nmap "filtered"). + sendRST := !isDialTimeoutErr(err) + r.Complete(sendRST) + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(start).Milliseconds(), + Protocol: "tcp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "error", + UpstreamProxy: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + Error: err.Error(), + }) + return + } + + // Remote port is genuinely OPEN -> now complete 3-way handshake with sandbox. + var wq waiter.Queue + ep, tcpErr := r.CreateEndpoint(&wq) + r.Complete(false) + if tcpErr != nil { + _ = dstConn.Close() + // Remote TCP handshake genuinely succeeded (e.g. nmap -sT received SYN-ACK, + // sent ACK, and immediately sent RST before CreateEndpoint returned). Record + // the allowed flow so open-port scan hits are visible in net_flows. + end := time.Now() + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: "tcp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "allow", + UpstreamProxy: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) + return + } + rawClientConn := gonet.NewTCPConn(&wq, ep) + defer rawClientConn.Close() + + // Peek client's first bytes to classify HTTP / TLS / raw TCP. + sniff, clientConn := SniffProtocol(rawClientConn, n.cfg.PeekTimeout) + + // Re-resolve logical host using SNI / HTTP Host if available, and re-check blacklist. + logicalHost := dstHost + if sniff.SNI != "" { + logicalHost = sniff.SNI + } else if sniff.Host != "" { + h, _ := splitHostAndPort(sniff.Host) + if strings.TrimSpace(h) != "" { + logicalHost = strings.TrimSpace(h) + } + } + if logicalHost != dstHost && logicalHost != dstIP { + scheme := string(sniff.Proto) + if sniff.Proto == ProtoTLS { + scheme = "https" + } + if b2 := n.backend.CheckOutbound(net.JoinHostPort(logicalHost, strconv.Itoa(dstPort)), scheme, src); b2 != nil { + _ = dstConn.Close() + n.recordTCPBlock(start, string(sniff.Proto), src, srcPort, dstIP, logicalHost, dstPort, sniff.SNI, b2) + return + } + } + + // Route sniffed HTTP/TLS into go-mitmproxy when MITM is enabled and host is not downgraded. + mitmAddr := strings.TrimSpace(n.cfg.MITMProxyAddr) + if mitmAddr != "" { + if sniff.Proto == ProtoHTTP { + _ = dstConn.Close() + n.gw.forwardHTTPToMITM(clientConn, mitmAddr, logicalHost, dstPort, src) + return + } + if sniff.Proto == ProtoTLS && !n.backend.IsPassthrough(logicalHost) { + _ = dstConn.Close() + _ = n.gw.forwardTLSToMITM(clientConn, mitmAddr, logicalHost, dstPort, src) + return + } + } + + // Direct DNS-over-TCP to an external target:53 (already connected via deferred + // handshake) -> enforce domain/IP blacklist and log to dns_queries while talking + // to the real target socket rather than hijacking to the host's DNS resolver. + if dstPort == 53 && sniff.Proto == ProtoTCP && looksLikeTCPDNS(clientConn) { + n.serveConnectedTCPDNS(clientConn, dstConn, src, dstIP, upstreamLabel) + return + } + + // Raw TCP (SSH, MySQL, Redis, SMB, nc, nmap -sT) or TLS passthrough: + // reuse the ALREADY-CONNECTED dstConn (zero double-connect!). + action := "allow" + if sniff.Proto == ProtoTLS { + action = "passthrough" + } + n.gw.relayConnectedL4TCP(clientConn, dstConn, start, string(sniff.Proto), action, src, srcPort, dstIP, logicalHost, dstPort, sniff.SNI, upstreamLabel) +} + +func (n *NetstackGateway) recordTCPBlock(start time.Time, proto string, src SourceIdentity, srcPort int, dstIP, dstHost string, dstPort int, sni string, b *BlockDecision) { + n.backend.RecordBlockEvent(EgressBlockEvent{ + At: start.UTC(), + Host: dstHost, + Port: strconv.Itoa(dstPort), + Method: strings.ToUpper(proto), + URL: fmt.Sprintf("%s://%s:%d", proto, dstHost, dstPort), + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: b.Reason, + RuleKind: b.RuleKind, + RuleID: b.RuleID, + Pattern: b.Pattern, + Source: b.Source, + }) + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(start).Milliseconds(), + Protocol: proto, + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + SNI: sni, + Action: "block", + BlockReason: b.Reason, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) +} + +func looksLikeTCPDNS(conn net.Conn) bool { + pc, ok := conn.(*PeekConn) + if !ok || pc.br == nil { + return false + } + avail := pc.br.Buffered() + if avail < 14 { // 2-byte TCP length prefix + 12-byte DNS header minimum + return false + } + hdr, err := pc.br.Peek(2) + if err != nil { + return false + } + msgLen := int(binary.BigEndian.Uint16(hdr)) + if msgLen < 12 || msgLen > 4096 || avail < 2+msgLen { + return false + } + frame, err := pc.br.Peek(2 + msgLen) + if err != nil { + return false + } + req := new(dns.Msg) + if err := req.Unpack(frame[2:]); err != nil || req.Response || len(req.Question) == 0 { + return false + } + return true +} + +func (n *NetstackGateway) recordTCPDNSError(start time.Time, qname, qtype, upstreamTag string, src SourceIdentity, err error) { + errMsg := "tcp dns exchange failed" + if err != nil { + errMsg = err.Error() + } + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeServerFailure], + Answers: []string{}, + Action: "error", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + Error: errMsg, + }) +} + +// writeTCPDNSFrame writes the 2-octet length prefix and DNS message in a single +// Write call (RFC 7766 Section 8) so strict TCP DNS servers (e.g. AliDNS 223.5.5.5) +// do not reset connections receiving split length/payload segments. +func writeTCPDNSFrame(w io.Writer, payload []byte) error { + frame := make([]byte, 2+len(payload)) + binary.BigEndian.PutUint16(frame[:2], uint16(len(payload))) + copy(frame[2:], payload) + _, err := w.Write(frame) + return err +} + +func (n *NetstackGateway) serveConnectedTCPDNS( + clientConn, dstConn net.Conn, + src SourceIdentity, + dstIP string, + upstreamLabel string, +) { + defer dstConn.Close() + targetAddr := net.JoinHostPort(dstIP, "53") + upstreamTag := "direct-tcp:" + targetAddr + if upstreamLabel != "" && upstreamLabel != "direct" { + upstreamTag = "tcp-via:" + upstreamLabel + "->" + targetAddr + } + + for { + _ = clientConn.SetReadDeadline(time.Now().Add(8 * time.Second)) + var lenBuf [2]byte + if _, err := io.ReadFull(clientConn, lenBuf[:]); err != nil { + return + } + msgLen := int(binary.BigEndian.Uint16(lenBuf[:])) + if msgLen <= 0 || msgLen > 65535 { + return + } + raw := make([]byte, msgLen) + if _, err := io.ReadFull(clientConn, raw); err != nil { + return + } + req := new(dns.Msg) + if err := req.Unpack(raw); err != nil { + return + } + qStart := time.Now() + qname := "" + qtype := "A" + isZoneTransfer := false + if len(req.Question) > 0 { + qname = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Question[0].Name)), ".") + qtype = dns.TypeToString[req.Question[0].Qtype] + if qtype == "" { + qtype = strconv.Itoa(int(req.Question[0].Qtype)) + } + isZoneTransfer = req.Question[0].Qtype == dns.TypeAXFR || req.Question[0].Qtype == dns.TypeIXFR + } + + // Pre-resolution domain check against SSRF guard + global/task egress blacklist. + if qname != "" { + if blocked := n.backend.CheckOutbound(qname, "dns", src); blocked != nil { + refused := new(dns.Msg) + refused.SetRcode(req, dns.RcodeRefused) + n.backend.RecordBlockEvent(EgressBlockEvent{ + At: qStart.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: []string{}, + Action: "block", + BlockReason: blocked.Reason, + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + if packed, err := refused.Pack(); err == nil { + _ = writeTCPDNSFrame(clientConn, packed) + } + continue + } + } + + // Forward the framed DNS query directly to the already-connected real target dstIP:53. + _ = dstConn.SetDeadline(time.Now().Add(8 * time.Second)) + if err := writeTCPDNSFrame(dstConn, raw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + if isZoneTransfer { + // AXFR/IXFR returns a multi-message TCP stream; record the query and pipe verbatim. + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: "STREAM", + Answers: []string{}, + Action: "allow", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + _ = dstConn.SetDeadline(time.Time{}) + _ = clientConn.SetDeadline(time.Time{}) + _, _ = io.Copy(clientConn, dstConn) + return + } + + var respLenBuf [2]byte + if _, err := io.ReadFull(dstConn, respLenBuf[:]); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + respLen := int(binary.BigEndian.Uint16(respLenBuf[:])) + if respLen <= 0 || respLen > 65535 { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, fmt.Errorf("invalid dns tcp response length %d", respLen)) + return + } + respRaw := make([]byte, respLen) + if _, err := io.ReadFull(dstConn, respRaw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + reply := new(dns.Msg) + if err := reply.Unpack(respRaw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + + answers, resolvedIPs := extractDNSAnswers(reply) + blockedPost := false + for _, ipStr := range resolvedIPs { + if blocked := n.backend.CheckOutbound(ipStr, "dns", src); blocked != nil { + refused := new(dns.Msg) + refused.SetRcode(req, dns.RcodeRefused) + n.backend.RecordBlockEvent(EgressBlockEvent{ + At: qStart.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname + " -> " + ipStr, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: answers, + Action: "block", + BlockReason: blocked.Reason, + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + if packed, err := refused.Pack(); err == nil { + _ = writeTCPDNSFrame(clientConn, packed) + } + blockedPost = true + break + } + } + if blockedPost { + continue + } + + if qname != "" { + for _, ipStr := range resolvedIPs { + n.backend.RememberDNS(ipStr, qname) + } + } + rcode := dns.RcodeToString[reply.Rcode] + if rcode == "" { + rcode = strconv.Itoa(reply.Rcode) + } + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: rcode, + Answers: answers, + Action: "allow", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + + if err := writeTCPDNSFrame(clientConn, respRaw); err != nil { + return + } + } +} + +// handleUDPForward intercepts UDP packets routed into netstack: +// port 53 => ProcessDNSQuery; other ports => TransparentGateway UDP relay/policy. +func (n *NetstackGateway) handleUDPForward(r *udp.ForwarderRequest) bool { + id := r.ID() + srcIP := normalizeIP(net.IP(id.RemoteAddress.AsSlice())) + srcPort := int(id.RemotePort) + dstIP := normalizeIP(net.IP(id.LocalAddress.AsSlice())) + dstPort := int(id.LocalPort) + + var wq waiter.Queue + ep, tcpErr := r.CreateEndpoint(&wq) + if tcpErr != nil { + return false + } + uconn := gonet.NewUDPConn(&wq, ep) + + go func() { + defer uconn.Close() + srcAddr := &net.UDPAddr{IP: srcIP, Port: srcPort} + origDst := &net.UDPAddr{IP: dstIP, Port: dstPort} + if dstPort == 53 { + n.serveNetstackUDPDNS(uconn, srcAddr, origDst) + return + } + n.serveNetstackUDPRelay(uconn, srcAddr, origDst, nil) + }() + return true +} + +func (n *NetstackGateway) serveNetstackUDPDNS(uconn *gonet.UDPConn, srcAddr, origDst *net.UDPAddr) { + srcIP := srcAddr.IP.String() + dstIP := origDst.IP.String() + src := n.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + + buf := make([]byte, 4096) + for { + _ = uconn.SetReadDeadline(time.Now().Add(5 * time.Second)) + nr, _, err := uconn.ReadFrom(buf) + if err != nil { + return + } + pkt := append([]byte(nil), buf[:nr]...) + + // Pre-check SSRF / egress blacklist on the destination DNS server IP itself. + targetIPPort := net.JoinHostPort(dstIP, "53") + if blocked := n.backend.CheckOutbound(targetIPPort, "udp", src); blocked != nil { + n.gw.recordBlockedUDP(time.Now(), src, srcAddr.Port, dstIP, dstIP, 53, pkt, blocked) + return + } + + req := new(dns.Msg) + if nr == 0 || req.Unpack(pkt) != nil || len(req.Question) == 0 { + // Non-DNS probe (e.g. 0-byte or raw payload UDP scan to port 53): + // relay as raw UDP so port status is genuinely probed and recorded. + n.serveNetstackUDPRelay(uconn, srcAddr, origDst, pkt) + return + } + + // Forward directly to origDst:53 when no upstream proxy is active so + // scanning port 53 on non-DNS hosts never returns a false-positive answer. + resp, qerr := n.gw.ProcessDNSQueryToTarget(srcIP, req, false, targetIPPort) + if qerr != nil && errors.Is(qerr, syscall.ECONNREFUSED) { + n.sendICMPv4PortUnreachable(srcAddr, origDst, pkt) + return + } + if resp == nil { + continue + } + packed, err := resp.Pack() + if err != nil { + continue + } + _, _ = uconn.Write(packed) + } +} + +func (n *NetstackGateway) serveNetstackUDPRelay(uconn *gonet.UDPConn, srcAddr, origDst *net.UDPAddr, preRead []byte) { + start := time.Now() + srcIP := srcAddr.IP.String() + dstIP := origDst.IP.String() + dstPort := origDst.Port + src := n.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + dstHost := n.backend.LookupDNSReverse(dstIP) + if dstHost == "" { + dstHost = dstIP + } + + var firstPkt []byte + if preRead != nil { + firstPkt = preRead + } else { + buf := make([]byte, 65535) + _ = uconn.SetReadDeadline(time.Now().Add(5 * time.Second)) + firstN, _, err := uconn.ReadFrom(buf) + if err != nil { + return + } + firstPkt = append([]byte(nil), buf[:firstN]...) + } + + targetIPPort := net.JoinHostPort(dstIP, strconv.Itoa(dstPort)) + targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + var blocked *BlockDecision + if dstHost != dstIP { + blocked = n.backend.CheckOutbound(targetHostPort, "udp", src) + } + if blocked == nil { + blocked = n.backend.CheckOutbound(targetIPPort, "udp", src) + } + if blocked != nil { + n.gw.recordBlockedUDP(start, src, srcAddr.Port, dstIP, dstHost, dstPort, firstPkt, blocked) + return + } + + policy := NormalizeUDPPolicy(n.backend.UDPPolicy()) + upstream := n.backend.ResolveUpstream(src) + if policy == UDPPolicyBlock || (policy == UDPPolicyBlockOnProxy && upstream != nil) { + reason := "UDP 流量已被策略阻断" + if upstream != nil { + reason = "已启用出口代理,为防止真实出口 IP 泄露已阻断直连 UDP(OPSEC)" + } + n.gw.recordBlockedUDP(start, src, srcAddr.Port, dstIP, dstHost, dstPort, firstPkt, &BlockDecision{ + Reason: reason, + RuleKind: "udp_policy", + Source: "udp_policy", + }) + return + } + + remote, err := net.DialUDP("udp", nil, origDst) + if err != nil { + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(start).Milliseconds(), + Protocol: "udp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "error", + UpstreamProxy: "direct", + BytesTX: int64(len(firstPkt)), + TXPreview: clipBytes(firstPkt, maxFlowPreviewBytes), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcAddr.Port, + Error: err.Error(), + }) + return + } + defer remote.Close() + + txCap := &limitedCapture{max: maxFlowPreviewBytes} + rxCap := &limitedCapture{max: maxFlowPreviewBytes} + var bytesTX, bytesRX int64 + const ( + probeIdleTTL = 5 * time.Second + activeIdleTTL = 15 * time.Second + ) + + _, _ = txCap.Write(firstPkt) + bytesTX = int64(len(firstPkt)) + _, _ = remote.Write(firstPkt) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + rb := make([]byte, 65535) + ttl := probeIdleTTL + for { + _ = remote.SetReadDeadline(time.Now().Add(ttl)) + nr, rerr := remote.Read(rb) + if rerr != nil { + if errors.Is(rerr, syscall.ECONNREFUSED) { + n.sendICMPv4PortUnreachable(srcAddr, origDst, firstPkt) + } + _ = uconn.Close() + return + } + ttl = activeIdleTTL + if nr > 0 { + bytesRX += int64(nr) + _, _ = rxCap.Write(rb[:nr]) + if _, werr := uconn.Write(rb[:nr]); werr != nil { + return + } + } + } + }() + go func() { + defer wg.Done() + cb := make([]byte, 65535) + for { + _ = uconn.SetReadDeadline(time.Now().Add(probeIdleTTL)) + nr, _, rerr := uconn.ReadFrom(cb) + if rerr != nil { + _ = remote.Close() + return + } + bytesTX += int64(nr) + if nr > 0 { + _, _ = txCap.Write(cb[:nr]) + } + _, _ = remote.Write(cb[:nr]) + } + }() + wg.Wait() + + end := time.Now() + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: "udp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "allow", + UpstreamProxy: "direct", + BytesTX: bytesTX, + BytesRX: bytesRX, + TXPreview: txCap.Bytes(), + RXPreview: rxCap.Bytes(), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcAddr.Port, + }) +} + +func isDialTimeoutErr(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || os.IsTimeout(err) { + return true + } + // Local gateway resource exhaustion must never synthesize a remote RST ("closed"). + if errors.Is(err, syscall.EMFILE) || errors.Is(err, syscall.ENFILE) || errors.Is(err, syscall.EADDRNOTAVAIL) { + return true + } + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + return true + } + // ECONNREFUSED / EHOSTUNREACH / ENETUNREACH are active refusals, not timeouts. + if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EHOSTUNREACH) || errors.Is(err, syscall.ENETUNREACH) { + return false + } + return strings.Contains(strings.ToLower(err.Error()), "i/o timeout") +} + +// Suppress unused import warnings if log is needed for diagnostics. +var _ = log.Printf + +// sendICMPv4PortUnreachable injects a genuine ICMPv4 Destination Unreachable +// (Type 3, Code 3) packet back to the sandbox container when the real remote +// UDP target responds with ECONNREFUSED, so `nmap -sU` accurately reports +// closed UDP ports as "closed" instead of "open|filtered". +func (n *NetstackGateway) sendICMPv4PortUnreachable(clientAddr, remoteAddr *net.UDPAddr, udpPayload []byte) { + src4 := remoteAddr.IP.To4() + dst4 := clientAddr.IP.To4() + if src4 == nil || dst4 == nil { + return + } + quotePayloadLen := len(udpPayload) + if quotePayloadLen > 8 { + quotePayloadLen = 8 + } + // Quoted original packet: 20B IPv4 + 8B UDP + up to 8B payload. + quotedLen := header.IPv4MinimumSize + header.UDPMinimumSize + quotePayloadLen + icmpLen := header.ICMPv4MinimumSize + quotedLen + totalLen := header.IPv4MinimumSize + icmpLen + + pkt := make([]byte, totalLen) + // Outer IPv4 header: src=remoteAddr, dst=clientAddr, proto=ICMP. + outerIP := header.IPv4(pkt[:header.IPv4MinimumSize]) + outerIP.Encode(&header.IPv4Fields{ + TotalLength: uint16(totalLen), + TTL: 64, + Protocol: uint8(header.ICMPv4ProtocolNumber), + SrcAddr: tcpip.AddrFrom4Slice(src4), + DstAddr: tcpip.AddrFrom4Slice(dst4), + }) + outerIP.SetChecksum(^outerIP.CalculateChecksum()) + + // Quoted inner IPv4 header: src=clientAddr, dst=remoteAddr, proto=UDP. + quotedOff := header.IPv4MinimumSize + header.ICMPv4MinimumSize + innerIP := header.IPv4(pkt[quotedOff : quotedOff+header.IPv4MinimumSize]) + innerIP.Encode(&header.IPv4Fields{ + TotalLength: uint16(header.IPv4MinimumSize + header.UDPMinimumSize + len(udpPayload)), + TTL: 64, + Protocol: uint8(header.UDPProtocolNumber), + SrcAddr: tcpip.AddrFrom4Slice(dst4), + DstAddr: tcpip.AddrFrom4Slice(src4), + }) + innerIP.SetChecksum(^innerIP.CalculateChecksum()) + + // Quoted inner UDP header + up to 8 bytes of payload. + udpOff := quotedOff + header.IPv4MinimumSize + innerUDP := header.UDP(pkt[udpOff : udpOff+header.UDPMinimumSize]) + innerUDP.Encode(&header.UDPFields{ + SrcPort: uint16(clientAddr.Port), + DstPort: uint16(remoteAddr.Port), + Length: uint16(header.UDPMinimumSize + len(udpPayload)), + }) + if quotePayloadLen > 0 { + copy(pkt[udpOff+header.UDPMinimumSize:], udpPayload[:quotePayloadLen]) + } + + // ICMPv4 header (Type 3 Dest Unreachable, Code 3 Port Unreachable). + icmpHdr := header.ICMPv4(pkt[header.IPv4MinimumSize:]) + icmpHdr.SetType(header.ICMPv4DstUnreachable) + icmpHdr.SetCode(header.ICMPv4PortUnreachable) + icmpHdr.SetChecksum(0) + icmpHdr.SetChecksum(header.ICMPv4Checksum(icmpHdr, 0)) + + _, _ = n.dev.Write(pkt) +} + +// handleICMPv4Echo enforces SSRF/blacklist/OPSEC policy on sandbox ICMP Echo +// Requests and forwards allowed pings to the real destination so `ping` and +// `nmap -PE` observe genuine RTT/loss rather than gVisor's fake local replies. +func (n *NetstackGateway) handleICMPv4Echo(rawPkt []byte) { + start := time.Now() + ip4 := header.IPv4(rawPkt) + ihl := int(ip4.HeaderLength()) + if ihl < header.IPv4MinimumSize || len(rawPkt) < ihl+header.ICMPv4MinimumSize { + return + } + icmpReq := header.ICMPv4(rawPkt[ihl:]) + if icmpReq.Type() != header.ICMPv4Echo { + return + } + + srcAddr := ip4.SourceAddress() + dstAddr := ip4.DestinationAddress() + srcIPBytes := append([]byte(nil), srcAddr.AsSlice()...) + dstIPBytes := append([]byte(nil), dstAddr.AsSlice()...) + srcIP := net.IP(srcIPBytes).String() + dstIP := net.IP(dstIPBytes).String() + origID := icmpReq.Ident() + origSeq := icmpReq.Sequence() + payload := append([]byte(nil), icmpReq.Payload()...) + + src := n.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + dstHost := n.backend.LookupDNSReverse(dstIP) + if dstHost == "" { + dstHost = dstIP + } + + var blocked *BlockDecision + if dstHost != dstIP { + blocked = n.backend.CheckOutbound(net.JoinHostPort(dstHost, "0"), "icmp", src) + } + if blocked == nil { + blocked = n.backend.CheckOutbound(net.JoinHostPort(dstIP, "0"), "icmp", src) + } + if blocked != nil { + n.recordTCPBlock(start, "icmp", src, 0, dstIP, dstHost, 0, "", blocked) + return + } + + policy := NormalizeUDPPolicy(n.backend.UDPPolicy()) + upstream := n.backend.ResolveUpstream(src) + if policy == UDPPolicyBlock || (policy == UDPPolicyBlockOnProxy && upstream != nil) { + reason := "ICMP traffic blocked by gateway policy" + if upstream != nil { + reason = "Direct ICMP blocked while egress proxy is active (OPSEC)" + } + n.recordTCPBlock(start, "icmp", src, 0, dstIP, dstHost, 0, "", &BlockDecision{ + Reason: reason, + RuleKind: "udp_policy", + Source: "udp_policy", + }) + return + } + + pingTimeout := n.cfg.DialTimeout + if pingTimeout <= 0 || pingTimeout > 3*time.Second { + pingTimeout = 2 * time.Second + } + pingCtx, cancel := context.WithTimeout(n.ctx, pingTimeout) + pingFn := n.cfg.ICMPPingFunc + if pingFn == nil { + pingFn = n.defaultICMPv4Ping + } + replyPayload, err := pingFn(pingCtx, net.IP(dstIPBytes), origSeq, payload) + cancel() + + end := time.Now() + if err != nil { + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: "icmp", + DstIP: dstIP, + DstHost: dstHost, + Action: "error", + UpstreamProxy: "direct", + BytesTX: int64(len(icmpReq)), + TXPreview: clipBytes(payload, maxFlowPreviewBytes), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + Error: err.Error(), + }) + return + } + + n.sendICMPv4EchoReply(net.IP(srcIPBytes), net.IP(dstIPBytes), origID, origSeq, replyPayload) + n.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: "icmp", + DstIP: dstIP, + DstHost: dstHost, + Action: "allow", + UpstreamProxy: "direct", + BytesTX: int64(len(icmpReq)), + BytesRX: int64(header.ICMPv4MinimumSize + len(replyPayload)), + TXPreview: clipBytes(payload, maxFlowPreviewBytes), + RXPreview: clipBytes(replyPayload, maxFlowPreviewBytes), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) +} + +func (n *NetstackGateway) defaultICMPv4Ping(ctx context.Context, dstIP net.IP, seq uint16, payload []byte) ([]byte, error) { + conn, err := net.DialIP("ip4:icmp", nil, &net.IPAddr{IP: dstIP}) + if err != nil { + return nil, err + } + defer conn.Close() + if dl, ok := ctx.Deadline(); ok { + _ = conn.SetDeadline(dl) + } + + // Use a unique per-probe Echo ID so concurrent sandbox pings never cross-talk. + probeID := uint16((n.icmpID.Add(1) & 0x7fff) | 0x8000) + reqBuf := make([]byte, header.ICMPv4MinimumSize+len(payload)) + reqICMP := header.ICMPv4(reqBuf) + reqICMP.SetType(header.ICMPv4Echo) + reqICMP.SetCode(0) + reqICMP.SetIdent(probeID) + reqICMP.SetSequence(seq) + copy(reqBuf[header.ICMPv4MinimumSize:], payload) + reqICMP.SetChecksum(0) + reqICMP.SetChecksum(header.ICMPv4Checksum(reqICMP, 0)) + + if _, err := conn.Write(reqBuf); err != nil { + return nil, err + } + + rb := make([]byte, 2048) + for { + nr, err := conn.Read(rb) + if err != nil { + return nil, err + } + if nr < header.IPv4MinimumSize+header.ICMPv4MinimumSize { + continue + } + // Raw ip4:icmp sockets include the outer IPv4 header on read. + ihl := int(rb[0]&0x0f) * 4 + if ihl < header.IPv4MinimumSize || nr < ihl+header.ICMPv4MinimumSize { + continue + } + resp := header.ICMPv4(rb[ihl:nr]) + if resp.Type() == header.ICMPv4EchoReply && resp.Ident() == probeID && resp.Sequence() == seq { + return append([]byte(nil), resp.Payload()...), nil + } + } +} + +func (n *NetstackGateway) sendICMPv4EchoReply(clientIP, remoteIP net.IP, id, seq uint16, payload []byte) { + src4 := remoteIP.To4() + dst4 := clientIP.To4() + if src4 == nil || dst4 == nil { + return + } + totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload) + if totalLen > int(n.cfg.MTU) { + payload = payload[:int(n.cfg.MTU)-header.IPv4MinimumSize-header.ICMPv4MinimumSize] + totalLen = header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload) + } + pkt := make([]byte, totalLen) + outerIP := header.IPv4(pkt[:header.IPv4MinimumSize]) + outerIP.Encode(&header.IPv4Fields{ + TotalLength: uint16(totalLen), + TTL: 64, + Protocol: uint8(header.ICMPv4ProtocolNumber), + SrcAddr: tcpip.AddrFrom4Slice(src4), + DstAddr: tcpip.AddrFrom4Slice(dst4), + }) + outerIP.SetChecksum(^outerIP.CalculateChecksum()) + + replyICMP := header.ICMPv4(pkt[header.IPv4MinimumSize:]) + replyICMP.SetType(header.ICMPv4EchoReply) + replyICMP.SetCode(0) + replyICMP.SetIdent(id) + replyICMP.SetSequence(seq) + copy(pkt[header.IPv4MinimumSize+header.ICMPv4MinimumSize:], payload) + replyICMP.SetChecksum(0) + replyICMP.SetChecksum(header.ICMPv4Checksum(replyICMP, 0)) + _, _ = n.dev.Write(pkt) +} diff --git a/traffic/netstack_test.go b/traffic/netstack_test.go new file mode 100644 index 0000000..76bcb5b --- /dev/null +++ b/traffic/netstack_test.go @@ -0,0 +1,850 @@ +package traffic + +import ( + "bufio" + "context" + "encoding/binary" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/miekg/dns" + "gvisor.dev/gvisor/pkg/tcpip" + "gvisor.dev/gvisor/pkg/tcpip/checksum" + "gvisor.dev/gvisor/pkg/tcpip/header" +) + +// memTunPipe simulates a Linux TUN L3 packet device in memory so NetstackGateway's +// deferred TCP handshake (SYN-ACK on open vs RST on closed/blocked) can be tested +// deterministically on any OS without CAP_NET_ADMIN. +type memTunPipe struct { + in chan []byte + out chan []byte + end chan struct{} +} + +func newMemTunPipe() *memTunPipe { + return &memTunPipe{ + in: make(chan []byte, 64), + out: make(chan []byte, 64), + end: make(chan struct{}), + } +} + +func (p *memTunPipe) Read(b []byte) (int, error) { + select { + case pkt := <-p.in: + return copy(b, pkt), nil + case <-p.end: + return 0, io.EOF + } +} + +func (p *memTunPipe) Write(b []byte) (int, error) { + cp := append([]byte(nil), b...) + select { + case p.out <- cp: + return len(b), nil + case <-p.end: + return 0, io.ErrClosedPipe + } +} + +func (p *memTunPipe) Close() error { + select { + case <-p.end: + default: + close(p.end) + } + return nil +} + +func buildIPv4TCPSYN(srcIP, dstIP net.IP, srcPort, dstPort uint16, seq uint32) []byte { + const ipLen = header.IPv4MinimumSize + const tcpLen = header.TCPMinimumSize + pkt := make([]byte, ipLen+tcpLen) + + ip := header.IPv4(pkt[:ipLen]) + ip.Encode(&header.IPv4Fields{ + TotalLength: uint16(len(pkt)), + ID: 1, + TTL: 64, + Protocol: uint8(header.TCPProtocolNumber), + SrcAddr: header.IPv4(pkt).SourceAddress(), // overwritten below + }) + copy(pkt[12:16], srcIP.To4()) + copy(pkt[16:20], dstIP.To4()) + ip.SetChecksum(0) + ip.SetChecksum(^ip.CalculateChecksum()) + + tcpHdr := header.TCP(pkt[ipLen:]) + binary.BigEndian.PutUint16(tcpHdr[0:2], srcPort) + binary.BigEndian.PutUint16(tcpHdr[2:4], dstPort) + binary.BigEndian.PutUint32(tcpHdr[4:8], seq) + tcpHdr[12] = (tcpLen / 4) << 4 + tcpHdr[13] = uint8(header.TCPFlagSyn) + binary.BigEndian.PutUint16(tcpHdr[14:16], 65535) + + xsum := header.PseudoHeaderChecksum(header.TCPProtocolNumber, ip.SourceAddress(), ip.DestinationAddress(), uint16(tcpLen)) + xsum = checksum.Checksum(tcpHdr, xsum) + tcpHdr.SetChecksum(^xsum) + return pkt +} + +func parseTCPFlags(pkt []byte) (header.TCPFlags, bool) { + if len(pkt) < header.IPv4MinimumSize+header.TCPMinimumSize || header.IPVersion(pkt) != header.IPv4Version { + return 0, false + } + ip := header.IPv4(pkt) + if ip.TransportProtocol() != header.TCPProtocolNumber { + return 0, false + } + tcpHdr := header.TCP(pkt[ip.HeaderLength():]) + return tcpHdr.Flags(), true +} + +func TestNetstackDeferredTCPHandshakeOpenClosedBlocked(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "task", OwnerID: "218", ContainerID: "sbx218", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + tr.SetEgressBlacklist([]EgressBlacklistRule{ + {ID: "blk-1", Enabled: true, Kind: "ip", Pattern: "198.51.100.99"}, + }) + + // 1. Start a real open TCP listener on loopback. + openLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen open: %v", err) + } + defer openLn.Close() + go func() { + for { + c, err := openLn.Accept() + if err != nil { + return + } + _ = c.Close() + } + }() + openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) + + // 2. Reserve and immediately close a port to guarantee ECONNREFUSED ("closed"). + closedLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen closed probe: %v", err) + } + closedPort := uint16(closedLn.Addr().(*net.TCPAddr).Port) + _ = closedLn.Close() + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 200 * time.Millisecond, + PeekTimeout: 50 * time.Millisecond, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + switch target { + case fmt.Sprintf("203.0.113.10:%d", openPort): + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) + case fmt.Sprintf("203.0.113.10:%d", closedPort): + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", closedPort), timeout) + case "203.0.113.20:80": + return nil, context.DeadlineExceeded + default: + return dialTCPThroughUpstream(ctx, upstream, target, timeout) + } + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + readReplyFlags := func(t *testing.T, label string) header.TCPFlags { + t.Helper() + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + if !ok { + t.Fatalf("%s: non-TCP reply packet (%d bytes)", label, len(pkt)) + } + return flags + case <-time.After(3 * time.Second): + t.Fatalf("%s: timed out waiting for reply packet", label) + return 0 + } + } + + // Case A: OPEN port => MUST reply SYN+ACK. + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41001, openPort, 100) + flagsOpen := readReplyFlags(t, "open port") + if !flagsOpen.Contains(header.TCPFlagSyn | header.TCPFlagAck) { + t.Fatalf("open port: expected SYN+ACK, got flags=%v", flagsOpen) + } + + // Case B: CLOSED port (ECONNREFUSED) => MUST reply RST (NEVER SYN+ACK -> zero nmap false positives!). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 41002, closedPort, 200) + flagsClosed := readReplyFlags(t, "closed port") + if !flagsClosed.Contains(header.TCPFlagRst) || flagsClosed.Contains(header.TCPFlagSyn) { + t.Fatalf("closed port: expected RST without SYN, got flags=%v", flagsClosed) + } + + // Case C: FILTERED port (timeout) => MUST drop silently (neither SYN+ACK nor RST!). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.20"), 41004, 80, 250) + select { + case pkt := <-pipe.out: + flags, _ := parseTCPFlags(pkt) + t.Fatalf("filtered port: expected silent drop, got reply packet with flags=%v", flags) + case <-time.After(150 * time.Millisecond): + } + + // Case D: BLACKLISTED IP => MUST reply immediate RST and record net_flows(action=block). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("198.51.100.99"), 41003, 80, 300) + flagsBlocked := readReplyFlags(t, "blacklisted IP") + if !flagsBlocked.Contains(header.TCPFlagRst) || flagsBlocked.Contains(header.TCPFlagSyn) { + t.Fatalf("blacklisted IP: expected RST without SYN, got flags=%v", flagsBlocked) + } + + deadline := time.Now().Add(2 * time.Second) + var blocked []NetFlowRecord + for time.Now().Before(deadline) { + rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "218", Action: "block"}, 0, 10) + if len(rows) > 0 { + blocked = rows + break + } + time.Sleep(20 * time.Millisecond) + } + if len(blocked) != 1 || blocked[0].DstIP != "198.51.100.99" { + t.Fatalf("expected 1 blocked net_flow for 198.51.100.99, got %+v", blocked) + } +} + +func TestGatewayTokenAttributionAcrossDockerBridge(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + tr.SetGatewayToken("gw-secret-218") + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "session", OwnerID: "conv-6", ContainerID: "abcdef123456", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + + // Simulated docker-proxy source IP (172.19.0.1) carrying valid gateway token must resolve to 172.30.0.3 / session:conv-6. + authVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "gw-secret-218") + h := http.Header{"Proxy-Authorization": []string{"Basic " + authVal}} + src := tr.resolveSourceForConn("172.19.0.1:51234", h) + if src.SrcIP != "172.30.0.3" || src.Scope != "session" || src.OwnerID != "conv-6" { + t.Fatalf("valid gateway token from docker-proxy should preserve attribution, got %+v", src) + } + + // Wrong token from non-loopback must NOT trust forwarded SrcIP. + badVal := FormatProxyContextAuthValue(SourceIdentity{SrcIP: "172.30.0.3"}, "wrong-token") + hBad := http.Header{"Proxy-Authorization": []string{"Basic " + badVal}} + srcBad := tr.resolveSourceForConn("172.19.0.1:51235", hBad) + if srcBad.SrcIP != "172.19.0.1" || srcBad.Scope != "" { + t.Fatalf("invalid gateway token must not spoof attribution, got %+v", srcBad) + } +} + +func TestSSRFGuardHostNetworkModeInfraPorts(t *testing.T) { + g := newSSRFGuard(SSRFGuardConfig{ + Enabled: true, + InfraIPs: []net.IP{net.ParseIP("192.168.110.238")}, + HostNetworkMode: true, + }) + if r := g.Check("192.168.110.238:8787"); r == "" { + t.Fatalf("expected :8787 on host LAN IP to be blocked") + } + if r := g.Check("192.168.110.238:8788"); r == "" { + t.Fatalf("expected :8788 on host LAN IP to be blocked") + } + if r := g.Check("192.168.110.238:22"); r != "" { + t.Fatalf("expected :22 on host LAN IP to remain reachable, got %q", r) + } + if r := g.Check("127.0.0.1:80"); r == "" { + t.Fatalf("expected loopback 127.0.0.1:80 to remain blocked") + } +} + +func buildIPv4ICMPEcho(srcIP, dstIP net.IP, id, seq uint16, payload []byte) []byte { + totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(payload) + pkt := make([]byte, totalLen) + ip := header.IPv4(pkt[:header.IPv4MinimumSize]) + ip.Encode(&header.IPv4Fields{ + TotalLength: uint16(totalLen), + TTL: 64, + Protocol: uint8(header.ICMPv4ProtocolNumber), + SrcAddr: tcpip.AddrFrom4Slice(srcIP.To4()), + DstAddr: tcpip.AddrFrom4Slice(dstIP.To4()), + }) + ip.SetChecksum(^ip.CalculateChecksum()) + + icmp := header.ICMPv4(pkt[header.IPv4MinimumSize:]) + icmp.SetType(header.ICMPv4Echo) + icmp.SetCode(0) + icmp.SetIdent(id) + icmp.SetSequence(seq) + copy(pkt[header.IPv4MinimumSize+header.ICMPv4MinimumSize:], payload) + icmp.SetChecksum(0) + icmp.SetChecksum(header.ICMPv4Checksum(icmp, 0)) + return pkt +} + +func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetStoreErrorTraffic(true) + tr.SetEgressBlacklist([]EgressBlacklistRule{{ + ID: "blk-icmp", + Kind: "ip", + Pattern: "203.0.113.99", + Enabled: true, + }}) + + pipe := newMemTunPipe() + ng, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 300 * time.Millisecond, + AllowedSrcCIDR: "172.30.0.0/16", + DeniedSrcIPs: []string{"172.30.0.1"}, + ICMPPingFunc: func(_ context.Context, dstIP net.IP, _ uint16, payload []byte) ([]byte, error) { + if dstIP.String() == "203.0.113.10" { + return payload, nil + } + return nil, context.DeadlineExceeded + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ng.Start() + defer ng.Close() + + // 1. Live host ICMP Echo -> genuine Echo Reply with matching ID/Seq/Payload. + pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 0x1234, 7, []byte("ping-ok")) + select { + case resp := <-pipe.out: + ip4 := header.IPv4(resp) + if ip4.Protocol() != uint8(header.ICMPv4ProtocolNumber) { + t.Fatalf("expected ICMPv4 reply, got proto=%d", ip4.Protocol()) + } + icmp := header.ICMPv4(resp[ip4.HeaderLength():]) + if icmp.Type() != header.ICMPv4EchoReply || icmp.Ident() != 0x1234 || icmp.Sequence() != 7 || string(icmp.Payload()) != "ping-ok" { + t.Fatalf("unexpected ICMP echo reply: type=%d id=%#x seq=%d payload=%q", icmp.Type(), icmp.Ident(), icmp.Sequence(), string(icmp.Payload())) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for ICMP echo reply from live target") + } + + // 2. Dead host ICMP Echo -> MUST NOT receive a fake local Echo Reply from gVisor. + pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.55"), 0x1234, 8, []byte("ping-dead")) + select { + case resp := <-pipe.out: + t.Fatalf("dead host must not receive synthetic reply, got %d bytes", len(resp)) + case <-time.After(250 * time.Millisecond): + } + + // 3. Blacklisted host ICMP Echo -> no reply + recorded as blocked flow. + pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.99"), 0x1234, 9, []byte("ping-blk")) + select { + case resp := <-pipe.out: + t.Fatalf("blacklisted host must not receive reply, got %d bytes", len(resp)) + case <-time.After(200 * time.Millisecond): + } + + // 4. Spoofed source IP outside AllowedSrcCIDR or equal to gateway IP -> silently dropped. + pipe.in <- buildIPv4ICMPEcho(net.ParseIP("10.99.0.5"), net.ParseIP("203.0.113.10"), 0x5678, 1, []byte("spoof-ext")) + pipe.in <- buildIPv4ICMPEcho(net.ParseIP("172.30.0.1"), net.ParseIP("203.0.113.10"), 0x5678, 2, []byte("spoof-gw")) + select { + case resp := <-pipe.out: + t.Fatalf("spoofed source packet must be dropped, got %d bytes", len(resp)) + case <-time.After(200 * time.Millisecond): + } + + deadline := time.Now().Add(2 * time.Second) + var flows []NetFlowRecord + var total int + for time.Now().Before(deadline) { + flows, total, err = tr.PageNetFlows(NetFlowQuery{Protocol: "icmp"}, 0, 20) + if err == nil && total >= 3 { + break + } + time.Sleep(20 * time.Millisecond) + } + if err != nil || total < 3 { + t.Fatalf("expected >=3 recorded icmp flows (allow/error/block), got total=%d err=%v flows=%+v", total, err, flows) + } +} + +func TestNetstackTCP53DeferredHandshakeNoFalsePositiveAndRealDNS(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "task", OwnerID: "53", ContainerID: "sbx53", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + tr.SetEgressBlacklist([]EgressBlacklistRule{ + {ID: "blk-dom", Enabled: true, Kind: "domain", Pattern: "blocked.example"}, + }) + + // Start a mock authoritative TCP DNS server returning 198.51.100.77. + dnsLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock tcp dns: %v", err) + } + defer dnsLn.Close() + go func() { + for { + c, err := dnsLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + for { + var lb [2]byte + if _, err := io.ReadFull(conn, lb[:]); err != nil { + return + } + n := int(binary.BigEndian.Uint16(lb[:])) + buf := make([]byte, n) + if _, err := io.ReadFull(conn, buf); err != nil { + return + } + req := new(dns.Msg) + if err := req.Unpack(buf); err != nil { + return + } + resp := new(dns.Msg) + resp.SetReply(req) + if len(req.Question) > 0 { + resp.Answer = append(resp.Answer, &dns.A{ + Hdr: dns.RR_Header{Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.ParseIP("198.51.100.77"), + }) + } + packed, err := resp.Pack() + if err != nil { + return + } + var outLb [2]byte + binary.BigEndian.PutUint16(outLb[:], uint16(len(packed))) + _, _ = conn.Write(outLb[:]) + _, _ = conn.Write(packed) + } + }(c) + } + }() + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 150 * time.Millisecond, + PeekTimeout: 80 * time.Millisecond, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + switch target { + case "203.0.113.74:53": + return nil, context.DeadlineExceeded + case "203.0.113.75:53": + return nil, syscall.ECONNREFUSED + case "203.0.113.53:53": + return dialTCPThroughUpstream(ctx, upstream, dnsLn.Addr().String(), timeout) + default: + return nil, syscall.ECONNREFUSED + } + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + // 1. Filtered external target:53/TCP (repro of 47.116.200.74:53) -> MUST NOT receive SYN-ACK. + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.74"), 45001, 53, 1001) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + t.Fatalf("filtered TCP/53 must drop silently, got tcp=%v flags=%v", ok, flags) + case <-time.After(300 * time.Millisecond): + } + + // 2. Closed external target:53/TCP -> MUST receive RST (not SYN-ACK). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.75"), 45002, 53, 1002) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + if !ok || !flags.Contains(header.TCPFlagRst) || flags.Contains(header.TCPFlagSyn) { + t.Fatalf("closed TCP/53 expected RST without SYN, got ok=%v flags=%v", ok, flags) + } + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for RST on closed TCP/53") + } + + // 3. Direct unit check of serveConnectedTCPDNS against real target socket: + // allowed query gets target's real answer (198.51.100.77) and logs direct-tcp:203.0.113.53:53; + // blacklisted domain gets REFUSED and logs block without hitting upstream. + clientSide, gwClient := net.Pipe() + dstConn, err := net.DialTimeout("tcp4", dnsLn.Addr().String(), time.Second) + if err != nil { + t.Fatalf("dial mock dns: %v", err) + } + done := make(chan struct{}) + go func() { + defer close(done) + defer gwClient.Close() + sniff, peeked := SniffProtocol(gwClient, 200*time.Millisecond) + if sniff.Proto != ProtoTCP || !looksLikeTCPDNS(peeked) { + t.Errorf("expected looksLikeTCPDNS=true, proto=%s", sniff.Proto) + return + } + ns.serveConnectedTCPDNS(peeked, dstConn, SourceIdentity{Scope: "task", OwnerID: "53", SrcIP: "172.30.0.3"}, "203.0.113.53", "direct") + }() + + sendTCPQuery := func(qname string) *dns.Msg { + q := new(dns.Msg) + q.SetQuestion(dns.Fqdn(qname), dns.TypeA) + packed, err := q.Pack() + if err != nil { + t.Fatalf("pack query: %v", err) + } + var lb [2]byte + binary.BigEndian.PutUint16(lb[:], uint16(len(packed))) + if _, err := clientSide.Write(append(lb[:], packed...)); err != nil { + t.Fatalf("write query: %v", err) + } + var rlb [2]byte + if _, err := io.ReadFull(clientSide, rlb[:]); err != nil { + t.Fatalf("read resp len: %v", err) + } + rbuf := make([]byte, binary.BigEndian.Uint16(rlb[:])) + if _, err := io.ReadFull(clientSide, rbuf); err != nil { + t.Fatalf("read resp: %v", err) + } + resp := new(dns.Msg) + if err := resp.Unpack(rbuf); err != nil { + t.Fatalf("unpack resp: %v", err) + } + return resp + } + + okResp := sendTCPQuery("ok.example") + if okResp.Rcode != dns.RcodeSuccess || len(okResp.Answer) != 1 || okResp.Answer[0].(*dns.A).A.String() != "198.51.100.77" { + t.Fatalf("unexpected real TCP DNS answer: %+v", okResp) + } + blkResp := sendTCPQuery("blocked.example") + if blkResp.Rcode != dns.RcodeRefused { + t.Fatalf("expected REFUSED for blacklisted domain, got rcode=%d", blkResp.Rcode) + } + _ = clientSide.Close() + <-done + + rows, total, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 10) + if err != nil || total != 2 { + t.Fatalf("expected 2 recorded TCP DNS queries, got total=%d err=%v rows=%+v", total, err, rows) + } + var sawOK, sawBlk bool + for _, r := range rows { + if r.QName == "ok.example" && r.Action == "allow" && r.Upstream == "direct-tcp:203.0.113.53:53" { + sawOK = true + } + if r.QName == "blocked.example" && r.Action == "block" && r.Upstream == "direct-tcp:203.0.113.53:53" { + sawBlk = true + } + } + if !sawOK || !sawBlk { + t.Fatalf("expected both ok (direct-tcp:203.0.113.53:53) and blocked rows, got %+v", rows) + } +} + +func TestProcessDNSQueryToTargetUnderUpstreamProxyNeverSubstitutesHostDNS(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // Set a host DNS upstream that MUST NOT be contacted when targetServer is explicit. + tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "198.51.100.254:53") + + // Mock HTTP CONNECT proxy that records the requested CONNECT target and rejects 47.116.200.74:53. + proxyLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen proxy: %v", err) + } + defer proxyLn.Close() + var mu sync.Mutex + var connectTargets []string + go func() { + for { + c, err := proxyLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + br := bufio.NewReader(conn) + line, err := br.ReadString('\n') + if err != nil { + return + } + parts := strings.Fields(line) + if len(parts) >= 2 && parts[0] == "CONNECT" { + mu.Lock() + connectTargets = append(connectTargets, parts[1]) + mu.Unlock() + } + _, _ = conn.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n")) + }(c) + } + }() + + proxyURL, _ := url.Parse("http://" + proxyLn.Addr().String()) + tr.SetUpstreamResolver(func(SourceIdentity) (*url.URL, bool) { + return proxyURL, true + }) + + gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr}) + q := new(dns.Msg) + q.SetQuestion("example.com.", dns.TypeA) + resp, qerr := gw.ProcessDNSQueryToTarget("172.30.0.3", q, false, "47.116.200.74:53") + if resp != nil || qerr == nil { + t.Fatalf("expected (nil, err) when targetServer fails through proxy, got resp=%v err=%v", resp, qerr) + } + + mu.Lock() + got := append([]string(nil), connectTargets...) + mu.Unlock() + if len(got) != 1 || got[0] != "47.116.200.74:53" { + t.Fatalf("expected proxy CONNECT to targetServer 47.116.200.74:53 (not host DNSUpstream), got %v", got) + } +} + +func buildIPv4TCPPacket(srcIP, dstIP net.IP, srcPort, dstPort uint16, seq, ack uint32, flags header.TCPFlags) []byte { + const ipLen = header.IPv4MinimumSize + const tcpLen = header.TCPMinimumSize + pkt := make([]byte, ipLen+tcpLen) + + ip := header.IPv4(pkt[:ipLen]) + ip.Encode(&header.IPv4Fields{ + TotalLength: uint16(len(pkt)), + ID: 2, + TTL: 64, + Protocol: uint8(header.TCPProtocolNumber), + SrcAddr: header.IPv4(pkt).SourceAddress(), + }) + copy(pkt[12:16], srcIP.To4()) + copy(pkt[16:20], dstIP.To4()) + ip.SetChecksum(0) + ip.SetChecksum(^ip.CalculateChecksum()) + + tcpHdr := header.TCP(pkt[ipLen:]) + binary.BigEndian.PutUint16(tcpHdr[0:2], srcPort) + binary.BigEndian.PutUint16(tcpHdr[2:4], dstPort) + binary.BigEndian.PutUint32(tcpHdr[4:8], seq) + binary.BigEndian.PutUint32(tcpHdr[8:12], ack) + tcpHdr[12] = (tcpLen / 4) << 4 + tcpHdr[13] = uint8(flags) + binary.BigEndian.PutUint16(tcpHdr[14:16], 65535) + + xsum := header.PseudoHeaderChecksum(header.TCPProtocolNumber, ip.SourceAddress(), ip.DestinationAddress(), uint16(tcpLen)) + xsum = checksum.Checksum(tcpHdr, xsum) + tcpHdr.SetChecksum(^xsum) + return pkt +} + +func TestNetstackDialSaturationDropsSilentlyAndReleasesSlotAfterDial(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // An open listener that holds connections open until test ends. + openLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen open: %v", err) + } + defer openLn.Close() + go func() { + for { + c, err := openLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + _, _ = io.Copy(io.Discard, conn) + }(c) + } + }() + openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) + + releaseSlowDial := make(chan struct{}) + defer close(releaseSlowDial) + slowStarted := make(chan struct{}, 2) + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 2 * time.Second, + PeekTimeout: 50 * time.Millisecond, + MaxPendingDials: 1, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + if target == fmt.Sprintf("203.0.113.10:%d", openPort) { + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) + } + if target == "203.0.113.20:80" { + select { + case slowStarted <- struct{}{}: + default: + } + select { + case <-releaseSlowDial: + return nil, context.DeadlineExceeded + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return nil, syscall.ECONNREFUSED + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + // 1. Occupy the single pending-dial slot with a slow filtered target. + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.20"), 46001, 80, 100) + select { + case <-slowStarted: + case <-time.After(time.Second): + t.Fatal("timed out waiting for slow dial to start") + } + + // 2. While saturated, send another SYN -> MUST drop silently (NO synthetic RST). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.10"), 46002, openPort, 200) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + t.Fatalf("saturated dialCh must drop silently without synthetic RST, got tcp=%v flags=%v", ok, flags) + case <-time.After(250 * time.Millisecond): + } +} + +func TestNetstackQuickRSTAfterOpenHandshakeStillRecordsNetFlow(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "task", OwnerID: "3", ContainerID: "sbx3", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + + // Silent open server (does not close until peer closes, like SSH waiting for client). + openLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen open: %v", err) + } + defer openLn.Close() + go func() { + for { + c, err := openLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + _, _ = io.Copy(io.Discard, conn) + }(c) + } + }() + openPort := uint16(openLn.Addr().(*net.TCPAddr).Port) + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 500 * time.Millisecond, + PeekTimeout: 50 * time.Millisecond, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + if target == fmt.Sprintf("203.0.113.74:%d", openPort) { + return dialTCPThroughUpstream(ctx, upstream, fmt.Sprintf("127.0.0.1:%d", openPort), timeout) + } + return nil, syscall.ECONNREFUSED + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + srcIP := net.ParseIP("172.30.0.3") + dstIP := net.ParseIP("203.0.113.74") + const clientPort uint16 = 47001 + const clientISN uint32 = 5000 + + // Simulate nmap -sT: SYN -> receive SYN-ACK -> immediately send ACK + RST. + pipe.in <- buildIPv4TCPSYN(srcIP, dstIP, clientPort, openPort, clientISN) + var srvSeq uint32 + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + if !ok || !flags.Contains(header.TCPFlagSyn|header.TCPFlagAck) { + t.Fatalf("expected SYN-ACK for open port, got ok=%v flags=%v", ok, flags) + } + ip := header.IPv4(pkt) + tcpHdr := header.TCP(pkt[ip.HeaderLength():]) + srvSeq = tcpHdr.SequenceNumber() + case <-time.After(time.Second): + t.Fatal("timed out waiting for SYN-ACK") + } + + pipe.in <- buildIPv4TCPPacket(srcIP, dstIP, clientPort, openPort, clientISN+1, srvSeq+1, header.TCPFlagAck) + pipe.in <- buildIPv4TCPPacket(srcIP, dstIP, clientPort, openPort, clientISN+1, srvSeq+1, header.TCPFlagRst|header.TCPFlagAck) + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + flows, total, err := tr.PageNetFlows(NetFlowQuery{Protocol: "tcp", Action: "allow"}, 0, 10) + if err == nil && total >= 1 { + for _, f := range flows { + if f.DstIP == "203.0.113.74" && f.DstPort == int(openPort) && f.SandboxOwnerID == "3" { + return + } + } + } + time.Sleep(25 * time.Millisecond) + } + flows, total, _ := tr.PageNetFlows(NetFlowQuery{}, 0, 10) + t.Fatalf("expected allow net_flow for quick-RST nmap -sT hit, got total=%d flows=%+v", total, flows) +} diff --git a/traffic/origdst_linux.go b/traffic/origdst_linux.go new file mode 100644 index 0000000..e35afb9 --- /dev/null +++ b/traffic/origdst_linux.go @@ -0,0 +1,170 @@ +//go:build linux + +package traffic + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "net" + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +const ( + soOriginalDst = 80 // linux/netfilter_ipv4.h SO_ORIGINAL_DST + ip6tOriginalDst = 80 // linux/netfilter_ipv6/ip6_tables.h IP6T_SO_ORIGINAL_DST +) + +// originalDstTCP retrieves the pre-REDIRECT destination address of a netfilter- +// redirected TCP connection via SO_ORIGINAL_DST / IP6T_SO_ORIGINAL_DST. +func originalDstTCP(conn net.Conn) (net.IP, int, error) { + sc, ok := conn.(syscall.Conn) + if !ok { + return nil, 0, errors.New("connection does not implement syscall.Conn") + } + rc, err := sc.SyscallConn() + if err != nil { + return nil, 0, err + } + var ( + ip net.IP + port int + sockErr error + ) + if err := rc.Control(func(fd uintptr) { + var addr4 unix.RawSockaddrInet4 + vallen := uint32(unsafe.Sizeof(addr4)) + _, _, errno := unix.Syscall6( + unix.SYS_GETSOCKOPT, + fd, + unix.SOL_IP, + soOriginalDst, + uintptr(unsafe.Pointer(&addr4)), + uintptr(unsafe.Pointer(&vallen)), + 0, + ) + if errno == 0 { + ip = net.IPv4(addr4.Addr[0], addr4.Addr[1], addr4.Addr[2], addr4.Addr[3]) + port = int(binary.BigEndian.Uint16((*(*[2]byte)(unsafe.Pointer(&addr4.Port)))[:])) + return + } + var addr6 unix.RawSockaddrInet6 + vallen6 := uint32(unsafe.Sizeof(addr6)) + _, _, errno6 := unix.Syscall6( + unix.SYS_GETSOCKOPT, + fd, + unix.SOL_IPV6, + ip6tOriginalDst, + uintptr(unsafe.Pointer(&addr6)), + uintptr(unsafe.Pointer(&vallen6)), + 0, + ) + if errno6 == 0 { + b := make([]byte, net.IPv6len) + copy(b, addr6.Addr[:]) + ip = net.IP(b) + port = int(binary.BigEndian.Uint16((*(*[2]byte)(unsafe.Pointer(&addr6.Port)))[:])) + return + } + sockErr = fmt.Errorf("getsockopt SO_ORIGINAL_DST failed: ipv4=%v ipv6=%v", errno, errno6) + }); err != nil { + return nil, 0, err + } + if sockErr != nil { + return nil, 0, sockErr + } + return normalizeIP(ip), port, nil +} + +// listenTransparentUDP creates a UDP listener configured with IP_TRANSPARENT +// and IP_RECVORIGDSTADDR for Linux iptables TPROXY interception. +func listenTransparentUDP(addr string) (*net.UDPConn, error) { + lc := net.ListenConfig{ + Control: func(network, address string, c syscall.RawConn) error { + var ctrlErr error + err := c.Control(func(fd uintptr) { + _ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) + if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_TRANSPARENT, 1); err != nil { + ctrlErr = fmt.Errorf("setsockopt IP_TRANSPARENT: %w", err) + return + } + if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_RECVORIGDSTADDR, 1); err != nil { + ctrlErr = fmt.Errorf("setsockopt IP_RECVORIGDSTADDR: %w", err) + return + } + }) + if err != nil { + return err + } + return ctrlErr + }, + } + pc, err := lc.ListenPacket(context.Background(), "udp4", addr) + if err != nil { + return nil, err + } + uc, ok := pc.(*net.UDPConn) + if !ok { + _ = pc.Close() + return nil, errors.New("expected *net.UDPConn") + } + return uc, nil +} + +// readTransparentUDP reads one TPROXY UDP datagram along with its source and +// original destination addresses from the IP_ORIGDSTADDR control message. +func readTransparentUDP(conn *net.UDPConn, buf []byte) (n int, src, origDst *net.UDPAddr, err error) { + oob := make([]byte, 1024) + n, oobn, _, src, err := conn.ReadMsgUDP(buf, oob) + if err != nil { + return 0, nil, nil, err + } + msgs, parseErr := unix.ParseSocketControlMessage(oob[:oobn]) + if parseErr != nil { + return n, src, nil, parseErr + } + for _, msg := range msgs { + if msg.Header.Level == unix.SOL_IP && msg.Header.Type == unix.IP_ORIGDSTADDR && len(msg.Data) >= 8 { + port := int(binary.BigEndian.Uint16(msg.Data[2:4])) + ip := net.IPv4(msg.Data[4], msg.Data[5], msg.Data[6], msg.Data[7]) + origDst = &net.UDPAddr{IP: ip, Port: port} + break + } + } + if origDst == nil { + return n, src, nil, errors.New("missing IP_ORIGDSTADDR control message") + } + return n, src, origDst, nil +} + +// dialTransparentUDPReply sends a UDP reply packet back to clientAddr spoofed +// as coming from origDst (requires CAP_NET_ADMIN / IP_TRANSPARENT). +func sendTransparentUDPReply(origDst, clientAddr *net.UDPAddr, payload []byte) error { + d := net.Dialer{ + LocalAddr: origDst, + Control: func(network, address string, c syscall.RawConn) error { + var ctrlErr error + err := c.Control(func(fd uintptr) { + _ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) + if err := unix.SetsockoptInt(int(fd), unix.SOL_IP, unix.IP_TRANSPARENT, 1); err != nil { + ctrlErr = err + } + }) + if err != nil { + return err + } + return ctrlErr + }, + } + conn, err := d.Dial("udp4", clientAddr.String()) + if err != nil { + return err + } + defer conn.Close() + _, err = conn.Write(payload) + return err +} diff --git a/traffic/origdst_other.go b/traffic/origdst_other.go new file mode 100644 index 0000000..c39d3a8 --- /dev/null +++ b/traffic/origdst_other.go @@ -0,0 +1,32 @@ +//go:build !linux + +package traffic + +import ( + "errors" + "net" +) + +func originalDstTCP(_ net.Conn) (net.IP, int, error) { + return nil, 0, errors.New("SO_ORIGINAL_DST is only supported on Linux") +} + +func listenTransparentUDP(addr string) (*net.UDPConn, error) { + udpAddr, err := net.ResolveUDPAddr("udp", addr) + if err != nil { + return nil, err + } + return net.ListenUDP("udp", udpAddr) +} + +func readTransparentUDP(conn *net.UDPConn, buf []byte) (int, *net.UDPAddr, *net.UDPAddr, error) { + n, src, err := conn.ReadFromUDP(buf) + if err != nil { + return 0, nil, nil, err + } + return n, src, nil, errors.New("TPROXY IP_ORIGDSTADDR is only supported on Linux") +} + +func sendTransparentUDPReply(_, _ *net.UDPAddr, _ []byte) error { + return errors.New("transparent UDP reply is only supported on Linux") +} diff --git a/traffic/proxy_router.go b/traffic/proxy_router.go new file mode 100644 index 0000000..c9e427e --- /dev/null +++ b/traffic/proxy_router.go @@ -0,0 +1,163 @@ +package traffic + +import ( + "bufio" + "context" + "crypto/tls" + "encoding/base64" + "fmt" + "net" + "net/http" + "net/url" + "strings" + "time" + + xproxy "golang.org/x/net/proxy" +) + +// UpstreamResolver overrides the global upstream proxy for a specific traffic +// source (sandbox container / task / session). Returning (nil, true) forces a +// direct connection; returning (u, true) routes through u; returning (_, false) +// inherits the global upstream proxy. +type UpstreamResolver func(src SourceIdentity) (*url.URL, bool) + +// SetUpstreamResolver installs an optional per-source upstream proxy resolver +// (#218 Phase 4). Both explicit HTTP/HTTPS proxy traffic and transparent L4 +// TCP/DNS traffic honor it. +func (t *Traffic) SetUpstreamResolver(fn UpstreamResolver) { + if t == nil { + return + } + t.attrMu.Lock() + t.upstreamResolver = fn + t.attrMu.Unlock() +} + +// resolveUpstreamForSource returns the effective upstream proxy URL for src +// (nil means direct connection). +func (t *Traffic) resolveUpstreamForSource(src SourceIdentity) *url.URL { + if t == nil { + return nil + } + t.attrMu.RLock() + fn := t.upstreamResolver + t.attrMu.RUnlock() + if fn != nil { + if u, override := fn(src); override { + return u + } + } + return t.upstream.Load() +} + +// MaskProxyURL removes credentials from a proxy URL for logs/storage/UI. +func MaskProxyURL(u *url.URL) string { + if u == nil { + return "direct" + } + cp := *u + if cp.User != nil { + cp.User = url.User("***") + } + return cp.String() +} + +// dialTCPThroughUpstream establishes a TCP connection to target (host:port), +// either directly or via an HTTP/HTTPS CONNECT or SOCKS5/SOCKS5H upstream proxy. +func dialTCPThroughUpstream(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + if timeout <= 0 { + timeout = 15 * time.Second + } + baseDialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second} + if upstream == nil { + return baseDialer.DialContext(ctx, "tcp", target) + } + + scheme := strings.ToLower(strings.TrimSpace(upstream.Scheme)) + switch scheme { + case "socks5", "socks5h": + var auth *xproxy.Auth + if upstream.User != nil { + pwd, _ := upstream.User.Password() + auth = &xproxy.Auth{User: upstream.User.Username(), Password: pwd} + } + socksDialer, err := xproxy.SOCKS5("tcp", upstream.Host, auth, baseDialer) + if err != nil { + return nil, fmt.Errorf("socks5 dialer init: %w", err) + } + if cd, ok := socksDialer.(xproxy.ContextDialer); ok { + return cd.DialContext(ctx, "tcp", target) + } + return socksDialer.Dial("tcp", target) + + case "http", "https": + proxyAddr := upstream.Host + if _, _, err := net.SplitHostPort(proxyAddr); err != nil { + if scheme == "https" { + proxyAddr = net.JoinHostPort(proxyAddr, "443") + } else { + proxyAddr = net.JoinHostPort(proxyAddr, "80") + } + } + conn, err := baseDialer.DialContext(ctx, "tcp", proxyAddr) + if err != nil { + return nil, fmt.Errorf("dial http proxy %s: %w", MaskProxyURL(upstream), err) + } + if scheme == "https" { + tlsConn := tls.Client(conn, &tls.Config{ + ServerName: upstream.Hostname(), + InsecureSkipVerify: true, + }) + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = conn.Close() + return nil, fmt.Errorf("tls handshake http proxy %s: %w", MaskProxyURL(upstream), err) + } + conn = tlsConn + } + if err := httpConnectHandshake(ctx, conn, target, upstream.User); err != nil { + _ = conn.Close() + return nil, err + } + return conn, nil + + default: + return nil, fmt.Errorf("unsupported upstream proxy scheme %q", scheme) + } +} + +func httpConnectHandshake(ctx context.Context, conn net.Conn, target string, user *url.Userinfo) error { + if dl, ok := ctx.Deadline(); ok { + _ = conn.SetDeadline(dl) + defer func() { _ = conn.SetDeadline(time.Time{}) }() + } else { + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + defer func() { _ = conn.SetDeadline(time.Time{}) }() + } + var sb strings.Builder + sb.WriteString("CONNECT ") + sb.WriteString(target) + sb.WriteString(" HTTP/1.1\r\nHost: ") + sb.WriteString(target) + sb.WriteString("\r\n") + if user != nil { + pwd, _ := user.Password() + cred := base64.StdEncoding.EncodeToString([]byte(user.Username() + ":" + pwd)) + sb.WriteString("Proxy-Authorization: Basic ") + sb.WriteString(cred) + sb.WriteString("\r\n") + } + sb.WriteString("\r\n") + if _, err := conn.Write([]byte(sb.String())); err != nil { + return fmt.Errorf("send CONNECT %s: %w", target, err) + } + br := bufio.NewReader(conn) + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect}) + if err != nil { + return fmt.Errorf("read CONNECT response for %s: %w", target, err) + } + _ = resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("upstream proxy rejected CONNECT %s: %s", target, resp.Status) + } + return nil +} diff --git a/traffic/sniff.go b/traffic/sniff.go new file mode 100644 index 0000000..d098cea --- /dev/null +++ b/traffic/sniff.go @@ -0,0 +1,234 @@ +package traffic + +import ( + "bufio" + "bytes" + "encoding/binary" + "io" + "net" + "os" + "strings" + "time" +) + +// SniffedProto identifies the detected L7 protocol from a TCP stream's first bytes. +type SniffedProto string + +const ( + ProtoTCP SniffedProto = "tcp" + ProtoHTTP SniffedProto = "http" + ProtoTLS SniffedProto = "tls" +) + +// SniffResult carries the sniffed protocol plus any extracted Host / SNI. +type SniffResult struct { + Proto SniffedProto + Host string + SNI string +} + +// PeekConn wraps a net.Conn so already-peeked bytes are transparently replayed +// on subsequent Read calls. +type PeekConn struct { + net.Conn + br *bufio.Reader +} + +func (c *PeekConn) Read(p []byte) (int, error) { + return c.br.Read(p) +} + +// CloseWrite propagates TCP half-close to the underlying net.Conn so L4 relays +// deliver EOF to the peer instead of deadlocking when one side finishes first. +func (c *PeekConn) CloseWrite() error { + if cw, ok := c.Conn.(interface{ CloseWrite() error }); ok { + return cw.CloseWrite() + } + return nil +} +// SniffProtocol inspects the first bytes of a newly accepted TCP connection +// without consuming them from the returned net.Conn. +// +// If the client does not send bytes within peekTimeout (e.g. server-speaks-first +// protocols like SSH, MySQL, SMTP), it classifies the stream as raw ProtoTCP +// immediately without blocking the connection. +func SniffProtocol(conn net.Conn, peekTimeout time.Duration) (SniffResult, net.Conn) { + if peekTimeout <= 0 { + peekTimeout = 250 * time.Millisecond + } + br := bufio.NewReaderSize(conn, 4096) + wrapped := &PeekConn{Conn: conn, br: br} + + _ = conn.SetReadDeadline(time.Now().Add(peekTimeout)) + buf, err := peekAvailable(br, 2048) + _ = conn.SetReadDeadline(time.Time{}) + + if len(buf) == 0 { + if err != nil && !os.IsTimeout(err) && err != io.EOF { + return SniffResult{Proto: ProtoTCP}, wrapped + } + return SniffResult{Proto: ProtoTCP}, wrapped + } + + if sni, ok := parseTLSClientHelloSNI(buf); ok { + return SniffResult{Proto: ProtoTLS, SNI: sni, Host: sni}, wrapped + } + if host, ok := parseHTTPFirstLineHost(buf); ok { + return SniffResult{Proto: ProtoHTTP, Host: host}, wrapped + } + return SniffResult{Proto: ProtoTCP}, wrapped +} + +func peekAvailable(br *bufio.Reader, maxBytes int) ([]byte, error) { + if _, err := br.Peek(1); err != nil { + return nil, err + } + n := br.Buffered() + if n > maxBytes { + n = maxBytes + } + if n <= 0 { + return nil, nil + } + return br.Peek(n) +} + +// parseTLSClientHelloSNI checks whether buf starts with a TLS Handshake +// ClientHello record and extracts the RFC 6066 server_name (SNI) if present. +func parseTLSClientHelloSNI(buf []byte) (sni string, isTLS bool) { + if len(buf) < 6 { + return "", false + } + if buf[0] != 0x16 || buf[1] != 0x03 || buf[2] > 0x04 { + return "", false + } + if buf[5] != 0x01 { + return "", false + } + isTLS = true + + recLen := int(binary.BigEndian.Uint16(buf[3:5])) + end := 5 + recLen + if end > len(buf) { + end = len(buf) + } + p := buf[5:end] + if len(p) < 4 { + return "", true + } + p = p[4:] // handshake header + if len(p) < 34 { + return "", true + } + p = p[34:] // version + random + if len(p) < 1 { + return "", true + } + sidLen := int(p[0]) + if len(p) < 1+sidLen { + return "", true + } + p = p[1+sidLen:] + if len(p) < 2 { + return "", true + } + csLen := int(binary.BigEndian.Uint16(p[:2])) + if len(p) < 2+csLen { + return "", true + } + p = p[2+csLen:] + if len(p) < 1 { + return "", true + } + cmLen := int(p[0]) + if len(p) < 1+cmLen { + return "", true + } + p = p[1+cmLen:] + if len(p) < 2 { + return "", true + } + extTotal := int(binary.BigEndian.Uint16(p[:2])) + p = p[2:] + if extTotal < len(p) { + p = p[:extTotal] + } + for len(p) >= 4 { + extType := binary.BigEndian.Uint16(p[0:2]) + extLen := int(binary.BigEndian.Uint16(p[2:4])) + p = p[4:] + if extLen > len(p) { + break + } + if extType == 0x0000 { // server_name + ext := p[:extLen] + if len(ext) < 2 { + return "", true + } + listLen := int(binary.BigEndian.Uint16(ext[0:2])) + ext = ext[2:] + if listLen < len(ext) { + ext = ext[:listLen] + } + for len(ext) >= 3 { + nameType := ext[0] + nameLen := int(binary.BigEndian.Uint16(ext[1:3])) + ext = ext[3:] + if nameLen > len(ext) { + break + } + if nameType == 0x00 { + return strings.ToLower(strings.TrimSpace(string(ext[:nameLen]))), true + } + ext = ext[nameLen:] + } + return "", true + } + p = p[extLen:] + } + return "", true +} + +var httpMethodPrefixes = [][]byte{ + []byte("GET "), + []byte("POST "), + []byte("PUT "), + []byte("DELETE "), + []byte("HEAD "), + []byte("OPTIONS "), + []byte("PATCH "), + []byte("CONNECT "), + []byte("TRACE "), +} + +func parseHTTPFirstLineHost(buf []byte) (host string, isHTTP bool) { + matched := false + for _, m := range httpMethodPrefixes { + if bytes.HasPrefix(buf, m) { + matched = true + break + } + } + if !matched { + return "", false + } + lineEnd := bytes.IndexByte(buf, '\n') + firstLine := buf + if lineEnd > 0 { + firstLine = buf[:lineEnd] + } + if !bytes.Contains(firstLine, []byte("HTTP/1.")) && !bytes.Contains(firstLine, []byte("HTTP/2")) { + return "", false + } + lines := bytes.Split(buf, []byte("\n")) + for i := 1; i < len(lines); i++ { + line := strings.TrimSpace(string(lines[i])) + if line == "" { + break + } + if len(line) > 5 && strings.EqualFold(line[:5], "host:") { + return strings.TrimSpace(line[5:]), true + } + } + return "", true +} diff --git a/traffic/ssrf_guard.go b/traffic/ssrf_guard.go new file mode 100644 index 0000000..1c8f8d8 --- /dev/null +++ b/traffic/ssrf_guard.go @@ -0,0 +1,286 @@ +package traffic + +import ( + "fmt" + "net" + "os" + "strconv" + "strings" + "sync" +) + +// SSRFGuardConfig controls which destinations the recording proxy refuses to dial. +// Loopback, link-local / cloud metadata, and ARTEX's own internal services are +// always blocked when the guard is enabled. Private RFC1918 networks are allowed +// by default so authorized internal pentests keep working, and can be blocked by +// setting BlockPrivate=true. +type SSRFGuardConfig struct { + Enabled bool + BlockPrivate bool + BlockedHosts []string + BlockedCIDRs []*net.IPNet + // InfraIPs are machines that also host ordinary scan targets (for example the + // ARTEX host LAN address, where :18080 may be in scope). Every port on those + // addresses stays reachable except AdminPorts, which would reach this process. + InfraIPs []net.IP + AdminPorts []int + // HostNetworkMode should be set when the guard runs in the Docker host's + // network namespace (artex-gateway): local host interface IPs are protected + // on AdminPorts (via InfraIPs) rather than blocked on every port, and the + // host's LAN router is not treated as a Docker bridge hairpin address. + HostNetworkMode bool +} +type ssrfGuard struct { + mu sync.RWMutex + enabled bool + blockPrivate bool + blockedHosts map[string]struct{} + blockedIPs map[string]struct{} + blockedCIDRs []*net.IPNet + infraIPs []net.IP + adminPorts map[string]struct{} +} + +var ( + alwaysBlockedCIDRs = mustParseCIDRs( + "0.0.0.0/8", + "127.0.0.0/8", + "169.254.0.0/16", + "::1/128", + "::/128", + "fe80::/10", + "ff00::/8", + ) + privateCIDRs = mustParseCIDRs( + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "fc00::/7", + ) + alwaysBlockedHostnames = map[string]struct{}{ + "localhost": {}, + "metadata.google.internal": {}, + "metadata.goog": {}, + "host.docker.internal": {}, + "gateway.docker.internal": {}, + } +) + +func mustParseCIDRs(raw ...string) []*net.IPNet { + out := make([]*net.IPNet, 0, len(raw)) + for _, s := range raw { + _, ipnet, err := net.ParseCIDR(s) + if err == nil { + out = append(out, ipnet) + } + } + return out +} + +func newSSRFGuard(cfg SSRFGuardConfig) *ssrfGuard { + g := &ssrfGuard{ + enabled: cfg.Enabled, + blockPrivate: cfg.BlockPrivate, + blockedHosts: make(map[string]struct{}), + blockedIPs: make(map[string]struct{}), + blockedCIDRs: append([]*net.IPNet(nil), cfg.BlockedCIDRs...), + adminPorts: map[string]struct{}{"8787": {}, "8788": {}}, + } + for _, p := range cfg.AdminPorts { + if p > 0 && p < 65536 { + g.adminPorts[strconv.Itoa(p)] = struct{}{} + } + } + for _, ip := range cfg.InfraIPs { + if ip = normalizeIP(ip); ip != nil { + g.infraIPs = append(g.infraIPs, ip) + } + } + for _, h := range cfg.BlockedHosts { + h = strings.ToLower(strings.TrimSpace(h)) + if h == "" { + continue + } + if ip := net.ParseIP(h); ip != nil { + g.blockedIPs[ip.String()] = struct{}{} + continue + } + g.blockedHosts[h] = struct{}{} + if ips, err := net.LookupIP(h); err == nil { + for _, ip := range ips { + g.blockedIPs[ip.String()] = struct{}{} + } + } + } + infraSet := make(map[string]struct{}, len(g.infraIPs)) + for _, ip := range g.infraIPs { + infraSet[ip.String()] = struct{}{} + } + // Protect local interface IPs. Inside the ARTEX container, block all ports on + // container IPs (unless explicitly listed in InfraIPs). In host network mode + // (artex-gateway), protect all host interface IPs on AdminPorts via infraIPs + // so ARTEX :8787/:8788 stay unreachable while other host LAN ports remain scannable. + if addrs, err := net.InterfaceAddrs(); err == nil { + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok || ipnet.IP == nil { + continue + } + ip := normalizeIP(ipnet.IP) + if ip == nil { + continue + } + if cfg.HostNetworkMode { + if _, seen := infraSet[ip.String()]; !seen { + g.infraIPs = append(g.infraIPs, ip) + infraSet[ip.String()] = struct{}{} + } + continue + } + if _, isInfra := infraSet[ip.String()]; isInfra { + continue + } + g.blockedIPs[ip.String()] = struct{}{} + } + } + // In container mode, the default gateway is the Docker host bridge; blocking it + // stops hairpinning onto published host ports. In host network mode, the default + // gateway is the LAN router and must not be blocked on all ports. + if !cfg.HostNetworkMode { + if gw := linuxDefaultGatewayIPv4(); gw != nil { + if _, isInfra := infraSet[gw.String()]; !isInfra { + g.blockedIPs[gw.String()] = struct{}{} + } + } + } + return g +} + +func normalizeIP(ip net.IP) net.IP { + if ip == nil { + return nil + } + if v4 := ip.To4(); v4 != nil { + return v4 + } + return ip +} + +// linuxDefaultGatewayIPv4 reads the IPv4 default route. Missing on non-Linux +// and in unit tests that do not mount /proc; callers treat nil as "unknown". +func linuxDefaultGatewayIPv4() net.IP { + data, err := os.ReadFile("/proc/net/route") + if err != nil { + return nil + } + lines := strings.Split(string(data), "\n") + for _, line := range lines[1:] { + fields := strings.Fields(line) + if len(fields) < 3 || fields[1] != "00000000" { + continue + } + gw, err := strconv.ParseUint(fields[2], 16, 32) + if err != nil || gw == 0 { + continue + } + return net.IPv4(byte(gw), byte(gw>>8), byte(gw>>16), byte(gw>>24)).To4() + } + return nil +} + +// Check returns a non-empty denial reason if rawHost (host or host:port) is blocked. +func (g *ssrfGuard) Check(rawHost string) string { + if g == nil { + return "" + } + g.mu.RLock() + defer g.mu.RUnlock() + if !g.enabled { + return "" + } + host, port := splitHostAndPort(rawHost) + host = strings.ToLower(strings.TrimSpace(host)) + host = strings.TrimPrefix(host, "[") + host = strings.TrimSuffix(host, "]") + if host == "" { + return "empty target host" + } + if _, ok := alwaysBlockedHostnames[host]; ok || strings.HasSuffix(host, ".localhost") { + return fmt.Sprintf("internal host %q is blocked", host) + } + if _, ok := g.blockedHosts[host]; ok { + return fmt.Sprintf("protected service host %q is blocked", host) + } + if ip := net.ParseIP(host); ip != nil { + if reason := g.checkIP(ip); reason != "" { + return reason + } + return g.checkInfraPort(ip, port) + } + // Resolve hostname to guard against DNS rebinding / internal Docker DNS names. + ips, err := net.LookupIP(host) + if err != nil { + return "" + } + for _, ip := range ips { + if reason := g.checkIP(ip); reason != "" { + return fmt.Sprintf("%s (resolved from %s)", reason, host) + } + if reason := g.checkInfraPort(ip, port); reason != "" { + return reason + } + } + return "" +} + +func splitHostAndPort(raw string) (string, string) { + raw = strings.TrimSpace(raw) + if h, p, err := net.SplitHostPort(raw); err == nil { + return h, p + } + return raw, "" +} + +func (g *ssrfGuard) checkInfraPort(ip net.IP, port string) string { + if port == "" || len(g.infraIPs) == 0 { + return "" + } + if _, ok := g.adminPorts[port]; !ok { + return "" + } + ip = normalizeIP(ip) + for _, infra := range g.infraIPs { + if infra.Equal(ip) { + return fmt.Sprintf("ARTEX admin port %s on %s is blocked", port, ip.String()) + } + } + return "" +} + +func (g *ssrfGuard) checkIP(ip net.IP) string { + if ip == nil { + return "" + } + ip = normalizeIP(ip) + if _, ok := g.blockedIPs[ip.String()]; ok { + return fmt.Sprintf("protected host IP %s is blocked", ip.String()) + } + for _, n := range alwaysBlockedCIDRs { + if n.Contains(ip) { + return fmt.Sprintf("restricted address %s (%s) is blocked", ip.String(), n.String()) + } + } + for _, n := range g.blockedCIDRs { + if n.Contains(ip) { + return fmt.Sprintf("sandbox/internal network address %s (%s) is blocked", ip.String(), n.String()) + } + } + if g.blockPrivate { + for _, n := range privateCIDRs { + if n.Contains(ip) { + return fmt.Sprintf("private network address %s (%s) is blocked", ip.String(), n.String()) + } + } + } + return "" +} diff --git a/traffic/ssrf_guard_test.go b/traffic/ssrf_guard_test.go new file mode 100644 index 0000000..2f27999 --- /dev/null +++ b/traffic/ssrf_guard_test.go @@ -0,0 +1,69 @@ +package traffic + +import ( + "net" + "testing" +) + +func TestSSRFGuardBlocksLoopbackMetadataProtectedAndOptionalPrivate(t *testing.T) { + _, sbxNet, _ := net.ParseCIDR("172.29.0.0/16") + g := newSSRFGuard(SSRFGuardConfig{ + Enabled: true, + BlockPrivate: false, + BlockedHosts: []string{"postgres", "docker-socket-proxy", "10.99.0.2"}, + BlockedCIDRs: []*net.IPNet{sbxNet}, + }) + + blocked := []string{ + "127.0.0.1:8787", + "127.0.0.2:80", + "[::1]:8787", + "localhost:8787", + "foo.localhost:80", + "169.254.169.254:80", + "metadata.google.internal:80", + "postgres:5432", + "docker-socket-proxy:2375", + "10.99.0.2:5432", + "172.29.0.15:8080", + } + for _, h := range blocked { + if reason := g.Check(h); reason == "" { + t.Fatalf("expected %q to be blocked", h) + } + } + + // Authorized internal target allowed when BlockPrivate=false + if reason := g.Check("192.168.110.50:8080"); reason != "" { + t.Fatalf("expected internal target allowed when BlockPrivate=false, got: %s", reason) + } + if reason := g.Check("93.184.216.34:443"); reason != "" { + t.Fatalf("expected public IP allowed, got: %s", reason) + } + + // Private targets blocked when BlockPrivate=true + strict := newSSRFGuard(SSRFGuardConfig{Enabled: true, BlockPrivate: true}) + if reason := strict.Check("192.168.110.50:8080"); reason == "" { + t.Fatalf("expected private IP blocked when BlockPrivate=true") + } + if reason := strict.Check("10.0.0.1:80"); reason == "" { + t.Fatalf("expected 10/8 blocked when BlockPrivate=true") + } + + infra := newSSRFGuard(SSRFGuardConfig{ + Enabled: true, + InfraIPs: []net.IP{net.ParseIP("192.168.110.238")}, + }) + if reason := infra.Check("192.168.110.238:8787"); reason == "" { + t.Fatal("expected admin port on the ARTEX host to be blocked") + } + if reason := infra.Check("192.168.110.238:8788"); reason == "" { + t.Fatal("expected recording proxy port on the ARTEX host to be blocked") + } + if reason := infra.Check("192.168.110.238:18080"); reason != "" { + t.Fatalf("expected ordinary target port on the ARTEX host to stay open, got %s", reason) + } + if reason := infra.Check("192.168.110.50:8787"); reason != "" { + t.Fatalf("expected another LAN host on 8787 to stay open, got %s", reason) + } +} diff --git a/traffic/ssrf_proxy_test.go b/traffic/ssrf_proxy_test.go new file mode 100644 index 0000000..961e296 --- /dev/null +++ b/traffic/ssrf_proxy_test.go @@ -0,0 +1,151 @@ +package traffic + +import ( + "bufio" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" +) + +func freeLoopbackAddr(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() + return addr +} + +func startProxy(t *testing.T, guard bool) (*Traffic, string) { + t.Helper() + addr := freeLoopbackAddr(t) + tr, err := Open(t.TempDir(), addr) + if err != nil { + t.Fatal(err) + } + if guard { + tr.EnableSSRFGuard(SSRFGuardConfig{Enabled: true}) + } + go func() { _ = tr.Start() }() + t.Cleanup(func() { + _ = tr.proxy.Close() + _ = tr.Close() + }) + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + conn, err := net.DialTimeout("tcp", addr, 100*time.Millisecond) + if err == nil { + conn.Close() + return tr, addr + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("proxy did not start listening") + return nil, "" +} + +func TestProxySSRFGuardBlocksLoopbackHTTPAndConnect(t *testing.T) { + var hits atomic.Int32 + upstream, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer upstream.Close() + go func() { + for { + conn, err := upstream.Accept() + if err != nil { + return + } + hits.Add(1) + _, _ = io.WriteString(conn, "HTTP/1.1 200 OK\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}") + conn.Close() + } + }() + + _, proxyAddr := startProxy(t, true) + proxyURL, _ := url.Parse("http://" + proxyAddr) + client := &http.Client{ + Timeout: 3 * time.Second, + Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, + } + resp, err := client.Get("http://" + upstream.Addr().String() + "/api/health") + if err != nil { + t.Fatalf("guarded http request: %v", err) + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("status=%d body=%s", resp.StatusCode, body) + } + if !strings.Contains(string(body), "blocked by ARTEX proxy SSRF guard") { + t.Fatalf("body=%s", body) + } + if hits.Load() != 0 { + t.Fatalf("proxy dialed loopback %d times", hits.Load()) + } + + conn, err := net.Dial("tcp", proxyAddr) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + target := upstream.Addr().String() + if _, err := io.WriteString(conn, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n\r\n"); err != nil { + t.Fatal(err) + } + _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) + status, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + t.Fatal(err) + } + if !strings.Contains(status, "502") && !strings.Contains(status, "403") { + t.Fatalf("CONNECT status=%q", status) + } + time.Sleep(150 * time.Millisecond) + if hits.Load() != 0 { + t.Fatalf("CONNECT dialed loopback %d times", hits.Load()) + } +} + +func TestProxyForwardsLoopbackWhenGuardDisabled(t *testing.T) { + upstream := http.Server{} + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + hits := 0 + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + hits++ + w.Write([]byte("ok")) + }) + upstream.Handler = mux + go upstream.Serve(ln) + defer upstream.Close() + + _, proxyAddr := startProxy(t, false) + proxyURL, _ := url.Parse("http://" + proxyAddr) + client := &http.Client{ + Timeout: 3 * time.Second, + Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, + } + resp, err := client.Get("http://" + ln.Addr().String() + "/") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != 200 { + t.Fatalf("status=%d", resp.StatusCode) + } + if hits != 1 { + t.Fatalf("hits=%d", hits) + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index 7e4fbcc..8da700f 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -39,17 +39,23 @@ import ( const indexSchema = ` CREATE TABLE IF NOT EXISTS exchanges ( - id TEXT PRIMARY KEY, - ts INTEGER, - host TEXT, - method TEXT, - url_template TEXT, - url TEXT, - status INTEGER, - content_type TEXT, - req_len INTEGER, - resp_len INTEGER, - path TEXT + id TEXT PRIMARY KEY, + ts INTEGER, + host TEXT, + method TEXT, + url_template TEXT, + url TEXT, + status INTEGER, + content_type TEXT, + req_len INTEGER, + resp_len INTEGER, + path TEXT, + sandbox_scope TEXT NOT NULL DEFAULT '', + sandbox_owner_id TEXT NOT NULL DEFAULT '', + container_id TEXT NOT NULL DEFAULT '', + session_id TEXT NOT NULL DEFAULT '', + intent_id INTEGER NOT NULL DEFAULT 0, + src_ip TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS idx_ex_host ON exchanges(host); CREATE INDEX IF NOT EXISTS idx_ex_tmpl ON exchanges(host, url_template); @@ -131,7 +137,7 @@ const ( // TrafficSearchDescription is persisted into the tool catalog for new and // upgraded installations. Keep it in the traffic package so the runtime tool // and the catalog migration cannot drift apart. -const TrafficSearchDescription = "查询记录代理已抓取的目标流量(必须指定 host;支持裸主机、主机:端口或完整 URL,可再按 URL 子串或正文关键词过滤)。指定端口时只返回该服务的流量,避免同一 IP 的不同端口串包。body_contains 会在已抓取的请求/响应头与正文中做全文搜索,支持任意子串和中文(至少 3 个字符)。仅返回极轻量索引(id/method/url/status/resp_len),不含响应内容;结果非空后必须用 traffic_get 逐条核实请求/响应,再把确实支持当前漏洞的 ID 交给 bind_finding_traffic。默认只返回 3 条、每页最多 10 条;结果多时用 page 翻页。" +const TrafficSearchDescription = "查询记录代理与透明网关已抓取的目标流量(HTTP/HTTPS 默认按 host 过滤,支持裸主机、主机:端口或完整 URL,可再按 URL 子串或正文关键词过滤;也可通过 protocol='tcp'|'tls'|'udp'|'dns' 查询非 HTTP 原始 TCP/UDP 连接和 DNS 解析记录,支持按 action='block' 查出口拦截记录)。HTTP 流量仅返回轻量索引(id/method/url/status/resp_len),需用 traffic_get 核实正文后再交给 bind_finding_traffic。" // Traffic runs the recording proxy and owns the file tree + index. type Traffic struct { @@ -172,6 +178,42 @@ type Traffic struct { upstream atomic.Pointer[url.URL] upstreamMu sync.RWMutex upstreamFailure func(error) + ssrf atomic.Pointer[ssrfGuard] + blacklist atomic.Pointer[egressBlacklist] + blockLog *blockEventLog + attrMu sync.RWMutex + sourceResolver SourceResolver + taskBlacklistFn TaskBlacklistChecker + upstreamResolver UpstreamResolver + gatewayToken string + udpPolicy string + dnsUpstream string + storeErrorTraffic atomic.Bool + ssrfCfg *SSRFGuardConfig + dnsCache *dnsReverseCache + nfWrites atomic.Int64 + dnsWrites atomic.Int64 + flowAttr sync.Map // uuid.UUID -> SourceIdentity + connAttr sync.Map // remoteAddr(string) -> connAttrEntry +} +// EnableSSRFGuard installs an outbound destination filter on the recording +// proxy so sandboxed workloads cannot pivot to localhost, cloud metadata, or +// ARTEX's own management/database endpoints. +func (t *Traffic) EnableSSRFGuard(cfg SSRFGuardConfig) { + if t == nil { + return + } + t.attrMu.Lock() + if !cfg.Enabled { + t.ssrfCfg = nil + t.attrMu.Unlock() + t.ssrf.Store(nil) + return + } + cp := cfg + t.ssrfCfg = &cp + t.attrMu.Unlock() + t.ssrf.Store(newSSRFGuard(cfg)) } // Open initializes the traffic tree, blob store and SQLite index under dir. @@ -197,7 +239,7 @@ func Open(dir, addr string) (*Traffic, error) { if err != nil { return nil, err } - t := &Traffic{dir: dir, addr: addr, db: db, closed: make(chan struct{})} + t := &Traffic{dir: dir, addr: addr, db: db, closed: make(chan struct{}), blockLog: &blockEventLog{}, dnsCache: newDNSReverseCache()} if err := t.initIndex(); err != nil { db.Close() return nil, err @@ -220,12 +262,39 @@ func Open(dir, addr string) (*Traffic, error) { // a direct dial. When a global egress proxy IS configured (SetUpstreamProxy), // every captured request — intercepted AND transparently tunneled — is // forwarded through it instead, so no host leaks the real source IP. - p.SetUpstreamProxy(func(*http.Request) (*url.URL, error) { return t.upstream.Load(), nil }) + // Dial-time rejection. Requestheaders can answer a plain HTTP proxy request + // with 403, but a CONNECT (HTTPS) still dials the target unless this returns + // an error: go-mitmproxy ignores a synthetic response on the CONNECT path. + p.SetUpstreamProxy(func(req *http.Request) (*url.URL, error) { + if err := t.rejectBlockedDestination(req); err != nil { + return nil, err + } + if req != nil { + src := t.resolveSourceForConn(req.RemoteAddr, req.Header) + return t.resolveUpstreamForSource(src), nil + } + return t.upstream.Load(), nil + }) // Fail-open: MITM every host by default, EXCEPT ones a prior request proved we // can't intercept without breaking (see maybePassthrough). Those are tunneled // transparently so the request still reaches the target instead of being killed. + // Blocked destinations stay intercepted so the addon can return 403 before dial. p.SetShouldInterceptRule(func(req *http.Request) bool { - _, tunnel := t.pass.Load(hostOnly(req.Host)) + if req != nil { + scheme := "" + if req.URL != nil { + scheme = req.URL.Scheme + } + src := t.resolveSourceForConn(req.RemoteAddr, req.Header) + if t.checkOutboundForSource(req.Host, scheme, src) != nil { + return true + } + } + host := "" + if req != nil { + host = req.Host + } + _, tunnel := t.pass.Load(hostOnly(host)) return !tunnel }) p.AddAddon(&sink{t: t}) @@ -233,6 +302,52 @@ func Open(dir, addr string) (*Traffic, error) { return t, nil } +// rejectBlockedDestination refuses to dial loopback, metadata, and the hosts +// configured on the SSRF guard. An empty host is left to the caller: some +// internal proxy requests have no target yet, and blocking those would drop +// legitimate traffic. +func (t *Traffic) rejectBlockedDestination(req *http.Request) error { + if t == nil || req == nil { + return nil + } + host := req.Host + scheme := "" + rawURL := "" + if req.URL != nil { + if host == "" { + host = req.URL.Host + } + scheme = req.URL.Scheme + rawURL = req.URL.String() + } + if strings.TrimSpace(host) == "" { + return nil + } + src := t.resolveSourceForConn(req.RemoteAddr, req.Header) + if m := t.checkOutboundForSource(host, scheme, src); m != nil { + h, port := splitHostAndPort(host) + t.blockLog.Record(EgressBlockEvent{ + Host: h, + Port: port, + Method: req.Method, + URL: rawURL, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: m.Reason, + RuleKind: m.RuleKind, + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: m.Source, + }) + if m.Source == "ssrf_guard" { + return fmt.Errorf("blocked by ARTEX proxy SSRF guard: %s", m.Reason) + } + return fmt.Errorf("blocked by ARTEX egress blacklist: %s", m.Reason) + } + return nil +} + // initIndex applies the schema on a single pinned connection. Pinning is what // makes auto_vacuum reliable: it can only be set while the database still holds // no tables, and only the VACUUM that follows writes it into the file header — @@ -285,6 +400,12 @@ func (t *Traffic) initIndex() error { if _, err := conn.ExecContext(ctx, indexSchema); err != nil { return err } + if err := ensureAttributionColumns(ctx, conn); err != nil { + return err + } + if err := ensureNetFlowSchema(ctx, conn); err != nil { + return err + } if _, err := conn.ExecContext(ctx, ftsSchema); err != nil { log.Printf("[traffic] 全文索引不可用,正文搜索将被禁用(元数据搜索不受影响):%v", err) return nil @@ -293,6 +414,59 @@ func (t *Traffic) initIndex() error { return nil } +func ensureAttributionColumns(ctx context.Context, conn *sql.Conn) error { + rows, err := conn.QueryContext(ctx, `PRAGMA table_info(exchanges)`) + if err != nil { + return err + } + have := make(map[string]bool) + for rows.Next() { + var cid int + var name, typ string + var notNull int + var dflt sql.NullString + var pk int + if err := rows.Scan(&cid, &name, &typ, ¬Null, &dflt, &pk); err != nil { + rows.Close() + return err + } + have[strings.ToLower(name)] = true + } + if err := rows.Err(); err != nil { + rows.Close() + return err + } + rows.Close() + + cols := []struct { + name string + ddl string + }{ + {"sandbox_scope", `ALTER TABLE exchanges ADD COLUMN sandbox_scope TEXT NOT NULL DEFAULT ''`}, + {"sandbox_owner_id", `ALTER TABLE exchanges ADD COLUMN sandbox_owner_id TEXT NOT NULL DEFAULT ''`}, + {"container_id", `ALTER TABLE exchanges ADD COLUMN container_id TEXT NOT NULL DEFAULT ''`}, + {"session_id", `ALTER TABLE exchanges ADD COLUMN session_id TEXT NOT NULL DEFAULT ''`}, + {"intent_id", `ALTER TABLE exchanges ADD COLUMN intent_id INTEGER NOT NULL DEFAULT 0`}, + {"src_ip", `ALTER TABLE exchanges ADD COLUMN src_ip TEXT NOT NULL DEFAULT ''`}, + } + for _, c := range cols { + if !have[c.name] { + if _, err := conn.ExecContext(ctx, c.ddl); err != nil { + return err + } + } + } + for _, idx := range []string{ + `CREATE INDEX IF NOT EXISTS idx_ex_owner ON exchanges(sandbox_scope, sandbox_owner_id)`, + `CREATE INDEX IF NOT EXISTS idx_ex_container ON exchanges(container_id)`, + } { + if _, err := conn.ExecContext(ctx, idx); err != nil { + return err + } + } + return nil +} + // hostOnly strips an optional :port, so passthrough keys match whether the host // arrives as "example.com:443" (CONNECT) or "example.com" (request URL). func hostOnly(hostport string) string { @@ -426,6 +600,48 @@ func (s *sink) Requestheaders(f *mproxy.Flow) { if f.Request == nil { return } + if s.t != nil { + host := "" + scheme := "" + rawURL := "" + if f.Request.URL != nil { + host = f.Request.URL.Host + scheme = f.Request.URL.Scheme + rawURL = f.Request.URL.String() + } + if host == "" && f.Request.Header != nil { + host = f.Request.Header.Get("Host") + } + src := s.t.resolveSourceForConn(flowClientAddr(f), f.Request.Header) + if m := s.t.checkOutboundForSource(host, scheme, src); m != nil { + h, port := splitHostAndPort(host) + s.t.blockLog.Record(EgressBlockEvent{ + Host: h, + Port: port, + Method: f.Request.Method, + URL: rawURL, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: m.Reason, + RuleKind: m.RuleKind, + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: m.Source, + }) + prefix := "blocked by ARTEX egress blacklist: " + if m.Source == "ssrf_guard" { + prefix = "blocked by ARTEX proxy SSRF guard: " + } + f.Response = &mproxy.Response{ + StatusCode: http.StatusForbidden, + Header: http.Header{"Content-Type": []string{"text/plain; charset=utf-8"}}, + Body: []byte(prefix + m.Reason), + } + return + } + s.t.flowAttr.Store(f.Id, src) + } if f.Request.Header == nil { f.Request.Header = make(http.Header) } @@ -434,6 +650,35 @@ func (s *sink) Requestheaders(f *mproxy.Flow) { } } +func (s *sink) ClientDisconnected(c *mproxy.ClientConn) { + if s.t == nil || c == nil || c.Conn == nil || c.Conn.RemoteAddr() == nil { + return + } + s.t.connAttr.Delete(c.Conn.RemoteAddr().String()) +} + +func (s *sink) ServerConnected(connCtx *mproxy.ConnContext) { + if connCtx == nil || connCtx.ServerConn == nil || s.t == nil { + return + } + src := s.t.resolveSourceForConn(connClientAddr(connCtx), nil) + if m := s.t.checkOutboundForSource(connCtx.ServerConn.Address, "", src); m != nil && connCtx.ServerConn.Conn != nil { + h, port := splitHostAndPort(connCtx.ServerConn.Address) + s.t.blockLog.Record(EgressBlockEvent{ + Host: h, + Port: port, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: m.Reason, + RuleKind: m.RuleKind, + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: m.Source, + }) + _ = connCtx.ServerConn.Conn.Close() + } +} func (s *sink) Response(f *mproxy.Flow) { if f.Request == nil || f.Response == nil { return @@ -446,10 +691,12 @@ func (s *sink) Response(f *mproxy.Flow) { // errors) — not a plain target-unreachable error — we flag the host for // transparent passthrough so future requests to it succeed instead of dying. func (s *sink) RequestError(f *mproxy.Flow, err error) { + if f != nil && s.t != nil { + s.t.flowAttr.Delete(f.Id) + } s.t.reportUpstreamFailure(err) s.t.maybePassthrough(f, err) } - func (s *sink) HTTPConnectError(_ *mproxy.Flow, err error) { s.t.reportUpstreamFailure(err) } @@ -513,14 +760,23 @@ func (t *Traffic) record(f *mproxy.Flow) { } defer tx.Rollback() //nolint:errcheck // no-op once committed + var src SourceIdentity + if v, ok := t.flowAttr.LoadAndDelete(f.Id); ok { + if s, ok2 := v.(SourceIdentity); ok2 { + src = s + } + } else { + src = t.resolveSourceForConn(flowClientAddr(f), nil) + } + // path stays empty for db-resident exchanges; a non-empty path marks a legacy // row whose bodies still live in the old on-disk tree (see Get). - res, err := tx.Exec(`INSERT OR REPLACE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) -VALUES(?,?,?,?,?,?,?,?,?,?,'')`, + res, err := tx.Exec(`INSERT OR REPLACE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path,sandbox_scope,sandbox_owner_id,container_id,session_id,intent_id,src_ip) +VALUES(?,?,?,?,?,?,?,?,?,?,'',?,?,?,?,?,?)`, id, now.Unix(), host, method, tmpl, url, f.Response.StatusCode, ct, - len(f.Request.Body), len(f.Response.Body)) + len(f.Request.Body), len(f.Response.Body), + src.Scope, src.OwnerID, src.ContainerID, src.SessionID, src.IntentID, src.SrcIP) if err != nil { - log.Printf("[traffic] 记录 %s 失败(写索引):%v", url, err) return } rowid, err := res.LastInsertId() @@ -805,16 +1061,22 @@ func (t *Traffic) BlobRange(hash string, offset, length int64) (data []byte, tot // ExchangeMeta is one row of the index (returned by Search). type ExchangeMeta struct { - ID string `json:"id"` - TS int64 `json:"ts"` - Host string `json:"host"` - Method string `json:"method"` - URLTemplate string `json:"url_template"` - URL string `json:"url"` - Status int `json:"status"` - ContentType string `json:"content_type"` - RespLen int `json:"resp_len"` - Path string `json:"path"` + ID string `json:"id"` + TS int64 `json:"ts"` + Host string `json:"host"` + Method string `json:"method"` + URLTemplate string `json:"url_template"` + URL string `json:"url"` + Status int `json:"status"` + ContentType string `json:"content_type"` + RespLen int `json:"resp_len"` + Path string `json:"path"` + SandboxScope string `json:"sandbox_scope,omitempty"` + SandboxOwnerID string `json:"sandbox_owner_id,omitempty"` + ContainerID string `json:"container_id,omitempty"` + SessionID string `json:"session_id,omitempty"` + IntentID int64 `json:"intent_id,omitempty"` + SrcIP string `json:"src_ip,omitempty"` } // Search returns paged exchange metadata (never bodies). @@ -822,7 +1084,7 @@ func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error) { if size <= 0 || size > 500 { size = 100 } - q := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path FROM exchanges` + q := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,COALESCE(sandbox_scope,''),COALESCE(sandbox_owner_id,''),COALESCE(container_id,''),COALESCE(session_id,''),COALESCE(intent_id,0),COALESCE(src_ip,'') FROM exchanges` args := []any{} if host != "" { q += ` WHERE host=?` @@ -838,7 +1100,7 @@ func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error) { var out []ExchangeMeta for rows.Next() { var m ExchangeMeta - if err := rows.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path); err != nil { + if err := rows.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.SandboxScope, &m.SandboxOwnerID, &m.ContainerID, &m.SessionID, &m.IntentID, &m.SrcIP); err != nil { return nil, err } out = append(out, m) @@ -870,17 +1132,23 @@ func ftsQuote(s string) string { // of -1 skip the response-size bounds. An empty Sort/Order defaults to // newest-first by timestamp. type PageQuery struct { - Host string // host substring - Hosts []string // task-scoped host candidates (exact host or host:port) - Method string // exact method (case-insensitive) - Query string // broad search box: metadata columns OR captured text - Body string // content box: captured request/response text only (full-text) - Path string // url_template substring — the vulnerability's path - Status string // exact code ("404") or class bucket ("4xx") - RespMin int64 // minimum resp_len, or -1 when unset - RespMax int64 // maximum resp_len, or -1 when unset - Sort string // ts | status | resp_len (default ts) - Order string // asc | desc (default desc) + Host string // host substring + Hosts []string // task-scoped host candidates (exact host or host:port) + OwnerTaskID string // task ID for strict attribution matching (+ legacy unattributed fallback on Hosts) + SandboxScope string // exact sandbox_scope ("task" | "session") + SandboxOwnerID string // exact sandbox_owner_id + ContainerID string // container_id prefix match + SessionID string // exact session_id + IntentID int64 // exact intent_id (>0) + Method string // exact method (case-insensitive) + Query string // broad search box: metadata columns OR captured text + Body string // content box: captured request/response text only (full-text) + Path string // url_template substring — the vulnerability's path + Status string // exact code ("404") or class bucket ("4xx") + RespMin int64 // minimum resp_len, or -1 when unset + RespMax int64 // maximum resp_len, or -1 when unset + Sort string // ts | status | resp_len (default ts) + Order string // asc | desc (default desc) } // hostScopeClause limits traffic to the hosts attached to a task. Captures @@ -967,9 +1235,33 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total if h := strings.TrimSpace(f.Host); h != "" { add("host LIKE ?", "%"+h+"%") } - if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" { + if ownerTaskID := strings.TrimSpace(f.OwnerTaskID); ownerTaskID != "" { + if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" { + allArgs := make([]any, 0, 1+len(scopeArgs)) + allArgs = append(allArgs, ownerTaskID) + allArgs = append(allArgs, scopeArgs...) + add("((sandbox_scope='task' AND sandbox_owner_id=?) OR (COALESCE(sandbox_owner_id,'')='' AND "+cond+"))", allArgs...) + } else { + add("(sandbox_scope='task' AND sandbox_owner_id=?)", ownerTaskID) + } + } else if cond, scopeArgs := hostScopeClause(f.Hosts); cond != "" { add(cond, scopeArgs...) } + if sc := strings.TrimSpace(f.SandboxScope); sc != "" { + add("sandbox_scope=?", sc) + } + if ow := strings.TrimSpace(f.SandboxOwnerID); ow != "" { + add("sandbox_owner_id=?", ow) + } + if cid := strings.TrimSpace(f.ContainerID); cid != "" { + add("container_id LIKE ?", cid+"%") + } + if sid := strings.TrimSpace(f.SessionID); sid != "" { + add("session_id=?", sid) + } + if f.IntentID > 0 { + add("intent_id=?", f.IntentID) + } if m := strings.TrimSpace(f.Method); m != "" { add("method=?", strings.ToUpper(m)) } @@ -1018,7 +1310,7 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total } // id embeds capture timestamp + sequence, so a trailing id DESC makes the order // total and pagination stable even when the sort column has many ties. - sel := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path FROM exchanges` + + sel := `SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,COALESCE(sandbox_scope,''),COALESCE(sandbox_owner_id,''),COALESCE(container_id,''),COALESCE(session_id,''),COALESCE(intent_id,0),COALESCE(src_ip,'') FROM exchanges` + where + ` ORDER BY ` + col + ` ` + dir + `, id DESC LIMIT ? OFFSET ?` qargs := append(append([]any{}, args...), size, page*size) rs, err := t.db.Query(sel, qargs...) @@ -1028,7 +1320,7 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total defer rs.Close() for rs.Next() { var m ExchangeMeta - if err := rs.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path); err != nil { + if err := rs.Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.SandboxScope, &m.SandboxOwnerID, &m.ContainerID, &m.SessionID, &m.IntentID, &m.SrcIP); err != nil { return nil, 0, err } rows = append(rows, m) @@ -1131,6 +1423,39 @@ func (t *Traffic) HostsForScope(scope []string) ([]HostCount, error) { return out, rows.Err() } +// HostsForTask returns distinct recorded hosts attributed to ownerTaskID OR +// matching legacy unattributed exchanges in scope. +func (t *Traffic) HostsForTask(ownerTaskID string, scope []string) ([]HostCount, error) { + ownerTaskID = strings.TrimSpace(ownerTaskID) + if ownerTaskID == "" { + return t.HostsForScope(scope) + } + var where string + var args []any + if cond, scopeArgs := hostScopeClause(scope); cond != "" { + where = "((sandbox_scope='task' AND sandbox_owner_id=?) OR (COALESCE(sandbox_owner_id,'')='' AND " + cond + "))" + args = append(args, ownerTaskID) + args = append(args, scopeArgs...) + } else { + where = "(sandbox_scope='task' AND sandbox_owner_id=?)" + args = append(args, ownerTaskID) + } + rows, err := t.db.Query(`SELECT host, COUNT(*) AS n, MAX(ts) AS last FROM exchanges WHERE `+where+` GROUP BY host ORDER BY last DESC`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []HostCount + for rows.Next() { + var h HostCount + var last int64 + if err := rows.Scan(&h.Host, &h.Count, &last); err != nil { + return nil, err + } + out = append(out, h) + } + return out, rows.Err() +} // Count returns total recorded exchanges. func (t *Traffic) Count() (int, error) { var n int @@ -1213,6 +1538,8 @@ func (t *Traffic) DeleteAll() (deleted int64, reclaimed int64, err error) { if deleted, err = t.deleteWhere(tx, `1=1`); err != nil { return 0, 0, err } + _, _ = tx.Exec(`DELETE FROM net_flows`) + _, _ = tx.Exec(`DELETE FROM dns_queries`) // Staged before the commit so a filesystem failure can still abort the whole // deletion, exactly as in DeleteHost. stageDir, moves, err := t.stageTrees(trees) @@ -2126,48 +2453,104 @@ func (t *Traffic) Tools() []actool.CoreTool { Schema: map[string]any{ "type": "object", "properties": map[string]any{ - "host": map[string]any{"type": "string", "description": "按主机过滤(必填;如 '107.172.96.177'、'107.172.96.177:8082' 或 'http://107.172.96.177:8082/path')"}, - "contains": map[string]any{"type": "string", "description": "URL 子串过滤(可选,如 'api' / 'login')"}, - "body_contains": map[string]any{"type": "string", "description": "正文全文搜索(可选,至少 3 个字符),匹配请求/响应的头与正文,如 'password' / 'root:x:0' / '内网测试'"}, + "protocol": map[string]any{"type": "string", "description": "协议类型:http(默认,含 HTTPS)、tcp、tls、udp、dns"}, + "host": map[string]any{"type": "string", "description": "HTTP 协议下必填(如 '107.172.96.177'、'107.172.96.177:8082' 或完整 URL);非 HTTP 协议下可选,按目标主机/IP/域名过滤"}, + "contains": map[string]any{"type": "string", "description": "URL 子串或非 HTTP 关键词过滤(可选,如 'api' / 'login')"}, + "body_contains": map[string]any{"type": "string", "description": "HTTP 正文全文搜索(可选,至少 3 个字符),匹配请求/响应头与正文"}, + "action": map[string]any{"type": "string", "description": "非 HTTP 动作过滤(可选):allow / block / error / passthrough"}, + "task_id": map[string]any{"type": "string", "description": "按任务 ID 过滤(可选)"}, "limit": map[string]any{"type": "integer", "description": "每页条数,默认 3,最大 10"}, "page": map[string]any{"type": "integer", "description": "页码,从 0 开始,默认 0(按 ts 倒序分页)"}, }, - "required": []any{"host"}, }, ReadOnly: ro, Permissions: allow, Run: func(_ context.Context, in json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { var a struct { - Host, Contains string - BodyContains string `json:"body_contains"` - Limit int - Page int + Protocol string + Host string + Contains string + BodyContains string `json:"body_contains"` + Action string + TaskID string `json:"task_id"` + Limit int + Page int } _ = json.Unmarshal(in, &a) - if strings.TrimSpace(a.Host) == "" { - return actool.Errorf("host 为必填参数:请指定裸主机、主机:端口或完整 URL,避免全库扫描。"), nil + proto := strings.ToLower(strings.TrimSpace(a.Protocol)) + if proto == "" { + proto = "http" } - rows, err := t.query(a.Host, a.Contains, a.BodyContains, a.Page, a.Limit) - if err != nil { - return actool.Errorf(err.Error()), nil + limit := a.Limit + if limit <= 0 { + limit = 3 } - if len(rows) == 0 { - return actool.Text("无匹配流量。"), nil + if limit > 10 { + limit = 10 } - // 精简为最小索引:仅保留定位所需字段 + 响应码/长度,不带任何响应内容。 - type liteRow struct { - ID string `json:"id"` - Method string `json:"method"` - URL string `json:"url"` - Status int `json:"status"` - RespLen int `json:"resp_len"` + switch proto { + case "dns": + kw := strings.TrimSpace(a.Host) + if kw == "" { + kw = strings.TrimSpace(a.Contains) + } + rows, _, err := t.PageDNSQueries(DNSQueryFilter{ + Action: a.Action, + OwnerTaskID: a.TaskID, + Query: kw, + }, a.Page, limit) + if err != nil { + return actool.Errorf(err.Error()), nil + } + if len(rows) == 0 { + return actool.Text("无匹配 DNS 记录。"), nil + } + b, _ := json.Marshal(rows) + return actool.Text(string(b)), nil + case "tcp", "tls", "udp": + kw := strings.TrimSpace(a.Host) + if kw == "" { + kw = strings.TrimSpace(a.Contains) + } + rows, _, err := t.PageNetFlows(NetFlowQuery{ + Protocol: proto, + Action: a.Action, + OwnerTaskID: a.TaskID, + Query: kw, + }, a.Page, limit) + if err != nil { + return actool.Errorf(err.Error()), nil + } + if len(rows) == 0 { + return actool.Text("无匹配非 HTTP 流量。"), nil + } + b, _ := json.Marshal(rows) + return actool.Text(string(b)), nil + default: + if strings.TrimSpace(a.Host) == "" { + return actool.Errorf("host 为必填参数:请指定裸主机、主机:端口或完整 URL,避免全库扫描。"), nil + } + rows, err := t.query(a.Host, a.Contains, a.BodyContains, a.Page, a.Limit) + if err != nil { + return actool.Errorf(err.Error()), nil + } + if len(rows) == 0 { + return actool.Text("无匹配流量。"), nil + } + type liteRow struct { + ID string `json:"id"` + Method string `json:"method"` + URL string `json:"url"` + Status int `json:"status"` + RespLen int `json:"resp_len"` + } + lite := make([]liteRow, 0, len(rows)) + for _, r := range rows { + lite = append(lite, liteRow{ID: r.ID, Method: r.Method, URL: r.URL, Status: r.Status, RespLen: r.RespLen}) + } + b, _ := json.Marshal(lite) + return actool.Text(string(b)), nil } - lite := make([]liteRow, 0, len(rows)) - for _, r := range rows { - lite = append(lite, liteRow{ID: r.ID, Method: r.Method, URL: r.URL, Status: r.Status, RespLen: r.RespLen}) - } - b, _ := json.Marshal(lite) - return actool.Text(string(b)), nil }, }) diff --git a/traffic/transparent.go b/traffic/transparent.go new file mode 100644 index 0000000..98038e1 --- /dev/null +++ b/traffic/transparent.go @@ -0,0 +1,1484 @@ +package traffic + +import ( + "bufio" + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/miekg/dns" +) + +// UDPPolicy controls how non-DNS UDP packets are handled by the transparent gateway. +const ( + UDPPolicyBlockOnProxy = "block_on_proxy" // OPSEC default: block UDP whenever an upstream proxy is active + UDPPolicyBlock = "block" // always block non-DNS UDP + UDPPolicyDirect = "direct" // allow direct UDP (still subject to SSRF guard & egress blacklist) +) + +// NormalizeUDPPolicy validates and normalizes a UDP policy value. +func NormalizeUDPPolicy(raw string) string { + switch strings.ToLower(strings.TrimSpace(raw)) { + case UDPPolicyBlock: + return UDPPolicyBlock + case UDPPolicyDirect: + return UDPPolicyDirect + default: + return UDPPolicyBlockOnProxy + } +} + +// BlockDecision describes why an outbound flow or DNS query was blocked. +type BlockDecision struct { + Reason string + RuleKind string + RuleID string + Pattern string + Source string +} + +// TransparentBackend decouples TransparentGateway from the local SQLite store so +// the exact same protocol-sniffing / L4 TCP / DNS / UDP engine runs both inside +// the main ARTEX binary and inside the standalone cmd/artex-gateway container. +type TransparentBackend interface { + ResolveSource(srcIP string) SourceIdentity + CheckOutbound(rawHost, scheme string, src SourceIdentity) *BlockDecision + ResolveUpstream(src SourceIdentity) *url.URL + IsPassthrough(host string) bool + LookupDNSReverse(ip string) string + RememberDNS(ip, domain string) + RecordNetFlow(rec NetFlowRecord) + RecordDNSQuery(rec DNSQueryRecord) + RecordBlockEvent(ev EgressBlockEvent) + UDPPolicy() string + DNSUpstream() string + GatewayToken() string +} + +// TransparentConfig configures the transparent TCP / DNS / UDP listeners. +type TransparentConfig struct { + TCPAddr string // e.g. "0.0.0.0:15001" + DNSAddr string // e.g. "0.0.0.0:15053" + UDPAddr string // e.g. "0.0.0.0:15002" + MITMProxyAddr string // e.g. "127.0.0.1:8788" (go-mitmproxy for sniffed HTTP/TLS) + PeekTimeout time.Duration + DialTimeout time.Duration + // Optional hook for tests to supply the original destination without Linux SO_ORIGINAL_DST. + OrigDstResolver func(conn net.Conn) (net.IP, int, error) + // Optional hook for tests to deliver UDP replies without Linux IP_TRANSPARENT. + UDPReplyFunc func(origDst, clientAddr *net.UDPAddr, payload []byte) error +} + +// TransparentGateway intercepts raw TCP, DNS (UDP+TCP), and UDP traffic from +// sandbox containers, sniffs HTTP/TLS to forward to go-mitmproxy, relays non-HTTP +// L4 flows through egress blacklist + SSRF guard + upstream proxies, and records +// net_flows and dns_queries. +type TransparentGateway struct { + cfg TransparentConfig + backend TransparentBackend + + mu sync.Mutex + tcpLn net.Listener + dnsUDP *dns.Server + dnsTCP *dns.Server + udpConn *net.UDPConn + closed chan struct{} + wg sync.WaitGroup + + udpMu sync.Mutex + udpSessions map[string]*udpRelaySession +} + +// NewTransparentGateway creates a TransparentGateway bound to backend. +func NewTransparentGateway(cfg TransparentConfig, backend TransparentBackend) *TransparentGateway { + if cfg.PeekTimeout <= 0 { + cfg.PeekTimeout = 250 * time.Millisecond + } + if cfg.DialTimeout <= 0 { + cfg.DialTimeout = 15 * time.Second + } + return &TransparentGateway{ + cfg: cfg, + backend: backend, + closed: make(chan struct{}), + udpSessions: make(map[string]*udpRelaySession), + } +} + +// Start launches all configured listeners (TCP, DNS UDP+TCP, UDP TPROXY). +func (g *TransparentGateway) Start() error { + if g.cfg.TCPAddr != "" { + ln, err := net.Listen("tcp", g.cfg.TCPAddr) + if err != nil { + _ = g.Close() + return fmt.Errorf("listen transparent tcp %s: %w", g.cfg.TCPAddr, err) + } + g.mu.Lock() + g.tcpLn = ln + g.mu.Unlock() + g.wg.Add(1) + go func() { + defer g.wg.Done() + g.serveTCP(ln) + }() + } + + if g.cfg.DNSAddr != "" { + mux := dns.NewServeMux() + mux.HandleFunc(".", g.handleDNSRequest) + udpSrv := &dns.Server{Addr: g.cfg.DNSAddr, Net: "udp", Handler: mux} + tcpSrv := &dns.Server{Addr: g.cfg.DNSAddr, Net: "tcp", Handler: mux} + + udpReady := make(chan error, 1) + udpSrv.NotifyStartedFunc = func() { udpReady <- nil } + g.wg.Add(1) + go func() { + defer g.wg.Done() + if err := udpSrv.ListenAndServe(); err != nil { + select { + case udpReady <- err: + default: + } + } + }() + if err := <-udpReady; err != nil { + _ = g.Close() + return fmt.Errorf("listen transparent dns udp %s: %w", g.cfg.DNSAddr, err) + } + + tcpReady := make(chan error, 1) + tcpSrv.NotifyStartedFunc = func() { tcpReady <- nil } + g.wg.Add(1) + go func() { + defer g.wg.Done() + if err := tcpSrv.ListenAndServe(); err != nil { + select { + case tcpReady <- err: + default: + } + } + }() + if err := <-tcpReady; err != nil { + _ = udpSrv.Shutdown() + _ = g.Close() + return fmt.Errorf("listen transparent dns tcp %s: %w", g.cfg.DNSAddr, err) + } + + g.mu.Lock() + g.dnsUDP = udpSrv + g.dnsTCP = tcpSrv + g.mu.Unlock() + } + + if g.cfg.UDPAddr != "" { + uc, err := listenTransparentUDP(g.cfg.UDPAddr) + if err != nil { + _ = g.Close() + return fmt.Errorf("listen transparent udp %s: %w", g.cfg.UDPAddr, err) + } + g.mu.Lock() + g.udpConn = uc + g.mu.Unlock() + g.wg.Add(1) + go func() { + defer g.wg.Done() + g.serveUDP(uc) + }() + } + + return nil +} + +// TCPAddr returns the bound transparent TCP listener address (useful when bound to :0 in tests). +func (g *TransparentGateway) TCPAddr() string { + g.mu.Lock() + defer g.mu.Unlock() + if g.tcpLn != nil { + return g.tcpLn.Addr().String() + } + return g.cfg.TCPAddr +} + +// Close stops all listeners and waits for active accept loops to exit. +func (g *TransparentGateway) Close() error { + g.mu.Lock() + select { + case <-g.closed: + default: + close(g.closed) + } + if g.tcpLn != nil { + _ = g.tcpLn.Close() + g.tcpLn = nil + } + if g.dnsUDP != nil { + _ = g.dnsUDP.Shutdown() + g.dnsUDP = nil + } + if g.dnsTCP != nil { + _ = g.dnsTCP.Shutdown() + g.dnsTCP = nil + } + if g.udpConn != nil { + _ = g.udpConn.Close() + g.udpConn = nil + } + g.mu.Unlock() + + g.udpMu.Lock() + for k, sess := range g.udpSessions { + sess.close() + delete(g.udpSessions, k) + } + g.udpMu.Unlock() + + g.wg.Wait() + return nil +} + +func (g *TransparentGateway) serveTCP(ln net.Listener) { + for { + conn, err := ln.Accept() + if err != nil { + select { + case <-g.closed: + return + default: + } + continue + } + go g.HandleTCPConn(conn) + } +} + +// HandleTCPConn processes one transparently redirected TCP connection. +func (g *TransparentGateway) HandleTCPConn(rawConn net.Conn) { + defer rawConn.Close() + start := time.Now() + + srcIP, srcPort := splitAddrIPPort(rawConn.RemoteAddr()) + origIP, origPort, err := g.resolveOrigDst(rawConn) + if err != nil || origIP == nil || origPort <= 0 { + log.Printf("[gateway] tcp origdst failed from %s: %v", srcIP, err) + return + } + dstIPStr := origIP.String() + src := g.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + + sniff, conn := SniffProtocol(rawConn, g.cfg.PeekTimeout) + + // Resolve logical destination host: SNI > HTTP Host > reverse DNS cache > raw IP. + dstHost := strings.TrimSpace(sniff.SNI) + if dstHost == "" && sniff.Host != "" { + h, _ := splitHostAndPort(sniff.Host) + dstHost = strings.TrimSpace(h) + } + if dstHost == "" { + dstHost = g.backend.LookupDNSReverse(dstIPStr) + } + if dstHost == "" { + dstHost = dstIPStr + } + + scheme := string(sniff.Proto) + if sniff.Proto == ProtoTLS { + scheme = "https" + } + + // Enforce SSRF guard + global/task egress blacklist on both logical host and raw destination IP. + targetIPPort := net.JoinHostPort(dstIPStr, strconv.Itoa(origPort)) + targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(origPort)) + var blocked *BlockDecision + if dstHost != dstIPStr { + blocked = g.backend.CheckOutbound(targetHostPort, scheme, src) + } + if blocked == nil { + blocked = g.backend.CheckOutbound(targetIPPort, scheme, src) + } + if blocked != nil { + g.backend.RecordBlockEvent(EgressBlockEvent{ + At: start.UTC(), + Host: dstHost, + Port: strconv.Itoa(origPort), + Method: strings.ToUpper(string(sniff.Proto)), + URL: fmt.Sprintf("%s://%s", sniff.Proto, targetHostPort), + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + g.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(start).Milliseconds(), + Protocol: string(sniff.Proto), + DstIP: dstIPStr, + DstPort: origPort, + DstHost: dstHost, + SNI: sniff.SNI, + Action: "block", + BlockReason: blocked.Reason, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) + return + } + + // Route sniffed HTTP/TLS into go-mitmproxy when available and not downgraded to passthrough. + mitmAddr := strings.TrimSpace(g.cfg.MITMProxyAddr) + if mitmAddr != "" { + if sniff.Proto == ProtoHTTP { + g.forwardHTTPToMITM(conn, mitmAddr, dstHost, origPort, src) + return + } + if sniff.Proto == ProtoTLS && !g.backend.IsPassthrough(dstHost) { + if err := g.forwardTLSToMITM(conn, mitmAddr, dstHost, origPort, src); err == nil { + return + } + // MITM bridge failed before handshake; fall through to L4 passthrough only if not already consumed. + return + } + } + + // Non-HTTP raw TCP or TLS passthrough: L4 transparent relay with upstream proxy + flow recording. + action := "allow" + if sniff.Proto == ProtoTLS { + action = "passthrough" + } + g.relayL4TCP(conn, start, string(sniff.Proto), action, src, srcPort, dstIPStr, dstHost, origPort, sniff.SNI) +} + +func (g *TransparentGateway) resolveOrigDst(conn net.Conn) (net.IP, int, error) { + if g.cfg.OrigDstResolver != nil { + return g.cfg.OrigDstResolver(conn) + } + return originalDstTCP(conn) +} + +func (g *TransparentGateway) mitmProxyAuthHeader(src SourceIdentity) string { + val := FormatProxyContextAuthValue(src, g.backend.GatewayToken()) + if val == "" { + return "" + } + return "Basic " + val +} + +// forwardTLSToMITM bridges a transparently intercepted TLS stream into +// go-mitmproxy via an HTTP CONNECT tunnel, replaying the sniffed ClientHello. +func (g *TransparentGateway) forwardTLSToMITM(clientConn net.Conn, mitmAddr, dstHost string, dstPort int, src SourceIdentity) error { + dialer := &net.Dialer{Timeout: g.cfg.DialTimeout} + proxyConn, err := dialer.Dial("tcp", mitmAddr) + if err != nil { + log.Printf("[gateway] dial mitmproxy %s failed for TLS %s:%d: %v", mitmAddr, dstHost, dstPort, err) + return err + } + defer proxyConn.Close() + + target := net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + var req strings.Builder + req.WriteString("CONNECT ") + req.WriteString(target) + req.WriteString(" HTTP/1.1\r\nHost: ") + req.WriteString(target) + req.WriteString("\r\n") + if auth := g.mitmProxyAuthHeader(src); auth != "" { + req.WriteString("Proxy-Authorization: ") + req.WriteString(auth) + req.WriteString("\r\n") + } + req.WriteString("\r\n") + + _ = proxyConn.SetDeadline(time.Now().Add(10 * time.Second)) + if _, err := proxyConn.Write([]byte(req.String())); err != nil { + return err + } + br := bufio.NewReader(proxyConn) + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect}) + if err != nil { + return err + } + _ = resp.Body.Close() + _ = proxyConn.SetDeadline(time.Time{}) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("mitmproxy CONNECT %s returned %s", target, resp.Status) + } + + // Splice bidirectional TLS stream (PeekConn replays the exact ClientHello). + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + _, _ = io.Copy(proxyConn, clientConn) + if cw, ok := proxyConn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + go func() { + defer wg.Done() + if br.Buffered() > 0 { + _, _ = io.CopyN(clientConn, br, int64(br.Buffered())) + } + _, _ = io.Copy(clientConn, proxyConn) + if cw, ok := clientConn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + wg.Wait() + return nil +} + +// forwardHTTPToMITM converts origin-form transparent HTTP/1.x requests into +// proxy-form requests sent through go-mitmproxy so exchanges are captured in full. +func (g *TransparentGateway) forwardHTTPToMITM(clientConn net.Conn, mitmAddr, dstHost string, dstPort int, src SourceIdentity) { + dialer := &net.Dialer{Timeout: g.cfg.DialTimeout} + proxyConn, err := dialer.Dial("tcp", mitmAddr) + if err != nil { + log.Printf("[gateway] dial mitmproxy %s failed for HTTP %s:%d: %v", mitmAddr, dstHost, dstPort, err) + return + } + defer proxyConn.Close() + + clientBR := bufio.NewReader(clientConn) + proxyBR := bufio.NewReader(proxyConn) + auth := g.mitmProxyAuthHeader(src) + + for { + req, err := http.ReadRequest(clientBR) + if err != nil { + return + } + host := strings.TrimSpace(req.Host) + if host == "" { + if dstPort == 80 { + host = dstHost + } else { + host = net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + } + req.Host = host + } + req.URL.Scheme = "http" + req.URL.Host = host + req.RequestURI = "" + if auth != "" { + req.Header.Set("Proxy-Authorization", auth) + } + if err := req.WriteProxy(proxyConn); err != nil { + _ = req.Body.Close() + return + } + _ = req.Body.Close() + + resp, err := http.ReadResponse(proxyBR, req) + if err != nil { + return + } + if err := resp.Write(clientConn); err != nil { + _ = resp.Body.Close() + return + } + closeAfter := resp.Close || req.Close + _ = resp.Body.Close() + if closeAfter { + return + } + } +} + +// relayL4TCP performs transparent L4 TCP forwarding with upstream proxy support, +// capped TX/RX payload preview capture, and net_flows persistence. +func (g *TransparentGateway) relayL4TCP( + clientConn net.Conn, + start time.Time, + proto, action string, + src SourceIdentity, + srcPort int, + dstIP, dstHost string, + dstPort int, + sni string, +) { + upstream := g.backend.ResolveUpstream(src) + upstreamLabel := MaskProxyURL(upstream) + target := net.JoinHostPort(dstIP, strconv.Itoa(dstPort)) + if upstream != nil && dstHost != "" && dstHost != dstIP { + // Pass hostname to SOCKS5/HTTP CONNECT so remote proxy can resolve when needed. + target = net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + } + + ctx, cancel := context.WithTimeout(context.Background(), g.cfg.DialTimeout) + dstConn, err := dialTCPThroughUpstream(ctx, upstream, target, g.cfg.DialTimeout) + cancel() + if err != nil { + g.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(start).Milliseconds(), + Protocol: proto, + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + SNI: sni, + Action: "error", + UpstreamProxy: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + Error: err.Error(), + }) + return + } + g.relayConnectedL4TCP(clientConn, dstConn, start, proto, action, src, srcPort, dstIP, dstHost, dstPort, sni, upstreamLabel) +} + +// relayConnectedL4TCP relays bytes bidirectionally over an already-connected +// upstream TCP socket, capturing capped TX/RX payload previews and recording +// the flow into net_flows. Used by both REDIRECT and gVisor netstack deferred +// handshake modes. +func (g *TransparentGateway) relayConnectedL4TCP( + clientConn, dstConn net.Conn, + start time.Time, + proto, action string, + src SourceIdentity, + srcPort int, + dstIP, dstHost string, + dstPort int, + sni, upstreamLabel string, +) { + defer dstConn.Close() + + txCap := &limitedCapture{max: maxFlowPreviewBytes} + rxCap := &limitedCapture{max: maxFlowPreviewBytes} + var bytesTX, bytesRX int64 + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + n, err := io.Copy(io.MultiWriter(dstConn, txCap), clientConn) + bytesTX = n + if err != nil { + _ = dstConn.Close() + } else if cw, ok := dstConn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + go func() { + defer wg.Done() + n, err := io.Copy(io.MultiWriter(clientConn, rxCap), dstConn) + bytesRX = n + if err != nil { + _ = clientConn.Close() + } else if cw, ok := clientConn.(interface{ CloseWrite() error }); ok { + _ = cw.CloseWrite() + } + }() + wg.Wait() + + end := time.Now() + g.backend.RecordNetFlow(NetFlowRecord{ + TS: start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(start).Milliseconds(), + Protocol: proto, + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + SNI: sni, + Action: action, + UpstreamProxy: upstreamLabel, + BytesTX: bytesTX, + BytesRX: bytesRX, + TXPreview: txCap.Bytes(), + RXPreview: rxCap.Bytes(), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) +} + +// handleDNSRequest intercepts UDP and TCP DNS queries, enforces SSRF guard and +// egress blacklist (pre-query on domain + post-resolution on returned A/AAAA IPs), +// prevents DNS leaks by using DNS-over-TCP via upstream proxy when active, and +// records every query into dns_queries. +func (g *TransparentGateway) handleDNSRequest(w dns.ResponseWriter, r *dns.Msg) { + srcIP, _ := splitAddrIPPort(w.RemoteAddr()) + viaTCP := w.LocalAddr() != nil && strings.Contains(strings.ToLower(w.LocalAddr().Network()), "tcp") + resp := g.ProcessDNSQuery(srcIP, r, viaTCP) + if resp != nil { + _ = w.WriteMsg(resp) + } +} + +// ProcessDNSQuery evaluates a DNS request from srcIP against SSRF/blacklist +// rules (pre- and post-resolution), forwards upstream (over TCP via upstream +// proxy when active), populates the reverse DNS cache, and records dns_queries. +func (g *TransparentGateway) ProcessDNSQuery(srcIP string, r *dns.Msg, viaTCP bool) *dns.Msg { + resp, _ := g.processDNSQuery(srcIP, r, viaTCP, "", true) + return resp +} + +// ProcessDNSQueryToTarget evaluates a direct DNS request sent to a specific +// destination IP:port (e.g. `dig @223.5.5.5` or `nmap -sU -p 53 `). +// It always queries targetServer (directly or via upstream proxy when active) +// and never substitutes the host's DNSUpstream(), returning (nil, err) on +// failure instead of synthesizing SERVFAIL to prevent false-positive open +// resolver / `53/udp open` reports on non-DNS hosts. +func (g *TransparentGateway) ProcessDNSQueryToTarget(srcIP string, r *dns.Msg, viaTCP bool, targetServer string) (*dns.Msg, error) { + return g.processDNSQuery(srcIP, r, viaTCP, strings.TrimSpace(targetServer), false) +} + +func (g *TransparentGateway) processDNSQuery(srcIP string, r *dns.Msg, viaTCP bool, targetServer string, synthServfail bool) (*dns.Msg, error) { + start := time.Now() + src := g.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + + qname := "" + qtype := "A" + if len(r.Question) > 0 { + qname = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(r.Question[0].Name)), ".") + qtype = dns.TypeToString[r.Question[0].Qtype] + if qtype == "" { + qtype = strconv.Itoa(int(r.Question[0].Qtype)) + } + } + + // Pre-resolution domain check against SSRF guard + global/task egress blacklist. + if qname != "" { + if blocked := g.backend.CheckOutbound(qname, "dns", src); blocked != nil { + resp := new(dns.Msg) + resp.SetRcode(r, dns.RcodeRefused) + g.backend.RecordBlockEvent(EgressBlockEvent{ + At: start.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + g.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: []string{}, + Action: "block", + BlockReason: blocked.Reason, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + return resp, nil + } + } + + upstreamProxy := g.backend.ResolveUpstream(src) + dnsServer := "" + if targetServer != "" { + dnsServer = targetServer + } else { + dnsServer = strings.TrimSpace(g.backend.DNSUpstream()) + if dnsServer == "" { + dnsServer = defaultSystemDNSUpstream() + } + if upstreamProxy != nil { + // A remote upstream proxy cannot reach the host's loopback stub (e.g. 127.0.0.53). + h, _ := splitHostAndPort(dnsServer) + if ip := net.ParseIP(strings.TrimSpace(h)); ip != nil && ip.IsLoopback() { + dnsServer = "8.8.8.8:53" + } + } + } + if _, _, err := net.SplitHostPort(dnsServer); err != nil { + dnsServer = net.JoinHostPort(dnsServer, "53") + } + var ( + reply *dns.Msg + err error + upstreamLabel string + ) + if upstreamProxy != nil { + // Anti-DNS-leak: tunnel DNS-over-TCP through the configured upstream proxy. + upstreamLabel = "tcp-via:" + MaskProxyURL(upstreamProxy) + "->" + dnsServer + reply, err = g.exchangeDNSOverProxy(r, upstreamProxy, dnsServer) + } else { + upstreamLabel = "direct:" + dnsServer + netProto := "udp" + if viaTCP { + netProto = "tcp" + } + timeout := 5 * time.Second + if targetServer != "" { + timeout = 3 * time.Second + } + client := &dns.Client{Net: netProto, Timeout: timeout} + reply, _, err = client.Exchange(r, dnsServer) + if err == nil && reply != nil && reply.Truncated && netProto == "udp" { + tcpClient := &dns.Client{Net: "tcp", Timeout: 5 * time.Second} + if tcpReply, _, terr := tcpClient.Exchange(r, dnsServer); terr == nil { + reply = tcpReply + } + } + } + + if err != nil || reply == nil { + resp := new(dns.Msg) + resp.SetRcode(r, dns.RcodeServerFailure) + errMsg := "dns exchange failed" + if err != nil { + errMsg = err.Error() + } + g.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeServerFailure], + Answers: []string{}, + Action: "error", + Upstream: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + Error: errMsg, + }) + if !synthServfail { + return nil, err + } + return resp, err + } + + answers, resolvedIPs := extractDNSAnswers(reply) + + // Post-resolution IP check (blocks DNS rebinding & IP/CIDR blacklist targets). + for _, ipStr := range resolvedIPs { + if blocked := g.backend.CheckOutbound(ipStr, "dns", src); blocked != nil { + resp := new(dns.Msg) + resp.SetRcode(r, dns.RcodeRefused) + g.backend.RecordBlockEvent(EgressBlockEvent{ + At: start.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname + " -> " + ipStr, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + g.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: answers, + Action: "block", + BlockReason: blocked.Reason, + Upstream: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + return resp, nil + } + } + + // Cache resolved IPs -> domain for subsequent raw TCP/UDP attribution & filtering. + if qname != "" { + for _, ipStr := range resolvedIPs { + g.backend.RememberDNS(ipStr, qname) + } + } + + rcode := dns.RcodeToString[reply.Rcode] + if rcode == "" { + rcode = strconv.Itoa(reply.Rcode) + } + g.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: rcode, + Answers: answers, + Action: "allow", + Upstream: upstreamLabel, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + return reply, nil +} + +func (g *TransparentGateway) exchangeDNSOverProxy(r *dns.Msg, upstream *url.URL, dnsServer string) (*dns.Msg, error) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + conn, err := dialTCPThroughUpstream(ctx, upstream, dnsServer, 8*time.Second) + if err != nil { + return nil, err + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(8 * time.Second)) + dc := &dns.Conn{Conn: conn} + if err := dc.WriteMsg(r); err != nil { + return nil, err + } + return dc.ReadMsg() +} + +func extractDNSAnswers(msg *dns.Msg) (answers []string, ips []string) { + if msg == nil { + return []string{}, nil + } + answers = make([]string, 0, len(msg.Answer)) + for _, rr := range msg.Answer { + switch v := rr.(type) { + case *dns.A: + s := v.A.String() + answers = append(answers, s) + ips = append(ips, s) + case *dns.AAAA: + s := v.AAAA.String() + answers = append(answers, s) + ips = append(ips, s) + case *dns.CNAME: + answers = append(answers, "CNAME "+strings.TrimSuffix(v.Target, ".")) + case *dns.TXT: + answers = append(answers, "TXT "+strings.Join(v.Txt, " ")) + case *dns.MX: + answers = append(answers, fmt.Sprintf("MX %d %s", v.Preference, strings.TrimSuffix(v.Mx, "."))) + case *dns.NS: + answers = append(answers, "NS "+strings.TrimSuffix(v.Ns, ".")) + case *dns.PTR: + answers = append(answers, "PTR "+strings.TrimSuffix(v.Ptr, ".")) + case *dns.SRV: + answers = append(answers, fmt.Sprintf("SRV %s:%d", strings.TrimSuffix(v.Target, "."), v.Port)) + default: + answers = append(answers, rr.String()) + } + } + return answers, ips +} + +// --- Transparent UDP handling --- + +type udpRelaySession struct { + key string + start time.Time + src SourceIdentity + srcPort int + client *net.UDPAddr + origDst *net.UDPAddr + dstHost string + remote *net.UDPConn + mu sync.Mutex + lastSeen time.Time + bytesTX int64 + bytesRX int64 + txCap limitedCapture + rxCap limitedCapture + closeOnce sync.Once + done chan struct{} +} + +func (s *udpRelaySession) close() { + s.closeOnce.Do(func() { + close(s.done) + if s.remote != nil { + _ = s.remote.Close() + } + }) +} + +func (g *TransparentGateway) serveUDP(uc *net.UDPConn) { + buf := make([]byte, 65535) + for { + n, srcAddr, origDst, err := readTransparentUDP(uc, buf) + if err != nil { + select { + case <-g.closed: + return + default: + } + continue + } + if srcAddr == nil || origDst == nil { + continue + } + pkt := make([]byte, n) + copy(pkt, buf[:n]) + g.HandleUDPPacket(srcAddr, origDst, pkt) + } +} + +// HandleUDPPacket processes one transparently intercepted non-DNS UDP datagram. +func (g *TransparentGateway) HandleUDPPacket(srcAddr, origDst *net.UDPAddr, payload []byte) { + if srcAddr == nil || origDst == nil { + return + } + now := time.Now() + srcIP := normalizeIP(srcAddr.IP).String() + dstIP := normalizeIP(origDst.IP).String() + dstPort := origDst.Port + src := g.backend.ResolveSource(srcIP) + if src.SrcIP == "" { + src.SrcIP = srcIP + } + dstHost := g.backend.LookupDNSReverse(dstIP) + if dstHost == "" { + dstHost = dstIP + } + + targetIPPort := net.JoinHostPort(dstIP, strconv.Itoa(dstPort)) + targetHostPort := net.JoinHostPort(dstHost, strconv.Itoa(dstPort)) + var blocked *BlockDecision + if dstHost != dstIP { + blocked = g.backend.CheckOutbound(targetHostPort, "udp", src) + } + if blocked == nil { + blocked = g.backend.CheckOutbound(targetIPPort, "udp", src) + } + if blocked != nil { + g.recordBlockedUDP(now, src, srcAddr.Port, dstIP, dstHost, dstPort, payload, blocked) + return + } + + policy := NormalizeUDPPolicy(g.backend.UDPPolicy()) + upstream := g.backend.ResolveUpstream(src) + if policy == UDPPolicyBlock || (policy == UDPPolicyBlockOnProxy && upstream != nil) { + reason := "UDP 流量已被策略阻断" + if upstream != nil { + reason = "已启用出口代理,为防止真实出口 IP 泄露已阻断直连 UDP(OPSEC)" + } + g.recordBlockedUDP(now, src, srcAddr.Port, dstIP, dstHost, dstPort, payload, &BlockDecision{ + Reason: reason, + RuleKind: "udp_policy", + Source: "udp_policy", + }) + return + } + + key := fmt.Sprintf("%s:%d->%s:%d", srcIP, srcAddr.Port, dstIP, dstPort) + g.udpMu.Lock() + sess, ok := g.udpSessions[key] + if !ok { + remote, err := net.DialUDP("udp", nil, origDst) + if err != nil { + g.udpMu.Unlock() + g.backend.RecordNetFlow(NetFlowRecord{ + TS: now.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(now).Milliseconds(), + Protocol: "udp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "error", + UpstreamProxy: "direct", + BytesTX: int64(len(payload)), + TXPreview: clipBytes(payload, maxFlowPreviewBytes), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcAddr.Port, + Error: err.Error(), + }) + return + } + sess = &udpRelaySession{ + key: key, + start: now, + src: src, + srcPort: srcAddr.Port, + client: srcAddr, + origDst: origDst, + dstHost: dstHost, + remote: remote, + lastSeen: now, + txCap: limitedCapture{max: maxFlowPreviewBytes}, + rxCap: limitedCapture{max: maxFlowPreviewBytes}, + done: make(chan struct{}), + } + g.udpSessions[key] = sess + g.udpMu.Unlock() + go g.runUDPSession(sess) + } else { + g.udpMu.Unlock() + } + + sess.mu.Lock() + sess.lastSeen = now + sess.bytesTX += int64(len(payload)) + _, _ = sess.txCap.Write(payload) + sess.mu.Unlock() + _, _ = sess.remote.Write(payload) +} + +func (g *TransparentGateway) recordBlockedUDP(now time.Time, src SourceIdentity, srcPort int, dstIP, dstHost string, dstPort int, payload []byte, b *BlockDecision) { + g.backend.RecordBlockEvent(EgressBlockEvent{ + At: now.UTC(), + Host: dstHost, + Port: strconv.Itoa(dstPort), + Method: "UDP", + URL: fmt.Sprintf("udp://%s:%d", dstHost, dstPort), + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: b.Reason, + RuleKind: b.RuleKind, + RuleID: b.RuleID, + Pattern: b.Pattern, + Source: b.Source, + }) + g.backend.RecordNetFlow(NetFlowRecord{ + TS: now.Unix(), + EndedAt: time.Now().Unix(), + DurationMS: time.Since(now).Milliseconds(), + Protocol: "udp", + DstIP: dstIP, + DstPort: dstPort, + DstHost: dstHost, + Action: "block", + BlockReason: b.Reason, + BytesTX: int64(len(payload)), + TXPreview: clipBytes(payload, maxFlowPreviewBytes), + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + SrcPort: srcPort, + }) +} + +func (g *TransparentGateway) runUDPSession(sess *udpRelaySession) { + const idleTimeout = 20 * time.Second + defer func() { + sess.close() + g.udpMu.Lock() + if cur, ok := g.udpSessions[sess.key]; ok && cur == sess { + delete(g.udpSessions, sess.key) + } + g.udpMu.Unlock() + + sess.mu.Lock() + end := sess.lastSeen + bytesTX, bytesRX := sess.bytesTX, sess.bytesRX + txPrev, rxPrev := sess.txCap.Bytes(), sess.rxCap.Bytes() + sess.mu.Unlock() + if end.Before(sess.start) { + end = time.Now() + } + g.backend.RecordNetFlow(NetFlowRecord{ + TS: sess.start.Unix(), + EndedAt: end.Unix(), + DurationMS: end.Sub(sess.start).Milliseconds(), + Protocol: "udp", + DstIP: normalizeIP(sess.origDst.IP).String(), + DstPort: sess.origDst.Port, + DstHost: sess.dstHost, + Action: "allow", + UpstreamProxy: "direct", + BytesTX: bytesTX, + BytesRX: bytesRX, + TXPreview: txPrev, + RXPreview: rxPrev, + SandboxScope: sess.src.Scope, + SandboxOwnerID: sess.src.OwnerID, + ContainerID: sess.src.ContainerID, + SessionID: sess.src.SessionID, + IntentID: sess.src.IntentID, + SrcIP: sess.src.SrcIP, + SrcPort: sess.srcPort, + }) + }() + + replyFn := g.cfg.UDPReplyFunc + if replyFn == nil { + replyFn = sendTransparentUDPReply + } + buf := make([]byte, 65535) + for { + _ = sess.remote.SetReadDeadline(time.Now().Add(idleTimeout)) + n, err := sess.remote.Read(buf) + if err != nil { + if os.IsTimeout(err) { + sess.mu.Lock() + idle := time.Since(sess.lastSeen) >= idleTimeout + sess.mu.Unlock() + if idle { + return + } + continue + } + return + } + if n > 0 { + sess.mu.Lock() + sess.lastSeen = time.Now() + sess.bytesRX += int64(n) + _, _ = sess.rxCap.Write(buf[:n]) + sess.mu.Unlock() + _ = replyFn(sess.origDst, sess.client, buf[:n]) + } + } +} + +// --- Helpers --- + +type limitedCapture struct { + mu sync.Mutex + buf bytes.Buffer + max int +} + +func (c *limitedCapture) Write(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + rem := c.max - c.buf.Len() + if rem > 0 { + if len(p) > rem { + _, _ = c.buf.Write(p[:rem]) + } else { + _, _ = c.buf.Write(p) + } + } + return len(p), nil +} + +func (c *limitedCapture) Bytes() []byte { + c.mu.Lock() + defer c.mu.Unlock() + if c.buf.Len() == 0 { + return nil + } + out := make([]byte, c.buf.Len()) + copy(out, c.buf.Bytes()) + return out +} + +func splitAddrIPPort(addr net.Addr) (string, int) { + if addr == nil { + return "", 0 + } + switch v := addr.(type) { + case *net.TCPAddr: + return normalizeIP(v.IP).String(), v.Port + case *net.UDPAddr: + return normalizeIP(v.IP).String(), v.Port + default: + h, p := splitHostAndPort(addr.String()) + port, _ := strconv.Atoi(p) + return normalizeIPString(h), port + } +} + +func defaultSystemDNSUpstream() string { + // On Ubuntu/Debian with systemd-resolved, /etc/resolv.conf only lists the + // local stub 127.0.0.53 while real uplink nameservers live in + // /run/systemd/resolve/resolv.conf. Prefer a real non-loopback resolver when + // present; otherwise allow 127.0.0.53 (systemd-resolved stub, reachable from + // host-networked artex-gateway without looping since gateway listens on :15053) + // before falling back to 8.8.8.8:53. + var systemdStub string + for _, path := range []string{"/run/systemd/resolve/resolv.conf", "/etc/resolv.conf"} { + cfg, err := dns.ClientConfigFromFile(path) + if err != nil || len(cfg.Servers) == 0 { + continue + } + port := cfg.Port + if port == "" { + port = "53" + } + for _, s := range cfg.Servers { + ip := net.ParseIP(strings.TrimSpace(s)) + if ip == nil || ip.IsUnspecified() { + continue + } + if ip.IsLoopback() { + if ip.String() == "127.0.0.53" && systemdStub == "" { + systemdStub = net.JoinHostPort(ip.String(), port) + } + continue + } + return net.JoinHostPort(ip.String(), port) + } + } + if systemdStub != "" { + return systemdStub + } + return "8.8.8.8:53" +} + +// FormatProxyContextAuthValue encodes SourceIdentity (plus optional gateway +// token for trusted src_ip/container_id forwarding) into a Basic auth value. +func FormatProxyContextAuthValue(id SourceIdentity, gwToken string) string { + q := url.Values{} + if id.Scope != "" { + q.Set("sc", id.Scope) + } + if id.OwnerID != "" { + q.Set("ow", id.OwnerID) + } + if id.ContainerID != "" { + q.Set("cid", id.ContainerID) + } + if id.SrcIP != "" { + q.Set("sip", id.SrcIP) + } + if id.SessionID != "" { + q.Set("sid", id.SessionID) + } + if id.IntentID > 0 { + q.Set("iid", strconv.FormatInt(id.IntentID, 10)) + } + if len(q) == 0 { + return "" + } + pwd := "x" + if gwToken != "" { + pwd = gwToken + } + return base64.StdEncoding.EncodeToString([]byte(proxyContextUserPrefix + q.Encode() + ":" + pwd)) +} + +// LocalTransparentBackend adapts *Traffic to TransparentBackend for embedded use. +type LocalTransparentBackend struct { + T *Traffic +} + +func (b LocalTransparentBackend) ResolveSource(srcIP string) SourceIdentity { + return b.T.resolveSource(srcIP, nil) +} + +func (b LocalTransparentBackend) CheckOutbound(rawHost, scheme string, src SourceIdentity) *BlockDecision { + m := b.T.checkOutboundForSource(rawHost, scheme, src) + if m == nil { + return nil + } + return &BlockDecision{ + Reason: m.Reason, + RuleKind: m.RuleKind, + RuleID: m.RuleID, + Pattern: m.Pattern, + Source: m.Source, + } +} + +func (b LocalTransparentBackend) ResolveUpstream(src SourceIdentity) *url.URL { + return b.T.resolveUpstreamForSource(src) +} + +func (b LocalTransparentBackend) IsPassthrough(host string) bool { + if b.T == nil || host == "" { + return false + } + _, ok := b.T.pass.Load(hostOnly(host)) + return ok +} + +func (b LocalTransparentBackend) LookupDNSReverse(ip string) string { + return b.T.LookupDNSReverse(ip) +} + +func (b LocalTransparentBackend) RememberDNS(ip, domain string) { + b.T.RememberDNS(ip, domain) +} + +func (b LocalTransparentBackend) RecordNetFlow(rec NetFlowRecord) { + _ = b.T.RecordNetFlow(rec) +} + +func (b LocalTransparentBackend) RecordDNSQuery(rec DNSQueryRecord) { + _ = b.T.RecordDNSQuery(rec) +} + +func (b LocalTransparentBackend) RecordBlockEvent(ev EgressBlockEvent) { + if b.T != nil && b.T.blockLog != nil { + b.T.blockLog.Record(ev) + } +} + +func (b LocalTransparentBackend) UDPPolicy() string { + if b.T == nil { + return UDPPolicyBlockOnProxy + } + return b.T.UDPPolicy() +} + +func (b LocalTransparentBackend) DNSUpstream() string { + if b.T == nil { + return "" + } + return b.T.DNSUpstream() +} + +func (b LocalTransparentBackend) GatewayToken() string { + if b.T == nil { + return "" + } + return b.T.GatewayToken() +} + +// Exported helpers on *Traffic for gateway/server policy sync. + +func (t *Traffic) SetGatewayToken(token string) { + if t == nil { + return + } + t.attrMu.Lock() + t.gatewayToken = strings.TrimSpace(token) + t.attrMu.Unlock() +} + +func (t *Traffic) GatewayToken() string { + if t == nil { + return "" + } + t.attrMu.RLock() + defer t.attrMu.RUnlock() + return t.gatewayToken +} + +func (t *Traffic) SetGatewaySettings(udpPolicy, dnsUpstream string) { + if t == nil { + return + } + t.attrMu.Lock() + t.udpPolicy = NormalizeUDPPolicy(udpPolicy) + t.dnsUpstream = strings.TrimSpace(dnsUpstream) + t.attrMu.Unlock() +} + +func (t *Traffic) UDPPolicy() string { + if t == nil { + return UDPPolicyBlockOnProxy + } + t.attrMu.RLock() + defer t.attrMu.RUnlock() + return NormalizeUDPPolicy(t.udpPolicy) +} + +func (t *Traffic) DNSUpstream() string { + if t == nil { + return "" + } + t.attrMu.RLock() + defer t.attrMu.RUnlock() + return t.dnsUpstream +} + +func (t *Traffic) SetStoreErrorTraffic(enabled bool) { + if t == nil { + return + } + t.storeErrorTraffic.Store(enabled) +} + +func (t *Traffic) StoreErrorTraffic() bool { + if t == nil { + return false + } + return t.storeErrorTraffic.Load() +} + +// PassthroughHosts returns the list of hostnames currently downgraded to L4 passthrough. +func (t *Traffic) PassthroughHosts() []string { + if t == nil { + return nil + } + var hosts []string + t.pass.Range(func(k, _ any) bool { + if s, ok := k.(string); ok && s != "" { + hosts = append(hosts, s) + } + return true + }) + return hosts +} + +// RecordBlockEvent records an external block event (e.g. ingested from artex-gateway). +func (t *Traffic) RecordBlockEvent(ev EgressBlockEvent) { + if t == nil || t.blockLog == nil { + return + } + t.blockLog.Record(ev) +} + +// SSRFGuardConfigSnapshot returns the active SSRF guard config (if enabled) for gateway sync. +func (t *Traffic) SSRFGuardConfigSnapshot() *SSRFGuardConfig { + if t == nil { + return nil + } + t.attrMu.RLock() + defer t.attrMu.RUnlock() + if t.ssrfCfg == nil { + return nil + } + cp := *t.ssrfCfg + return &cp +} + +// Ensure errors import is used cleanly. +var _ = errors.New diff --git a/traffic/transparent_test.go b/traffic/transparent_test.go new file mode 100644 index 0000000..b2c29da --- /dev/null +++ b/traffic/transparent_test.go @@ -0,0 +1,593 @@ +package traffic + +import ( + "bytes" + "crypto/tls" + "encoding/binary" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/miekg/dns" +) + +func buildTestClientHello(sni string) []byte { + // Build minimal valid TLS 1.2 ClientHello with server_name extension. + var ext []byte + if sni != "" { + nameBytes := []byte(sni) + entry := make([]byte, 3+len(nameBytes)) + entry[0] = 0x00 // host_name + binary.BigEndian.PutUint16(entry[1:3], uint16(len(nameBytes))) + copy(entry[3:], nameBytes) + + list := make([]byte, 2+len(entry)) + binary.BigEndian.PutUint16(list[0:2], uint16(len(entry))) + copy(list[2:], entry) + + ext = make([]byte, 4+len(list)) + binary.BigEndian.PutUint16(ext[0:2], 0x0000) // server_name ext type + binary.BigEndian.PutUint16(ext[2:4], uint16(len(list))) + copy(ext[4:], list) + } + + var body bytes.Buffer + body.Write([]byte{0x03, 0x03}) // TLS 1.2 + body.Write(make([]byte, 32)) // random + body.WriteByte(0x00) // session id len + body.Write([]byte{0x00, 0x02, 0x13, 0x01}) // cipher suites + body.Write([]byte{0x01, 0x00}) // compression methods + var extLen [2]byte + binary.BigEndian.PutUint16(extLen[:], uint16(len(ext))) + body.Write(extLen[:]) + body.Write(ext) + + hs := make([]byte, 4+body.Len()) + hs[0] = 0x01 // ClientHello + hs[1] = byte((body.Len() >> 16) & 0xff) + hs[2] = byte((body.Len() >> 8) & 0xff) + hs[3] = byte(body.Len() & 0xff) + copy(hs[4:], body.Bytes()) + + rec := make([]byte, 5+len(hs)) + rec[0] = 0x16 // Handshake + rec[1] = 0x03 + rec[2] = 0x01 + binary.BigEndian.PutUint16(rec[3:5], uint16(len(hs))) + copy(rec[5:], hs) + return rec +} + +func TestSniffProtocol(t *testing.T) { + t.Run("TLS ClientHello SNI", func(t *testing.T) { + c1, c2 := net.Pipe() + defer c1.Close() + defer c2.Close() + ch := buildTestClientHello("api.target.example") + go func() { _, _ = c1.Write(ch) }() + + res, wrapped := SniffProtocol(c2, 200*time.Millisecond) + if res.Proto != ProtoTLS || res.SNI != "api.target.example" { + t.Fatalf("expected TLS with SNI api.target.example, got %+v", res) + } + buf := make([]byte, len(ch)) + if _, err := io.ReadFull(wrapped, buf); err != nil { + t.Fatalf("read replayed bytes: %v", err) + } + if !bytes.Equal(buf, ch) { + t.Fatalf("peeked bytes mismatch") + } + }) + + t.Run("Plaintext HTTP", func(t *testing.T) { + c1, c2 := net.Pipe() + defer c1.Close() + defer c2.Close() + req := []byte("GET /admin HTTP/1.1\r\nHost: web.target.local:8080\r\n\r\n") + go func() { _, _ = c1.Write(req) }() + + res, wrapped := SniffProtocol(c2, 200*time.Millisecond) + if res.Proto != ProtoHTTP || res.Host != "web.target.local:8080" { + t.Fatalf("expected HTTP host web.target.local:8080, got %+v", res) + } + buf := make([]byte, len(req)) + if _, err := io.ReadFull(wrapped, buf); err != nil { + t.Fatalf("read replayed bytes: %v", err) + } + if !bytes.Equal(buf, req) { + t.Fatalf("replayed HTTP mismatch") + } + }) + + t.Run("Raw TCP server-speaks-first timeout", func(t *testing.T) { + c1, c2 := net.Pipe() + defer c1.Close() + defer c2.Close() + start := time.Now() + res, _ := SniffProtocol(c2, 40*time.Millisecond) + if res.Proto != ProtoTCP { + t.Fatalf("expected ProtoTCP on timeout, got %+v", res) + } + if time.Since(start) > 500*time.Millisecond { + t.Fatalf("peek timeout took too long: %v", time.Since(start)) + } + }) + + t.Run("Raw TCP binary protocol", func(t *testing.T) { + c1, c2 := net.Pipe() + defer c1.Close() + defer c2.Close() + payload := []byte("SSH-2.0-OpenSSH_9.6\r\n") + go func() { _, _ = c1.Write(payload) }() + + res, _ := SniffProtocol(c2, 200*time.Millisecond) + if res.Proto != ProtoTCP { + t.Fatalf("expected ProtoTCP for SSH banner, got %+v", res) + } + }) +} + +func TestTransparentTCPAndBlacklistAndNetFlows(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // Pretend loopback client belongs to task 77 container. + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "127.0.0.1" { + return SourceIdentity{ + Scope: "task", + OwnerID: "77", + ContainerID: "deadbeef12345678", + SrcIP: "172.30.0.9", + }, true + } + return SourceIdentity{}, false + }) + + // Start a raw TCP echo server (simulating Redis/nc/custom TCP service). + echoLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen echo: %v", err) + } + defer echoLn.Close() + go func() { + for { + c, err := echoLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + _, _ = conn.Write([]byte("+PONG-BANNER\r\n")) + buf := make([]byte, 64) + n, _ := conn.Read(buf) + if n > 0 { + _, _ = conn.Write([]byte("ECHO:" + string(buf[:n]))) + } + }(c) + } + }() + echoAddr := echoLn.Addr().(*net.TCPAddr) + + // Map echo IP to a domain in reverse DNS cache and test allow + block. + tr.RememberDNS(echoAddr.IP.String(), "redis.internal.test") + + gw := NewTransparentGateway(TransparentConfig{ + TCPAddr: "127.0.0.1:0", + PeekTimeout: 60 * time.Millisecond, + OrigDstResolver: func(_ net.Conn) (net.IP, int, error) { + return echoAddr.IP, echoAddr.Port, nil + }, + }, LocalTransparentBackend{T: tr}) + if err := gw.Start(); err != nil { + t.Fatalf("start transparent gateway: %v", err) + } + defer gw.Close() + + // 1) Allowed raw TCP connection. + conn, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second) + if err != nil { + t.Fatalf("dial gateway: %v", err) + } + _, _ = conn.Write([]byte("PING\r\n")) + got, _ := io.ReadAll(conn) + _ = conn.Close() + if !strings.Contains(string(got), "+PONG-BANNER") || !strings.Contains(string(got), "ECHO:PING") { + t.Fatalf("unexpected TCP relay response: %q", string(got)) + } + + // Wait briefly for flow persistence. + var flows []NetFlowRecord + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "77"}, 0, 10) + if len(rows) > 0 { + flows = rows + break + } + time.Sleep(20 * time.Millisecond) + } + if len(flows) != 1 { + t.Fatalf("expected 1 net_flow row, got %d", len(flows)) + } + if flows[0].Protocol != "tcp" || flows[0].Action != "allow" || flows[0].DstHost != "redis.internal.test" { + t.Fatalf("unexpected flow row: %+v", flows[0]) + } + if flows[0].BytesTX == 0 || flows[0].BytesRX == 0 { + t.Fatalf("expected non-zero bytes TX/RX: %+v", flows[0]) + } + detail, err := tr.GetNetFlow(flows[0].ID) + if err != nil { + t.Fatalf("GetNetFlow: %v", err) + } + if !strings.Contains(detail.TXPreviewText, "PING") || !strings.Contains(detail.RXPreviewText, "PONG-BANNER") { + t.Fatalf("unexpected previews: tx=%q rx=%q", detail.TXPreviewText, detail.RXPreviewText) + } + + // 2) Add egress blacklist for redis.internal.test -> next TCP flow must be blocked and recorded. + tr.SetEgressBlacklist([]EgressBlacklistRule{{ + ID: "r1", + Enabled: true, + Kind: "suffix", + Pattern: "internal.test", + }}) + conn2, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second) + if err != nil { + t.Fatalf("dial gateway (blocked): %v", err) + } + _, _ = conn2.Write([]byte("PING\r\n")) + got2, _ := io.ReadAll(conn2) + _ = conn2.Close() + if len(got2) != 0 { + t.Fatalf("expected blocked TCP connection to receive 0 bytes, got %q", string(got2)) + } + deadline = time.Now().Add(2 * time.Second) + var blockedFlows []NetFlowRecord + for time.Now().Before(deadline) { + rows, _, _ := tr.PageNetFlows(NetFlowQuery{Action: "block"}, 0, 10) + if len(rows) > 0 { + blockedFlows = rows + break + } + time.Sleep(20 * time.Millisecond) + } + if len(blockedFlows) != 1 || blockedFlows[0].BlockReason == "" { + t.Fatalf("expected 1 blocked net_flow, got %+v", blockedFlows) + } + + // 3) Verify traffic_search tool queries tcp flows. + tools := tr.Tools() + rawArgs, _ := json.Marshal(map[string]any{"protocol": "tcp", "host": "redis.internal.test", "task_id": "77"}) + res, err := tools[0].Call(t.Context(), rawArgs, nil) + if err != nil { + t.Fatalf("traffic_search tcp: %v", err) + } + if !strings.Contains(res.Flatten(), "redis.internal.test") { + t.Fatalf("expected traffic_search tcp to return flow, got %s", res.Flatten()) + } + + // 4) DeleteNonHTTPByOwner cleans up task 77's flows. + deleted, err := tr.DeleteNonHTTPByOwner("task", "77") + if err != nil || deleted < 2 { + t.Fatalf("expected >=2 deleted rows, got %d err=%v", deleted, err) + } +} + +func TestTransparentDNSInterceptionAndBlocking(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "127.0.0.1" { + return SourceIdentity{Scope: "task", OwnerID: "88", ContainerID: "cafebabe9999", SrcIP: "172.30.0.8"}, true + } + return SourceIdentity{}, false + }) + tr.SetEgressBlacklist([]EgressBlacklistRule{ + {ID: "b-dom", Enabled: true, Kind: "suffix", Pattern: "blocked.gov"}, + {ID: "b-ip", Enabled: true, Kind: "ip", Pattern: "198.51.100.77"}, + }) + + // Mock upstream authoritative DNS server on localhost. + upPC, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock upstream dns: %v", err) + } + defer upPC.Close() + upMux := dns.NewServeMux() + upMux.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) { + m := new(dns.Msg) + m.SetReply(r) + if len(r.Question) > 0 { + q := r.Question[0] + ip := "93.184.216.34" + if strings.Contains(strings.ToLower(q.Name), "rebind.example") { + ip = "198.51.100.77" + } + m.Answer = append(m.Answer, &dns.A{ + Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.ParseIP(ip), + }) + } + _ = w.WriteMsg(m) + }) + upSrv := &dns.Server{PacketConn: upPC, Handler: upMux} + go func() { _ = upSrv.ActivateAndServe() }() + defer upSrv.Shutdown() + + tr.SetGatewaySettings(UDPPolicyBlockOnProxy, upPC.LocalAddr().String()) + + // Pick a free UDP+TCP port for the transparent DNS listener. + probeLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("probe port: %v", err) + } + dnsAddr := probeLn.Addr().String() + _ = probeLn.Close() + + gw := NewTransparentGateway(TransparentConfig{DNSAddr: dnsAddr}, LocalTransparentBackend{T: tr}) + if err := gw.Start(); err != nil { + t.Fatalf("start dns gateway: %v", err) + } + defer gw.Close() + + c := &dns.Client{Net: "udp", Timeout: 2 * time.Second} + + // 1) Allowed domain resolves and caches IP -> domain. + q1 := new(dns.Msg) + q1.SetQuestion("app.allowed.example.", dns.TypeA) + r1, _, err := c.Exchange(q1, dnsAddr) + if err != nil || r1.Rcode != dns.RcodeSuccess || len(r1.Answer) == 0 { + t.Fatalf("expected allowed DNS reply, got r1=%v err=%v", r1, err) + } + if rev := tr.LookupDNSReverse("93.184.216.34"); rev != "app.allowed.example" { + t.Fatalf("expected reverse DNS cache 'app.allowed.example', got %q", rev) + } + + // 2) Blacklisted domain is REFUSED pre-resolution. + q2 := new(dns.Msg) + q2.SetQuestion("secret.blocked.gov.", dns.TypeA) + r2, _, err := c.Exchange(q2, dnsAddr) + if err != nil || r2.Rcode != dns.RcodeRefused { + t.Fatalf("expected REFUSED for blacklisted domain, got r2=%v err=%v", r2, err) + } + + // 3) DNS rebinding / resolved blacklisted IP is REFUSED post-resolution. + q3 := new(dns.Msg) + q3.SetQuestion("rebind.example.", dns.TypeA) + r3, _, err := c.Exchange(q3, dnsAddr) + if err != nil || r3.Rcode != dns.RcodeRefused { + t.Fatalf("expected REFUSED for blacklisted resolved IP, got r3=%v err=%v", r3, err) + } + + // Verify all 3 queries recorded in dns_queries with task attribution. + rows, total, err := tr.PageDNSQueries(DNSQueryFilter{OwnerTaskID: "88"}, 0, 10) + if err != nil || total != 3 || len(rows) != 3 { + t.Fatalf("expected 3 dns_queries rows, got total=%d len=%d err=%v", total, len(rows), err) + } +} + +func TestTransparentUDPPolicy(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // Set global upstream proxy + OPSEC default UDPPolicyBlockOnProxy. + if err := tr.SetUpstreamProxy("socks5://127.0.0.1:1080"); err != nil { + t.Fatalf("set upstream: %v", err) + } + tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "") + + gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr}) + src := &net.UDPAddr{IP: net.ParseIP("172.30.0.5"), Port: 54321} + dst := &net.UDPAddr{IP: net.ParseIP("93.184.216.34"), Port: 9999} + gw.HandleUDPPacket(src, dst, []byte("hello-udp")) + + rows, total, err := tr.PageNetFlows(NetFlowQuery{Protocol: "udp", Action: "block"}, 0, 10) + if err != nil || total != 1 || len(rows) != 1 { + t.Fatalf("expected 1 blocked UDP flow under block_on_proxy, got total=%d err=%v", total, err) + } + if !strings.Contains(rows[0].BlockReason, "OPSEC") { + t.Fatalf("expected OPSEC block reason, got %q", rows[0].BlockReason) + } +} + +func TestPerSourceUpstreamOverrideAndTransparentHTTPBridge(t *testing.T) { + // Start recording proxy on an ephemeral port. + probe, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("probe: %v", err) + } + proxyAddr := probe.Addr().String() + _ = probe.Close() + + tr, err := Open(t.TempDir(), proxyAddr) + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetGatewayToken("gw-secret-token") + + // Verify per-source upstream resolver precedence. + if err := tr.SetUpstreamProxy("http://127.0.0.1:19999"); err != nil { + t.Fatalf("set global upstream: %v", err) + } + directURL, _ := url.Parse("http://127.0.0.1:29999") + tr.SetUpstreamResolver(func(src SourceIdentity) (*url.URL, bool) { + if src.Scope == "task" && src.OwnerID == "10" { + return nil, true // force direct + } + if src.Scope == "task" && src.OwnerID == "20" { + return directURL, true // custom proxy + } + return nil, false // inherit global + }) + if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "10"}); u != nil { + t.Fatalf("task 10 should resolve to direct (nil), got %v", u) + } + if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "20"}); u == nil || u.String() != directURL.String() { + t.Fatalf("task 20 should resolve to %v, got %v", directURL, u) + } + if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "30"}); u == nil || u.Host != "127.0.0.1:19999" { + t.Fatalf("task 30 should inherit global proxy, got %v", u) + } + + // Clear global proxy and start real go-mitmproxy to verify HTTP transparent bridge. + _ = tr.SetUpstreamProxy("") + go func() { _ = tr.Start() }() + // Wait for proxy port to listen. + for range 40 { + if c, derr := net.DialTimeout("tcp", proxyAddr, 50*time.Millisecond); derr == nil { + _ = c.Close() + break + } + time.Sleep(25 * time.Millisecond) + } + + targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Proxy-Authorization") != "" { + w.WriteHeader(http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte("transparent-http-ok")) + })) + defer targetSrv.Close() + tu, _ := url.Parse(targetSrv.URL) + th, tpStr, _ := net.SplitHostPort(tu.Host) + tp, _ := strconv.Atoi(tpStr) + + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "127.0.0.1" { + return SourceIdentity{Scope: "task", OwnerID: "10", ContainerID: "abc123456789", SrcIP: "172.30.0.10"}, true + } + return SourceIdentity{}, false + }) + + gw := NewTransparentGateway(TransparentConfig{ + TCPAddr: "127.0.0.1:0", + MITMProxyAddr: proxyAddr, + OrigDstResolver: func(_ net.Conn) (net.IP, int, error) { + return net.ParseIP(th), tp, nil + }, + }, LocalTransparentBackend{T: tr}) + if err := gw.Start(); err != nil { + t.Fatalf("start gateway: %v", err) + } + defer gw.Close() + + // Send origin-form HTTP directly to transparent gateway (simulating curl after `unset HTTP_PROXY`). + c, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second) + if err != nil { + t.Fatalf("dial gw: %v", err) + } + _, _ = c.Write([]byte("GET /hello HTTP/1.1\r\nHost: " + tu.Host + "\r\nConnection: close\r\n\r\n")) + respBytes, _ := io.ReadAll(c) + _ = c.Close() + if !strings.Contains(string(respBytes), "transparent-http-ok") { + t.Fatalf("expected transparent HTTP response, got %q", string(respBytes)) + } + + // Verify exchange recorded with task 10 attribution. + deadline := time.Now().Add(2 * time.Second) + var rows []ExchangeMeta + for time.Now().Before(deadline) { + ex, _, _ := tr.Page(PageQuery{OwnerTaskID: "10", RespMin: -1, RespMax: -1}, 0, 10) + if len(ex) > 0 { + rows = ex + break + } + time.Sleep(25 * time.Millisecond) + } + if len(rows) == 0 || rows[0].SandboxOwnerID != "10" { + t.Fatalf("expected HTTP exchange attributed to task 10, got %+v", rows) + } + + // Silence unused tls import check if not needed. + _ = tls.VersionTLS12 +} + +func TestStoreErrorTrafficDefaultOffAndToggle(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + if tr.StoreErrorTraffic() { + t.Fatalf("expected StoreErrorTraffic to default to false") + } + + // Default OFF: error flows and DNS error queries are dropped; allow/block/passthrough are stored. + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-allow", Protocol: "tcp", DstIP: "1.1.1.1", DstPort: 80, Action: "allow"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-block", Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 80, Action: "block"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-pass", Protocol: "tls", DstIP: "1.1.1.3", DstPort: 443, Action: "passthrough"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-dropped", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"}) + + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-allow", QName: "ok.example", QType: "A", Action: "allow"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-block", QName: "bad.example", QType: "A", Action: "block"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-dropped", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"}) + + flows, totalFlows, err := tr.PageNetFlows(NetFlowQuery{}, 0, 20) + if err != nil || totalFlows != 3 || len(flows) != 3 { + t.Fatalf("expected 3 non-error flows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalFlows, flows, err) + } + dnsRows, totalDNS, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 20) + if err != nil || totalDNS != 2 || len(dnsRows) != 2 { + t.Fatalf("expected 2 non-error DNS rows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalDNS, dnsRows, err) + } + + // Enable error storage -> error flows & DNS errors are persisted. + tr.SetStoreErrorTraffic(true) + if !tr.StoreErrorTraffic() { + t.Fatalf("expected StoreErrorTraffic=true after toggle") + } + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-kept", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-kept", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"}) + + errFlows, errFlowTotal, _ := tr.PageNetFlows(NetFlowQuery{Action: "error"}, 0, 10) + if errFlowTotal != 1 || len(errFlows) != 1 || errFlows[0].ID != "nf-err-kept" { + t.Fatalf("expected 1 stored error flow after enabling, got total=%d rows=%+v", errFlowTotal, errFlows) + } + errDNS, errDNSTotal, _ := tr.PageDNSQueries(DNSQueryFilter{Action: "error"}, 0, 10) + if errDNSTotal != 1 || len(errDNS) != 1 || errDNS[0].ID != "dns-err-kept" { + t.Fatalf("expected 1 stored error DNS query after enabling, got total=%d rows=%+v", errDNSTotal, errDNS) + } + + // RemotePolicyState mirrors default-off and snapshot toggle before queueing events. + var gotFlows []NetFlowRecord + var gotDNS []DNSQueryRecord + rs := NewRemotePolicyState("tok", + func(r NetFlowRecord) { gotFlows = append(gotFlows, r) }, + func(r DNSQueryRecord) { gotDNS = append(gotDNS, r) }, + nil, + ) + rs.RecordNetFlow(NetFlowRecord{ID: "r-err-1", Action: "error"}) + rs.RecordNetFlow(NetFlowRecord{ID: "r-ok-1", Action: "allow"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-1", Action: "error"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-ok-1", Action: "allow"}) + if len(gotFlows) != 1 || gotFlows[0].ID != "r-ok-1" || len(gotDNS) != 1 || gotDNS[0].ID != "d-ok-1" { + t.Fatalf("RemotePolicyState should drop error events by default: flows=%+v dns=%+v", gotFlows, gotDNS) + } + rs.Apply(GatewayPolicySnapshot{UDPPolicy: UDPPolicyBlockOnProxy, StoreErrorTraffic: true}) + rs.RecordNetFlow(NetFlowRecord{ID: "r-err-2", Action: "error"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-2", Action: "error"}) + if len(gotFlows) != 2 || gotFlows[1].ID != "r-err-2" || len(gotDNS) != 2 || gotDNS[1].ID != "d-err-2" { + t.Fatalf("RemotePolicyState should forward error events when enabled: flows=%+v dns=%+v", gotFlows, gotDNS) + } +} diff --git a/update.sh b/update.sh index 10cfbbc..fc536de 100755 --- a/update.sh +++ b/update.sh @@ -1,61 +1,91 @@ #!/usr/bin/env bash -# ARTEX 更新脚本:① Docker 更新(拉新镜像重建) ② 本地编译更新(重建二进制) -# 与 install.sh 对应:install 负责首次落地,update 负责升级到新版本。 -# DB 迁移无需手动执行——artex 每次启动都会幂等重跑 schema.sql(含 ADD COLUMN/CREATE -# INDEX IF NOT EXISTS),所以“重启即迁移”。数据(pgdata 卷、./data、./skills)不受影响。 +# ARTEX 升级与回滚脚本: +# - 升级 Docker 部署(保留 pgdata / ./data / ./skills,兼容旧版自动校准目录权限) +# - 回滚到任意历史部署快照(本地固定镜像 ID,离线/覆盖 latest 也可 100% 精准回滚;健康检查失败自动回滚) +# - 本地 Go 编译更新(自动备份 ./artex -> ./artex.old 支持回滚) set -euo pipefail cd "$(cd "$(dirname "$0")" && pwd)" -info(){ printf '\033[36m[*]\033[0m %s\n' "$*"; } -ok(){ printf '\033[32m[+]\033[0m %s\n' "$*"; } -warn(){ printf '\033[33m[!]\033[0m %s\n' "$*"; } -die(){ printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; } -ask(){ local p="$1" d="${2:-}" a; read -rp "$p${d:+ [$d]}: " a; echo "${a:-$d}"; } +# shellcheck source=scripts/deploy-lib.sh +. ./scripts/deploy-lib.sh -# ── 可选:同步仓库到最新代码(compose/脚本/本地编译源码都靠它更新)─────── sync_repo(){ - [ -d .git ] && command -v git >/dev/null 2>&1 || { warn "非 git 工作副本,跳过 git pull"; return; } - [ "$(ask '拉取最新代码 (git pull --ff-only)? (y/n)' y)" = y ] || return + [ "${ARTEX_SKIP_GIT_PULL:-0}" = "1" ] && return 0 + [ -d .git ] && command -v git >/dev/null 2>&1 || { warn "非 git 工作副本,跳过 git pull"; return 0; } + [ "$(ask '拉取最新代码 (git pull --ff-only)? (y/n)' y)" = y ] || return 0 if ! git pull --ff-only; then warn "git pull 未能快进(本地有改动或分支分叉)——请手动处理后重试,本次沿用当前代码" fi } -# ── ① Docker 更新 ─────────────────────────────── -update_docker(){ +require_docker_env(){ command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1 \ || die "未检测到 docker / docker compose,请先用 ./install.sh 安装部署" [ -f .env ] || die "未找到 .env,请先运行 ./install.sh 完成首次部署" - - # 可选:升级到指定版本 tag(不填则沿用 .env 中的 ARTEX_TAG,缺省为 latest) - local tag; tag="$(ask '目标镜像 tag(回车沿用 .env / latest)' '')" - if [ -n "$tag" ]; then - if grep -q '^ARTEX_TAG=' .env; then - sed -i.bak "s|^ARTEX_TAG=.*|ARTEX_TAG=${tag}|" .env && rm -f .env.bak - else - printf '\nARTEX_TAG=%s\n' "$tag" >> .env - fi - ok "已将 ARTEX_TAG 设为 ${tag}" - fi - - # 只动 artex:postgres 是固定的 16-alpine,不需要跟着升级(拉它纯属浪费带宽, - # 且大版本变动还会有兼容风险)。artex 声明了 depends_on postgres,所以带服务名 - # up 时若 pg 没起会自动拉起,已在跑的则原样保留、不重建。 - info "拉取新镜像(仅 artex)…" - docker compose pull artex - info "重建并启动(artex 重启时自动迁移 schema)…" - docker compose up -d artex - ok "更新完成 → http://localhost:8787" - info "查看日志:docker compose logs -f artex" - info "清理旧镜像(可选):docker image prune -f" } -# ── ② 本地编译更新 ────────────────────────────── +# ── ① Docker 升级(自动快照 + 失败自动回滚)───────────────────────────── +update_docker(){ + local tag="${1:-}" skip_db="${2:-0}" + require_docker_env + preflight_docker + + if [ -z "$tag" ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then + tag="$(ask '目标镜像 tag(回车沿用 .env / latest;如 v0.3.33)' '')" + fi + + info "正在创建升级前部署快照(用于失败自动回滚或手动回滚)…" + local snap_id + snap_id="$(create_deploy_snapshot "upgrade" "$skip_db")" + ok "已创建回滚快照:${snap_id}" + + prepare_env_for_docker "$tag" .env + prepare_migrated_workspaces ./data + + deploy_with_rollback "$snap_id" + ok "升级完成 → http://localhost:8787" + info "如需回滚到升级前状态:./update.sh --rollback ${snap_id}" + info "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex" +} + +# ── ④ 回滚到历史部署快照 ──────────────────────────────────────────────── +interactive_rollback(){ + local snap_id="${1:-}" restore_db="${2:-0}" + require_docker_env + + if [ -z "$snap_id" ]; then + echo "可用的部署回滚快照:" + list_deploy_snapshots + local latest="" + [ -f "${DEPLOY_STATE_DIR}/latest" ] && latest="$(cat "${DEPLOY_STATE_DIR}/latest")" + [ -n "$latest" ] || die "当前没有任何可回滚的部署快照" + snap_id="$(ask '要回滚的快照 ID(回车选最新)' "$latest")" + fi + + local snap_dir="${DEPLOY_SNAP_DIR}/${snap_id}" + [ -f "${snap_dir}/meta.env" ] || die "快照不存在:${snap_id}" + + if [ "$restore_db" != "1" ] && [ "$(env_get HAS_PG_DUMP "${snap_dir}/meta.env")" = "1" ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then + warn "当前版本与上一版本数据库结构前向/后向兼容,通常无需覆盖数据库。" + if [ "$(ask '是否同时用快照中的 postgres.sql.gz 覆盖恢复数据库? (y/n)' n)" = "y" ]; then + restore_db=1 + fi + fi + + rollback_to_snapshot "$snap_id" "$restore_db" +} + +# ── ⑤ 本地编译更新 ────────────────────────────────────────────────────── update_local(){ command -v go >/dev/null 2>&1 || die "未检测到 Go(>=1.26):https://go.dev/dl/" [ -f config.json ] || warn "未找到 config.json——若首次部署请改用 ./install.sh" ok "Go: $(go version)" + if [ -x ./artex ]; then + cp ./artex ./artex.old + ok "已备份当前二进制 → ./artex.old(如需回滚可执行 mv ./artex.old ./artex 后重启)" + fi + if command -v npm >/dev/null 2>&1; then info "重建前端静态产物…" ( cd web && npm ci && npm run build:static ) @@ -70,13 +100,87 @@ update_local(){ warn "请重启正在运行的 artex 进程以生效(重启时会自动迁移 schema)" } -echo "==============================" -echo " ARTEX 更新" -echo " 1) Docker 更新(拉新镜像重建)" -echo " 2) 本地更新(go 重新编译)" -echo "==============================" +usage(){ + cat <<'USAGE' +用法: ./update.sh [动作] [选项] + +动作(不传则进入交互菜单): + --upgrade 升级 Docker 部署(自动创建回滚快照) + --rollback [SNAPSHOT_ID] 回滚到最新或指定的历史部署快照 + --list-snapshots 列出所有可用的部署回滚快照 + --local 本地 Go 重新编译更新 + +选项: + --tag 指定目标镜像版本 tag(如 v0.3.33 / latest) + --restore-db 配合 --rollback 同时恢复快照中的 PostgreSQL 备份 + --no-db-backup 创建快照时跳过 pg_dump + --skip-pull 跳过镜像拉取 + --skip-git-pull 跳过 git pull + -y, --yes 非交互模式 + -h, --help 显示本帮助 +USAGE +} + +ACTION="" +OPT_TAG="" +OPT_SNAP="" +OPT_RESTORE_DB=0 +OPT_SKIP_DB=0 + +while [ "$#" -gt 0 ]; do + case "$1" in + --upgrade) ACTION="upgrade" ;; + --rollback) + ACTION="rollback" + if [ "${2:-}" != "" ] && [ "${2#-}" = "${2}" ]; then + shift + OPT_SNAP="$1" + fi + ;; + --list-snapshots) ACTION="list-snapshots" ;; + --local) ACTION="local" ;; + --tag) shift; [ "$#" -gt 0 ] || die "--tag 需要参数"; OPT_TAG="$1" ;; + --restore-db) OPT_RESTORE_DB=1 ;; + --no-db-backup) OPT_SKIP_DB=1 ;; + --skip-pull) export ARTEX_SKIP_PULL=1 ;; + --skip-git-pull) export ARTEX_SKIP_GIT_PULL=1 ;; + -y|--yes) export ARTEX_NONINTERACTIVE=1 ;; + -h|--help) usage; exit 0 ;; + *) die "未知参数:$1(使用 --help 查看帮助)" ;; + esac + shift +done + +case "$ACTION" in + upgrade) + sync_repo + update_docker "$OPT_TAG" "$OPT_SKIP_DB" + exit 0 + ;; + rollback) + interactive_rollback "$OPT_SNAP" "$OPT_RESTORE_DB" + exit 0 + ;; + list-snapshots) + list_deploy_snapshots + exit 0 + ;; + local) + sync_repo + update_local + exit 0 + ;; +esac + +echo "==========================================" +echo " ARTEX 升级与回滚" +echo " 1) Docker 升级(自动创建回滚快照)" +echo " 2) 回滚到历史部署快照" +echo " 3) 本地更新(Go 重新编译)" +echo "==========================================" case "$(ask '选择' 1)" in - 1) sync_repo; update_docker ;; - 2) sync_repo; update_local ;; + 1) sync_repo; update_docker "$OPT_TAG" "$OPT_SKIP_DB" ;; + 2) interactive_rollback "$OPT_SNAP" "$OPT_RESTORE_DB" ;; + 3) sync_repo; update_local ;; *) die "无效选择" ;; esac diff --git a/web/src/app/(main)/chat/_components/session-sandbox-control.tsx b/web/src/app/(main)/chat/_components/session-sandbox-control.tsx new file mode 100644 index 0000000..2559e31 --- /dev/null +++ b/web/src/app/(main)/chat/_components/session-sandbox-control.tsx @@ -0,0 +1,503 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import { + BoxIcon, + ExternalLinkIcon, + PlayIcon, + RefreshCwIcon, + RotateCcwIcon, + SquareIcon, + Trash2Icon, +} from "lucide-react"; +import { toast } from "sonner"; +import { ContainerProxyControlSection } from "@/components/proxy-route-selector"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Label } from "@/components/ui/label"; +import { + Popover, + PopoverContent, + PopoverDescription, + PopoverHeader, + PopoverTitle, + PopoverTrigger, +} from "@/components/ui/popover"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import { api } from "@/lib/api"; +import type { SandboxContainerInfo } from "@/lib/types"; + +function fmtBytes(n?: number): string { + if (!n || n <= 0) return "0 B"; + if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`; + if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`; + if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`; + return `${n} B`; +} + +function fmtUptime(startedAt?: string): string { + if (!startedAt) return "-"; + const ts = Date.parse(startedAt); + if (Number.isNaN(ts)) return "-"; + const sec = Math.max(0, Math.floor((Date.now() - ts) / 1000)); + if (sec < 60) return `${sec}s`; + const min = Math.floor(sec / 60); + if (min < 60) return `${min}m ${sec % 60}s`; + const hr = Math.floor(min / 60); + if (hr < 24) return `${hr}h ${min % 60}m`; + return `${Math.floor(hr / 24)}d ${hr % 24}h`; +} + +export function SessionSandboxControl({ + conversationId, + sandboxScope, + sandboxOwnerId, + running: chatRunning, +}: { + conversationId: number; + sandboxScope?: string; + sandboxOwnerId?: string; + running: boolean; +}) { + const { isEn } = useLiveTranslation(); + const L = (zh: string, en: string) => (isEn ? en : zh); + + const scope = sandboxScope === "task" ? "task" : "session"; + const ownerID = sandboxOwnerId ?? `conv-${conversationId}`; + const taskBound = scope === "task"; + const boxZh = taskBound ? "任务沙箱" : "会话沙箱"; + const boxEn = taskBound ? "Task sandbox" : "Session sandbox"; + const [open, setOpen] = React.useState(false); + const [info, setInfo] = React.useState(null); + const [loading, setLoading] = React.useState(false); + const [busy, setBusy] = React.useState<"" | "start" | "stop" | "recreate" | "remove">(""); + const [recreateOpen, setRecreateOpen] = React.useState(false); + const [clearWorkspace, setClearWorkspace] = React.useState(false); + const [removeOpen, setRemoveOpen] = React.useState(false); + + const reqSeqRef = React.useRef(0); + + const fetchInfo = React.useCallback( + async (withStats: boolean, silent = false) => { + const seq = ++reqSeqRef.current; + if (!silent) setLoading(true); + try { + const res = await api.sandboxContainer(scope, ownerID, withStats); + if (seq === reqSeqRef.current) { + setInfo(res); + } + } catch { + // Ignore transient poll errors; popover refresh button lets user retry. + } finally { + if (seq === reqSeqRef.current && !silent) { + setLoading(false); + } + } + }, + [scope, ownerID], + ); + + React.useEffect(() => { + reqSeqRef.current += 1; + setInfo(null); + void fetchInfo(false); + }, [fetchInfo]); + + React.useEffect(() => { + if (!open) return; + void fetchInfo(true); + }, [open, fetchInfo]); + + // Refresh container status whenever a chat turn starts or completes (tool calls + // lazily create/start the container mid-turn). + const prevRunningRef = React.useRef(chatRunning); + React.useEffect(() => { + if (prevRunningRef.current !== chatRunning) { + void fetchInfo(open, true); + } + prevRunningRef.current = chatRunning; + }, [chatRunning, open, fetchInfo]); + + // Poll while a chat turn is running (every 2s until the container reports running, + // then every 5s) or while the popover is open so live status never stays stale. + const infoState = info?.state; + React.useEffect(() => { + if (infoState === "local") return; + if (!chatRunning && !open) return; + const intervalMs = chatRunning && infoState !== "running" ? 2000 : 5000; + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }, intervalMs); + return () => window.clearInterval(timer); + }, [chatRunning, open, infoState, fetchInfo]); + + React.useEffect(() => { + if (infoState === "local") return; + const onVisibility = () => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }; + document.addEventListener("visibilitychange", onVisibility); + return () => document.removeEventListener("visibilitychange", onVisibility); + }, [open, infoState, fetchInfo]); + + // Hide completely when running in local (non-Docker) mode. + if (!info || info.state === "local") { + return null; + } + + const running = info.state === "running"; + const exists = info.state !== "missing"; + + let stateLabel = info.state; + if (info.state === "running") stateLabel = L("沙箱运行中", "Sandbox Running"); + else if (info.state === "created") stateLabel = L("沙箱启动中", "Sandbox Starting"); + else if (info.state === "exited") stateLabel = L("沙箱已停止", "Sandbox Stopped"); + else if (info.state === "missing") stateLabel = L("沙箱未创建", "Sandbox Standby"); + else if (info.state === "error") stateLabel = L("沙箱异常", "Sandbox Error"); + + let dotClass = "bg-muted-foreground/50"; + if (running) dotClass = "bg-emerald-500"; + else if (info.state === "created") dotClass = "bg-amber-500"; + else if (info.state === "error") dotClass = "bg-red-500"; + + const handleStart = async () => { + setBusy("start"); + try { + const res = await api.startSandboxContainer(scope, ownerID); + reqSeqRef.current += 1; + setInfo(res); + toast.success(L(`${boxZh}容器已启动`, `${boxEn} container started`)); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(""); + } + }; + + const handleStop = async () => { + setBusy("stop"); + try { + const res = await api.stopSandboxContainer(scope, ownerID); + reqSeqRef.current += 1; + setInfo(res); + toast.success(L(`${boxZh}容器已停止(内存已释放)`, `${boxEn} container stopped`)); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(""); + } + }; + + const executeRecreate = async () => { + const wipe = clearWorkspace; + setRecreateOpen(false); + setClearWorkspace(false); + setBusy("recreate"); + try { + const res = await api.recreateSandboxContainer(scope, ownerID, { clear_workspace: wipe }); + reqSeqRef.current += 1; + setInfo(res); + toast.success( + wipe + ? L(`${boxZh}已重建并清空工作区`, `${boxEn} recreated with clean workspace`) + : L(`${boxZh}已重建(工作区文件已保留)`, `${boxEn} recreated`), + ); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(""); + } + }; + + const executeRemove = async () => { + setRemoveOpen(false); + setBusy("remove"); + try { + await api.removeSandboxContainer(scope, ownerID); + await fetchInfo(false); + toast.success(L(`${boxZh}容器已删除(工作区文件已保留)`, `${boxEn} container removed`)); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(""); + } + }; + return ( + <> + + + + + + + + + + {L(taskBound ? "任务沙箱" : "对话隔离沙箱", taskBound ? "Task Sandbox" : "Chat Sandbox")} + + {info.state} + + + {taskBound + ? L( + "本对话调用命令、脚本或浏览器时,实际跑在关联任务的沙箱容器里,不会另开一个对话容器。", + "Commands, scripts, and browser tools in this chat run in the linked task sandbox, not a separate chat container.", + ) + : L( + "本对话调用命令、脚本或浏览器时将在此独立非 root 容器内执行(按需自动创建,空闲自动停机)。", + "Commands, scripts, and browser tools in this chat run inside this isolated non-root container (created on demand).", + )} + + + +
+
+ + {L(taskBound ? "任务" : "会话", taskBound ? "Task" : "Session")} + + {ownerID} +
+
+ {L("容器", "Container")} + {info.short_id || "-"} +
+
+ {L("镜像", "Image")} + + {info.image} + +
+
+ {L("网络", "Network")} + {info.network || "-"} +
+
+ {L("活跃执行", "Active runs")} + {info.active_runs} +
+ {running ? ( + <> +
+ {L("运行时长", "Uptime")} + {fmtUptime(info.started_at)} +
+
+ CPU + {(info.cpu_percent ?? 0).toFixed(1)}% +
+
+ {L("内存", "Memory")} + + {fmtBytes(info.mem_usage_bytes)} + {info.mem_limit_bytes ? ` / ${fmtBytes(info.mem_limit_bytes)}` : ""} + +
+ {info.pids_current != null ? ( +
+ PIDs + {info.pids_current} +
+ ) : null} + + ) : null} + {info.error ?

{info.error}

: null} +
+ + + +
+ {!running ? ( + + ) : ( + + )} + + {exists ? ( + + ) : null} + +
+ +
+ {taskBound ? ( + + {L("查看关联任务", "Open task")} + + + ) : ( + + )} + + {L("前往沙箱容器管理", "All Sandbox Containers")} + + +
+
+
+ + + + + + {L( + taskBound ? "重建任务沙箱容器" : "重建对话沙箱容器", + taskBound ? "Recreate Task Sandbox" : "Recreate Chat Sandbox", + )} + + + {taskBound + ? L( + "确定销毁关联任务的沙箱容器,并按最新镜像与资源配额重新创建吗?这会影响该任务,不会另开对话容器。", + "Replace the linked task's sandbox container with a fresh one? This affects that task.", + ) + : L( + "确定销毁当前对话的旧容器并按最新镜像与资源配额重新创建启动吗?", + "Replace this chat's sandbox container with a fresh one using the latest image and limits?", + )} + + +
+ setClearWorkspace(Boolean(v))} + className="mt-0.5" + /> + +
+ + {L("取消", "Cancel")} + void executeRecreate()}> + {clearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")} + + +
+
+ + + + + + {L( + taskBound ? "删除任务沙箱容器" : "删除对话沙箱容器", + taskBound ? "Delete Task Sandbox" : "Delete Chat Sandbox", + )} + + + {taskBound + ? L( + "确定删除关联任务的沙箱容器吗?任务工作区文件会保留,下次执行命令时会重新创建。", + "Remove the linked task's sandbox container? Task workspace files will be preserved.", + ) + : L( + "确定删除该对话的沙箱容器吗?宿主机工作区文件会保留,后续调用工具时将自动重新创建。", + "Remove this chat's sandbox container? Host workspace files will be preserved.", + )} + + + + {L("取消", "Cancel")} + void executeRemove()} + > + {L("确认删除", "Delete")} + + + + + + ); +} diff --git a/web/src/app/(main)/chat/page.tsx b/web/src/app/(main)/chat/page.tsx index 506ac49..a3040b9 100644 --- a/web/src/app/(main)/chat/page.tsx +++ b/web/src/app/(main)/chat/page.tsx @@ -64,6 +64,7 @@ import { isBtwCommand } from "@/lib/side-questions"; import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { SessionSandboxControl } from "./_components/session-sandbox-control"; // fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx). function fmtBytes(n: number): string { if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`; @@ -755,7 +756,9 @@ function ChatView({ if (files.length === 0) return; setUploading(true); try { - const r = await api.chatUpload("session", `conv-${conv.id}`, files); + const uploadScope = conv.sandbox_scope === "task" ? "task" : "session"; + const uploadOwner = conv.sandbox_owner_id ?? `conv-${conv.id}`; + const r = await api.chatUpload(uploadScope, uploadOwner, files); setAttachments((prev) => [...prev, ...r.attachments]); } catch (e) { toast.error(translate("overview.uploadFailedPrefix") + localizedError(e, translate)); @@ -824,6 +827,12 @@ function ChatView({ )} {running && } +
{tokenTotal.turns > 0 && ( diff --git a/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx b/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx new file mode 100644 index 0000000..6a24ac1 --- /dev/null +++ b/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx @@ -0,0 +1,478 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import { ArrowUpRightIcon } from "lucide-react"; +import { Area, AreaChart, CartesianGrid, Tooltip as RechartsTooltip, XAxis, YAxis } from "recharts"; + +import { Badge } from "@/components/ui/badge"; +import { Card } from "@/components/ui/card"; +import { type ChartConfig, ChartContainer } from "@/components/ui/chart"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import type { ActiveFindingRetest, Finding, FindingStatus, SandboxGlobalStatus, Task } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +type TrendTab = "findings" | "containers" | "lifecycle"; +type WindowDays = 7 | 14 | 30; + +interface DayBucket { + dayKey: string; + label: string; + findingsTotal: number; + findingsHighCrit: number; + findingsMedLow: number; + findingsClosed: number; + containersCreated: number; + containersRunning: number; + containersTask: number; + containersSession: number; + tasksCreated: number; + tasksCompleted: number; +} + +const CLOSED_FINDING_STATUS: Partial> = { + resolved: true, + fixed: true, + false_positive: true, + ignored: true, + duplicate: true, + risk_accepted: true, +}; + +const WINDOW_OPTIONS: readonly WindowDays[] = [7, 14, 30]; + +function toLocalDayKey(date: Date): string { + const y = date.getFullYear(); + const m = String(date.getMonth() + 1).padStart(2, "0"); + const d = String(date.getDate()).padStart(2, "0"); + return `${y}-${m}-${d}`; +} + +function parseTimestamp(ts?: string | number): Date | null { + if (!ts) return null; + if (typeof ts === "number") { + if (ts <= 0) return null; + const d = new Date(ts * 1000); + return Number.isNaN(d.getTime()) ? null : d; + } + const ms = Date.parse(ts); + if (Number.isNaN(ms)) return null; + return new Date(ms); +} + +export function EnvironmentLifecycleRow({ + sandboxStatus, + findings, + tasks, + activeRetests, +}: { + sandboxStatus: SandboxGlobalStatus | null; + findings: Finding[]; + tasks: Task[]; + activeRetests: ActiveFindingRetest[]; +}) { + const { t: translate } = useLiveTranslation(); + const [tab, setTab] = React.useState("findings"); + const [days, setDays] = React.useState(7); + + const { buckets, summary } = React.useMemo(() => { + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const list: DayBucket[] = []; + const byKey = new Map(); + for (let i = days - 1; i >= 0; i--) { + const d = new Date(today); + d.setDate(today.getDate() - i); + const dayKey = toLocalDayKey(d); + const bucket: DayBucket = { + dayKey, + label: dayKey.slice(5).replace("-", "/"), + findingsTotal: 0, + findingsHighCrit: 0, + findingsMedLow: 0, + findingsClosed: 0, + containersCreated: 0, + containersRunning: 0, + containersTask: 0, + containersSession: 0, + tasksCreated: 0, + tasksCompleted: 0, + }; + list.push(bucket); + byKey.set(dayKey, bucket); + } + + let windowFindings = 0; + let windowHighCrit = 0; + let windowClosedFindings = 0; + let totalClosedFindings = 0; + + for (const f of findings) { + const isClosed = Boolean(CLOSED_FINDING_STATUS[f.status]); + if (isClosed) totalClosedFindings++; + const dt = parseTimestamp(f.ts); + if (!dt) continue; + const bucket = byKey.get(toLocalDayKey(dt)); + if (!bucket) continue; + bucket.findingsTotal++; + windowFindings++; + if (f.severity === "critical" || f.severity === "high") { + bucket.findingsHighCrit++; + windowHighCrit++; + } else { + bucket.findingsMedLow++; + } + if (isClosed) { + bucket.findingsClosed++; + windowClosedFindings++; + } + } + + const containers = Array.isArray(sandboxStatus?.containers) ? sandboxStatus.containers : []; + let windowContainersCreated = 0; + let currentRunningContainers = 0; + let currentStoppedContainers = 0; + + for (const c of containers) { + if (c.state === "running") currentRunningContainers++; + else currentStoppedContainers++; + const dt = parseTimestamp(c.created_at); + if (!dt) continue; + const bucket = byKey.get(toLocalDayKey(dt)); + if (!bucket) continue; + bucket.containersCreated++; + windowContainersCreated++; + if (c.state === "running") bucket.containersRunning++; + if (c.scope === "task") bucket.containersTask++; + else if (c.scope === "session") bucket.containersSession++; + } + + let windowTasksCreated = 0; + let windowTasksCompleted = 0; + + for (const t of tasks) { + const createdDt = parseTimestamp(t.created_unix ?? t.created_at); + if (createdDt) { + const b = byKey.get(toLocalDayKey(createdDt)); + if (b) { + b.tasksCreated++; + windowTasksCreated++; + } + } + const completedDt = parseTimestamp(t.completed_unix && t.completed_unix > 0 ? t.completed_unix : t.completed_at); + if (completedDt) { + const b = byKey.get(toLocalDayKey(completedDt)); + if (b) { + b.tasksCompleted++; + windowTasksCompleted++; + } + } + } + + const closureRate = findings.length > 0 ? Math.round((totalClosedFindings / findings.length) * 100) : 0; + + return { + buckets: list, + summary: { + windowFindings, + windowHighCrit, + windowClosedFindings, + windowContainersCreated, + currentRunningContainers, + currentStoppedContainers, + windowTasksCreated, + windowTasksCompleted, + closureRate, + }, + }; + }, [days, findings, sandboxStatus, tasks]); + + const seriesByTab = { + findings: { + primaryKey: "findingsTotal" as const, + primaryLabel: translate("overview.trendSeriesFindings"), + secondaryKey: "findingsHighCrit" as const, + secondaryLabel: translate("overview.trendSeriesHighCrit"), + secondaryColor: "#f43f5e", + }, + containers: { + primaryKey: "containersCreated" as const, + primaryLabel: translate("overview.trendSeriesContainersCreated"), + secondaryKey: "containersRunning" as const, + secondaryLabel: translate("overview.trendSeriesContainersRunning"), + secondaryColor: "#10b981", + }, + lifecycle: { + primaryKey: "tasksCreated" as const, + primaryLabel: translate("overview.trendSeriesTasksCreated"), + secondaryKey: "tasksCompleted" as const, + secondaryLabel: translate("overview.trendSeriesTasksCompleted"), + secondaryColor: "#10b981", + }, + }; + const activeSeries = seriesByTab[tab]; + + const chartConfig: ChartConfig = { + primary: { label: activeSeries.primaryLabel, color: "#2563eb" }, + secondary: { label: activeSeries.secondaryLabel, color: activeSeries.secondaryColor }, + }; + + const formatTick = (value: number) => translate("overview.trendYAxisTick", { count: value }); + + let sandboxBadge: React.ReactNode = null; + if (tab === "containers" && sandboxStatus) { + if (!sandboxStatus.enabled) { + sandboxBadge = ( + + {translate("overview.sandboxLocal")} + + ); + } else if (sandboxStatus.available) { + sandboxBadge = ( + + {translate("overview.sandboxDocker", { runtime: sandboxStatus.runtime || "runc" })} + + ); + } else { + sandboxBadge = ( + + {translate("overview.sandboxUnavailable")} + + ); + } + } + + let footerSummary: string; + let footerHref: string; + let footerLinkLabel: string; + + if (tab === "findings") { + footerSummary = translate("overview.trendFooterFindings", { + total: summary.windowFindings, + highCrit: summary.windowHighCrit, + closed: summary.windowClosedFindings, + }); + footerHref = "/function/findings"; + footerLinkLabel = translate("overview.trendLinkFindings"); + } else if (tab === "containers") { + footerSummary = translate("overview.trendFooterContainers", { + created: summary.windowContainersCreated, + running: summary.currentRunningContainers, + stopped: summary.currentStoppedContainers, + }); + footerHref = "/system/sandbox"; + footerLinkLabel = translate("overview.trendLinkContainers"); + } else { + footerSummary = translate("overview.trendFooterLifecycle", { + created: summary.windowTasksCreated, + completed: summary.windowTasksCompleted, + rate: summary.closureRate, + }); + footerHref = "/function/tasks"; + footerLinkLabel = translate("overview.trendLinkLifecycle"); + } + + const tabs: ReadonlyArray<{ id: TrendTab; label: string }> = [ + { id: "findings", label: translate("overview.trendTabFindings") }, + { id: "containers", label: translate("overview.trendTabContainers") }, + { id: "lifecycle", label: translate("overview.trendTabLifecycle") }, + ]; + + return ( + + {/* Header */} +
+
+

{translate("overview.trendTitle")}

+

{translate("overview.trendSubtitle", { days })}

+
+ +
+ {/* Day window switcher */} +
+ {WINDOW_OPTIONS.map((w) => ( + + ))} +
+ + {/* Metric tabs */} +
+ {tabs.map((item) => ( + + ))} +
+
+
+ + {/* Area / Line Trend Chart */} + + + + + + + + + + + Math.max(dataMax, 4)]} + tick={{ fontSize: 11 }} + tickFormatter={formatTick} + /> + { + if (!active || !payload?.length) return null; + const b = payload[0]?.payload as DayBucket | undefined; + if (!b) return null; + + let rows: Array<{ label: string; value: number; color: string }>; + if (tab === "findings") { + rows = [ + { label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#2563eb" }, + { label: translate("overview.trendSeriesHighCrit"), value: b.findingsHighCrit, color: "#f43f5e" }, + { label: translate("overview.trendSeriesMedLow"), value: b.findingsMedLow, color: "#f59e0b" }, + { label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#10b981" }, + ]; + } else if (tab === "containers") { + rows = [ + { + label: translate("overview.trendSeriesContainersCreated"), + value: b.containersCreated, + color: "#2563eb", + }, + { + label: translate("overview.trendSeriesContainersRunning"), + value: b.containersRunning, + color: "#10b981", + }, + { + label: translate("overview.trendSeriesTaskContainers"), + value: b.containersTask, + color: "#6366f1", + }, + { + label: translate("overview.trendSeriesSessionContainers"), + value: b.containersSession, + color: "#0ea5e9", + }, + ]; + } else { + rows = [ + { label: translate("overview.trendSeriesTasksCreated"), value: b.tasksCreated, color: "#2563eb" }, + { label: translate("overview.trendSeriesTasksCompleted"), value: b.tasksCompleted, color: "#10b981" }, + { label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#f59e0b" }, + { label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#14b8a6" }, + ]; + } + + return ( +
+
+ {b.dayKey} +
+
+ {rows.map((r) => ( +
+ + + {r.label} + + {r.value} +
+ ))} +
+
+ ); + }} + /> + + +
+
+ + {/* Footer */} +
+
+ {footerSummary} + {sandboxBadge} + {tab === "lifecycle" && activeRetests.length > 0 && ( + + + {translate("overview.activeRetests", { count: activeRetests.length })} + + )} +
+ + {footerLinkLabel} + + +
+
+ ); +} diff --git a/web/src/app/(main)/dashboard/page.tsx b/web/src/app/(main)/dashboard/page.tsx index 4720b22..0fe7343 100644 --- a/web/src/app/(main)/dashboard/page.tsx +++ b/web/src/app/(main)/dashboard/page.tsx @@ -28,6 +28,7 @@ import { Progress } from "@/components/ui/progress"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api } from "@/lib/api"; import type { + ActiveFindingRetest, Activity, Agent, ConvTokenSummary, @@ -35,6 +36,7 @@ import type { InterceptPending, LLMProfile, MCPServer, + SandboxGlobalStatus, Settings, SkillItem, Stats, @@ -47,6 +49,8 @@ import type { } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { EnvironmentLifecycleRow } from "./_components/environment-lifecycle-row"; + // ── chart constants ─────────────────────────────────────────────────────────── // ── helpers ────────────────────────────────────────────────────────────────── @@ -194,6 +198,8 @@ export default function DashboardPage() { const [tools, setTools] = React.useState([]); const [llmProfiles, setLLMProfiles] = React.useState([]); const [systemMetrics, setSystemMetrics] = React.useState(null); + const [sandboxStatus, setSandboxStatus] = React.useState(null); + const [activeRetests, setActiveRetests] = React.useState([]); React.useEffect(() => { let alive = true; @@ -213,6 +219,49 @@ export default function DashboardPage() { }; }, []); + React.useEffect(() => { + let alive = true; + let loading = false; + const load = async (progressive: boolean) => { + if (loading) return; + loading = true; + try { + const fast = await api.sandboxStatus(!progressive); + if (!alive) return; + setSandboxStatus(fast); + if ( + progressive && + fast.enabled && + Array.isArray(fast.containers) && + fast.containers.some((c) => c.state === "running") + ) { + void api + .sandboxStatus(true) + .then((fresh) => { + if (alive) setSandboxStatus(fresh); + }) + .catch(() => { + /* ignore transient live stats errors */ + }); + } + } catch { + /* retry on the next interval */ + } finally { + loading = false; + } + }; + void load(true); + const timer = setInterval(() => { + if (document.visibilityState === "visible") { + void load(false); + } + }, 10000); + return () => { + alive = false; + clearInterval(timer); + }; + }, []); + // The task list is the most expensive dashboard source. Poll it independently // so a large history cannot hold back every other dashboard panel. React.useEffect(() => { @@ -252,7 +301,7 @@ export default function DashboardPage() { if (loading) return; loading = true; try { - const [findings, stats, settings, pending, activity, tokens, conversationTokens] = await Promise.all([ + const [findings, stats, settings, pending, activity, tokens, conversationTokens, retests] = await Promise.all([ api.findings(), api.stats(), api.settings(), @@ -260,6 +309,7 @@ export default function DashboardPage() { api.activity(undefined, { limit: 30 }), api.tokenStats(), api.conversationTokens(), + api.activeFindingRetests().catch(() => [] as ActiveFindingRetest[]), ]); if (!alive) return; setFindings(findings); @@ -269,6 +319,7 @@ export default function DashboardPage() { setActivity(activity.items); setTokens(tokens.total ?? null); setConvTokens(conversationTokens); + setActiveRetests(retests); } catch { // Preserve stale data and retry on the next interval. } finally { @@ -942,6 +993,14 @@ export default function DashboardPage() {
+ {/* ── Row 3: 漏洞、容器与生命周期趋势 ── */} + + {/* ── Row 3: 活动流 | 发现 ── */}
{/* 活动流 */} diff --git a/web/src/app/(main)/function/findings/page.tsx b/web/src/app/(main)/function/findings/page.tsx index 9c0d06b..b81c9f5 100644 --- a/web/src/app/(main)/function/findings/page.tsx +++ b/web/src/app/(main)/function/findings/page.tsx @@ -1048,8 +1048,8 @@ export default function FindingsPage() { })}
-
- +
+ -
+
{selectedIds.size > 0 && ( - + {ui("screen.7ecf1cde648680")} {selectedIds.size} {ui("screen.f004f1d84cf962")} diff --git a/web/src/app/(main)/function/schedules/_components/month-swimlane-view.tsx b/web/src/app/(main)/function/schedules/_components/month-swimlane-view.tsx new file mode 100644 index 0000000..dfacb81 --- /dev/null +++ b/web/src/app/(main)/function/schedules/_components/month-swimlane-view.tsx @@ -0,0 +1,1249 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import { + ChevronDownIcon, + ChevronRightIcon, + HistoryIcon, + ListChecksIcon, + PauseIcon, + PencilIcon, + PlayIcon, + PlusIcon, + RouteIcon, + ZapIcon, +} from "lucide-react"; + +import { formatProxyRouteSummary } from "@/components/proxy-route-selector"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import { + type CalendarEventOccurrence, + makeDateKey, + parseClockMinutes, + parseDateKey, + weekdayOfDateKey, +} from "@/lib/schedule-calendar"; +import { scheduleDisplay } from "@/lib/schedule-display"; +import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +interface StatusVisual { + dot: string; + accent: string; + bar: string; + barOnce: string; + barSelected: string; + pill: string; +} + +const LANE_STATUS_VISUAL: Record = { + running: { + dot: "bg-emerald-500", + accent: "bg-emerald-500", + bar: "bg-emerald-500/16 border-emerald-500/35 text-emerald-950 dark:bg-emerald-500/22 dark:border-emerald-400/40 dark:text-emerald-100", + barOnce: "bg-emerald-500/90 border-emerald-600 text-white dark:bg-emerald-600 dark:border-emerald-400", + barSelected: "ring-2 ring-emerald-500 ring-offset-1 ring-offset-background", + pill: "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300", + }, + waiting: { + dot: "bg-blue-500", + accent: "bg-blue-500", + bar: "bg-blue-500/12 border-blue-500/30 text-blue-950 dark:bg-blue-500/20 dark:border-blue-400/35 dark:text-blue-100", + barOnce: "bg-indigo-500/90 border-indigo-600 text-white dark:bg-indigo-600 dark:border-indigo-400", + barSelected: "ring-2 ring-blue-500 ring-offset-1 ring-offset-background", + pill: "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-950/50 dark:text-blue-300", + }, + outside: { + dot: "bg-orange-500", + accent: "bg-orange-500", + bar: "bg-orange-500/14 border-orange-500/35 text-orange-950 dark:bg-orange-500/20 dark:border-orange-400/40 dark:text-orange-100", + barOnce: "bg-orange-500/90 border-orange-600 text-white dark:bg-orange-600 dark:border-orange-400", + barSelected: "ring-2 ring-orange-500 ring-offset-1 ring-offset-background", + pill: "border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-800 dark:bg-orange-950/50 dark:text-orange-300", + }, + completed: { + dot: "bg-sky-500", + accent: "bg-sky-500", + bar: "bg-sky-500/14 border-sky-500/30 text-sky-950 dark:bg-sky-500/20 dark:border-sky-400/35 dark:text-sky-100", + barOnce: "bg-sky-600/90 border-sky-700 text-white dark:bg-sky-600 dark:border-sky-400", + barSelected: "ring-2 ring-sky-500 ring-offset-1 ring-offset-background", + pill: "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-950/50 dark:text-sky-300", + }, + paused: { + dot: "bg-slate-400", + accent: "bg-slate-400", + bar: "bg-slate-400/15 border-slate-400/35 text-slate-700 dark:bg-slate-500/20 dark:border-slate-500/40 dark:text-slate-300", + barOnce: "bg-slate-500/80 border-slate-600 text-white", + barSelected: "ring-2 ring-slate-400 ring-offset-1 ring-offset-background", + pill: "border-slate-200 bg-slate-100 text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300", + }, + error: { + dot: "bg-rose-500", + accent: "bg-rose-500", + bar: "bg-rose-500/16 border-rose-500/40 text-rose-950 dark:bg-rose-500/24 dark:border-rose-400/45 dark:text-rose-100", + barOnce: "bg-rose-600/90 border-rose-700 text-white dark:bg-rose-600 dark:border-rose-400", + barSelected: "ring-2 ring-rose-500 ring-offset-1 ring-offset-background", + pill: "border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-950/50 dark:text-rose-300", + }, +}; + +const STATUS_SORT_RANK: Record = { + running: 0, + error: 1, + waiting: 2, + outside: 3, + completed: 4, + paused: 5, +}; + +type MonthLaneSortMode = "time" | "priority"; + +const MONTH_SORT_STORAGE_KEY = "artex.schedules.monthSortMode"; +const LANE_ROW_HEIGHT = 46; +const INACTIVE_HEADER_HEIGHT = 30; +const EXPANDED_CARD_WIDTH = 320; + +interface ExpandedLaneCardState { + scheduleId: number; + anchorLeft: number; + openAbove: boolean; +} + +interface LanePullDragState { + scheduleId: number; + originY: number; + deltaY: number; + wasExpanded: boolean; + anchorLeft: number; + openAbove: boolean; +} + +export interface MonthSlideBinding { + containerRef: React.RefObject; + viewportRef: React.MutableRefObject; + headerTrackRef: React.RefObject; + gridTrackRef: React.RefObject; + onPointerDown: (e: React.PointerEvent) => void; + onClickCapture: (e: React.MouseEvent) => void; +} + +interface SwimlaneSpan { + key: string; + startIdx: number; + spanDays: number; + occurrences: CalendarEventOccurrence[]; + startDateKey: string; + endDateKey: string; + overnight: boolean; + continuesBeforeTrack: boolean; + continuesAfterTrack: boolean; +} + +interface SwimlaneRowData { + schedule: TaskSchedule; + spans: SwimlaneSpan[]; + visibleDayCount: number; + firstVisibleOccurrence: CalendarEventOccurrence | null; +} + +function cadenceKey(schedule: TaskSchedule): string { + if (schedule.schedule_type === "once") return "schedule.month.cadenceOnce"; + const wds = [...new Set(schedule.weekdays)].sort((a, b) => a - b); + if (wds.length === 7) return "schedule.month.cadenceDaily"; + if (wds.length === 5 && wds[0] === 1 && wds[4] === 5) return "schedule.month.cadenceWeekdays"; + if (wds.length === 2 && wds[0] === 6 && wds[1] === 7) return "schedule.month.cadenceWeekends"; + return "schedule.month.cadenceWeekly"; +} + +function formatScheduleWindow(schedule: TaskSchedule): string { + const start = schedule.start_time.slice(0, 5); + if (!schedule.end_time) return `${start} →`; + return `${start}–${schedule.end_time.slice(0, 5)}`; +} + +function scheduleStartMinutes(schedule: TaskSchedule): number { + return parseClockMinutes(schedule.start_time) ?? 0; +} + +function scheduleEndMinutes(schedule: TaskSchedule): number { + const end = parseClockMinutes(schedule.end_time); + if (end === null) return Number.MAX_SAFE_INTEGER; + const start = scheduleStartMinutes(schedule); + return end <= start ? end + 1440 : end; +} + +function buildRowSpans( + schedule: TaskSchedule, + scheduleOccs: CalendarEventOccurrence[], + dayIndexByKey: Map, + trackDateKeys: string[], + visibleStartIdx: number, + visibleEndIdx: number, +): { + spans: SwimlaneSpan[]; + visibleDayCount: number; + firstVisibleOccurrence: CalendarEventOccurrence | null; + activeIndices: number[]; +} { + if (scheduleOccs.length === 0) { + return { spans: [], visibleDayCount: 0, firstVisibleOccurrence: null, activeIndices: [] }; + } + + const isMultiDayOnce = + schedule.schedule_type === "once" && + Boolean(schedule.run_date && schedule.end_date && schedule.end_date > schedule.run_date); + + // Pick primary occurrence per day index along the entire sliding track. + const occByDay = new Map(); + for (const occ of scheduleOccs) { + const idx = dayIndexByKey.get(occ.dateKey); + if (idx === undefined) continue; + // Skip pure overnight continuation spill on day D+1 for non-multiday schedules so Wed-Fri overnight stays Wed-Fri. + if (!isMultiDayOnce && occ.isContinuedFromPrev && idx > 0) continue; + const prev = occByDay.get(idx); + if (!prev || (prev.isContinuedFromPrev && !occ.isContinuedFromPrev)) { + occByDay.set(idx, occ); + } + } + + const sortedIndices = [...occByDay.keys()].sort((a, b) => a - b); + const spans: SwimlaneSpan[] = []; + let visibleDayCount = 0; + let firstVisibleOccurrence: CalendarEventOccurrence | null = null; + + let i = 0; + while (i < sortedIndices.length) { + const startIdx = sortedIndices[i]; + let endIdx = startIdx; + const spanOccs: CalendarEventOccurrence[] = []; + const first = occByDay.get(startIdx); + if (first) spanOccs.push(first); + + // Merge consecutive active days into one clean horizontal timeline bar (e.g., Mon-Fri, Wed-Fri, Sat-Sun, multi-day once). + while (i + 1 < sortedIndices.length && sortedIndices[i + 1] === endIdx + 1) { + i++; + endIdx = sortedIndices[i]; + const next = occByDay.get(endIdx); + if (next) spanOccs.push(next); + } + + if (spanOccs.length > 0) { + for (let d = startIdx; d <= endIdx; d++) { + if (d >= visibleStartIdx && d < visibleEndIdx) { + visibleDayCount++; + if (!firstVisibleOccurrence) { + firstVisibleOccurrence = occByDay.get(d) ?? null; + } + } + } + const lastOcc = spanOccs[spanOccs.length - 1]; + spans.push({ + key: `${schedule.id}:span:${trackDateKeys[startIdx]}:${endIdx - startIdx + 1}`, + startIdx, + spanDays: endIdx - startIdx + 1, + occurrences: spanOccs, + startDateKey: trackDateKeys[startIdx], + endDateKey: trackDateKeys[endIdx], + overnight: !isMultiDayOnce && Boolean(lastOcc.isContinuesToNext && !lastOcc.allDay), + continuesBeforeTrack: Boolean(startIdx === 0 && spanOccs[0].isContinuedFromPrev), + continuesAfterTrack: Boolean(endIdx === trackDateKeys.length - 1 && lastOcc.isContinuesToNext), + }); + } + i++; + } + + return { + spans, + visibleDayCount, + firstVisibleOccurrence: firstVisibleOccurrence ?? spans[0]?.occurrences[0] ?? null, + activeIndices: sortedIndices, + }; +} + +export function MonthSwimlaneView({ + slide, + trackDateKeys, + visibleStartIdx, + visibleCount, + dominantMonth, + monthShortFmt, + todayKey, + anchorDateKey, + schedules, + occurrences, + taskById, + proxyPool, + selectedOccurrenceId, + onSelectOccurrence, + onSelectDay, + onCreateAtSlot, + onEdit, + onAction, +}: { + slide: MonthSlideBinding; + trackDateKeys: string[]; + visibleStartIdx: number; + visibleCount: number; + dominantMonth: { year: number; month: number }; + monthShortFmt: Intl.DateTimeFormat; + todayKey: string; + anchorDateKey: string; + schedules: TaskSchedule[]; + occurrences: CalendarEventOccurrence[]; + taskById: Map; + proxyPool: ProxyPoolEntry[]; + selectedOccurrenceId: string | null; + onSelectOccurrence: (occ: CalendarEventOccurrence) => void; + onSelectDay: (dateKey: string) => void; + onCreateAtSlot: (dateKey: string, startMin: number, endMin: number) => void; + onEdit: (item: TaskSchedule) => void; + onAction: (id: number, type: "pause" | "resume" | "run") => Promise; +}) { + const { t: translate, i18n, isEn } = useLiveTranslation(); + const { statusText, timezoneLabel, windowLabel } = scheduleDisplay(translate, i18n.resolvedLanguage ?? "zh-CN"); + const [sortMode, setSortMode] = React.useState("time"); + const [showInactive, setShowInactive] = React.useState(false); + const [expandedCard, setExpandedCard] = React.useState(null); + const [pullDrag, setPullDrag] = React.useState(null); + const bodyScrollRef = React.useRef(null); + + React.useEffect(() => { + if (!pullDrag) return; + const handleMove = (e: PointerEvent) => { + const dy = e.clientY - pullDrag.originY; + setPullDrag((prev) => (prev ? { ...prev, deltaY: dy } : null)); + }; + const handleUp = (e: PointerEvent) => { + const dy = e.clientY - pullDrag.originY; + const { scheduleId, wasExpanded, anchorLeft, openAbove } = pullDrag; + setPullDrag(null); + if (Math.abs(dy) < 6) { + setExpandedCard((prev) => (prev?.scheduleId === scheduleId ? null : { scheduleId, anchorLeft, openAbove })); + return; + } + if (!wasExpanded && dy >= 24) { + setExpandedCard({ scheduleId, anchorLeft, openAbove }); + } else if (wasExpanded && dy <= -24) { + setExpandedCard(null); + } + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp, { once: true }); + window.addEventListener("pointercancel", handleUp, { once: true }); + return () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + }; + }, [pullDrag]); + + React.useEffect(() => { + if (!expandedCard) return; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "Escape") { + setExpandedCard(null); + } + }; + const onPointerDown = (e: PointerEvent) => { + const target = e.target as HTMLElement | null; + if (target?.closest('[data-month-expand-card="true"], [data-month-expand-handle="true"]')) return; + setExpandedCard(null); + }; + window.addEventListener("keydown", onKeyDown); + window.addEventListener("pointerdown", onPointerDown); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("pointerdown", onPointerDown); + }; + }, [expandedCard]); + React.useEffect(() => { + try { + const saved = window.localStorage.getItem(MONTH_SORT_STORAGE_KEY); + if (saved === "time" || saved === "priority") { + setSortMode(saved); + } + } catch { + // ignore storage errors + } + }, []); + + const changeSortMode = React.useCallback((next: MonthLaneSortMode) => { + setSortMode(next); + try { + window.localStorage.setItem(MONTH_SORT_STORAGE_KEY, next); + } catch { + // ignore storage errors + } + }, []); + const [hoveredInfo, setHoveredInfo] = React.useState<{ + schedule: TaskSchedule; + occ: CalendarEventOccurrence; + span: SwimlaneSpan; + } | null>(null); + + const totalCols = trackDateKeys.length; + const visibleEndIdx = visibleStartIdx + visibleCount; + + const trackDays = React.useMemo( + () => + trackDateKeys.map((dateKey, idx) => { + const p = parseDateKey(dateKey); + const weekday = weekdayOfDateKey(dateKey); + const day = p ? p.day : 1; + const inDominantMonth = p?.year === dominantMonth.year && p?.month === dominantMonth.month; + const shortMonth = day === 1 && p ? monthShortFmt.format(new Date(Date.UTC(p.year, p.month - 1, 15))) : ""; + return { + idx, + day, + dateKey, + weekday, + isWeekend: weekday === 6 || weekday === 7, + isToday: dateKey === todayKey, + isAnchor: dateKey === anchorDateKey, + isMonthStart: day === 1, + inDominantMonth, + shortMonth, + }; + }), + [trackDateKeys, dominantMonth.year, dominantMonth.month, monthShortFmt, todayKey, anchorDateKey], + ); + + const { activeRows, inactiveRows, dayLoads, maxDayLoad, totalVisibleRuns } = React.useMemo(() => { + const dayIndexByKey = new Map(); + for (const d of trackDays) dayIndexByKey.set(d.dateKey, d.idx); + + const occsBySchedule = new Map(); + for (const occ of occurrences) { + if (!dayIndexByKey.has(occ.dateKey)) continue; + const list = occsBySchedule.get(occ.scheduleId); + if (list) list.push(occ); + else occsBySchedule.set(occ.scheduleId, [occ]); + } + + const loads = Array.from({ length: trackDays.length }, () => 0); + const active: SwimlaneRowData[] = []; + const inactive: SwimlaneRowData[] = []; + let runs = 0; + + for (const schedule of schedules) { + const built = buildRowSpans( + schedule, + occsBySchedule.get(schedule.id) ?? [], + dayIndexByKey, + trackDateKeys, + visibleStartIdx, + visibleEndIdx, + ); + for (const idx of built.activeIndices) { + loads[idx]++; + } + const row: SwimlaneRowData = { + schedule, + spans: built.spans, + visibleDayCount: built.visibleDayCount, + firstVisibleOccurrence: built.firstVisibleOccurrence, + }; + if (built.visibleDayCount > 0) { + active.push(row); + runs += built.visibleDayCount; + } else { + inactive.push(row); + } + } + + const compareRows = (a: SwimlaneRowData, b: SwimlaneRowData) => { + if (sortMode === "priority") { + const rankDiff = (STATUS_SORT_RANK[a.schedule.status] ?? 9) - (STATUS_SORT_RANK[b.schedule.status] ?? 9); + if (rankDiff !== 0) return rankDiff; + const typeDiff = (a.schedule.schedule_type === "once" ? 0 : 1) - (b.schedule.schedule_type === "once" ? 0 : 1); + if (typeDiff !== 0) return typeDiff; + } + const startDiff = scheduleStartMinutes(a.schedule) - scheduleStartMinutes(b.schedule); + if (startDiff !== 0) return startDiff; + const endDiff = scheduleEndMinutes(a.schedule) - scheduleEndMinutes(b.schedule); + if (endDiff !== 0) return endDiff; + if (sortMode === "time") { + const rankDiff = (STATUS_SORT_RANK[a.schedule.status] ?? 9) - (STATUS_SORT_RANK[b.schedule.status] ?? 9); + if (rankDiff !== 0) return rankDiff; + } + const nameDiff = a.schedule.name.localeCompare(b.schedule.name); + if (nameDiff !== 0) return nameDiff; + return a.schedule.id - b.schedule.id; + }; + + active.sort(compareRows); + inactive.sort(compareRows); + + const visibleLoads = loads.slice(visibleStartIdx, visibleEndIdx); + return { + activeRows: active, + inactiveRows: inactive, + dayLoads: loads, + maxDayLoad: Math.max(...visibleLoads, 1), + totalVisibleRuns: runs, + }; + }, [trackDays, trackDateKeys, occurrences, schedules, visibleStartIdx, visibleEndIdx, sortMode]); + + const todayIdx = trackDays.findIndex((d) => d.isToday); + const trackWidthPct = (totalCols / Math.max(visibleCount, 1)) * 100; + + const headerTrackStyle = React.useMemo( + () => ({ + width: `${trackWidthPct}%`, + gridTemplateColumns: `repeat(${totalCols}, minmax(0, 1fr))`, + }), + [trackWidthPct, totalCols], + ); + const gridTrackOuterStyle = React.useMemo( + () => ({ + width: `${trackWidthPct}%`, + }), + [trackWidthPct], + ); + const dayGridColsStyle = React.useMemo( + () => ({ + gridTemplateColumns: `repeat(${totalCols}, minmax(0, 1fr))`, + }), + [totalCols], + ); + + const openScheduleDetail = (row: SwimlaneRowData) => { + if (row.firstVisibleOccurrence) { + onSelectOccurrence(row.firstVisibleOccurrence); + return; + } + const fallbackDate = + row.schedule.run_date && row.schedule.run_date.length > 0 + ? row.schedule.run_date + : makeDateKey(dominantMonth.year, dominantMonth.month, 1); + onSelectOccurrence({ + id: `${row.schedule.id}:${fallbackDate}:lane`, + scheduleId: row.schedule.id, + schedule: row.schedule, + dateKey: fallbackDate, + startMin: 0, + endMin: 60, + allDay: !row.schedule.end_time, + displayTimeRange: formatScheduleWindow(row.schedule), + }); + }; + + const startPullDrag = (scheduleId: number, e: React.PointerEvent, source: "label" | "bar" | "card") => { + if (e.button !== 0) return; + e.stopPropagation(); + const wasExpanded = expandedCard?.scheduleId === scheduleId; + let anchorLeft = expandedCard?.scheduleId === scheduleId ? expandedCard.anchorLeft : 8; + let openAbove = expandedCard?.scheduleId === scheduleId ? expandedCard.openAbove : false; + + if (source !== "card") { + const scrollEl = bodyScrollRef.current; + const bodyRect = scrollEl?.getBoundingClientRect(); + const targetRect = (e.currentTarget as HTMLElement).getBoundingClientRect(); + const containerW = bodyRect?.width ?? EXPANDED_CARD_WIDTH + 16; + if (source === "bar" && bodyRect) { + const centerX = targetRect.left + targetRect.width / 2 - bodyRect.left; + anchorLeft = Math.round(centerX - EXPANDED_CARD_WIDTH / 2); + } else { + anchorLeft = 8; + } + anchorLeft = Math.max(8, Math.min(anchorLeft, Math.max(8, containerW - EXPANDED_CARD_WIDTH - 8))); + if (bodyRect) { + const spaceBelow = bodyRect.bottom - targetRect.bottom; + const spaceAbove = targetRect.top - bodyRect.top; + openAbove = spaceBelow < 220 && spaceAbove >= 220; + } else { + openAbove = false; + } + } + + setPullDrag({ + scheduleId, + originY: e.clientY, + deltaY: 0, + wasExpanded, + anchorLeft, + openAbove, + }); + }; + + const activeCard = React.useMemo(() => { + const isPulling = Boolean(pullDrag); + const targetId = pullDrag?.scheduleId ?? expandedCard?.scheduleId ?? null; + if (targetId === null) return null; + + let previewHeight: number | null = null; + if (pullDrag) { + if (!pullDrag.wasExpanded) { + if (pullDrag.deltaY < 14) return null; + previewHeight = Math.max(56, Math.min(260, pullDrag.deltaY + 28)); + } else { + const shrunk = 210 + pullDrag.deltaY; + previewHeight = Math.max(48, Math.min(280, shrunk)); + } + } + + const anchorLeft = pullDrag?.anchorLeft ?? expandedCard?.anchorLeft ?? 8; + const openAbove = pullDrag?.openAbove ?? expandedCard?.openAbove ?? false; + + const activeIdx = activeRows.findIndex((r) => r.schedule.id === targetId); + if (activeIdx >= 0) { + return { + row: activeRows[activeIdx], + rowTopPx: activeIdx * LANE_ROW_HEIGHT, + anchorLeft, + openAbove, + previewHeight, + isPulling, + }; + } + if (showInactive) { + const inactiveIdx = inactiveRows.findIndex((r) => r.schedule.id === targetId); + if (inactiveIdx >= 0) { + return { + row: inactiveRows[inactiveIdx], + rowTopPx: activeRows.length * LANE_ROW_HEIGHT + INACTIVE_HEADER_HEIGHT + inactiveIdx * LANE_ROW_HEIGHT, + anchorLeft, + openAbove, + previewHeight, + isPulling, + }; + } + } + return null; + }, [activeRows, inactiveRows, showInactive, expandedCard, pullDrag]); + + const renderLeftLabel = (row: SwimlaneRowData, muted = false) => { + const { schedule } = row; + const vis = LANE_STATUS_VISUAL[schedule.status] ?? LANE_STATUS_VISUAL.waiting; + const isOnce = schedule.schedule_type === "once"; + const cadenceLabel = translate(cadenceKey(schedule)); + const windowText = formatScheduleWindow(schedule); + const isExpanded = expandedCard?.scheduleId === schedule.id; + + return ( +
+ + + {/* Pull-down handle matching Week/Day cards */} + +
+ ); + }; + + const renderTrackRow = (row: SwimlaneRowData, muted = false) => { + const { schedule } = row; + const vis = LANE_STATUS_VISUAL[schedule.status] ?? LANE_STATUS_VISUAL.waiting; + const isOnce = schedule.schedule_type === "once"; + const windowText = formatScheduleWindow(schedule); + const shortStart = schedule.start_time.slice(0, 5); + const isExpanded = expandedCard?.scheduleId === schedule.id; + + return ( +
+
+
+ {trackDays.map((d) => ( + + ))} +
+ + {/* Continuous merged horizontal bars */} + {row.spans.length > 0 && ( +
+ {row.spans.map((span) => { + const anySelected = span.occurrences.some((o) => o.id === selectedOccurrenceId); + const barLabel = span.spanDays >= 2 ? windowText : shortStart; + + return ( +
+
+ {/* Crisp left accent edge for recurring bars */} + {!isOnce && ( +
+
+ ); + })} +
+ )} +
+
+ ); + }; + + return ( +
+ {/* Sticky top header row: fixed left lane header + continuously sliding day header track */} +
+
+
+ {translate("schedule.month.laneTitle")} + + {activeRows.length}/{schedules.length} + +
+
+ {(["time", "priority"] as const).map((mode) => { + const active = sortMode === mode; + return ( + + ); + })} +
+
+ +
+
+ {trackDays.map((d) => { + const load = dayLoads[d.idx] ?? 0; + const loadRatio = load > 0 ? Math.max(0.2, load / maxDayLoad) : 0; + let loadBarClass = "bg-blue-500/45"; + if (load >= 5) loadBarClass = "bg-amber-500/80"; + else if (load >= 3) loadBarClass = "bg-blue-500/75"; + + return ( +
+ + {d.isMonthStart ? d.shortMonth : translate(`schedule.calendar.weekdayShort.${d.weekday}`)} + + + + {/* Daily load density micro-indicator */} +
0 ? translate("schedule.calendar.dayEventCount", { count: load }) : undefined} + > + {load > 0 && ( + <> + + {load} + +
+
+
+ + )} +
+
+ ); + })} +
+
+
+ + {/* Vertically scrollable swimlane body: fixed left labels + synchronized horizontal sliding track */} + {schedules.length === 0 ? ( +
+ {translate("schedule.month.empty")} +
+ ) : ( +
+
+ {/* Left column: pinned schedule labels */} +
+ {activeRows.map((row) => renderLeftLabel(row, false))} + {inactiveRows.length > 0 && ( + <> + + {showInactive && inactiveRows.map((row) => renderLeftLabel(row, true))} + + )} +
+
+ + {/* Right column: clipped viewport + single GPU sliding track */} +
+
+ {activeRows.map((row) => renderTrackRow(row, false))} + + {inactiveRows.length > 0 && ( + <> +
+ {showInactive && inactiveRows.map((row) => renderTrackRow(row, true))} + + )} + + {/* Remaining vertical background columns */} +
+ {trackDays.map((d) => ( +
+ ))} +
+ + {/* Full-height today vertical guide line */} + {todayIdx >= 0 && ( + +
+ + {/* Compact floating detail card anchored to the pulled lane/bar (matching Week/Day pull-down) */} + {activeCard && + (() => { + const { row, rowTopPx, anchorLeft, openAbove, previewHeight, isPulling } = activeCard; + const { schedule } = row; + const vis = LANE_STATUS_VISUAL[schedule.status] ?? LANE_STATUS_VISUAL.waiting; + const windowText = formatScheduleWindow(schedule); + const linkedTasks = schedule.task_ids.map((id) => ({ id, task: taskById.get(id) })); + const posStyle: React.CSSProperties = { + left: `${anchorLeft}px`, + ...(openAbove && !isPulling + ? { bottom: `calc(100% - ${rowTopPx + 2}px)` } + : { top: `${rowTopPx + LANE_ROW_HEIGHT - 2}px` }), + ...(previewHeight !== null ? { height: `${previewHeight}px` } : {}), + }; + return ( +
+
+ {/* Header: status dot + title + status badge */} +
+
+ + {schedule.name} +
+ + {statusText(schedule)} + +
+ + {/* Time window, rule & timezone */} +
+ {windowText} + · + {windowLabel(schedule)} +
+
{timezoneLabel(schedule)}
+ + {/* Proxy route if configured */} + {schedule.proxy_mode && schedule.proxy_mode !== "inherit" ? ( +
+ + + {formatProxyRouteSummary( + { + mode: schedule.proxy_mode, + proxy_pool_id: schedule.proxy_pool_id, + proxy_url: schedule.proxy_url, + effective_proxy: schedule.effective_proxy, + }, + isEn, + proxyPool, + )} + +
+ ) : null} + + {/* Remark */} + {schedule.remark ? ( +

+ {schedule.remark} +

+ ) : null} + + {/* Linked tasks */} +
+
+ + + {linkedTasks.length > 0 + ? translate("schedule.calendar.boundTasksCount", { count: linkedTasks.length }) + : translate("schedule.calendar.noBoundTasks")} + +
+ {linkedTasks.length > 0 ? ( +
+ {linkedTasks.slice(0, 4).map(({ id, task }) => ( + + + #{id} {task?.name?.trim() || task?.description || ""} + + {task?.status ? ( + {task.status} + ) : null} + + ))} +
+ ) : null} +
+
+ + {/* Compact inline action bar */} +
+ + + + +
+ + {/* Bottom pull-up / click-to-collapse handle */} + +
+ ); + })()} +
+
+ )} + + {/* Bottom status / hover preview bar */} +
+ {hoveredInfo ? ( +
+ + {hoveredInfo.schedule.name} + + {hoveredInfo.span.spanDays > 1 && hoveredInfo.schedule.schedule_type === "once" + ? `${hoveredInfo.span.startDateKey} → ${hoveredInfo.span.endDateKey}` + : hoveredInfo.occ.dateKey} + + {hoveredInfo.occ.displayTimeRange} + {hoveredInfo.span.overnight && ( + + {translate("schedule.month.overnight")} + + )} +
+ ) : ( +
+ {(["running", "waiting", "outside", "completed", "paused", "error"] as const).map((st) => ( + + + {translate(`schedule.status.${st}`)} + + ))} + + · {translate("schedule.calendar.swipeHint")} + +
+ )} + + {translate("schedule.month.footerSummary", { active: activeRows.length, runs: totalVisibleRuns })} + +
+
+ ); +} diff --git a/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx b/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx new file mode 100644 index 0000000..0ac811e --- /dev/null +++ b/web/src/app/(main)/function/schedules/_components/schedule-calendar-workspace.tsx @@ -0,0 +1,3021 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import type { TFunction } from "i18next"; +import { + CalendarIcon, + ChevronDown, + ChevronLeft, + ChevronRight, + ChevronUp, + ClockIcon, + CopyIcon, + HistoryIcon, + ListChecksIcon, + PanelLeftClose, + PanelLeftOpen, + Pause, + PencilIcon, + Play, + Plus, + RouteIcon, + Search, + Trash2, + XIcon, + Zap, +} from "lucide-react"; + +import { formatProxyRouteSummary } from "@/components/proxy-route-selector"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import type { ScheduleInput } from "@/lib/api"; +import { + addDaysToDateKey, + buildMonthGridDateKeys, + buildRollingDateKeys, + buildScheduleInputFromDrag, + type CalendarClockMode, + type CalendarEventOccurrence, + type CalendarViewMode, + expandSchedulesForDateKeys, + formatGMTOffset, + formatMinutesAsClock, + layoutDayTimedEvents, + makeDateKey, + parseClockMinutes, + parseDateKey, + resolveDisplayOffsetMinutes, + startOfWeekDateKey, + toZonedParts, +} from "@/lib/schedule-calendar"; +import { scheduleDisplay } from "@/lib/schedule-display"; +import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types"; +import { cn } from "@/lib/utils"; +import { MonthSwimlaneView } from "./month-swimlane-view"; + +const HOUR_HEIGHT = 52; // px per hour slot in scrollable Day/Week time grid +const ALL_STATUSES: TaskSchedule["status"][] = ["running", "waiting", "outside", "paused", "completed", "error"]; + +const STATUS_STYLE: Record< + TaskSchedule["status"], + { + card: string; + cardSelected: string; + dot: string; + pill: string; + } +> = { + running: { + card: "border-emerald-300/90 bg-emerald-50/90 text-emerald-950 hover:bg-emerald-100/90 dark:border-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-100 dark:hover:bg-emerald-900/60", + cardSelected: "ring-2 ring-emerald-500/70 bg-emerald-100 dark:bg-emerald-900/80", + dot: "bg-emerald-500", + pill: "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300", + }, + waiting: { + card: "border-blue-300/90 bg-blue-50/90 text-blue-950 hover:bg-blue-100/90 dark:border-blue-800 dark:bg-blue-950/60 dark:text-blue-100 dark:hover:bg-blue-900/60", + cardSelected: "ring-2 ring-blue-500/70 bg-blue-100 dark:bg-blue-900/80", + dot: "bg-blue-500", + pill: "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-950/50 dark:text-blue-300", + }, + outside: { + card: "border-orange-300/90 bg-orange-50/90 text-orange-950 hover:bg-orange-100/90 dark:border-orange-800 dark:bg-orange-950/60 dark:text-orange-100 dark:hover:bg-orange-900/60", + cardSelected: "ring-2 ring-orange-500/70 bg-orange-100 dark:bg-orange-900/80", + dot: "bg-orange-500", + pill: "border-orange-200 bg-orange-50 text-orange-700 dark:border-orange-800 dark:bg-orange-950/50 dark:text-orange-300", + }, + completed: { + card: "border-sky-300/90 bg-sky-50/90 text-sky-950 hover:bg-sky-100/90 dark:border-sky-800 dark:bg-sky-950/60 dark:text-sky-100 dark:hover:bg-sky-900/60", + cardSelected: "ring-2 ring-sky-500/70 bg-sky-100 dark:bg-sky-900/80", + dot: "bg-sky-500", + pill: "border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-950/50 dark:text-sky-300", + }, + paused: { + card: "border-slate-300/90 bg-slate-100/90 text-slate-800 hover:bg-slate-200/80 dark:border-slate-700 dark:bg-slate-800/70 dark:text-slate-200 dark:hover:bg-slate-800", + cardSelected: "ring-2 ring-slate-400/70 bg-slate-200/90 dark:bg-slate-700/80", + dot: "bg-slate-400", + pill: "border-slate-200 bg-slate-100 text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300", + }, + error: { + card: "border-rose-300/90 bg-rose-50/90 text-rose-950 hover:bg-rose-100/90 dark:border-rose-800 dark:bg-rose-950/60 dark:text-rose-100 dark:hover:bg-rose-900/60", + cardSelected: "ring-2 ring-rose-500/70 bg-rose-100 dark:bg-rose-900/80", + dot: "bg-rose-500", + pill: "border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-950/50 dark:text-rose-300", + }, +}; + +type DragState = { + occurrence: CalendarEventOccurrence; + originClientX: number; + originClientY: number; + originDayIndex: number; + previewDateKey: string; + previewStartMin: number; + previewEndMin: number; + moved: boolean; +}; + +type ExpandDragState = { + occId: string; + originY: number; + deltaY: number; + wasExpanded: boolean; +}; + +const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect; + + +function addYearMonth(year: number, month: number, deltaMonths: number): { year: number; month: number } { + const d = new Date(Date.UTC(year, month - 1 + deltaMonths, 1)); + return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1 }; +} + +// Unified continuous track slider (horizontal or vertical) for Day, Week, Month, Year, and Mini Calendar: +// keeps fixed chrome (time axis / weekday headers / sidebar) pinned while individual day columns, +// week rows, or quarter columns glide smoothly 1:1 into view and snap onto exact unit boundaries. +function useContinuousTrackSlider({ + enabled, + axis = "x", + crossAxisWheel = false, + attachKey, + visibleUnits, + bufferUnits, + trackKey, + onShiftUnits, + shouldIgnorePointerDown, + shouldIgnoreWheel, +}: { + enabled: boolean; + axis?: "x" | "y"; + crossAxisWheel?: boolean; + attachKey: string; + visibleUnits: number; + bufferUnits: number; + trackKey: string; + onShiftUnits: (deltaUnits: number) => void; + shouldIgnorePointerDown?: (target: HTMLElement | null) => boolean; + shouldIgnoreWheel?: (target: HTMLElement | null) => boolean; +}) { + const containerRef = React.useRef(null); + const viewportRef = React.useRef(null); + const headerTrackRef = React.useRef(null); + const allDayTrackRef = React.useRef(null); + const gridTrackRef = React.useRef(null); + + const totalUnits = visibleUnits + bufferUnits * 2; + const basePct = (bufferUnits / totalUnits) * 100; + + const enabledRef = React.useRef(enabled); + enabledRef.current = enabled; + const axisRef = React.useRef(axis); + axisRef.current = axis; + const crossAxisRef = React.useRef(crossAxisWheel); + crossAxisRef.current = crossAxisWheel; + const visibleUnitsRef = React.useRef(visibleUnits); + visibleUnitsRef.current = visibleUnits; + const bufferUnitsRef = React.useRef(bufferUnits); + bufferUnitsRef.current = bufferUnits; + const basePctRef = React.useRef(basePct); + basePctRef.current = basePct; + const onShiftUnitsRef = React.useRef(onShiftUnits); + onShiftUnitsRef.current = onShiftUnits; + const ignorePointerRef = React.useRef(shouldIgnorePointerDown); + ignorePointerRef.current = shouldIgnorePointerDown; + const ignoreWheelRef = React.useRef(shouldIgnoreWheel); + ignoreWheelRef.current = shouldIgnoreWheel; + + const offsetPxRef = React.useRef(0); + const pendingWrapPxRef = React.useRef(0); + const drawRafRef = React.useRef(null); + const snapRafRef = React.useRef(null); + const snapPendingCommitRef = React.useRef<(() => void) | null>(null); + const suppressClickUntilRef = React.useRef(0); + + const getUnitSize = React.useCallback(() => { + if (axisRef.current === "y") { + const h = viewportRef.current?.clientHeight || containerRef.current?.clientHeight || 0; + if (h > 0) return h / visibleUnitsRef.current; + return 100; + } + const w = viewportRef.current?.clientWidth || containerRef.current?.clientWidth || 0; + if (w > 0) return w / visibleUnitsRef.current; + return visibleUnitsRef.current === 1 ? 420 : 140; + }, []); + + const getSnapThreshold = React.useCallback( + (unitSize: number, wrappedInGesture: boolean) => { + if (visibleUnitsRef.current === 1) { + return wrappedInGesture ? Math.min(unitSize * 0.35, 160) : Math.min(unitSize * 0.18, 120); + } + return wrappedInGesture ? Math.min(unitSize * 0.38, 140) : Math.min(unitSize * 0.22, 88); + }, + [], + ); + + const applyOffsetNow = React.useCallback((px: number) => { + offsetPxRef.current = px; + const unitSize = getUnitSize(); + const maxDomPx = Math.max(unitSize * 0.5, (bufferUnitsRef.current - 0.05) * unitSize); + const visualPx = Math.max(-maxDomPx, Math.min(maxDomPx, px)); + const pct = basePctRef.current; + const transform = + axisRef.current === "y" + ? Math.abs(visualPx) < 0.05 + ? `translate3d(0, -${pct}%, 0)` + : `translate3d(0, calc(-${pct}% + ${visualPx.toFixed(2)}px), 0)` + : Math.abs(visualPx) < 0.05 + ? `translate3d(-${pct}%, 0, 0)` + : `translate3d(calc(-${pct}% + ${visualPx.toFixed(2)}px), 0, 0)`; + if (headerTrackRef.current) headerTrackRef.current.style.transform = transform; + if (allDayTrackRef.current) allDayTrackRef.current.style.transform = transform; + if (gridTrackRef.current) gridTrackRef.current.style.transform = transform; + }, [getUnitSize]); + + const scheduleDraw = React.useCallback(() => { + if (drawRafRef.current !== null) return; + drawRafRef.current = window.requestAnimationFrame(() => { + drawRafRef.current = null; + applyOffsetNow(offsetPxRef.current); + }); + }, [applyOffsetNow]); + + const cancelAnimations = React.useCallback((commitInFlight = false) => { + if (drawRafRef.current !== null) { + window.cancelAnimationFrame(drawRafRef.current); + drawRafRef.current = null; + } + if (snapRafRef.current !== null) { + window.cancelAnimationFrame(snapRafRef.current); + snapRafRef.current = null; + } + const pendingCommit = snapPendingCommitRef.current; + snapPendingCommitRef.current = null; + if (commitInFlight && pendingCommit) { + pendingCommit(); + } + }, []); + + const clampStepOffset = React.useCallback((rawLogical: number, unitSize: number) => { + const maxTravel = Math.max(unitSize, (bufferUnitsRef.current - 0.5) * unitSize); + const maxDomPx = Math.max(unitSize * 0.5, (bufferUnitsRef.current - 0.08) * unitSize); + const clampedLogical = Math.max(-maxTravel, Math.min(maxTravel, rawLogical)); + const rawDom = clampedLogical - pendingWrapPxRef.current; + return Math.max(-maxDomPx, Math.min(maxDomPx, rawDom)); + }, []); + + const maybeWrapLive = React.useCallback((): number => { + const unitSize = getUnitSize(); + const logical = offsetPxRef.current + pendingWrapPxRef.current; + if (Math.abs(logical) < unitSize) return 0; + const maxBuf = Math.max(1, bufferUnitsRef.current - 1); + const rawSteps = logical > 0 ? -Math.floor(logical / unitSize) : Math.floor(-logical / unitSize); + const steps = Math.max(-maxBuf, Math.min(maxBuf, rawSteps)); + if (steps === 0) return 0; + pendingWrapPxRef.current += steps * unitSize; + onShiftUnitsRef.current(steps); + return steps; + }, [getUnitSize]); + + const animateToDomOffset = React.useCallback( + (targetDomPx: number, durationMs: number, onDone?: () => void) => { + cancelAnimations(false); + const startPx = offsetPxRef.current; + const delta = targetDomPx - startPx; + if (Math.abs(delta) < 0.5 || durationMs <= 0) { + applyOffsetNow(targetDomPx); + onDone?.(); + return; + } + const startTime = performance.now(); + const finish = () => { + snapRafRef.current = null; + snapPendingCommitRef.current = null; + applyOffsetNow(targetDomPx); + onDone?.(); + }; + snapPendingCommitRef.current = () => { + applyOffsetNow(targetDomPx); + onDone?.(); + }; + const tick = (now: number) => { + const t = Math.min(1, (now - startTime) / durationMs); + const eased = 1 - (1 - t) * (1 - t) * (1 - t); + applyOffsetNow(startPx + delta * eased); + if (t < 1) { + snapRafRef.current = window.requestAnimationFrame(tick); + } else { + finish(); + } + }; + snapRafRef.current = window.requestAnimationFrame(tick); + }, + [applyOffsetNow, cancelAnimations], + ); + + const snapToNearestUnit = React.useCallback( + (wrappedInGesture: boolean, quickFlickDir: -1 | 0 | 1 = 0) => { + const unitSize = getUnitSize(); + const logical = offsetPxRef.current + pendingWrapPxRef.current; + const threshold = getSnapThreshold(unitSize, wrappedInGesture); + + let stepUnits = 0; + if (quickFlickDir !== 0 && !wrappedInGesture) { + stepUnits = quickFlickDir; + } else if (Math.abs(logical) >= threshold) { + stepUnits = + logical > 0 + ? -Math.max(1, Math.round(logical / unitSize)) + : Math.max(1, Math.round(-logical / unitSize)); + } + const maxStep = Math.max(1, bufferUnitsRef.current); + stepUnits = Math.max(-maxStep, Math.min(maxStep, stepUnits)); + + const targetLogical = -stepUnits * unitSize; + const targetDom = targetLogical - pendingWrapPxRef.current; + const distRatio = Math.min(1, Math.abs(targetDom - offsetPxRef.current) / Math.max(1, unitSize)); + const duration = stepUnits === 0 ? 150 : Math.round(170 + distRatio * 70); + + animateToDomOffset(targetDom, duration, () => { + if (stepUnits !== 0) { + pendingWrapPxRef.current += stepUnits * unitSize; + onShiftUnitsRef.current(stepUnits); + } else if (pendingWrapPxRef.current === 0) { + applyOffsetNow(0); + } + }); + }, + [animateToDomOffset, applyOffsetNow, getUnitSize, getSnapThreshold], + ); + + const slideByUnits = React.useCallback( + (deltaUnits: number) => { + if (deltaUnits === 0) return; + cancelAnimations(true); + const unitSize = getUnitSize(); + const maxBuf = bufferUnitsRef.current; + if (Math.abs(deltaUnits) > maxBuf) { + pendingWrapPxRef.current = 0; + applyOffsetNow(0); + onShiftUnitsRef.current(deltaUnits); + return; + } + const targetDom = -deltaUnits * unitSize - pendingWrapPxRef.current; + const duration = Math.abs(deltaUnits) > 1 ? 250 : 200; + animateToDomOffset(targetDom, duration, () => { + pendingWrapPxRef.current += deltaUnits * unitSize; + onShiftUnitsRef.current(deltaUnits); + }); + }, + [animateToDomOffset, applyOffsetNow, cancelAnimations, getUnitSize], + ); + + // Synchronously reconcile pixel offset when React commits shifted units (zero visual jump). + useIsomorphicLayoutEffect(() => { + if (!attachKey) return; + if (pendingWrapPxRef.current !== 0) { + const nextPx = offsetPxRef.current + pendingWrapPxRef.current; + pendingWrapPxRef.current = 0; + applyOffsetNow(nextPx); + } else { + applyOffsetNow(offsetPxRef.current); + } + }, [attachKey, trackKey, applyOffsetNow]); + + // Reset offset cleanly when switching layouts or mounting, and clear inline transforms on cleanup. + useIsomorphicLayoutEffect(() => { + if (!attachKey) return; + const h = headerTrackRef.current; + const a = allDayTrackRef.current; + const g = gridTrackRef.current; + cancelAnimations(false); + pendingWrapPxRef.current = 0; + applyOffsetNow(0); + return () => { + if (h) h.style.transform = ""; + if (a) a.style.transform = ""; + if (g) g.style.transform = ""; + }; + }, [attachKey, axis, visibleUnits, bufferUnits, applyOffsetNow, cancelAnimations]); + + React.useEffect(() => () => cancelAnimations(false), [cancelAnimations]); + + // Non-passive wheel listener: 1:1 continuous unit gliding on trackpad / wheel. + React.useEffect(() => { + if (!attachKey) return; + const el = containerRef.current; + if (!el) return; + + let wrappedInGesture = false; + let idleTimer: number | null = null; + + const onWheel = (e: WheelEvent) => { + if (!enabledRef.current) return; + if (ignoreWheelRef.current?.(e.target as HTMLElement | null)) return; + const absX = Math.abs(e.deltaX); + const absY = Math.abs(e.deltaY); + let delta = 0; + if (axisRef.current === "y") { + if (absY >= absX && absY > 0.5) { + delta = e.deltaY; + } else if (crossAxisRef.current && absX > absY * 1.15 && absX > 0.5) { + delta = e.deltaX; + } else { + return; + } + } else { + if (absX > absY * 1.15 && absX > 0.5) { + delta = e.deltaX; + } else if (e.shiftKey && absY > 0.5) { + delta = e.deltaY; + } else { + return; + } + } + + if (e.deltaMode === 1) delta *= 24; + else if (e.deltaMode === 2) delta *= 120; + + e.preventDefault(); + cancelAnimations(false); + + const unitSize = getUnitSize(); + const rawLogical = offsetPxRef.current + pendingWrapPxRef.current - delta * 0.9; + offsetPxRef.current = clampStepOffset(rawLogical, unitSize); + + if (maybeWrapLive() !== 0) { + wrappedInGesture = true; + } + scheduleDraw(); + + const snapThreshold = getSnapThreshold(unitSize, wrappedInGesture); + const currentLogical = offsetPxRef.current + pendingWrapPxRef.current; + const isInertiaDust = Math.abs(delta) < 2 && Math.abs(currentLogical) >= snapThreshold; + if (!isInertiaDust || idleTimer === null) { + if (idleTimer !== null) window.clearTimeout(idleTimer); + idleTimer = window.setTimeout(() => { + idleTimer = null; + const didWrap = wrappedInGesture; + wrappedInGesture = false; + snapToNearestUnit(didWrap, 0); + }, 90); + } + }; + + el.addEventListener("wheel", onWheel, { passive: false }); + return () => { + el.removeEventListener("wheel", onWheel); + if (idleTimer !== null) window.clearTimeout(idleTimer); + }; + }, [attachKey, cancelAnimations, clampStepOffset, getUnitSize, getSnapThreshold, maybeWrapLive, scheduleDraw, snapToNearestUnit]); + + // Unified pointer (mouse + touch + pen) 1:1 continuous unit drag. + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (!enabledRef.current) return; + if (e.pointerType === "mouse" && e.button !== 0) return; + const target = e.target as HTMLElement | null; + if (ignorePointerRef.current?.(target)) return; + + const pointerId = e.pointerId; + const startX = e.clientX; + const startY = e.clientY; + const startTime = Date.now(); + let lockMode: "pending" | "active-x" | "active-y" | "ignored" = "pending"; + let prevClientX = startX; + let prevClientY = startY; + let totalDelta = 0; + let wrappedInGesture = false; + + const cleanup = () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleCancel); + }; + + const handleMove = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + const dx = ev.clientX - startX; + const dy = ev.clientY - startY; + + if (lockMode === "pending") { + if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return; + if (axisRef.current === "y") { + if (Math.abs(dy) >= Math.abs(dx)) { + lockMode = "active-y"; + } else if (crossAxisRef.current) { + lockMode = "active-x"; + } else { + lockMode = "ignored"; + cleanup(); + return; + } + } else { + if (Math.abs(dx) > Math.abs(dy) * 1.15) { + lockMode = "active-x"; + } else { + lockMode = "ignored"; + cleanup(); + return; + } + } + cancelAnimations(false); + prevClientX = ev.clientX; + prevClientY = ev.clientY; + } + + if (lockMode === "active-x" || lockMode === "active-y") { + const stepPx = lockMode === "active-y" ? ev.clientY - prevClientY : ev.clientX - prevClientX; + prevClientX = ev.clientX; + prevClientY = ev.clientY; + totalDelta = lockMode === "active-y" ? dy : dx; + const unitSize = getUnitSize(); + const rawLogical = offsetPxRef.current + pendingWrapPxRef.current + stepPx; + offsetPxRef.current = clampStepOffset(rawLogical, unitSize); + if (maybeWrapLive() !== 0) { + wrappedInGesture = true; + } + scheduleDraw(); + } + }; + + const handleUp = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + cleanup(); + if (lockMode !== "active-x" && lockMode !== "active-y") return; + suppressClickUntilRef.current = Date.now() + 260; + const elapsed = Date.now() - startTime; + const quickFlickDir: -1 | 0 | 1 = + !wrappedInGesture && Math.abs(totalDelta) >= 22 && elapsed < 220 ? (totalDelta < 0 ? 1 : -1) : 0; + snapToNearestUnit(wrappedInGesture, quickFlickDir); + }; + + const handleCancel = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + cleanup(); + if (lockMode === "active-x" || lockMode === "active-y") snapToNearestUnit(wrappedInGesture, 0); + }; + + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleCancel); + }, + [cancelAnimations, clampStepOffset, getUnitSize, maybeWrapLive, scheduleDraw, snapToNearestUnit], + ); + + const onClickCapture = React.useCallback((e: React.MouseEvent) => { + if (Date.now() < suppressClickUntilRef.current) { + e.preventDefault(); + e.stopPropagation(); + } + }, []); + + return { + containerRef, + viewportRef, + headerTrackRef, + allDayTrackRef, + gridTrackRef, + slideByUnits, + onPointerDown, + onClickCapture, + }; +} +function formatDurationBadge(minutes: number, translate: TFunction): string { + const safe = Math.max(0, Math.round(minutes)); + const h = Math.floor(safe / 60); + const m = safe % 60; + if (h > 0 && m > 0) return translate("schedule.calendar.durationHoursMinutes", { hours: h, minutes: m }); + if (h > 0) return translate("schedule.calendar.durationHours", { hours: h }); + return translate("schedule.calendar.durationMinutes", { minutes: m }); +} + +function formatHourGutter(hour: number, isEn: boolean): string { + if (!isEn) return `${String(hour).padStart(2, "0")}:00`; + if (hour === 0) return "12 am"; + if (hour < 12) return `${hour} am`; + if (hour === 12) return "12 pm"; + return `${hour - 12} pm`; +} + +export function ScheduleCalendarWorkspace({ + schedules, + tasks, + proxyPool, + serverTimeISO, + serverUtcOffsetMinutes, + query, + onQueryChange, + onCreateNew, + onCreateAtSlot, + onEdit, + onDuplicate, + onAction, + onDelete, + onQuickUpdateSchedule, + onLoadTimeline, + renderTimeline, + listViewContent, +}: { + schedules: TaskSchedule[]; + tasks: Task[]; + proxyPool: ProxyPoolEntry[]; + serverTimeISO?: string; + serverUtcOffsetMinutes?: number; + query: string; + onQueryChange: (q: string) => void; + onCreateNew: () => void; + onCreateAtSlot: (dateKey: string, startMin: number, endMin: number) => void; + onEdit: (item: TaskSchedule) => void; + onDuplicate: (item: TaskSchedule) => void; + onAction: (id: number, type: "pause" | "resume" | "run") => Promise; + onDelete: (id: number) => Promise; + onQuickUpdateSchedule: (id: number, input: ScheduleInput) => Promise; + onLoadTimeline: (id: number) => Promise; + renderTimeline: (id: number) => React.ReactNode; + listViewContent: React.ReactNode; +}) { + const { t: translate, i18n, isEn } = useLiveTranslation(); + const locale = i18n.resolvedLanguage ?? "zh-CN"; + const { statusText, timezoneLabel, windowLabel, formatDateValue } = scheduleDisplay(translate, locale); + + // Calibrate server clock offset (ms) when server_time arrives. + const [clockOffsetMs, setClockOffsetMs] = React.useState(0); + const [tickNowMs, setTickNowMs] = React.useState(() => Date.now()); + React.useEffect(() => { + if (!serverTimeISO) return; + const parsed = Date.parse(serverTimeISO); + if (!Number.isNaN(parsed)) { + setClockOffsetMs(parsed - Date.now()); + setTickNowMs(Date.now()); + } + }, [serverTimeISO]); + React.useEffect(() => { + const timer = setInterval(() => setTickNowMs(Date.now()), 30_000); + return () => clearInterval(timer); + }, []); + + const serverOffset = serverUtcOffsetMinutes ?? -new Date().getTimezoneOffset(); + const [clockMode, setClockMode] = React.useState("server"); + const displayOffset = resolveDisplayOffsetMinutes(clockMode, serverOffset); + const calibratedNowMs = tickNowMs + clockOffsetMs; + const nowParts = toZonedParts(calibratedNowMs, displayOffset); + const todayKey = nowParts.dateKey; + const nowMinutes = nowParts.hour * 60 + nowParts.minute; + + const [viewMode, setViewMode] = React.useState("week"); + const [anchorDateKey, setAnchorDateKey] = React.useState(todayKey); + const [weekStartDateKey, setWeekStartDateKey] = React.useState(() => startOfWeekDateKey(todayKey)); + const [monthStartDateKey, setMonthStartDateKey] = React.useState(() => { + const p = parseDateKey(todayKey); + return p ? makeDateKey(p.year, p.month, 1) : todayKey; + }); + const [yearStartQuarter, setYearStartQuarter] = React.useState<{ year: number; month: number }>(() => { + const p = parseDateKey(todayKey); + return { year: p?.year ?? nowParts.year, month: 1 }; + }); + const [yearVisibleCols, setYearVisibleCols] = React.useState(4); + const jumpToDateKey = React.useCallback((dk: string) => { + setAnchorDateKey(dk); + setWeekStartDateKey(startOfWeekDateKey(dk)); + const p = parseDateKey(dk); + if (p) { + setYearStartQuarter({ year: p.year, month: 1 }); + setMonthStartDateKey(makeDateKey(p.year, p.month, 1)); + } + }, []); + const initializedAnchor = React.useRef(false); + React.useEffect(() => { + if (!initializedAnchor.current && serverTimeISO) { + initializedAnchor.current = true; + jumpToDateKey(todayKey); + } + }, [serverTimeISO, todayKey, jumpToDateKey]); + + const anchorParts = parseDateKey(anchorDateKey) ?? { + year: nowParts.year, + month: nowParts.month, + day: nowParts.day, + }; + const [miniMonth, setMiniMonth] = React.useState<{ year: number; month: number }>({ + year: anchorParts.year, + month: anchorParts.month, + }); + const [miniPickerMode, setMiniPickerMode] = React.useState<"days" | "months" | "years">("days"); + const [quickJumpYear, setQuickJumpYear] = React.useState(anchorParts.year); + const [quickJumpOpen, setQuickJumpOpen] = React.useState(false); + React.useEffect(() => { + setMiniMonth({ year: anchorParts.year, month: anchorParts.month }); + setQuickJumpYear(anchorParts.year); + }, [anchorParts.year, anchorParts.month]); + const [enabledStatuses, setEnabledStatuses] = React.useState>({ + running: true, + waiting: true, + outside: true, + paused: true, + completed: true, + error: true, + }); + const [selectedOccurrence, setSelectedOccurrence] = React.useState(null); + const [popoverTimelineOpen, setPopoverTimelineOpen] = React.useState(false); + const [dragState, setDragState] = React.useState(null); + const [expandedOccId, setExpandedOccId] = React.useState(null); + const [expandDrag, setExpandDrag] = React.useState(null); + const [yearDayPopover, setYearDayPopover] = React.useState<{ + dateKey: string; + left: number; + top: number; + } | null>(null); + const [sidebarOpen, setSidebarOpen] = React.useState(true); + React.useEffect(() => { + try { + const saved = window.localStorage.getItem("artex.schedule.calendar.sidebar-open"); + if (saved === "false") setSidebarOpen(false); + } catch { + // ignore storage errors + } + }, []); + const toggleSidebar = React.useCallback(() => { + setSidebarOpen((prev) => { + const next = !prev; + try { + window.localStorage.setItem("artex.schedule.calendar.sidebar-open", next ? "true" : "false"); + } catch { + // ignore storage errors + } + return next; + }); + }, []); + const gridBodyRef = React.useRef(null); + const dayColumnsRef = React.useRef(null); + + const scrollToCurrentHour = React.useCallback( + (smooth = false) => { + const el = gridBodyRef.current; + if (!el) return; + const targetHour = Math.max(0, Math.min(18, nowParts.hour >= 6 ? nowParts.hour - 2 : 7)); + el.scrollTo({ top: targetHour * HOUR_HEIGHT, behavior: smooth ? "smooth" : "auto" }); + }, + [nowParts.hour], + ); + + // Scroll the week/day time grid near current server hour when switching into Day/Week view. + React.useEffect(() => { + if (viewMode !== "week" && viewMode !== "day") return; + scrollToCurrentHour(false); + }, [viewMode]); // intentionally run on view switch + const taskById = React.useMemo(() => { + const map = new Map(); + for (const t of tasks) { + map.set(Number(t.id), t); + } + return map; + }, [tasks]); + + // Filter schedules by search query + status checkboxes. + const searchMatchedSchedules = React.useMemo(() => { + const q = query.trim().toLowerCase(); + if (!q) return schedules; + return schedules.filter((item) => + [item.name, item.remark ?? "", String(item.id), ...item.task_ids.map(String)] + .join(" ") + .toLowerCase() + .includes(q), + ); + }, [schedules, query]); + + const statusCounts = React.useMemo(() => { + const counts: Record = { + running: 0, + waiting: 0, + outside: 0, + paused: 0, + completed: 0, + error: 0, + }; + for (const s of searchMatchedSchedules) { + if (s.status in counts) counts[s.status] += 1; + } + return counts; + }, [searchMatchedSchedules]); + + const visibleSchedules = React.useMemo( + () => searchMatchedSchedules.filter((s) => enabledStatuses[s.status] !== false), + [searchMatchedSchedules, enabledStatuses], + ); + + const monthVisibleCols = 31; + const monthBufferCols = 31; + const monthDominantParts = React.useMemo(() => { + const midKey = addDaysToDateKey(monthStartDateKey, Math.floor(monthVisibleCols / 2)); + return parseDateKey(midKey) ?? anchorParts; + }, [monthStartDateKey, anchorParts]); + + // Visible date keys for current view (Week uses rolling 7-day window; Month uses rolling 31-day swimlane window). + const visibleDateKeys = React.useMemo(() => { + if (viewMode === "day") return [anchorDateKey]; + if (viewMode === "week") return buildRollingDateKeys(weekStartDateKey, 7); + if (viewMode === "month") return buildRollingDateKeys(monthStartDateKey, monthVisibleCols); + return []; + }, [viewMode, anchorDateKey, weekStartDateKey, monthStartDateKey]); + + const timeGridVisibleCols = viewMode === "day" ? 1 : 7; + const timeGridBufferCols = viewMode === "day" ? 3 : 7; + const timeGridDateKeys = React.useMemo(() => { + if (viewMode !== "day" && viewMode !== "week") return []; + const start = viewMode === "week" ? weekStartDateKey : anchorDateKey; + return buildRollingDateKeys( + addDaysToDateKey(start, -timeGridBufferCols), + timeGridVisibleCols + timeGridBufferCols * 2, + ); + }, [viewMode, weekStartDateKey, anchorDateKey, timeGridBufferCols, timeGridVisibleCols]); + + const dateFormatters = React.useMemo( + () => ({ + yearFmt: new Intl.DateTimeFormat(locale, { year: "numeric", timeZone: "UTC" }), + monthLongFmt: new Intl.DateTimeFormat(locale, { month: "long", timeZone: "UTC" }), + monthShortFmt: new Intl.DateTimeFormat(locale, { month: "short", timeZone: "UTC" }), + monthYearLongFmt: new Intl.DateTimeFormat(locale, { year: "numeric", month: "long", timeZone: "UTC" }), + monthYearShortFmt: new Intl.DateTimeFormat(locale, { year: "numeric", month: "short", timeZone: "UTC" }), + weekdayShortFmt: new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" }), + dayLongFmt: new Intl.DateTimeFormat(locale, { + year: "numeric", + month: "short", + day: "numeric", + weekday: "short", + timeZone: "UTC", + }), + }), + [locale], + ); + + const monthTrackDateKeys = React.useMemo(() => { + if (viewMode !== "month") return []; + return buildRollingDateKeys( + addDaysToDateKey(monthStartDateKey, -monthBufferCols), + monthVisibleCols + monthBufferCols * 2, + ); + }, [viewMode, monthStartDateKey]); + + const occurrenceDateKeys = React.useMemo(() => { + if (viewMode === "day" || viewMode === "week") return timeGridDateKeys; + if (viewMode === "month") return monthTrackDateKeys; + return visibleDateKeys; + }, [viewMode, timeGridDateKeys, monthTrackDateKeys, visibleDateKeys]); + + const occurrences = React.useMemo( + () => + occurrenceDateKeys.length > 0 + ? expandSchedulesForDateKeys(visibleSchedules, occurrenceDateKeys, displayOffset, serverOffset) + : [], + [visibleSchedules, occurrenceDateKeys, displayOffset, serverOffset], + ); + // Mini month calendar: 3 adjacent months [prev, current, next] for continuous horizontal sliding. + const miniMonthPanes = React.useMemo(() => { + return [-1, 0, 1].map((delta) => { + const ym = addYearMonth(miniMonth.year, miniMonth.month, delta); + return { + year: ym.year, + month: ym.month, + key: `${ym.year}-${ym.month}`, + keys: buildMonthGridDateKeys(ym.year, ym.month), + }; + }); + }, [miniMonth.year, miniMonth.month]); + + const miniMonthCountByDay = React.useMemo(() => { + const seen = new Set(); + const allKeys: string[] = []; + for (const pane of miniMonthPanes) { + for (const dk of pane.keys) { + if (!seen.has(dk)) { + seen.add(dk); + allKeys.push(dk); + } + } + } + const occs = expandSchedulesForDateKeys(visibleSchedules, allKeys, displayOffset, serverOffset); + const counts = new Map(); + for (const o of occs) { + counts.set(o.dateKey, (counts.get(o.dateKey) ?? 0) + 1); + } + return counts; + }, [visibleSchedules, miniMonthPanes, displayOffset, serverOffset]); + + const yearBufferCols = yearVisibleCols; + const yearTotalCols = yearVisibleCols + yearBufferCols * 2; + // Year view: continuous quarter columns (3 months stacked per column), gliding 1 quarter column at a time. + const yearTrackColumns = React.useMemo(() => { + if (viewMode !== "year") return []; + const cols: Array<{ + key: string; + year: number; + quarter: number; + yearLabel: string; + months: Array<{ year: number; month: number; title: string; keys: string[] }>; + }> = []; + const allDaysSet = new Set(); + for (let idx = -yearBufferCols; idx < yearVisibleCols + yearBufferCols; idx++) { + const qStart = addYearMonth(yearStartQuarter.year, yearStartQuarter.month, idx * 3); + const quarter = Math.floor((qStart.month - 1) / 3) + 1; + const months: Array<{ year: number; month: number; title: string; keys: string[] }> = []; + for (let offset = 0; offset < 3; offset++) { + const ym = addYearMonth(qStart.year, qStart.month, offset); + const daysInMonth = new Date(Date.UTC(ym.year, ym.month, 0)).getUTCDate(); + for (let d = 1; d <= daysInMonth; d++) { + allDaysSet.add(makeDateKey(ym.year, ym.month, d)); + } + months.push({ + year: ym.year, + month: ym.month, + title: dateFormatters.monthLongFmt.format(new Date(Date.UTC(ym.year, ym.month - 1, 15))), + keys: buildMonthGridDateKeys(ym.year, ym.month), + }); + } + cols.push({ + key: `${qStart.year}-Q${quarter}`, + year: qStart.year, + quarter, + yearLabel: dateFormatters.yearFmt.format(new Date(Date.UTC(qStart.year, 0, 15))), + months, + }); + } + const occs = expandSchedulesForDateKeys(visibleSchedules, Array.from(allDaysSet), displayOffset, serverOffset); + const dayCounts = new Map(); + const dayOccurrences = new Map(); + const monthScheduleIds = new Map>(); + for (const o of occs) { + dayCounts.set(o.dateKey, (dayCounts.get(o.dateKey) ?? 0) + 1); + const list = dayOccurrences.get(o.dateKey); + if (list) list.push(o); + else dayOccurrences.set(o.dateKey, [o]); + const p = parseDateKey(o.dateKey); + if (p) { + const ymKey = `${p.year}-${p.month}`; + const set = monthScheduleIds.get(ymKey) ?? new Set(); + set.add(o.scheduleId); + monthScheduleIds.set(ymKey, set); + } + } + for (const list of dayOccurrences.values()) { + list.sort((a, b) => { + const sa = parseClockMinutes(a.schedule.start_time) ?? a.startMin; + const sb = parseClockMinutes(b.schedule.start_time) ?? b.startMin; + if (sa !== sb) return sa - sb; + return a.schedule.name.localeCompare(b.schedule.name); + }); + } + return cols.map((col) => ({ + ...col, + dayCounts, + dayOccurrences, + monthScheduleIds, + })); + }, [ + viewMode, + yearStartQuarter.year, + yearStartQuarter.month, + yearVisibleCols, + yearBufferCols, + visibleSchedules, + displayOffset, + serverOffset, + dateFormatters, + ]); + const upcomingItems = React.useMemo(() => { + return visibleSchedules + .filter((s) => s.enabled && s.status !== "completed" && (s.status === "running" || s.next_start)) + .map((s) => { + const nextMs = s.next_start ? Date.parse(s.next_start) : calibratedNowMs; + const deltaMs = s.status === "running" ? 0 : nextMs - calibratedNowMs; + return { schedule: s, deltaMs, nextMs }; + }) + .sort((a, b) => a.deltaMs - b.deltaMs) + .slice(0, 5); + }, [visibleSchedules, calibratedNowMs]); + + const formatCountdown = (deltaMs: number, status: TaskSchedule["status"]) => { + if (status === "running" || deltaMs <= 0) return translate("schedule.calendar.nowRunning"); + const mins = Math.max(1, Math.round(deltaMs / 60_000)); + if (mins < 60) return translate("schedule.calendar.inMinutes", { count: mins }); + const hrs = Math.round(mins / 60); + if (hrs < 48) return translate("schedule.calendar.inHours", { count: hrs }); + return translate("schedule.calendar.inDays", { count: Math.round(hrs / 24) }); + }; + + // Period header label (e.g. "Nov – Dec 2026", "2026年12月", or "2026年"). + const headerRangeLabel = React.useMemo(() => { + const fmtMonthYear = (y: number, m: number) => + dateFormatters.monthYearShortFmt.format(new Date(Date.UTC(y, m - 1, 15))); + if (viewMode === "year") { + const firstY = yearStartQuarter.year; + const lastYm = addYearMonth(yearStartQuarter.year, yearStartQuarter.month, yearVisibleCols * 3 - 1); + const firstLabel = dateFormatters.yearFmt.format(new Date(Date.UTC(firstY, 0, 15))); + if (lastYm.year === firstY) return firstLabel; + const lastLabel = dateFormatters.yearFmt.format(new Date(Date.UTC(lastYm.year, 0, 15))); + return `${firstLabel} – ${lastLabel}`; + } + if (viewMode === "day") { + return formatDateValue(anchorDateKey); + } + if (viewMode === "week") { + const first = parseDateKey(visibleDateKeys[0]); + const last = parseDateKey(visibleDateKeys[visibleDateKeys.length - 1]); + if (first && last) { + if (first.year === last.year && first.month === last.month) { + return fmtMonthYear(first.year, first.month); + } + const m1 = dateFormatters.monthShortFmt.format(new Date(Date.UTC(first.year, first.month - 1, 15))); + const m2 = dateFormatters.monthShortFmt.format(new Date(Date.UTC(last.year, last.month - 1, 15))); + return `${m1} – ${m2} ${last.year}`; + } + } + if (viewMode === "month") { + return dateFormatters.monthYearLongFmt.format( + new Date(Date.UTC(monthDominantParts.year, monthDominantParts.month - 1, 15)), + ); + } + return dateFormatters.monthYearLongFmt.format(new Date(Date.UTC(anchorParts.year, anchorParts.month - 1, 15))); + }, [ + viewMode, + yearStartQuarter.year, + yearStartQuarter.month, + yearVisibleCols, + anchorDateKey, + visibleDateKeys, + monthDominantParts.year, + monthDominantParts.month, + anchorParts.year, + anchorParts.month, + dateFormatters, + formatDateValue, + ]); + + const shiftTimeGridDays = React.useCallback( + (deltaDays: number) => { + if (deltaDays === 0) return; + setExpandedOccId(null); + if (viewMode === "week") { + setWeekStartDateKey((prev) => addDaysToDateKey(prev, deltaDays)); + setAnchorDateKey((prev) => addDaysToDateKey(prev, deltaDays)); + } else { + setAnchorDateKey((prev) => { + const next = addDaysToDateKey(prev, deltaDays); + setWeekStartDateKey(startOfWeekDateKey(next)); + return next; + }); + } + }, + [viewMode], + ); + + const shiftMonthDays = React.useCallback((deltaDays: number) => { + if (deltaDays === 0) return; + setExpandedOccId(null); + setMonthStartDateKey((prev) => { + const next = addDaysToDateKey(prev, deltaDays); + const mid = parseDateKey(addDaysToDateKey(next, Math.floor(monthVisibleCols / 2))); + if (mid) { + const nextAnchor = makeDateKey(mid.year, mid.month, 1); + setAnchorDateKey(nextAnchor); + setWeekStartDateKey(startOfWeekDateKey(nextAnchor)); + } + return next; + }); + }, []); + + const shiftYearQuarters = React.useCallback((deltaQuarters: number) => { + if (deltaQuarters === 0) return; + setExpandedOccId(null); + setYearDayPopover(null); + setYearStartQuarter((prev) => { + const next = addYearMonth(prev.year, prev.month, deltaQuarters * 3); + const nextAnchor = makeDateKey(next.year, next.month, 1); + setAnchorDateKey(nextAnchor); + setWeekStartDateKey(startOfWeekDateKey(nextAnchor)); + setMonthStartDateKey(nextAnchor); + return next; + }); + }, []); + + const shiftMiniBySteps = React.useCallback( + (delta: number) => { + if (delta === 0) return; + if (miniPickerMode === "months") { + setMiniMonth((prev) => ({ year: prev.year + delta, month: prev.month })); + return; + } + if (miniPickerMode === "years") { + setMiniMonth((prev) => ({ year: prev.year + delta * 12, month: prev.month })); + return; + } + setMiniMonth((prev) => addYearMonth(prev.year, prev.month, delta)); + }, + [miniPickerMode], + ); + + const timeGridSlide = useContinuousTrackSlider({ + enabled: (viewMode === "week" || viewMode === "day") && !dragState && !expandDrag, + axis: "x", + attachKey: viewMode === "week" || viewMode === "day" ? viewMode : "", + visibleUnits: timeGridVisibleCols, + bufferUnits: timeGridBufferCols, + trackKey: viewMode === "week" ? weekStartDateKey : anchorDateKey, + onShiftUnits: shiftTimeGridDays, + shouldIgnorePointerDown: (target) => + Boolean(target?.closest('[data-calendar-event="true"], [data-no-calendar-swipe="true"], input, textarea, select')), + shouldIgnoreWheel: (target) => + Boolean(target?.closest('[data-no-calendar-swipe="true"], input, textarea, select')), + }); + + const setDayColumnsViewportRef = React.useCallback( + (node: HTMLDivElement | null) => { + dayColumnsRef.current = node; + timeGridSlide.viewportRef.current = node; + }, + [timeGridSlide.viewportRef], + ); + + const monthSlide = useContinuousTrackSlider({ + enabled: viewMode === "month" && !dragState && !expandDrag, + axis: "x", + attachKey: viewMode === "month" ? "month" : "", + visibleUnits: monthVisibleCols, + bufferUnits: monthBufferCols, + trackKey: monthStartDateKey, + onShiftUnits: shiftMonthDays, + shouldIgnorePointerDown: (target) => + Boolean(target?.closest('[data-calendar-event="true"], [data-no-calendar-swipe="true"], input, textarea, select')), + shouldIgnoreWheel: (target) => + Boolean(target?.closest('[data-no-calendar-swipe="true"], input, textarea, select')), + }); + + const yearSlide = useContinuousTrackSlider({ + enabled: viewMode === "year" && !dragState && !expandDrag, + axis: "x", + attachKey: viewMode === "year" ? `year-${yearVisibleCols}` : "", + visibleUnits: yearVisibleCols, + bufferUnits: yearBufferCols, + trackKey: `${yearStartQuarter.year}-${yearStartQuarter.month}`, + onShiftUnits: shiftYearQuarters, + shouldIgnorePointerDown: (target) => + Boolean(target?.closest('[data-calendar-event="true"], [data-no-calendar-swipe="true"], input, textarea, select')), + shouldIgnoreWheel: (target) => + Boolean(target?.closest('[data-no-calendar-swipe="true"], input, textarea, select')), + }); + + const yearViewportNodeRef = React.useRef(null); + const setYearViewportRef = React.useCallback( + (node: HTMLDivElement | null) => { + yearViewportNodeRef.current = node; + yearSlide.viewportRef.current = node; + }, + [yearSlide.viewportRef], + ); + React.useEffect(() => { + if (viewMode !== "year") return; + const el = yearViewportNodeRef.current; + if (!el) return; + const updateCols = () => { + const w = el.clientWidth; + if (w > 0) setYearVisibleCols(w < 640 ? 2 : 4); + }; + updateCols(); + if (typeof ResizeObserver === "undefined") return; + const ro = new ResizeObserver(updateCols); + ro.observe(el); + return () => ro.disconnect(); + }, [viewMode]); + + const selectViewMode = React.useCallback( + (mode: CalendarViewMode) => { + setExpandedOccId(null); + setYearDayPopover(null); + if (mode === "month") { + const p = parseDateKey(anchorDateKey); + if (p) setMonthStartDateKey(makeDateKey(p.year, p.month, 1)); + } else if (mode === "year") { + const p = parseDateKey(anchorDateKey); + if (p) { + setYearStartQuarter({ year: p.year, month: 1 }); + } + } else if (mode === "week") { + setWeekStartDateKey(startOfWeekDateKey(anchorDateKey)); + } + setViewMode(mode); + }, + [anchorDateKey], + ); + + const navigatePeriod = React.useCallback( + (dir: -1 | 1) => { + if (viewMode === "week") { + timeGridSlide.slideByUnits(dir * 7); + } else if (viewMode === "day") { + timeGridSlide.slideByUnits(dir); + } else if (viewMode === "month") { + const target = addYearMonth(monthDominantParts.year, monthDominantParts.month, dir); + const targetFirst = makeDateKey(target.year, target.month, 1); + const curMs = Date.parse(`${monthStartDateKey}T00:00:00Z`); + const nextMs = Date.parse(`${targetFirst}T00:00:00Z`); + const deltaDays = Math.round((nextMs - curMs) / 86_400_000); + monthSlide.slideByUnits(deltaDays || dir * 30); + } else if (viewMode === "year") { + yearSlide.slideByUnits(dir * yearVisibleCols); + } + }, + [ + viewMode, + timeGridSlide.slideByUnits, + monthSlide.slideByUnits, + yearSlide.slideByUnits, + monthDominantParts.year, + monthDominantParts.month, + monthStartDateKey, + yearVisibleCols, + ], + ); + + const timeGridTotalCols = timeGridVisibleCols + timeGridBufferCols * 2; + const timeGridTrackStyle = React.useMemo( + () => ({ + width: `${(timeGridTotalCols / timeGridVisibleCols) * 100}%`, + gridTemplateColumns: `repeat(${timeGridTotalCols}, minmax(0, 1fr))`, + }), + [timeGridTotalCols, timeGridVisibleCols], + ); + const yearTrackStyle = React.useMemo( + () => ({ + width: `${(yearTotalCols / yearVisibleCols) * 100}%`, + gridTemplateColumns: `repeat(${yearTotalCols}, minmax(0, 1fr))`, + }), + [yearTotalCols, yearVisibleCols], + ); + const threePaneTrackStyle = React.useMemo( + () => ({ + width: "300%", + gridTemplateColumns: "repeat(3, minmax(0, 1fr))", + }), + [], + ); + + const miniSlide = useContinuousTrackSlider({ + enabled: sidebarOpen, + axis: "x", + attachKey: miniPickerMode, + visibleUnits: 1, + bufferUnits: 1, + trackKey: `${miniPickerMode}:${miniMonth.year}-${miniMonth.month}`, + onShiftUnits: shiftMiniBySteps, + shouldIgnorePointerDown: (target) => Boolean(target?.closest('[data-no-calendar-swipe="true"], input, textarea, select')), + shouldIgnoreWheel: (target) => Boolean(target?.closest('[data-no-calendar-swipe="true"], input, textarea, select')), + }); + const shiftMiniPeriod = miniSlide.slideByUnits; + // Keyboard Left/Right arrows navigate period; Escape collapses inline expanded card. + React.useEffect(() => { + if (viewMode === "list" || selectedOccurrence) return; + const onKeyDown = (e: KeyboardEvent) => { + if (e.metaKey || e.ctrlKey || e.altKey) return; + const target = e.target as HTMLElement | null; + if ( + target && + (target.tagName === "INPUT" || + target.tagName === "TEXTAREA" || + target.tagName === "SELECT" || + target.isContentEditable) + ) { + return; + } + if (e.key === "Escape" && yearDayPopover) { + e.preventDefault(); + setYearDayPopover(null); + return; + } + if (e.key === "Escape" && expandedOccId) { + e.preventDefault(); + setExpandedOccId(null); + return; + } + if (e.key === "ArrowLeft") { + e.preventDefault(); + navigatePeriod(-1); + } else if (e.key === "ArrowRight") { + e.preventDefault(); + navigatePeriod(1); + } + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [viewMode, selectedOccurrence, expandedOccId, yearDayPopover, navigatePeriod]); + + React.useEffect(() => { + if (!yearDayPopover) return; + const onPointerDown = (e: PointerEvent) => { + const target = e.target as HTMLElement | null; + if (target?.closest('[data-year-day-popover="true"], [data-year-day-cell="true"]')) return; + setYearDayPopover(null); + }; + window.addEventListener("pointerdown", onPointerDown); + return () => window.removeEventListener("pointerdown", onPointerDown); + }, [yearDayPopover]); + const miniYearBlockStart = Math.floor(miniMonth.year / 12) * 12; + const shortMonthNames = React.useMemo( + () => + Array.from({ length: 12 }, (_, idx) => + dateFormatters.monthShortFmt.format(new Date(Date.UTC(2026, idx, 15))), + ), + [dateFormatters], + ); + + // Pull-down / pull-up handle to expand or collapse inline schedule details (never modifies schedule times). + React.useEffect(() => { + if (!expandDrag) return; + const handleMove = (e: PointerEvent) => { + const dy = e.clientY - expandDrag.originY; + setExpandDrag((prev) => (prev ? { ...prev, deltaY: dy } : null)); + }; + const handleUp = (e: PointerEvent) => { + const dy = e.clientY - expandDrag.originY; + const { occId, wasExpanded } = expandDrag; + setExpandDrag(null); + if (Math.abs(dy) < 6) { + setExpandedOccId((prev) => (prev === occId ? null : occId)); + return; + } + if (!wasExpanded && dy >= 24) { + setExpandedOccId(occId); + } else if (wasExpanded && dy <= -24) { + setExpandedOccId(null); + } + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp, { once: true }); + window.addEventListener("pointercancel", handleUp, { once: true }); + return () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + }; + }, [expandDrag]); + + // Drag-to-move handler for Week/Day grid event card bodies. + React.useEffect(() => { + if (!dragState) return; + const handleMove = (e: PointerEvent) => { + const dx = e.clientX - dragState.originClientX; + const dy = e.clientY - dragState.originClientY; + const moved = dragState.moved || Math.abs(dx) > 4 || Math.abs(dy) > 4; + const deltaMinutes = Math.round(((dy / HOUR_HEIGHT) * 60) / 15) * 15; + + let nextDateKey = dragState.occurrence.dateKey; + if (viewMode === "week" && dayColumnsRef.current) { + const rect = dayColumnsRef.current.getBoundingClientRect(); + if (rect.width > 0) { + const colW = rect.width / visibleDateKeys.length; + const colIdx = Math.max(0, Math.min(visibleDateKeys.length - 1, Math.floor((e.clientX - rect.left) / colW))); + nextDateKey = visibleDateKeys[colIdx]; + } + } + const dur = dragState.occurrence.endMin - dragState.occurrence.startMin; + const nextStart = Math.max(0, Math.min(1440 - dur, dragState.occurrence.startMin + deltaMinutes)); + setDragState((prev) => + prev + ? { + ...prev, + previewDateKey: nextDateKey, + previewStartMin: nextStart, + previewEndMin: nextStart + dur, + moved, + } + : null, + ); + }; + + const handleUp = () => { + const current = dragState; + setDragState(null); + if (!current.moved) { + setPopoverTimelineOpen(false); + setSelectedOccurrence(current.occurrence); + return; + } + const changed = + current.previewDateKey !== current.occurrence.dateKey || + current.previewStartMin !== current.occurrence.startMin || + current.previewEndMin !== current.occurrence.endMin; + if (!changed) return; + const payload = buildScheduleInputFromDrag( + current.occurrence, + current.previewDateKey, + current.previewStartMin, + current.previewEndMin, + displayOffset, + serverOffset, + ); + void onQuickUpdateSchedule(current.occurrence.scheduleId, payload); + }; + + const handleCancel = () => setDragState(null); + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp, { once: true }); + window.addEventListener("pointercancel", handleCancel, { once: true }); + return () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleCancel); + }; + }, [dragState, viewMode, visibleDateKeys, displayOffset, serverOffset, onQuickUpdateSchedule]); + // Keep selectedOccurrence synced if schedule refreshes. + const activeSelectedSchedule = React.useMemo(() => { + if (!selectedOccurrence) return null; + return schedules.find((s) => s.id === selectedOccurrence.scheduleId) ?? null; + }, [selectedOccurrence, schedules]); + + const gmtLabel = formatGMTOffset(displayOffset); + const liveClockStr = `${String(nowParts.hour).padStart(2, "0")}:${String(nowParts.minute).padStart(2, "0")}`; + const miniMonthTitle = React.useMemo( + () => dateFormatters.monthYearLongFmt.format(new Date(Date.UTC(miniMonth.year, miniMonth.month - 1, 15))), + [dateFormatters, miniMonth.year, miniMonth.month], + ); + + // Group occurrences by dateKey for O(1) lookups across Month, Week and Day views. + const occurrencesByDate = React.useMemo(() => { + const map = new Map(); + for (const ev of occurrences) { + const list = map.get(ev.dateKey) ?? []; + list.push(ev); + map.set(ev.dateKey, list); + } + return map; + }, [occurrences]); + + const allDayByDate = React.useMemo(() => { + const map = new Map(); + for (const ev of occurrences) { + if (!ev.allDay) continue; + const list = map.get(ev.dateKey) ?? []; + list.push(ev); + map.set(ev.dateKey, list); + } + return map; + }, [occurrences]); + + const timedByDate = React.useMemo(() => { + const map = new Map(); + for (const ev of occurrences) { + if (ev.allDay) continue; + const list = map.get(ev.dateKey) ?? []; + list.push(ev); + map.set(ev.dateKey, list); + } + return map; + }, [occurrences]); + + const renderEventDetailCard = (item: TaskSchedule, occ: CalendarEventOccurrence) => { + const style = STATUS_STYLE[item.status] ?? STATUS_STYLE.waiting; + const durationMins = occ.allDay ? 0 : Math.max(0, occ.endMin - occ.startMin); + const linkedTasks = item.task_ids.map((id) => ({ id, task: taskById.get(id) })); + + return ( +
+ {/* Top row: status badge + quick actions (Edit / Pause / Duplicate / Delete / Close) */} +
+
+ + {statusText(item)} +
+
+ + + + + +
+
+ + {/* Title & Time range */} +
+
{item.name}
+
+ {formatDateValue(occ.dateKey)} + · + {occ.allDay ? windowLabel(item) : occ.displayTimeRange} + {durationMins > 0 ? ( + + {formatDurationBadge(durationMins, translate)} + + ) : null} +
+
+ + {timezoneLabel(item)} + {item.proxy_mode && item.proxy_mode !== "inherit" ? ( + + + {formatProxyRouteSummary( + { + mode: item.proxy_mode, + proxy_pool_id: item.proxy_pool_id, + proxy_url: item.proxy_url, + effective_proxy: item.effective_proxy, + }, + isEn, + proxyPool, + )} + + ) : null} +
+ {item.remark ?

{item.remark}

: null} +
+ + {/* Primary Run Now CTA button (matching screenshot's blue action button) */} +
+ + +
+ + {/* Linked Tasks section (matching screenshot's guests list) */} +
+
+ + + {linkedTasks.length > 0 + ? translate("schedule.calendar.boundTasksCount", { count: linkedTasks.length }) + : translate("schedule.calendar.noBoundTasks")} + +
+ {linkedTasks.length > 0 ? ( +
+ {linkedTasks.map(({ id, task }) => ( + + + + + #{id} {task?.name?.trim() || task?.description || ""} + + + {task?.status ? ( + {task.status} + ) : null} + + ))} +
+ ) : null} +
+ + {/* Optional expandable timeline */} + {popoverTimelineOpen ? ( +
{renderTimeline(item.id)}
+ ) : null} +
+ ); + }; + + return ( +
+ {/* Left Sidebar: Search + Mini Month Calendar + Status Filters + Up Next */} + + + {/* Main Right Area */} +
+ {/* Top Toolbar */} +
+
+ + +
+ + +
+ + + + + +
+ + + +
+
+ {shortMonthNames.map((label, idx) => { + const m = idx + 1; + const isSelected = quickJumpYear === anchorParts.year && m === anchorParts.month; + return ( + + ); + })} +
+
+
+ {translate("schedule.calendar.jumpDate")} +
+ { + if (e.target.value) { + jumpToDateKey(e.target.value); + setQuickJumpOpen(false); + } + }} + className="h-8 font-mono text-xs" + /> +
+
+
+
+ + {/* Right: Server clock & TZ switcher + manual date picker + view switcher + New button */} +
+ {/* Server time & timezone switcher */} +
+ + {liveClockStr} + +
+ + {/* Manual date jump */} + + + + + +
{translate("schedule.calendar.jumpDate")}
+ { + if (e.target.value) jumpToDateKey(e.target.value); + }} + className="h-8 font-mono text-xs" + /> +
+
+ + {/* View mode segmented control */} +
+ {(["day", "week", "month", "year", "list"] as CalendarViewMode[]).map((mode) => ( + + ))} +
+ + {/* Primary New Schedule button */} + +
+
+ + {/* Main Content Body (continuous unit-by-unit track viewports; keyed per viewMode to prevent DOM/transform reuse) */} + {viewMode === "list" ? ( +
{listViewContent}
+ ) : viewMode === "year" && yearTrackColumns.length > 0 ? ( + /* Year View: continuous quarter columns (3 months per column) gliding 1 column at a time horizontally */ +
+
+
+ {yearTrackColumns.map((col, colIdx) => { + const isFirstVisible = colIdx === yearBufferCols; + const showYearAccent = col.quarter === 1 || isFirstVisible; + return ( +
+
+ + {col.yearLabel} + + + Q{col.quarter} + +
+
+ {col.months.map(({ year: my, month: m, title: monthTitle, keys: monthKeys }) => { + const monthSchedCount = col.monthScheduleIds.get(`${my}-${m}`)?.size ?? 0; + return ( +
+
+ + {monthSchedCount > 0 ? ( + + {translate("schedule.calendar.monthSchedulesCount", { count: monthSchedCount })} + + ) : null} +
+
+ {[1, 2, 3, 4, 5, 6, 7].map((wd) => ( +
+ {translate(`schedule.calendar.weekdayShort.${wd}`)} +
+ ))} +
+
+ {monthKeys.map((dk) => { + const p = parseDateKey(dk); + const inMonth = p?.month === m; + const isToday = dk === todayKey; + const isSelected = dk === (yearDayPopover?.dateKey ?? anchorDateKey); + const dayCount = inMonth ? (col.dayCounts.get(dk) ?? 0) : 0; + const dayTitle = + dayCount > 0 + ? `${translate("schedule.calendar.dayEventCount", { count: dayCount })} · ${translate("schedule.year.dayHint")}` + : translate("schedule.year.dayHint"); + return ( + + ); + })} +
+
+ ); + })} +
+
+ ); + })} +
+
+ + {/* Floating Day Agenda Popover for Year view */} + {yearDayPopover && (() => { + const dk = yearDayPopover.dateKey; + const p = parseDateKey(dk); + const dayDate = p ? new Date(Date.UTC(p.year, p.month - 1, p.day)) : null; + const dayOccs = yearTrackColumns[0]?.dayOccurrences.get(dk) ?? []; + const isTodayPop = dk === todayKey; + return ( +
+
+
+ + {dayDate ? dateFormatters.dayLongFmt.format(dayDate) : dk} + + {isTodayPop ? ( + + {translate("schedule.calendar.today")} + + ) : null} +
+
+ {dayOccs.length > 0 ? ( + + {translate("schedule.calendar.monthSchedulesCount", { count: dayOccs.length })} + + ) : null} + +
+
+ +
+ {dayOccs.length === 0 ? ( +
+ {translate("schedule.year.dayEmpty")} +
+ ) : ( +
+ {dayOccs.map((occ) => { + const st = STATUS_STYLE[occ.schedule.status] ?? STATUS_STYLE.waiting; + return ( + + ); + })} +
+ )} +
+ +
+
+ + +
+ +
+
+ ); + })()} +
+ ) : viewMode === "month" ? ( + { + setPopoverTimelineOpen(false); + setSelectedOccurrence(occ); + }} + onSelectDay={(dk) => { + jumpToDateKey(dk); + selectViewMode("day"); + }} + onCreateAtSlot={onCreateAtSlot} + onEdit={onEdit} + onAction={onAction} + /> + ) : ( + /* Week & Day Time Grid View: 64px time axis stays fixed while adjacent day columns glide smoothly */ +
+ {/* Sticky Day Column Headers */} +
+
+ {gmtLabel} +
+
+
+ {timeGridDateKeys.map((dk) => { + const p = parseDateKey(dk); + const isToday = dk === todayKey; + const d = p ? new Date(Date.UTC(p.year, p.month - 1, p.day)) : new Date(); + const wdShort = dateFormatters.weekdayShortFmt.format(d); + return ( +
+ + {wdShort} + + + {viewMode === "day" && p ? ( + + {dateFormatters.monthYearShortFmt.format(d)} + + ) : null} +
+ ); + })} +
+
+
+ + {/* All-day / Continuous strip */} +
+
+ {translate("schedule.calendar.allDayShort")} +
+
+
+ {timeGridDateKeys.map((dk) => { + const pills = allDayByDate.get(dk) ?? []; + return ( +
+ {pills.map((ev) => { + const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting; + return ( + + ); + })} +
+ ); + })} +
+
+
+ + {/* Scrollable 24-hour Grid */} +
+
+ {/* Left Time Gutter */} +
+ {Array.from({ length: 24 }, (_, hour) => ( +
+ {hour > 0 ? {formatHourGutter(hour, isEn)} : null} +
+ ))} + {/* Red Current-Time Pill on Gutter */} + {visibleDateKeys.includes(todayKey) ? ( +
+ {liveClockStr} +
+ ) : null} +
+ + {/* Day Columns Viewport (clipped at left time gutter) */} +
+
+ {timeGridDateKeys.map((dk, colIdx) => { + const visibleIdx = colIdx - timeGridBufferCols; + const isToday = dk === todayKey; + const dayTimed = timedByDate.get(dk) ?? []; + const positioned = layoutDayTimedEvents(dayTimed); + + return ( +
+ {/* Hourly clickable background slots */} + {Array.from({ length: 24 }, (_, hour) => ( +
{ + if (expandedOccId) { + setExpandedOccId(null); + return; + } + onCreateAtSlot(dk, hour * 60, Math.min(1440, (hour + 1) * 60)); + }} + className="cursor-crosshair border-b border-border/50 transition-colors hover:bg-blue-50/40 dark:hover:bg-blue-950/20" + style={{ height: `${HOUR_HEIGHT}px` }} + /> + ))} + + {/* Red Current-Time Line with Leading Dot on Today */} + {isToday ? ( +
+ +
+
+ ) : null} + + {/* Timed Event Blocks */} + {positioned.map((ev) => { + const isBeingDragged = dragState?.occurrence.id === ev.id; + if (isBeingDragged && dragState.previewDateKey !== dk) { + return null; + } + const startM = isBeingDragged ? dragState.previewStartMin : ev.startMin; + const endM = isBeingDragged ? dragState.previewEndMin : ev.endMin; + const topPx = (startM / 60) * HOUR_HEIGHT; + const baseHeightPx = Math.max(22, ((endM - startM) / 60) * HOUR_HEIGHT - 2); + const widthPct = 100 / ev.colCount; + const leftPct = ev.col * widthPct; + const st = STATUS_STYLE[ev.schedule.status] ?? STATUS_STYLE.waiting; + const canDrag = !ev.isContinuedFromPrev && !ev.isContinuesToNext; + + const isExpanded = expandedOccId === ev.id; + const isPullingThis = expandDrag?.occId === ev.id; + const pullExtra = + isPullingThis && !expandDrag.wasExpanded + ? Math.max(0, Math.min(220, expandDrag.deltaY)) + : 0; + const pullShrink = + isPullingThis && expandDrag.wasExpanded + ? Math.max(0, Math.min(180, -expandDrag.deltaY)) + : 0; + const showInlineDetails = isExpanded || pullExtra >= 18; + const nearGridBottom = topPx + 220 > 24 * HOUR_HEIGHT; + const cardHeightPx = isPullingThis + ? expandDrag.wasExpanded + ? Math.max(baseHeightPx, 210 - pullShrink) + : baseHeightPx + pullExtra + : baseHeightPx; + const durationMins = Math.max(0, ev.endMin - ev.startMin); + const linkedTasks = ev.schedule.task_ids.map((id) => ({ id, task: taskById.get(id) })); + + const anchorRight = timeGridVisibleCols > 1 && visibleIdx >= timeGridVisibleCols - 2; + const cardStyle: React.CSSProperties = showInlineDetails + ? { + ...(nearGridBottom && isExpanded && !isPullingThis + ? { bottom: "4px" } + : { top: `${topPx}px` }), + ...(isPullingThis + ? { height: `${cardHeightPx}px` } + : { minHeight: `${Math.max(baseHeightPx, 176)}px`, maxHeight: "300px" }), + ...(anchorRight + ? { right: "2px" } + : { left: ev.colCount > 1 ? "2px" : `calc(${leftPct}% + 2px)` }), + width: ev.colCount > 1 ? "calc(100% - 4px)" : `calc(${widthPct}% - 4px)`, + minWidth: "220px", + } + : { + top: `${topPx}px`, + height: `${cardHeightPx}px`, + left: `calc(${leftPct}% + 2px)`, + width: `calc(${widthPct}% - 4px)`, + }; + + return ( +
{ + if (e.button !== 0) return; + e.stopPropagation(); + if (showInlineDetails) return; + if (!canDrag) { + setPopoverTimelineOpen(false); + setSelectedOccurrence(ev); + return; + } + setDragState({ + occurrence: ev, + originClientX: e.clientX, + originClientY: e.clientY, + originDayIndex: colIdx, + previewDateKey: dk, + previewStartMin: ev.startMin, + previewEndMin: ev.endMin, + moved: false, + }); + }} + title={showInlineDetails ? undefined : `${ev.schedule.name} · ${ev.displayTimeRange}`} + style={cardStyle} + className={cn( + "group absolute flex select-none flex-col overflow-hidden rounded-md border text-left shadow-[0_1px_2px_rgba(0,0,0,0.04)]", + showInlineDetails + ? "z-30 bg-popover/98 px-2.5 pt-2 pb-4 text-popover-foreground shadow-lg ring-1 ring-border/80 backdrop-blur-xs" + : cn( + "z-10 transition-shadow", + cardHeightPx < 30 ? "justify-center px-1.5 py-0" : "px-2 pt-1 pb-2.5", + st.card, + canDrag ? "cursor-grab active:cursor-grabbing" : "cursor-pointer", + ), + selectedOccurrence?.id === ev.id && st.cardSelected, + isBeingDragged && "z-30 shadow-lg opacity-95", + )} + > + {showInlineDetails ? ( +
+ {/* Header: status + full title */} +
+
+
+ + + {ev.schedule.name} + +
+
+ + {statusText(ev.schedule)} + +
+ + {/* Time window, duration & rule */} +
+ {ev.displayTimeRange} + {durationMins > 0 ? ( + · {formatDurationBadge(durationMins, translate)} + ) : null} +
+
+ {windowLabel(ev.schedule)} + · + {timezoneLabel(ev.schedule)} +
+ + {/* Proxy route if configured */} + {ev.schedule.proxy_mode && ev.schedule.proxy_mode !== "inherit" ? ( +
+ + + {formatProxyRouteSummary( + { + mode: ev.schedule.proxy_mode, + proxy_pool_id: ev.schedule.proxy_pool_id, + proxy_url: ev.schedule.proxy_url, + effective_proxy: ev.schedule.effective_proxy, + }, + isEn, + proxyPool, + )} + +
+ ) : null} + + {/* Remark */} + {ev.schedule.remark ? ( +

+ {ev.schedule.remark} +

+ ) : null} + + {/* Linked tasks */} +
+
+ + + {linkedTasks.length > 0 + ? translate("schedule.calendar.boundTasksCount", { count: linkedTasks.length }) + : translate("schedule.calendar.noBoundTasks")} + +
+ {linkedTasks.length > 0 ? ( +
+ {linkedTasks.slice(0, 4).map(({ id, task }) => ( + e.stopPropagation()} + className="flex items-center justify-between gap-1 rounded px-1 py-0.5 text-[10px] hover:bg-muted" + > + + #{id} {task?.name?.trim() || task?.description || ""} + + {task?.status ? ( + + {task.status} + + ) : null} + + ))} +
+ ) : null} +
+ + {/* Quick inline actions */} +
e.stopPropagation()} + > + + + + +
+
+ ) : ( + <> + {cardHeightPx < 30 ? ( +
+ {ev.schedule.name} + + {isBeingDragged ? formatMinutesAsClock(startM) : ev.schedule.start_time.slice(0, 5)} + +
+ ) : ( + <> +
{ev.schedule.name}
+
+ {isBeingDragged + ? `${formatMinutesAsClock(startM)} - ${formatMinutesAsClock(endM)}` + : ev.displayTimeRange} +
+ + )} + {cardHeightPx >= 52 && ev.schedule.task_ids.length > 0 ? ( +
+ {ev.schedule.task_ids.map((id) => `#${id}`).join(", ")} +
+ ) : null} + + )} + + {/* Bottom pull-to-expand / collapse handle (inspect details without editing time) */} +
{ + if (e.button !== 0) return; + e.stopPropagation(); + setExpandDrag({ + occId: ev.id, + originY: e.clientY, + deltaY: 0, + wasExpanded: isExpanded, + }); + }} + className={cn( + "absolute inset-x-0 bottom-0 flex h-3.5 cursor-ns-resize items-center justify-center gap-1 transition-opacity", + showInlineDetails + ? "border-t bg-muted/40 opacity-100 hover:bg-muted/70" + : "opacity-45 group-hover:opacity-100", + )} + > + + {showInlineDetails ? ( + + ) : ( + + )} +
+
+ ); + })} + + {/* Render drag ghost when dragged into another column */} + {dragState && + dragState.previewDateKey === dk && + dragState.occurrence.dateKey !== dk ? ( +
+
+ {dragState.occurrence.schedule.name} +
+
+ {formatMinutesAsClock(dragState.previewStartMin)} -{" "} + {formatMinutesAsClock(dragState.previewEndMin)} +
+
+ ) : null} +
+ ); + })} +
+
+
+
+
+ )} +
+ + {/* Floating Event Detail Card Modal / Popover (matching Image #2) */} + {selectedOccurrence && activeSelectedSchedule ? ( +
setSelectedOccurrence(null)} + > +
e.stopPropagation()} + > + {renderEventDetailCard(activeSelectedSchedule, selectedOccurrence)} +
+
+ ) : null} +
+ ); +} diff --git a/web/src/app/(main)/function/schedules/page.tsx b/web/src/app/(main)/function/schedules/page.tsx index dfdbaa7..a9ae194 100644 --- a/web/src/app/(main)/function/schedules/page.tsx +++ b/web/src/app/(main)/function/schedules/page.tsx @@ -18,12 +18,18 @@ import { toast } from "sonner"; import { DateSelect } from "@/components/date-select"; import { RemarkEditor, ScheduleNameEditor } from "@/components/remark-editor"; +import { + formatProxyRouteSummary, + normalizeProxyMode, + ProxyRouteFields, +} from "@/components/proxy-route-selector"; import { TimeSelect } from "@/components/time-select"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; @@ -31,7 +37,9 @@ import { localizedError } from "@/i18n/errors"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api, type ScheduleInput } from "@/lib/api"; import { scheduleDisplay } from "@/lib/schedule-display"; -import type { Task, TaskSchedule } from "@/lib/types"; +import { formatMinutesAsClock, weekdayOfDateKey } from "@/lib/schedule-calendar"; +import type { ProxyPoolEntry, Task, TaskSchedule } from "@/lib/types"; +import { ScheduleCalendarWorkspace } from "./_components/schedule-calendar-workspace"; const blank: ScheduleInput = { name: "", @@ -42,6 +50,9 @@ const blank: ScheduleInput = { task_ids: [], timezone_mode: "beijing", start_immediately: false, + proxy_mode: "inherit", + proxy_pool_id: "", + proxy_url: "", }; type ScheduleHistoryEntry = NonNullable[number]; @@ -145,17 +156,19 @@ function statusClass(status: TaskSchedule["status"]) { function ScheduleForm({ value, tasks, + proxyPool, onSave, onCancel, saving, }: { value: ScheduleInput; tasks: Task[]; + proxyPool: ProxyPoolEntry[]; onSave: (v: ScheduleInput) => void; onCancel?: () => void; saving: boolean; }) { - const { t: translate, i18n } = useLiveTranslation(); + const { t: translate, i18n, isEn } = useLiveTranslation(); const { weekdays } = scheduleDisplay(translate, i18n.resolvedLanguage ?? "zh-CN"); const [draft, setDraft] = React.useState(value); const [taskQuery, setTaskQuery] = React.useState(""); @@ -197,7 +210,7 @@ function ScheduleForm({ )); } return ( -
+
-
+
+ + + + + + {L( + "启用代理时阻断 UDP(OPSEC 推荐,防真实 IP 泄露)", + "Block UDP when proxy active (OPSEC default)", + )} + + {L("始终阻断非 DNS UDP", "Always block non-DNS UDP")} + + {L("允许 UDP 直连(仍受黑名单/SSRF 限制)", "Allow direct UDP (still filtered)")} + + + +
+
+ +
+ setDnsUpstream(e.target.value)} + placeholder="8.8.8.8:53 / 1.1.1.1:53" + className="h-9 font-mono text-xs" + /> + +
+
+
+
+
+ +

+ {L( + "默认关闭:放行、透传与黑名单拦截流量默认存储,端口扫描/超时等错误记录不落库。开启后可在「流量」页排查失败连接。", + "Off by default: allowed, passthrough, and blocked flows are stored, while connection/DNS errors are dropped. Enable to inspect failed connections on the Traffic page.", + )} +

+
+ void toggleStoreErrorTraffic(checked)} + /> +
+ {gw?.last_seen ? ( +

+ {L("网关标识:", "Gateway ID: ")} + {gw.gateway_id || "artex-gateway"} · {L("最近心跳:", "Last heartbeat: ")} + {new Date(gw.last_seen).toLocaleString(locale)} +

+ ) : null} + + + + {/* Add Per-Container / Task Proxy Route Override */} + + + + {L("按任务 / 容器覆盖出口代理", "Per-Task / Container Egress Override")} + + + {L("默认继承全局出口代理(当前:", "Containers inherit the global egress proxy by default (current: ")} + {formatProxyValue(routesState?.global_proxy)} + {L( + ")。可为特定任务或会话容器单独指定代理池节点、自定义代理或强制直连,HTTP / TCP / DNS 均实时生效。", + "). Override any task or session container with a pool node, custom proxy, or direct egress.", + )} + + + +
+
+ +
+
+ setNewOwnerID(e.target.value)} + placeholder={newScope === "task" ? L("任务 ID,如 42", "Task ID, e.g. 42") : L("会话 ID", "Session ID")} + className="h-8 font-mono text-xs" + /> +
+
+ +
+ {newMode === "proxy" ? ( +
+ +
+ ) : null} + {newMode === "proxy" && newPoolID === "__custom__" ? ( +
+ setNewProxyURL(e.target.value)} + placeholder="socks5://127.0.0.1:1080" + className="h-8 font-mono text-xs" + /> +
+ ) : ( +
+ setNewNote(e.target.value)} + placeholder={L("备注(可选)", "Note (optional)")} + className="h-8 text-xs" + /> +
+ )} +
+ +
+
+ + {/* Active Containers & Persisted Route Rules Table */} +
+ + + + {L("归属", "Owner")} + {L("容器 / IP", "Container / IP")} + {L("状态", "State")} + {L("当前生效出口", "Effective Egress")} + {L("快捷切换", "Quick Override")} + {L("操作", "Action")} + + + + {containers.length === 0 ? ( + + + {L( + "暂无运行中的沙箱容器或自定义路由规则", + "No active sandbox containers or custom egress route overrides", + )} + + + ) : ( + containers.map((c) => { + const key = `${c.scope}:${c.owner_id}`; + let currentVal = "__custom__"; + if (c.mode === "inherit") { + currentVal = "__inherit__"; + } else if (c.mode === "direct") { + currentVal = "__direct__"; + } else if (c.mode === "pool") { + currentVal = "__pool__"; + } else if (c.proxy_pool_id) { + currentVal = `pool:${c.proxy_pool_id}`; + } + return ( + + + + {formatScope(c.scope)} + + {c.owner_id} + + +
{c.container_name || "—"}
+ {c.ip ?
{c.ip}
: null} +
+ + + {formatState(c.state)} + + + + {formatEffectiveProxy(c)} + + + + + + {c.mode !== "inherit" ? ( + + ) : null} + +
+ ); + }) + )} +
+
+
+
+
+
+ ); +} diff --git a/web/src/app/(main)/system/proxy/page.tsx b/web/src/app/(main)/system/proxy/page.tsx new file mode 100644 index 0000000..96a3ac7 --- /dev/null +++ b/web/src/app/(main)/system/proxy/page.tsx @@ -0,0 +1,1246 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import { + CheckCircle2Icon, + ExternalLinkIcon, + PlusIcon, + RadioTowerIcon, + RefreshCwIcon, + RouteIcon, + ShieldAlertIcon, + ShieldBanIcon, + Trash2Icon, +} from "lucide-react"; +import { toast } from "sonner"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Switch } from "@/components/ui/switch"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Textarea } from "@/components/ui/textarea"; +import { localizedError } from "@/i18n/errors"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import { api } from "@/lib/api"; +import type { + EgressBlacklistRule, + EgressBlacklistState, + EgressReport, + ProxyPoolEntry, + ProxyRoutesState, + Settings, +} from "@/lib/types"; + +import { useEgressIp } from "../../_components/egress-ip-banner"; +import { ContainerRoutesTab } from "./_components/container-routes-tab"; +export default function ProxyEgressPage() { + const { t, isEn, locale } = useLiveTranslation(); + const L = (zh: string, en: string) => (isEn ? en : zh); + + const [loaded, setLoaded] = React.useState(false); + const [refreshing, setRefreshing] = React.useState(false); + + // Global proxy + pool state + const [globalProxyInput, setGlobalProxyInput] = React.useState(""); + const [savingGlobalProxy, setSavingGlobalProxy] = React.useState(false); + const [proxyPool, setProxyPool] = React.useState([]); + const [proxyPoolActiveId, setProxyPoolActiveId] = React.useState(""); + const [proxyPoolText, setProxyPoolText] = React.useState(""); + const [proxyPoolTimed, setProxyPoolTimed] = React.useState(false); + const [proxyPoolInterval, setProxyPoolInterval] = React.useState("30"); + const [proxyPoolFailure, setProxyPoolFailure] = React.useState(false); + const [proxyPoolStrategy, setProxyPoolStrategy] = React.useState<"sequential" | "random">("sequential"); + const [proxyPoolThreshold, setProxyPoolThreshold] = React.useState("3"); + const [proxyPoolCooldown, setProxyPoolCooldown] = React.useState("60"); + const [proxyPoolHealthInterval, setProxyPoolHealthInterval] = React.useState("30"); + const [proxyPoolLogs, setProxyPoolLogs] = React.useState< + Array<{ at: string; from: string; to: string; reason: string }> + >([]); + const [proxyReconnectMax, setProxyReconnectMax] = React.useState("3"); + const [proxyReconnectInterval, setProxyReconnectInterval] = React.useState("10"); + const [egressProbeUrl, setEgressProbeUrl] = React.useState(""); + const [savingEgressProbeUrl, setSavingEgressProbeUrl] = React.useState(false); + const [savingEgressVisibility, setSavingEgressVisibility] = React.useState(false); + const [egressTesting, setEgressTesting] = React.useState(false); + const [egressReport, setEgressReport] = React.useState(null); + const egressSeq = React.useRef(0); + const clearEgressReport = () => { + egressSeq.current += 1; + setEgressTesting(false); + setEgressReport(null); + }; + + const { + enabled: showEgressIp, + isLoading: egressProbeLoading, + setEnabled: setShowEgressIp, + probeEgress, + } = useEgressIp(); + + // Egress blacklist state + const [blacklist, setBlacklist] = React.useState({ + rules: [], + synced_rules: [], + sync_asset_intercept: false, + events: [], + }); + const [savingSync, setSavingSync] = React.useState(false); + const [newKind, setNewKind] = React.useState<"domain" | "suffix" | "ip" | "cidr">("domain"); + const [newPattern, setNewPattern] = React.useState(""); + const [newPort, setNewPort] = React.useState(""); + const [newNote, setNewNote] = React.useState(""); + const [addingRule, setAddingRule] = React.useState(false); + const [routesState, setRoutesState] = React.useState(null); + const [savingStoreErrorTraffic, setSavingStoreErrorTraffic] = React.useState(false); + + const applySettings = React.useCallback((s: Settings) => { + setGlobalProxyInput(s.global_proxy ?? ""); + setProxyPool(s.proxy_pool ?? []); + setProxyPoolActiveId(s.proxy_pool_active_id ?? ""); + setProxyPoolTimed(Boolean(s.proxy_rotate_timed_enabled)); + setProxyPoolInterval(String(s.proxy_rotate_interval_seconds ?? 30)); + setProxyPoolFailure(Boolean(s.proxy_rotate_on_failure)); + setProxyPoolStrategy(s.proxy_rotate_strategy === "random" ? "random" : "sequential"); + setProxyPoolThreshold(String(s.proxy_health_fail_threshold ?? 3)); + setProxyPoolCooldown(String(s.proxy_health_cooldown_seconds ?? 60)); + setProxyPoolHealthInterval(String(s.proxy_health_check_interval_seconds ?? 30)); + setProxyPoolLogs(s.proxy_pool_switch_log ?? []); + setProxyReconnectMax(String(s.proxy_reconnect_max_attempts ?? 3)); + setProxyReconnectInterval(String(s.proxy_reconnect_interval_seconds ?? 10)); + setEgressProbeUrl(s.egress_probe_url ?? ""); + setLoaded(true); + }, []); + + const loadAll = React.useCallback(async () => { + setRefreshing(true); + try { + const [s, bl, rt] = await Promise.all([ + api.settings(), + api.egressBlacklist(), + api.proxyRoutes().catch(() => null), + ]); + applySettings(s); + setBlacklist(bl); + if (rt) setRoutesState(rt); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setRefreshing(false); + } + }, [applySettings]); + + const refreshRoutes = React.useCallback(async () => { + const rt = await api.proxyRoutes(); + setRoutesState(rt); + }, []); + + const toggleStoreErrorTraffic = async (checked: boolean) => { + const prev = Boolean(routesState?.gateway.store_error_traffic); + setSavingStoreErrorTraffic(true); + setRoutesState((current) => + current ? { ...current, gateway: { ...current.gateway, store_error_traffic: checked } } : current, + ); + try { + await api.updateGatewaySettings({ store_error_traffic: checked }); + await refreshRoutes().catch(() => undefined); + toast.success( + checked + ? L("已开启错误流量存储(连接失败/DNS 错误将落库)", "Error traffic storage enabled") + : L("已关闭错误流量存储(仅存储正常、透传与拦截流量)", "Error traffic storage disabled (default)"), + ); + } catch (e) { + setRoutesState((current) => + current ? { ...current, gateway: { ...current.gateway, store_error_traffic: prev } } : current, + ); + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setSavingStoreErrorTraffic(false); + } + }; + + React.useEffect(() => { + void loadAll(); + }, [loadAll]); + + const refreshProxyPool = () => + api.proxyPool().then((r) => { + setProxyPool(r.entries); + setProxyPoolActiveId(r.active_id); + setProxyPoolLogs(r.switch_log); + }); + + const refreshBlacklist = async () => { + try { + const bl = await api.egressBlacklist(); + setBlacklist(bl); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } + }; + + // --- Proxy & Pool Actions --- + const saveGlobalProxy = () => { + if (proxyPool.length > 0) { + toast.info(t("settings.poolOverridesProxy")); + return; + } + setSavingGlobalProxy(true); + api + .setSettings({ global_proxy: globalProxyInput.trim() }) + .then((s) => { + applySettings(s); + clearEgressReport(); + if (showEgressIp) void probeEgress().catch(() => undefined); + toast.success(globalProxyInput.trim() ? t("settings.globalProxySaved") : t("settings.globalProxyCleared")); + }) + .catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t))) + .finally(() => setSavingGlobalProxy(false)); + }; + + const testEgress = () => { + const seq = ++egressSeq.current; + setEgressTesting(true); + setEgressReport(null); + api + .testEgressProxy({ + global_proxy: globalProxyInput.trim(), + resume: true, + probe_url: egressProbeUrl.trim(), + }) + .then((rep) => { + if (seq !== egressSeq.current) return; + setEgressReport(rep); + if (rep.ok) { + const hit = + rep.checks.find((c) => c.key === "global" && !c.skipped && c.result.ok) ?? + rep.checks.find((c) => !c.skipped && c.result.ok); + toast.success( + hit?.result.exit_ip ? t("settings.egressResult", { ip: hit.result.exit_ip }) : t("settings.probeSucceeded"), + ); + } else { + toast.error(t("settings.egressFailed")); + } + }) + .catch((e) => { + if (seq === egressSeq.current) toast.error(t("settings.probeFailedPrefix") + localizedError(e, t)); + }) + .finally(() => { + if (seq === egressSeq.current) setEgressTesting(false); + }); + }; + + const saveProxyReconnect = () => { + api + .setSettings({ + proxy_reconnect_max_attempts: Number(proxyReconnectMax), + proxy_reconnect_interval_seconds: Number(proxyReconnectInterval), + }) + .then((s) => { + applySettings(s); + toast.success(t("settings.reconnectSaved")); + }) + .catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t))); + }; + + const toggleEgressVisibility = async (checked: boolean) => { + setSavingEgressVisibility(true); + try { + await setShowEgressIp(checked); + toast.success(checked ? t("settings.egressShown") : t("settings.egressHidden")); + } catch (e) { + toast.error(t("settings.egressVisibilityFailed") + localizedError(e, t)); + } finally { + setSavingEgressVisibility(false); + } + }; + + const saveEgressProbeUrl = async () => { + setSavingEgressProbeUrl(true); + try { + const settings = await api.setSettings({ egress_probe_url: egressProbeUrl.trim() }); + setEgressProbeUrl(settings.egress_probe_url ?? ""); + clearEgressReport(); + toast.success(settings.egress_probe_url ? t("settings.probeServiceSaved") : t("settings.probeServiceReset")); + if (showEgressIp) void probeEgress().catch(() => undefined); + } catch (e) { + toast.error(t("settings.probeServiceSaveFailed", { message: localizedError(e, t) })); + } finally { + setSavingEgressProbeUrl(false); + } + }; + + const importProxyPool = () => { + api + .importProxyPool({ text: proxyPoolText }) + .then((r) => { + setProxyPool(r.entries); + setProxyPoolActiveId(r.active_id); + setProxyPoolLogs(r.switch_log); + setProxyPoolText(""); + if (r.errors.length) { + toast.error( + r.errors.map((e) => t("settings.importLineError", { line: e.line, message: e.error })).join(";"), + ); + } else { + toast.success(t("settings.proxyPoolImported")); + } + }) + .catch((e) => toast.error(t("settings.importFailedPrefix") + localizedError(e, t))); + }; + + const saveProxyPoolStrategy = () => { + const interval = Number(proxyPoolInterval); + if (!Number.isFinite(interval) || !Number.isInteger(interval) || interval < 3) { + toast.error(t("settings.invalidRotationInterval")); + return; + } + api + .setSettings({ + proxy_rotate_timed_enabled: proxyPoolTimed, + proxy_rotate_interval_seconds: Number(proxyPoolInterval), + proxy_rotate_on_failure: proxyPoolFailure, + proxy_rotate_strategy: proxyPoolStrategy, + proxy_health_fail_threshold: Number(proxyPoolThreshold), + proxy_health_cooldown_seconds: Number(proxyPoolCooldown), + proxy_health_check_interval_seconds: Number(proxyPoolHealthInterval), + }) + .then((s) => { + applySettings(s); + toast.success(t("settings.rotationSaved")); + }) + .catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t))); + }; + + const testAllProxyPool = () => + api + .testAllProxyPool() + .then((r) => { + setProxyPool(r.entries); + setProxyPoolActiveId(r.active_id); + setProxyPoolLogs(r.switch_log); + toast.success(t("settings.allProxiesTested")); + }) + .catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t))); + + const testOneProxyPool = (id: string) => + api + .testProxyPoolEntry(id) + .then(() => refreshProxyPool()) + .catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t))); + + const activateProxyEntry = (id: string) => + api + .activateProxyPool(id) + .then(() => refreshProxyPool()) + .then(() => { + toast.success(L("已切换当前出口代理", "Switched active egress proxy")); + }) + .catch((e) => toast.error(t("settings.updateFailedPrefix") + localizedError(e, t))); + const toggleProxyPoolEntry = (entry: ProxyPoolEntry) => + api + .updateProxyPool(entry.id, { enabled: !entry.enabled }) + .then(() => refreshProxyPool()) + .catch((e) => toast.error(t("settings.updateFailedPrefix") + localizedError(e, t))); + + const deleteProxyPoolEntry = (id: string) => + api + .deleteProxyPool(id) + .then(() => refreshProxyPool()) + .catch((e) => toast.error(t("settings.deleteFailedPrefix") + localizedError(e, t))); + + // --- Egress Blacklist Actions --- + const toggleSyncAssetIntercept = async (checked: boolean) => { + setSavingSync(true); + try { + const next = await api.updateEgressBlacklistSettings(checked); + setBlacklist(next); + toast.success( + checked + ? L("已开启资产拦截规则同步到网络出口层", "Synced asset intercept rules to network egress") + : L("已关闭资产拦截联动", "Disabled asset intercept sync"), + ); + } catch (e) { + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setSavingSync(false); + } + }; + + const handleAddRule = async (e: React.FormEvent) => { + e.preventDefault(); + const pat = newPattern.trim(); + if (!pat) return; + const portNum = newPort.trim() ? Number(newPort.trim()) : 0; + if (!Number.isInteger(portNum) || portNum < 0 || portNum > 65535) { + toast.error(L("端口必须是 0–65535 之间的整数", "Port must be an integer between 0 and 65535")); + return; + } + setAddingRule(true); + try { + await api.createEgressBlacklistRule({ + enabled: true, + kind: newKind, + pattern: pat, + port: portNum, + note: newNote.trim(), + }); + setNewPattern(""); + setNewPort(""); + setNewNote(""); + await refreshBlacklist(); + toast.success(L("出口黑名单规则已添加并即时生效", "Egress blacklist rule added and active")); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } finally { + setAddingRule(false); + } + }; + + const toggleRule = async (rule: EgressBlacklistRule) => { + try { + await api.updateEgressBlacklistRule(rule.id, { enabled: !rule.enabled }); + await refreshBlacklist(); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + }; + + const deleteRule = async (id: string) => { + try { + await api.deleteEgressBlacklistRule(id); + await refreshBlacklist(); + toast.success(L("规则已删除", "Rule deleted")); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + }; + + const clearEvents = async () => { + try { + await api.clearEgressBlockEvents(); + await refreshBlacklist(); + toast.success(L("已清空拦截记录", "Block events cleared")); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + }; + + const activeProxyEntry = proxyPool.find((p) => p.id === proxyPoolActiveId); + const activeProxyLabel = activeProxyEntry + ? activeProxyEntry.name || activeProxyEntry.url + : globalProxyInput.trim() || L("直连", "Direct"); + + const enabledCustomCount = blacklist.rules.filter((r) => r.enabled).length; + const activeSyncedCount = blacklist.sync_asset_intercept ? blacklist.synced_rules.length : 0; + + const kindLabel = (kind: string) => { + if (kind === "domain") return L("精确域名", "Domain"); + if (kind === "suffix") return L("泛域名/后缀", "Suffix"); + if (kind === "ip") return L("精确 IP", "IP"); + if (kind === "cidr") return L("CIDR 网段", "CIDR"); + return kind; + }; + + const sourceBadge = (source?: string) => { + if (source === "ssrf_guard") return {L("SSRF 防护", "SSRF Guard")}; + if (source === "asset_intercept") return {L("资产拦截联动", "Asset Sync")}; + return {L("自定义黑名单", "Custom")}; + }; + + return ( +
+ {/* Header */} +
+
+
+

+ + {L("代理与出口", "Proxy & Egress")} +

+ + {L("当前出口:", "Egress: ")} + {activeProxyLabel} + + + {L( + `生效黑名单 ${enabledCustomCount + activeSyncedCount} 条`, + `${enabledCustomCount + activeSyncedCount} active block rule(s)`, + )} + +
+

+ {L( + "集中管理全局出口代理、代理池轮换与健康检查、网络出口层黑名单硬拦截以及拦截审计记录。", + "Manage global egress proxy, proxy pool rotation and health checks, network-layer egress blacklist rules, and block audit events.", + )} +

+
+ + +
+ + { + if (value === "routes") { + void refreshRoutes().catch(() => undefined); + } + }} + className="w-full min-w-0 space-y-4" + > + + + + {L(`代理池与出口 (${proxyPool.length})`, `Proxy Pool (${proxyPool.length})`)} + + + + {L( + `出口黑名单 (${enabledCustomCount + activeSyncedCount})`, + `Egress Blacklist (${enabledCustomCount + activeSyncedCount})`, + )} + + + + {L(`拦截记录 (${blacklist.events.length})`, `Block Events (${blacklist.events.length})`)} + + + + {L( + `容器路由与网关 (${routesState?.routes.length ?? 0})`, + `Container Routes (${routesState?.routes.length ?? 0})`, + )} + + + + {/* Tab 1: Proxy Pool & Global Egress */} + + + + {t("settings.globalProxy")} + {t("settings.globalProxyHelp")} + + +
+ +
+ { + setGlobalProxyInput(e.target.value); + clearEgressReport(); + }} + /> + + +
+

+ {globalProxyInput.trim() ? t("settings.proxyConfigured") : t("settings.proxyUnconfigured")} +

+
+ + {t("settings.howProxyWorks")} + +

+ {t("settings.howProxyWorksHelp")} +

+
+
+ +
+ + {t("settings.reconnection")} + +
+

{t("settings.reconnectionHelp")}

+
+
+ + setProxyReconnectMax(e.target.value)} + /> +
+
+ + setProxyReconnectInterval(e.target.value)} + /> +
+ +
+
+
+ +
+
+ +

{t("settings.showEgressHelp")}

+
+ void toggleEgressVisibility(checked)} + /> +
+ +
+
+ +

+ {L( + "默认关闭:仅存储放行、透传与拦截流量,不存储连接失败/超时及 DNS 解析错误;也可在「流量」页随时切换。", + "Off by default: stores allowed, passthrough, and blocked traffic while dropping connection/DNS errors. Also configurable on the Traffic page.", + )} +

+
+ void toggleStoreErrorTraffic(checked)} + /> +
+ +
+ + {t("settings.customProbe")} + +
+ +
+ { + setEgressProbeUrl(e.target.value); + clearEgressReport(); + }} + /> + +
+ {t("settings.probePersistenceHelp")} + + {t("settings.probeResponseStart")} + {'{"ip":"1.2.3.4"}'} + {t("settings.probeResponseEnd")} + +
+
+ + {egressReport && ( +
+ {egressReport.checks.map((c) => { + const viaCapture = !!c.path && c.path !== egressReport.configured; + return ( +
+ + {c.skipped ? "—" : c.result.ok ? "✓" : "✗"} + + + {t(`settings.egressCheck.${c.key}`, { defaultValue: c.label })} + + {c.skipped ? ( + + {c.skip_code + ? t(`settings.egressSkip.${c.skip_code}`, { defaultValue: c.skip_reason }) + : c.skip_reason} + + ) : c.result.ok ? ( + + {c.result.exit_ip} · {c.result.latency_ms}ms + {c.result.via && c.result.via !== "direct" && !viaCapture && ( + + {" "} + {t("settings.viaPrefix")} + {c.result.via.toUpperCase()} + + )} + + ) : ( + + {c.result.probes?.find((p) => p.error)?.error ?? c.result.error} + + )} +
+ ); + })} + {( + egressReport.warning_details ?? + egressReport.warnings?.map((message) => ({ code: "", message, params: {} })) + )?.map((notice) => ( +

+ ⚠{" "} + {notice.code + ? t(`settings.egressWarning.${notice.code}`, { + ...notice.params, + defaultValue: notice.message, + }) + : notice.message} +

+ ))} +
+ )} +
+
+ + + +
+
+ + {t("settings.proxyPool")}{" "} + ({proxyPool.length}) + + + {t("settings.currentProxyPrefix")} + {proxyPool.find((entry) => entry.id === proxyPoolActiveId)?.name ?? + (proxyPoolActiveId ? t("settings.selectedProxy") : t("settings.direct"))} + +
+ +
+
+ +
+ + {t("settings.importProxies")} + +