Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ inventory of all post-v1.1.0 changes.

### Added

- Confined local model execution (#72, F16): `forge suggest run` now executes
the consented adapter under OS confinement on macOS (deny-default Seatbelt
via `sandbox-exec`) and Linux (Landlock filesystem ruleset + seccomp-BPF
network deny), with verified-byte execution, cleared environment, bounded
output, and process-group cleanup on timeout or refusal. Execution fails
closed where no approved mechanism exists; Windows stays refused. Recorded-
response mode is unchanged. See `docs/local-model-confinement.md`. No new
dependencies.
- Local container packaging (#63): multi-stage Dockerfile with digest-pinned
bases and a non-root runtime, Docker Compose loopback workspace setup, and
container usage documentation (`docs/container.md`). No conversion or
Expand Down
119 changes: 119 additions & 0 deletions docs/local-model-confinement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Local model confinement boundary

`forge suggest run` can execute a consented local model executable
(`ProcessModelAdapter`) or replay a separately reviewed recorded response
(`--recorded-response`). Process execution is confined by the operating
system on macOS and Linux and **fails closed everywhere else**: if the
confinement mechanism cannot be established, FORGE refuses to run the adapter
rather than running it unconfined. This note records exactly what is confined,
the platform limitations, and how to verify the boundary.

The design was approved Unix-first in the owner decision record of 2026-11-13
(ticket #72 / F16). Windows remains refused pending a separate `windows-sys`
PRD 069 approval; no Windows confinement is implemented or claimed.

## What is confined

On both supported platforms the adapter child:

- runs with a **cleared environment** (`env_clear`);
- is bound to **verified bytes**: the executable is re-hashed immediately
before spawn and refused if it differs from the consented
`executable_sha256`;
- leads a **fresh process group**, so a timeout or refusal kills every
descendant with one `killpg`, not just the leader;
- has **bounded stdout/stderr** (8 MiB / 64 KiB); an over-bound stream is a
refusal, never a silent truncation;
- must finish within the requested `--timeout`; descendants holding the pipes
open cannot extend it. After a kill, pipe draining is bounded by a short
grace period: a reader still blocked by an escaped descendant is detached
(not joined forever), and the scratch directory is kept rather than recycled
so a surviving descendant cannot write into a reused path.

### macOS — Seatbelt via `sandbox-exec`

The child is spawned through `/usr/bin/sandbox-exec` with a deny-default
profile. The profile allows:

- read of the executable, its ancestor directories (path traversal), and the
system runtime (`/usr/lib`, `/bin`, `/usr/bin`, `/System`, the dyld cache
locations, `/dev/fd`);
- read/write of `/dev/null`, `/dev/zero`, `/dev/random`, `/dev/urandom`,
`/dev/tty`, `/dev/dtracehelper`;
- read/write of one private per-invocation scratch directory;
- `process*`, `signal`, `sysctl-read`, `mach*` (needed to launch and run).

Everything else — including **all network access** and any file outside the
allowlist — is denied. The profile is inherited by every descendant. If
`sandbox-exec` is absent the adapter fails closed.

### Linux — Landlock + seccomp-BPF

Before `exec`, the child installs (via `libc`, no new dependency):

- a **Landlock** filesystem ruleset (kernel ≥ 5.13) allowing read/execute of
the executable, read/execute of the runtime directories and linker cache,
read/write of the null/zero/random devices, and read/write/create within the
private scratch directory. All other filesystem access is denied. On a
kernel without Landlock the adapter refuses with a clear error.
- a **seccomp-BPF** filter that returns `EPERM` for every socket-creating
syscall (`socket`, `socketpair`, the `io_uring_*` family, and `socketcall`
on i386),
kills the process on a foreign ABI or the x32 syscall range, and allows the
rest. This blocks network egress including the `io_uring` bypass. The filter
is inherited across `fork`/`exec`.

`no_new_privs` is set first, as both mechanisms require it. The seccomp policy
is defined for x86-64 and aarch64; other Linux architectures fail closed.

## What is NOT confined

The boundary is **filesystem and network only**. CPU time, memory, and process
count are not limited, and the executable runs with the operator's own user
identity inside the sandbox. A malicious model can still consume resources
until the timeout kills its group. Treat the executable as trusted code that
is being prevented from reaching data and networks it was not consented to,
not as a defense against arbitrary hostile computation.

## Platform limitations

- **Windows**: refused (`PROCESS_EXECUTION_UNAVAILABLE`). No mechanism is
implemented; a separate `windows-sys` approval is deferred.
- **Linux kernels < 5.13** (or Landlock disabled): refused with a clear
"Landlock is unavailable" error.
- **Linux containers with a blocking seccomp profile** (e.g. the Docker
default profile, which denies the `landlock_*` syscalls): the adapter fails
closed. To exercise confinement in such a container, run with
`--security-opt seccomp=unconfined` or a profile that permits the Landlock
syscalls; FORGE does not weaken confinement to accommodate the container.
- **macOS without `/usr/bin/sandbox-exec`**: refused.
- **Linux architectures other than x86-64/aarch64**: refused (no approved
seccomp policy).

## How to verify

The integration suite `tests/suggest_confinement_test.rs` exercises the
boundary on each platform (gated by `cfg`):

```bash
cargo test --test suggest_confinement_test
```

It asserts: a replaced or deleted executable is refused before spawn; a
confined child cannot read or write outside the allowlist; a confined child
cannot create a socket or reach a listening socket (with an unconfined control
proving the listener is reachable); the exact payload is delivered; a timeout
kills every descendant; a pipe-holding descendant cannot extend the timeout;
and over-bound output and non-zero exits are refused. On hosts where the
mechanism is unavailable the tests assert the fail-closed refusal instead.

To verify manually on Linux in Docker:

```bash
docker run --rm --security-opt seccomp=unconfined \
-v "$PWD":/w -w /w rust:1.90-bookworm \
cargo test --test suggest_confinement_test
```

Recorded-response mode (`--recorded-response`) never spawns a process and is
unaffected by any of the above.
4 changes: 2 additions & 2 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1916,7 +1916,7 @@ pub enum SuggestCommand {
#[arg(long, value_enum, default_value_t = AuthorReportFormat::Text)]
format: AuthorReportFormat,
},
/// Import a recorded response for a consented payload (process execution is disabled)
/// Run the consented adapter under OS confinement, or import a recorded response
Run {
/// The prepared forge.suggest-request/1 document
#[arg(long)]
Expand All @@ -1933,7 +1933,7 @@ pub enum SuggestCommand {
/// Adapter timeout in seconds
#[arg(long, default_value_t = crate::suggest::run::DEFAULT_TIMEOUT_SECS)]
timeout: u64,
/// Import a recorded response; required while process execution is disabled
/// Import a recorded response instead of running the confined adapter
#[arg(long)]
recorded_response: Option<PathBuf>,
/// Print text or versioned JSON to stdout
Expand Down
58 changes: 41 additions & 17 deletions src/suggest/adapter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! Recorded-response adapters and a fail-closed process boundary.
//! Recorded-response adapters and a confined process boundary.
//!
//! Process execution is unavailable until FORGE can enforce filesystem and
//! network confinement, bind execution to verified bytes, and own descendants
//! on every supported platform. A local executable is not itself a sandbox.
//! On macOS and Linux a process adapter runs under OS filesystem/network
//! confinement (Seatbelt or Landlock+seccomp), bound to verified bytes, with
//! every descendant owned by FORGE. Where no approved mechanism exists the
//! adapter fails closed; a local executable is not itself a sandbox. See
//! `docs/local-model-confinement.md` for the exact boundary.

use std::path::{Path, PathBuf};
use std::time::Duration;
Expand All @@ -13,8 +15,9 @@ use super::request::MAX_ARG_BYTES;
use super::response::MAX_RESPONSE_BYTES;
use super::shared;

/// Why the process adapter cannot execute, shared by CLI and library callers.
pub const PROCESS_EXECUTION_UNAVAILABLE: &str = "process adapter execution is disabled until OS filesystem/network confinement, verified-byte execution and process-tree cleanup are available; use --recorded-response with a separately reviewed response file";
/// Why the process adapter cannot execute on platforms without an approved
/// confinement mechanism, shared by CLI and library callers.
pub const PROCESS_EXECUTION_UNAVAILABLE: &str = "process adapter execution is disabled on this platform: no approved OS filesystem/network confinement mechanism exists; use --recorded-response with a separately reviewed response file";

/// Read a local executable the operator named, following symlinks to the file.
///
Expand All @@ -31,8 +34,8 @@ pub(in crate::suggest) fn read_executable(
path: &Path,
max: u64,
) -> Result<Vec<u8>, crate::ForgeError> {
// Resolve shims for fingerprinting only. This digest does not authorize
// execution: invoke always refuses, including if this path is replaced.
// Resolve shims for fingerprinting. invoke re-reads the resolved bytes
// immediately before spawn and refuses any replacement.
let resolved = std::fs::canonicalize(path)?;
crate::io::read_bounded(&resolved, max)
}
Expand Down Expand Up @@ -68,11 +71,17 @@ pub trait LocalModelInvoke {
}
}

/// A fingerprinted local executable whose invocation currently fails closed.
/// A fingerprinted local executable executed under OS confinement.
///
/// Invocation re-verifies the executable bytes, clears the environment, runs
/// the child under a deny-default filesystem/network sandbox in its own
/// process group, and kills the whole group on timeout or refusal. See
/// the `confinement` module and `docs/local-model-confinement.md`.
#[derive(Debug)]
pub struct ProcessModelAdapter {
executable: PathBuf,
executable_sha256: String,
argv: Vec<String>,
}

impl ProcessModelAdapter {
Expand All @@ -94,6 +103,7 @@ impl ProcessModelAdapter {
Ok(Self {
executable: executable.to_path_buf(),
executable_sha256: crate::hashing::sha256_hex(&bytes),
argv: argv.to_vec(),
})
}

Expand All @@ -105,10 +115,14 @@ impl ProcessModelAdapter {
}

impl LocalModelInvoke for ProcessModelAdapter {
fn invoke(&self, _payload: &[u8], _timeout: Duration) -> Result<AdapterOutput, ForgeError> {
// There is deliberately no spawn path or opt-out: env_clear and a
// pathname digest cannot enforce the promised isolation boundary.
Err(shared::error(PROCESS_EXECUTION_UNAVAILABLE))
fn invoke(&self, payload: &[u8], timeout: Duration) -> Result<AdapterOutput, ForgeError> {
super::confinement::invoke_confined(
&self.executable,
&self.executable_sha256,
&self.argv,
payload,
timeout,
)
}

fn executable_sha256(&self) -> Option<&str> {
Expand Down Expand Up @@ -178,15 +192,25 @@ mod tests {
}

#[test]
fn process_invocation_is_unavailable_on_every_platform_even_after_replacement() {
fn a_replaced_executable_is_refused_before_spawn() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("adapter");
std::fs::write(&path, b"placeholder executable").unwrap();
std::fs::write(&path, b"#!/bin/sh\ncat\n").unwrap();
let adapter = ProcessModelAdapter::new(&path, &[]).unwrap();
assert_eq!(adapter.executable(), path);
assert!(adapter.executable_sha256().is_some());
std::fs::remove_file(&path).unwrap();
// Even direct library callers cannot spawn or reopen a changed path.
std::fs::write(&path, b"#!/bin/sh\nprintf replaced\n").unwrap();
let error = adapter.invoke(b"private payload", Duration::from_secs(5)).unwrap_err();
assert!(error.to_string().contains("changed since it was fingerprinted"));
}

#[cfg(not(unix))]
#[test]
fn process_invocation_is_unavailable_without_an_approved_mechanism() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("adapter");
std::fs::write(&path, b"placeholder executable").unwrap();
let adapter = ProcessModelAdapter::new(&path, &[]).unwrap();
let error = adapter.invoke(b"private payload", Duration::ZERO).unwrap_err();
assert!(error.to_string().contains(PROCESS_EXECUTION_UNAVAILABLE));
}
Expand Down
Loading
Loading