Require Windows sandbox setup completion

This commit is contained in:
Abhinav Vedmala
2026-06-02 21:44:12 -07:00
parent d36a3ead3c
commit 52330b7559
6 changed files with 309 additions and 20 deletions
@@ -30,6 +30,7 @@ use codex_windows_sandbox::sync_persistent_deny_read_acls;
use codex_windows_sandbox::to_wide;
use codex_windows_sandbox::workspace_write_cap_sid_for_root;
use codex_windows_sandbox::workspace_write_root_overlaps_path;
use codex_windows_sandbox::write_setup_completion_report;
use codex_windows_sandbox::write_setup_error_report;
use serde::Deserialize;
use serde::Serialize;
@@ -98,6 +99,8 @@ struct Payload {
mode: SetupMode,
#[serde(default)]
refresh_only: bool,
#[serde(default)]
completion_nonce: Option<String>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Default)]
@@ -447,7 +450,19 @@ fn real_main() -> Result<()> {
format!("open log in {} failed", sbx_dir.display()),
))
})?;
let result = run_setup(&payload, &mut log, &sbx_dir);
let result = run_setup(&payload, &mut log, &sbx_dir).and_then(|()| {
if let Some(completion_nonce) = payload.completion_nonce.as_deref() {
write_setup_completion_report(&payload.codex_home, completion_nonce).map_err(
|err| {
anyhow::Error::new(SetupFailure::new(
SetupErrorCode::HelperCompletionReportWriteFailed,
format!("failed to write setup completion report: {err}"),
))
},
)?;
}
Ok(())
});
if let Err(err) = &result {
let _ = log_line(&mut log, &format!("setup error: {err:?}"));
log_note(&format!("setup error: {err:?}"), Some(sbx_dir.as_path()));
+34 -18
View File
@@ -12,6 +12,7 @@ use crate::setup::run_elevated_setup;
use crate::setup::run_setup_refresh_with_overrides;
use crate::setup::sandbox_users_path;
use crate::setup::setup_marker_path;
use crate::setup_error::setup_completion_report_is_complete;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
@@ -40,6 +41,9 @@ pub struct SandboxCreds {
/// This is a coarse readiness check; `require_logon_sandbox_creds` performs the
/// additional runtime validation for offline firewall settings.
pub fn sandbox_setup_is_complete(codex_home: &Path) -> bool {
if !setup_completion_report_is_complete(codex_home) {
return false;
}
let marker_ok = matches!(load_marker(codex_home), Ok(Some(marker)) if marker.version_matches());
if !marker_ok {
return false;
@@ -110,6 +114,9 @@ fn select_identity(
network_identity: SandboxNetworkIdentity,
codex_home: &Path,
) -> Result<Option<SandboxIdentity>> {
if !setup_completion_report_is_complete(codex_home) {
return Ok(None);
}
let _marker = match load_marker(codex_home)? {
Some(m) if m.version_matches() => m,
_ => return Ok(None),
@@ -156,26 +163,31 @@ pub fn require_logon_sandbox_creds(
// granting the sandbox group access to this directory without granting the capability SID.
let mut setup_reason: Option<String> = None;
let mut identity = match load_marker(codex_home)? {
Some(marker) if marker.version_matches() => {
if let Some(reason) =
marker.request_mismatch_reason(network_identity, &desired_offline_proxy_settings)
{
setup_reason = Some(reason);
None
} else {
let selected = select_identity(network_identity, codex_home)?;
if selected.is_none() {
setup_reason = Some(
"sandbox users missing or incompatible with marker version".to_string(),
);
let mut identity = if !setup_completion_report_is_complete(codex_home) {
setup_reason = Some("sandbox setup completion report missing or invalid".to_string());
None
} else {
match load_marker(codex_home)? {
Some(marker) if marker.version_matches() => {
if let Some(reason) = marker
.request_mismatch_reason(network_identity, &desired_offline_proxy_settings)
{
setup_reason = Some(reason);
None
} else {
let selected = select_identity(network_identity, codex_home)?;
if selected.is_none() {
setup_reason = Some(
"sandbox users missing or incompatible with marker version".to_string(),
);
}
selected
}
selected
}
}
_ => {
setup_reason = Some("sandbox setup marker missing or incompatible".to_string());
None
_ => {
setup_reason = Some("sandbox setup marker missing or incompatible".to_string());
None
}
}
};
@@ -233,3 +245,7 @@ pub fn require_logon_sandbox_creds(
password: identity.password,
})
}
#[cfg(test)]
#[path = "identity_tests.rs"]
mod tests;
@@ -0,0 +1,59 @@
use super::sandbox_setup_is_complete;
use crate::setup::SETUP_VERSION;
use crate::setup::SandboxUserRecord;
use crate::setup::SandboxUsersFile;
use crate::setup::SetupMarker;
use crate::setup::sandbox_users_path;
use crate::setup::setup_marker_path;
use crate::setup_error::prepare_setup_completion_report;
use crate::setup_error::write_setup_completion_report;
use std::fs;
use tempfile::TempDir;
#[test]
fn sandbox_setup_requires_completion_report() {
let codex_home = TempDir::new().expect("tempdir");
let marker = SetupMarker {
version: SETUP_VERSION,
offline_username: "offline".to_string(),
online_username: "online".to_string(),
created_at: None,
proxy_ports: Vec::new(),
allow_local_binding: false,
};
let users = SandboxUsersFile {
version: SETUP_VERSION,
offline: SandboxUserRecord {
username: "offline".to_string(),
password: "offline-password".to_string(),
},
online: SandboxUserRecord {
username: "online".to_string(),
password: "online-password".to_string(),
},
};
let marker_path = setup_marker_path(codex_home.path());
let users_path = sandbox_users_path(codex_home.path());
fs::create_dir_all(marker_path.parent().expect("marker parent")).expect("create marker parent");
fs::create_dir_all(users_path.parent().expect("users parent")).expect("create users parent");
fs::write(
marker_path,
serde_json::to_vec_pretty(&marker).expect("serialize marker"),
)
.expect("write marker");
fs::write(
users_path,
serde_json::to_vec_pretty(&users).expect("serialize users"),
)
.expect("write users");
assert!(!sandbox_setup_is_complete(codex_home.path()));
prepare_setup_completion_report(codex_home.path(), "completed")
.expect("prepare completion report");
assert!(!sandbox_setup_is_complete(codex_home.path()));
write_setup_completion_report(codex_home.path(), "completed").expect("write completion report");
assert!(sandbox_setup_is_complete(codex_home.path()));
}
+2
View File
@@ -267,6 +267,8 @@ pub use setup_error::sanitize_setup_metric_tag_value;
#[cfg(target_os = "windows")]
pub use setup_error::setup_error_path;
#[cfg(target_os = "windows")]
pub use setup_error::write_setup_completion_report;
#[cfg(target_os = "windows")]
pub use setup_error::write_setup_error_report;
#[cfg(target_os = "windows")]
#[doc(hidden)]
+76 -1
View File
@@ -22,7 +22,9 @@ use crate::setup_error::SetupErrorCode;
use crate::setup_error::SetupFailure;
use crate::setup_error::clear_setup_error_report;
use crate::setup_error::failure;
use crate::setup_error::prepare_setup_completion_report;
use crate::setup_error::read_setup_error_report;
use crate::setup_error::setup_completion_matches;
use crate::ssh_config_dependencies::ssh_config_dependency_paths;
use anyhow::Context;
use anyhow::Result;
@@ -31,6 +33,9 @@ use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use rand::Rng;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::GetLastError;
@@ -39,7 +44,7 @@ use windows_sys::Win32::Security::CheckTokenMembership;
use windows_sys::Win32::Security::FreeSid;
use windows_sys::Win32::Security::SECURITY_NT_AUTHORITY;
pub const SETUP_VERSION: u32 = 5;
pub const SETUP_VERSION: u32 = 6;
pub const OFFLINE_USERNAME: &str = "CodexSandboxOffline";
pub const ONLINE_USERNAME: &str = "CodexSandboxOnline";
const ERROR_CANCELLED: u32 = 1223;
@@ -205,6 +210,7 @@ fn run_setup_refresh_inner(
real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()),
mode: SetupMode::Full,
refresh_only: true,
completion_nonce: None,
};
let json = serde_json::to_vec(&payload)?;
let b64 = BASE64_STANDARD.encode(json);
@@ -500,6 +506,8 @@ struct ElevationPayload {
mode: SetupMode,
#[serde(default)]
refresh_only: bool,
#[serde(default)]
completion_nonce: Option<String>,
}
#[derive(Clone, Copy, Serialize)]
@@ -671,6 +679,27 @@ fn report_helper_failure(
}
}
fn new_setup_completion_nonce() -> String {
let mut rng = SmallRng::from_entropy();
format!("{:x}", rng.r#gen::<u128>())
}
fn verify_setup_completion(codex_home: &Path, expected_nonce: &str) -> Result<()> {
match setup_completion_matches(codex_home, expected_nonce) {
Ok(true) => Ok(()),
Ok(false) => Err(failure(
SetupErrorCode::OrchestratorHelperIncomplete,
"setup helper exited successfully without a matching completion report",
)),
Err(err) => Err(failure(
SetupErrorCode::OrchestratorHelperIncomplete,
format!(
"setup helper exited successfully but its completion report was invalid: {err}"
),
)),
}
}
fn run_setup_exe(
payload: &ElevationPayload,
needs_elevation: bool,
@@ -682,6 +711,12 @@ fn run_setup_exe(
use windows_sys::Win32::UI::Shell::SEE_MASK_NOCLOSEPROCESS;
use windows_sys::Win32::UI::Shell::SHELLEXECUTEINFOW;
use windows_sys::Win32::UI::Shell::ShellExecuteExW;
let completion_nonce = payload.completion_nonce.as_deref().ok_or_else(|| {
failure(
SetupErrorCode::OrchestratorPayloadSerializeFailed,
"setup helper payload is missing a completion nonce",
)
})?;
let exe = find_setup_exe();
let payload_json = serde_json::to_string(payload).map_err(|err| {
failure(
@@ -702,6 +737,12 @@ fn run_setup_exe(
false
}
};
prepare_setup_completion_report(codex_home, completion_nonce).map_err(|err| {
failure(
SetupErrorCode::OrchestratorCompletionReportWriteFailed,
format!("failed to prepare the setup completion report before launch: {err}"),
)
})?;
if !needs_elevation {
let status = Command::new(&exe)
@@ -724,6 +765,7 @@ fn run_setup_exe(
status.code(),
));
}
verify_setup_completion(codex_home, completion_nonce)?;
if let Err(err) = clear_setup_error_report(codex_home) {
log_note(
&format!(
@@ -773,6 +815,7 @@ fn run_setup_exe(
));
}
}
verify_setup_completion(codex_home, completion_nonce)?;
if let Err(err) = clear_setup_error_report(codex_home) {
log_note(
&format!("setup orchestrator: failed to clear setup_error.json after success: {err}"),
@@ -819,6 +862,7 @@ pub fn run_elevated_setup(
otel: codex_otel::global_statsig_metrics_settings(),
mode: SetupMode::Full,
refresh_only: false,
completion_nonce: Some(new_setup_completion_nonce()),
};
let needs_elevation = !is_elevated().map_err(|err| {
failure(
@@ -864,6 +908,7 @@ pub fn run_elevated_provisioning_setup(codex_home: &Path, real_user: &str) -> Re
real_user: real_user.to_string(),
mode: SetupMode::ProvisionOnly,
refresh_only: false,
completion_nonce: Some(new_setup_completion_nonce()),
};
run_setup_exe(&payload, /*needs_elevation*/ false, codex_home)
}
@@ -1067,10 +1112,14 @@ mod tests {
use super::offline_proxy_settings_from_env;
use super::profile_read_roots;
use super::proxy_ports_from_env;
use super::verify_setup_completion;
use crate::helper_materialization::BIN_DIRNAME;
use crate::helper_materialization::RESOURCES_DIRNAME;
use crate::helper_materialization::helper_bin_dir;
use crate::resolved_permissions::ResolvedWindowsSandboxPermissions;
use crate::setup_error::SetupErrorCode;
use crate::setup_error::extract_failure;
use crate::setup_error::write_setup_completion_report;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -1154,6 +1203,32 @@ mod tests {
}
}
#[test]
fn setup_completion_requires_matching_nonce() {
let codex_home = TempDir::new().expect("tempdir");
let missing = verify_setup_completion(codex_home.path(), "expected")
.expect_err("missing completion report should fail");
assert_eq!(
extract_failure(&missing).map(|failure| failure.code),
Some(SetupErrorCode::OrchestratorHelperIncomplete)
);
write_setup_completion_report(codex_home.path(), "stale")
.expect("write stale completion report");
let mismatched = verify_setup_completion(codex_home.path(), "expected")
.expect_err("mismatched completion report should fail");
assert_eq!(
extract_failure(&mismatched).map(|failure| failure.code),
Some(SetupErrorCode::OrchestratorHelperIncomplete)
);
write_setup_completion_report(codex_home.path(), "expected")
.expect("write matching completion report");
verify_setup_completion(codex_home.path(), "expected")
.expect("matching completion report should succeed");
}
#[test]
fn loopback_proxy_url_parsing_supports_common_forms() {
assert_eq!(
@@ -31,6 +31,10 @@ pub enum SetupErrorCode {
OrchestratorHelperExitNonzero,
/// Helper exited non-zero and reading `setup_error.json` failed.
OrchestratorHelperReportReadFailed,
/// Helper exited successfully without proving that setup completed.
OrchestratorHelperIncomplete,
/// Failed to initialize the setup completion report before launching the helper.
OrchestratorCompletionReportWriteFailed,
// Helper (elevated process) failures.
/// Helper failed while validating or decoding the request payload.
HelperRequestArgsFailed,
@@ -50,6 +54,8 @@ pub enum SetupErrorCode {
HelperUsersFileWriteFailed,
/// Helper failed to write the setup marker file.
HelperSetupMarkerWriteFailed,
/// Helper failed to write the setup completion report.
HelperCompletionReportWriteFailed,
/// Helper failed to resolve a SID or convert it to a PSID.
HelperSidResolveFailed,
/// Helper failed to load or convert capability SIDs.
@@ -83,6 +89,10 @@ impl SetupErrorCode {
Self::OrchestratorHelperLaunchCanceled => "orchestrator_helper_launch_canceled",
Self::OrchestratorHelperExitNonzero => "orchestrator_helper_exit_nonzero",
Self::OrchestratorHelperReportReadFailed => "orchestrator_helper_report_read_failed",
Self::OrchestratorHelperIncomplete => "orchestrator_helper_incomplete",
Self::OrchestratorCompletionReportWriteFailed => {
"orchestrator_completion_report_write_failed"
}
Self::HelperRequestArgsFailed => "helper_request_args_failed",
Self::HelperSandboxDirCreateFailed => "helper_sandbox_dir_create_failed",
Self::HelperLogFailed => "helper_log_failed",
@@ -92,6 +102,7 @@ impl SetupErrorCode {
Self::HelperDpapiProtectFailed => "helper_dpapi_protect_failed",
Self::HelperUsersFileWriteFailed => "helper_users_file_write_failed",
Self::HelperSetupMarkerWriteFailed => "helper_setup_marker_write_failed",
Self::HelperCompletionReportWriteFailed => "helper_completion_report_write_failed",
Self::HelperSidResolveFailed => "helper_sid_resolve_failed",
Self::HelperCapabilitySidFailed => "helper_capability_sid_failed",
Self::HelperFirewallComInitFailed => "helper_firewall_com_init_failed",
@@ -114,6 +125,19 @@ pub struct SetupErrorReport {
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct SetupCompletionReport {
nonce: String,
status: SetupCompletionStatus,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum SetupCompletionStatus {
Pending,
Complete,
}
#[derive(Debug)]
pub struct SetupFailure {
pub code: SetupErrorCode,
@@ -157,6 +181,10 @@ pub fn setup_error_path(codex_home: &Path) -> PathBuf {
codex_home.join(".sandbox").join("setup_error.json")
}
fn setup_completion_path(codex_home: &Path) -> PathBuf {
crate::setup::sandbox_secrets_dir(codex_home).join("setup_completion.json")
}
pub fn clear_setup_error_report(codex_home: &Path) -> Result<()> {
let path = setup_error_path(codex_home);
match fs::remove_file(&path) {
@@ -188,6 +216,64 @@ pub fn read_setup_error_report(codex_home: &Path) -> Result<Option<SetupErrorRep
Ok(Some(report))
}
pub(crate) fn prepare_setup_completion_report(codex_home: &Path, nonce: &str) -> Result<()> {
write_setup_completion_report_with_status(codex_home, nonce, SetupCompletionStatus::Pending)
}
/// Records that the elevated setup helper completed every synchronous setup stage.
pub fn write_setup_completion_report(codex_home: &Path, nonce: &str) -> Result<()> {
write_setup_completion_report_with_status(codex_home, nonce, SetupCompletionStatus::Complete)
}
fn write_setup_completion_report_with_status(
codex_home: &Path,
nonce: &str,
status: SetupCompletionStatus,
) -> Result<()> {
let secrets_dir = crate::setup::sandbox_secrets_dir(codex_home);
fs::create_dir_all(&secrets_dir)
.with_context(|| format!("create sandbox secrets dir {}", secrets_dir.display()))?;
let path = setup_completion_path(codex_home);
let json = serde_json::to_vec_pretty(&SetupCompletionReport {
nonce: nonce.to_string(),
status,
})?;
fs::write(&path, json).with_context(|| format!("write {}", path.display()))?;
Ok(())
}
fn read_setup_completion_report(codex_home: &Path) -> Result<Option<SetupCompletionReport>> {
let path = setup_completion_path(codex_home);
let bytes = match fs::read(&path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err).with_context(|| format!("read {}", path.display())),
};
let report = serde_json::from_slice::<SetupCompletionReport>(&bytes)
.with_context(|| format!("parse {}", path.display()))?;
Ok(Some(report))
}
pub(crate) fn setup_completion_matches(codex_home: &Path, expected_nonce: &str) -> Result<bool> {
Ok(matches!(
read_setup_completion_report(codex_home)?,
Some(SetupCompletionReport {
nonce,
status: SetupCompletionStatus::Complete,
}) if nonce == expected_nonce
))
}
pub(crate) fn setup_completion_report_is_complete(codex_home: &Path) -> bool {
matches!(
read_setup_completion_report(codex_home),
Ok(Some(SetupCompletionReport {
status: SetupCompletionStatus::Complete,
..
}))
)
}
/// Sanitize a setup error message for use as a metric tag.
pub fn sanitize_setup_metric_tag_value(value: &str) -> String {
sanitize_metric_tag_value(redact_home_paths(value).as_str())
@@ -254,8 +340,44 @@ fn redact_username_segments(value: &str, usernames: &[String]) -> String {
#[cfg(test)]
mod tests {
use super::prepare_setup_completion_report;
use super::redact_username_segments;
use super::setup_completion_matches;
use super::setup_completion_report_is_complete;
use super::write_setup_completion_report;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn setup_completion_report_requires_matching_complete_nonce() {
let codex_home = TempDir::new().expect("tempdir");
assert!(!setup_completion_report_is_complete(codex_home.path()));
assert!(
!setup_completion_matches(codex_home.path(), "expected-nonce")
.expect("read missing completion report")
);
prepare_setup_completion_report(codex_home.path(), "expected-nonce")
.expect("prepare completion report");
assert!(!setup_completion_report_is_complete(codex_home.path()));
assert!(
!setup_completion_matches(codex_home.path(), "expected-nonce")
.expect("read pending completion report")
);
write_setup_completion_report(codex_home.path(), "expected-nonce")
.expect("complete completion report");
assert!(setup_completion_report_is_complete(codex_home.path()));
assert!(
setup_completion_matches(codex_home.path(), "expected-nonce")
.expect("read matching completion report")
);
assert!(
!setup_completion_matches(codex_home.path(), "stale-nonce")
.expect("read mismatched completion report")
);
}
#[test]
fn sanitize_tag_value_redacts_username_segments() {