aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,262 @@
//! Framed IPC protocol used between the parent (CLI) and the elevated command runner.
//!
//! This module defines the JSON message schema (spawn request/ready, output, stdin,
//! exit, error, terminate) plus length‑prefixed framing helpers for a byte stream.
//! It is **elevated-path only**: the parent uses it to bootstrap the runner and
//! stream unified_exec I/O over named pipes. The legacy restricted‑token path does
//! not use this protocol, and non‑unified exec capture uses it only when running
//! through the elevated runner.
use anyhow::Result;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use akode_protocol::models::PermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
/// Protocol version shared by the parent process and elevated command runner.
pub const IPC_PROTOCOL_VERSION: u8 = 6;
/// Length-prefixed, JSON-encoded frame.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FramedMessage {
pub version: u8,
#[serde(flatten)]
pub message: Message,
}
/// IPC message variants exchanged between parent and runner.
///
/// `SpawnRequest`, `Stdin`, `CloseStdin`, `Resize`, and `Terminate` are parent->runner commands.
/// `SpawnReady`, `Output`, `Exit`, and `Error` are runner->parent events/results.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Message {
SpawnRequest { payload: Box<SpawnRequest> },
SpawnReady { payload: SpawnReady },
Output { payload: OutputPayload },
Stdin { payload: StdinPayload },
CloseStdin { payload: EmptyPayload },
Resize { payload: ResizePayload },
Exit { payload: ExitPayload },
Error { payload: ErrorPayload },
Terminate { payload: EmptyPayload },
}
/// Spawn parameters sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpawnRequest {
pub command: Vec<String>,
pub cwd: PathBuf,
pub env: HashMap<String, String>,
pub permission_profile: PermissionProfile,
pub workspace_roots: Vec<AbsolutePathBuf>,
pub codex_home: PathBuf,
pub real_codex_home: PathBuf,
pub cap_sids: Vec<String>,
/// Optional managed-network identity added only to the child's restricting SID set.
#[serde(default)]
pub network_proxy_restricting_sid: Option<String>,
pub timeout_ms: Option<u64>,
pub tty: bool,
#[serde(default)]
pub stdin_open: bool,
/// Private desktop kept alive by the parent across command runners.
pub private_desktop_name: Option<String>,
}
/// Ack from runner after it spawns the child process.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpawnReady {
pub process_id: u32,
}
/// Output data sent from runner to parent.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OutputPayload {
pub data_b64: String,
pub stream: OutputStream,
}
/// Output stream identifier for `OutputPayload`.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OutputStream {
Stdout,
Stderr,
}
/// Stdin bytes sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StdinPayload {
pub data_b64: String,
}
/// PTY resize request sent from parent to runner.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ResizePayload {
pub rows: u16,
pub cols: u16,
}
/// Exit status sent from runner to parent.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExitPayload {
pub exit_code: i32,
pub timed_out: bool,
}
/// Error payload sent when the runner fails to spawn or stream.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ErrorPayload {
pub message: String,
pub stage: ErrorStage,
pub windows_error_code: Option<u32>,
}
/// Runner startup stage that produced an error.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ErrorStage {
ReadSpawnRequest,
SpawnChild,
WriteSpawnReady,
}
/// Empty payload for control messages.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct EmptyPayload {}
/// Base64-encode raw bytes for IPC payloads.
pub fn encode_bytes(data: &[u8]) -> String {
STANDARD.encode(data)
}
/// Decode base64 payload data into raw bytes.
pub fn decode_bytes(data: &str) -> Result<Vec<u8>> {
Ok(STANDARD.decode(data.as_bytes())?)
}
/// Write a length-prefixed JSON frame.
pub fn write_frame<W: Write>(writer: W, msg: &FramedMessage) -> Result<()> {
crate::framed_io::write_frame(writer, msg)
}
/// Read a length-prefixed JSON frame; returns `Ok(None)` on EOF.
pub fn read_frame<R: Read>(reader: R) -> Result<Option<FramedMessage>> {
crate::framed_io::read_frame(reader)
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn framed_round_trip() {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Output {
payload: OutputPayload {
data_b64: encode_bytes(b"hello"),
stream: OutputStream::Stdout,
},
},
};
let mut buf = Vec::new();
write_frame(&mut buf, &msg).expect("write");
let decoded = read_frame(buf.as_slice()).expect("read").expect("some");
assert_eq!(decoded.version, IPC_PROTOCOL_VERSION);
match decoded.message {
Message::Output { payload } => {
assert_eq!(payload.stream, OutputStream::Stdout);
let data = decode_bytes(&payload.data_b64).expect("decode");
assert_eq!(data, b"hello");
}
other => panic!("unexpected message: {other:?}"),
}
}
#[test]
fn spawn_request_serializes_permission_profile() {
let workspace_roots = vec![
AbsolutePathBuf::from_absolute_path(PathBuf::from(r"C:\workspace"))
.expect("absolute workspace root"),
];
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::SpawnRequest {
payload: Box::new(SpawnRequest {
command: vec!["cmd.exe".to_string(), "/c".to_string(), "ver".to_string()],
cwd: PathBuf::from(r"C:\workspace"),
env: HashMap::new(),
permission_profile: PermissionProfile::read_only(),
workspace_roots: workspace_roots.clone(),
codex_home: PathBuf::from(r"C:\codex"),
real_codex_home: PathBuf::from(r"C:\Users\codex"),
cap_sids: vec!["S-1-15-3-1024-1".to_string()],
network_proxy_restricting_sid: Some("S-1-5-21-100-200-300-400".to_string()),
timeout_ms: Some(1000),
tty: false,
stdin_open: false,
private_desktop_name: Some("CodexSandboxDesktop-1234".to_string()),
}),
},
};
let encoded = serde_json::to_value(&msg).expect("serialize");
assert_eq!("spawn_request", encoded["type"]);
assert_eq!("managed", encoded["payload"]["permission_profile"]["type"]);
assert_eq!(None, encoded["payload"].get("policy_json_or_preset"));
assert_eq!(None, encoded["payload"].get("sandbox_policy_cwd"));
assert_eq!(None, encoded["payload"].get("permission_profile_cwd"));
let decoded: FramedMessage = serde_json::from_value(encoded).expect("deserialize");
let Message::SpawnRequest { payload } = decoded.message else {
panic!("unexpected message");
};
assert_eq!(PermissionProfile::read_only(), payload.permission_profile);
assert_eq!(workspace_roots, payload.workspace_roots);
assert_eq!(
Some("CodexSandboxDesktop-1234"),
payload.private_desktop_name.as_deref()
);
assert_eq!(
Some("S-1-5-21-100-200-300-400"),
payload.network_proxy_restricting_sid.as_deref()
);
}
#[test]
fn error_payload_serializes_stage_and_windows_error_code() {
let msg = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::Error {
payload: ErrorPayload {
message: "CreateProcessAsUserW failed".to_string(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(1312),
},
},
};
let encoded = serde_json::to_value(&msg).expect("serialize");
assert_eq!(
serde_json::json!({
"version": IPC_PROTOCOL_VERSION,
"type": "error",
"payload": {
"message": "CreateProcessAsUserW failed",
"stage": "spawn_child",
"windows_error_code": 1312,
}
}),
encoded
);
}
}

View File

@@ -0,0 +1,4 @@
pub(crate) mod ipc_framed;
pub(crate) mod runner_client;
pub(crate) mod runner_metrics;
pub(crate) mod runner_pipe;

View File

@@ -0,0 +1,643 @@
use crate::app_package::registered_core_requested;
use crate::app_package::verify_registered_core_runner;
use crate::desktop::DesktopPolicy;
use crate::desktop::shared_private_desktop_for_user;
use crate::identity::SandboxCreds;
use crate::ipc_framed::ErrorPayload;
use crate::ipc_framed::ErrorStage;
use crate::ipc_framed::FramedMessage;
use crate::ipc_framed::IPC_PROTOCOL_VERSION;
use crate::ipc_framed::Message;
use crate::ipc_framed::SpawnRequest;
use crate::ipc_framed::read_frame;
use crate::ipc_framed::write_frame;
use crate::runner_pipe::PIPE_ACCESS_INBOUND;
use crate::runner_pipe::PIPE_ACCESS_OUTBOUND;
use crate::runner_pipe::connect_pipe;
use crate::runner_pipe::create_named_pipe;
use crate::runner_pipe::find_runner_exe;
use crate::runner_pipe::pipe_pair;
use crate::winutil::quote_windows_arg;
use crate::winutil::to_wide;
use anyhow::Context;
use anyhow::Result;
use std::fs::File;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::path::Path;
use std::ptr;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS;
use windows_sys::Win32::Foundation::DuplicateHandle;
use windows_sys::Win32::Foundation::ERROR_ACCOUNT_DISABLED;
use windows_sys::Win32::Foundation::ERROR_LOGON_FAILURE;
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::Diagnostics::Debug::SetErrorMode;
use windows_sys::Win32::System::IO::CancelSynchronousIo;
use windows_sys::Win32::System::Threading::CreateProcessWithLogonW;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::GetCurrentThread;
use windows_sys::Win32::System::Threading::LOGON_WITH_PROFILE;
use windows_sys::Win32::System::Threading::PROCESS_INFORMATION;
use windows_sys::Win32::System::Threading::STARTF_FORCEOFFFEEDBACK;
use windows_sys::Win32::System::Threading::STARTUPINFOW;
use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
const RUNNER_SPAWN_READY_TIMEOUT: Duration = Duration::from_secs(15);
const RUNNER_PIPE_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const RUNNER_ERROR_MODE_FLAGS: u32 = 0x0001 | 0x0002;
const WAIT_OBJECT_0: u32 = 0;
struct NonOwningHandle(HANDLE);
// SAFETY: Pipe and thread handles are opaque process-wide tokens that may be
// passed between threads. This wrapper does not own or extend their lifetime.
unsafe impl Send for NonOwningHandle {}
impl NonOwningHandle {
fn raw(&self) -> HANDLE {
self.0
}
}
#[derive(Debug)]
pub(crate) struct RunnerLogonError {
pub(crate) code: u32,
}
impl std::fmt::Display for RunnerLogonError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CreateProcessWithLogonW failed: {}", self.code)
}
}
impl std::error::Error for RunnerLogonError {}
#[derive(Debug)]
pub(crate) struct RunnerStartupError {
payload: ErrorPayload,
}
impl RunnerStartupError {
pub(crate) fn new(payload: ErrorPayload) -> Self {
Self { payload }
}
}
impl std::fmt::Display for RunnerStartupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"runner failed during {:?}: {}",
self.payload.stage, self.payload.message
)?;
if let Some(code) = self.payload.windows_error_code {
write!(f, " (Windows error {code})")?;
}
Ok(())
}
}
impl std::error::Error for RunnerStartupError {}
pub(crate) struct RunnerTransport {
pipe_write: File,
pipe_read: File,
}
fn is_refreshable_windows_error(code: u32) -> bool {
matches!(
code,
ERROR_ACCOUNT_DISABLED | ERROR_LOGON_FAILURE | ERROR_NO_SUCH_LOGON_SESSION
)
}
fn command_targets_windows_apps(command: &[String]) -> bool {
command.first().is_some_and(|program| {
Path::new(program).components().any(|component| {
component
.as_os_str()
.to_string_lossy()
.eq_ignore_ascii_case("WindowsApps")
})
})
}
pub(crate) fn is_refreshable_sandbox_creds_error(err: &anyhow::Error, command: &[String]) -> bool {
if err
.downcast_ref::<RunnerLogonError>()
.is_some_and(|err| is_refreshable_windows_error(err.code))
{
return true;
}
err.downcast_ref::<RunnerStartupError>().is_some_and(|err| {
err.payload.stage == ErrorStage::SpawnChild
&& err.payload.windows_error_code.is_some_and(|code| {
// AppX activation can return 1312 for a healthy sandbox token. Rotating the
// account password cannot make the same WindowsApps command launch.
is_refreshable_windows_error(code)
&& (code != ERROR_NO_SUCH_LOGON_SESSION
|| !command_targets_windows_apps(command))
})
})
}
pub(crate) fn retry_runner_spawn_once<T>(
sandbox_creds: SandboxCreds,
command: &[String],
mut spawn: impl FnMut(SandboxCreds) -> Result<T>,
refresh: impl FnOnce() -> Result<SandboxCreds>,
) -> Result<T> {
let result = match spawn(sandbox_creds.clone()) {
Ok(result) => Ok(result),
// No runner (and therefore no user command) started. Keep credentials unchanged.
Err(err)
if err
.downcast_ref::<RunnerLogonError>()
.is_some_and(|err| err.code == ERROR_SERVICE_ALREADY_RUNNING) =>
{
spawn(sandbox_creds)
}
Err(err) if is_refreshable_sandbox_creds_error(&err, command) => refresh().and_then(spawn),
Err(err) => Err(err),
};
super::runner_metrics::record("startup", if result.is_ok() { "success" } else { "error" });
result
}
impl RunnerTransport {
pub(crate) fn send_spawn_request(&mut self, request: SpawnRequest) -> Result<()> {
let spawn_request = FramedMessage {
version: IPC_PROTOCOL_VERSION,
message: Message::SpawnRequest {
payload: Box::new(request),
},
};
write_frame(&mut self.pipe_write, &spawn_request)
}
pub(crate) fn read_spawn_ready(&mut self) -> Result<()> {
crate::framed_io::wait_for_complete_frame(
&self.pipe_read,
Instant::now() + RUNNER_SPAWN_READY_TIMEOUT,
)
.context("wait for runner spawn_ready")?;
let msg = read_frame(&mut self.pipe_read)?
.ok_or_else(|| anyhow::anyhow!("runner pipe closed before spawn_ready"))?;
match msg.message {
Message::SpawnReady { .. } => Ok(()),
Message::Error { payload } => Err(RunnerStartupError::new(payload).into()),
other => Err(anyhow::anyhow!(
"expected spawn_ready from runner, got {other:?}"
)),
}
}
pub(crate) fn into_files(self) -> (File, File) {
(self.pipe_write, self.pipe_read)
}
}
fn try_take_completed_connect_result(
connect_thread: &mut Option<thread::JoinHandle<()>>,
connect_result_rx: &mpsc::Receiver<Result<()>>,
thread_handle: HANDLE,
pipe_label: &str,
) -> Result<Option<Result<()>>> {
let thread_wait = unsafe { WaitForSingleObject(thread_handle, 0) };
if thread_wait != WAIT_OBJECT_0 {
return Ok(None);
}
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
let result = connect_result_rx.recv().map_err(|_| {
anyhow::anyhow!("runner {pipe_label} connect thread exited before reporting its result")
})?;
Ok(Some(result))
}
fn connect_pipe_with_timeout(
h_pipe: HANDLE,
expected_runner_pid: u32,
pipe_label: &str,
) -> Result<()> {
let pipe_label = pipe_label.to_string();
let pipe_label_for_thread = pipe_label.clone();
let (thread_handle_tx, thread_handle_rx) = mpsc::sync_channel(1);
let (connect_result_tx, connect_result_rx) = mpsc::sync_channel(1);
let h_pipe = NonOwningHandle(h_pipe);
let mut connect_thread = Some(
thread::Builder::new()
.name(format!("codex-runner-connect-{pipe_label}"))
.spawn(move || {
let current_process = unsafe { GetCurrentProcess() };
let mut thread_handle = std::ptr::null_mut();
let duplicate_ok = unsafe {
DuplicateHandle(
current_process,
GetCurrentThread(),
current_process,
&mut thread_handle,
0,
0,
DUPLICATE_SAME_ACCESS,
)
};
if duplicate_ok == 0 {
let _ = thread_handle_tx.send(Err(anyhow::anyhow!(
"DuplicateHandle failed for runner {pipe_label_for_thread} connect thread: {}",
unsafe { GetLastError() }
)));
return;
}
// Publish the helper thread HANDLE before the blocking pipe connect so the
// parent can cancel this specific operation if it times out.
let _ = thread_handle_tx.send(Ok(NonOwningHandle(thread_handle)));
let result = connect_pipe(h_pipe.raw(), expected_runner_pid)
.map_err(anyhow::Error::from)
.context(format!("connect {pipe_label_for_thread}"));
let _ = connect_result_tx.send(result);
})?,
);
let thread_handle = thread_handle_rx.recv().map_err(|_| {
anyhow::anyhow!("runner {pipe_label} connect thread exited before publishing its handle")
})??;
let result = match connect_result_rx.recv_timeout(RUNNER_PIPE_CONNECT_TIMEOUT) {
Ok(result) => {
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
result
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if let Some(result) = try_take_completed_connect_result(
&mut connect_thread,
&connect_result_rx,
thread_handle.raw(),
&pipe_label,
)? {
result
} else {
let cancel_ok = unsafe { CancelSynchronousIo(thread_handle.raw()) };
if cancel_ok == 0 {
let err = unsafe { GetLastError() };
if err != ERROR_NOT_FOUND {
Err(anyhow::anyhow!(
"CancelSynchronousIo failed for runner {pipe_label} connect thread: {err}"
))
} else if let Some(result) = try_take_completed_connect_result(
&mut connect_thread,
&connect_result_rx,
thread_handle.raw(),
&pipe_label,
)? {
result
} else {
Err(anyhow::anyhow!(
"timed out after {}ms connecting runner {pipe_label}",
RUNNER_PIPE_CONNECT_TIMEOUT.as_millis()
))
}
} else {
// Do not join the helper thread on the timeout path. Parent-side cleanup will
// close the pipe handles, which lets the blocked connect unwind without
// risking another indefinite wait here.
Err(anyhow::anyhow!(
"timed out after {}ms connecting runner {pipe_label}",
RUNNER_PIPE_CONNECT_TIMEOUT.as_millis()
))
}
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
if let Some(connect_thread) = connect_thread.take() {
let _ = connect_thread.join();
}
Err(anyhow::anyhow!(
"runner {pipe_label} connect thread exited before reporting its result"
))
}
};
unsafe {
CloseHandle(thread_handle.raw());
}
result
}
pub(crate) fn spawn_runner_transport(
codex_home: &Path,
cwd: &Path,
sandbox_creds: &SandboxCreds,
log_dir: Option<&Path>,
mut spawn_request: SpawnRequest,
desktop_policy: Option<&DesktopPolicy>,
) -> Result<RunnerTransport> {
let runner_exe = find_runner_exe(codex_home, log_dir)?;
let registered_alias = if registered_core_requested() {
Some(crate::app_package::registered_runner_alias(
codex_home,
&sandbox_creds.username,
)?)
} else {
None
};
if let Some(policy) = desktop_policy {
spawn_request.private_desktop_name = Some(shared_private_desktop_for_user(
&sandbox_creds.username,
policy,
log_dir,
)?);
}
let (pipe_in_name, pipe_out_name) = pipe_pair();
let pipe_write = unsafe {
File::from_raw_handle(create_named_pipe(
&pipe_in_name,
PIPE_ACCESS_OUTBOUND,
&sandbox_creds.username,
)? as _)
};
let pipe_read = unsafe {
File::from_raw_handle(create_named_pipe(
&pipe_out_name,
PIPE_ACCESS_INBOUND,
&sandbox_creds.username,
)? as _)
};
let h_pipe_in = pipe_write.as_raw_handle() as HANDLE;
let h_pipe_out = pipe_read.as_raw_handle() as HANDLE;
let runner_cmdline = registered_alias
.as_deref()
.unwrap_or(&runner_exe)
.to_str()
.map(str::to_owned)
.unwrap_or_else(|| "akode-command-runner.exe".to_string());
let runner_full_cmd = format!(
"{} {} {}",
quote_windows_arg(&runner_cmdline),
quote_windows_arg(&format!("--pipe-in={pipe_in_name}")),
quote_windows_arg(&format!("--pipe-out={pipe_out_name}"))
);
let mut cmdline_vec = to_wide(&runner_full_cmd);
let exe_w = to_wide(&runner_cmdline);
let cwd_w = to_wide(cwd);
let user_w = to_wide(&sandbox_creds.username);
let domain_w = to_wide(".");
let password_w = to_wide(&sandbox_creds.password);
let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
si.dwFlags = STARTF_FORCEOFFFEEDBACK;
let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
let previous_error_mode = unsafe { SetErrorMode(RUNNER_ERROR_MODE_FLAGS) };
// Execution aliases require the registered account's profile.
// Other launches retain their existing profile-free behavior.
let spawn_res = unsafe {
CreateProcessWithLogonW(
user_w.as_ptr(),
domain_w.as_ptr(),
password_w.as_ptr(),
if registered_alias.is_some() {
LOGON_WITH_PROFILE
} else {
0
},
exe_w.as_ptr(),
cmdline_vec.as_mut_ptr(),
windows_sys::Win32::System::Threading::CREATE_NO_WINDOW
| windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT,
ptr::null(),
cwd_w.as_ptr(),
&si,
&mut pi,
)
};
// Preserve the failure code before SetErrorMode can overwrite it.
let spawn_error = (spawn_res == 0).then(|| unsafe { GetLastError() });
unsafe {
SetErrorMode(previous_error_mode);
}
if let Some(err) = spawn_error {
return Err(RunnerLogonError { code: err }.into());
}
// Keep the process pinned through the entire startup handshake. Pipes close
// automatically on every error, including failure to create the second pipe.
let _runner_process = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) };
let _runner_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) };
let expected_runner_pid = pi.dwProcessId;
let mut transport = RunnerTransport {
pipe_write,
pipe_read,
};
let startup_result = (|| -> Result<()> {
// An update can retarget the alias after setup. Check the selected image
// and authenticate its pipes before sending it the command.
if registered_alias.is_some() {
verify_registered_core_runner(pi.hProcess, &runner_exe)?;
}
connect_pipe_with_timeout(h_pipe_in, expected_runner_pid, "pipe-in")?;
connect_pipe_with_timeout(h_pipe_out, expected_runner_pid, "pipe-out")?;
transport.send_spawn_request(spawn_request)?;
transport.read_spawn_ready()?;
Ok(())
})();
if let Err(err) = startup_result {
unsafe {
let _ = TerminateProcess(pi.hProcess, 1);
}
return Err(err);
}
if registered_alias.is_some() {
crate::logging::debug_log(
&format!(
"registered_core_runner_ready pid={expected_runner_pid} package_verified=true pipes_authenticated=true"
),
log_dir,
);
}
Ok(transport)
}
#[cfg(test)]
mod tests {
use super::RunnerLogonError;
use super::RunnerStartupError;
use super::is_refreshable_sandbox_creds_error;
use super::retry_runner_spawn_once;
use crate::identity::SandboxCreds;
use crate::ipc_framed::ErrorPayload;
use crate::ipc_framed::ErrorStage;
use pretty_assertions::assert_eq;
use windows_sys::Win32::Foundation::ERROR_ACCOUNT_DISABLED;
use windows_sys::Win32::Foundation::ERROR_LOGON_FAILURE;
use windows_sys::Win32::Foundation::ERROR_NO_SUCH_LOGON_SESSION;
use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;
use windows_sys::Win32::Foundation::ERROR_SERVICE_ALREADY_RUNNING;
#[test]
fn logon_service_already_running_retries_once_without_refresh() {
let mut attempts = 0;
let result = retry_runner_spawn_once(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|creds| {
attempts += 1;
assert_eq!(
(creds.username.as_str(), creds.password.as_str()),
("sandbox-user", "test-only")
);
if attempts == 1 {
Err(anyhow::Error::new(RunnerLogonError {
code: ERROR_SERVICE_ALREADY_RUNNING,
})
.context("runner launch failed"))
} else {
Ok(42)
}
},
|| panic!("1056 must not refresh credentials"),
);
assert_eq!((result.unwrap(), attempts), (42, 2));
}
#[test]
fn logon_service_already_running_stops_after_two_failures() {
let mut attempts = 0;
let err = retry_runner_spawn_once::<()>(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|_| {
attempts += 1;
Err(RunnerLogonError {
code: ERROR_SERVICE_ALREADY_RUNNING,
}
.into())
},
|| panic!("1056 must not refresh credentials"),
)
.unwrap_err();
assert_eq!(
(
attempts,
err.downcast_ref::<RunnerLogonError>().unwrap().code
),
(2, ERROR_SERVICE_ALREADY_RUNNING)
);
}
#[test]
fn child_service_already_running_does_not_replay_command() {
let mut attempts = 0;
let err = retry_runner_spawn_once::<()>(
SandboxCreds {
username: "sandbox-user".into(),
password: "test-only".into(),
},
&[],
|_| {
attempts += 1;
Err(RunnerStartupError::new(ErrorPayload {
message: "child startup failed".into(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(ERROR_SERVICE_ALREADY_RUNNING),
})
.into())
},
|| panic!("1056 must not refresh credentials"),
)
.unwrap_err();
assert_eq!(
(
attempts,
err.downcast_ref::<RunnerStartupError>()
.unwrap()
.payload
.windows_error_code,
),
(1, Some(ERROR_SERVICE_ALREADY_RUNNING))
);
}
#[test]
fn refreshable_sandbox_creds_error_recognizes_credential_and_child_start_failures() {
assert_eq!(
[
ERROR_ACCOUNT_DISABLED,
ERROR_LOGON_FAILURE,
ERROR_NO_SUCH_LOGON_SESSION,
ERROR_NOT_FOUND,
]
.map(|code| {
let err =
anyhow::Error::new(RunnerLogonError { code }).context("runner launch failed");
is_refreshable_sandbox_creds_error(&err, &[])
}),
[true, true, true, false]
);
assert_eq!(
[
(ErrorStage::SpawnChild, ERROR_NO_SUCH_LOGON_SESSION),
(ErrorStage::SpawnChild, ERROR_NOT_FOUND),
(ErrorStage::ReadSpawnRequest, ERROR_NO_SUCH_LOGON_SESSION),
]
.map(|(stage, windows_error_code)| {
let err = anyhow::Error::new(RunnerStartupError::new(ErrorPayload {
message: "runner startup failed".to_string(),
stage,
windows_error_code: Some(windows_error_code),
}));
is_refreshable_sandbox_creds_error(&err, &["cmd.exe".to_string()])
}),
[true, false, false]
);
let windows_apps_commands = [
vec![
r"C:\Users\user\AppData\Local\Microsoft\WindowsApps\pwsh.exe".to_string(),
],
vec![
r"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.3.0_x64__8wekyb3d8bbwe\pwsh.exe"
.to_string(),
],
];
assert_eq!(
windows_apps_commands.map(|command| {
let err = anyhow::Error::new(RunnerStartupError::new(ErrorPayload {
message: "runner startup failed".to_string(),
stage: ErrorStage::SpawnChild,
windows_error_code: Some(ERROR_NO_SUCH_LOGON_SESSION),
}));
is_refreshable_sandbox_creds_error(&err, &command)
}),
[false, false]
);
}
}

View File

@@ -0,0 +1,35 @@
//! Compare registered and legacy runner outcomes at the actual local execution boundary.
//! Startup is counted once after credential retry; commands are counted on exit or pipe failure.
pub(crate) fn record(phase: &'static str, outcome: &'static str) {
let runtime = if crate::app_package::registered_core_requested() {
"registered"
} else {
"legacy"
};
if let Some(metrics) = akode_otel::global() {
// Fixed labels only: never send command text, paths, or arbitrary error messages.
let _ = metrics.counter(
"codex.windows_sandbox.runner_result",
/*inc*/ 1,
&[("runtime", runtime), ("phase", phase), ("outcome", outcome)],
);
}
}
pub(crate) fn record_command(exit: Option<(i32, bool)>) {
record("command", command_outcome(exit));
}
fn command_outcome(exit: Option<(i32, bool)>) -> &'static str {
match exit {
Some((_, true)) => "timeout",
Some((0, false)) => "success",
Some((_, false)) => "nonzero_exit",
None => "transport_error",
}
}
#[cfg(test)]
#[path = "runner_metrics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,27 @@
//! Keep command outcomes distinct without publishing arbitrary exit-code metric labels.
use super::command_outcome;
use pretty_assertions::assert_eq;
#[test]
fn command_results_distinguish_timeouts_transport_errors_and_nonzero_exits() {
assert_eq!(
[
Some((0, false)),
Some((1, false)),
Some((0xc0000135u32 as i32, false)), // Windows DLL-not-found status.
Some((0, true)),
Some((1, true)),
None,
]
.map(command_outcome),
[
"success",
"nonzero_exit",
"nonzero_exit",
"timeout",
"timeout",
"transport_error",
]
);
}

View File

@@ -0,0 +1,133 @@
//! Named pipe helpers for the elevated Windows sandbox runner.
//!
//! This module generates paired pipe names, creates server‑side pipes with
//! sandbox-user-scoped ACLs, and waits for the runner to connect. It is
//! **elevated-path only** and is
//! used by the parent to establish the IPC channel for both unified_exec sessions
//! and elevated capture. The legacy restricted‑token path spawns the child directly
//! and does not use these helpers.
use crate::helper_materialization::resolve_command_runner;
use crate::winutil::resolve_sid;
use crate::winutil::string_from_sid_bytes;
use crate::winutil::to_wide;
use rand::Rng;
use rand::SeedableRng;
use rand::rngs::SmallRng;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HLOCAL;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::System::Pipes::ConnectNamedPipe;
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
use windows_sys::Win32::System::Pipes::GetNamedPipeClientProcessId;
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
use windows_sys::Win32::System::Pipes::PIPE_WAIT;
/// PIPE_ACCESS_INBOUND (win32 constant), not exposed in windows-sys 0.52.
pub const PIPE_ACCESS_INBOUND: u32 = 0x0000_0001;
/// PIPE_ACCESS_OUTBOUND (win32 constant), not exposed in windows-sys 0.52.
pub const PIPE_ACCESS_OUTBOUND: u32 = 0x0000_0002;
/// Resolve the installed runner for registered Core; otherwise use the legacy copy path.
pub fn find_runner_exe(codex_home: &Path, log_dir: Option<&Path>) -> anyhow::Result<PathBuf> {
resolve_command_runner(codex_home, log_dir)
}
/// Generates a unique named-pipe path used to communicate with the runner process.
pub fn pipe_pair() -> (String, String) {
let mut rng = SmallRng::from_entropy();
let nonce: u128 = rng.r#gen();
let base = format!(r"\\.\pipe\codex-runner-{nonce:x}");
(format!("{base}-in"), format!("{base}-out"))
}
/// Creates a named pipe whose DACL only allows the sandbox user to connect.
pub fn create_named_pipe(name: &str, access: u32, sandbox_username: &str) -> io::Result<HANDLE> {
let sandbox_sid = resolve_sid(sandbox_username)
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err.to_string()))?;
let sandbox_sid = string_from_sid_bytes(&sandbox_sid)
.map_err(|err| io::Error::new(io::ErrorKind::PermissionDenied, err))?;
let sddl = to_wide(format!("D:(A;;GA;;;{sandbox_sid})"));
let mut sd: PSECURITY_DESCRIPTOR = ptr::null_mut();
let ok = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
1, // SDDL_REVISION_1
&mut sd,
ptr::null_mut(),
)
};
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
let mut sa = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: sd,
bInheritHandle: 0,
};
let wide = to_wide(name);
let h = unsafe {
CreateNamedPipeW(
wide.as_ptr(),
access,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
65536,
65536,
0,
&mut sa as *mut SECURITY_ATTRIBUTES,
)
};
unsafe {
LocalFree(sd as HLOCAL);
}
if h.is_null() || h == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
Ok(h)
}
/// Waits for the runner to connect to a parent-created server pipe.
///
/// This is parent-side only: the runner opens the pipe with `CreateFileW`, while the
/// parent calls `ConnectNamedPipe`, tolerates the already-connected case, and
/// verifies that the connected client is the runner process we just spawned.
pub fn connect_pipe(h: HANDLE, expected_runner_pid: u32) -> io::Result<()> {
let ok = unsafe { ConnectNamedPipe(h, ptr::null_mut()) };
if ok == 0 {
let err = unsafe { GetLastError() };
const ERROR_PIPE_CONNECTED: u32 = 535;
if err != ERROR_PIPE_CONNECTED {
return Err(io::Error::from_raw_os_error(err as i32));
}
}
let mut client_pid = 0;
let ok = unsafe { GetNamedPipeClientProcessId(h, &mut client_pid) };
if ok == 0 {
return Err(io::Error::from_raw_os_error(unsafe {
GetLastError() as i32
}));
}
if client_pid != expected_runner_pid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"named pipe client pid {client_pid} did not match runner pid {expected_runner_pid}"
),
));
}
Ok(())
}