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:
224
akode-rs/windows-sandbox-service/src/ipc/authentication.rs
Normal file
224
akode-rs/windows-sandbox-service/src/ipc/authentication.rs
Normal file
@@ -0,0 +1,224 @@
|
||||
//! Authenticates provisioning clients and validates impersonated machine policy.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::create_directory_guard;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use std::ffi::OsString;
|
||||
use std::ffi::c_void;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::BorrowedHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::PathBuf;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::System::Pipes as pipes;
|
||||
use windows_sys::Win32::System::Threading as threading;
|
||||
|
||||
use super::home::prepare_codex_home;
|
||||
use super::request::ServiceRequest;
|
||||
|
||||
pub(crate) struct ClientIdentity {
|
||||
pub(crate) account: String,
|
||||
pub(crate) codex_home: PathBuf,
|
||||
pub(crate) user_sid: String,
|
||||
pub(crate) session_id: u32,
|
||||
// The requested route, authenticated against the held client's installed image.
|
||||
pub(crate) runtime: SetupRuntime,
|
||||
pub(crate) token: OwnedHandle,
|
||||
pub(crate) desktop_installation: Option<crate::installation_record::DesktopInstallation>,
|
||||
// Pins and guards remain live through registration and the provisioning helper.
|
||||
pub(crate) directory_handles: Vec<OwnedHandle>,
|
||||
}
|
||||
|
||||
pub(super) fn authenticate_client(
|
||||
pipe: BorrowedHandle<'_>,
|
||||
authorized_process: &crate::package_identity::AuthorizedClientProcess,
|
||||
sandbox_sid: &[u8],
|
||||
request: &ServiceRequest,
|
||||
) -> Result<(ClientIdentity, Result<()>)> {
|
||||
std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let identity = authenticate_impersonated_client(
|
||||
pipe,
|
||||
authorized_process,
|
||||
sandbox_sid,
|
||||
request,
|
||||
)?;
|
||||
let policy_result = match request {
|
||||
// Registration does not provision resources or change sandbox policy.
|
||||
ServiceRequest::RegisterInstallation { .. } => Ok(()),
|
||||
ServiceRequest::ProvisionSandbox(request) => {
|
||||
crate::machine_policy::validate_provisioning_request(
|
||||
&identity.codex_home,
|
||||
request,
|
||||
identity.token.as_raw_handle(),
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok((identity, policy_result))
|
||||
})
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("provisioning client authentication thread panicked"))?
|
||||
})
|
||||
}
|
||||
|
||||
fn authenticate_impersonated_client(
|
||||
pipe: BorrowedHandle<'_>,
|
||||
authorized_process: &crate::package_identity::AuthorizedClientProcess,
|
||||
sandbox_sid: &[u8],
|
||||
request: &ServiceRequest,
|
||||
) -> Result<ClientIdentity> {
|
||||
// Pin the group generation through identity capture.
|
||||
// Release this lock before the provisioning worker checks machine policy.
|
||||
let _setup_lock = akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
anyhow::ensure!(
|
||||
akode_windows_sandbox::resolve_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)
|
||||
.is_ok_and(|current| current == sandbox_sid),
|
||||
akode_windows_sandbox::SANDBOX_GROUP_CHANGED
|
||||
);
|
||||
if unsafe { pipes::ImpersonateNamedPipeClient(pipe.as_raw_handle()) } == 0 {
|
||||
return Err(std::io::Error::last_os_error()).context("impersonate provisioning client");
|
||||
}
|
||||
let mut raw_token = std::ptr::null_mut();
|
||||
if unsafe {
|
||||
threading::OpenThreadToken(
|
||||
threading::GetCurrentThread(),
|
||||
security::TOKEN_QUERY | security::TOKEN_IMPERSONATE,
|
||||
1,
|
||||
&mut raw_token,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("open provisioning client token");
|
||||
}
|
||||
// SAFETY: OpenThreadToken transferred this handle on success.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
|
||||
crate::package_identity::authorize_client(authorized_process, token.as_raw_handle())
|
||||
.context("authorize the packaged Codex provisioning client")?;
|
||||
let mut session = 0_u32;
|
||||
let mut returned = 0_u32;
|
||||
if unsafe {
|
||||
security::GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
security::TokenSessionId,
|
||||
(&raw mut session).cast(),
|
||||
size_of::<u32>() as u32,
|
||||
&mut returned,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("read provisioning client session");
|
||||
}
|
||||
if session == 0 {
|
||||
bail!("non-interactive service accounts cannot request provisioning");
|
||||
}
|
||||
|
||||
let mut is_sandbox_member = 0;
|
||||
if unsafe {
|
||||
security::CheckTokenMembership(
|
||||
token.as_raw_handle(),
|
||||
sandbox_sid.as_ptr() as *mut c_void,
|
||||
&mut is_sandbox_member,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("check sandbox group membership");
|
||||
}
|
||||
if is_sandbox_member != 0 {
|
||||
bail!("sandbox accounts cannot request provisioning");
|
||||
}
|
||||
|
||||
let user = unsafe { akode_windows_sandbox::get_user_sid_bytes(token.as_raw_handle()) }
|
||||
.context("read provisioning client identity")?;
|
||||
let user_sid = string_from_sid_bytes(&user).map_err(anyhow::Error::msg)?;
|
||||
let account = unsafe { akode_windows_sandbox::account_name_from_sid(user.as_ptr() as _) }
|
||||
.context("resolve provisioning client account")?;
|
||||
let runtime = crate::package_identity::authorize_setup_runtime(authorized_process, request)?;
|
||||
let requested_home = match request {
|
||||
ServiceRequest::RegisterInstallation { codex_home } => codex_home,
|
||||
ServiceRequest::ProvisionSandbox(request) => &request.codex_home,
|
||||
};
|
||||
let (codex_home, handles) = match request {
|
||||
ServiceRequest::ProvisionSandbox(request) => prepare_codex_home(
|
||||
requested_home,
|
||||
runtime,
|
||||
if request.refresh_only {
|
||||
DirectoryOpenDisposition::OpenExisting
|
||||
} else {
|
||||
DirectoryOpenDisposition::OpenOrCreate
|
||||
},
|
||||
)?,
|
||||
ServiceRequest::RegisterInstallation { .. } => {
|
||||
// Registration must not create the sandbox directories or change their ACLs.
|
||||
akode_windows_sandbox::validate_local_directory_path(requested_home)?;
|
||||
let mut handles = Vec::new();
|
||||
super::home::pin_existing_ancestors(requested_home, &mut handles)?;
|
||||
// Uninstall removes sandbox files as SYSTEM; read access cannot grant that authority.
|
||||
let home = super::home::pin_directory(
|
||||
requested_home,
|
||||
filesystem::FILE_ADD_FILE
|
||||
| filesystem::FILE_ADD_SUBDIRECTORY
|
||||
| filesystem::WRITE_DAC,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?;
|
||||
// Bind the guard to the authorized directory before resolving its pathname.
|
||||
let guard = create_directory_guard(home.as_handle())?;
|
||||
drop(super::home::pin_directory(
|
||||
requested_home,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
// Preserve the authorized directory's literal name (including trailing dots).
|
||||
let mut buffer = vec![0_u16; 260];
|
||||
let path = loop {
|
||||
let length = unsafe {
|
||||
filesystem::GetFinalPathNameByHandleW(
|
||||
home.as_raw_handle(),
|
||||
buffer.as_mut_ptr(),
|
||||
buffer.len() as u32,
|
||||
filesystem::FILE_NAME_NORMALIZED | filesystem::VOLUME_NAME_DOS,
|
||||
)
|
||||
};
|
||||
if length == 0 {
|
||||
return Err(std::io::Error::last_os_error())
|
||||
.context("resolve authorized desktop home");
|
||||
}
|
||||
if (length as usize) < buffer.len() {
|
||||
break PathBuf::from(OsString::from_wide(&buffer[..length as usize]));
|
||||
}
|
||||
buffer.resize(length as usize, /*value*/ 0);
|
||||
};
|
||||
handles.push(home);
|
||||
handles.push(guard);
|
||||
(path, handles)
|
||||
}
|
||||
};
|
||||
let desktop_installation =
|
||||
crate::installation_record::read_desktop_installation(&codex_home, token.as_raw_handle())
|
||||
.inspect_err(|_| {
|
||||
crate::service::log_error(
|
||||
crate::service::EVENT_SERVICE_FAILED,
|
||||
"unable to read desktop directory ownership; preserving desktop directories",
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
Ok(ClientIdentity {
|
||||
account,
|
||||
codex_home,
|
||||
user_sid,
|
||||
session_id: session,
|
||||
runtime,
|
||||
token,
|
||||
desktop_installation,
|
||||
directory_handles: handles,
|
||||
})
|
||||
}
|
||||
170
akode-rs/windows-sandbox-service/src/ipc/home.rs
Normal file
170
akode-rs/windows-sandbox-service/src/ipc/home.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! Validates and pins local Codex home and sandbox directories, keeping sandbox
|
||||
//! leaves nonempty so they cannot become junctions during provisioning.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::DirectoryOpenDisposition;
|
||||
use akode_windows_sandbox::SetupRuntime;
|
||||
use akode_windows_sandbox::create_directory_guard;
|
||||
use akode_windows_sandbox::open_directory_no_reparse;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use akode_windows_sandbox::validate_local_directory_path;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use std::os::windows::io::AsHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use windows_sys::Win32::Foundation as foundation;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
|
||||
use super::ServiceUnavailable;
|
||||
|
||||
const DRIVE_FIXED: u32 = 3;
|
||||
|
||||
pub(super) fn prepare_codex_home(
|
||||
requested: &Path,
|
||||
runtime: SetupRuntime,
|
||||
disposition: DirectoryOpenDisposition,
|
||||
) -> Result<(PathBuf, Vec<OwnedHandle>)> {
|
||||
let directory_count = match runtime {
|
||||
SetupRuntime::Registered => 3,
|
||||
SetupRuntime::Legacy => 4,
|
||||
};
|
||||
let mut handles = Vec::new();
|
||||
validate_local_directory_path(requested)?;
|
||||
let requested_root = requested
|
||||
.ancestors()
|
||||
.last()
|
||||
.context("find the root of the requested Codex home")?;
|
||||
if unsafe { filesystem::GetDriveTypeW(to_wide(requested_root.as_os_str()).as_ptr()) }
|
||||
!= DRIVE_FIXED
|
||||
{
|
||||
return Err(ServiceUnavailable("Codex home must be located on a fixed local drive").into());
|
||||
}
|
||||
let parent = requested
|
||||
.parent()
|
||||
.context("Codex home must have an existing parent directory")?;
|
||||
pin_existing_ancestors(parent, &mut handles)?;
|
||||
handles.push(pin_directory(
|
||||
requested,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
disposition,
|
||||
)?);
|
||||
let home = requested
|
||||
.canonicalize()
|
||||
.with_context(|| format!("canonicalize Codex home {}", requested.display()))?;
|
||||
validate_local_directory_path(&home)?;
|
||||
let root = home
|
||||
.ancestors()
|
||||
.last()
|
||||
.context("find the root of the requested Codex home")?;
|
||||
if unsafe { filesystem::GetDriveTypeW(to_wide(root.as_os_str()).as_ptr()) } != DRIVE_FIXED {
|
||||
return Err(ServiceUnavailable("Codex home must be located on a fixed local drive").into());
|
||||
}
|
||||
if home != requested {
|
||||
pin_existing_ancestors(&home, &mut handles)?;
|
||||
}
|
||||
let sandbox_bin = home.join(".sandbox-bin");
|
||||
for (index, directory) in [
|
||||
home.as_path(),
|
||||
&home.join(".sandbox"),
|
||||
&home.join(".sandbox-secrets"),
|
||||
&sandbox_bin,
|
||||
]
|
||||
.into_iter()
|
||||
.take(directory_count)
|
||||
.enumerate()
|
||||
{
|
||||
let mut access = filesystem::FILE_READ_ATTRIBUTES
|
||||
| filesystem::FILE_ADD_FILE
|
||||
| filesystem::FILE_ADD_SUBDIRECTORY;
|
||||
if index != 0 {
|
||||
access |= filesystem::WRITE_DAC;
|
||||
}
|
||||
let handle = pin_directory(directory, access, disposition)
|
||||
.map_err(|error| {
|
||||
// Older elevated installs omitted WRITE_DAC; let the interactive helper repair it.
|
||||
if directory == sandbox_bin.as_path()
|
||||
&& error.downcast_ref::<std::io::Error>().is_some_and(|error| {
|
||||
error.raw_os_error() == Some(foundation::ERROR_ACCESS_DENIED as i32)
|
||||
})
|
||||
{
|
||||
error.context(ServiceUnavailable("sandbox binary directory needs elevated repair"))
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})
|
||||
.with_context(|| {
|
||||
if index == 0 {
|
||||
format!(
|
||||
"requesting user must be permitted to write Codex home {}",
|
||||
directory.display()
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"requesting user must be permitted to write and modify sandbox directory ACL {}",
|
||||
directory.display()
|
||||
)
|
||||
}
|
||||
})?;
|
||||
if index != 0 {
|
||||
let guard = create_directory_guard(handle.as_handle())?;
|
||||
// Reject conversion before guard creation; after creation the retained
|
||||
// file prevents this directory from becoming empty and being converted.
|
||||
drop(pin_directory(
|
||||
directory,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
handles.push(guard);
|
||||
}
|
||||
handles.push(handle);
|
||||
if index == 0 {
|
||||
continue;
|
||||
}
|
||||
for entry in std::fs::read_dir(directory)? {
|
||||
let entry = entry?;
|
||||
let metadata = entry.path().symlink_metadata()?;
|
||||
if metadata.file_attributes() & filesystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
bail!("refusing reparse point {}", entry.path().display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pinned parent handles prevent directory replacement, but existing helper file
|
||||
// opens remain pathname-based; hardlink/leaf-file races need a follow-up redesign.
|
||||
Ok((home, handles))
|
||||
}
|
||||
|
||||
pub(crate) fn pin_existing_ancestors(path: &Path, handles: &mut Vec<OwnedHandle>) -> Result<()> {
|
||||
let mut current = PathBuf::new();
|
||||
for component in path.components() {
|
||||
current.push(component.as_os_str());
|
||||
if !matches!(component, Component::Prefix(_)) && current.is_absolute() {
|
||||
handles.push(pin_directory(
|
||||
¤t,
|
||||
filesystem::FILE_READ_ATTRIBUTES,
|
||||
DirectoryOpenDisposition::OpenExisting,
|
||||
)?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pin_directory(
|
||||
path: &Path,
|
||||
access: u32,
|
||||
disposition: DirectoryOpenDisposition,
|
||||
) -> Result<OwnedHandle> {
|
||||
let handle = open_directory_no_reparse(
|
||||
path,
|
||||
// Metadata-only access does not enforce no-delete sharing.
|
||||
access | filesystem::FILE_TRAVERSE,
|
||||
filesystem::FILE_SHARE_READ | filesystem::FILE_SHARE_WRITE,
|
||||
disposition,
|
||||
)
|
||||
.with_context(|| format!("pin {}", path.display()))?;
|
||||
Ok(handle)
|
||||
}
|
||||
121
akode-rs/windows-sandbox-service/src/ipc/listener.rs
Normal file
121
akode-rs/windows-sandbox-service/src/ipc/listener.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Owns a provisioning pipe and the sandbox group generation in its deny rule.
|
||||
//! Replaces stale listeners only after a response, closing the old pipe before creating another.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::ensure_sandbox_users_group;
|
||||
use akode_windows_sandbox::string_from_sid_bytes;
|
||||
use akode_windows_sandbox::to_wide;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::Foundation as foundation;
|
||||
use windows_sys::Win32::Security as security;
|
||||
use windows_sys::Win32::Security::Authorization as authorization;
|
||||
use windows_sys::Win32::Storage::FileSystem as filesystem;
|
||||
use windows_sys::Win32::System::Pipes as pipes;
|
||||
|
||||
use super::MAX_REQUEST_BYTES;
|
||||
use super::pipe_security_descriptor;
|
||||
|
||||
pub(super) struct ProvisioningListener {
|
||||
pub(super) pipe: OwnedHandle,
|
||||
pub(super) sandbox_sid: Vec<u8>,
|
||||
_descriptor: SecurityDescriptor,
|
||||
}
|
||||
|
||||
impl ProvisioningListener {
|
||||
pub(super) fn open() -> Result<Self> {
|
||||
let pipe_name = akode_windows_sandbox::windows_sandbox_service_pipe_name()?;
|
||||
let _setup_lock =
|
||||
akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
if crate::installation_record::load()?
|
||||
.and_then(|record| record.runtime)
|
||||
.is_some_and(|runtime| runtime.retiring.is_some())
|
||||
{
|
||||
bail!("interrupted sandbox cleanup requires repair");
|
||||
}
|
||||
let sandbox_sid = ensure_sandbox_users_group()?;
|
||||
let (descriptor, pipe) = create_provisioning_pipe(&pipe_name, &sandbox_sid)?;
|
||||
Ok(Self {
|
||||
pipe,
|
||||
sandbox_sid,
|
||||
_descriptor: descriptor,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn refresh(self) -> Result<Self> {
|
||||
let current_group = {
|
||||
let _setup_lock =
|
||||
akode_windows_sandbox::acquire_sandbox_setup_lock(/*timeout_ms*/ 5_000)?;
|
||||
akode_windows_sandbox::resolve_sid(akode_windows_sandbox::SANDBOX_USERS_GROUP)
|
||||
};
|
||||
if current_group.is_ok_and(|current| current == self.sandbox_sid) {
|
||||
unsafe { pipes::DisconnectNamedPipe(self.pipe.as_raw_handle()) };
|
||||
return Ok(self);
|
||||
}
|
||||
// A stale deny SID was refused before dispatch. Close this first-instance
|
||||
// pipe before rebuilding its descriptor for the current group generation.
|
||||
drop(self);
|
||||
Self::open()
|
||||
}
|
||||
}
|
||||
|
||||
struct SecurityDescriptor(security::PSECURITY_DESCRIPTOR);
|
||||
|
||||
impl Drop for SecurityDescriptor {
|
||||
fn drop(&mut self) {
|
||||
unsafe { foundation::LocalFree(self.0 as foundation::HLOCAL) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserves the existing listener and descriptor lifetimes.
|
||||
fn create_provisioning_pipe(
|
||||
pipe_name: &str,
|
||||
sandbox_sid: &[u8],
|
||||
) -> Result<(SecurityDescriptor, OwnedHandle)> {
|
||||
let sid_string = string_from_sid_bytes(sandbox_sid).map_err(anyhow::Error::msg)?;
|
||||
let sddl = pipe_security_descriptor(&sid_string);
|
||||
let mut descriptor: security::PSECURITY_DESCRIPTOR = ptr::null_mut();
|
||||
if unsafe {
|
||||
authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
to_wide(sddl).as_ptr(),
|
||||
authorization::SDDL_REVISION_1,
|
||||
&mut descriptor,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(std::io::Error::last_os_error()).context("create provisioning pipe DACL");
|
||||
}
|
||||
let descriptor = SecurityDescriptor(descriptor);
|
||||
let attributes = security::SECURITY_ATTRIBUTES {
|
||||
nLength: size_of::<security::SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
|
||||
let pipe = unsafe {
|
||||
pipes::CreateNamedPipeW(
|
||||
to_wide(pipe_name).as_ptr(),
|
||||
filesystem::PIPE_ACCESS_DUPLEX | filesystem::FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
pipes::PIPE_TYPE_BYTE
|
||||
| pipes::PIPE_READMODE_BYTE
|
||||
| pipes::PIPE_WAIT
|
||||
| pipes::PIPE_REJECT_REMOTE_CLIENTS,
|
||||
1,
|
||||
1024,
|
||||
MAX_REQUEST_BYTES as u32,
|
||||
0,
|
||||
&attributes,
|
||||
)
|
||||
};
|
||||
if pipe == foundation::INVALID_HANDLE_VALUE {
|
||||
return Err(std::io::Error::last_os_error()).context("create provisioning pipe");
|
||||
}
|
||||
// SAFETY: CreateNamedPipeW transferred this pipe handle on success.
|
||||
Ok((descriptor, unsafe { OwnedHandle::from_raw_handle(pipe) }))
|
||||
}
|
||||
97
akode-rs/windows-sandbox-service/src/ipc/request.rs
Normal file
97
akode-rs/windows-sandbox-service/src/ipc/request.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
//! Validates framed provisioning requests and normalizes proxy settings.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_windows_sandbox::PROVISIONING_PROTOCOL_VERSION;
|
||||
use akode_windows_sandbox::ProvisioningMessage;
|
||||
use akode_windows_sandbox::WindowsSandboxProvisioningSettings;
|
||||
use akode_windows_sandbox::WindowsSandboxProxyListeners;
|
||||
use akode_windows_sandbox::read_provisioning_frame;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::MAX_REQUEST_BYTES;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ServiceRequest {
|
||||
RegisterInstallation { codex_home: PathBuf },
|
||||
ProvisionSandbox(ProvisioningRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub(crate) struct ProvisioningRequest {
|
||||
pub(crate) codex_home: PathBuf,
|
||||
pub(crate) registered_core: bool,
|
||||
pub(crate) refresh_only: bool,
|
||||
pub(crate) listeners: WindowsSandboxProxyListeners,
|
||||
pub(crate) settings: WindowsSandboxProvisioningSettings,
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(request: &[u8]) -> Result<ServiceRequest> {
|
||||
if request.len() > MAX_REQUEST_BYTES {
|
||||
bail!("provisioning request exceeds size limit");
|
||||
}
|
||||
let mut reader = request;
|
||||
let frame = read_provisioning_frame(&mut reader)
|
||||
.context("invalid framed provisioning request")?
|
||||
.context("provisioning client sent an empty request")?;
|
||||
if !reader.is_empty() {
|
||||
bail!("provisioning requests must contain exactly one IPC frame");
|
||||
}
|
||||
|
||||
if frame.version != PROVISIONING_PROTOCOL_VERSION {
|
||||
bail!(
|
||||
"unsupported provisioning request version: {}",
|
||||
frame.version
|
||||
);
|
||||
}
|
||||
let request = match frame.message {
|
||||
ProvisioningMessage::RegisterInstallationRequest { codex_home } => {
|
||||
validate_home(&codex_home)?;
|
||||
return Ok(ServiceRequest::RegisterInstallation {
|
||||
codex_home: PathBuf::from(codex_home),
|
||||
});
|
||||
}
|
||||
ProvisioningMessage::ProvisionSandboxRequest { payload } => payload,
|
||||
ProvisioningMessage::ProvisionSandboxResponse { .. } => bail!("expected a service request"),
|
||||
};
|
||||
validate_home(&request.codex_home)?;
|
||||
if request.refresh_only && !request.registered_core {
|
||||
bail!("registration refresh requires registered Core");
|
||||
}
|
||||
let mut settings = request.settings;
|
||||
let mut listeners = request.listeners;
|
||||
for ports in [
|
||||
&mut settings.proxy_ports,
|
||||
&mut listeners.http_ports,
|
||||
&mut listeners.socks_ports,
|
||||
] {
|
||||
if ports.contains(&0) {
|
||||
bail!("provisioning request includes an invalid proxy port");
|
||||
}
|
||||
ports.sort_unstable();
|
||||
ports.dedup();
|
||||
}
|
||||
if listeners
|
||||
.http_ports
|
||||
.iter()
|
||||
.chain(&listeners.socks_ports)
|
||||
.any(|port| !settings.proxy_ports.contains(port))
|
||||
{
|
||||
bail!("provisioning listener is absent from the proxy settings");
|
||||
}
|
||||
Ok(ServiceRequest::ProvisionSandbox(ProvisioningRequest {
|
||||
codex_home: PathBuf::from(request.codex_home),
|
||||
registered_core: request.registered_core,
|
||||
refresh_only: request.refresh_only,
|
||||
listeners,
|
||||
settings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn validate_home(home: &str) -> Result<()> {
|
||||
if home.is_empty() || home.contains(['\0', '\r', '\n']) {
|
||||
bail!("Codex home is empty or contains an invalid control character");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user