From 0f678c17c8d342e3071ac6a7f0eb580cffc9b631 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 24 Jun 2026 23:50:16 -0700 Subject: [PATCH 1/5] feat: run clawscan commands in docker sandbox by default --- .github/workflows/runtime-image.yml | 59 +++++++ README.md | 35 +++- cmd/clawscan/main.go | 5 +- cmd/clawscan/main_test.go | 5 + docker/clawscan-runtime/Dockerfile | 22 +++ docs/development.md | 8 + docs/quickstart.md | 12 ++ docs/scanners.md | 25 ++- internal/profiles/resolver.go | 26 +++ internal/runner/benchmark.go | 8 + internal/runner/runner.go | 51 +++++- internal/runner/runner_test.go | 263 +++++++++++++++++++++++++++- internal/runner/sandbox.go | 256 +++++++++++++++++++++++++++ internal/runner/scanner_registry.go | 50 ++++-- internal/runner/snyk_scanner.go | 4 + internal/runner/socket_scanner.go | 4 + 16 files changed, 802 insertions(+), 31 deletions(-) create mode 100644 .github/workflows/runtime-image.yml create mode 100644 docker/clawscan-runtime/Dockerfile create mode 100644 internal/runner/sandbox.go diff --git a/.github/workflows/runtime-image.yml b/.github/workflows/runtime-image.yml new file mode 100644 index 00000000..134b50e3 --- /dev/null +++ b/.github/workflows/runtime-image.yml @@ -0,0 +1,59 @@ +name: Runtime Image + +on: + push: + branches: + - main + tags: + - 'v*' + paths: + - '.github/workflows/runtime-image.yml' + - 'docker/clawscan-runtime/**' + pull_request: + paths: + - '.github/workflows/runtime-image.yml' + - 'docker/clawscan-runtime/**' + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + build: + name: Build runtime image + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry + if: github.event_name != 'pull_request' + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + + - name: Resolve image metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository_owner }}/clawscan-runtime + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest,enable={{is_default_branch}} + + - name: Build image + uses: docker/build-push-action@v6 + with: + context: . + file: docker/clawscan-runtime/Dockerfile + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/README.md b/README.md index 69879beb..dbc9be3b 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,34 @@ export AIG_MODEL=gpt-4.1 export AIG_MODEL_API_KEY=... ``` +## Sandbox Runtime + +ClawScan runs command-backed scanners and judge commands through Docker by +default. The runtime image is `ghcr.io/openclaw/clawscan-runtime:latest`, which +is built to contain the built-in scanner CLIs and the Codex CLI used by the +built-in ClawHub judge profile, so users do not need to install those tools on +the host. + +The Docker sandbox keeps network access on for scanner APIs, mounts only the +target/work/output paths needed by the command, and passes only the declared env +var names for the selected scanners or profile judge. ClawScan records env +presence as `present` or `missing`; it never writes secret values to artifacts. + +Use the opt-out only when the surrounding environment is already isolated, such +as a locked-down CI worker where Docker is unavailable: + +```bash +clawscan ./my-skill --scanner skillspector --sandbox off +CLAWSCAN_SANDBOX=off clawscan ./my-skill --scanner skillspector +``` + +CI runners can smoke-test Docker support with: + +```bash +docker version +docker run --rm ghcr.io/openclaw/clawscan-runtime:latest skillspector --help +``` + ## Install Homebrew is the recommended install path on macOS and Linux: @@ -299,11 +327,8 @@ GitHub Pages publishes the docs site from `docs/` on pushes to `main`. - Command-backed custom scanner adapters, so teams can add their own scanner commands through a documented adapter contract once the built-in scanner boundary has settled. -- Reusable GitHub Action or workflow for CI. The goal is a copy-pasteable way - to install ClawScan, install the dependencies needed by built-in scanners, - run a selected profile or config, and upload the JSON artifact. Judge harness - CLIs such as `codex` should stay explicit setup steps because `--judge` is an - arbitrary command supplied by the workflow author. +- Version-pinned Docker runtime image tags that pair each ClawScan release with + a reviewed scanner toolchain. ## Development diff --git a/cmd/clawscan/main.go b/cmd/clawscan/main.go index cb2e320a..a4daea6b 100644 --- a/cmd/clawscan/main.go +++ b/cmd/clawscan/main.go @@ -359,6 +359,8 @@ Core flags: Defaults to ./clawscan-results.json unless --json is passed. --json Print the full artifact JSON to stdout and skip the default output file. --judge Optional external judge harness command. + --sandbox Command sandbox mode. Defaults to docker; use off only in already-isolated environments. + --sandbox-image Docker runtime image. Defaults to %s or CLAWSCAN_SANDBOX_IMAGE. --benchmark [id] Run a supported benchmark dataset instead of one target. Defaults to SkillTrustBench. --split Benchmark split. Defaults to benchmark for SkillTrustBench and eval_holdout for OpenClaw. --limit Maximum benchmark rows to run. 0 means all rows. @@ -378,6 +380,7 @@ Built-in profiles: %s Required environment variables: + sandbox: CLAWSCAN_SANDBOX=off disables Docker by default; CLAWSCAN_SANDBOX_IMAGE overrides the runtime image. clawhub judge: OPENAI_API_KEY ai-infra-guard: AIG_BASE_URL, AIG_MODEL, AIG_MODEL_API_KEY socket: SOCKET_TOKEN @@ -398,5 +401,5 @@ Judge summary: If no judge is configured, ClawScan only records scanner evidence. If a judge is configured, ClawScan runs it through the platform shell and expects a JSON object on stdout or at {{ output }}. Placeholders: {{ workspace }}, {{ prompt[:path] }}, {{ output_schema[:path] }}, {{ output }}. -`, strings.Join(runner.ScannerIDs(), ", "), strings.Join(profiles.ProfileIDs(), ", ")) +`, runner.DefaultSandboxImage, strings.Join(runner.ScannerIDs(), ", "), strings.Join(profiles.ProfileIDs(), ", ")) } diff --git a/cmd/clawscan/main_test.go b/cmd/clawscan/main_test.go index ac0e74a7..10649682 100644 --- a/cmd/clawscan/main_test.go +++ b/cmd/clawscan/main_test.go @@ -32,6 +32,8 @@ func TestRunCommandPrintsHelp(t *testing.T) { "--limit ", "--offset ", "--predictions-output ", + "--sandbox ", + "--sandbox-image ", "clawscan-results.json", "Supported benchmarks:", "cuhk-zhuque/SkillTrustBench", @@ -40,6 +42,8 @@ func TestRunCommandPrintsHelp(t *testing.T) { "Accepted scanner IDs:", "agentverus, ai-infra-guard, cisco, clawscan-static, skillspector, snyk, socket, virustotal", "Required environment variables:", + "CLAWSCAN_SANDBOX=off", + "CLAWSCAN_SANDBOX_IMAGE", "OPENAI_API_KEY", "AIG_BASE_URL", "AIG_MODEL", @@ -265,6 +269,7 @@ func TestRunCommandUsesBuiltInProfile(t *testing.T) { "--scanner-result", "skillspector=" + skillSpectorFixture, "--scanner-result", "virustotal=" + virusTotalFixture, "--judge", "printf '{\"verdict\":\"benign\"}\\n' > {{ output }}", + "--sandbox", "off", "--json", }, []string{}); err != nil { t.Fatal(err) diff --git a/docker/clawscan-runtime/Dockerfile b/docker/clawscan-runtime/Dockerfile new file mode 100644 index 00000000..f04713a9 --- /dev/null +++ b/docker/clawscan-runtime/Dockerfile @@ -0,0 +1,22 @@ +FROM python:3.12-slim + +ENV PATH="/root/.local/bin:${PATH}" \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PYTHONUNBUFFERED=1 + +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl git gnupg \ + && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ + && apt-get install -y --no-install-recommends nodejs \ + && rm -rf /var/lib/apt/lists/* + +RUN python -m pip install --no-cache-dir --upgrade pip uv \ + && python -m pip install --no-cache-dir \ + "git+https://github.com/NVIDIA/skillspector.git" \ + "cisco-ai-skill-scanner" \ + && uv tool install "snyk-agent-scan@latest" \ + && ln -sf /root/.local/bin/snyk-agent-scan /usr/local/bin/snyk-agent-scan + +RUN npm install -g @openai/codex agentverus-scanner socket + +WORKDIR /workspace diff --git a/docs/development.md b/docs/development.md index 2695cac0..64a651a8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -31,6 +31,14 @@ go run ./cmd/clawscan \ --output /tmp/clawscan-benchmark-smoke.json ``` +Docker runtime smoke: + +```bash +docker build -t clawscan-runtime:dev docker/clawscan-runtime +docker run --rm clawscan-runtime:dev codex --help +docker run --rm clawscan-runtime:dev skillspector --help +``` + ## Docs Site The docs site is generated from Markdown in `docs/`: diff --git a/docs/quickstart.md b/docs/quickstart.md index 56250300..c7f06dfe 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -54,6 +54,11 @@ export OPENAI_API_KEY=... clawscan --scanner skillspector ``` +By default, ClawScan runs command-backed scanners and judge commands inside the +Docker runtime image `ghcr.io/openclaw/clawscan-runtime:latest`. The sandbox +keeps network access on for scanner APIs and passes only the env var names +declared by the selected scanner or profile judge. + Run scanners that require credentials by exporting env vars next to the command: ```bash @@ -86,6 +91,13 @@ To use another built-in profile over the same discovered skill targets: clawscan --profile skills-sh ``` +If Docker is unavailable because the surrounding worker is already isolated, +opt out explicitly: + +```bash +clawscan --profile skills-sh --sandbox off +``` + Built-in profiles: | Profile | Scanners | Judge | diff --git a/docs/scanners.md b/docs/scanners.md index 17494fae..7c4bbaa8 100644 --- a/docs/scanners.md +++ b/docs/scanners.md @@ -7,12 +7,12 @@ by themselves. | Scanner ID | Source | Target support | Required env vars | | --- | --- | --- | --- | -| `agentverus` | [AgentVerus](https://agentverus.ai/) | Local file or directory through `npx --yes agentverus-scanner scan --json`. | None for the local scanner path. | +| `agentverus` | [AgentVerus](https://agentverus.ai/) | Local file or directory through the runtime image's `agentverus-scanner scan --json`. With `--sandbox off`, ClawScan falls back to `npx --yes agentverus-scanner scan --json`. | None for the local scanner path. | | `ai-infra-guard` | [Tencent AI-Infra-Guard](https://github.com/Tencent/AI-Infra-Guard) | Local targets are zipped and uploaded to a self-hosted A.I.G taskapi service. URL targets are passed to `mcp_scan`. | `AIG_BASE_URL`, `AIG_MODEL`, `AIG_MODEL_API_KEY`. | -| `cisco` | [Cisco AI Defense skill-scanner](https://github.com/cisco-ai-defense/skill-scanner) | Local file or directory through `skill-scanner scan --format json --output `. | None required by ClawScan. Configure Cisco's CLI separately. | +| `cisco` | [Cisco AI Defense skill-scanner](https://github.com/cisco-ai-defense/skill-scanner) | Local file or directory through the runtime image's `skill-scanner scan --format json --output `. With `--sandbox off`, ClawScan expects `skill-scanner` on the host path. | None required by ClawScan. Configure Cisco's CLI separately. | | `skillspector` | [NVIDIA SkillSpector](https://github.com/NVIDIA/skillspector) | Local file or directory. Runs the SkillSpector LLM path by default. | `OPENAI_API_KEY` by default. Set `SKILLSPECTOR_PROVIDER=anthropic` for `ANTHROPIC_API_KEY` or `SKILLSPECTOR_PROVIDER=nv_inference` / `nv_build` / `nvidia` for `NVIDIA_INFERENCE_KEY`. | -| `snyk` | [Snyk Agent Scan](https://github.com/snyk/agent-scan) | Local skill path through `uvx snyk-agent-scan@latest scan --json --no-bootstrap --skills `. | `SNYK_TOKEN`. | -| `socket` | [Socket CLI](https://github.com/SocketDev/socket-cli) | Local file or directory through `npx --yes socket scan create --json `. This uses Socket's public full-scan CLI path and does not claim private skills.sh backend parity. | `SOCKET_TOKEN`. | +| `snyk` | [Snyk Agent Scan](https://github.com/snyk/agent-scan) | Local skill path through the runtime image's `snyk-agent-scan scan --json --no-bootstrap --skills `. With `--sandbox off`, ClawScan falls back to `uvx snyk-agent-scan@latest scan --json --no-bootstrap --skills `. | `SNYK_TOKEN`. | +| `socket` | [Socket CLI](https://github.com/SocketDev/socket-cli) | Local file or directory through the runtime image's `socket scan create --json `. With `--sandbox off`, ClawScan falls back to `npx --yes socket scan create --json `. This uses Socket's public full-scan CLI path and does not claim private skills.sh backend parity. | `SOCKET_TOKEN`. | | `clawscan-static` | Built in | Local file or directory. URL targets return a skipped result. | None. | | `virustotal` | [VirusTotal API](https://docs.virustotal.com/reference/file) | Single local file hash lookup in v1. Directories return a skipped result. | `VIRUSTOTAL_API_KEY`. | @@ -47,6 +47,23 @@ and lets ClawScan validate that prompts only reference requested scanners. ClawScan never accepts scanner API keys as CLI flags. This avoids leaking secrets through shell history, process lists, CI logs, and run artifacts. +## Docker Sandbox + +Command-backed scanners and judge commands run through Docker by default using +`ghcr.io/openclaw/clawscan-runtime:latest`. The runtime image contains the +built-in command-backed scanner tools and the Codex CLI used by the built-in +ClawHub judge profile, so operators do not need to install those tools on the +host. + +ClawScan keeps network access enabled for scanner APIs, mounts the target and +temporary output paths needed by the command, and passes only declared env var +names for the selected scanners or profile judge. It never passes the whole +host environment into the container. + +Use `--sandbox off` or `CLAWSCAN_SANDBOX=off` only when the caller is already +running in an isolated CI worker or another environment where Docker is +unavailable by design. + ## Adding A Built-In Scanner Adapter Built-in scanners are registered through `internal/runner.ScannerRegistry`. diff --git a/internal/profiles/resolver.go b/internal/profiles/resolver.go index 83327a5a..207d90f4 100644 --- a/internal/profiles/resolver.go +++ b/internal/profiles/resolver.go @@ -55,6 +55,10 @@ type cliIntent struct { json bool judge string judgeSet bool + sandbox string + sandboxSet bool + sandboxImage string + sandboxImageSet bool benchmark string benchmarkSet bool split string @@ -397,6 +401,22 @@ func parseCLIIntent(args []string) (cliIntent, error) { intent.judge = value intent.judgeSet = true i = next + case "--sandbox": + value, next, err := readValue(args, i, arg) + if err != nil { + return cliIntent{}, err + } + intent.sandbox = value + intent.sandboxSet = true + i = next + case "--sandbox-image": + value, next, err := readValue(args, i, arg) + if err != nil { + return cliIntent{}, err + } + intent.sandboxImage = value + intent.sandboxImageSet = true + i = next case "--benchmark": intent.benchmarkSet = true next := i + 1 @@ -527,6 +547,12 @@ func buildRunnerArgs(intent cliIntent, selected resolvedProfile, profileName str if judgeCommand != "" { args = append(args, "--judge", judgeCommand) } + if intent.sandboxSet { + args = append(args, "--sandbox", intent.sandbox) + } + if intent.sandboxImageSet { + args = append(args, "--sandbox-image", intent.sandboxImage) + } return args, extraEnv, selected.files, nil } diff --git a/internal/runner/benchmark.go b/internal/runner/benchmark.go index 0610287e..5a7378b9 100644 --- a/internal/runner/benchmark.go +++ b/internal/runner/benchmark.go @@ -56,6 +56,7 @@ type BenchmarkArtifact struct { StartedAt string `json:"startedAt"` CompletedAt string `json:"completedAt"` Env map[string]string `json:"env"` + Sandbox SandboxMetadata `json:"sandbox"` Cases []BenchmarkCase `json:"cases"` Summary BenchmarkSummary `json:"summary"` } @@ -196,6 +197,10 @@ func RunBenchmark(opts Options, ctx RunContext) (BenchmarkArtifact, error) { if err := ValidateRequirements(opts, env); err != nil { return BenchmarkArtifact{}, err } + sandbox, err := sandboxMetadata(opts, env) + if err != nil { + return BenchmarkArtifact{}, err + } now := ctx.Now if now == nil { now = time.Now @@ -217,6 +222,7 @@ func RunBenchmark(opts Options, ctx RunContext) (BenchmarkArtifact, error) { }, StartedAt: startedAt, Env: envPresence(opts, env), + Sandbox: sandbox, Cases: []BenchmarkCase{}, Summary: BenchmarkSummary{ ExpectedVerdicts: map[string]int{}, @@ -472,6 +478,8 @@ func runBenchmarkTarget(opts Options, ctx RunContext, env map[string]string, now Env: env, Now: now, CommandRunner: ctx.CommandRunner, + HostCommandRunner: ctx.HostCommandRunner, + DockerAvailability: ctx.DockerAvailability, ScannerRunner: ctx.ScannerRunner, SkillSpectorCommand: ctx.SkillSpectorCommand, AIInfraGuardHTTPClient: ctx.AIInfraGuardHTTPClient, diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 25aabb44..21ffb113 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -31,6 +31,7 @@ type Options struct { JSON bool Judge *JudgeOptions AdditionalRequiredEnv []EnvRequirement + Sandbox SandboxOptions } type BenchmarkOptions struct { @@ -55,6 +56,8 @@ type RunContext struct { Env map[string]string Now func() time.Time CommandRunner CommandRunner + HostCommandRunner CommandRunner + DockerAvailability func() error ScannerRunner ScannerRunner SkillSpectorCommand []string AIInfraGuardHTTPClient AIInfraGuardHTTPClient @@ -82,6 +85,7 @@ type Artifact struct { StartedAt string `json:"startedAt"` CompletedAt string `json:"completedAt"` Env map[string]string `json:"env"` + Sandbox SandboxMetadata `json:"sandbox"` Scanners map[string]ScannerResult `json:"scanners"` Judge *JudgeResult `json:"judge"` } @@ -107,6 +111,7 @@ type BatchArtifact struct { StartedAt string `json:"startedAt"` CompletedAt string `json:"completedAt"` Env map[string]string `json:"env"` + Sandbox SandboxMetadata `json:"sandbox"` Runs []Artifact `json:"runs"` Errors []BatchError `json:"errors,omitempty"` Summary BatchSummary `json:"summary"` @@ -299,6 +304,24 @@ func ParseArgs(args []string) (Options, error) { } judge = value i = next + case "--sandbox": + value, next, err := readValue(args, i, arg) + if err != nil { + return Options{}, err + } + value = strings.ToLower(strings.TrimSpace(value)) + if err := validateSandboxMode(value, "--sandbox"); err != nil { + return Options{}, err + } + opts.Sandbox.Mode = value + i = next + case "--sandbox-image": + value, next, err := readValue(args, i, arg) + if err != nil { + return Options{}, err + } + opts.Sandbox.Image = value + i = next default: return Options{}, fmt.Errorf("Unknown argument: %s", arg) } @@ -381,15 +404,20 @@ func Run(opts Options, ctx RunContext) (Artifact, error) { if err != nil { return Artifact{}, err } - commandRunner := ctx.CommandRunner - if commandRunner == nil { - commandRunner = defaultCommandRunner{Env: env} + commandRunner, sandbox, err := commandRunnerForOptions(opts, ctx, env) + if err != nil { + return Artifact{}, err } scannerRunner := ctx.ScannerRunner if scannerRunner == nil { + scannerSandboxMode := sandbox.Mode + if ctx.CommandRunner != nil { + scannerSandboxMode = SandboxModeOff + } scannerRunner = ExternalScannerRunner{ CommandRunner: commandRunner, Env: env, + SandboxMode: scannerSandboxMode, SkillSpectorCommand: ctx.SkillSpectorCommand, AIInfraGuardHTTPClient: ctx.AIInfraGuardHTTPClient, VirusTotalHTTPClient: ctx.VirusTotalHTTPClient, @@ -397,6 +425,7 @@ func Run(opts Options, ctx RunContext) (Artifact, error) { } } artifact := NewArtifact(opts, target.resolvedPath, startedAt, startedAt, env) + artifact.Sandbox = sandbox artifact.Target.Kind = target.kind for _, scanner := range opts.Scanners { scannerStartedAt := now().UTC().Format(time.RFC3339Nano) @@ -475,6 +504,9 @@ func RunTargets(opts Options, ctx RunContext, cwd string) (RunTargetsResult, err ScannerStatuses: map[string]map[string]int{}, }, } + if sandbox, err := sandboxMetadata(opts, env); err == nil { + batch.Sandbox = sandbox + } for _, targetInput := range targetInputs { runOpts := opts runOpts.Target = targetInput @@ -523,6 +555,7 @@ func RunProfileBatch(optsList []Options, ctx RunContext, cwd string) (BatchArtif ScannerStatuses: map[string]map[string]int{}, }, } + batch.Sandbox = sandboxMetadataForOptionList(optsList, env) targets := map[string]bool{} for _, opts := range optsList { runOpts := opts @@ -1376,6 +1409,7 @@ type ExternalScannerRunner struct { CommandRunner CommandRunner Env map[string]string Registry ScannerRegistry + SandboxMode string SkillSpectorCommand []string AIInfraGuardHTTPClient AIInfraGuardHTTPClient VirusTotalHTTPClient VirusTotalHTTPClient @@ -1465,6 +1499,10 @@ func (runner ExternalScannerRunner) RunScanner(name string, target string, start func (runner ExternalScannerRunner) runAgentVerus(target string, startedAt string) (ScannerResult, error) { command := "npx" args := []string{"--yes", "agentverus-scanner", "scan", target, "--json"} + if runner.SandboxMode == SandboxModeDocker { + command = "agentverus-scanner" + args = []string{"scan", target, "--json"} + } fullCommand := append([]string{command}, args...) timeout := runner.Timeout if timeout == 0 { @@ -1527,7 +1565,11 @@ func (runner ExternalScannerRunner) runAgentVerus(target string, startedAt strin func (runner ExternalScannerRunner) runSkillSpector(target string, startedAt string) (ScannerResult, error) { commandParts := runner.SkillSpectorCommand if len(commandParts) == 0 { - commandParts = discoverSkillSpectorCommand() + if runner.SandboxMode == SandboxModeDocker { + commandParts = []string{"skillspector"} + } else { + commandParts = discoverSkillSpectorCommand() + } } command := commandParts[0] args := append([]string{}, commandParts[1:]...) @@ -1663,6 +1705,7 @@ func NewArtifact(opts Options, resolvedPath string, startedAt string, completedA StartedAt: startedAt, CompletedAt: completedAt, Env: envPresence(opts, env), + Sandbox: mustSandboxMetadata(opts, env), Scanners: scanners, Judge: nil, } diff --git a/internal/runner/runner_test.go b/internal/runner/runner_test.go index 2bc3bf32..9ddca4e8 100644 --- a/internal/runner/runner_test.go +++ b/internal/runner/runner_test.go @@ -121,6 +121,23 @@ func TestParseArgsSupportsJudgeCommand(t *testing.T) { } } +func TestParseArgsSupportsSandboxOff(t *testing.T) { + opts, err := ParseArgs([]string{"./my-skill", "--scanner", "skillspector", "--sandbox", "off"}) + if err != nil { + t.Fatal(err) + } + if opts.Sandbox.Mode != "off" { + t.Fatalf("sandbox mode = %q", opts.Sandbox.Mode) + } +} + +func TestParseArgsRejectsUnsupportedSandboxMode(t *testing.T) { + _, err := ParseArgs([]string{"./my-skill", "--scanner", "skillspector", "--sandbox", "host"}) + if err == nil || err.Error() != "Unsupported --sandbox mode: host (valid: docker, off)" { + t.Fatalf("err = %v", err) + } +} + func TestParseArgsSupportsOpenClawBenchmark(t *testing.T) { opts, err := ParseArgs([]string{ "--benchmark", "OpenClaw/clawhub-security-signals", @@ -972,6 +989,246 @@ func TestRunExecutesSkillSpectorScanner(t *testing.T) { } } +func TestRunUsesDockerSandboxForCommandBackedScannersByDefault(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{ + writeOutput: `{"status":"clean","findings":[]}`, + } + opts, err := ParseArgs([]string{target, "--scanner", "skillspector"}) + if err != nil { + t.Fatal(err) + } + artifact, err := Run(opts, RunContext{ + Env: map[string]string{ + "OPENAI_API_KEY": "secret-openai", + "CLAWSCAN_UNRELATED_SECRET": "do-not-pass", + }, + HostCommandRunner: host, + DockerAvailability: dockerAvailable, + SkillSpectorCommand: []string{"skillspector"}, + }) + if err != nil { + t.Fatal(err) + } + if artifact.Sandbox.Mode != "docker" { + t.Fatalf("sandbox = %#v", artifact.Sandbox) + } + if artifact.Sandbox.Image != DefaultSandboxImage { + t.Fatalf("sandbox image = %q", artifact.Sandbox.Image) + } + if artifact.Scanners["skillspector"].Status != "completed" { + t.Fatalf("scanner = %#v", artifact.Scanners["skillspector"]) + } + if len(host.calls) != 1 { + t.Fatalf("calls = %#v", host.calls) + } + call := host.calls[0] + if call.command != "docker" { + t.Fatalf("command = %q args = %#v", call.command, call.args) + } + if !containsArg(call.args, "run") || !containsArg(call.args, "--rm") { + t.Fatalf("docker args = %#v", call.args) + } + if !containsArg(call.args, "-e") || !containsArg(call.args, "OPENAI_API_KEY") { + t.Fatalf("missing allowed env passthrough: %#v", call.args) + } + joined := strings.Join(call.args, "\x00") + if strings.Contains(joined, "secret-openai") || strings.Contains(joined, "CLAWSCAN_UNRELATED_SECRET") || strings.Contains(joined, "do-not-pass") { + t.Fatalf("docker args leaked env value or undeclared env name: %#v", call.args) + } + if !containsArg(call.args, DefaultSandboxImage) { + t.Fatalf("missing image in docker args: %#v", call.args) + } + imageIndex := indexOfArg(call.args, DefaultSandboxImage) + if imageIndex < 0 || imageIndex+1 >= len(call.args) || call.args[imageIndex+1] != "skillspector" { + t.Fatalf("missing scanner command after image: %#v", call.args) + } +} + +func TestRunPassesSkillSpectorProviderSelectorIntoDockerSandbox(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{ + writeOutput: `{"status":"clean","findings":[]}`, + } + opts, err := ParseArgs([]string{target, "--scanner", "skillspector"}) + if err != nil { + t.Fatal(err) + } + _, err = Run(opts, RunContext{ + Env: map[string]string{ + "SKILLSPECTOR_PROVIDER": "anthropic", + "ANTHROPIC_API_KEY": "secret-anthropic", + }, + HostCommandRunner: host, + DockerAvailability: dockerAvailable, + SkillSpectorCommand: []string{"skillspector"}, + }) + if err != nil { + t.Fatal(err) + } + if len(host.calls) != 1 { + t.Fatalf("calls = %#v", host.calls) + } + if !containsArg(host.calls[0].args, "SKILLSPECTOR_PROVIDER") || !containsArg(host.calls[0].args, "ANTHROPIC_API_KEY") { + t.Fatalf("docker args missing SkillSpector provider env: %#v", host.calls[0].args) + } + if strings.Contains(strings.Join(host.calls[0].args, "\x00"), "secret-anthropic") { + t.Fatalf("docker args leaked secret value: %#v", host.calls[0].args) + } +} + +func TestRunSandboxOffRunsCommandsDirectly(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{ + writeOutput: `{"status":"clean","findings":[]}`, + } + opts, err := ParseArgs([]string{target, "--scanner", "skillspector", "--sandbox", "off"}) + if err != nil { + t.Fatal(err) + } + artifact, err := Run(opts, RunContext{ + Env: map[string]string{"OPENAI_API_KEY": "present"}, + HostCommandRunner: host, + DockerAvailability: func() error { return errors.New("docker unavailable") }, + SkillSpectorCommand: []string{"skillspector"}, + }) + if err != nil { + t.Fatal(err) + } + if artifact.Sandbox.Mode != "off" { + t.Fatalf("sandbox = %#v", artifact.Sandbox) + } + if len(host.calls) != 1 { + t.Fatalf("calls = %#v", host.calls) + } + if host.calls[0].command != "skillspector" { + t.Fatalf("command = %q args = %#v", host.calls[0].command, host.calls[0].args) + } +} + +func TestRunFailsBeforePartialExecutionWhenDockerUnavailable(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{} + opts, err := ParseArgs([]string{target, "--scanner", "agentverus"}) + if err != nil { + t.Fatal(err) + } + _, err = Run(opts, RunContext{ + Env: map[string]string{}, + HostCommandRunner: host, + DockerAvailability: func() error { + return errors.New("docker not found") + }, + }) + if err == nil || !strings.Contains(err.Error(), "Docker sandbox is required") || !strings.Contains(err.Error(), "docker not found") { + t.Fatalf("err = %v", err) + } + if len(host.calls) != 0 { + t.Fatalf("expected preflight failure before command execution, got %#v", host.calls) + } +} + +func TestRunUsesDockerSandboxForJudgeCommandsByDefault(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{ + stdout: `{"verdict":"clean"}`, + } + opts, err := ParseArgs([]string{ + target, + "--scanner", "clawscan-static", + "--judge", `printf '{"verdict":"clean"}'`, + }) + if err != nil { + t.Fatal(err) + } + opts.AdditionalRequiredEnv = []EnvRequirement{{EnvVar: "OPENAI_API_KEY", Reason: "judge"}} + artifact, err := Run(opts, RunContext{ + Env: map[string]string{ + "OPENAI_API_KEY": "secret-openai", + "CLAWSCAN_OTHER_SECRET": "do-not-pass", + }, + HostCommandRunner: host, + DockerAvailability: dockerAvailable, + }) + if err != nil { + t.Fatal(err) + } + if artifact.Judge == nil || artifact.Judge.Status != "completed" { + t.Fatalf("judge = %#v", artifact.Judge) + } + if len(host.calls) != 1 { + t.Fatalf("calls = %#v", host.calls) + } + call := host.calls[0] + if call.command != "docker" { + t.Fatalf("command = %q args = %#v", call.command, call.args) + } + if !containsArg(call.args, "OPENAI_API_KEY") { + t.Fatalf("missing judge env passthrough: %#v", call.args) + } + imageIndex := indexOfArg(call.args, DefaultSandboxImage) + if imageIndex < 0 || imageIndex+1 >= len(call.args) || call.args[imageIndex+1] == "" { + t.Fatalf("missing judge shell after image: %#v", call.args) + } + joined := strings.Join(call.args, "\x00") + if strings.Contains(joined, "secret-openai") || strings.Contains(joined, "CLAWSCAN_OTHER_SECRET") || strings.Contains(joined, "do-not-pass") { + t.Fatalf("docker args leaked env value or undeclared env name: %#v", call.args) + } +} + +func TestRunSandboxOffEnvRunsCommandsDirectly(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(dir, "skill") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + host := &recordingCommandRunner{ + writeOutput: `{"status":"clean","findings":[]}`, + } + opts, err := ParseArgs([]string{target, "--scanner", "skillspector"}) + if err != nil { + t.Fatal(err) + } + artifact, err := Run(opts, RunContext{ + Env: map[string]string{ + "CLAWSCAN_SANDBOX": "off", + "OPENAI_API_KEY": "present", + }, + HostCommandRunner: host, + DockerAvailability: func() error { return errors.New("docker unavailable") }, + SkillSpectorCommand: []string{"skillspector"}, + }) + if err != nil { + t.Fatal(err) + } + if artifact.Sandbox.Mode != "off" { + t.Fatalf("sandbox = %#v", artifact.Sandbox) + } + if len(host.calls) != 1 || host.calls[0].command != "skillspector" { + t.Fatalf("calls = %#v", host.calls) + } +} + func TestRunPassesResolvedEnvToDefaultCommandRunner(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "skill") @@ -999,7 +1256,7 @@ printf '%s' "$CLAWSCAN_UNRELATED_SECRET" > "$CLAWSCAN_LEAK_FILE" } t.Setenv("CLAWSCAN_ENV_PROBE", "process") t.Setenv("CLAWSCAN_UNRELATED_SECRET", "process-secret") - opts, err := ParseArgs([]string{target, "--scanner", "skillspector"}) + opts, err := ParseArgs([]string{target, "--scanner", "skillspector", "--sandbox", "off"}) if err != nil { t.Fatal(err) } @@ -1259,6 +1516,7 @@ func TestRunResolvesSymlinkedDirectoryTargets(t *testing.T) { linkTarget, "--scanner", "clawscan-static", "--judge", "if test -f artifact/SKILL.md; then printf '{\"copied\":true}\\n'; else printf '{\"copied\":false}\\n'; fi", + "--sandbox", "off", }) if err != nil { t.Fatal(err) @@ -2221,6 +2479,7 @@ func TestRunJudgeWorkspaceSkipsIgnoredAndLargeTargetFiles(t *testing.T) { target, "--scanner", "skillspector", "--judge", "test ! -e {{ workspace }}/artifact/node_modules/pkg/payload.js && test ! -e {{ workspace }}/artifact/large.txt && printf '{\"ok\":true}\\n' > {{ output }} # {{ prompt }} {{ output_schema }}", + "--sandbox", "off", }) if err != nil { t.Fatal(err) @@ -2412,6 +2671,7 @@ func TestRunJudgeRejectsNonObjectJSON(t *testing.T) { target, "--scanner", "skillspector", "--judge", "printf '[true]\\n'", + "--sandbox", "off", }) if err != nil { t.Fatal(err) @@ -2627,6 +2887,7 @@ func TestRunJudgeQuotesGeneratedPlaceholderPaths(t *testing.T) { target, "--scanner", "skillspector", "--judge", "test -d {{ workspace }} && printf '{\"ok\":true}\\n' > {{ output }}", + "--sandbox", "off", }) if err != nil { t.Fatal(err) diff --git a/internal/runner/sandbox.go b/internal/runner/sandbox.go new file mode 100644 index 00000000..fb64d3ba --- /dev/null +++ b/internal/runner/sandbox.go @@ -0,0 +1,256 @@ +package runner + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "time" +) + +const ( + SandboxModeDocker = "docker" + SandboxModeOff = "off" + + DefaultSandboxImage = "ghcr.io/openclaw/clawscan-runtime:latest" +) + +type SandboxOptions struct { + Mode string + Image string +} + +type SandboxMetadata struct { + Mode string `json:"mode"` + Image string `json:"image,omitempty"` + Network string `json:"network,omitempty"` + Env []string `json:"env,omitempty"` +} + +type resolvedSandbox struct { + Mode string + Image string +} + +type dockerCommandRunner struct { + Host CommandRunner + Env map[string]string + Image string + EnvNames []string +} + +func resolveSandbox(opts Options, env map[string]string) (resolvedSandbox, error) { + mode := strings.TrimSpace(opts.Sandbox.Mode) + if mode == "" { + mode = strings.TrimSpace(env["CLAWSCAN_SANDBOX"]) + } + if mode == "" { + mode = SandboxModeDocker + } + mode = strings.ToLower(mode) + if err := validateSandboxMode(mode, "CLAWSCAN_SANDBOX"); err != nil { + return resolvedSandbox{}, err + } + image := strings.TrimSpace(opts.Sandbox.Image) + if image == "" { + image = strings.TrimSpace(env["CLAWSCAN_SANDBOX_IMAGE"]) + } + if image == "" && mode == SandboxModeDocker { + image = DefaultSandboxImage + } + return resolvedSandbox{Mode: mode, Image: image}, nil +} + +func validateSandboxMode(mode string, source string) error { + switch strings.ToLower(strings.TrimSpace(mode)) { + case SandboxModeDocker, SandboxModeOff: + return nil + default: + return fmt.Errorf("Unsupported %s mode: %s (valid: docker, off)", source, mode) + } +} + +func sandboxMetadata(opts Options, env map[string]string) (SandboxMetadata, error) { + sandbox, err := resolveSandbox(opts, env) + if err != nil { + return SandboxMetadata{}, err + } + metadata := SandboxMetadata{Mode: sandbox.Mode} + if sandbox.Mode == SandboxModeDocker { + metadata.Image = sandbox.Image + metadata.Network = "on" + metadata.Env = sandboxEnvNames(opts, env) + } + return metadata, nil +} + +func mustSandboxMetadata(opts Options, env map[string]string) SandboxMetadata { + metadata, err := sandboxMetadata(opts, env) + if err != nil { + return SandboxMetadata{Mode: SandboxModeDocker, Image: DefaultSandboxImage, Network: "on"} + } + return metadata +} + +func sandboxMetadataForOptionList(optsList []Options, env map[string]string) SandboxMetadata { + if len(optsList) == 0 { + return SandboxMetadata{} + } + first := mustSandboxMetadata(optsList[0], env) + for _, opts := range optsList[1:] { + next := mustSandboxMetadata(opts, env) + if next.Mode != first.Mode || next.Image != first.Image || next.Network != first.Network || strings.Join(next.Env, "\x00") != strings.Join(first.Env, "\x00") { + return SandboxMetadata{Mode: "mixed"} + } + } + return first +} + +func commandRunnerForOptions(opts Options, ctx RunContext, env map[string]string) (CommandRunner, SandboxMetadata, error) { + metadata, err := sandboxMetadata(opts, env) + if err != nil { + return nil, SandboxMetadata{}, err + } + if ctx.CommandRunner != nil { + return ctx.CommandRunner, metadata, nil + } + host := ctx.HostCommandRunner + if host == nil { + host = defaultCommandRunner{Env: env} + } + if metadata.Mode == SandboxModeOff { + return host, metadata, nil + } + if requiresCommandExecution(opts) { + availability := ctx.DockerAvailability + if availability == nil { + availability = dockerAvailable + } + if err := availability(); err != nil { + return nil, metadata, fmt.Errorf("Docker sandbox is required for selected command-backed scanners or judge; install/start Docker or rerun with --sandbox=off: %w", err) + } + } + return dockerCommandRunner{ + Host: host, + Env: env, + Image: metadata.Image, + EnvNames: metadata.Env, + }, metadata, nil +} + +func dockerAvailable() error { + if _, err := exec.LookPath("docker"); err != nil { + return err + } + return nil +} + +func (runner dockerCommandRunner) Run(command string, args []string, cwd string, timeout time.Duration) (CommandOutput, error) { + dockerArgs := []string{"run", "--rm", "--network", "bridge"} + for _, name := range runner.EnvNames { + if strings.TrimSpace(runner.Env[name]) != "" { + dockerArgs = append(dockerArgs, "-e", name) + } + } + for _, mount := range dockerMounts(cwd, args) { + dockerArgs = append(dockerArgs, "--mount", mount) + } + if cwd != "" { + dockerArgs = append(dockerArgs, "-w", cwd) + } + dockerArgs = append(dockerArgs, runner.Image, command) + dockerArgs = append(dockerArgs, args...) + return runner.Host.Run("docker", dockerArgs, "", timeout) +} + +func dockerMounts(cwd string, args []string) []string { + mounts := map[string]bool{} + add := func(path string, readOnly bool) { + if path == "" { + return + } + clean := filepath.Clean(path) + if !filepath.IsAbs(clean) { + return + } + if existing, err := os.Stat(clean); err == nil { + if !existing.IsDir() { + mounts[clean] = readOnly + return + } + mounts[clean] = readOnly + return + } + parent := filepath.Dir(clean) + if parent != "." && parent != clean { + mounts[parent] = false + } + } + add(cwd, false) + for _, arg := range args { + add(arg, true) + } + sources := make([]string, 0, len(mounts)) + for source := range mounts { + sources = append(sources, source) + } + sort.Strings(sources) + out := make([]string, 0, len(sources)) + for _, source := range sources { + option := "type=bind,source=" + source + ",target=" + source + if mounts[source] { + option += ",readonly" + } + out = append(out, option) + } + return out +} + +func sandboxEnvNames(opts Options, env map[string]string) []string { + seen := map[string]bool{} + add := func(name string) { + name = strings.TrimSpace(name) + if name != "" { + seen[name] = true + } + } + for _, req := range requirements(opts, env) { + add(req.EnvVar) + } + for _, scanner := range opts.Scanners { + if opts.ScannerResultPaths[scanner] != "" { + continue + } + switch scanner { + case "skillspector": + add("SKILLSPECTOR_PROVIDER") + } + } + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + sort.Strings(names) + return names +} + +func requiresCommandExecution(opts Options) bool { + if opts.Judge != nil { + return true + } + for _, scanner := range opts.Scanners { + if opts.ScannerResultPaths[scanner] != "" { + continue + } + adapter, ok := DefaultScannerRegistry().Adapter(scanner) + if !ok { + continue + } + if commandBackedScanner(adapter) { + return true + } + } + return false +} diff --git a/internal/runner/scanner_registry.go b/internal/runner/scanner_registry.go index 924e2587..056a66a3 100644 --- a/internal/runner/scanner_registry.go +++ b/internal/runner/scanner_registry.go @@ -62,9 +62,10 @@ func (registry ScannerRegistry) isZero() bool { } type scannerAdapter struct { - id string - requirements func(env map[string]string) []EnvRequirement - run func(runner ExternalScannerRunner, target string, startedAt string) (ScannerResult, error) + id string + requirements func(env map[string]string) []EnvRequirement + commandBacked bool + run func(runner ExternalScannerRunner, target string, startedAt string) (ScannerResult, error) } func (adapter scannerAdapter) ID() string { @@ -82,6 +83,10 @@ func (adapter scannerAdapter) Run(runner ExternalScannerRunner, target string, s return adapter.run(runner, target, startedAt) } +func (adapter scannerAdapter) CommandBacked() bool { + return adapter.commandBacked +} + var defaultScannerRegistry = mustScannerRegistry(defaultScannerAdapters()...) func mustScannerRegistry(adapters ...ScannerAdapter) ScannerRegistry { @@ -95,8 +100,9 @@ func mustScannerRegistry(adapters ...ScannerAdapter) ScannerRegistry { func defaultScannerAdapters() []ScannerAdapter { return []ScannerAdapter{ scannerAdapter{ - id: "agentverus", - run: ExternalScannerRunner.runAgentVerus, + id: "agentverus", + commandBacked: true, + run: ExternalScannerRunner.runAgentVerus, }, scannerAdapter{ id: "ai-infra-guard", @@ -104,27 +110,31 @@ func defaultScannerAdapters() []ScannerAdapter { run: ExternalScannerRunner.runAIInfraGuard, }, scannerAdapter{ - id: "cisco", - run: ExternalScannerRunner.runCisco, + id: "cisco", + commandBacked: true, + run: ExternalScannerRunner.runCisco, }, scannerAdapter{ id: "clawscan-static", run: ExternalScannerRunner.runStatic, }, scannerAdapter{ - id: "skillspector", - requirements: skillSpectorRequirements, - run: ExternalScannerRunner.runSkillSpector, + id: "skillspector", + requirements: skillSpectorRequirements, + commandBacked: true, + run: ExternalScannerRunner.runSkillSpector, }, scannerAdapter{ - id: "snyk", - requirements: staticEnvRequirements("scanner snyk", "SNYK_TOKEN"), - run: ExternalScannerRunner.runSnyk, + id: "snyk", + requirements: staticEnvRequirements("scanner snyk", "SNYK_TOKEN"), + commandBacked: true, + run: ExternalScannerRunner.runSnyk, }, scannerAdapter{ - id: "socket", - requirements: staticEnvRequirements("scanner socket", "SOCKET_TOKEN"), - run: ExternalScannerRunner.runSocket, + id: "socket", + requirements: staticEnvRequirements("scanner socket", "SOCKET_TOKEN"), + commandBacked: true, + run: ExternalScannerRunner.runSocket, }, scannerAdapter{ id: "virustotal", @@ -134,6 +144,14 @@ func defaultScannerAdapters() []ScannerAdapter { } } +func commandBackedScanner(adapter ScannerAdapter) bool { + type commandBacked interface { + CommandBacked() bool + } + typed, ok := adapter.(commandBacked) + return ok && typed.CommandBacked() +} + func staticEnvRequirements(reason string, envVars ...string) func(env map[string]string) []EnvRequirement { return func(env map[string]string) []EnvRequirement { reqs := make([]EnvRequirement, 0, len(envVars)) diff --git a/internal/runner/snyk_scanner.go b/internal/runner/snyk_scanner.go index bcfc0498..9ee966a5 100644 --- a/internal/runner/snyk_scanner.go +++ b/internal/runner/snyk_scanner.go @@ -12,6 +12,10 @@ var errInvalidSnykJSON = errors.New("Snyk scanner returned invalid JSON") func (runner ExternalScannerRunner) runSnyk(target string, startedAt string) (ScannerResult, error) { command := "uvx" args := []string{"snyk-agent-scan@latest", "scan", "--json", "--no-bootstrap", "--skills", target} + if runner.SandboxMode == SandboxModeDocker { + command = "snyk-agent-scan" + args = []string{"scan", "--json", "--no-bootstrap", "--skills", target} + } fullCommand := append([]string{command}, args...) timeout := runner.Timeout if timeout == 0 { diff --git a/internal/runner/socket_scanner.go b/internal/runner/socket_scanner.go index 5d454395..3f37e8e2 100644 --- a/internal/runner/socket_scanner.go +++ b/internal/runner/socket_scanner.go @@ -12,6 +12,10 @@ var errInvalidSocketJSON = errors.New("Socket scanner returned invalid JSON") func (runner ExternalScannerRunner) runSocket(target string, startedAt string) (ScannerResult, error) { command := "npx" args := []string{"--yes", "socket", "scan", "create", "--no-banner", "--no-spinner", "--no-interactive", "--json", target} + if runner.SandboxMode == SandboxModeDocker { + command = "socket" + args = []string{"scan", "create", "--no-banner", "--no-spinner", "--no-interactive", "--json", target} + } fullCommand := append([]string{command}, args...) timeout := runner.Timeout if timeout == 0 { From b65c3e98222ac1c1839df590202f6e5a4d75c9aa Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 26 Jun 2026 12:39:45 -0700 Subject: [PATCH 2/5] chore: include claude code in clawscan runtime --- README.md | 5 ++--- docker/clawscan-runtime/Dockerfile | 2 +- docs/development.md | 1 + docs/scanners.md | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index dbc9be3b..4591daeb 100644 --- a/README.md +++ b/README.md @@ -234,9 +234,8 @@ export AIG_MODEL_API_KEY=... ClawScan runs command-backed scanners and judge commands through Docker by default. The runtime image is `ghcr.io/openclaw/clawscan-runtime:latest`, which -is built to contain the built-in scanner CLIs and the Codex CLI used by the -built-in ClawHub judge profile, so users do not need to install those tools on -the host. +is built to contain the built-in scanner CLIs plus Codex and Claude Code for +judge/profile commands, so users do not need to install those tools on the host. The Docker sandbox keeps network access on for scanner APIs, mounts only the target/work/output paths needed by the command, and passes only the declared env diff --git a/docker/clawscan-runtime/Dockerfile b/docker/clawscan-runtime/Dockerfile index f04713a9..8bd99670 100644 --- a/docker/clawscan-runtime/Dockerfile +++ b/docker/clawscan-runtime/Dockerfile @@ -17,6 +17,6 @@ RUN python -m pip install --no-cache-dir --upgrade pip uv \ && uv tool install "snyk-agent-scan@latest" \ && ln -sf /root/.local/bin/snyk-agent-scan /usr/local/bin/snyk-agent-scan -RUN npm install -g @openai/codex agentverus-scanner socket +RUN npm install -g @anthropic-ai/claude-code @openai/codex agentverus-scanner socket WORKDIR /workspace diff --git a/docs/development.md b/docs/development.md index 64a651a8..fb5dcc7a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -36,6 +36,7 @@ Docker runtime smoke: ```bash docker build -t clawscan-runtime:dev docker/clawscan-runtime docker run --rm clawscan-runtime:dev codex --help +docker run --rm clawscan-runtime:dev claude --help docker run --rm clawscan-runtime:dev skillspector --help ``` diff --git a/docs/scanners.md b/docs/scanners.md index 7c4bbaa8..81f02245 100644 --- a/docs/scanners.md +++ b/docs/scanners.md @@ -51,8 +51,8 @@ secrets through shell history, process lists, CI logs, and run artifacts. Command-backed scanners and judge commands run through Docker by default using `ghcr.io/openclaw/clawscan-runtime:latest`. The runtime image contains the -built-in command-backed scanner tools and the Codex CLI used by the built-in -ClawHub judge profile, so operators do not need to install those tools on the +built-in command-backed scanner tools plus Codex and Claude Code for +judge/profile commands, so operators do not need to install those tools on the host. ClawScan keeps network access enabled for scanner APIs, mounts the target and From ecbb8a061a2e0e9ccdb2ebd4d3b04e3db821b09d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 26 Jun 2026 12:51:54 -0700 Subject: [PATCH 3/5] feat: support sandbox config in clawscan profiles --- docs/quickstart.md | 8 +++ internal/profiles/resolver.go | 32 +++++++++++- internal/profiles/resolver_test.go | 82 ++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 1 deletion(-) diff --git a/docs/quickstart.md b/docs/quickstart.md index c7f06dfe..70ae5a41 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -128,6 +128,10 @@ fails with an ambiguity error. ```yaml version: 1 +sandbox: + mode: docker + image: ghcr.io/openclaw/clawscan-runtime:latest + profiles: clawhub-release: scanners: @@ -139,6 +143,8 @@ profiles: - skillspector - clawscan-static output: ./clawscan-results/skills-sh-review.json + sandbox: + image: ghcr.io/acme/custom-clawscan-runtime:v1 judge: command: judge --out {{ output }} requiredEnv: @@ -235,6 +241,8 @@ Actual secret values are never written to run artifacts. | `--output ` | Write the full artifact JSON to a specific file. Defaults to `./clawscan-results.json` when `--json` is not passed. | | `--json` | Print the full artifact JSON to stdout and skip the default output file. | | `--judge ` | Run an optional external judge harness. | +| `--sandbox ` | Select command sandbox mode. Defaults to Docker. | +| `--sandbox-image ` | Override the Docker runtime image. | | `--benchmark [id]` | Run a supported benchmark instead of one target. Defaults to SkillTrustBench. | | `--split ` | Benchmark split. Defaults to `benchmark` for SkillTrustBench and `eval_holdout` for OpenClaw. | | `--limit ` | Maximum benchmark rows to run. `0` means all rows. | diff --git a/internal/profiles/resolver.go b/internal/profiles/resolver.go index 207d90f4..563c363a 100644 --- a/internal/profiles/resolver.go +++ b/internal/profiles/resolver.go @@ -21,6 +21,7 @@ var builtinFiles embed.FS type Config struct { Version int `yaml:"version"` + Sandbox *Sandbox `yaml:"sandbox,omitempty"` Profiles map[string]Profile `yaml:"profiles"` } @@ -29,9 +30,15 @@ type Profile struct { ScannerResults map[string]string `yaml:"scannerResults,omitempty"` Output string `yaml:"output,omitempty"` JSON bool `yaml:"json,omitempty"` + Sandbox *Sandbox `yaml:"sandbox,omitempty"` Judge *Judge `yaml:"judge,omitempty"` } +type Sandbox struct { + Mode string `yaml:"mode,omitempty"` + Image string `yaml:"image,omitempty"` +} + type Judge struct { Command string `yaml:"command"` RequiredEnv []string `yaml:"requiredEnv,omitempty"` @@ -39,6 +46,7 @@ type Judge struct { type resolvedProfile struct { profile Profile + sandbox Sandbox configDir string files map[string][]byte } @@ -304,8 +312,24 @@ func readConfigBytes(label string, read func() ([]byte, error)) (Config, error) func mergeProfiles(out map[string]resolvedProfile, config Config, configDir string, files map[string][]byte) { for name, profile := range config.Profiles { - out[name] = resolvedProfile{profile: profile, configDir: configDir, files: files} + out[name] = resolvedProfile{profile: profile, sandbox: mergeSandbox(config.Sandbox, profile.Sandbox), configDir: configDir, files: files} + } +} + +func mergeSandbox(defaults *Sandbox, override *Sandbox) Sandbox { + var out Sandbox + if defaults != nil { + out = *defaults } + if override != nil { + if override.Mode != "" { + out.Mode = override.Mode + } + if override.Image != "" { + out.Image = override.Image + } + } + return out } func discoverConfig(cwd string) (string, error) { @@ -547,6 +571,12 @@ func buildRunnerArgs(intent cliIntent, selected resolvedProfile, profileName str if judgeCommand != "" { args = append(args, "--judge", judgeCommand) } + if selected.sandbox.Mode != "" { + args = append(args, "--sandbox", selected.sandbox.Mode) + } + if selected.sandbox.Image != "" { + args = append(args, "--sandbox-image", selected.sandbox.Image) + } if intent.sandboxSet { args = append(args, "--sandbox", intent.sandbox) } diff --git a/internal/profiles/resolver_test.go b/internal/profiles/resolver_test.go index e95933bf..18bad099 100644 --- a/internal/profiles/resolver_test.go +++ b/internal/profiles/resolver_test.go @@ -382,6 +382,88 @@ profiles: } } +func TestResolveArgsSupportsSandboxConfig(t *testing.T) { + dir := t.TempDir() + config := filepath.Join(dir, ".clawscan.yml") + writeFile(t, config, `version: 1 +sandbox: + mode: docker + image: ghcr.io/acme/clawscan-runtime:v1 +profiles: + review: + scanners: + - clawscan-static +`) + + opts, err := ResolveArgs([]string{"./skill", "--profile", "review"}, dir) + if err != nil { + t.Fatal(err) + } + if opts.Sandbox.Mode != "docker" { + t.Fatalf("sandbox mode = %q", opts.Sandbox.Mode) + } + if opts.Sandbox.Image != "ghcr.io/acme/clawscan-runtime:v1" { + t.Fatalf("sandbox image = %q", opts.Sandbox.Image) + } +} + +func TestResolveArgsSupportsProfileSandboxOverride(t *testing.T) { + dir := t.TempDir() + config := filepath.Join(dir, ".clawscan.yml") + writeFile(t, config, `version: 1 +sandbox: + mode: docker + image: ghcr.io/acme/default-runtime:v1 +profiles: + review: + scanners: + - clawscan-static + sandbox: + image: ghcr.io/acme/review-runtime:v2 +`) + + opts, err := ResolveArgs([]string{"./skill", "--profile", "review"}, dir) + if err != nil { + t.Fatal(err) + } + if opts.Sandbox.Mode != "docker" { + t.Fatalf("sandbox mode = %q", opts.Sandbox.Mode) + } + if opts.Sandbox.Image != "ghcr.io/acme/review-runtime:v2" { + t.Fatalf("sandbox image = %q", opts.Sandbox.Image) + } +} + +func TestResolveArgsSandboxCLIOverridesConfig(t *testing.T) { + dir := t.TempDir() + config := filepath.Join(dir, ".clawscan.yml") + writeFile(t, config, `version: 1 +sandbox: + mode: docker + image: ghcr.io/acme/default-runtime:v1 +profiles: + review: + scanners: + - clawscan-static +`) + + opts, err := ResolveArgs([]string{ + "./skill", + "--profile", "review", + "--sandbox", "off", + "--sandbox-image", "ghcr.io/acme/manual-runtime:v3", + }, dir) + if err != nil { + t.Fatal(err) + } + if opts.Sandbox.Mode != "off" { + t.Fatalf("sandbox mode = %q", opts.Sandbox.Mode) + } + if opts.Sandbox.Image != "ghcr.io/acme/manual-runtime:v3" { + t.Fatalf("sandbox image = %q", opts.Sandbox.Image) + } +} + func TestResolveArgsResolvesConfigRelativeJudgePlaceholderPaths(t *testing.T) { dir := t.TempDir() config := filepath.Join(dir, "security", ".clawscan.yml") From 4fc74f13229015d6ff65658d42efd172a4e934b8 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 26 Jun 2026 13:07:41 -0700 Subject: [PATCH 4/5] chore: automate runtime tool update PRs --- .github/workflows/runtime-tool-updates.yml | 88 ++++++++++++++++++++ docker/clawscan-runtime/Dockerfile | 20 ++++- docs/development.md | 28 +++++++ scripts/update-runtime-tool-versions.mjs | 94 ++++++++++++++++++++++ 4 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/runtime-tool-updates.yml create mode 100644 scripts/update-runtime-tool-versions.mjs diff --git a/.github/workflows/runtime-tool-updates.yml b/.github/workflows/runtime-tool-updates.yml new file mode 100644 index 00000000..7b6fcb67 --- /dev/null +++ b/.github/workflows/runtime-tool-updates.yml @@ -0,0 +1,88 @@ +name: Runtime Tool Updates + +on: + schedule: + - cron: '17 9 1 * *' + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +jobs: + update-runtime-tools: + name: Update runtime tool pins + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 24 + + - name: Update Dockerfile pins + run: node scripts/update-runtime-tool-versions.mjs + + - name: Detect runtime pin changes + id: changes + run: | + if git diff --quiet -- docker/clawscan-runtime/Dockerfile; then + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Build candidate runtime image + if: steps.changes.outputs.changed == 'true' + run: docker build -t clawscan-runtime:candidate docker/clawscan-runtime + + - name: Smoke candidate runtime image + if: steps.changes.outputs.changed == 'true' + run: | + docker run --rm clawscan-runtime:candidate codex --help >/dev/null + docker run --rm clawscan-runtime:candidate claude --help >/dev/null + docker run --rm clawscan-runtime:candidate skillspector --help >/dev/null + docker run --rm clawscan-runtime:candidate snyk-agent-scan --help >/dev/null + docker run --rm clawscan-runtime:candidate socket --help >/dev/null + docker run --rm clawscan-runtime:candidate agentverus-scanner --help >/dev/null + docker run --rm clawscan-runtime:candidate skill-scanner --help >/dev/null + + - name: Open runtime update PR + if: steps.changes.outputs.changed == 'true' + env: + GH_TOKEN: ${{ github.token }} + BRANCH: automation/runtime-tool-updates + TITLE: Update ClawScan runtime tool pins + run: | + set -euo pipefail + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git checkout -B "$BRANCH" + git add docker/clawscan-runtime/Dockerfile + git commit -m "chore: update clawscan runtime tool pins" + git push --force-with-lease origin "$BRANCH" + + cat > /tmp/runtime-tool-update-pr.md <<'EOF' + Updates pinned tool versions in `docker/clawscan-runtime/Dockerfile`. + + Automated proof in this workflow: + - Docker runtime image builds. + - Baked CLIs print help successfully. + + Manual merge gate: + - Build the candidate image from this branch. + - Run ClawScan with `CLAWSCAN_SANDBOX_IMAGE=clawscan-runtime:candidate`. + - Compare benchmark artifacts against the current runtime image. + - Include SkillTrustBench evidence before merge. + - Include OpenClaw Security Signals evidence when ClawHub profile behavior is affected. + - Explain any verdict drift, failure-rate change, or runtime regression. + EOF + + if gh pr view "$BRANCH" --json number >/dev/null 2>&1; then + gh pr edit "$BRANCH" --title "$TITLE" --body-file /tmp/runtime-tool-update-pr.md + else + gh pr create --base main --head "$BRANCH" --title "$TITLE" --body-file /tmp/runtime-tool-update-pr.md + fi diff --git a/docker/clawscan-runtime/Dockerfile b/docker/clawscan-runtime/Dockerfile index 8bd99670..8c99030a 100644 --- a/docker/clawscan-runtime/Dockerfile +++ b/docker/clawscan-runtime/Dockerfile @@ -1,5 +1,13 @@ FROM python:3.12-slim +ARG SKILLSPECTOR_REF=ab0431ff2a9e9d75ba866f986be17f8600cfd086 +ARG CISCO_AI_SKILL_SCANNER_VERSION=2.0.12 +ARG SNYK_AGENT_SCAN_VERSION=0.5.12 +ARG CLAUDE_CODE_VERSION=2.1.193 +ARG OPENAI_CODEX_VERSION=0.142.2 +ARG AGENTVERUS_SCANNER_VERSION=0.8.1 +ARG SOCKET_CLI_VERSION=1.1.129 + ENV PATH="/root/.local/bin:${PATH}" \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ PYTHONUNBUFFERED=1 @@ -12,11 +20,15 @@ RUN apt-get update \ RUN python -m pip install --no-cache-dir --upgrade pip uv \ && python -m pip install --no-cache-dir \ - "git+https://github.com/NVIDIA/skillspector.git" \ - "cisco-ai-skill-scanner" \ - && uv tool install "snyk-agent-scan@latest" \ + "git+https://github.com/NVIDIA/skillspector.git@${SKILLSPECTOR_REF}" \ + "cisco-ai-skill-scanner==${CISCO_AI_SKILL_SCANNER_VERSION}" \ + && uv tool install "snyk-agent-scan==${SNYK_AGENT_SCAN_VERSION}" \ && ln -sf /root/.local/bin/snyk-agent-scan /usr/local/bin/snyk-agent-scan -RUN npm install -g @anthropic-ai/claude-code @openai/codex agentverus-scanner socket +RUN npm install -g \ + "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" \ + "@openai/codex@${OPENAI_CODEX_VERSION}" \ + "agentverus-scanner@${AGENTVERUS_SCANNER_VERSION}" \ + "socket@${SOCKET_CLI_VERSION}" WORKDIR /workspace diff --git a/docs/development.md b/docs/development.md index fb5dcc7a..700df465 100644 --- a/docs/development.md +++ b/docs/development.md @@ -40,6 +40,34 @@ docker run --rm clawscan-runtime:dev claude --help docker run --rm clawscan-runtime:dev skillspector --help ``` +## Runtime Tool Updates + +The runtime image pins scanner and judge-tool versions in +`docker/clawscan-runtime/Dockerfile`. Do not float these installs to `latest`: +runtime tool changes can alter scanner output, judge behavior, runtime, and +failure rate. + +The `Runtime Tool Updates` workflow runs monthly, updates the pinned versions, +builds the candidate image, runs CLI smoke checks, and opens a PR. That PR must +not be auto-merged from smoke checks alone. + +Before merging a runtime-tool update PR, run a benchmark comparison from the PR +branch and attach the result artifacts or summary to the PR: + +```bash +docker build -t clawscan-runtime:candidate docker/clawscan-runtime + +CLAWSCAN_SANDBOX_IMAGE=clawscan-runtime:candidate \ +go run ./cmd/clawscan \ + --benchmark SkillTrustBench \ + --scanner clawscan-static \ + --output /tmp/clawscan-skilltrustbench-candidate.json +``` + +For ClawHub-affecting changes, also compare the OpenClaw Security Signals +benchmark or the relevant ClawHub profile benchmark path. Explain any verdict +drift, scanner failures, or runtime regression before merge. + ## Docs Site The docs site is generated from Markdown in `docs/`: diff --git a/scripts/update-runtime-tool-versions.mjs b/scripts/update-runtime-tool-versions.mjs new file mode 100644 index 00000000..c7cf2f08 --- /dev/null +++ b/scripts/update-runtime-tool-versions.mjs @@ -0,0 +1,94 @@ +import { execFileSync } from 'node:child_process'; +import { readFile, writeFile } from 'node:fs/promises'; + +const dockerfilePath = new URL('../docker/clawscan-runtime/Dockerfile', import.meta.url); + +const pins = [ + { + arg: 'SKILLSPECTOR_REF', + latest: () => gitHead('https://github.com/NVIDIA/skillspector.git'), + }, + { + arg: 'CISCO_AI_SKILL_SCANNER_VERSION', + latest: () => pypiVersion('cisco-ai-skill-scanner'), + }, + { + arg: 'SNYK_AGENT_SCAN_VERSION', + latest: () => pypiVersion('snyk-agent-scan'), + }, + { + arg: 'CLAUDE_CODE_VERSION', + latest: () => npmVersion('@anthropic-ai/claude-code'), + }, + { + arg: 'OPENAI_CODEX_VERSION', + latest: () => npmVersion('@openai/codex'), + }, + { + arg: 'AGENTVERUS_SCANNER_VERSION', + latest: () => npmVersion('agentverus-scanner'), + }, + { + arg: 'SOCKET_CLI_VERSION', + latest: () => npmVersion('socket'), + }, +]; + +let dockerfile = await readFile(dockerfilePath, 'utf8'); +let changed = false; + +for (const pin of pins) { + const latest = await pin.latest(); + const pattern = new RegExp(`^ARG ${pin.arg}=([^\\n]+)$`, 'm'); + const match = dockerfile.match(pattern); + if (!match) { + throw new Error(`Missing ${pin.arg} in ${dockerfilePath.pathname}`); + } + const current = match[1].trim(); + if (current === latest) { + console.log(`${pin.arg}: ${current} unchanged`); + continue; + } + console.log(`${pin.arg}: ${current} -> ${latest}`); + dockerfile = dockerfile.replace(pattern, `ARG ${pin.arg}=${latest}`); + changed = true; +} + +if (changed) { + await writeFile(dockerfilePath, dockerfile); +} else { + console.log('Runtime tool pins are already current.'); +} + +async function npmVersion(name) { + const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`); + if (!response.ok) { + throw new Error(`npm metadata fetch failed for ${name}: ${response.status} ${response.statusText}`); + } + const metadata = await response.json(); + if (!metadata.version) { + throw new Error(`npm metadata missing version for ${name}`); + } + return metadata.version; +} + +async function pypiVersion(name) { + const response = await fetch(`https://pypi.org/pypi/${encodeURIComponent(name)}/json`); + if (!response.ok) { + throw new Error(`PyPI metadata fetch failed for ${name}: ${response.status} ${response.statusText}`); + } + const metadata = await response.json(); + if (!metadata.info?.version) { + throw new Error(`PyPI metadata missing version for ${name}`); + } + return metadata.info.version; +} + +function gitHead(repo) { + const output = execFileSync('git', ['ls-remote', repo, 'HEAD'], { encoding: 'utf8' }).trim(); + const [sha] = output.split(/\s+/); + if (!/^[0-9a-f]{40}$/i.test(sha)) { + throw new Error(`Could not resolve HEAD for ${repo}: ${output}`); + } + return sha; +} From b2c48f2c6652ee0982b41384950448a592fa6bfc Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 26 Jun 2026 13:16:59 -0700 Subject: [PATCH 5/5] ci: make security signals publish manual only --- .../workflows/publish-security-signals-results.yml | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/.github/workflows/publish-security-signals-results.yml b/.github/workflows/publish-security-signals-results.yml index 6657f214..7156d47b 100644 --- a/.github/workflows/publish-security-signals-results.yml +++ b/.github/workflows/publish-security-signals-results.yml @@ -2,17 +2,6 @@ name: Publish Security Signals results on: workflow_dispatch: - push: - branches: - - main - - 'pe/**' - paths: - - '.github/workflows/publish-security-signals-results.yml' - - 'cmd/clawscan/**' - - 'internal/**' - - 'leaderboard/submissions/**' - - 'scripts/publish-security-signals-results.sh' - - 'scripts/validate-security-signals-submissions.sh' permissions: contents: read