feat(security): stop executing code from scanned repositories (#257)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 5m46s

Most of the pipeline reads customer code. Four stages ran it — inside the
agent container, as root, with the Mongo URI, the Keycloak and registry client
secrets and the LLM key in the environment, and a database user that reaches
every tenant:

- `cargo clippy` compiles the repo, so its `build.rs` and proc macros run;
- ESLint is executed from the repo's own `node_modules/.bin`, and its config
  files are JavaScript;
- `pip-compile` builds source distributions to read metadata, running `setup.py`;
- the firmware reproducible build shells out to Nix with `sandbox = false`.

Scanning hostile code is the job, so new `compliance_core::ExecPolicy` gates
all four. It is off by default and a hardened deployment ignores the
`PW_ALLOW_UNTRUSTED_CODE_EXEC` opt-out, which stays for single-tenant and
sandboxed deployments. Dependency resolution is unaffected: npm already runs
`--package-lock-only --ignore-scripts`, and `cargo generate-lockfile` and
`cargo metadata` resolve without compiling. A complete firmware SBOM comes from
an imported Firmwerk bundle (#280) instead of a build here.

Every external tool now spawns through `pipeline::tool_cmd`:

- an empty environment plus a named allowlist (PATH, HOME, TMPDIR, LANG, and a
  tool's own cache variables), so semgrep, syft, gitleaks, ruff, cargo and npm
  no longer inherit the agent's credentials;
- `kill_on_drop`, because a tokio child outlives its timeout otherwise — the
  comment claiming a timed-out scanner was SIGKILLed was wrong;
- a bounded run for the lockfile and metadata commands, which had no timeout.

Part of #253 · MVP-0 safety baseline.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
Sharang ParnerkarandClaude Opus 5 committed 2026-09-21 08:53:44 +02:00
1 parent cc3a9c7130
commit bf89e57b58
17 files changed
+458 -89

No files matched your search

+9
View File
@@ -114,6 +114,15 @@ BREAKPILOT_SNAPSHOT_DIR=/data/compliance-scanner/oscal
# BREAKPILOT_SEMANTIC_MAPPING=false
# BREAKPILOT_GROUNDED_CHECKS=true
# Execute code from the repositories being scanned? A few stages do: cargo
# clippy compiles the repo (build.rs, proc macros), ESLint runs from the repo's
# own node_modules, pip-compile builds sdists (setup.py), and the firmware
# reproducible build shells out to Nix with sandbox=false. They are OFF unless
# this is set, and a staging/production APP_ENV ignores it — the agent holds
# every tenant's data. Firmware SBOMs come from an imported Firmwerk bundle
# instead.
# PW_ALLOW_UNTRUSTED_CODE_EXEC=1
# Deployment feature flags (comma list). `source_only` = static analysis only:
# the scan pipeline skips DAST, pentest, the ICS probe and the ephemeral PLC
# runtime (recorded as skipped stages, not failures), and the dashboard hides
+18 -4
View File
@@ -15,6 +15,7 @@
use std::path::Path;
use compliance_core::models::{SbomEntry, TargetType};
use compliance_core::ExecPolicy;
use firmwerk_repro::ReproBackend;
use firmwerk_sbom::ComponentKind;
@@ -29,13 +30,14 @@ pub fn is_firmware_target(target_type: TargetType) -> bool {
/// Build SBOM entries for a firmware target from its source tree. Prefers a full
/// reproducible build (sealed lock); falls back to analysis-only. Returns an
/// empty vector when tramiton cannot even form a build plan.
pub async fn firmware_sbom_entries(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
pub async fn firmware_sbom_entries(path: &Path, repo_id: &str, exec: ExecPolicy) -> Vec<SbomEntry> {
let p = path.to_path_buf();
let repo = repo_id.to_string();
let allow_build = exec.untrusted_code_allowed();
// The whole analyze → seal → build → render sequence is blocking (it shells
// out to nix), so keep it off the async runtime. Bound it: a firmware build
// that hangs must not wedge the scan (the orphaned task is abandoned).
let handle = tokio::task::spawn_blocking(move || build_sbom_blocking(&p, &repo));
let handle = tokio::task::spawn_blocking(move || build_sbom_blocking(&p, &repo, allow_build));
match tokio::time::timeout(std::time::Duration::from_secs(900), handle).await {
Ok(Ok(entries)) => entries,
Ok(Err(e)) => {
@@ -49,7 +51,7 @@ pub async fn firmware_sbom_entries(path: &Path, repo_id: &str) -> Vec<SbomEntry>
}
}
fn build_sbom_blocking(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
fn build_sbom_blocking(path: &Path, repo_id: &str, allow_build: bool) -> Vec<SbomEntry> {
let repo = firmwerk_core::Repo::new(path);
let plan = match firmwerk_core::provider::analyze(&repo) {
Ok(Some(bp)) => bp,
@@ -61,7 +63,19 @@ fn build_sbom_blocking(path: &Path, repo_id: &str) -> Vec<SbomEntry> {
};
// Phase 2: reproducible build → sealed lock → complete SBOM.
if let Some(backend) = firmwerk_repro::NixBackend::detect() {
//
// The build runs the repository's own build system through Nix with
// `sandbox = false`, i.e. arbitrary tenant code inside the agent. Where that
// is not allowed we stop at analysis-only; the complete firmware SBOM comes
// from an imported Firmwerk bundle instead, which is built on the
// customer's side.
if !allow_build {
tracing::info!(
repo_id,
"Firmware SBOM: reproducible build skipped (it executes the repository's build \
system); import a Firmwerk bundle for a complete firmware SBOM"
);
} else if let Some(backend) = firmwerk_repro::NixBackend::detect() {
match firmwerk_repro::seal_and_build(&backend, &plan, path) {
Ok(lock) => {
let mut sbom = firmwerk_sbom::Sbom::from_lock(&lock, repo_id);
+1 -1
View File
@@ -21,7 +21,7 @@ impl Scanner for GitleaksScanner {
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let output = tokio::time::timeout(
std::time::Duration::from_secs(300),
tokio::process::Command::new("gitleaks")
crate::pipeline::tool_cmd::tool("gitleaks", &[])
.args([
"detect",
"--source",
+22 -19
View File
@@ -2,31 +2,34 @@ use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::CoreError;
use tokio::process::Command;
use crate::pipeline::dedup;
use super::run_with_timeout;
pub(super) async fn run_clippy(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
let child = Command::new("cargo")
.args([
"clippy",
"--message-format=json",
"--quiet",
"--",
"-W",
"clippy::all",
])
.current_dir(repo_path)
.env("RUSTC_WRAPPER", "")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| CoreError::Scanner {
scanner: "clippy".to_string(),
source: Box::new(e),
})?;
let child = crate::pipeline::tool_cmd::tool_in(
"cargo",
repo_path,
crate::pipeline::tool_cmd::CARGO_ENV,
)
.args([
"clippy",
"--message-format=json",
"--quiet",
"--",
"-W",
"clippy::all",
])
.current_dir(repo_path)
.env("RUSTC_WRAPPER", "")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| CoreError::Scanner {
scanner: "clippy".to_string(),
source: Box::new(e),
})?;
let output = run_with_timeout(child, "clippy").await?;
let stdout = String::from_utf8_lossy(&output.stdout);
+14 -11
View File
@@ -2,7 +2,6 @@ use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::CoreError;
use tokio::process::Command;
use crate::pipeline::dedup;
@@ -11,16 +10,20 @@ use super::run_with_timeout;
pub(super) async fn run_eslint(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
// Use the project-local eslint binary directly, not npx (which can hang downloading)
let eslint_bin = repo_path.join("node_modules/.bin/eslint");
let child = Command::new(eslint_bin)
.args([".", "--format", "json", "--no-error-on-unmatched-pattern"])
.current_dir(repo_path)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| CoreError::Scanner {
scanner: "eslint".to_string(),
source: Box::new(e),
})?;
let child = crate::pipeline::tool_cmd::tool_in(
eslint_bin,
repo_path,
crate::pipeline::tool_cmd::NPM_ENV,
)
.args([".", "--format", "json", "--no-error-on-unmatched-pattern"])
.current_dir(repo_path)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| CoreError::Scanner {
scanner: "eslint".to_string(),
source: Box::new(e),
})?;
let output = run_with_timeout(child, "eslint").await?;
+63 -8
View File
@@ -7,12 +7,24 @@ use std::time::Duration;
use compliance_core::models::ScanType;
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use compliance_core::{CoreError, ExecPolicy};
/// Timeout for each individual lint command
pub(crate) const LINT_TIMEOUT: Duration = Duration::from_secs(120);
pub struct LintScanner;
/// Language linters. Two of the three run code from the repository itself —
/// clippy compiles it (`build.rs`, proc macros) and ESLint is the repo's own
/// binary with JavaScript config — so they are gated on [`ExecPolicy`]. Ruff
/// only parses, and always runs.
pub struct LintScanner {
exec: ExecPolicy,
}
impl LintScanner {
pub fn new(exec: ExecPolicy) -> Self {
Self { exec }
}
}
impl Scanner for LintScanner {
fn name(&self) -> &str {
@@ -29,16 +41,24 @@ impl Scanner for LintScanner {
// Detect which languages are present and run appropriate linters
if has_rust_project(repo_path) {
match clippy::run_clippy(repo_path, repo_id).await {
Ok(findings) => all_findings.extend(findings),
Err(e) => tracing::warn!("Clippy failed: {e}"),
if self.exec.untrusted_code_allowed() {
match clippy::run_clippy(repo_path, repo_id).await {
Ok(findings) => all_findings.extend(findings),
Err(e) => tracing::warn!("Clippy failed: {e}"),
}
} else {
tracing::info!("{}", self.exec.skip_reason("cargo clippy"));
}
}
if has_js_project(repo_path) {
match eslint::run_eslint(repo_path, repo_id).await {
Ok(findings) => all_findings.extend(findings),
Err(e) => tracing::warn!("ESLint failed: {e}"),
if self.exec.untrusted_code_allowed() {
match eslint::run_eslint(repo_path, repo_id).await {
Ok(findings) => all_findings.extend(findings),
Err(e) => tracing::warn!("ESLint failed: {e}"),
}
} else {
tracing::info!("{}", self.exec.skip_reason("ESLint"));
}
}
@@ -95,3 +115,38 @@ pub(crate) async fn run_with_timeout(
}
}
}
#[cfg(test)]
mod tests {
use super::{has_js_project, has_rust_project, LintScanner};
use compliance_core::traits::Scanner;
use compliance_core::ExecPolicy;
/// A repo that would trigger both code-executing linters. The scan must
/// come back empty — and, more to the point, must not have compiled
/// anything — when the policy forbids executing tenant code.
#[tokio::test]
async fn code_executing_linters_are_skipped_without_the_policy() {
let dir = std::env::temp_dir().join(format!("cs-lint-gate-{}", std::process::id()));
let bin = dir.join("node_modules/.bin");
std::fs::create_dir_all(&bin).expect("mkdir");
std::fs::write(dir.join("Cargo.toml"), "[package]\nname=\"x\"\n").expect("cargo.toml");
std::fs::write(dir.join("package.json"), "{}").expect("package.json");
// A "linter" that would fail the test if it ever ran.
std::fs::write(bin.join("eslint"), "#!/bin/sh\nexit 3\n").expect("eslint stub");
assert!(has_rust_project(&dir) && has_js_project(&dir), "fixture");
let out = LintScanner::new(ExecPolicy::trusted_only())
.scan(&dir, "repo-1")
.await
.expect("scan");
assert!(
out.findings.is_empty(),
"clippy and eslint must not run: {:?}",
out.findings
);
std::fs::remove_dir_all(&dir).ok();
}
}
+1 -2
View File
@@ -2,14 +2,13 @@ use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::CoreError;
use tokio::process::Command;
use crate::pipeline::dedup;
use super::run_with_timeout;
pub(super) async fn run_ruff(repo_path: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
let child = Command::new("ruff")
let child = crate::pipeline::tool_cmd::tool_in("ruff", repo_path, &[])
.args(["check", ".", "--output-format", "json", "--exit-zero"])
.current_dir(repo_path)
.stdout(std::process::Stdio::piped())
+1
View File
@@ -15,4 +15,5 @@ mod pr_review;
pub mod repo_view;
pub mod sbom;
pub mod semgrep;
pub mod tool_cmd;
mod tracker_dispatch;
@@ -93,7 +93,8 @@ impl PipelineOrchestrator {
tracing::info!("[{repo_id}] Stage 2: SBOM Generation");
self.update_phase(scan_run_id, "sbom_generation").await;
let mut sbom_entries = match async {
let sbom_scanner = SbomScanner;
let sbom_scanner =
SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env));
sbom_scanner.scan(&repo_path, &repo_id).await
}
.instrument(tracing::info_span!("stage_sbom_generation"))
@@ -180,7 +181,7 @@ impl PipelineOrchestrator {
tracing::info!("[{repo_id}] Stage 4b: Lint Scanning");
self.update_phase(scan_run_id, "lint_scanning").await;
match async {
let lint = LintScanner;
let lint = LintScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env));
lint.scan(&repo_path, &repo_id).await
}
.instrument(tracing::info_span!("stage_lint_scanning"))
@@ -1028,9 +1029,12 @@ impl PipelineOrchestrator {
if crate::pipeline::firmware_sbom::is_firmware_target(target.target_type) {
if let Some(code) = target.code_artifact() {
if let Some(path) = working_paths.get(&code.id) {
let entries =
crate::pipeline::firmware_sbom::firmware_sbom_entries(path, target_id)
.await;
let entries = crate::pipeline::firmware_sbom::firmware_sbom_entries(
path,
target_id,
compliance_core::ExecPolicy::from_env(self.config.app_env),
)
.await;
if !entries.is_empty() {
let _ = self
.db
@@ -18,16 +18,23 @@ pub(super) async fn run_cargo_audit(
return Ok(Vec::new());
}
let output = tokio::process::Command::new("cargo")
// Reads Cargo.lock against the advisory DB; it does not build, so no
// `build.rs` runs. Bounded and stripped of the agent's environment.
let output = crate::pipeline::tool_cmd::run_bounded(
crate::pipeline::tool_cmd::tool_in(
"cargo",
repo_path,
crate::pipeline::tool_cmd::CARGO_ENV,
)
.args(["audit", "--json"])
.current_dir(repo_path)
.env("RUSTC_WRAPPER", "")
.output()
.await
.map_err(|e| CoreError::Scanner {
scanner: "cargo-audit".to_string(),
source: Box::new(e),
})?;
.env("RUSTC_WRAPPER", ""),
"cargo audit",
)
.await
.map_err(|e| CoreError::Scanner {
scanner: "cargo-audit".to_string(),
source: Box::new(e),
})?;
let result: CargoAuditOutput =
serde_json::from_slice(&output.stdout).unwrap_or_else(|_| CargoAuditOutput {
+52 -28
View File
@@ -5,9 +5,19 @@ use std::path::Path;
use compliance_core::models::{SbomEntry, ScanType, VulnRef};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use compliance_core::{CoreError, ExecPolicy};
pub struct SbomScanner;
use crate::pipeline::tool_cmd::{run_bounded, tool_in, CARGO_ENV, NPM_ENV};
pub struct SbomScanner {
exec: ExecPolicy,
}
impl SbomScanner {
pub fn new(exec: ExecPolicy) -> Self {
Self { exec }
}
}
impl Scanner for SbomScanner {
fn name(&self) -> &str {
@@ -23,7 +33,7 @@ impl Scanner for SbomScanner {
let mut entries = Vec::new();
// Generate missing lock files so Syft can resolve the full dependency tree
generate_lockfiles(repo_path).await;
generate_lockfiles(repo_path, self.exec).await;
// Run syft for SBOM generation
match syft::run_syft(repo_path, repo_id).await {
@@ -50,16 +60,19 @@ impl Scanner for SbomScanner {
/// Generate missing lock files so Syft can resolve the full dependency tree.
/// This handles repos that gitignore their lock files (common for Rust libraries).
#[tracing::instrument(skip_all)]
async fn generate_lockfiles(repo_path: &Path) {
async fn generate_lockfiles(repo_path: &Path, exec: ExecPolicy) {
// Cargo: generate Cargo.lock if Cargo.toml exists without it
if repo_path.join("Cargo.toml").exists() && !repo_path.join("Cargo.lock").exists() {
tracing::info!("generating Cargo.lock for SBOM scan");
let result = tokio::process::Command::new("cargo")
.args(["generate-lockfile"])
.current_dir(repo_path)
.env("RUSTC_WRAPPER", "")
.output()
.await;
// Resolution only: this reads manifests and the registry index, it does
// not compile, so no `build.rs` runs.
let result = run_bounded(
tool_in("cargo", repo_path, CARGO_ENV)
.args(["generate-lockfile"])
.env("RUSTC_WRAPPER", ""),
"cargo generate-lockfile",
)
.await;
match result {
Ok(o) if o.status.success() => tracing::info!("Cargo.lock generated"),
Ok(o) => tracing::warn!(
@@ -81,17 +94,21 @@ async fn generate_lockfiles(repo_path: &Path) {
if has_pip_manifest && !has_pip_lock {
// Try pip-compile (pip-tools) first, fall back to pip freeze approach
tracing::info!("attempting to generate pip requirements for SBOM scan");
if repo_path.join("pyproject.toml").exists() {
let result = tokio::process::Command::new("pip-compile")
.args([
// pip-compile builds source distributions to read their metadata,
// which executes the project's own `setup.py`.
if repo_path.join("pyproject.toml").exists() && !exec.untrusted_code_allowed() {
tracing::info!("{}", exec.skip_reason("pip-compile"));
} else if repo_path.join("pyproject.toml").exists() {
let result = run_bounded(
tool_in("pip-compile", repo_path, &[]).args([
"--quiet",
"--output-file",
"requirements.txt",
"pyproject.toml",
])
.current_dir(repo_path)
.output()
.await;
]),
"pip-compile",
)
.await;
match result {
Ok(o) if o.status.success() => {
tracing::info!("requirements.txt generated via pip-compile")
@@ -109,11 +126,17 @@ async fn generate_lockfiles(repo_path: &Path) {
|| repo_path.join("pnpm-lock.yaml").exists();
if repo_path.join("package.json").exists() && !has_npm_lock {
tracing::info!("generating package-lock.json for SBOM scan");
let result = tokio::process::Command::new("npm")
.args(["install", "--package-lock-only", "--ignore-scripts"])
.current_dir(repo_path)
.output()
.await;
// `--package-lock-only --ignore-scripts`: resolve versions, write the
// lockfile, run none of the package's lifecycle scripts.
let result = run_bounded(
tool_in("npm", repo_path, NPM_ENV).args([
"install",
"--package-lock-only",
"--ignore-scripts",
]),
"npm install --package-lock-only",
)
.await;
match result {
Ok(o) if o.status.success() => tracing::info!("package-lock.json generated"),
Ok(o) => tracing::warn!(
@@ -138,12 +161,13 @@ async fn enrich_cargo_licenses(repo_path: &Path, entries: &mut [SbomEntry]) {
return;
}
let output = match tokio::process::Command::new("cargo")
.args(["metadata", "--format-version", "1"])
.current_dir(repo_path)
.env("RUSTC_WRAPPER", "")
.output()
.await
let output = match run_bounded(
tool_in("cargo", repo_path, CARGO_ENV)
.args(["metadata", "--format-version", "1"])
.env("RUSTC_WRAPPER", ""),
"cargo metadata",
)
.await
{
Ok(o) if o.status.success() => o,
Ok(o) => {
+1 -1
View File
@@ -7,7 +7,7 @@ use compliance_core::CoreError;
pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result<Vec<SbomEntry>, CoreError> {
let output = tokio::time::timeout(
std::time::Duration::from_secs(300),
tokio::process::Command::new("syft")
crate::pipeline::tool_cmd::tool("syft", &["SYFT_CACHE_DIR"])
.arg(repo_path)
.args(["-o", "cyclonedx-json"])
.env("SYFT_GOLANG_SEARCH_REMOTE_LICENSES", "true")
+3 -1
View File
@@ -44,7 +44,9 @@ impl Scanner for SemgrepScanner {
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let cra_rules = stage_cra_rules().await;
let mut command = tokio::process::Command::new("semgrep");
// Empty environment + kill-on-drop: semgrep only needs to find itself
// and write temp files, and a timed-out run must actually die.
let mut command = crate::pipeline::tool_cmd::tool("semgrep", &["SEMGREP_RULES"]);
command.arg("--config=auto");
if let Some(path) = &cra_rules {
command.arg(format!("--config={}", path.display()));
+117
View File
@@ -0,0 +1,117 @@
//! How the pipeline spawns an external tool.
//!
//! Every scanner shells out — semgrep, syft, gitleaks, ruff, cargo, npm. Two
//! things used to be true of all of them and should not be:
//!
//! 1. **They inherited the agent's whole environment.** That environment holds
//! the Mongo URI with its password, the Keycloak client secret, the registry
//! client secret, the LiteLLM key, the NVD key. A tool that reads its own
//! environment — or any code it runs — could read all of it. Here each tool
//! starts from an empty environment and gets back only what it needs.
//!
//! 2. **A timed-out tool kept running.** `wait_with_output` was wrapped in a
//! timeout, but dropping a tokio `Child` does not kill the process unless
//! `kill_on_drop` is set, so a hung semgrep survived its own timeout and
//! kept its CPU and memory. Every command built here sets it.
use std::path::Path;
use std::time::Duration;
use tokio::process::Command;
/// Environment a tool gets regardless: enough to find its own installation,
/// write temporary files and format output.
const BASE_ENV: &[&str] = &["PATH", "HOME", "LANG", "LC_ALL", "TZ", "TMPDIR"];
/// Build a command for an external tool: an empty environment plus
/// [`BASE_ENV`], killed when dropped.
///
/// `extra_env` names further variables to pass through — a tool's own cache or
/// registry configuration (`CARGO_HOME`, `NPM_CONFIG_CACHE`). Name variables,
/// never values, so a secret cannot be added by accident.
pub fn tool(program: impl AsRef<std::ffi::OsStr>, extra_env: &[&str]) -> Command {
let mut cmd = Command::new(program);
cmd.env_clear();
for key in BASE_ENV.iter().chain(extra_env.iter()) {
if let Ok(val) = std::env::var(key) {
cmd.env(key, val);
}
}
cmd.kill_on_drop(true);
cmd
}
/// A tool run inside a repository checkout.
pub fn tool_in(
program: impl AsRef<std::ffi::OsStr>,
repo_path: &Path,
extra_env: &[&str],
) -> Command {
let mut cmd = tool(program, extra_env);
cmd.current_dir(repo_path);
cmd
}
/// Run a command to completion under `timeout`, killing it if it overruns.
///
/// The kill is what `kill_on_drop` on [`tool`] buys: without it a timed-out
/// child kept running, holding its CPU, memory and clone directory.
pub async fn run_bounded_for(
cmd: &mut Command,
name: &str,
timeout: Duration,
) -> std::io::Result<std::process::Output> {
match tokio::time::timeout(timeout, cmd.output()).await {
Ok(result) => result,
Err(_) => Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!("{name} timed out after {}s", timeout.as_secs()),
)),
}
}
/// [`run_bounded_for`] with the default tool timeout (3 minutes).
pub async fn run_bounded(cmd: &mut Command, name: &str) -> std::io::Result<std::process::Output> {
run_bounded_for(cmd, name, DEFAULT_TOOL_TIMEOUT).await
}
/// How long a resolution / metadata tool may run before it is killed.
pub const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(180);
/// Variables a cargo invocation needs to find its toolchain and registry cache.
pub const CARGO_ENV: &[&str] = &["CARGO_HOME", "RUSTUP_HOME", "CARGO_NET_GIT_FETCH_WITH_CLI"];
/// Variables an npm invocation needs for its cache and registry configuration.
pub const NPM_ENV: &[&str] = &["NPM_CONFIG_CACHE", "NPM_CONFIG_REGISTRY", "NODE_PATH"];
#[cfg(test)]
mod tests {
use super::{tool, BASE_ENV};
#[test]
fn the_base_environment_is_a_name_allowlist_not_a_passthrough() {
// Nothing secret-shaped is in the allowlist. The point of the list is
// that adding a variable is a deliberate edit to this file.
for key in BASE_ENV {
let k = key.to_ascii_lowercase();
assert!(
!k.contains("secret")
&& !k.contains("token")
&& !k.contains("password")
&& !k.contains("key")
&& !k.contains("uri"),
"{key} should not be passed to external tools"
);
}
}
#[test]
fn a_built_command_carries_the_program_and_is_configured() {
// `Command`'s environment is not readable back, so assert on what we can
// see: the program, and that building one does not panic with a cleared
// environment plus extras.
let cmd = tool("semgrep", &["SEMGREP_RULES"]);
assert_eq!(cmd.as_std().get_program(), "semgrep");
assert!(cmd.as_std().get_envs().count() > 0, "allowlist applied");
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Whether this deployment may execute a tenant's code.
//!
//! Most of the scan pipeline only *reads* customer code: semgrep, gitleaks,
//! syft and the PLC parser parse files. A few stages instead **run** it, inside
//! the agent container, as root, with every secret in the process environment
//! and a Mongo user that can reach every tenant's database:
//!
//! * `cargo clippy` compiles the repo, so its `build.rs` and proc macros run;
//! * ESLint is executed from the repo's own `node_modules/.bin`, and its config
//! files are JavaScript;
//! * `pip-compile` builds source distributions to resolve metadata, which runs
//! `setup.py`;
//! * the firmware reproducible build shells out to Nix with `sandbox = false`.
//!
//! Scanning hostile code is the product's whole job, so those stages are off
//! wherever a deployment holds more than one tenant's data, and the findings
//! they produced (lint quality warnings, a firmware build SBOM) are worth less
//! than the blast radius. They return as sandboxed Werkbank jobs; firmware
//! SBOMs arrive as an imported Firmwerk bundle.
use crate::config::AppEnv;
/// Whether the tenant-code-executing stages may run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExecPolicy {
allow_untrusted_code: bool,
}
impl Default for ExecPolicy {
fn default() -> Self {
Self::trusted_only()
}
}
impl ExecPolicy {
/// Never execute tenant code.
pub fn trusted_only() -> Self {
Self {
allow_untrusted_code: false,
}
}
/// Execute it. Single-tenant local development, or a sandboxed runner whose
/// container is itself the boundary.
pub fn allow_untrusted_code() -> Self {
Self {
allow_untrusted_code: true,
}
}
/// Read the policy from the environment. `PW_ALLOW_UNTRUSTED_CODE_EXEC=1`
/// turns the stages back on, and a hardened deployment ignores it — there
/// the agent shares a process with other tenants' data.
pub fn from_env(app_env: AppEnv) -> Self {
let opted_in = std::env::var("PW_ALLOW_UNTRUSTED_CODE_EXEC")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
if opted_in && app_env.is_hardened() {
eprintln!(
"PW_ALLOW_UNTRUSTED_CODE_EXEC is ignored in a hardened deployment: \
clippy, ESLint, pip-compile and the Nix firmware build stay disabled"
);
}
Self {
allow_untrusted_code: opted_in && !app_env.is_hardened(),
}
}
/// Whether a stage that executes tenant code may run.
pub fn untrusted_code_allowed(self) -> bool {
self.allow_untrusted_code
}
/// The line to log when a stage is skipped, naming what to do instead.
pub fn skip_reason(self, stage: &str) -> String {
format!(
"{stage} executes code from the scanned repository and is disabled in this \
deployment (set PW_ALLOW_UNTRUSTED_CODE_EXEC=1 on a single-tenant or sandboxed \
deployment to enable it)"
)
}
}
#[cfg(test)]
mod tests {
use super::ExecPolicy;
#[test]
fn the_default_never_executes_tenant_code() {
assert!(!ExecPolicy::default().untrusted_code_allowed());
assert!(!ExecPolicy::trusted_only().untrusted_code_allowed());
assert!(ExecPolicy::allow_untrusted_code().untrusted_code_allowed());
}
#[test]
fn the_skip_reason_names_the_stage_and_the_escape_hatch() {
let r = ExecPolicy::trusted_only().skip_reason("clippy");
assert!(r.starts_with("clippy "), "{r}");
assert!(r.contains("PW_ALLOW_UNTRUSTED_CODE_EXEC"), "{r}");
}
}
+2
View File
@@ -2,6 +2,7 @@ pub mod config;
pub mod control_check;
pub mod db;
pub mod error;
pub mod exec_policy;
pub mod models;
pub mod net_guard;
pub mod scan_matrix;
@@ -17,5 +18,6 @@ pub mod tenant_ctx;
pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfig};
pub use error::CoreError;
pub use exec_policy::ExecPolicy;
pub use net_guard::{NetGuard, NetGuardError};
pub use tenant::{OrgRole, TenantContext, TenantStatus};
+28
View File
@@ -81,6 +81,34 @@ address is refused.
aimed at `10.x` PLCs on purpose, so it sets `PW_ALLOW_PRIVATE_TARGETS=1`. A
hardened cloud deployment ignores that variable — it shares a network with the
platform's own services.
## What the scanner runs on your code
Nearly every stage only *reads* your code: Semgrep, gitleaks, Syft, Ruff and the
PLC parser parse files and never execute them. Four stages are different, because
the tool has to run the project to do its job:
| Stage | What it executes |
|---|---|
| `cargo clippy` | compiles the crate, so `build.rs` and proc macros run |
| ESLint | the repository's own `node_modules/.bin/eslint`, with JavaScript config files |
| `pip-compile` | builds source distributions to read their metadata, running `setup.py` |
| Firmware reproducible build | the project's build system, through Nix |
In a shared deployment those stages are **off**: the scanner holds many
tenants' data, and a lint warning is worth less than the blast radius of
running a stranger's build. Lockfile-based dependency resolution still happens —
npm runs with `--ignore-scripts`, and `cargo generate-lockfile` and
`cargo metadata` resolve without compiling — so your SBOM is unaffected. For a
complete firmware SBOM, build with Firmwerk on your side and import the bundle.
A single-tenant or sandboxed deployment can turn them on with
`PW_ALLOW_UNTRUSTED_CODE_EXEC=1`; a hardened deployment ignores it. The stages
return later as sandboxed Werkbank jobs.
Every external tool also runs with an empty environment apart from a short
allowlist (`PATH`, `HOME`, `TMPDIR`, and its own cache variables), so the
agent's credentials are not visible to it, and it is killed when its timeout
expires.
## Deduplication and Fingerprinting