#![forbid(unsafe_code)]
mod app_server;
#[cfg(unix)]
mod app_server_process;
mod app_server_runtime;
#[cfg(unix)]
mod s08_owned_child_turn;
mod sse;
mod wire;
pub use app_server::{
AppServerAuthMode, AppServerRpc, AppServerTransport, CURRENT_DESKTOP_APP_VERSION,
CURRENT_DESKTOP_BUILD, CURRENT_DESKTOP_CODEX_VERSION, CURRENT_STANDALONE_CLI_VERSION,
CapabilityInputError, CodexAppServerCapabilityReceipt, CodexAppServerProbe, CodexCliVersion,
CodexSubscriptionUnavailableReason, InstalledCodexCli, InstalledCodexDesktop,
SUPPORTED_DISCOVERY_QUOTA_RPCS,
};
#[cfg(unix)]
pub use app_server_process::{
APP_SERVER_DISCOVERY_SCHEMA_VERSION, ActiveCodexTurn, AppServerDiscoveryReceipt,
AppServerLineTransport, AppServerProcessError, CODEX_APP_SERVER_PROTOCOL_VERSION,
CodexAppServerClient, OwnedAppServerConfig, OwnedAppServerTransport, ShutdownReceipt,
TurnRunReceipt,
};
pub use app_server_runtime::{
CodexAgentRuntime, CodexRole, CodexRoleProjection, CodexToolPolicy, ManagedAccountProjection,
ModelPageProjection, ModelProjection, OPENAI_ROLE_PROJECTIONS, RateLimitWindowProjection,
RateLimitsProjection, ReasoningEffort, ReplayDisposition, RuntimeError, RuntimeEvent,
TerminalFailureClass, TerminalStatus, ToolCallStatus, TurnCompletionReceipt,
};
#[cfg(unix)]
pub use s08_owned_child_turn::{
S08_OPENAI_MODEL, S08_OWNED_CHILD_TURN_SCHEMA, S08OwnedChildTurnReceipt,
run_s08_owned_child_turn,
};
pub use sse::{CodexSseEncodeError, CodexSseEncoder};
pub use wire::{
CodexRequestIdentity, CodexSubagentRequestContext, CodexWireError, CodexWireErrorKind,
MAV2_AGENTS_NAMESPACE, MAV2_COLLABORATION_NAMESPACE, MAV2_TOOL_NAMES, MULTI_AGENT_NAMESPACE,
Mav2ForkTurns, Mav2SpawnAgentContract, Mav2SpawnAgentError, NAMESPACE_ID_SMUGGLE_MARKER,
NamespaceIdSmuggleError, canonical_subagent_request_context, decode_namespace_call_id,
encode_namespace_call_id, is_mav2_tool_name, is_subagent_namespace,
normalize_mav2_provider_tool_call, normalize_provider_tool_call, normalize_responses_request,
validate_mav2_spawn_agent_arguments,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};
use subtle::ConstantTimeEq;
use thiserror::Error;
#[derive(Clone)]
pub struct AuthToken {
digest: [u8; 32],
}
impl AuthToken {
pub fn from_secret(secret: &[u8]) -> Result<Self, AuthError> {
if secret.len() < 16 || secret.len() > 4096 {
return Err(AuthError::InvalidTokenMaterial);
}
Ok(Self {
digest: Sha256::digest(secret).into(),
})
}
pub fn verify_bearer(&self, header: &str) -> bool {
let candidate = header.strip_prefix("Bearer ").unwrap_or_default();
let candidate_digest: [u8; 32] = Sha256::digest(candidate.as_bytes()).into();
bool::from(self.digest.ct_eq(&candidate_digest))
}
}
impl fmt::Debug for AuthToken {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("AuthToken([REDACTED])")
}
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum AuthError {
#[error("invalid local authentication material")]
InvalidTokenMaterial,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserConfigTarget {
path: PathBuf,
}
impl UserConfigTarget {
pub fn under_config_root(config_root: impl AsRef<Path>) -> Result<Self, ConfigError> {
let config_root = config_root.as_ref();
if !config_root.is_absolute()
|| config_root
.components()
.any(|component| component == Component::ParentDir)
{
return Err(ConfigError::UnsafeTarget);
}
let metadata = fs::symlink_metadata(config_root)?;
if metadata.file_type().is_symlink() || !metadata.is_dir() {
return Err(ConfigError::UnsafeTarget);
}
let canonical_root = fs::canonicalize(config_root)?;
Ok(Self {
path: canonical_root.join("config.toml"),
})
}
pub fn path(&self) -> &Path {
&self.path
}
}
#[derive(Clone)]
pub struct AuthCommand {
command: PathBuf,
args: Vec<String>,
}
impl AuthCommand {
pub fn new(command: impl Into<PathBuf>, args: Vec<String>) -> Result<Self, ConfigError> {
let command = command.into();
if !command.is_absolute()
|| command
.to_string_lossy()
.chars()
.any(|character| character.is_control())
|| args
.iter()
.any(|argument| argument.chars().any(char::is_control))
{
return Err(ConfigError::InvalidAuthCommand);
}
Ok(Self { command, args })
}
fn validate_host(&self) -> Result<(), ConfigError> {
let metadata =
fs::symlink_metadata(&self.command).map_err(|_| ConfigError::AuthCommandUnavailable)?;
if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
return Err(ConfigError::AuthCommandUnavailable);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = metadata.permissions().mode();
if mode & 0o111 == 0 || mode & 0o022 != 0 {
return Err(ConfigError::AuthCommandUnavailable);
}
}
Ok(())
}
}
impl fmt::Debug for AuthCommand {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("AuthCommand([REDACTED])")
}
}
struct PlanCore {
target: UserConfigTarget,
auth_command: AuthCommand,
original: OriginalFile,
desired: Vec<u8>,
installed_fingerprint: String,
preview_digest: String,
}
enum OriginalFile {
Absent,
Present { bytes: Vec<u8>, mode: Option<u32> },
}
pub struct ConfigPreview {
core: PlanCore,
pub human_diff: String,
pub machine_plan: MachinePlan,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MachinePlan {
pub target: &'static str,
pub operation: &'static str,
pub original_present: bool,
pub original_byte_length: usize,
pub original_fingerprint: String,
pub installed_fingerprint: String,
pub preview_digest: String,
pub project_config_access: &'static str,
}
pub struct ConfirmedConfigPlan {
core: PlanCore,
}
pub struct InstalledConfig {
target: UserConfigTarget,
backup_path: PathBuf,
original: OriginalFile,
installed_fingerprint: String,
receipt_path: PathBuf,
}
const BACKUP_FILE_NAME: &str = "config.toml.continuity-router-backup";
const RECEIPT_FILE_NAME: &str = "config.toml.continuity-router-receipt.json";
const LOCK_FILE_NAME: &str = ".config.toml.continuity-router.lock";
const MAX_CONFIG_BYTES: u64 = 1024 * 1024;
const MAX_RECEIPT_BYTES: u64 = 64 * 1024;
impl fmt::Debug for ConfigPreview {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ConfigPreview")
.field("human_diff", &"[REDACTED]")
.field("machine_plan", &self.machine_plan)
.field("config_contents", &"[REDACTED]")
.finish()
}
}
impl fmt::Debug for ConfirmedConfigPlan {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ConfirmedConfigPlan([REDACTED])")
}
}
impl fmt::Debug for InstalledConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("InstalledConfig([REDACTED])")
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct InstallationReceipt {
version: u8,
target: PathBuf,
original_present: bool,
original_mode: Option<u32>,
original_fingerprint: String,
installed_fingerprint: String,
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("user configuration is not valid UTF-8")]
InvalidUtf8,
#[error("user configuration is not valid TOML")]
InvalidToml,
#[error("the continuity_router provider already exists")]
ConflictingProvider,
#[error("the authentication command or arguments are invalid")]
InvalidAuthCommand,
#[error("the authentication command is unavailable or not executable")]
AuthCommandUnavailable,
#[error("user configuration must be a regular file")]
UnsupportedFileType,
#[error("user configuration target is outside a canonical config root")]
UnsafeTarget,
#[error("the installation receipt is invalid")]
InvalidReceipt,
#[error("the installation receipt targets a different file")]
ReceiptTargetMismatch,
#[error("the user configuration changed after installation")]
ConcurrentModification,
#[error("the supplied configuration preview digest is stale or invalid")]
PreviewDigestMismatch,
#[error("configuration I/O failed")]
Io(#[from] io::Error),
}
impl ConfigPreview {
pub fn build(
target: UserConfigTarget,
port: u16,
auth_command: &AuthCommand,
) -> Result<Self, ConfigError> {
let original = match read_regular_file(target.path(), MAX_CONFIG_BYTES) {
Ok((bytes, metadata)) => {
let text = std::str::from_utf8(&bytes).map_err(|_| ConfigError::InvalidUtf8)?;
let parsed: toml::Value =
toml::from_str(text).map_err(|_| ConfigError::InvalidToml)?;
if parsed
.get("model_providers")
.and_then(|providers| providers.get("continuity_router"))
.is_some()
{
return Err(ConfigError::ConflictingProvider);
}
OriginalFile::Present {
bytes,
mode: file_mode(&metadata),
}
}
Err(error) if error.kind() == io::ErrorKind::NotFound => OriginalFile::Absent,
Err(error) => return Err(ConfigError::Io(error)),
};
let original_text = match &original {
OriginalFile::Absent => "",
OriginalFile::Present { bytes, .. } => {
std::str::from_utf8(bytes).map_err(|_| ConfigError::InvalidUtf8)?
}
};
let desired = desired_config(original_text, port, auth_command).into_bytes();
let installed_fingerprint = fingerprint(&desired);
let original_bytes = match &original {
OriginalFile::Absent => &[][..],
OriginalFile::Present { bytes, .. } => bytes.as_slice(),
};
let original_fingerprint = fingerprint(original_bytes);
let preview_digest = config_preview_digest(
target.path(),
&original_fingerprint,
&installed_fingerprint,
port,
auth_command,
);
let human_diff = redacted_config_diff(original_text, port)?;
let machine_plan = MachinePlan {
target: "[USER_CONFIG]",
operation: "replace_routing_settings_and_append_provider",
original_present: matches!(original, OriginalFile::Present { .. }),
original_byte_length: original_bytes.len(),
original_fingerprint,
installed_fingerprint: installed_fingerprint.clone(),
preview_digest: preview_digest.clone(),
project_config_access: "none",
};
Ok(Self {
core: PlanCore {
target,
auth_command: auth_command.clone(),
original,
desired,
installed_fingerprint,
preview_digest,
},
human_diff,
machine_plan,
})
}
pub fn confirm(self) -> ConfirmedConfigPlan {
ConfirmedConfigPlan { core: self.core }
}
pub fn confirm_digest(
self,
supplied_preview_digest: &str,
) -> Result<ConfirmedConfigPlan, ConfigError> {
if !constant_time_fingerprint_eq(&self.core.preview_digest, supplied_preview_digest) {
return Err(ConfigError::PreviewDigestMismatch);
}
Ok(ConfirmedConfigPlan { core: self.core })
}
}
fn config_preview_digest(
target: &Path,
original_fingerprint: &str,
installed_fingerprint: &str,
port: u16,
auth_command: &AuthCommand,
) -> String {
let mut digest = Sha256::new();
digest.update(b"steadymux-codex-config-preview-v1\0");
digest.update(target.as_os_str().as_encoded_bytes());
digest.update(b"\0");
digest.update(original_fingerprint.as_bytes());
digest.update(b"\0");
digest.update(installed_fingerprint.as_bytes());
digest.update(b"\0");
digest.update(port.to_be_bytes());
digest.update(b"\0");
digest.update(auth_command.command.as_os_str().as_encoded_bytes());
for argument in &auth_command.args {
digest.update(b"\0");
digest.update(argument.as_bytes());
}
let digest: [u8; 32] = digest.finalize().into();
hex_digest(&digest)
}
fn hex_digest(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
fn original_still_matches(original: &OriginalFile, path: &Path) -> Result<bool, ConfigError> {
match original {
OriginalFile::Absent => match fs::symlink_metadata(path) {
Ok(_) => Ok(false),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
Err(error) => Err(ConfigError::Io(error)),
},
OriginalFile::Present { bytes, .. } => match read_regular_file(path, MAX_CONFIG_BYTES) {
Ok((current, _)) => Ok(current == *bytes),
Err(error) if error.kind() == io::ErrorKind::InvalidInput => Ok(false),
Err(error) => Err(ConfigError::Io(error)),
},
}
}
impl ConfirmedConfigPlan {
pub fn apply(self) -> Result<InstalledConfig, ConfigError> {
self.core.auth_command.validate_host()?;
let _lock = ConfigOperationLock::acquire(self.core.target.path())?;
if !original_still_matches(&self.core.original, self.core.target.path())? {
return Err(ConfigError::ConcurrentModification);
}
let parent =
self.core.target.path().parent().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "missing config parent")
})?;
fs::create_dir_all(parent)?;
set_directory_private(parent)?;
let backup_path = parent.join(BACKUP_FILE_NAME);
let receipt_path = parent.join(RECEIPT_FILE_NAME);
if backup_path.exists() || receipt_path.exists() {
return Err(ConfigError::Io(io::Error::new(
io::ErrorKind::AlreadyExists,
"configuration recovery artifacts already exist",
)));
}
match &self.core.original {
OriginalFile::Absent => write_atomic(&backup_path, &[], Some(0o600))?,
OriginalFile::Present { bytes, .. } => write_atomic(&backup_path, bytes, Some(0o600))?,
}
write_atomic(self.core.target.path(), &self.core.desired, Some(0o600))?;
let (original_present, original_mode) = match &self.core.original {
OriginalFile::Absent => (false, None),
OriginalFile::Present { mode, .. } => (true, *mode),
};
let receipt = InstallationReceipt {
version: 2,
target: self.core.target.path().to_path_buf(),
original_present,
original_mode,
original_fingerprint: match &self.core.original {
OriginalFile::Absent => fingerprint(&[]),
OriginalFile::Present { bytes, .. } => fingerprint(bytes),
},
installed_fingerprint: self.core.installed_fingerprint.clone(),
};
let receipt_bytes =
serde_json::to_vec(&receipt).map_err(|_| ConfigError::InvalidReceipt)?;
if let Err(error) = write_atomic(&receipt_path, &receipt_bytes, Some(0o600)) {
restore_original(self.core.target.path(), &self.core.original)?;
let _ = fs::remove_file(&backup_path);
return Err(ConfigError::Io(error));
}
Ok(InstalledConfig {
target: self.core.target,
backup_path,
original: self.core.original,
installed_fingerprint: self.core.installed_fingerprint,
receipt_path,
})
}
}
impl InstalledConfig {
pub fn uninstall(self) -> Result<(), ConfigError> {
let _lock = ConfigOperationLock::acquire(self.target.path())?;
let (current, _) = read_regular_file(self.target.path(), MAX_CONFIG_BYTES)?;
if !constant_time_fingerprint_eq(&fingerprint(¤t), &self.installed_fingerprint) {
return Err(ConfigError::ConcurrentModification);
}
match self.original {
OriginalFile::Absent => fs::remove_file(self.target.path())?,
OriginalFile::Present { bytes, mode } => {
write_atomic(self.target.path(), &bytes, mode)?;
}
}
remove_if_present(&self.backup_path)?;
remove_if_present(&self.receipt_path)
}
pub fn backup_path(&self) -> &Path {
&self.backup_path
}
pub fn receipt_path(&self) -> &Path {
&self.receipt_path
}
}
pub fn restore_from_receipt(target: UserConfigTarget) -> Result<(), ConfigError> {
let _lock = ConfigOperationLock::acquire(target.path())?;
let parent = target
.path()
.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing config parent"))?;
let backup_path = parent.join(BACKUP_FILE_NAME);
let receipt_path = parent.join(RECEIPT_FILE_NAME);
let (receipt_bytes, _) = read_regular_file(&receipt_path, MAX_RECEIPT_BYTES)
.map_err(|_| ConfigError::InvalidReceipt)?;
let (backup_bytes, _) = read_regular_file(&backup_path, MAX_CONFIG_BYTES)
.map_err(|_| ConfigError::InvalidReceipt)?;
let receipt: InstallationReceipt =
serde_json::from_slice(&receipt_bytes).map_err(|_| ConfigError::InvalidReceipt)?;
if receipt.version != 2 || receipt.target != target.path() {
return Err(ConfigError::ReceiptTargetMismatch);
}
if !constant_time_fingerprint_eq(&fingerprint(&backup_bytes), &receipt.original_fingerprint) {
return Err(ConfigError::InvalidReceipt);
}
let (current, _) = read_regular_file(target.path(), MAX_CONFIG_BYTES)?;
if !constant_time_fingerprint_eq(&fingerprint(¤t), &receipt.installed_fingerprint) {
return Err(ConfigError::ConcurrentModification);
}
if receipt.original_present {
write_atomic(target.path(), &backup_bytes, receipt.original_mode)?;
} else {
fs::remove_file(target.path())?;
}
remove_if_present(&backup_path)?;
remove_if_present(&receipt_path)
}
fn restore_original(path: &Path, original: &OriginalFile) -> Result<(), ConfigError> {
match original {
OriginalFile::Absent => {
remove_if_present(path)?;
Ok(())
}
OriginalFile::Present { bytes, mode } => {
write_atomic(path, bytes, *mode)?;
Ok(())
}
}
}
fn remove_if_present(path: &Path) -> Result<(), ConfigError> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(ConfigError::Io(error)),
}
}
struct ConfigOperationLock(PathBuf);
impl ConfigOperationLock {
fn acquire(target: &Path) -> Result<Self, ConfigError> {
let parent = target
.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing config parent"))?;
let path = parent.join(LOCK_FILE_NAME);
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(&path)?;
file.sync_all()?;
Ok(Self(path))
}
}
impl Drop for ConfigOperationLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
fn read_regular_file(path: &Path, limit: u64) -> Result<(Vec<u8>, fs::Metadata), io::Error> {
let before = fs::symlink_metadata(path)?;
if before.file_type().is_symlink() || !before.is_file() || before.len() > limit {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path is not a bounded regular file",
));
}
let mut file = File::open(path)?;
let opened = file.metadata()?;
let after_open = fs::symlink_metadata(path)?;
if !same_file_identity(&before, &opened) || !same_file_identity(&opened, &after_open) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"file identity changed while opening",
));
}
let mut bytes = Vec::with_capacity(opened.len().min(limit) as usize);
Read::by_ref(&mut file)
.take(limit.saturating_add(1))
.read_to_end(&mut bytes)?;
let final_metadata = file.metadata()?;
if bytes.len() as u64 > limit
|| !same_file_identity(&opened, &final_metadata)
|| final_metadata.len() != bytes.len() as u64
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"file changed while reading",
));
}
Ok((bytes, final_metadata))
}
#[cfg(unix)]
fn same_file_identity(left: &fs::Metadata, right: &fs::Metadata) -> bool {
use std::os::unix::fs::MetadataExt;
left.dev() == right.dev() && left.ino() == right.ino()
}
#[cfg(not(unix))]
fn same_file_identity(left: &fs::Metadata, right: &fs::Metadata) -> bool {
left.len() == right.len()
&& left.modified().ok() == right.modified().ok()
&& left.created().ok() == right.created().ok()
}
fn provider_snippet(port: u16, auth_command: &AuthCommand) -> String {
let command =
toml::Value::String(auth_command.command.to_string_lossy().into_owned()).to_string();
let args = toml::Value::Array(
auth_command
.args
.iter()
.cloned()
.map(toml::Value::String)
.collect(),
)
.to_string();
format!(
"\n[model_providers.continuity_router]\nname = \"Local Continuity Router\"\nbase_url = \"http://127.0.0.1:{port}/v1\"\nwire_api = \"responses\"\n\n[model_providers.continuity_router.auth]\ncommand = {command}\nargs = {args}\ntimeout_ms = 5000\nrefresh_interval_ms = 0\n"
)
}
fn redacted_provider_section(port: u16) -> String {
format!(
"[model_providers.continuity_router]\nname = \"Local Continuity Router\"\nbase_url = \"http://127.0.0.1:{port}/v1\"\nwire_api = \"responses\"\n\n[model_providers.continuity_router.auth]\ncommand = \"[REDACTED_AUTH_COMMAND]\"\nargs = [\"[REDACTED_AUTH_ARG]\"]\ntimeout_ms = 5000\nrefresh_interval_ms = 0\n"
)
}
fn redacted_config_diff(original: &str, port: u16) -> Result<String, ConfigError> {
let parsed: toml::Value = if original.is_empty() {
toml::Value::Table(toml::map::Map::new())
} else {
toml::from_str(original).map_err(|_| ConfigError::InvalidToml)?
};
let table = parsed.as_table().ok_or(ConfigError::InvalidToml)?;
let desired_settings = [
("model", toml::Value::String("router-auto".to_owned())),
(
"model_provider",
toml::Value::String("continuity_router".to_owned()),
),
("web_search", toml::Value::String("disabled".to_owned())),
];
let mut lines = vec![
"--- config.toml (current; unchanged fields omitted)".to_owned(),
"+++ config.toml (preview; auth command redacted)".to_owned(),
"@@ top-level routing settings @@".to_owned(),
];
for (key, desired) in desired_settings {
match table.get(key) {
Some(current) if current == &desired => {
lines.push(format!(" {key} = {desired}"));
}
Some(current) => {
lines.push(format!("- {key} = {current}"));
lines.push(format!("+ {key} = {desired}"));
}
None => lines.push(format!("+ {key} = {desired}")),
}
}
lines.push("@@ model_providers.continuity_router (new) @@".to_owned());
lines.extend(
redacted_provider_section(port)
.lines()
.map(|line| format!("+ {line}")),
);
Ok(lines.join("\n"))
}
fn desired_config(original: &str, port: u16, auth_command: &AuthCommand) -> String {
let mut rewritten = String::with_capacity(original.len() + 512);
let mut in_top_level = true;
let mut wrote_model = false;
let mut wrote_provider = false;
let mut wrote_web_search = false;
for line in original.split_inclusive('\n') {
let trimmed = line.trim_start();
if in_top_level && trimmed.starts_with('[') {
append_missing_top_level(
&mut rewritten,
&mut wrote_model,
&mut wrote_provider,
&mut wrote_web_search,
);
in_top_level = false;
}
let key = in_top_level
.then(|| trimmed.split_once('=').map(|(key, _)| key.trim()))
.flatten();
let ending = if line.ends_with("\r\n") {
"\r\n"
} else if line.ends_with('\n') {
"\n"
} else {
""
};
match key {
Some("model") => {
rewritten.push_str("model = \"router-auto\"");
rewritten.push_str(ending);
wrote_model = true;
}
Some("model_provider") => {
rewritten.push_str("model_provider = \"continuity_router\"");
rewritten.push_str(ending);
wrote_provider = true;
}
Some("web_search") => {
rewritten.push_str("web_search = \"disabled\"");
rewritten.push_str(ending);
wrote_web_search = true;
}
_ => rewritten.push_str(line),
}
}
append_missing_top_level(
&mut rewritten,
&mut wrote_model,
&mut wrote_provider,
&mut wrote_web_search,
);
if !rewritten.is_empty() && !rewritten.ends_with('\n') {
rewritten.push('\n');
}
rewritten.push_str(&provider_snippet(port, auth_command));
rewritten
}
fn append_missing_top_level(
output: &mut String,
wrote_model: &mut bool,
wrote_provider: &mut bool,
wrote_web_search: &mut bool,
) {
if (!*wrote_model || !*wrote_provider || !*wrote_web_search)
&& !output.is_empty()
&& !output.ends_with('\n')
{
output.push('\n');
}
if !*wrote_model {
output.push_str("model = \"router-auto\"\n");
*wrote_model = true;
}
if !*wrote_provider {
output.push_str("model_provider = \"continuity_router\"\n");
*wrote_provider = true;
}
if !*wrote_web_search {
output.push_str("web_search = \"disabled\"\n");
*wrote_web_search = true;
}
}
fn fingerprint(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn constant_time_fingerprint_eq(left: &str, right: &str) -> bool {
if left.len() != right.len() {
return false;
}
bool::from(left.as_bytes().ct_eq(right.as_bytes()))
}
fn write_atomic(path: &Path, bytes: &[u8], mode: Option<u32>) -> Result<(), io::Error> {
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid config file name"))?;
let temporary = path.with_file_name(format!(".{file_name}.continuity-router.tmp"));
let mut options = OpenOptions::new();
options.write(true).create_new(true);
let mut file = match options.open(&temporary) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"atomic configuration temporary already exists",
));
}
Err(error) => return Err(error),
};
if let Some(mode) = mode {
set_file_mode(&file, mode)?;
}
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
if let Err(error) = fs::rename(&temporary, path) {
let _ = fs::remove_file(&temporary);
return Err(error);
}
sync_parent_directory(path)
}
#[cfg(unix)]
fn sync_parent_directory(path: &Path) -> Result<(), io::Error> {
let parent = path
.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing parent"))?;
OpenOptions::new().read(true).open(parent)?.sync_all()
}
#[cfg(not(unix))]
fn sync_parent_directory(_path: &Path) -> Result<(), io::Error> {
Ok(())
}
#[cfg(unix)]
fn file_mode(metadata: &fs::Metadata) -> Option<u32> {
use std::os::unix::fs::PermissionsExt;
Some(metadata.permissions().mode() & 0o777)
}
#[cfg(not(unix))]
fn file_mode(_metadata: &fs::Metadata) -> Option<u32> {
None
}
#[cfg(unix)]
fn set_file_mode(file: &fs::File, mode: u32) -> Result<(), io::Error> {
use std::os::unix::fs::PermissionsExt;
file.set_permissions(fs::Permissions::from_mode(mode))
}
#[cfg(not(unix))]
fn set_file_mode(_file: &fs::File, _mode: u32) -> Result<(), io::Error> {
Ok(())
}
#[cfg(unix)]
fn set_directory_private(path: &Path) -> Result<(), io::Error> {
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o700))
}
#[cfg(not(unix))]
fn set_directory_private(_path: &Path) -> Result<(), io::Error> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
fn fixture_auth_command() -> AuthCommand {
AuthCommand::new(
std::env::current_exe().expect("current test executable"),
vec!["CONTINUITY_ROUTER_TOKEN".to_owned()],
)
.expect("fixture auth command")
}
fn confirm_preview(preview: ConfigPreview) -> ConfirmedConfigPlan {
let digest = preview.machine_plan.preview_digest.clone();
preview
.confirm_digest(&digest)
.expect("matching preview digest")
}
#[test]
fn token_debug_and_verification_are_redacted() {
let token = AuthToken::from_secret(b"synthetic-token-canary-12345").expect("fixture token");
assert!(token.verify_bearer("Bearer synthetic-token-canary-12345"));
assert!(!token.verify_bearer("Bearer wrong-token-value"));
assert_eq!(format!("{token:?}"), "AuthToken([REDACTED])");
}
#[test]
fn atomic_write_replaces_file_with_exact_bytes() {
let root = tempdir().expect("temporary config root");
let path = root.path().join("config.toml");
fs::write(&path, b"original\r\nbytes\r\n").expect("original fixture");
let replacement = b"replacement\r\nbytes\r\n";
write_atomic(&path, replacement, Some(0o600)).expect("atomic replacement");
assert_eq!(fs::read(&path).expect("replacement bytes"), replacement);
#[cfg(unix)]
assert_eq!(
file_mode(&fs::metadata(&path).expect("replacement metadata")),
Some(0o600)
);
}
#[test]
fn config_plan_debug_never_exposes_original_or_desired_secrets() {
let root = tempdir().expect("temporary config root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
let original_canary = "existing-config-secret-canary";
fs::write(target.path(), format!("model = \"{original_canary}\"\n"))
.expect("fixture config");
let auth_canary = "auth-command-secret-canary";
let command = AuthCommand::new(
std::env::current_exe().expect("current test executable"),
vec![auth_canary.to_owned()],
)
.expect("fixture auth command");
let preview = ConfigPreview::build(target, 49151, &command).expect("preview");
let debug = format!("{preview:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains(original_canary));
assert!(!debug.contains(auth_canary));
assert_eq!(
format!("{:?}", confirm_preview(preview)),
"ConfirmedConfigPlan([REDACTED])"
);
}
#[test]
fn preview_is_non_mutating_and_restore_is_byte_exact() {
let root = tempdir().expect("temporary config root");
let config_root = root.path().join("user-codex");
fs::create_dir_all(&config_root).expect("config directory");
let target =
UserConfigTarget::under_config_root(&config_root).expect("canonical config root");
let original = b"# user comment\r\nmodel = \"native\"\r\nmodel_provider = \"openai\"\r\nweb_search = \"live\"\r\n";
fs::write(target.path(), original).expect("fixture config");
let preview = ConfigPreview::build(target.clone(), 49152, &fixture_auth_command())
.expect("preview should succeed");
assert_eq!(fs::read(target.path()).expect("read unchanged"), original);
assert!(
preview
.human_diff
.contains("+ base_url = \"http://127.0.0.1:49152/v1\"")
);
assert!(preview.human_diff.contains("- model = \"native\""));
assert!(preview.human_diff.contains("+ model = \"router-auto\""));
assert!(preview.human_diff.contains("- model_provider = \"openai\""));
assert!(
preview
.human_diff
.contains("+ model_provider = \"continuity_router\"")
);
assert!(preview.human_diff.contains("- web_search = \"live\""));
assert!(preview.human_diff.contains("+ web_search = \"disabled\""));
assert!(!preview.human_diff.contains("# user comment"));
assert!(preview.human_diff.contains("[REDACTED_AUTH_COMMAND]"));
assert_eq!(preview.machine_plan.project_config_access, "none");
assert_eq!(
preview.machine_plan.operation,
"replace_routing_settings_and_append_provider"
);
let installed = confirm_preview(preview).apply().expect("confirmed install");
assert_ne!(fs::read(target.path()).expect("installed bytes"), original);
let backup = installed.backup_path().to_path_buf();
assert_eq!(fs::read(&backup).expect("backup bytes"), original);
#[cfg(unix)]
assert_eq!(
file_mode(&fs::metadata(&backup).expect("backup metadata")),
Some(0o600)
);
installed.uninstall().expect("uninstall should restore");
assert_eq!(fs::read(target.path()).expect("restored bytes"), original);
assert!(!backup.exists());
}
#[test]
fn uninstall_refuses_to_clobber_concurrent_edits() {
let root = tempdir().expect("temporary config root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
fs::write(target.path(), b"model = \"native\"\n").expect("fixture config");
let preview =
ConfigPreview::build(target.clone(), 49153, &fixture_auth_command()).expect("preview");
let installed = confirm_preview(preview).apply().expect("install");
fs::write(
target.path(),
b"# concurrent user edit\nmodel = \"native\"\n",
)
.expect("concurrent edit");
assert!(matches!(
installed.uninstall(),
Err(ConfigError::ConcurrentModification)
));
assert_eq!(
fs::read(target.path()).expect("preserved user edit"),
b"# concurrent user edit\nmodel = \"native\"\n"
);
}
#[test]
fn invalid_or_conflicting_config_is_rejected() {
let root = tempdir().expect("temporary config root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
fs::write(target.path(), b"not = [valid").expect("invalid fixture");
assert!(matches!(
ConfigPreview::build(target.clone(), 49154, &fixture_auth_command()),
Err(ConfigError::InvalidToml)
));
fs::write(
target.path(),
b"[model_providers.continuity_router]\nname = \"existing\"\n",
)
.expect("conflict fixture");
assert!(matches!(
ConfigPreview::build(target, 49154, &fixture_auth_command()),
Err(ConfigError::ConflictingProvider)
));
}
#[test]
fn absent_config_is_removed_on_uninstall() {
let root = tempdir().expect("temporary config root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
let preview =
ConfigPreview::build(target.clone(), 49155, &fixture_auth_command()).expect("preview");
let installed = confirm_preview(preview).apply().expect("install");
installed.uninstall().expect("uninstall");
assert!(!target.path().exists());
}
#[test]
fn project_config_is_never_read_or_written() {
let root = tempdir().expect("temporary root");
let user_root = root.path().join("user-codex");
let project_config = root.path().join("project/.codex/config.toml");
fs::create_dir_all(project_config.parent().expect("project parent"))
.expect("project config directory");
let project_bytes = b"model_provider = \"project-native\"\n";
fs::write(&project_config, project_bytes).expect("project fixture");
fs::create_dir_all(&user_root).expect("user config root");
let target = UserConfigTarget::under_config_root(&user_root).expect("canonical user root");
let preview =
ConfigPreview::build(target.clone(), 49156, &fixture_auth_command()).expect("preview");
assert_eq!(preview.machine_plan.project_config_access, "none");
let installed = confirm_preview(preview).apply().expect("install");
assert_eq!(
fs::read(&project_config).expect("project config after install"),
project_bytes
);
installed.uninstall().expect("uninstall");
assert_eq!(
fs::read(&project_config).expect("project config after uninstall"),
project_bytes
);
}
#[cfg(unix)]
#[test]
fn config_root_and_config_file_symlinks_are_refused() {
use std::os::unix::fs::symlink;
let root = tempdir().expect("temporary root");
let real_root = root.path().join("real");
let linked_root = root.path().join("linked");
fs::create_dir(&real_root).expect("real root");
symlink(&real_root, &linked_root).expect("linked root");
assert!(matches!(
UserConfigTarget::under_config_root(&linked_root),
Err(ConfigError::UnsafeTarget)
));
let target = UserConfigTarget::under_config_root(&real_root).expect("canonical root");
let real_config = root.path().join("other.toml");
fs::write(&real_config, b"model = \"native\"\n").expect("real config");
symlink(&real_config, target.path()).expect("config symlink");
assert!(matches!(
ConfigPreview::build(target, 49157, &fixture_auth_command()),
Err(ConfigError::Io(_))
));
}
#[test]
fn restore_refuses_tampered_backup_and_preserves_installed_config() {
let root = tempdir().expect("temporary root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
fs::write(target.path(), b"model = \"native\"\n").expect("original config");
let preview =
ConfigPreview::build(target.clone(), 49158, &fixture_auth_command()).expect("preview");
let installed = confirm_preview(preview).apply().expect("install");
let installed_bytes = fs::read(target.path()).expect("installed bytes");
fs::write(installed.backup_path(), b"tampered backup\n").expect("tamper backup");
drop(installed);
assert!(matches!(
restore_from_receipt(target.clone()),
Err(ConfigError::InvalidReceipt)
));
assert_eq!(
fs::read(target.path()).expect("preserved installed config"),
installed_bytes
);
}
#[test]
fn apply_refuses_a_competing_installer_lock() {
let root = tempdir().expect("temporary root");
let target = UserConfigTarget::under_config_root(root.path()).expect("canonical root");
fs::write(target.path(), b"model = \"native\"\n").expect("original config");
let preview =
ConfigPreview::build(target.clone(), 49159, &fixture_auth_command()).expect("preview");
fs::write(root.path().join(LOCK_FILE_NAME), b"").expect("competing lock");
assert!(matches!(
confirm_preview(preview).apply(),
Err(ConfigError::Io(_))
));
assert_eq!(
fs::read(target.path()).expect("unchanged config"),
b"model = \"native\"\n"
);
}
}