Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,43 @@
# Sandbox integrity: scope and review contract
These checks currently emit telemetry only. Findings and preparation errors must
not change sandbox construction, permissions, approvals, or command execution.
Supported backends are Seatbelt, bubblewrap, and MXC; legacy Windows is out of scope.
## Responsibilities
- Backends supply complete dependency inventories and interpret the request's
original filesystem policy: resolve command temp directories and MXC volumes,
and reuse the backend's deny-glob expansion where enforcement expands globs.
- The runner prepares dependency facts and invokes each checker per dependency.
Checkers remain independent of inventories and telemetry.
Blocking work runs on the blocking pool with a five-second caller timeout.
Timeouts use the existing check metric (`dependency=preparation`, `outcome=error`,
`error_kind=timeout`). Late results are discarded; cancelling the blocking task
or its scanner subprocess is deferred.
- Telemetry derives bounded tags from the policy, dependency facts, and checker
results. Never emit paths, environment values, or error text.
A missing metrics client disables emission, never the checks themselves.
Use the process-global metrics client; separately injected clients in programs
embedding Codex are outside this phase's scope.
## Deliberate approximation
Honor the basic read/write/deny rules. Do not reconstruct native enforcement or
audit OS ACLs. Additional backend protections can produce false positives;
additional write grants (such as Seatbelt scratch access) can produce false
negatives. Backend glob/symlink nuances and writable hard-link aliases are not
fully modeled. The separate glob scan can differ from enforcement's snapshot.
Metrics describe observed checker outcomes, not accuracy or missed violations.
These are accepted limitations of this phase, not requests to duplicate backend
implementations. Review against this scope. Regressions in explicit policy
handling, executor context, or reporting remain actionable; this is not a blanket
exemption for false positives or false negatives.
## Eligibility
Skip `SandboxOverride::EscalatedSandboxWithRestrictions` before preparation or
telemetry: these approved escalations retain only deny-read restrictions.
An ordinary configured `:root = write` policy with denials is still checked.
Do not infer approval from policy shape.

View File

@@ -0,0 +1,159 @@
//! Exercise backend policy preparation and dependency discovery.
use super::backend;
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
#[cfg(target_os = "linux")]
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::sandbox::SandboxOverride;
use akode_sandboxing::FileContentsChecker;
use akode_sandboxing::SandboxExecRequest;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::fs;
use std::io;
#[test]
fn snapshot_denials_replace_patterns_including_an_empty_expansion() -> io::Result<()> {
let temp = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(temp.path())?.canonicalize()?;
let target = root.join("helper");
fs::write(&target, "fixture")?;
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(root.clone().into(), FileSystemAccessMode::Write),
deny_glob(format!("{}/*", root.display())),
]);
for (expanded, writable) in [(vec![], true), (vec![target.clone()], false)] {
let prepared = policy.clone().with_expanded_deny_globs(expanded);
let checker = FileContentsChecker::new(&prepared, &root)?;
assert_eq!(checker.check(&target)?.is_some(), writable);
}
Ok(())
}
pub(super) fn deny_glob(pattern: impl Into<String>) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: pattern.into(),
},
FileSystemAccessMode::Deny,
)
}
pub(super) fn sandbox_request(
cwd: &AbsolutePathBuf,
policy: &FileSystemSandboxPolicy,
) -> SandboxExecRequest {
SandboxExecRequest {
sandbox_override: SandboxOverride::NoOverride,
command: vec![cwd.join("not-executed").to_string_lossy().into_owned()],
cwd: PathUri::from_abs_path(cwd),
sandbox_policy_cwd: PathUri::from_abs_path(cwd),
env: Default::default(),
network: None,
network_environment_id: None,
sandbox: backend::SANDBOX_TYPE,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
permission_profile: PermissionProfile::from_runtime_permissions(
policy,
NetworkSandboxPolicy::Restricted,
),
arg0: None,
}
}
#[cfg(target_os = "linux")]
#[test]
fn dependency_inventory_uses_launcher_location_and_command_path() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(temp.path())?.canonicalize()?;
let cwd = root.join("command");
let tools = root.join("tools");
let bundled = tools.join("akode-resources/bwrap");
fs::create_dir(&cwd)?;
fs::create_dir(&tools)?;
fs::create_dir(tools.join("akode-resources"))?;
for path in [tools.join("bwrap"), tools.join("akode"), bundled.clone()] {
fs::write(&path, "fixture")?;
fs::set_permissions(&path, fs::Permissions::from_mode(/*mode*/ 0o755))?;
}
let launcher = cwd.join("sandbox-helper");
std::os::unix::fs::symlink(tools.join("akode"), &launcher)?;
let policy = FileSystemSandboxPolicy::restricted(vec![deny_glob("*.key")]);
let mut request = sandbox_request(&cwd, &policy);
request.command[0] = launcher.to_string_lossy().into_owned();
for path in ["../tools", ":../tools"] {
request.env.insert("PATH".to_owned(), path.to_owned());
let dependencies = backend::critical_dependencies(&request, &policy, &cwd)?
.into_iter()
.filter(|(name, _)| {
matches!(*name, "bundled_bwrap_candidate" | "system_bwrap_candidate")
})
.map(|(name, path)| path.and_then(fs::canonicalize).map(|path| (name, path)))
.collect::<io::Result<Vec<_>>>()?;
assert_eq!(
dependencies,
vec![
("bundled_bwrap_candidate", bundled.to_path_buf()),
(
"system_bwrap_candidate",
tools.join("bwrap").into_path_buf()
),
]
);
}
Ok(())
}
#[cfg(target_os = "linux")]
#[test]
fn policy_preparation_uses_command_tmpdir_and_home() -> io::Result<()> {
let temp = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(temp.path())?.canonicalize()?;
let cwd = root.join("command");
let home = root.join("home");
fs::create_dir(&cwd)?;
fs::create_dir(&home)?;
let denied = home.join("secret.key");
fs::write(&denied, "fixture")?;
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
FileSystemAccessMode::Write,
),
deny_glob("~/secret.*"),
]);
let mut request = sandbox_request(&cwd, &policy);
request
.env
.insert("HOME".to_owned(), home.to_string_lossy().into_owned());
for (tmpdir, expected) in [
("", None),
("scratch", Some(cwd.join("scratch"))),
("~/scratch", Some(home.join("scratch"))),
] {
request.env.insert("TMPDIR".to_owned(), tmpdir.to_owned());
let mut entries = expected
.into_iter()
.map(|path| FileSystemSandboxEntry::new(path.into(), FileSystemAccessMode::Write))
.collect::<Vec<_>>();
entries.push(FileSystemSandboxEntry::new(
denied.clone().into(),
FileSystemAccessMode::Deny,
));
assert_eq!(
backend::prepare_policy(&request, policy.clone(), &cwd)?,
FileSystemSandboxPolicy::restricted(entries),
);
}
Ok(())
}

View File

@@ -0,0 +1,117 @@
//! Discover bubblewrap dependencies separately from resolving configured policy rules.
use super::dependencies::Dependency;
use super::dependencies::codex_and_launcher_dependencies;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_sandboxing::SandboxExecRequest;
use akode_sandboxing::SandboxType;
use akode_shell_command::shell_detect::get_user_home_path;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use std::ffi::OsString;
use std::io;
use std::path::PathBuf;
pub(super) const SANDBOX_TYPE: SandboxType = SandboxType::LinuxSeccomp;
pub(super) const NAME: &str = "bubblewrap";
pub(super) fn critical_dependencies(
request: &SandboxExecRequest,
policy: &FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> io::Result<Vec<Dependency>> {
let command_cwd = request.cwd.to_abs_path()?;
let path = request
.env
.get("PATH")
.map(|path| {
std::env::join_paths(
std::env::split_paths(path).map(|entry| command_cwd.as_path().join(entry)),
)
})
.transpose()
.map_err(io::Error::other)?;
let mut dependencies = codex_and_launcher_dependencies(request);
if let Some(exe) = request.command.first()
&& let Some(bwrap) = akode_linux_sandbox::find_bundled_bwrap_for_exe(
&command_cwd.as_path().join(exe),
command_cwd.as_path(),
|key| request.env.get(key).map(OsString::from),
)
{
dependencies.push(("bundled_bwrap_candidate", Ok(bwrap.into_path_buf())));
}
if let Some(path) = &path
&& let Some(bwrap) = akode_sandboxing::find_executable_in_search_paths(
"bwrap",
std::env::split_paths(path),
command_cwd.as_path(),
policy,
cwd.as_path(),
)
{
// The launcher probes this executable even if it later uses its bundled copy.
dependencies.push(("system_bwrap_candidate", Ok(bwrap)));
}
Ok(dependencies)
}
pub(super) fn prepare_policy(
request: &SandboxExecRequest,
mut policy: FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> io::Result<FileSystemSandboxPolicy> {
let command_cwd = request.cwd.to_abs_path()?;
let needs_home = policy.entries.iter().any(|entry| match &entry.path {
FileSystemPath::GlobPattern { pattern } => pattern.starts_with('~'),
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
} => request
.env
.get("TMPDIR")
.is_some_and(|path| path.starts_with('~')),
FileSystemPath::Path { .. } | FileSystemPath::Special { .. } => false,
});
let prepare = || {
// The helper resolves :tmpdir from its filtered environment, not the executor's.
policy.entries.retain_mut(|entry| {
if matches!(
entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir
}
) {
let Some(tmpdir) = request.env.get("TMPDIR").filter(|path| !path.is_empty()) else {
return false;
};
entry.path =
AbsolutePathBuf::resolve_path_against_base(tmpdir, &command_cwd).into();
}
true
});
let patterns = policy.get_unreadable_globs_with_cwd(cwd.as_path());
if !patterns.is_empty() {
let paths = akode_linux_sandbox::expand_unreadable_globs(
&patterns,
cwd.as_path(),
policy.glob_scan_max_depth,
)
.map_err(io::Error::other)?;
policy = policy.with_expanded_deny_globs(paths);
}
Ok(policy)
};
if !needs_home {
return prepare();
}
let home = request
.env
.get("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
.or_else(get_user_home_path)
.ok_or_else(|| io::Error::other("could not resolve the command's home directory"))?;
AbsolutePathBufGuard::with_home_directory(&home, prepare)
}

View File

@@ -0,0 +1,40 @@
//! Shared inventory entries and filesystem facts, independent of any checker.
use akode_utils_absolute_path::AbsolutePathBuf;
use std::fs;
use std::io;
use std::path::PathBuf;
pub(super) type Dependency = (&'static str, io::Result<PathBuf>);
pub(super) struct DependencyTarget {
pub path: AbsolutePathBuf,
pub metadata: fs::Metadata,
pub resolved_path: Option<AbsolutePathBuf>,
}
impl DependencyTarget {
pub(super) fn inspect(path: io::Result<PathBuf>) -> io::Result<Self> {
let path = AbsolutePathBuf::from_absolute_path(path?)?;
Ok(Self {
metadata: fs::metadata(&path)?,
resolved_path: path.canonicalize().ok(),
path,
})
}
}
pub(super) fn codex_executable() -> Dependency {
("codex", std::env::current_exe())
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(super) fn codex_and_launcher_dependencies(
request: &akode_sandboxing::SandboxExecRequest,
) -> Vec<Dependency> {
let mut dependencies = vec![codex_executable()];
if let Some(exe) = request.command.first() {
dependencies.push(("sandbox_launcher", Ok(PathBuf::from(exe))));
}
dependencies
}

View File

@@ -0,0 +1,13 @@
#[cfg_attr(target_os = "linux", path = "bubblewrap.rs")]
#[cfg_attr(target_os = "macos", path = "seatbelt.rs")]
#[cfg_attr(target_os = "windows", path = "mxc.rs")]
mod backend;
mod dependencies;
mod runner;
mod telemetry;
pub use runner::run_integrity_checks;
#[cfg(test)]
#[path = "backend_tests.rs"]
mod backend_tests;

View File

@@ -0,0 +1,30 @@
//! Discover MXC dependencies separately from resolving configured policy rules.
use super::dependencies::Dependency;
use super::dependencies::codex_and_launcher_dependencies;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_sandboxing::SandboxExecRequest;
use akode_sandboxing::SandboxType;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::io;
pub(super) const SANDBOX_TYPE: SandboxType = SandboxType::WindowsMxc;
pub(super) const NAME: &str = "windows_mxc";
pub(super) fn critical_dependencies(
request: &SandboxExecRequest,
_policy: &FileSystemSandboxPolicy,
_cwd: &AbsolutePathBuf,
) -> io::Result<Vec<Dependency>> {
Ok(codex_and_launcher_dependencies(request))
}
pub(super) fn prepare_policy(
request: &SandboxExecRequest,
policy: FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> io::Result<FileSystemSandboxPolicy> {
let command_cwd = request.cwd.to_abs_path()?;
akode_mxc_sandbox::prepare_file_system_policy(policy, &request.env, cwd, command_cwd.as_path())
.map_err(io::Error::other)
}

View File

@@ -0,0 +1,86 @@
//! Prepare the policy and dependency facts, then run checks per dependency.
//! Results never affect execution. See AGENTS.md for scope and accepted approximations.
use super::backend;
use super::dependencies::DependencyTarget;
use super::telemetry::IntegrityMetrics;
use akode_otel::MetricsClient;
use akode_protocol::sandbox::SandboxOverride;
use akode_sandboxing::FileContentsChecker;
use akode_sandboxing::SandboxExecRequest;
use std::io;
use std::time::Duration;
use std::time::Instant;
const CHECK_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
/// Observe executor-local containment dependencies without affecting the launch.
/// Used by both exec-server and the legacy local execution path.
pub async fn run_integrity_checks(request: &SandboxExecRequest) {
run_checks_with_metrics(request, akode_otel::global().as_ref()).await;
}
async fn run_checks_with_metrics(request: &SandboxExecRequest, metrics: Option<&MetricsClient>) {
if request.sandbox != backend::SANDBOX_TYPE
|| request.sandbox_override == SandboxOverride::EscalatedSandboxWithRestrictions
{
return;
}
let policy = request.permission_profile.file_system_sandbox_policy();
if policy.has_full_disk_write_access() {
return;
}
let telemetry = IntegrityMetrics::new(metrics, backend::NAME, &policy);
let _timer = telemetry.start_timer();
let request = request.clone();
let started_at = Instant::now();
let work = tokio::task::spawn_blocking(move || {
let mut dependencies = Vec::new();
let prepared_at = Instant::now();
let prepared = (|| {
let cwd = request.sandbox_policy_cwd.to_abs_path()?;
dependencies = backend::critical_dependencies(&request, &policy, &cwd)?;
let policy = backend::prepare_policy(&request, policy, &cwd)?;
// An empty glob expansion can remove the last write restriction.
if policy.has_full_disk_write_access() {
return Ok(None);
}
FileContentsChecker::new(&policy, &cwd).map(Some)
})();
let preparation_duration = prepared_at.elapsed();
let mut checks = Vec::new();
if matches!(&prepared, Ok(None)) {
return (preparation_duration, true, checks);
}
for (dependency, path) in dependencies {
let target = DependencyTarget::inspect(path);
let result = match (&prepared, &target) {
(Ok(Some(checker)), Ok(target)) => Some(checker.check(&target.path)),
_ => None,
};
checks.push((dependency, target, result));
}
(preparation_duration, prepared.is_ok(), checks)
});
// Timing out stops waiting; running blocking work is intentionally not cancelled.
let result = match tokio::time::timeout(CHECK_TIMEOUT, work).await {
Ok(result) => result.map_err(io::Error::other),
Err(error) => Err(io::Error::new(io::ErrorKind::TimedOut, error)),
};
match result {
Ok((duration, succeeded, checks)) => {
telemetry.record_preparation(duration, succeeded);
for (dependency, target, result) in checks {
telemetry.record_check("contents", dependency, &target, result);
}
}
Err(error) => {
telemetry.record_preparation(started_at.elapsed(), /*succeeded*/ false);
telemetry.record_check("contents", "preparation", &Err(error), /*result*/ None);
}
}
}
#[cfg(test)]
#[path = "runner_tests.rs"]
mod tests;

View File

@@ -0,0 +1,205 @@
//! Check outcome accounting and timings without installing process-global metrics.
use super::super::backend_tests::deny_glob;
use super::super::backend_tests::sandbox_request;
use super::*;
use akode_otel::MetricsConfig;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_sandboxing::SandboxType;
use akode_utils_absolute_path::AbsolutePathBuf;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::fs;
#[test]
fn records_every_outcome_and_times_preparation_without_paths() -> anyhow::Result<()> {
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"sandbox-integrity",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let temp = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(temp.path())?.canonicalize()?;
let writable = root.join("writable");
let protected = root.join("protected");
fs::write(&writable, "fixture")?;
fs::write(&protected, "fixture")?;
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(root.clone().into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(protected.clone().into(), FileSystemAccessMode::Read),
]);
let telemetry = IntegrityMetrics::new(Some(&metrics), "test", &policy);
let checker = FileContentsChecker::new(&policy, &root)?;
for (dependency, path) in [
("writable", Ok(writable.into_path_buf())),
("protected", Ok(protected.into_path_buf())),
("missing", Ok(root.join("missing").into_path_buf())),
("directory", Ok(root.to_path_buf())),
] {
let target = DependencyTarget::inspect(path);
let result = target
.as_ref()
.ok()
.map(|target| checker.check(&target.path));
telemetry.record_check("contents", dependency, &target, result);
}
telemetry.record_check(
"contents",
"preparation",
&DependencyTarget::inspect(Ok(root.join("writable").into_path_buf())),
/*result*/ None,
);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.max_blocking_threads(/*val*/ 1)
.build()?;
let broad_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(root.join("protected").into(), FileSystemAccessMode::Deny),
]);
let mut request = sandbox_request(&root, &broad_policy);
// The same policy is checked when configured, but skipped for an approved escalation.
runtime.block_on(run_checks_with_metrics(&request, Some(&metrics)));
request.sandbox_override = SandboxOverride::EscalatedSandboxWithRestrictions;
runtime.block_on(run_checks_with_metrics(&request, Some(&metrics)));
request.sandbox_override = SandboxOverride::NoOverride;
request.sandbox = SandboxType::None;
runtime.block_on(run_checks_with_metrics(&request, Some(&metrics)));
request.sandbox = backend::SANDBOX_TYPE;
request.permission_profile = PermissionProfile::Disabled;
runtime.block_on(run_checks_with_metrics(&request, Some(&metrics)));
let mut expected_preparations = 1;
if cfg!(any(target_os = "linux", target_os = "windows")) {
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Write,
),
deny_glob(format!("{}/absent/*.key", root.display())),
]);
request.permission_profile =
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted);
runtime.block_on(run_checks_with_metrics(&request, Some(&metrics)));
// Preparation still runs, but no dependency receives another check result.
expected_preparations += 1;
}
request = sandbox_request(&root, &policy);
runtime.block_on(async {
tokio::time::pause();
// Occupy the only worker; dropping release also unblocks it on assertion failure.
let (release, wait) = std::sync::mpsc::channel::<()>();
let (started, ready) = tokio::sync::oneshot::channel();
let blocker = tokio::task::spawn_blocking(move || {
let _ = started.send(());
let _ = wait.recv();
});
ready.await?;
let mut check = Box::pin(run_checks_with_metrics(&request, Some(&metrics)));
assert!(futures::poll!(&mut check).is_pending());
tokio::time::advance(CHECK_TIMEOUT + Duration::from_millis(/*millis*/ 1)).await;
assert!(futures::poll!(&mut check).is_ready());
drop(release);
blocker.await?;
Ok::<_, anyhow::Error>(())
})?;
// Wait for the abandoned worker before checking that it emitted no late results.
drop(runtime);
expected_preparations += 1;
let snapshot = metrics.snapshot()?;
let mut outcomes = BTreeMap::new();
let mut durations = Vec::new();
for metric in snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
{
match metric.data() {
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
assert_eq!(metric.name(), "codex.sandbox_integrity.check");
for point in sum.data_points() {
let attributes: BTreeMap<_, _> = point
.attributes()
.map(|tag| (tag.key.as_str(), tag.value.as_str().into_owned()))
.collect();
assert_eq!(attributes["checker"], "contents");
if attributes["backend"] == "test"
|| attributes["error_kind"] == "timeout"
|| matches!(
attributes["dependency"].as_str(),
"codex" | "sandbox_launcher" | "preparation"
)
{
*outcomes
.entry(
["dependency", "outcome", "error_kind"]
.map(|key| attributes[key].clone()),
)
.or_insert(0) += point.value();
}
}
}
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => {
assert_eq!(
histogram
.data_points()
.map(opentelemetry_sdk::metrics::data::HistogramDataPoint::count)
.sum::<u64>(),
expected_preparations
);
durations.push(metric.name().to_owned());
}
_ => panic!("unexpected metric type"),
}
}
let mut expected_outcomes = vec![
["codex", "finding", "none"],
["writable", "finding", "none"],
["protected", "clean", "none"],
["missing", "missing", "other"],
["directory", "error", "other"],
["preparation", "error", "preparation"],
["preparation", "error", "timeout"],
];
if matches!(
backend::SANDBOX_TYPE,
SandboxType::LinuxSeccomp | SandboxType::WindowsMxc
) {
expected_outcomes.push(["sandbox_launcher", "missing", "other"]);
}
assert_eq!(
outcomes,
expected_outcomes
.into_iter()
.map(|tags| (tags.map(str::to_owned), 1))
.collect::<BTreeMap<_, _>>()
);
durations.sort();
assert_eq!(
durations,
vec![
"codex.sandbox_integrity.duration_ms",
"codex.sandbox_integrity.preparation_ms"
]
);
assert!(!format!("{snapshot:?}").contains(root.as_path().to_str().expect("temporary path")));
Ok(())
}

View File

@@ -0,0 +1,37 @@
//! Seatbelt keeps deny globs as native patterns; no snapshot scan is needed.
use super::dependencies::Dependency;
use super::dependencies::codex_executable;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_sandboxing::SandboxExecRequest;
use akode_sandboxing::SandboxType;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::io;
use std::path::PathBuf;
pub(super) const SANDBOX_TYPE: SandboxType = SandboxType::MacosSeatbelt;
pub(super) const NAME: &str = "seatbelt";
pub(super) fn critical_dependencies(
_request: &SandboxExecRequest,
_policy: &FileSystemSandboxPolicy,
_cwd: &AbsolutePathBuf,
) -> io::Result<Vec<Dependency>> {
Ok(vec![
codex_executable(),
(
"seatbelt",
Ok(PathBuf::from(
akode_sandboxing::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE,
)),
),
])
}
pub(super) fn prepare_policy(
_request: &SandboxExecRequest,
policy: FileSystemSandboxPolicy,
_cwd: &AbsolutePathBuf,
) -> io::Result<FileSystemSandboxPolicy> {
Ok(policy)
}

View File

@@ -0,0 +1,131 @@
//! Construct bounded tags from policies, dependency facts, and checker results, and emit metrics.
//! This module does not discover dependencies, inspect files, prepare policies, or run checks.
//! Without a metrics client, emission is a no-op; callers still run the checks.
use super::dependencies::DependencyTarget;
use akode_otel::MetricsClient;
use akode_otel::Timer;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_sandboxing::IntegrityFinding;
use std::fs;
use std::io;
use std::time::Duration;
pub(super) struct IntegrityMetrics<'a> {
client: Option<&'a MetricsClient>,
tags: [(&'static str, &'static str); 2],
}
impl<'a> IntegrityMetrics<'a> {
pub(super) fn new(
client: Option<&'a MetricsClient>,
backend: &'static str,
policy: &FileSystemSandboxPolicy,
) -> Self {
let has_deny_globs = policy
.entries
.iter()
.any(|entry| matches!(entry.path, FileSystemPath::GlobPattern { .. }));
Self {
client,
tags: [
("backend", backend),
("has_deny_globs", bool_tag(Some(has_deny_globs))),
],
}
}
pub(super) fn start_timer(&self) -> Option<Timer> {
self.client?
.start_timer("codex.sandbox_integrity.duration_ms", &self.tags)
.ok()
}
pub(super) fn record_preparation(&self, duration: Duration, succeeded: bool) {
let Some(client) = self.client else {
return;
};
let _ = client.record_duration(
"codex.sandbox_integrity.preparation_ms",
duration,
&[
self.tags[0],
self.tags[1],
("outcome", if succeeded { "ok" } else { "error" }),
],
);
}
/// A missing result means dependency or checker preparation failed.
pub(super) fn record_check(
&self,
checker: &'static str,
dependency: &'static str,
target: &io::Result<DependencyTarget>,
result: Option<io::Result<Option<IntegrityFinding>>>,
) {
let Some(client) = self.client else {
return;
};
let error_kind = match (target, &result) {
(Err(error), _) | (_, Some(Err(error))) => {
if error.kind() == io::ErrorKind::TimedOut {
"timeout"
} else {
"other"
}
}
(_, None) => "preparation",
(_, Some(Ok(_))) => "none",
};
let (outcome, multiple_roots) = match (target, result) {
(Err(error), _) if error.kind() == io::ErrorKind::NotFound => ("missing", None),
(_, Some(Ok(Some(finding)))) => ("finding", Some(finding.write_roots.len() > 1)),
(_, Some(Ok(None))) => ("clean", Some(false)),
_ => ("error", None),
};
let target = target.as_ref().ok();
let resolution_changed = target.and_then(|target| {
target
.resolved_path
.as_ref()
.map(|resolved| resolved != &target.path)
});
let hard_links = target.and_then(|target| multiple_hard_links(&target.metadata));
let _ = client.counter(
"codex.sandbox_integrity.check",
/*inc*/ 1,
&[
self.tags[0],
("checker", checker),
("dependency", dependency),
("outcome", outcome),
("error_kind", error_kind),
self.tags[1],
("target_resolution_changed", bool_tag(resolution_changed)),
("multiple_hard_links", bool_tag(hard_links)),
("multiple_write_roots", bool_tag(multiple_roots)),
],
);
}
}
#[cfg(unix)]
fn multiple_hard_links(metadata: &fs::Metadata) -> Option<bool> {
use std::os::unix::fs::MetadataExt;
Some(metadata.nlink() > 1)
}
#[cfg(not(unix))]
fn multiple_hard_links(_: &fs::Metadata) -> Option<bool> {
None
}
fn bool_tag(value: Option<bool>) -> &'static str {
match value {
Some(true) => "true",
Some(false) => "false",
None => "unknown",
}
}