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,114 @@
use super::Config;
use super::ConfigTomlLoadResult;
use super::ManagedFeatures;
use super::resolve_bootstrap_auth_route_config;
use akode_config::types::AuthKeyringBackendKind;
use akode_features::Feature;
use akode_features::FeatureConfigSource;
use akode_features::FeatureOverrides;
use akode_features::Features;
use akode_login::AuthConfig;
use std::path::Path;
impl Config {
pub fn auth_keyring_backend_kind(&self) -> AuthKeyringBackendKind {
auth_keyring_backend_kind_from_secret_auth_storage(
self.features.enabled(Feature::SecretAuthStorage),
)
}
pub fn auth_config(&self) -> AuthConfig {
AuthConfig {
codex_home: self.codex_home.to_path_buf(),
auth_credentials_store_mode: self.cli_auth_credentials_store_mode,
keyring_backend_kind: self.auth_keyring_backend_kind(),
forced_login_method: self.forced_login_method,
managed_auth_policy: self
.config_layer_stack
.requirements()
.managed_auth_policy()
.with_forced_chatgpt_workspaces(self.forced_chatgpt_workspace_id.as_deref()),
auth_route_config: self.auth_route_config(),
}
}
}
/// Builds authentication settings from the locally resolved bootstrap config.
///
/// Use this before the full configuration is loaded, when a full [`Config`] is not
/// yet available. Preserves the configured credential store, keyring backend,
/// auth routing, and managed login restrictions.
pub fn bootstrap_auth_config(
codex_home: &Path,
bootstrap_config: &ConfigTomlLoadResult,
) -> std::io::Result<AuthConfig> {
let config = &bootstrap_config.config_toml;
let requirements = bootstrap_config.config_layer_stack.requirements();
let mut auth_config = AuthConfig {
codex_home: codex_home.to_path_buf(),
auth_credentials_store_mode: config.cli_auth_credentials_store.unwrap_or_default(),
keyring_backend_kind: resolve_bootstrap_auth_keyring_backend_kind(bootstrap_config)?,
forced_login_method: config.forced_login_method,
managed_auth_policy: requirements
.managed_auth_policy()
.with_forced_chatgpt_workspaces(
config
.forced_chatgpt_workspace_id
.clone()
.and_then(akode_config::config_toml::ForcedChatgptWorkspaceIds::normalized)
.as_deref(),
),
auth_route_config: resolve_bootstrap_auth_route_config(
config,
requirements.feature_requirements.as_ref(),
)?,
};
if let Some(required) = requirements.cli_auth_credentials_store.as_ref() {
auth_config.auth_credentials_store_mode = required.value;
}
auth_config.validate()?;
Ok(auth_config)
}
/// Resolve the auth keyring backend from a partially loaded bootstrap config.
///
/// This is intended for startup paths that must read auth before managed cloud
/// requirements can be loaded and before a full [`Config`] exists.
pub fn resolve_bootstrap_auth_keyring_backend_kind(
bootstrap_config: &ConfigTomlLoadResult,
) -> std::io::Result<AuthKeyringBackendKind> {
let config_toml = &bootstrap_config.config_toml;
let features = Features::from_sources(
FeatureConfigSource {
features: config_toml.features.as_ref(),
experimental_use_unified_exec_tool: config_toml.experimental_use_unified_exec_tool,
},
FeatureConfigSource::default(),
FeatureOverrides::default(),
);
let managed_features = ManagedFeatures::from_configured(
features,
bootstrap_config
.config_layer_stack
.requirements()
.feature_requirements
.clone(),
)?;
Ok(auth_keyring_backend_kind_from_secret_auth_storage(
managed_features.enabled(Feature::SecretAuthStorage),
))
}
fn auth_keyring_backend_kind_from_secret_auth_storage(
secret_auth_storage_enabled: bool,
) -> AuthKeyringBackendKind {
if secret_auth_storage_enabled {
AuthKeyringBackendKind::Secrets
} else {
AuthKeyringBackendKind::Direct
}
}
#[cfg(test)]
#[path = "auth_keyring_tests.rs"]
mod tests;

View File

@@ -0,0 +1,174 @@
use super::*;
use akode_config::ConfigLayerStack;
use akode_config::ConfigRequirements;
use akode_config::ConfigRequirementsToml;
use akode_config::FeatureRequirementsToml;
use akode_config::RequirementSource;
use akode_config::Sourced;
use akode_config::config_toml::ConfigToml;
use akode_config::config_toml::ForcedChatgptWorkspaceIds;
use akode_config::types::AuthCredentialsStoreMode;
use akode_features::FeaturesToml;
use akode_protocol::config_types::ForcedLoginMethod;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn resolve_bootstrap_auth_keyring_backend_kind_uses_secret_auth_storage_feature()
-> std::io::Result<()> {
let config_toml = ConfigToml {
features: Some(FeaturesToml::from(BTreeMap::from([(
"secret_auth_storage".to_string(),
true,
)]))),
..Default::default()
};
assert_eq!(
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
config_toml,
/*feature_requirements*/ None,
)?)?,
AuthKeyringBackendKind::Secrets
);
let config_toml = ConfigToml {
features: Some(FeaturesToml::from(BTreeMap::from([(
"secret_auth_storage".to_string(),
false,
)]))),
..Default::default()
};
assert_eq!(
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
config_toml.clone(),
/*feature_requirements*/ None,
)?)?,
AuthKeyringBackendKind::Direct
);
let requirements = Sourced::new(
FeatureRequirementsToml {
entries: BTreeMap::from([("secret_auth_storage".to_string(), true)]),
..Default::default()
},
RequirementSource::Unknown,
);
assert_eq!(
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
config_toml,
Some(requirements),
)?)?,
AuthKeyringBackendKind::Secrets
);
Ok(())
}
#[test]
fn managed_auth_restrictions_apply_and_fail_closed() {
let config = ConfigToml {
forced_login_method: None,
forced_chatgpt_workspace_id: Some(ForcedChatgptWorkspaceIds::Multiple(vec![
" denied ".to_string(),
" allowed ".to_string(),
])),
..Default::default()
};
let mut requirements = ConfigRequirements {
allowed_login_methods: Some(Sourced::new(
vec![ForcedLoginMethod::Chatgpt],
RequirementSource::Unknown,
)),
allowed_chatgpt_workspaces: Some(Sourced::new(
vec!["allowed".to_string()],
RequirementSource::Unknown,
)),
..Default::default()
};
let bootstrap_config = ConfigTomlLoadResult {
config_toml: config.clone(),
config_layer_stack: ConfigLayerStack::new(
Vec::new(),
requirements.clone(),
ConfigRequirementsToml::default(),
)
.expect("requirements should stack"),
};
let auth_config = bootstrap_auth_config(Path::new("akode-home"), &bootstrap_config)
.expect("policy should resolve");
assert_eq!(auth_config.forced_login_method, None);
assert!(auth_config.is_login_method_allowed(ForcedLoginMethod::Chatgpt));
assert!(!auth_config.is_login_method_allowed(ForcedLoginMethod::Api));
requirements.allowed_chatgpt_workspaces =
Some(Sourced::new(Vec::new(), RequirementSource::Unknown));
let bootstrap_config = ConfigTomlLoadResult {
config_toml: config,
config_layer_stack: ConfigLayerStack::new(
Vec::new(),
requirements,
ConfigRequirementsToml::default(),
)
.expect("requirements should stack"),
};
assert_eq!(
bootstrap_auth_config(Path::new("akode-home"), &bootstrap_config)
.expect_err("ChatGPT-only policy without an allowed workspace must fail")
.kind(),
std::io::ErrorKind::PermissionDenied
);
}
#[test]
fn bootstrap_auth_config_applies_managed_store() {
let configured_store = AuthCredentialsStoreMode::File;
let configured_url = "https://user.example/backend-api/";
let managed_store = AuthCredentialsStoreMode::Keyring;
let managed_url = "https://managed.example/backend-api/";
let config_toml = ConfigToml {
cli_auth_credentials_store: Some(configured_store),
chatgpt_base_url: Some(configured_url.to_string()),
..Default::default()
};
let requirements = ConfigRequirements {
cli_auth_credentials_store: Some(Sourced::new(managed_store, RequirementSource::Unknown)),
chatgpt_base_url: Some(Sourced::new(
managed_url.to_string(),
RequirementSource::Unknown,
)),
..Default::default()
};
let bootstrap_config = ConfigTomlLoadResult {
config_toml,
config_layer_stack: ConfigLayerStack::new(
Vec::new(),
requirements,
ConfigRequirementsToml::default(),
)
.expect("requirements should stack"),
};
let auth_config = bootstrap_auth_config(Path::new("akode-home"), &bootstrap_config)
.expect("managed authentication settings should resolve");
assert_eq!(auth_config.auth_credentials_store_mode, managed_store);
}
fn config_toml_load_result(
config_toml: ConfigToml,
feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
) -> std::io::Result<ConfigTomlLoadResult> {
let requirements = ConfigRequirements {
feature_requirements,
..Default::default()
};
Ok(ConfigTomlLoadResult {
config_toml,
config_layer_stack: ConfigLayerStack::new(
Vec::new(),
requirements,
ConfigRequirementsToml::default(),
)?,
})
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,351 @@
use anyhow::Context;
use akode_config::types::AppToolApproval;
use akode_config::types::McpServerAuth;
use akode_config::types::McpServerConfig;
use akode_config::types::McpServerEnvVar;
use akode_config::types::McpServerToolConfig;
use akode_config::types::McpServerTransportConfig;
use akode_config::types::McpStartupReadiness;
use akode_config::types::ToolSuggestDisabledTool;
use akode_config::types::ToolSuggestDiscoverableType;
use toml_edit::Array as TomlArray;
use toml_edit::InlineTable;
use toml_edit::Item as TomlItem;
use toml_edit::Table as TomlTable;
use toml_edit::Value as TomlValue;
use toml_edit::value;
pub(super) fn ensure_table_for_write(item: &mut TomlItem) -> Option<&mut TomlTable> {
match item {
TomlItem::Table(table) => Some(table),
TomlItem::Value(value) => {
if let Some(inline) = value.as_inline_table() {
*item = TomlItem::Table(table_from_inline(inline));
item.as_table_mut()
} else {
*item = TomlItem::Table(new_implicit_table());
item.as_table_mut()
}
}
TomlItem::None => {
*item = TomlItem::Table(new_implicit_table());
item.as_table_mut()
}
_ => None,
}
}
pub(super) fn ensure_table_for_read(item: &mut TomlItem) -> Option<&mut TomlTable> {
match item {
TomlItem::Table(table) => Some(table),
TomlItem::Value(value) => {
let inline = value.as_inline_table()?;
*item = TomlItem::Table(table_from_inline(inline));
item.as_table_mut()
}
_ => None,
}
}
fn serialize_mcp_server_table(config: &McpServerConfig) -> anyhow::Result<TomlTable> {
let mut entry = TomlTable::new();
entry.set_implicit(false);
match &config.transport {
McpServerTransportConfig::Stdio {
command,
args,
env,
env_vars,
cwd,
} => {
entry["command"] = value(command.clone());
if !args.is_empty() {
entry["args"] = array_from_iter(args.iter().cloned());
}
if let Some(env) = env
&& !env.is_empty()
{
entry["env"] = table_from_pairs(env.iter());
}
if !env_vars.is_empty() {
entry["env_vars"] = array_from_env_vars(env_vars);
}
if let Some(cwd) = cwd {
entry["cwd"] = value(cwd.as_str());
}
}
McpServerTransportConfig::StreamableHttp {
url,
bearer_token_env_var,
http_headers,
env_http_headers,
http_headers_helper,
} => {
entry["url"] = value(url.clone());
if let Some(env_var) = bearer_token_env_var {
entry["bearer_token_env_var"] = value(env_var.clone());
}
if let Some(headers) = http_headers
&& !headers.is_empty()
{
entry["http_headers"] = table_from_pairs(headers.iter());
}
if let Some(headers) = env_http_headers
&& !headers.is_empty()
{
entry["env_http_headers"] = table_from_pairs(headers.iter());
}
if let Some(command) = http_headers_helper {
entry["http_headers_helper"] = value(command.clone());
}
}
}
match config.auth {
McpServerAuth::OAuth => {}
McpServerAuth::ChatGpt => entry["auth"] = value("chatgpt"),
McpServerAuth::EmaAuth => entry["auth"] = value("ema_auth"),
}
if !config.enabled {
entry["enabled"] = value(false);
}
if !config.is_local_environment() {
entry["environment_id"] = value(config.environment_id.clone());
}
if config.required {
entry["required"] = value(true);
}
match config.startup_readiness {
McpStartupReadiness::Connection => {}
McpStartupReadiness::Catalog => entry["startup_readiness"] = value("catalog"),
}
if config.supports_parallel_tool_calls {
entry["supports_parallel_tool_calls"] = value(true);
}
if let Some(budget) = config.tool_input_schema_max_bytes {
entry["tool_input_schema_max_bytes"] = value(i64::try_from(budget.get())?);
}
if let Some(omit_tools_from) = &config.omit_tools_from {
entry["omit_tools_from"] = array_from_iter(omit_tools_from.iter().map(ToString::to_string));
}
if let Some(timeout) = config.startup_timeout_sec {
entry["startup_timeout_sec"] = value(timeout.as_secs_f64());
}
if let Some(timeout) = config.tool_timeout_sec {
entry["tool_timeout_sec"] = value(timeout.as_secs_f64());
}
if let Some(approval_mode) = config.default_tools_approval_mode {
entry["default_tools_approval_mode"] = value(match approval_mode {
AppToolApproval::Auto => "auto",
AppToolApproval::Prompt => "prompt",
AppToolApproval::Writes => "writes",
AppToolApproval::Approve => "approve",
});
}
if let Some(enabled_tools) = &config.enabled_tools
&& !enabled_tools.is_empty()
{
entry["enabled_tools"] = array_from_iter(enabled_tools.iter().cloned());
}
if let Some(disabled_tools) = &config.disabled_tools
&& !disabled_tools.is_empty()
{
entry["disabled_tools"] = array_from_iter(disabled_tools.iter().cloned());
}
if let Some(scopes) = &config.scopes
&& !scopes.is_empty()
{
entry["scopes"] = array_from_iter(scopes.iter().cloned());
}
if let Some(oauth) = &config.oauth {
let mut oauth_table = TomlTable::new();
oauth_table.set_implicit(false);
if let Some(client_id) = &oauth.client_id
&& !client_id.is_empty()
{
oauth_table["client_id"] = value(client_id.clone());
}
if let Some(client_secret) = &oauth.client_secret {
oauth_table["client_secret"] = value(client_secret.as_str());
}
if let Some(callback_url) = &oauth.callback_url {
oauth_table["callback_url"] = value(callback_url.clone());
}
if let Some(callback_port) = oauth.callback_port {
oauth_table["callback_port"] = value(i64::from(callback_port));
}
if !oauth_table.is_empty() {
entry["oauth"] = TomlItem::Table(oauth_table);
}
}
if let Some(resource) = &config.oauth_resource
&& !resource.is_empty()
{
entry["oauth_resource"] = value(resource.clone());
}
if !config.tools.is_empty() {
let mut tools = new_implicit_table();
let mut tool_entries: Vec<_> = config.tools.iter().collect();
tool_entries.sort_by_key(|(name, _)| *name);
for (name, tool_config) in tool_entries {
tools.insert(name, serialize_mcp_server_tool(tool_config)?);
}
entry.insert("tools", TomlItem::Table(tools));
}
Ok(entry)
}
fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> anyhow::Result<TomlItem> {
let mut entry = TomlTable::new();
entry.set_implicit(false);
if let Some(approval_mode) = config.approval_mode {
entry["approval_mode"] = value(match approval_mode {
AppToolApproval::Auto => "auto",
AppToolApproval::Prompt => "prompt",
AppToolApproval::Writes => "writes",
AppToolApproval::Approve => "approve",
});
}
if let Some(output_token_limit) = config.output_token_limit {
entry["output_token_limit"] = value(
i64::try_from(output_token_limit.get())
.context("output_token_limit exceeds the TOML integer range")?,
);
}
Ok(TomlItem::Table(entry))
}
pub(super) fn serialize_mcp_server(config: &McpServerConfig) -> anyhow::Result<TomlItem> {
Ok(TomlItem::Table(serialize_mcp_server_table(config)?))
}
pub(super) fn serialize_mcp_server_inline(config: &McpServerConfig) -> anyhow::Result<InlineTable> {
Ok(serialize_mcp_server_table(config)?.into_inline_table())
}
pub(super) fn merge_inline_table(existing: &mut InlineTable, replacement: InlineTable) {
existing.retain(|key, _| replacement.get(key).is_some());
for (key, value) in replacement.iter() {
if let Some(existing_value) = existing.get_mut(key) {
let mut updated_value = value.clone();
*updated_value.decor_mut() = existing_value.decor().clone();
*existing_value = updated_value;
} else {
existing.insert(key.to_string(), value.clone());
}
}
}
fn table_from_inline(inline: &InlineTable) -> TomlTable {
let mut table = new_implicit_table();
for (key, value) in inline.iter() {
let mut value = value.clone();
let decor = value.decor_mut();
decor.set_suffix("");
table.insert(key, TomlItem::Value(value));
}
table
}
pub(super) fn new_implicit_table() -> TomlTable {
let mut table = TomlTable::new();
table.set_implicit(true);
table
}
pub(super) fn parse_tool_suggest_disabled_tool(
value: &TomlValue,
) -> Option<ToolSuggestDisabledTool> {
let table = value.as_inline_table()?;
let kind = match table.get("type").and_then(TomlValue::as_str) {
Some("connector") => ToolSuggestDiscoverableType::Connector,
Some("plugin") => ToolSuggestDiscoverableType::Plugin,
_ => return None,
};
let id = table.get("id").and_then(TomlValue::as_str)?;
Some(ToolSuggestDisabledTool {
kind,
id: id.to_string(),
})
}
pub(super) fn parse_tool_suggest_disabled_tool_table(
table: &TomlTable,
) -> Option<ToolSuggestDisabledTool> {
let kind = match table.get("type").and_then(TomlItem::as_str) {
Some("connector") => ToolSuggestDiscoverableType::Connector,
Some("plugin") => ToolSuggestDiscoverableType::Plugin,
_ => return None,
};
let id = table.get("id").and_then(TomlItem::as_str)?;
Some(ToolSuggestDisabledTool {
kind,
id: id.to_string(),
})
}
pub(super) fn tool_suggest_disabled_tools_value(
disabled_tools: &[ToolSuggestDisabledTool],
) -> TomlItem {
let mut array = TomlArray::new();
for disabled_tool in disabled_tools {
let mut table = InlineTable::new();
table.insert(
"type",
match disabled_tool.kind {
ToolSuggestDiscoverableType::Connector => "connector",
ToolSuggestDiscoverableType::Plugin => "plugin",
}
.into(),
);
table.insert("id", disabled_tool.id.clone().into());
array.push(table);
}
TomlItem::Value(array.into())
}
fn array_from_iter<I>(iter: I) -> TomlItem
where
I: Iterator<Item = String>,
{
let mut array = TomlArray::new();
for value in iter {
array.push(value);
}
TomlItem::Value(array.into())
}
fn array_from_env_vars(env_vars: &[McpServerEnvVar]) -> TomlItem {
let mut array = TomlArray::new();
for env_var in env_vars {
match env_var {
McpServerEnvVar::Name(name) => array.push(name.clone()),
McpServerEnvVar::Config { name, source } => {
let mut table = InlineTable::new();
table.insert("name", name.clone().into());
if let Some(source) = source {
table.insert("source", source.clone().into());
}
array.push(table);
}
}
}
TomlItem::Value(array.into())
}
fn table_from_pairs<'a, I>(pairs: I) -> TomlItem
where
I: IntoIterator<Item = (&'a String, &'a String)>,
{
let mut entries: Vec<_> = pairs.into_iter().collect();
entries.sort_by_key(|(key, _)| *key);
let mut table = TomlTable::new();
table.set_implicit(false);
for (key, val) in entries {
table.insert(key, value(val.clone()));
}
TomlItem::Table(table)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
//! Resolves Guardian requirements and retained configuration fallbacks identically
//! during startup and runtime publication.
use super::guardian_policy_config_from_requirements;
use super::normalize_guardian_policy_config;
use akode_config::ConfigRequirements;
use akode_config::ConfigRequirementsToml;
use akode_config::config_toml::AutoReviewToml;
use akode_protocol::config_types::ApprovalsReviewer;
pub(crate) fn resolve_guardian_policy_text(
requirements: &ConfigRequirementsToml,
fallback: Option<&AutoReviewToml>,
) -> (Option<String>, Option<String>) {
let policy = guardian_policy_config_from_requirements(requirements).or_else(|| {
normalize_guardian_policy_config(fallback.and_then(|fallback| fallback.policy.as_deref()))
});
let extra = normalize_guardian_policy_config(requirements.guardian_extra_policy.as_deref())
.or_else(|| {
normalize_guardian_policy_config(
fallback.and_then(|fallback| fallback.extra_policy.as_deref()),
)
});
(policy, extra)
}
/// Resolves the effective reviewer without replacing the retained request.
/// Trusted private reviewers omit the model to bypass model-required review.
pub(crate) fn resolve_guardian_reviewer(
requested: ApprovalsReviewer,
model: Option<&str>,
requirements: &ConfigRequirements,
) -> super::ConstraintResult<ApprovalsReviewer> {
let reviewer = if model.is_some_and(|model| requirements.auto_review_required_for_model(model))
{
ApprovalsReviewer::AutoReview
} else if requirements.approvals_reviewer.can_set(&requested).is_ok() {
requested
} else {
requirements.approvals_reviewer.value()
};
requirements.approvals_reviewer.can_set(&reviewer)?;
Ok(reviewer)
}

View File

@@ -0,0 +1,452 @@
use std::collections::BTreeMap;
use akode_config::ConfigLayerSource;
use akode_config::ConfigLayerStack;
use akode_config::Constrained;
use akode_config::ConstrainedWithSource;
use akode_config::ConstraintError;
use akode_config::ConstraintResult;
use akode_config::FeatureRequirementsToml;
use akode_config::RequirementSource;
use akode_config::Sourced;
use akode_config::config_toml::ConfigToml;
use akode_features::Feature;
use akode_features::FeatureConfigSource;
use akode_features::FeatureOverrides;
use akode_features::FeatureToml;
use akode_features::Features;
use akode_features::RuntimeAuthMode;
use akode_features::canonical_feature_for_key;
use akode_features::feature_for_key;
/// A project's explicit opt-in replaces only a strictly lower-priority V1 opt-out.
pub(super) fn project_overrides_legacy_subagent_opt_out(layers: &ConfigLayerStack) -> bool {
let mut project_enabled = false;
for layer in layers.layers_high_to_low() {
if let Some(features) = layer.config.get("features").and_then(toml::Value::as_table)
&& features.iter().any(|(key, enabled)| {
enabled.as_bool() == Some(false) && feature_for_key(key) == Some(Feature::Collab)
})
{
return project_enabled;
}
if matches!(layer.name, ConfigLayerSource::Project { .. })
&& layer
.config
.get("agents")
.and_then(|agents| agents.get("enabled"))
.and_then(toml::Value::as_bool)
== Some(true)
{
project_enabled = true;
}
}
false
}
/// Wrapper around [`Features`] which enforces constraints defined in
/// `FeatureRequirementsToml` and provides normalization to ensure constraints
/// are satisfied. Constraints are enforced on construction and mutation of
/// `ManagedFeatures`.
#[derive(Debug, Clone, PartialEq)]
pub struct ManagedFeatures {
value: ConstrainedWithSource<Features>,
pinned_features: BTreeMap<Feature, bool>,
}
impl Default for ManagedFeatures {
fn default() -> Self {
Self {
value: ConstrainedWithSource::new(
Constrained::allow_any(Features::default()),
/*source*/ None,
),
pinned_features: BTreeMap::new(),
}
}
}
impl ManagedFeatures {
pub(crate) fn from_configured(
configured_features: Features,
feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
) -> std::io::Result<Self> {
Self::from_configured_with_optional_warnings(
configured_features,
feature_requirements,
/*startup_warnings*/ None,
)
}
/// Applies managed feature requirements and dependency normalization to
/// configured features, collecting warnings for unsupported requirements.
pub fn from_configured_with_warnings(
configured_features: Features,
feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<Self> {
Self::from_configured_with_optional_warnings(
configured_features,
feature_requirements,
Some(startup_warnings),
)
}
fn from_configured_with_optional_warnings(
configured_features: Features,
feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
startup_warnings: Option<&mut Vec<String>>,
) -> std::io::Result<Self> {
let (pinned_features, source) = match feature_requirements {
Some(Sourced {
value: feature_requirements,
source,
}) => (
parse_feature_requirements(feature_requirements, &source, startup_warnings),
Some(source),
),
None => (BTreeMap::new(), None),
};
let normalized_features = normalize_candidate(configured_features, &pinned_features);
validate_pinned_features(&normalized_features, &pinned_features, source.as_ref())?;
Ok(Self {
value: ConstrainedWithSource::new(Constrained::allow_any(normalized_features), source),
pinned_features,
})
}
pub fn get(&self) -> &Features {
self.value.get()
}
fn normalize_and_validate(&self, candidate: Features) -> ConstraintResult<Features> {
let normalized = normalize_candidate(candidate, &self.pinned_features);
self.value.can_set(&normalized)?;
validate_pinned_features_constraint(
&normalized,
&self.pinned_features,
self.value.source.as_ref(),
)?;
Ok(normalized)
}
pub fn can_set(&self, candidate: &Features) -> ConstraintResult<()> {
self.normalize_and_validate(candidate.clone()).map(|_| ())
}
pub fn set(&mut self, candidate: Features) -> ConstraintResult<()> {
let normalized = self.normalize_and_validate(candidate)?;
self.value.value.set(normalized)
}
pub fn set_enabled(&mut self, feature: Feature, enabled: bool) -> ConstraintResult<()> {
let mut next = self.get().clone();
next.set_enabled(feature, enabled);
self.set(next)
}
/// Refresh ordinary MCP feature values and pins without changing session-static features.
pub(crate) fn refresh_mcp_features(&mut self, next: &Self) -> ConstraintResult<()> {
let mut refreshed = self.clone();
let mut values = self.get().clone();
for feature in [
Feature::EnableMcpApps,
Feature::McpConnectionSharing,
Feature::McpLazyStdioStartup,
Feature::SecretAuthStorage,
Feature::McpOAuthRefreshCoordination,
] {
values.set_enabled(feature, next.enabled(feature));
if let Some(enabled) = next.pinned_features.get(&feature) {
refreshed.pinned_features.insert(feature, *enabled);
} else {
refreshed.pinned_features.remove(&feature);
}
}
refreshed.value.source = next.value.source.clone().or(refreshed.value.source);
refreshed.set(values)?;
*self = refreshed;
Ok(())
}
pub fn enable(&mut self, feature: Feature) -> ConstraintResult<()> {
self.set_enabled(feature, /*enabled*/ true)
}
pub fn disable(&mut self, feature: Feature) -> ConstraintResult<()> {
self.set_enabled(feature, /*enabled*/ false)
}
}
/// Only available for tests to ensure `ManagedFeatures` is constructed with
/// any required constraints taken into account.
#[cfg(test)]
impl From<Features> for ManagedFeatures {
fn from(features: Features) -> Self {
Self {
value: ConstrainedWithSource::new(
Constrained::allow_any(features),
/*source*/ None,
),
pinned_features: BTreeMap::new(),
}
}
}
impl std::ops::Deref for ManagedFeatures {
type Target = Features;
fn deref(&self) -> &Self::Target {
self.get()
}
}
fn normalize_candidate(
mut candidate: Features,
pinned_features: &BTreeMap<Feature, bool>,
) -> Features {
// Legacy user opt-outs selected the removed shell backend. Only managed
// requirements may disable the remaining unified-exec implementation.
if !pinned_features.contains_key(&Feature::UnifiedExec) {
candidate.enable(Feature::UnifiedExec);
}
for (feature, enabled) in pinned_features {
candidate.set_enabled(*feature, *enabled);
}
candidate.normalize_dependencies();
candidate
}
fn validate_pinned_features_constraint(
normalized_features: &Features,
pinned_features: &BTreeMap<Feature, bool>,
source: Option<&RequirementSource>,
) -> ConstraintResult<()> {
let Some(source) = source else {
return Ok(());
};
let allowed = feature_requirements_display(pinned_features);
for (feature, enabled) in pinned_features {
if normalized_features.enabled(*feature) != *enabled {
return Err(ConstraintError::InvalidValue {
field_name: "features",
candidate: format!(
"{}={}",
feature.key(),
normalized_features.enabled(*feature)
),
allowed,
requirement_source: source.clone(),
});
}
}
Ok(())
}
fn validate_pinned_features(
normalized_features: &Features,
pinned_features: &BTreeMap<Feature, bool>,
source: Option<&RequirementSource>,
) -> std::io::Result<()> {
validate_pinned_features_constraint(normalized_features, pinned_features, source)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
fn feature_requirements_display(feature_requirements: &BTreeMap<Feature, bool>) -> String {
let values = feature_requirements
.iter()
.map(|(feature, enabled)| format!("{}={enabled}", feature.key()))
.collect::<Vec<_>>();
format!("[{}]", values.join(", "))
}
fn parse_feature_requirements(
feature_requirements: FeatureRequirementsToml,
source: &RequirementSource,
mut startup_warnings: Option<&mut Vec<String>>,
) -> BTreeMap<Feature, bool> {
let mut pinned_features = BTreeMap::new();
for (key, enabled) in feature_requirements.entries {
if key == Feature::Personality.key() || key == Feature::PluginDiscoveryPrefetch.key() {
continue;
}
if key == Feature::Worktrees.key() || key == Feature::RealtimeConversation.key() {
push_feature_requirement_warning(
&mut startup_warnings,
format!(
"Ignoring removed `features` requirement `{key}` from {source}; availability no longer depends on this feature flag."
),
);
continue;
}
if matches!(key.as_str(), "shell_zsh_fork" | "unified_exec_zsh_fork") {
push_feature_requirement_warning(
&mut startup_warnings,
format!(
"Ignoring removed `features` requirement `{key}` from {source}; the patched zsh backend has been removed."
),
);
continue;
}
if key == Feature::GuardianThreadContext.key() {
push_feature_requirement_warning(
&mut startup_warnings,
format!(
"Ignoring removed `features` requirement `{key}` from {source}; thread-owned Guardian context is always enabled."
),
);
continue;
}
if key == "auto_review" {
pinned_features.insert(Feature::GuardianApproval, enabled);
continue;
}
if let Some(feature) = canonical_feature_for_key(&key) {
pinned_features.insert(feature, enabled);
continue;
}
if let Some(feature) = feature_for_key(&key) {
push_feature_requirement_warning(
&mut startup_warnings,
format!(
"Using legacy `features` requirement `{key}` from {source}; prefer canonical feature key `{}`",
feature.key()
),
);
pinned_features.insert(feature, enabled);
continue;
}
push_feature_requirement_warning(
&mut startup_warnings,
format!("Ignoring unknown `features` requirement `{key}` from {source}"),
);
}
pinned_features
}
fn push_feature_requirement_warning(
startup_warnings: &mut Option<&mut Vec<String>>,
message: String,
) {
tracing::warn!("{message}");
if let Some(startup_warnings) = startup_warnings.as_deref_mut() {
startup_warnings.push(message);
}
}
fn explicit_feature_settings_in_config(cfg: &ConfigToml) -> Vec<(String, Feature, bool)> {
let mut explicit_settings = Vec::new();
if let Some(features) = cfg.features.as_ref() {
for (key, enabled) in features.entries() {
if let Some(feature) = feature_for_key(&key) {
explicit_settings.push((format!("features.{key}"), feature, enabled));
}
}
}
if let Some(enabled) = cfg.experimental_use_unified_exec_tool {
explicit_settings.push((
"experimental_use_unified_exec_tool".to_string(),
Feature::UnifiedExec,
enabled,
));
}
explicit_settings
}
pub(crate) fn resolve_runtime_auth_mode(
cfg: &ConfigToml,
requirements: Option<&Sourced<FeatureRequirementsToml>>,
) -> std::io::Result<RuntimeAuthMode> {
let configured = cfg
.features
.as_ref()
.and_then(|features| features.runtime_agent_instances.as_ref())
.and_then(|feature| match feature {
FeatureToml::Enabled(_) => None,
FeatureToml::Config(config) => config.mode,
});
if let Some(requirements) = requirements
&& let Some(required) = requirements.value.runtime_auth_mode
{
if configured.is_some_and(|mode| mode != required) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
ConstraintError::InvalidValue {
field_name: "features.runtime_agent_instances.mode",
candidate: format!("{:?}", configured.unwrap_or_default()),
allowed: format!("{required:?}"),
requirement_source: requirements.source.clone(),
},
));
}
return Ok(required);
}
Ok(configured.unwrap_or_default())
}
pub(crate) fn validate_explicit_feature_settings_in_config_toml(
cfg: &ConfigToml,
feature_requirements: Option<&Sourced<FeatureRequirementsToml>>,
) -> std::io::Result<()> {
resolve_runtime_auth_mode(cfg, feature_requirements)?;
let Some(Sourced {
value: feature_requirements,
source,
}) = feature_requirements
else {
return Ok(());
};
let pinned_features = parse_feature_requirements(
feature_requirements.clone(),
source,
/*startup_warnings*/ None,
);
if pinned_features.is_empty() {
return Ok(());
}
let allowed = feature_requirements_display(&pinned_features);
for (path, feature, enabled) in explicit_feature_settings_in_config(cfg) {
if pinned_features
.get(&feature)
.is_some_and(|required| *required != enabled)
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
ConstraintError::InvalidValue {
field_name: "features",
candidate: format!("{path}={enabled}"),
allowed,
requirement_source: source.clone(),
},
));
}
}
Ok(())
}
pub(crate) fn validate_feature_requirements_in_config_toml(
cfg: &ConfigToml,
feature_requirements: Option<&Sourced<FeatureRequirementsToml>>,
) -> std::io::Result<()> {
let configured_features = Features::from_sources(
FeatureConfigSource {
features: cfg.features.as_ref(),
experimental_use_unified_exec_tool: cfg.experimental_use_unified_exec_tool,
},
FeatureConfigSource::default(),
FeatureOverrides::default(),
);
ManagedFeatures::from_configured(configured_features, feature_requirements.cloned()).map(|_| ())
}

View File

@@ -0,0 +1,326 @@
#![cfg(test)]
//! Exercises the policy carried by MCP independently of tool-call publication.
use super::*;
use crate::config::ConfigBuilder;
use anyhow::Context;
use akode_execpolicy::Decision;
use akode_execpolicy::NetworkRuleProtocol::Https;
use akode_http_client::HttpClientBuilder;
use akode_network_proxy::NetworkMode;
use akode_protocol::models::PermissionProfile as Profile;
use akode_protocol::models::PermissionProfile::Disabled;
use akode_protocol::models::PermissionProfile::External;
use akode_protocol::permissions::NetworkSandboxPolicy::Enabled;
use akode_protocol::permissions::NetworkSandboxPolicy::Restricted;
use akode_protocol::protocol::AskForApproval::Never;
use akode_protocol::protocol::AskForApproval::OnRequest;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::time::Duration;
use test_case::test_case;
fn saved_rules(rules: &[(&str, Decision)]) -> anyhow::Result<Policy> {
let mut policy = Policy::empty();
for &(host, decision) in rules {
policy.add_network_rule(host, Https, decision, /*justification*/ None)?;
}
Ok(policy)
}
fn primary_controller_policy(
controller: &NetworkProxySpec,
profile: &Profile,
rules: &Policy,
) -> std::io::Result<NetworkPolicyMetadata> {
NetworkProxySpec::mcp_network_policy(
Some(controller),
profile,
McpNetworkRoute {
primary_allows_proxy: !matches!(profile, Disabled),
local_binding: LocalBindingPolicy::DefaultFalse,
owner: None,
},
profile,
OnRequest,
rules,
)
}
#[test_case(Profile::read_only(), false, None, false; "restricted offline")]
#[test_case(Profile::read_only(), true, None, true; "controller proxy")]
#[test_case(Profile::read_only(), false, Some(true), true; "managed proxy")]
#[test_case(Profile::read_only(), true, Some(false), false; "managed disable")]
#[test_case(External { network: Enabled }, false, None, true; "external network")]
#[test_case(Disabled, false, None, true; "disabled sandbox")]
#[test_case(Disabled, true, Some(false), false; "managed veto in disabled sandbox")]
fn controller_policy_keeps_managed_restrictions_after_stale_grants(
profile: Profile,
proxy_enabled: bool,
managed_enabled: Option<bool>,
expected_enabled: bool,
) -> anyhow::Result<()> {
let requirements = serde_json::from_value(json!({
"enabled": managed_enabled, "managed_allowed_domains_only": true, "allow_local_binding": true,
"review_domains": ["allowed2.example.com"],
"domains": {"allowed?.example.com": "allow", "blocked.example.com": "deny"},
}))?;
let config = NetworkProxyConfig {
enabled: proxy_enabled,
mode: NetworkMode::Limited,
..Default::default()
};
let controller =
NetworkProxySpec::from_config_and_constraints(config, Some(requirements), &profile)?;
let saved = saved_rules(&[
("previously-allowed.example.com", Decision::Allow),
("allowed1.example.com", Decision::Forbidden),
])?;
let result = primary_controller_policy(&controller, &profile, &saved)?;
let routed = managed_enabled.unwrap_or(proxy_enabled) && !matches!(profile, Disabled);
let mut denied = vec!["blocked.example.com"];
if routed && matches!(profile, Profile::Managed { .. }) {
denied.push("allowed1.example.com");
}
denied.push("allowed2.example.com");
assert_eq!(
serde_json::to_value(result)?,
json!({
"enabled": expected_enabled, "mode": if routed { "limited" } else { "full" }, "allowedDomains": ["allowed?.example.com"],
"deniedDomains": denied, "hardDenyAllowlistMisses": true,
})
);
Ok(())
}
const MANAGED_DOMAINS: &str =
"enabled = true\ndomains = { '*.example' = 'allow', 'admin.test' = 'deny' }";
#[test_case(None, false, Profile::read_only(), Some(MANAGED_DOMAINS), OnRequest, false, false; "no proxy restricted")]
#[test_case(None, false, Disabled, Some(MANAGED_DOMAINS), Never, true, false; "no proxy unrestricted")]
#[test_case(Some(Profile::workspace_write()), true, External { network: Enabled }, Some(MANAGED_DOMAINS), OnRequest, true, true; "external secondary retains thread denial under wildcard")]
#[test_case(Some(External { network: Enabled }), true, Profile::workspace_write(), Some(MANAGED_DOMAINS), Never, true, true; "managed secondary cannot restore rejected grants")]
#[test_case(Some(Disabled), false, Disabled, Some(MANAGED_DOMAINS), Never, true, false; "full access primary uses direct networking")]
#[test_case(Some(Disabled), false, Profile::workspace_write(), Some(MANAGED_DOMAINS), Never, false, false; "restricted secondary stays offline with full access primary")]
#[test_case(Some(Profile::workspace_write()), true, Disabled, Some(MANAGED_DOMAINS), OnRequest, true, true; "full access secondary uses primary proxy")]
#[test_case(Some(Profile::workspace_write()), true, Profile::workspace_write(), Some(MANAGED_DOMAINS), OnRequest, true, false; "managed call may approve misses")]
#[test_case(Some(Profile::workspace_write()), true, Profile::workspace_write(), Some(MANAGED_DOMAINS), Never, true, true; "never denies routed misses")]
#[test_case(Some(Profile::workspace_write()), true, Profile::workspace_write(), None, OnRequest, true, true; "profile-only proxy denies misses")]
#[test_case(Some(Disabled), false, Disabled, None, OnRequest, true, false; "direct call bypasses profile and saved rules")]
#[test_case(Some(Disabled), false, Disabled, Some("http_port = 3128"), OnRequest, true, false; "managed port leaves direct calls unrestricted")]
fn controller_allowlist_misses_follow_call_profile(
thread: Option<Profile>,
primary_allows_proxy: bool,
profile: Profile,
requirements: Option<&str>,
approval: AskForApproval,
enabled: bool,
hard_deny: bool,
) -> anyhow::Result<()> {
let mut config: NetworkProxyConfig = toml::from_str(
r#"
enabled = true
mode = 'limited'
allow_local_binding = true
domains = { '**.profile.test' = 'allow', 'blocked.example' = 'deny' }
mitm = true
mitm_hooks = [{ host = 'Hook.Profile.Test.:443', match = { methods = ['GET'], path_prefixes = ['/allowed/'] } }]
"#,
)?;
config.review_domains.push("review.profile.test".into());
let spec = NetworkProxySpec::from_config_and_constraints(
config,
requirements.map(toml::from_str).transpose()?,
&profile,
)?;
let saved = saved_rules(&[
("review.profile.test", Decision::Allow),
("saved-deny.test", Decision::Forbidden),
])?;
let result = NetworkProxySpec::mcp_network_policy(
thread.as_ref().map(|_| &spec),
thread.as_ref().unwrap_or(&profile),
McpNetworkRoute {
primary_allows_proxy,
local_binding: LocalBindingPolicy::DefaultFalse,
owner: None,
},
&profile,
approval,
&saved,
)?;
let mut allowed = Vec::new();
let mut denied = Vec::new();
if thread.is_some() && requirements == Some(MANAGED_DOMAINS) {
allowed.push("*.example");
denied.push("admin.test");
}
let uses_profile_rules = matches!(thread, Some(Profile::Managed { .. }));
if uses_profile_rules {
allowed.extend(["**.profile.test", "review.profile.test"]);
denied.extend(["blocked.example", "saved-deny.test"]);
}
if primary_allows_proxy {
denied.extend(["review.profile.test", "hook.profile.test"]);
}
assert_eq!(
serde_json::to_value(result)?,
json!({
"enabled": enabled, "mode": if primary_allows_proxy { "limited" } else { "full" },
"allowedDomains": allowed, "deniedDomains": denied, "hardDenyAllowlistMisses": hard_deny,
})
);
Ok(())
}
const FIXED_CONTROLLER_RULES: &str = "managed_allowed_domains_only = true\ndomains = { 'managed.example' = 'allow', 'managed-denied.example' = 'deny' }";
const ACTIVE_CONTROLLER: &str =
"enabled = true\nmode = 'limited'\ndomains = { 'controller-denied.example' = 'deny' }";
#[test_case(None, None, None, [true, false, true]; "absent controller")]
#[test_case(Some("enabled = false"), Some(FIXED_CONTROLLER_RULES), Some("managed-denied.example"), [false; 3]; "disabled controller with a disjoint managed allowlist")]
#[test_case(Some(ACTIVE_CONTROLLER), None, Some("controller-denied.example"), [true; 3]; "profile-only proxy with a reviewable owner")]
fn owner_activation_and_traffic_policy(
configured: Option<&str>,
managed: Option<&str>,
controller_denial: Option<&str>,
[required, offline, direct]: [bool; 3],
) -> anyhow::Result<()> {
let fixed_owner = managed.is_some() || configured.is_none();
let spec = NetworkProxySpec::from_config_and_constraints(
toml::from_str(configured.unwrap_or_default())?,
managed.map(toml::from_str).transpose()?,
&Profile::read_only(),
)?;
let controller = configured.or(managed).map(|_| &spec);
let mut owner: EnvironmentNetworkPolicy = serde_json::from_value(json!({
"domains": {"owner.example": "allow", "owner-denied.example": "deny"},
"reviewDomains": ["owner-review.example"], "allowUpstreamProxy": true,
"allowLocalBinding": true, "dangerouslyAllowAllUnixSockets": false, "managedAllowedDomainsOnly": fixed_owner,
}))?;
let saved = saved_rules(&[("owner-denied.example", Decision::Allow)])?;
let mut denied = vec!["owner-denied.example"];
denied.extend(controller_denial);
denied.push("owner-review.example");
for (requires_proxy, network, expected) in [
(true, Restricted, required),
(false, Restricted, offline),
(false, Enabled, direct),
] {
owner.requires_proxy = requires_proxy;
let profile = Profile::from_runtime_permissions(
&Profile::read_only().file_system_sandbox_policy(),
network,
);
for approval in [OnRequest, Never] {
let result = NetworkProxySpec::mcp_network_policy(
controller,
&Disabled,
McpNetworkRoute {
primary_allows_proxy: false,
local_binding: LocalBindingPolicy::DefaultFalse,
owner: Some(&owner),
},
&profile,
approval,
&saved,
)?;
assert_eq!(
json!(result),
json!({
"enabled": expected, "mode": if fixed_owner { "full" } else { "limited" }, "allowedDomains": ["owner.example"],
"deniedDomains": denied, "hardDenyAllowlistMisses": fixed_owner || approval == Never,
})
);
}
}
Ok(())
}
const MIXED_DOMAINS: &str = r#"
[permissions.profile.network.domains]
"*" = "allow"
"*.example" = "allow"
"named.example" = "allow"
"localhost" = "allow"
"127.0.0.1:*" = "allow"
"192.168.0.2" = "allow"
"[::1]" = "allow"
"#;
#[test_case("domains = { 'allowed.example' = 'allow' }", "outside.invalid", true, &["allowed.example"]; "allowlist miss")]
#[test_case(MIXED_DOMAINS, "127.0.0.1", false, &["192.168.0.2", "[::1]"]; "wildcard cannot grant loopback")]
#[test_case(MIXED_DOMAINS, "192.168.0.1", false, &["192.168.0.2", "[::1]"]; "wildcard cannot grant private address")]
#[tokio::test]
async fn profile_only_allowlist_projection_matches_native_proxy_denial(
domains: &str,
blocked_host: &str,
allow_local_binding: bool,
expected_grants: &[&str],
) -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let source = format!(
r#"
default_permissions = "profile"
features.network_proxy = true
permissions.profile.filesystem.":root" = "read"
[permissions.profile.network]
enabled = true
enable_socks5 = false
allow_local_binding = {allow_local_binding}
{domains}
"#
);
std::fs::write(home.path().join("config.toml"), source)?;
let config = ConfigBuilder::without_managed_config_for_tests()
.codex_home(home.path().to_path_buf())
.without_project_context()
.build()
.await?;
let spec = config
.permissions
.network
.as_ref()
.context("loaded profile proxy")?;
let profile = config.permissions.permission_profile();
let requirements = config.config_layer_stack.requirements_toml();
assert!(requirements.network.is_none());
let result = primary_controller_policy(spec, profile, &Policy::empty())?;
assert!(result.enabled && result.hard_deny_allowlist_misses);
assert_eq!(result.allowed_domains, expected_grants);
core_test_support::skip_if_no_network!(Ok(()));
let proxy = spec
.start_proxy(
profile,
ManagedProxyRouting::DedicatedListeners,
LocalBindingPolicy::DefaultFalse,
/*policy_decider*/ None,
/*blocked_request_observer*/ None,
/*enable_network_approval_flow*/ false,
NetworkProxyAuditMetadata::default(),
)
.await?;
let response = HttpClientBuilder::new()
.build_direct()?
.get(format!("http://{}/", proxy.proxy().http_addr()))
.header(http::header::HOST, blocked_host)
.timeout(Duration::from_secs(5))
.send()
.await?;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(response.headers()["x-proxy-error"], "blocked-by-allowlist");
let denial = response.json::<Value>().await?;
assert_eq!(denial["host"], blocked_host);
assert_eq!(
denial["reason"],
if allow_local_binding {
"not_allowed"
} else {
"not_allowed_local"
}
);
Ok(())
}

View File

@@ -0,0 +1,63 @@
//! Metrics derived from loaded configuration at session start.
use super::Config;
use akode_config::ConfigLayerSource;
use akode_config::ConfigLayerStack;
use akode_features::FEATURES;
use akode_features::Stage;
use akode_otel::SessionTelemetry;
pub(crate) fn emit_session_start_metrics(config: &Config, telemetry: &SessionTelemetry) {
for feature in FEATURES {
if matches!(feature.stage, Stage::Removed) {
continue;
}
if config.features.enabled(feature.id) != feature.default_enabled {
telemetry.counter(
"codex.feature.state",
/*inc*/ 1,
&[
("feature", feature.key),
("value", &config.features.enabled(feature.id).to_string()),
],
);
}
}
#[cfg(windows)]
crate::windows_system_config::emit_namespace_squatting_probe();
}
/// Report saved opt-outs even when a higher-precedence session setting overrides them.
pub(crate) fn legacy_multi_agent_disabled_sources(layers: &ConfigLayerStack) -> Vec<&'static str> {
let mut user = None;
let mut project = None;
for layer in layers.layers_low_to_high() {
let setting = match layer.name {
ConfigLayerSource::User { .. } => &mut user,
ConfigLayerSource::Project { .. } => &mut project,
_ => continue,
};
if let Some(value) = layer
.config
.get("features")
.and_then(|features| features.get("multi_agent"))
.and_then(toml::Value::as_bool)
{
*setting = Some(value);
}
}
let managed = layers
.requirements()
.feature_requirements
.as_ref()
.and_then(|requirements| requirements.value.entries.get("multi_agent"))
.copied();
[
("user", user),
("project", project),
("managed_requirement", managed),
]
.into_iter()
.filter_map(|(source, value)| (value == Some(false)).then_some(source))
.collect()
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,176 @@
//! Network configuration materialization from explicit, already-selected inputs.
//!
//! Preparing the configured proxy precedes permission requirements fallback in
//! local configuration loading. Keep that phase separate from applying network
//! requirements to the final permission profile so both callers share the same
//! ordering without reading a Config or any host state here.
//! Environment policy conversion drops listener addresses, and final validation
//! uses the same policy resolver as command execution.
use akode_config::NetworkConstraints;
use akode_config::Sourced;
use akode_config::permissions_toml::NetworkToml;
use akode_execpolicy::Policy;
use akode_features::FeatureToml;
use akode_features::FeaturesToml;
use akode_network_proxy::EnvironmentNetworkPolicy;
use akode_network_proxy::NetworkProxyConfig;
use akode_protocol::models::PermissionProfile;
use akode_utils_path_uri::Platform;
use super::NetworkProxySpec;
use super::permissions::apply_network_proxy_feature_config;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("invalid portable environment network policy")]
pub struct EnvironmentNetworkConfigError;
/// Drops listener addresses and rejects unsupported controller fields in an
/// environment's selected network configuration. Use the returned value when
/// deciding whether a policy is present and when preparing it.
///
/// Domain and socket values may be replaced by feature settings or requirements.
/// Validate the composed policy with [`validate_environment_network_policy`].
pub fn project_environment_profile_network(
network: Option<NetworkToml>,
) -> Result<Option<NetworkToml>, EnvironmentNetworkConfigError> {
let Some(mut network) = network else {
return Ok(None);
};
network.proxy_url = None;
network.socks_url = None;
let supported = NetworkToml {
enabled: network.enabled,
allow_upstream_proxy: network.allow_upstream_proxy,
dangerously_allow_all_unix_sockets: network.dangerously_allow_all_unix_sockets,
domains: network.domains.clone(),
unix_sockets: network.unix_sockets.clone(),
allow_local_binding: network.allow_local_binding,
..Default::default()
};
if network != supported {
return Err(EnvironmentNetworkConfigError);
}
Ok(Some(network))
}
/// Validates the owner policy for its final permission profile using the native
/// environment resolver. Execution also applies controller and saved exec rules.
/// This checks the supplied executor's path syntax; socket support is checked at execution.
pub fn validate_environment_network_policy(
policy: &EnvironmentNetworkPolicy,
permission_profile: &PermissionProfile,
executor_os: Platform,
) -> Result<(), EnvironmentNetworkConfigError> {
NetworkProxySpec::for_environment(
/*controller*/ None,
policy,
permission_profile,
&Policy::empty(),
akode_network_proxy::LocalBindingPolicy::DefaultFalse,
)
.and_then(|spec| spec.build_config_state_for_spec(executor_os).map(|_| ()))
.map_err(|_| EnvironmentNetworkConfigError)
}
pub struct NetworkConfigInputs<'a> {
pub configured_proxy: NetworkProxyConfig,
pub feature_enabled: bool,
pub features: Option<&'a FeaturesToml>,
pub candidate_permission_profile: &'a PermissionProfile,
pub credential_broker_base_url: Option<&'a str>,
}
/// The configured proxy before managed network requirements are applied.
pub struct PreparedNetworkConfig {
pub(super) configured_proxy: NetworkProxyConfig,
}
impl PreparedNetworkConfig {
pub fn from_inputs(inputs: NetworkConfigInputs<'_>) -> Self {
let NetworkConfigInputs {
mut configured_proxy,
feature_enabled,
features,
candidate_permission_profile,
credential_broker_base_url,
} = inputs;
if feature_enabled
&& candidate_permission_profile
.network_sandbox_policy()
.is_enabled()
{
if let Some(FeatureToml::Config(config)) =
features.and_then(|features| features.network_proxy.as_ref())
{
apply_network_proxy_feature_config(&mut configured_proxy, config);
}
configured_proxy.enabled = true;
}
configured_proxy.set_credential_broker_openai_base_url(credential_broker_base_url);
Self { configured_proxy }
}
/// Applies managed network requirements after permission fallback has run.
pub fn build(
self,
requirements: Option<Sourced<NetworkConstraints>>,
effective_permission_profile: &PermissionProfile,
) -> std::io::Result<Option<NetworkProxySpec>> {
let has_requirements = requirements.is_some();
let network = self.build_spec(requirements, effective_permission_profile)?;
Ok(if has_requirements {
Some(network)
} else {
network.enabled().then_some(network)
})
}
/// An attachment's portable policy can be enforced without a local proxy
/// controller. Its presence must not depend on the controller feature gate.
pub fn build_environment_policy(
self,
requirements: Option<Sourced<NetworkConstraints>>,
effective_permission_profile: &PermissionProfile,
has_selected_policy: bool,
) -> std::io::Result<Option<EnvironmentNetworkPolicy>> {
let has_requirements = requirements.is_some();
let network = self.build_spec(requirements, effective_permission_profile)?;
Ok(
(has_selected_policy || has_requirements || network.enabled())
.then(|| network.environment_policy()),
)
}
fn build_spec(
self,
requirements: Option<Sourced<NetworkConstraints>>,
effective_permission_profile: &PermissionProfile,
) -> std::io::Result<NetworkProxySpec> {
let (requirements, source) = match requirements {
Some(Sourced { value, source }) => (Some(value), Some(source)),
None => (None, None),
};
let network = NetworkProxySpec::from_config_and_constraints(
self.configured_proxy,
requirements,
effective_permission_profile,
)
.map_err(|error| {
if let Some(source) = source.as_ref() {
std::io::Error::new(
error.kind(),
format!("failed to build managed network proxy from {source}: {error}"),
)
} else {
error
}
})?;
Ok(network)
}
}
#[cfg(test)]
#[path = "network_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,209 @@
//! Covers policy presence and the environment-only configuration projection.
use super::*;
use akode_config::RequirementSource;
use akode_network_proxy::NetworkProxyConstraints;
use akode_network_proxy::build_config_state;
use pretty_assertions::assert_eq;
#[test]
fn environment_policy_presence_keeps_selected_and_managed_denials() {
let mut configured_proxy = NetworkProxyConfig::default();
configured_proxy.set_denied_domains(vec!["blocked.example".to_string()]);
let expected = EnvironmentNetworkPolicy::from_config(
&configured_proxy,
/*managed_allowed_domains_only*/ false,
);
for (has_selected_policy, requirements, has_policy) in [
(false, None, false),
(true, None, true),
(
false,
Some(NetworkConstraints {
enabled: Some(false),
..Default::default()
}),
true,
),
] {
let actual = PreparedNetworkConfig {
configured_proxy: configured_proxy.clone(),
}
.build_environment_policy(
requirements.map(|value| Sourced::new(value, RequirementSource::Unknown)),
&PermissionProfile::read_only(),
has_selected_policy,
)
.unwrap();
assert_eq!(actual, has_policy.then(|| expected.clone()));
}
}
#[test]
fn attachment_projection_preserves_policy_and_drops_listener_addresses() {
for executor_os in [
Platform::Linux,
Platform::Macos,
Platform::Windows,
Platform::Unknown,
] {
for (raw, windows_only) in [
("", false),
(
r#"
enabled = false
allow_upstream_proxy = false
dangerously_allow_all_unix_sockets = false
allow_local_binding = false
[domains]
'allowed.example' = 'allow'
'blocked.example' = 'deny'
[unix_sockets]
'/tmp/allowed.sock' = 'allow'
'/tmp/blocked.sock' = 'deny'
'relative.sock' = 'deny'
'~/blocked.sock' = 'deny'
'C:\blocked.sock' = 'deny'
"#,
false,
),
(
r#"[unix_sockets]
'C:\allowed.sock' = 'allow'
'\\server\share\allowed.sock' = 'allow'
"#,
true,
),
] {
let expected: NetworkToml = toml::from_str(raw).unwrap();
let accepted =
!windows_only || matches!(executor_os, Platform::Windows | Platform::Unknown);
assert_eq!(
build_config_state(
expected.to_network_proxy_config(),
NetworkProxyConstraints::default(),
executor_os,
)
.is_ok(),
accepted,
"native validation: {executor_os:?}, {raw}"
);
assert_eq!(
validate_environment_network_policy(
&EnvironmentNetworkPolicy::from_config(
&expected.to_network_proxy_config(),
/*managed_allowed_domains_only*/ false,
),
&PermissionProfile::read_only(),
executor_os,
)
.is_ok(),
accepted,
"environment validation: {executor_os:?}, {raw}"
);
let network = NetworkToml {
proxy_url: Some("not a listener URL".to_string()),
socks_url: Some("socks5://127.0.0.1:1080".to_string()),
..expected.clone()
};
assert_eq!(
project_environment_profile_network(Some(network)),
Ok(Some(expected)),
"projection: {executor_os:?}, {raw}"
);
}
assert_eq!(
project_environment_profile_network(/*network*/ None),
Ok(None)
);
}
}
#[test]
fn attachment_projection_rejects_unsupported_restrictions_and_defers_policy_validation() {
for raw in [
"mode = 'full'",
"mode = 'limited'",
r#"
[mitm.actions.redact]
strip_request_headers = ['Authorization']
[mitm.hooks.api]
host = 'api.example'
methods = ['GET']
path_prefixes = ['/']
action = ['redact']
"#,
] {
let network: NetworkToml = toml::from_str(raw).unwrap();
assert_eq!(
project_environment_profile_network(Some(network)),
Err(EnvironmentNetworkConfigError),
"{raw}"
);
}
for raw in [
"[unix_sockets]\n'relative.sock' = 'allow'",
"[unix_sockets]\n'~/allowed.sock' = 'allow'",
"[unix_sockets]\n\"/tmp/\\u0000allowed.sock\" = 'allow'",
"[domains]\n'[' = 'allow'",
] {
let network: NetworkToml = toml::from_str(raw).unwrap();
let projected = project_environment_profile_network(Some(network.clone()))
.unwrap()
.unwrap();
assert_eq!(projected, network);
let configured_proxy = projected.to_network_proxy_config();
let policy = EnvironmentNetworkPolicy::from_config(
&configured_proxy,
/*managed_allowed_domains_only*/ false,
);
assert_eq!(
validate_environment_network_policy(
&policy,
&PermissionProfile::read_only(),
Platform::Unknown,
),
Err(EnvironmentNetworkConfigError),
"{raw}"
);
// Managed requirements replace the invalid Allow entries before validation.
let policy = PreparedNetworkConfig { configured_proxy }
.build_environment_policy(
Some(Sourced::new(
NetworkConstraints {
enabled: Some(true),
managed_allowed_domains_only: Some(true),
unix_sockets: Some(Default::default()),
..Default::default()
},
RequirementSource::Unknown,
)),
&PermissionProfile::read_only(),
/*has_selected_policy*/ true,
)
.unwrap()
.unwrap();
assert_eq!(
policy,
EnvironmentNetworkPolicy::from_config(
&NetworkProxyConfig {
enabled: true,
unix_sockets: Some(Default::default()),
..Default::default()
},
/*managed_allowed_domains_only*/ true,
)
);
assert_eq!(
validate_environment_network_policy(
&policy,
&PermissionProfile::read_only(),
Platform::Unknown,
),
Ok(()),
"{raw}"
);
}
}

View File

@@ -0,0 +1,681 @@
use akode_config::NetworkConstraints;
use akode_execpolicy::Policy;
use akode_mcp::NetworkPolicyMetadata;
use akode_network_proxy::BlockedRequestObserver;
use akode_network_proxy::ConfigReloader;
use akode_network_proxy::ConfigReloaderFuture;
use akode_network_proxy::ConfigState;
use akode_network_proxy::EnvironmentNetworkPolicy;
use akode_network_proxy::LocalBindingPolicy;
use akode_network_proxy::ManagedProxyRouting;
use akode_network_proxy::NetworkDecision;
use akode_network_proxy::NetworkDomainPermission;
use akode_network_proxy::NetworkPolicyDecider;
use akode_network_proxy::NetworkProxy;
use akode_network_proxy::NetworkProxyAuditMetadata;
use akode_network_proxy::NetworkProxyConfig;
use akode_network_proxy::NetworkProxyConstraints;
use akode_network_proxy::NetworkProxyHandle;
use akode_network_proxy::NetworkProxyState;
use akode_network_proxy::build_config_state;
use akode_network_proxy::host_and_port_from_network_addr;
#[cfg(any(target_os = "windows", test))]
use akode_network_proxy::managed_proxy_ports;
use akode_network_proxy::normalize_host;
use akode_network_proxy::validate_policy_against_constraints;
use akode_protocol::models::PermissionProfile;
use akode_protocol::protocol::AskForApproval;
use akode_utils_path_uri::Platform;
use std::net::IpAddr;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkProxySpec {
base_config: NetworkProxyConfig,
requirements: Option<NetworkConstraints>,
config: NetworkProxyConfig,
constraints: NetworkProxyConstraints,
hard_deny_allowlist_misses: bool,
}
/// The primary attachment controls the shared proxy. The executor handling the call
/// supplies local-binding semantics even when it inherits the controller policy.
pub(crate) struct McpNetworkRoute<'a> {
pub(crate) primary_allows_proxy: bool,
pub(crate) local_binding: LocalBindingPolicy,
pub(crate) owner: Option<&'a EnvironmentNetworkPolicy>,
}
pub struct StartedNetworkProxy {
proxy: NetworkProxy,
network_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
_handle: NetworkProxyHandle,
}
impl StartedNetworkProxy {
fn new(
proxy: NetworkProxy,
handle: NetworkProxyHandle,
network_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
) -> Self {
Self {
proxy,
network_policy_decider,
_handle: handle,
}
}
pub fn proxy(&self) -> NetworkProxy {
self.proxy.clone()
}
pub(crate) fn network_policy_decider(&self) -> Option<Arc<dyn NetworkPolicyDecider>> {
self.network_policy_decider.as_ref().map(Arc::clone)
}
}
#[derive(Clone)]
struct StaticNetworkProxyReloader {
state: ConfigState,
}
impl StaticNetworkProxyReloader {
fn new(state: ConfigState) -> Self {
Self { state }
}
}
impl ConfigReloader for StaticNetworkProxyReloader {
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
Box::pin(async { Ok(None) })
}
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
Box::pin(async { Ok(self.state.clone()) })
}
fn source_label(&self) -> String {
"StaticNetworkProxyReloader".to_string()
}
}
impl NetworkProxySpec {
pub(crate) fn enabled(&self) -> bool {
self.config.enabled
}
pub(crate) fn credential_broker_enabled(&self) -> bool {
self.enabled() && self.config.credential_broker && self.constraints.enabled != Some(false)
}
pub fn proxy_host_and_port(&self) -> String {
host_and_port_from_network_addr(&self.config.proxy_url, /*default_port*/ 3128)
}
pub fn socks_enabled(&self) -> bool {
self.config.enable_socks5
}
#[cfg(any(target_os = "windows", test))]
pub(crate) fn configured_proxy_ports(&self) -> std::io::Result<Vec<u16>> {
managed_proxy_ports(&self.config).map_err(std::io::Error::other)
}
#[cfg(any(target_os = "windows", test))]
pub(crate) fn allow_local_binding(&self) -> bool {
self.config.allow_local_binding()
}
/// Returns the firewall settings and listener identities used by the Windows provisioning service.
#[cfg(target_os = "windows")]
pub fn windows_sandbox_proxy_listeners(
&self,
) -> std::io::Result<(
akode_windows_sandbox::WindowsSandboxProvisioningSettings,
akode_windows_sandbox::WindowsSandboxProxyListeners,
)> {
if !self.config.enabled {
return Ok((
akode_windows_sandbox::WindowsSandboxProvisioningSettings::default(),
akode_windows_sandbox::WindowsSandboxProxyListeners::default(),
));
}
let proxy_ports = self.configured_proxy_ports()?;
let http_port = self
.proxy_host_and_port()
.rsplit_once(':')
.and_then(|(_, port)| port.parse::<u16>().ok())
.ok_or_else(|| std::io::Error::other("invalid HTTP proxy listener port"))?;
let socks_port = self.config.enable_socks5.then(|| {
proxy_ports
.iter()
.copied()
.find(|port| *port != http_port)
.unwrap_or(http_port)
});
Ok((
akode_windows_sandbox::WindowsSandboxProvisioningSettings {
proxy_ports,
allow_local_binding: self.config.allow_local_binding(),
},
akode_windows_sandbox::WindowsSandboxProxyListeners {
http_ports: vec![http_port],
socks_ports: socks_port.into_iter().collect(),
},
))
}
pub fn from_config_and_constraints(
config: NetworkProxyConfig,
requirements: Option<NetworkConstraints>,
permission_profile: &PermissionProfile,
) -> std::io::Result<Self> {
let base_config = config.clone();
let hard_deny_allowlist_misses = requirements
.as_ref()
.is_some_and(Self::managed_allowed_domains_only);
let (config, constraints) = if let Some(requirements) = requirements.as_ref() {
Self::apply_requirements(
config,
requirements,
permission_profile,
hard_deny_allowlist_misses,
)
} else {
(config, NetworkProxyConstraints::default())
};
if config.enabled
&& config.mitm
&& !config.credential_broker
&& config
.mitm_hooks
.iter()
.any(|hook| hook.actions.aws_sigv4.is_some())
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"local AWS SigV4 hooks require features.credential_masking for protected shell snapshots",
));
}
validate_policy_against_constraints(&config, &constraints).map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("network proxy constraints are invalid: {err}"),
)
})?;
Ok(Self {
base_config,
requirements,
config,
constraints,
hard_deny_allowlist_misses,
})
}
#[allow(clippy::too_many_arguments)]
pub async fn start_proxy(
&self,
permission_profile: &PermissionProfile,
managed_proxy_routing: ManagedProxyRouting,
local_binding_policy: LocalBindingPolicy,
policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
blocked_request_observer: Option<Arc<dyn BlockedRequestObserver>>,
enable_network_approval_flow: bool,
audit_metadata: NetworkProxyAuditMetadata,
) -> std::io::Result<StartedNetworkProxy> {
let state = self.build_state_with_audit_metadata(
audit_metadata,
Platform::native(),
local_binding_policy,
)?;
let mut builder = NetworkProxy::builder()
.state(Arc::new(state))
.managed_proxy_routing(managed_proxy_routing);
let retained_policy_decider = policy_decider.as_ref().map(Arc::clone);
if enable_network_approval_flow && !self.hard_deny_allowlist_misses {
if let Some(policy_decider) = policy_decider {
builder = builder.policy_decider_arc(policy_decider);
} else if Self::managed_sandbox_active(permission_profile) {
builder = builder
.policy_decider(|_request| async { NetworkDecision::ask("not_allowed") });
}
}
if let Some(blocked_request_observer) = blocked_request_observer {
builder = builder.blocked_request_observer_arc(blocked_request_observer);
}
let proxy = builder.build().await.map_err(|err| {
std::io::Error::other(format!("failed to build network proxy: {err}"))
})?;
let handle = proxy
.run()
.await
.map_err(|err| std::io::Error::other(format!("failed to run network proxy: {err}")))?;
Ok(StartedNetworkProxy::new(
proxy,
handle,
retained_policy_decider,
))
}
pub(crate) fn recompute_for_permission_profile(
&self,
permission_profile: &PermissionProfile,
) -> std::io::Result<Self> {
Self::from_config_and_constraints(
self.base_config.clone(),
self.requirements.clone(),
permission_profile,
)
}
/// Returns proxy activation and traffic policy without controller-owned runtime settings.
pub fn environment_policy(&self) -> EnvironmentNetworkPolicy {
EnvironmentNetworkPolicy::from_config(&self.config, self.hard_deny_allowlist_misses)
}
pub(crate) fn for_environment(
controller: Option<&Self>,
policy: &EnvironmentNetworkPolicy,
permission_profile: &PermissionProfile,
exec_policy: &Policy,
local_binding_policy: LocalBindingPolicy,
) -> std::io::Result<Self> {
Self::compose_environment_policy(
controller,
policy,
permission_profile,
exec_policy,
Some(local_binding_policy),
)
}
fn compose_environment_policy(
controller: Option<&Self>,
policy: &EnvironmentNetworkPolicy,
permission_profile: &PermissionProfile,
exec_policy: &Policy,
routed_binding: Option<LocalBindingPolicy>,
) -> std::io::Result<Self> {
if routed_binding.is_some() && matches!(permission_profile, PermissionProfile::Disabled) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"environment network policy requires managed network enforcement",
));
}
if routed_binding.is_some() && controller.is_some_and(|controller| !controller.enabled()) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"environment network policy cannot override a disabled controller proxy",
));
}
let mut spec = match controller {
Some(controller) => controller.recompute_for_permission_profile(permission_profile)?,
None => Self::from_config_and_constraints(
NetworkProxyConfig {
enabled: true,
// Without a controller, the owner supplies the entire permission ceiling.
dangerously_allow_all_unix_sockets: Some(true),
allow_local_binding: Some(policy.allow_local_binding.unwrap_or(false)),
..NetworkProxyConfig::default()
},
/*requirements*/ None,
permission_profile,
)?,
};
policy.apply_to(&mut spec.config);
spec.config.allow_local_binding =
Some(routed_binding.unwrap_or_default().resolve(&spec.config));
let protected_denials = spec.config.denied_domains().unwrap_or_default();
// A fixed controller allowlist remains a ceiling; an expandable one is only a baseline.
// Profiles without managed approvals must not reuse approvals cached by another profile.
let fixed_allowlist = spec.hard_deny_allowlist_misses
|| spec.constraints.allowlist_expansion_enabled == Some(false);
spec.hard_deny_allowlist_misses |= policy.managed_allowed_domains_only
|| !Self::managed_sandbox_active(permission_profile);
let allow_owner_grants = !spec.hard_deny_allowlist_misses && !fixed_allowlist;
if fixed_allowlist {
spec.constraints.allowlist_expansion_enabled = None;
} else {
spec.constraints.allowed_domains =
Some(spec.config.allowed_domains().unwrap_or_default());
spec.constraints.allowlist_expansion_enabled = Some(allow_owner_grants);
}
spec.constraints.denylist_expansion_enabled = Some(true);
// Saved grants can extend a reviewable owner policy; owner denials are restored last.
let (allowed_domains, denied_domains) = exec_policy.compiled_network_domains();
spec.config.apply_saved_domain_rules(
if allow_owner_grants {
allowed_domains
} else {
Vec::new()
},
&denied_domains,
);
for host in protected_denials {
spec.config.upsert_domain_permission(
host,
NetworkDomainPermission::Deny,
normalize_host,
);
}
spec.constraints.denied_domains = spec.config.denied_domains();
if routed_binding.is_some() {
validate_policy_against_constraints(&spec.config, &spec.constraints).map_err(
|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"environment network policy violates managed requirements: {error}"
),
)
},
)?;
}
tracing::debug!(
controller_policy = ?controller.map(Self::environment_policy),
controller_allow_all_unix_sockets = ?controller.and_then(|spec| spec.config.dangerously_allow_all_unix_sockets),
attachment_policy = ?policy,
effective_policy = ?spec.environment_policy(),
"resolved environment network policy"
);
Ok(spec)
}
/// Derives the network restrictions a trusted MCP server may apply to a call.
#[cfg_attr(not(test), expect(dead_code, reason = "used by the next PR"))]
pub(crate) fn mcp_network_policy(
controller: Option<&Self>,
controller_profile: &PermissionProfile,
route: McpNetworkRoute<'_>,
permission_profile: &PermissionProfile,
approval_policy: AskForApproval,
exec_policy: &Policy,
) -> std::io::Result<NetworkPolicyMetadata> {
let direct_network = permission_profile.network_sandbox_policy().is_enabled();
// An owner can supply its own proxy when the controller is absent. A disabled
// controller vetoes that route, so file tools receive an offline policy.
let proxy_active = match route.owner {
Some(owner) => controller.map_or(owner.requires_proxy || direct_network, Self::enabled),
None => route.primary_allows_proxy && controller.is_some_and(Self::enabled),
};
let network_enabled = proxy_active || (route.owner.is_none() && direct_network);
let spec = if let Some(owner) = route.owner {
// Offline file tools retain the owner's traffic rules without needing a startable proxy.
Self::compose_environment_policy(
controller,
owner,
permission_profile,
exec_policy,
proxy_active.then_some(route.local_binding),
)?
} else if let Some(controller) = controller
&& proxy_active
{
// The routed controller uses the thread's profile even for calls from another executor.
let spec = controller.recompute_for_permission_profile(controller_profile)?;
spec.with_exec_policy_network_rules(exec_policy)
.unwrap_or(spec)
} else {
// Direct calls retain administrative policy, without importing unused proxy settings.
Self::from_config_and_constraints(
Default::default(),
controller.and_then(|controller| controller.requirements.clone()),
controller_profile,
)?
};
let config = spec.config;
// The native decider reviews fresh misses only for managed calls with approvals enabled.
let can_review = (route.owner.is_some() || spec.requirements.is_some())
&& Self::managed_sandbox_active(permission_profile)
&& approval_policy != AskForApproval::Never;
// The domain-only MCP contract cannot check DNS answers at connect time.
// With local access restricted, only explicit IP grants are safe to forward.
let require_ip_literal = proxy_active && !route.local_binding.resolve(&config);
// An MXC executor cannot launch an active proxy with an explicit local-binding denial.
let can_route =
!(require_ip_literal && route.local_binding == LocalBindingPolicy::RequireTrue);
let mut allowed_domains = config.allowed_domains().unwrap_or_default();
if require_ip_literal {
allowed_domains.retain(|rule| {
!rule.contains(['*', '?']) && normalize_host(rule).parse::<IpAddr>().is_ok()
});
}
let denied_domains = config.denied_domains().unwrap_or_default();
// The receiver cannot prompt for review or enforce a proxy hook's per-request restrictions.
let mut additional_denials = config.review_domains;
if proxy_active {
additional_denials.extend(
config
.mitm_hooks
.iter()
.map(|hook| normalize_host(&hook.host)),
);
}
Ok(NetworkPolicyMetadata {
enabled: network_enabled && can_route && spec.constraints.enabled != Some(false),
mode: config.mode,
allowed_domains,
denied_domains: Self::merge_domain_lists(denied_domains, &additional_denials),
hard_deny_allowlist_misses: require_ip_literal
|| spec.hard_deny_allowlist_misses
|| (proxy_active && !can_review),
})
}
pub(crate) fn with_exec_policy_network_rules(
&self,
exec_policy: &Policy,
) -> std::io::Result<Self> {
let mut spec = self.clone();
let (allowed, denied) = exec_policy.compiled_network_domains();
spec.config.apply_saved_domain_rules(allowed, &denied);
if validate_policy_against_constraints(&spec.config, &spec.constraints).is_ok() {
return Ok(spec);
}
// A stale grant cannot invalidate saved denials. Fixed deny lists retain their configured set.
spec.config.domains.clone_from(&self.config.domains);
spec.config.apply_saved_domain_rules(Vec::new(), &denied);
validate_policy_against_constraints(&spec.config, &spec.constraints).map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("network proxy constraints are invalid: {err}"),
)
})?;
Ok(spec)
}
pub(crate) async fn apply_to_started_proxy(
&self,
started_proxy: &StartedNetworkProxy,
) -> std::io::Result<()> {
let state = self
.build_config_state_for_spec(Platform::from_platform_os(Some(std::env::consts::OS)))?;
started_proxy
.proxy()
.replace_config_state(state)
.await
.map_err(|err| {
std::io::Error::other(format!("failed to update network proxy state: {err}"))
})
}
pub(crate) fn build_state_with_audit_metadata(
&self,
audit_metadata: NetworkProxyAuditMetadata,
executor_os: Platform,
local_binding_policy: LocalBindingPolicy,
) -> std::io::Result<NetworkProxyState> {
let state = self.build_config_state_for_spec(executor_os)?;
let reloader = Arc::new(StaticNetworkProxyReloader::new(state.clone()));
Ok(NetworkProxyState::with_reloader_and_audit_metadata(
state,
reloader,
audit_metadata,
local_binding_policy,
))
}
pub(super) fn build_config_state_for_spec(
&self,
executor_os: Platform,
) -> std::io::Result<ConfigState> {
let mut config = self.config.clone();
if !self.enabled() {
// Retained managed constraints must not let brokerage activate a disabled proxy.
config.set_credential_broker_enabled(/*enabled*/ false);
}
build_config_state(config, self.constraints.clone(), executor_os).map_err(|err| {
std::io::Error::other(format!("failed to build network proxy state: {err}"))
})
}
fn apply_requirements(
mut config: NetworkProxyConfig,
requirements: &NetworkConstraints,
permission_profile: &PermissionProfile,
hard_deny_allowlist_misses: bool,
) -> (NetworkProxyConfig, NetworkProxyConstraints) {
let mut constraints = NetworkProxyConstraints::default();
let allowlist_expansion_enabled =
Self::allowlist_expansion_enabled(permission_profile, hard_deny_allowlist_misses);
let denylist_expansion_enabled = Self::denylist_expansion_enabled(permission_profile);
if let Some(enabled) = requirements.enabled {
config.enabled = enabled;
constraints.enabled = Some(enabled);
}
if let Some(http_port) = requirements.http_port {
config.proxy_url = format!("http://127.0.0.1:{http_port}");
}
if let Some(socks_port) = requirements.socks_port {
config.socks_url = format!("http://127.0.0.1:{socks_port}");
}
if let Some(allow_upstream_proxy) = requirements.allow_upstream_proxy {
config.allow_upstream_proxy = allow_upstream_proxy;
constraints.allow_upstream_proxy = Some(allow_upstream_proxy);
}
if let Some(dangerously_allow_non_loopback_proxy) =
requirements.dangerously_allow_non_loopback_proxy
{
config.dangerously_allow_non_loopback_proxy = dangerously_allow_non_loopback_proxy;
constraints.dangerously_allow_non_loopback_proxy =
Some(dangerously_allow_non_loopback_proxy);
}
if let Some(dangerously_allow_all_unix_sockets) =
requirements.dangerously_allow_all_unix_sockets
{
config.dangerously_allow_all_unix_sockets = Some(dangerously_allow_all_unix_sockets);
constraints.dangerously_allow_all_unix_sockets =
Some(dangerously_allow_all_unix_sockets);
}
let managed_allowed_domains = if hard_deny_allowlist_misses {
Some(
requirements
.domains
.as_ref()
.and_then(akode_config::NetworkDomainPermissionsToml::allowed_domains)
.unwrap_or_default(),
)
} else {
requirements
.domains
.as_ref()
.and_then(akode_config::NetworkDomainPermissionsToml::allowed_domains)
};
if let Some(managed_allowed_domains) = managed_allowed_domains {
// Managed requirements seed the baseline allowlist. User additions
// can extend that baseline unless managed-only mode pins the
// effective allowlist to the managed set.
let effective_allowed_domains = if allowlist_expansion_enabled {
Self::merge_domain_lists(
managed_allowed_domains.clone(),
config.allowed_domains().as_deref().unwrap_or(&[]),
)
} else {
managed_allowed_domains.clone()
};
config.set_allowed_domains(effective_allowed_domains);
constraints.allowed_domains = Some(managed_allowed_domains);
constraints.allowlist_expansion_enabled = Some(allowlist_expansion_enabled);
}
let managed_denied_domains = requirements
.domains
.as_ref()
.and_then(akode_config::NetworkDomainPermissionsToml::denied_domains);
if let Some(managed_denied_domains) = managed_denied_domains {
let effective_denied_domains = if denylist_expansion_enabled {
Self::merge_domain_lists(
managed_denied_domains.clone(),
config.denied_domains().as_deref().unwrap_or(&[]),
)
} else {
managed_denied_domains.clone()
};
config.set_denied_domains(effective_denied_domains);
constraints.denied_domains = Some(managed_denied_domains);
constraints.denylist_expansion_enabled = Some(denylist_expansion_enabled);
}
if let Some(review_domains) = &requirements.review_domains {
config.review_domains =
Self::merge_domain_lists(review_domains.clone(), &config.review_domains);
}
if requirements.unix_sockets.is_some() {
let allow_unix_sockets = requirements
.unix_sockets
.as_ref()
.map(akode_config::NetworkUnixSocketPermissionsToml::allow_unix_sockets)
.unwrap_or_default();
config.set_allow_unix_sockets(allow_unix_sockets.clone());
constraints.allow_unix_sockets = Some(allow_unix_sockets);
}
if let Some(allow_local_binding) = requirements.allow_local_binding {
config.allow_local_binding = Some(allow_local_binding);
constraints.allow_local_binding = Some(allow_local_binding);
}
(config, constraints)
}
fn allowlist_expansion_enabled(
permission_profile: &PermissionProfile,
hard_deny_allowlist_misses: bool,
) -> bool {
Self::managed_sandbox_active(permission_profile) && !hard_deny_allowlist_misses
}
fn managed_allowed_domains_only(requirements: &NetworkConstraints) -> bool {
requirements.managed_allowed_domains_only.unwrap_or(false)
}
fn denylist_expansion_enabled(permission_profile: &PermissionProfile) -> bool {
Self::managed_sandbox_active(permission_profile)
}
fn managed_sandbox_active(permission_profile: &PermissionProfile) -> bool {
matches!(permission_profile, PermissionProfile::Managed { .. })
}
fn merge_domain_lists(mut managed: Vec<String>, user_entries: &[String]) -> Vec<String> {
for entry in user_entries {
if !managed
.iter()
.any(|managed_entry| managed_entry.eq_ignore_ascii_case(entry))
{
managed.push(entry.clone());
}
}
managed
}
}
#[cfg(test)]
#[path = "mcp_network_policy_tests.rs"]
mod mcp_network_policy_tests;
#[cfg(test)]
#[path = "network_proxy_spec_tests.rs"]
mod tests;

View File

@@ -0,0 +1,995 @@
use super::*;
use crate::config::EnvironmentNetworkConfigError;
use crate::config::validate_environment_network_policy;
use akode_config::NetworkDomainPermissionToml;
use akode_config::NetworkDomainPermissionsToml;
use akode_execpolicy::Decision::Allow;
use akode_execpolicy::NetworkRuleProtocol::Https;
use akode_network_proxy::LocalBindingPolicy::DefaultFalse;
use akode_network_proxy::LocalBindingPolicy::RequireTrue;
use akode_network_proxy::NetworkDomainPermission;
use akode_network_proxy::NetworkUnixSocketPermission;
use akode_network_proxy::NetworkUnixSocketPermissions;
use akode_network_proxy::RemoteCredentialMasking;
use akode_protocol::models::ManagedFileSystemPermissions;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use pretty_assertions::assert_eq;
fn domain_permissions(
entries: impl IntoIterator<Item = (&'static str, NetworkDomainPermissionToml)>,
) -> NetworkDomainPermissionsToml {
NetworkDomainPermissionsToml {
entries: entries
.into_iter()
.map(|(pattern, permission)| (pattern.to_string(), permission))
.collect(),
}
}
#[tokio::test]
async fn attachment_socket_grants_respect_configured_restrictions_at_remote_launch()
-> anyhow::Result<()> {
let profile = PermissionProfile::workspace_write();
let owner = EnvironmentNetworkPolicy::from_config(
&NetworkProxyConfig {
dangerously_allow_all_unix_sockets: Some(true),
..Default::default()
},
/*managed_allowed_domains_only*/ false,
);
for (name, toml, required, expected) in [
("omitted", "", None, true),
(
"explicit_deny",
"dangerously_allow_all_unix_sockets = false",
None,
false,
),
(
"explicit_allow",
"dangerously_allow_all_unix_sockets = true",
None,
true,
),
(
"finite",
"unix_sockets = { '/tmp/allowed.sock' = 'allow', '/tmp/denied.sock' = 'deny' }",
None,
false,
),
("empty", "unix_sockets = {}", None, false),
(
"managed_deny",
"dangerously_allow_all_unix_sockets = true",
Some(false),
false,
),
] {
let configured: akode_config::permissions_toml::NetworkToml = toml::from_str(toml)?;
let controller = NetworkProxySpec::from_config_and_constraints(
configured.to_network_proxy_config(),
Some(NetworkConstraints {
enabled: Some(true),
dangerously_allow_all_unix_sockets: required,
..Default::default()
}),
&profile,
)?;
let composed = NetworkProxySpec::for_environment(
Some(&controller),
&owner,
&profile,
&Policy::empty(),
DefaultFalse,
)?;
assert_eq!(
composed.config.dangerously_allow_all_unix_sockets,
Some(expected),
"{name}"
);
let state = Arc::new(controller.build_state_with_audit_metadata(
Default::default(),
Platform::Linux,
DefaultFalse,
)?);
let proxy = NetworkProxy::builder()
.state(Arc::clone(&state))
.managed_by_codex(false)
.build()
.await?;
let scoped = proxy.for_execution(
"socket-test",
name,
format!("socket-{name}"),
Some(composed.environment_policy()),
/*fallback_policy_decider*/ None,
)?;
let launch = scoped
.remote_launch_config(DefaultFalse, RemoteCredentialMasking::Disabled)
.await?;
assert_eq!(
launch.proxy.dangerously_allow_all_unix_sockets, expected,
"{name}"
);
assert_eq!(
launch.proxy.unix_sockets, composed.config.unix_sockets,
"{name}"
);
if name == "finite" {
assert_eq!(launch.proxy.unix_sockets, controller.config.unix_sockets);
}
if name == "omitted" {
// Inheritance must not grant sockets to ordinary controller-only commands.
assert!(
!proxy
.remote_launch_config(DefaultFalse, RemoteCredentialMasking::Disabled)
.await?
.proxy
.dangerously_allow_all_unix_sockets
);
state.add_allowed_domain("granted.example").await?;
assert!(
scoped
.remote_launch_config(DefaultFalse, RemoteCredentialMasking::Disabled)
.await?
.proxy
.dangerously_allow_all_unix_sockets
);
// A live handle must also honor a subsequently installed explicit restriction.
let restricted = NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig {
enabled: true,
dangerously_allow_all_unix_sockets: Some(false),
..Default::default()
},
/*requirements*/ None,
&profile,
)?;
proxy
.replace_config_state(restricted.build_config_state_for_spec(Platform::Linux)?)
.await?;
assert!(
!scoped
.remote_launch_config(DefaultFalse, RemoteCredentialMasking::Disabled)
.await?
.proxy
.dangerously_allow_all_unix_sockets
);
}
}
Ok(())
}
#[test]
fn build_state_with_audit_metadata_threads_metadata_to_state() {
let spec = NetworkProxySpec {
base_config: NetworkProxyConfig::default(),
requirements: None,
config: NetworkProxyConfig::default(),
constraints: NetworkProxyConstraints::default(),
hard_deny_allowlist_misses: false,
};
let metadata = NetworkProxyAuditMetadata {
conversation_id: Some("conversation-1".to_string()),
app_version: Some("1.2.3".to_string()),
user_account_id: Some("acct-1".to_string()),
..NetworkProxyAuditMetadata::default()
};
let state = spec
.build_state_with_audit_metadata(metadata.clone(), Platform::Linux, DefaultFalse)
.expect("state should build");
assert_eq!(state.audit_metadata(), &metadata);
}
#[cfg(target_os = "windows")]
#[test]
fn windows_sandbox_proxy_listeners_preserve_effective_protocol_roles() {
let spec = NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig {
enabled: true,
proxy_url: "http://127.0.0.1:48081".to_string(),
socks_url: "socks5h://127.0.0.1:3128".to_string(),
allow_local_binding: Some(true),
..NetworkProxyConfig::default()
},
/*requirements*/ None,
&PermissionProfile::workspace_write(),
)
.expect("effective network configuration should be valid");
assert_eq!(
spec.windows_sandbox_proxy_listeners()
.expect("effective proxy listeners should resolve"),
(
akode_windows_sandbox::WindowsSandboxProvisioningSettings {
proxy_ports: vec![3128, 48081],
allow_local_binding: true,
},
akode_windows_sandbox::WindowsSandboxProxyListeners {
http_ports: vec![48081],
socks_ports: vec![3128],
},
)
);
}
#[test]
fn environment_policy_replaces_soft_controller_allowlist_and_preserves_denials() {
let requirements = NetworkConstraints {
domains: Some(domain_permissions([
("controller.example", NetworkDomainPermissionToml::Allow),
("blocked.example", NetworkDomainPermissionToml::Deny),
])),
review_domains: Some(vec!["controller-review.example".to_string()]),
..Default::default()
};
let profile = PermissionProfile::workspace_write();
let spec = NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig {
enabled: true,
allow_upstream_proxy: false,
unix_sockets: Some(NetworkUnixSocketPermissions {
entries: [
(
"/tmp/controller.sock".to_string(),
NetworkUnixSocketPermission::Deny,
),
(
"/tmp/allowed.sock".to_string(),
NetworkUnixSocketPermission::Allow,
),
]
.into(),
}),
..NetworkProxyConfig::default()
},
Some(requirements),
&profile,
)
.expect("controller policy should be valid");
let mut owner = NetworkProxyConfig {
review_domains: vec!["owner-review.example".to_string()],
..NetworkProxyConfig::default()
};
owner.set_allowed_domains(vec!["owner.example".to_string()]);
owner.set_denied_domains(vec!["owner-blocked.example".to_string()]);
owner.set_allow_unix_sockets(vec![
"/tmp/controller.sock".to_string(),
"/private/tmp/controller.sock".to_string(),
"/tmp/allowed.sock".to_string(),
]);
owner.dangerously_allow_all_unix_sockets = Some(true);
owner.allow_local_binding = Some(true);
let owner_policy =
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert_eq!(
validate_environment_network_policy(&owner_policy, &profile, Platform::Linux),
Ok(())
);
assert_eq!(
validate_environment_network_policy(
&owner_policy,
&PermissionProfile::Disabled,
Platform::Linux
),
Err(EnvironmentNetworkConfigError)
);
let compose = |controller: Option<&NetworkProxySpec>,
policy: &EnvironmentNetworkPolicy,
profile: &PermissionProfile,
rules: &Policy| {
NetworkProxySpec::for_environment(controller, policy, profile, rules, DefaultFalse)
};
let empty = Policy::empty();
let disabled_controller = NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig::default(),
/*requirements*/ None,
&profile,
)
.expect("disabled controller policy should be valid");
assert!(compose(Some(&disabled_controller), &owner_policy, &profile, &empty).is_err());
let restricted = compose(Some(&spec), &owner_policy, &profile, &empty)
.expect("owner policy should replace soft controller grants");
let mut saved = Policy::empty();
for host in ["saved.example", "owner-blocked.example"] {
saved
.add_network_rule(host, Https, Allow, /*justification*/ None)
.expect("saved network grant should be valid");
}
let rootless = compose(/*controller*/ None, &owner_policy, &profile, &saved)
.expect("an owner policy can create executor-side proxy state");
assert_eq!(
rootless.config.allowed_domains().unwrap(),
["owner.example", "saved.example"]
);
owner.upsert_domain_permission(
"blocked.example".to_string(),
NetworkDomainPermission::Deny,
normalize_host,
);
owner.unix_sockets.clone_from(&spec.config.unix_sockets);
owner.allow_upstream_proxy = false;
owner.dangerously_allow_all_unix_sockets = Some(false);
owner.allow_local_binding = Some(true);
owner.enabled = true;
owner
.review_domains
.insert(0, "controller-review.example".to_string());
assert_eq!(
restricted.environment_policy(),
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false)
);
let external = PermissionProfile::External {
network: NetworkSandboxPolicy::Enabled,
};
let external_rootless = compose(/*controller*/ None, &owner_policy, &external, &saved)
.expect("an externally sandboxed owner policy should remain strict");
assert_eq!(
external_rootless.environment_policy(),
EnvironmentNetworkPolicy {
requires_proxy: true,
managed_allowed_domains_only: true,
..owner_policy.clone()
}
);
let controller_policy = spec.environment_policy();
let external_rooted = compose(Some(&spec), &controller_policy, &external, &saved)
.expect("an externally sandboxed owner policy may retain its controller allowlist");
assert_eq!(
external_rooted.environment_policy(),
EnvironmentNetworkPolicy {
allow_local_binding: Some(false),
managed_allowed_domains_only: true,
..controller_policy
}
);
assert!(compose(Some(&spec), &owner_policy, &external, &empty).is_err());
owner.set_allowed_domains(vec!["*".to_string()]);
let wildcard_policy =
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert!(compose(Some(&spec), &wildcard_policy, &profile, &empty).is_err());
assert_eq!(
validate_environment_network_policy(&wildcard_policy, &profile, Platform::Linux),
Err(EnvironmentNetworkConfigError)
);
owner.set_allowed_domains(vec!["[".to_string()]);
let malformed_policy =
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert_eq!(
validate_environment_network_policy(&malformed_policy, &profile, Platform::Linux),
Err(EnvironmentNetworkConfigError)
);
}
#[test]
fn requirements_allowed_domains_are_a_baseline_for_user_allowlist() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"*.example.com",
NetworkDomainPermissionToml::Allow,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::read_only(),
)
.expect("config should stay within the managed allowlist");
assert_eq!(
spec.config.allowed_domains(),
Some(vec![
"*.example.com".to_string(),
"api.example.com".to_string()
])
);
assert_eq!(
spec.constraints.allowed_domains,
Some(vec!["*.example.com".to_string()])
);
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(true));
}
#[test]
fn requirements_allowed_domains_do_not_override_user_denies_for_same_pattern() {
let mut config = NetworkProxyConfig::default();
config.set_denied_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"api.example.com",
NetworkDomainPermissionToml::Allow,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed allowlist should not erase a user deny");
assert_eq!(spec.config.allowed_domains(), None);
assert_eq!(
spec.config.denied_domains(),
Some(vec!["api.example.com".to_string()])
);
assert_eq!(
spec.constraints.allowed_domains,
Some(vec!["api.example.com".to_string()])
);
}
#[test]
fn requirements_allowlist_expansion_keeps_user_entries_mutable() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"*.example.com",
NetworkDomainPermissionToml::Allow,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed baseline should still allow user edits");
let mut candidate = spec.config.clone();
candidate.upsert_domain_permission(
"api.example.com".to_string(),
NetworkDomainPermission::Deny,
normalize_host,
);
assert_eq!(
candidate.allowed_domains(),
Some(vec!["*.example.com".to_string()])
);
assert_eq!(
candidate.denied_domains(),
Some(vec!["api.example.com".to_string()])
);
validate_policy_against_constraints(&candidate, &spec.constraints)
.expect("user allowlist entries should not become managed constraints");
}
#[test]
fn managed_unrestricted_profile_allows_domain_expansion() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"*.example.com",
NetworkDomainPermissionToml::Allow,
)])),
..Default::default()
};
let permission_profile = PermissionProfile::Managed {
file_system: ManagedFileSystemPermissions::Unrestricted,
network: NetworkSandboxPolicy::Restricted,
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&permission_profile,
)
.expect("managed unrestricted filesystem should still use managed network constraints");
assert_eq!(
spec.config.allowed_domains(),
Some(vec![
"*.example.com".to_string(),
"api.example.com".to_string()
])
);
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(true));
}
#[test]
fn danger_full_access_keeps_managed_allowlist_and_denylist_fixed() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["evil.com".to_string()]);
config.set_denied_domains(vec!["more-blocked.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([
("*.example.com", NetworkDomainPermissionToml::Allow),
("blocked.example.com", NetworkDomainPermissionToml::Deny),
])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::Disabled,
)
.expect("yolo mode should pin the effective policy to the managed baseline");
assert_eq!(
spec.config.allowed_domains(),
Some(vec!["*.example.com".to_string()])
);
assert_eq!(
spec.config.denied_domains(),
Some(vec!["blocked.example.com".to_string()])
);
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(false));
assert_eq!(spec.constraints.denylist_expansion_enabled, Some(false));
}
#[test]
fn managed_allowed_domains_only_disables_default_mode_allowlist_expansion() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"*.example.com",
NetworkDomainPermissionToml::Allow,
)])),
managed_allowed_domains_only: Some(true),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed baseline should still load");
assert_eq!(
spec.config.allowed_domains(),
Some(vec!["*.example.com".to_string()])
);
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(false));
}
#[test]
fn managed_allowed_domains_only_ignores_user_allowlist_and_hard_denies_misses() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"managed.example.com",
NetworkDomainPermissionToml::Allow,
)])),
managed_allowed_domains_only: Some(true),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed-only allowlist should still load");
assert_eq!(
spec.config.allowed_domains(),
Some(vec!["managed.example.com".to_string()])
);
assert_eq!(
spec.constraints.allowed_domains,
Some(vec!["managed.example.com".to_string()])
);
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(false));
assert!(spec.hard_deny_allowlist_misses);
}
#[test]
fn managed_allowed_domains_only_without_managed_allowlist_blocks_all_user_domains() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
managed_allowed_domains_only: Some(true),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed-only mode should treat missing managed allowlist as empty");
assert_eq!(spec.config.allowed_domains(), None);
assert_eq!(spec.constraints.allowed_domains, Some(Vec::new()));
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(false));
assert!(spec.hard_deny_allowlist_misses);
}
#[test]
fn managed_allowed_domains_only_blocks_all_user_domains_in_full_access_without_managed_list() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
managed_allowed_domains_only: Some(true),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::Disabled,
)
.expect("managed-only mode should treat missing managed allowlist as empty");
assert_eq!(spec.config.allowed_domains(), None);
assert_eq!(spec.constraints.allowed_domains, Some(Vec::new()));
assert_eq!(spec.constraints.allowlist_expansion_enabled, Some(false));
assert!(spec.hard_deny_allowlist_misses);
}
#[test]
fn deny_only_requirements_do_not_create_allow_constraints_in_full_access() {
let mut config = NetworkProxyConfig::default();
config.set_allowed_domains(vec!["api.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"managed-blocked.example.com",
NetworkDomainPermissionToml::Deny,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::Disabled,
)
.expect("deny-only requirements should not constrain the allowlist");
assert_eq!(
spec.config.allowed_domains(),
Some(vec!["api.example.com".to_string()])
);
assert_eq!(spec.constraints.allowed_domains, None);
assert_eq!(spec.constraints.allowlist_expansion_enabled, None);
assert_eq!(
spec.config.denied_domains(),
Some(vec!["managed-blocked.example.com".to_string()])
);
}
#[test]
fn allow_only_requirements_do_not_create_deny_constraints_in_full_access() {
let mut config = NetworkProxyConfig::default();
config.set_denied_domains(vec!["blocked.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"managed.example.com",
NetworkDomainPermissionToml::Allow,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::Disabled,
)
.expect("allow-only requirements should not constrain the denylist");
assert_eq!(
spec.config.allowed_domains(),
Some(vec!["managed.example.com".to_string()])
);
assert_eq!(
spec.config.denied_domains(),
Some(vec!["blocked.example.com".to_string()])
);
assert_eq!(spec.constraints.denied_domains, None);
assert_eq!(spec.constraints.denylist_expansion_enabled, None);
}
#[test]
fn requirements_denied_domains_are_a_baseline_for_default_mode() {
let mut config = NetworkProxyConfig::default();
config.set_denied_domains(vec!["blocked.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"managed-blocked.example.com",
NetworkDomainPermissionToml::Deny,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("default mode should merge managed and user deny entries");
assert_eq!(
spec.config.denied_domains(),
Some(vec![
"managed-blocked.example.com".to_string(),
"blocked.example.com".to_string()
])
);
assert_eq!(
spec.constraints.denied_domains,
Some(vec!["managed-blocked.example.com".to_string()])
);
assert_eq!(spec.constraints.denylist_expansion_enabled, Some(true));
}
#[test]
fn requirements_denylist_expansion_keeps_user_entries_mutable() {
let mut config = NetworkProxyConfig::default();
config.set_denied_domains(vec!["blocked.example.com".to_string()]);
let requirements = NetworkConstraints {
domains: Some(domain_permissions([(
"managed-blocked.example.com",
NetworkDomainPermissionToml::Deny,
)])),
..Default::default()
};
let spec = NetworkProxySpec::from_config_and_constraints(
config,
Some(requirements),
&PermissionProfile::workspace_write(),
)
.expect("managed baseline should still allow user edits");
let mut candidate = spec.config.clone();
candidate.upsert_domain_permission(
"blocked.example.com".to_string(),
NetworkDomainPermission::Allow,
normalize_host,
);
assert_eq!(
candidate.allowed_domains(),
Some(vec!["blocked.example.com".to_string()])
);
assert_eq!(
candidate.denied_domains(),
Some(vec!["managed-blocked.example.com".to_string()])
);
validate_policy_against_constraints(&candidate, &spec.constraints)
.expect("user denylist entries should not become managed constraints");
}
#[tokio::test]
async fn environment_local_binding_preserves_explicit_denials_and_inherits_omitted_settings()
-> anyhow::Result<()> {
let managed: akode_config::ConfigRequirementsToml = toml::from_str(
r#"
[experimental_network]
enabled = true
managed_allowed_domains_only = true
allowed_domains = ["example.com"]
"#,
)?;
let empty = Policy::empty();
for (name, configured, required, expected_bindings) in [
(
"absent",
None,
None,
[false, false, true, false, false, true],
),
(
"omitted",
Some(None),
None,
[false, false, true, true, false, true],
),
(
"managed_omitted",
Some(None),
managed.network.map(Into::into),
[false, false, true, true, false, true],
),
("configured_deny", Some(Some(false)), None, [false; 6]),
(
"configured_allow",
Some(Some(true)),
None,
[true, false, true, true, false, true],
),
(
"managed_deny",
Some(Some(true)),
Some(NetworkConstraints {
allow_local_binding: Some(false),
..Default::default()
}),
[false; 6],
),
(
"managed_allow",
Some(Some(false)),
Some(NetworkConstraints {
allow_local_binding: Some(true),
..Default::default()
}),
[true, false, true, true, false, true],
),
] {
let profile = PermissionProfile::workspace_write();
let controller = configured
.map(|allow_local_binding| {
NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig {
enabled: true,
allow_local_binding,
..Default::default()
},
required,
&profile,
)
})
.transpose()?;
if name == "managed_omitted" {
let controller = controller.as_ref().unwrap();
assert_eq!(
(
controller.config.allow_local_binding,
controller.constraints.allow_local_binding,
),
(None, None)
);
}
let original_controller = controller.clone();
for ((local_binding_policy, owner_binding), expected) in [
(DefaultFalse, None),
(DefaultFalse, Some(false)),
(DefaultFalse, Some(true)),
(RequireTrue, None),
(RequireTrue, Some(false)),
(RequireTrue, Some(true)),
]
.into_iter()
.zip(expected_bindings)
{
let mut owner_config = NetworkProxyConfig {
allow_local_binding: owner_binding,
..Default::default()
};
owner_config.set_allowed_domains(vec!["example.com".to_string()]);
let owner =
EnvironmentNetworkPolicy::from_config(&owner_config, name == "managed_omitted");
let composed = NetworkProxySpec::for_environment(
controller.as_ref(),
&owner,
&profile,
&Policy::empty(),
local_binding_policy,
)?;
assert_eq!(
composed.environment_policy(),
EnvironmentNetworkPolicy {
requires_proxy: true,
allow_local_binding: Some(expected),
..owner.clone()
},
"{name}: {local_binding_policy:?}, owner={owner_binding:?}"
);
let carrier = controller.as_ref().unwrap_or(&composed);
// Exercise both directions of a mixed-executor route when the controller
// leaves binding unspecified. An explicit denial cannot start an MXC proxy.
let (primary_os, primary_binding) = if local_binding_policy == DefaultFalse
&& carrier.config.allow_local_binding.is_none()
{
(Platform::Windows, RequireTrue)
} else {
(Platform::Linux, DefaultFalse)
};
let proxy = NetworkProxy::builder()
.state(Arc::new(carrier.build_state_with_audit_metadata(
Default::default(),
primary_os,
primary_binding,
)?))
.managed_by_codex(/*managed_by_codex*/ false)
.build()
.await?;
for policy in [Some(owner), Some(composed.environment_policy()), None] {
if policy.is_none() && (controller.is_none() || owner_binding.is_some()) {
continue;
}
if let Some(controller) = &controller {
let mcp = NetworkProxySpec::mcp_network_policy(
Some(controller),
&profile,
McpNetworkRoute {
primary_allows_proxy: true,
local_binding: local_binding_policy,
owner: policy.as_ref(),
},
&profile,
AskForApproval::OnRequest,
&empty,
)?;
assert_eq!(
mcp.enabled,
expected || local_binding_policy == DefaultFalse
);
if policy.is_some() || name == "managed_omitted" {
assert_eq!(
mcp.allowed_domains.iter().any(|host| host == "example.com"),
expected
);
}
if !expected {
assert!(mcp.hard_deny_allowlist_misses);
}
}
let scoped = proxy.for_execution(
"remote",
"binding-test",
"binding-token".to_string(),
policy,
Some(Arc::new(|_request| async { NetworkDecision::Allow })),
)?;
let launch = scoped
.remote_launch_config(local_binding_policy, RemoteCredentialMasking::Disabled)
.await;
assert_eq!(proxy.current_cfg().await?, carrier.config, "{name}");
if local_binding_policy == RequireTrue && !expected {
assert!(
launch
.unwrap_err()
.to_string()
.contains("MXC cannot enforce allow_local_binding=false"),
"{name}"
);
continue;
}
let launch = launch?;
assert_eq!(launch.proxy.allow_local_binding, expected, "{name}");
let Some(decider) = scoped.remote_policy_decider(launch.proxy.allow_local_binding)
else {
assert_eq!(name, "managed_omitted");
continue;
};
let decision = decider
.decide(akode_network_proxy::NetworkPolicyRequest::new(
akode_network_proxy::NetworkPolicyRequestArgs {
protocol: akode_network_proxy::NetworkProtocol::HttpsConnect,
host: "10.0.0.1".to_string(),
port: 443,
environment_id: None,
client_addr: None,
method: None,
command: None,
exec_policy_hint: None,
},
))
.await;
assert_eq!(
decision,
if expected {
NetworkDecision::Allow
} else {
NetworkDecision::deny_with_source(
"not_allowed_local",
akode_network_proxy::NetworkDecisionSource::BaselinePolicy,
)
},
"{name}"
);
}
}
assert_eq!(controller, original_controller, "{name}");
}
Ok(())
}

View File

@@ -0,0 +1,12 @@
use akode_config::types::OtelConfig;
use akode_config::types::OtelConfigToml;
/// Resolves the local logging settings kept under the historical `[otel]` table.
/// Telemetry exporters were removed; their former keys are accepted and ignored.
pub(crate) fn resolve_config(config: OtelConfigToml) -> OtelConfig {
OtelConfig {
tool_result: config.tool_result.unwrap_or_default(),
log_sse_deltas: config.log_sse_deltas.unwrap_or(true),
log_user_prompt: config.log_user_prompt.unwrap_or(false),
}
}

View File

@@ -0,0 +1,75 @@
//! Permission-profile path grammar. Path facts and resolution are owned by
//! the shared configuration context; symbolic paths preserve native spelling.
use std::io;
use akode_config::ConfigPathContext;
use akode_utils_absolute_path::normalize_windows_device_path;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
pub(super) fn contains_glob(path: &str, context: &ConfigPathContext) -> io::Result<bool> {
Ok(contains_glob_chars_for_platform(
path,
context.convention() == PathConvention::Windows,
))
}
pub(super) fn absolute_path(path: &str, context: &ConfigPathContext) -> io::Result<PathUri> {
let convention = context.convention();
if convention.home_relative_suffix(path).is_none()
&& LegacyAppPathString::from_string(path)
.to_path_uri(convention)
.is_err()
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("filesystem path `{path}` must be absolute, use `~/...`, or start with `:`"),
));
}
context
.resolve_path(path)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
}
pub(super) fn relative_subpath(subpath: &str, context: &ConfigPathContext) -> io::Result<String> {
let convention = context.convention();
let mut components = convention.path_segments(subpath);
let first = components.next();
let has_drive_prefix = convention == PathConvention::Windows
&& subpath
.as_bytes()
.first()
.is_some_and(u8::is_ascii_alphabetic)
&& subpath.as_bytes().get(1) == Some(&b':');
if !subpath.is_empty()
&& !matches!(first, Some("" | "." | ".."))
&& !has_drive_prefix
&& !components.any(|component| component == "..")
{
// Preserve spelling after the same validation as native components:
// interior `.` and repeated separators stay in symbolic rules.
return Ok(subpath.to_string());
}
Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"filesystem subpath `{subpath}` must be a descendant path without `.` or `..` components"
),
))
}
pub(super) fn contains_glob_chars_for_platform(path: &str, is_windows: bool) -> bool {
let normalized_windows_path = if is_windows {
normalize_windows_device_path(path)
} else {
None
};
let path = normalized_windows_path.as_deref().unwrap_or(path);
path.chars().any(|ch| matches!(ch, '*' | '?' | '[' | ']'))
}
#[cfg(test)]
#[path = "permission_path_tests.rs"]
mod tests;

View File

@@ -0,0 +1,542 @@
//! Permission compilation preserves executor paths and native policy semantics.
use super::super::permissions::CompiledPermissionProfile;
use super::super::permissions::WorkspaceWriteSettings;
use super::super::permissions::compile_permission_profile;
use super::relative_subpath;
use akode_config::ConfigPathContext;
use akode_config::permissions_toml::FilesystemPermissionToml;
use akode_config::permissions_toml::FilesystemPermissionToml::Access;
use akode_config::permissions_toml::FilesystemPermissionsToml;
use akode_config::permissions_toml::PermissionProfileToml;
use akode_config::permissions_toml::PermissionsToml;
use akode_config::permissions_toml::WorkspaceRootsToml;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemAccessMode::Deny;
use akode_protocol::permissions::FileSystemAccessMode::Read;
use akode_protocol::permissions::FileSystemAccessMode::Write;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::permissions::ReadDenyMatcher;
use akode_protocol::permissions::project_roots_glob_pattern;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::path::Path;
struct ExecutorPathFacts {
base_dir: PathUri,
user_home_dir: Option<PathUri>,
}
impl ExecutorPathFacts {
fn context(&self) -> ConfigPathContext {
ConfigPathContext::new(
self.base_dir.infer_path_convention().unwrap(),
Some(self.base_dir.clone()),
self.user_home_dir.clone(),
)
}
fn policy_context(&self) -> FileSystemSandboxPolicyContext<'_> {
FileSystemSandboxPolicyContext {
cwd: &self.base_dir,
workspace_roots: std::slice::from_ref(&self.base_dir),
user_home_dir: self.user_home_dir.as_ref(),
temporary_directories: None,
}
}
fn compile(&self, permissions: &PermissionsToml) -> std::io::Result<CompiledPermissionProfile> {
compile_permission_profile(
Some(permissions),
"remote",
&self.context(),
/*workspace_write*/ None,
&mut Vec::new(),
)
}
}
fn executor_contexts() -> impl Iterator<Item = ExecutorPathFacts> {
[
("file:///workspace/project", "file:///home/executor"),
("file:///Users/executor/project", "file:///Users/executor"),
("file:///C:/workspace/project", "file:///C:/Users/executor"),
(
"file://server/share/project",
"file://server/share/users/executor",
),
]
.into_iter()
.map(|(cwd, home)| ExecutorPathFacts {
base_dir: PathUri::parse(cwd).unwrap(),
user_home_dir: Some(PathUri::parse(home).unwrap()),
})
}
fn permissions_with_rule(
path: impl Into<String>,
permission: FilesystemPermissionToml,
) -> PermissionsToml {
PermissionsToml {
entries: BTreeMap::from([(
"remote".to_string(),
PermissionProfileToml {
filesystem: Some(FilesystemPermissionsToml {
glob_scan_max_depth: None,
entries: BTreeMap::from([(path.into(), permission)]),
}),
..Default::default()
},
)]),
}
}
fn scoped(entries: &[(&str, FileSystemAccessMode)]) -> FilesystemPermissionToml {
FilesystemPermissionToml::Scoped(
entries
.iter()
.map(|(path, access)| (path.to_string(), *access))
.collect(),
)
}
#[track_caller]
fn assert_invalid(result: std::io::Result<CompiledPermissionProfile>) {
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);
}
#[track_caller]
fn assert_read_denials(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
cases: &[(PathUri, bool)],
) {
let matcher = ReadDenyMatcher::try_new_with_context(policy, context)
.unwrap()
.unwrap();
for (path, denied) in cases {
assert_eq!(
matcher.is_read_denied_uri(path, context),
*denied,
"path={path}"
);
}
}
#[track_caller]
fn assert_executor_rule(
permissions: &PermissionsToml,
context: &ConfigPathContext,
expected: FileSystemSandboxEntry,
) -> CompiledPermissionProfile {
let mut warnings = Vec::new();
let compiled = compile_permission_profile(
Some(permissions),
"remote",
context,
/*workspace_write*/ None,
&mut warnings,
)
.unwrap();
assert_eq!(
(
compiled.permission_profile.to_runtime_permissions(),
&compiled.workspace_roots
),
(
(
FileSystemSandboxPolicy::restricted(vec![expected]),
NetworkSandboxPolicy::Restricted
),
&Vec::<PathUri>::new(),
),
"permissions={permissions:?}, context={context:?}",
);
assert!(warnings.is_empty(), "{warnings:?}");
compiled
}
fn deny_glob_entry(pattern: impl Into<String>) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: pattern.into(),
},
Deny,
)
}
#[test]
fn compiler_uses_shared_resolution_for_literal_and_glob_rules() {
for facts in executor_contexts() {
let home = facts.user_home_dir.as_ref().unwrap();
let root = home.join("shared").unwrap();
let literal = FileSystemSandboxEntry::new(root.into(), Write);
let glob = deny_glob_entry(
home.join("shared/*.env")
.unwrap()
.inferred_native_path_string(),
);
for (input, permission, expected) in [
("~/shared/**".into(), Access(Write), literal.clone()),
("~/shared/*.env".into(), Access(Deny), glob.clone()),
(
home.inferred_native_path_string(),
scoped(&[("shared", Write)]),
literal,
),
(
home.inferred_native_path_string(),
scoped(&[("shared/*.env", Deny)]),
glob,
),
] {
assert_executor_rule(
&permissions_with_rule(input, permission),
&facts.context(),
expected,
);
}
}
}
#[test]
fn scoped_home_rules_resolve_and_deny_the_supplied_home() {
for facts in executor_contexts() {
let home = facts.user_home_dir.as_ref().unwrap();
let home_glob = match facts.context().convention() {
PathConvention::Posix => "~/private/*.env",
PathConvention::Windows => r"~\private\*.env",
};
for outer in [
facts.base_dir.inferred_native_path_string(),
":workspace_roots".into(),
":project_roots".into(),
] {
for (subpath, resolved) in [
("~", home.clone()),
("~/private", home.join("private").unwrap()),
(home_glob, home.join("private/*.env").unwrap()),
] {
let expected = if subpath.contains('*') {
deny_glob_entry(resolved.inferred_native_path_string())
} else {
FileSystemSandboxEntry::new(resolved.into(), Deny)
};
let permissions = permissions_with_rule(&outer, scoped(&[(subpath, Deny)]));
let compiled = assert_executor_rule(&permissions, &facts.context(), expected);
assert_read_denials(
&compiled.permission_profile.file_system_sandbox_policy(),
&facts.policy_context(),
&[
(home.join("private/key.env").unwrap(), true),
(
facts.base_dir.join("private/key.env").unwrap(),
subpath == "~" && facts.base_dir.starts_with(home),
),
],
);
}
for subpath in ["~/../private", "~/child/../private"] {
let permissions = permissions_with_rule(&outer, scoped(&[(subpath, Deny)]));
assert_invalid(facts.compile(&permissions));
}
}
}
}
#[test]
fn inherited_workspace_roots_apply_to_executor_policy_and_read_denials() {
let permissions: PermissionsToml = toml::from_str(
r#"
[base]
extends = ":read-only"
[base.workspace_roots]
"../shared" = true
"~/scratch" = true
[remote]
extends = "base"
[remote.workspace_roots]
"../shared" = false
"./profile-root" = true
[remote.filesystem]
glob_scan_max_depth = 3
[remote.filesystem.":workspace_roots"]
"." = "write"
"private/*.env" = "deny"
[remote.network]
enabled = true
"#,
)
.unwrap();
for facts in executor_contexts() {
let compiled = facts.compile(&permissions).unwrap();
let (policy, network) = compiled.permission_profile.to_runtime_permissions();
let roots = compiled.workspace_roots;
let home = facts.user_home_dir.as_ref().unwrap();
assert_eq!(
(&roots, network),
(
&vec![
facts.base_dir.join("profile-root").unwrap(),
home.join("scratch").unwrap()
],
NetworkSandboxPolicy::Enabled
),
);
let policy =
policy.materialize_project_roots_with_path_uris(std::slice::from_ref(&facts.base_dir));
let context = facts.policy_context();
for root in std::iter::once(&facts.base_dir).chain(&roots) {
assert!(policy.can_write_path(&root.join("output").unwrap(), &context));
assert_read_denials(
&policy,
&context,
&[
(root.join("private/key.env").unwrap(), true),
(root.join("private/key.txt").unwrap(), false),
],
);
}
}
}
#[test]
fn interior_dot_workspace_glob_fails_closed_for_every_path_convention() {
let permissions = permissions_with_rule(
":workspace_roots",
scoped(&[(".", Write), ("private/./*.env", Deny)]),
);
// Preserve the symbolic spelling; strict materialization rejects dot components.
let expected = (
FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: akode_protocol::permissions::FileSystemSpecialPath::project_roots(
/*subpath*/ None,
),
},
Write,
),
deny_glob_entry("codex-project-roots://private/./*.env"),
]),
NetworkSandboxPolicy::Restricted,
);
for facts in executor_contexts() {
let compiled = facts.compile(&permissions).unwrap();
assert_eq!(
compiled.permission_profile.to_runtime_permissions(),
expected
);
let policy = compiled
.permission_profile
.file_system_sandbox_policy()
.materialize_project_roots_with_path_uris(std::slice::from_ref(&facts.base_dir));
let context = facts.policy_context();
assert!(!policy.can_write_path(&facts.base_dir.join("output").unwrap(), &context));
assert_read_denials(
&policy,
&context,
&[
(facts.base_dir.join("private/key.env").unwrap(), true),
(facts.base_dir.join("private/key.txt").unwrap(), true),
],
);
}
}
#[test]
fn permission_rules_require_absolute_paths_and_descendant_subpaths() {
for mut facts in executor_contexts() {
facts.user_home_dir = None;
// Unlike the shared resolver, permission rules cannot use cwd-relative paths.
// Missing executor home must not fall back to this host's home.
for input in [
"relative",
"./relative",
"~",
"~/private",
"C:private",
r"\private",
// Preserve raw-text validation even when URI parsing would remove `a:b`.
r"C:\base\a:b\..\private",
] {
assert_invalid(facts.compile(&permissions_with_rule(input, Access(Read))));
}
for outer in [
facts.base_dir.inferred_native_path_string(),
":workspace_roots".into(),
] {
for input in ["../private", "./private", "child/../private"] {
assert_invalid(
facts.compile(&permissions_with_rule(&outer, scoped(&[(input, Deny)]))),
);
}
}
}
}
#[test]
fn executor_scoped_globs_preserve_native_separator_spelling() {
for facts in
executor_contexts().filter(|facts| facts.context().convention() == PathConvention::Windows)
{
for subpath in ["secrets/*.env", r"secrets\*.env", r"nested/secrets\*.env"] {
assert_executor_rule(
&permissions_with_rule(":workspace_roots", scoped(&[(subpath, Deny)])),
&facts.context(),
deny_glob_entry(project_roots_glob_pattern(Path::new(subpath))),
);
}
}
}
fn native_context() -> ConfigPathContext {
ConfigPathContext::new(
PathConvention::native(),
std::env::current_dir()
.ok()
.and_then(|cwd| PathUri::from_host_native_path(cwd).ok()),
AbsolutePathBufGuard::home_directory()
.and_then(|home| PathUri::from_host_native_path(home).ok()),
)
}
#[test]
fn native_path_grammar_preserves_component_validation_and_spelling() {
let context = native_context();
for input in [
"",
".",
"..",
"./child",
"../child",
"child/../other",
"child/./other",
"child//other/",
"~/child",
r"~\child",
r"C:child",
"/child",
r"\child",
"child/.../leaf",
] {
let native_accepts = !input.is_empty()
&& Path::new(input)
.components()
.all(|component| matches!(component, std::path::Component::Normal(_)));
match relative_subpath(input, &context) {
Ok(actual) => {
assert!(native_accepts, "{input}");
assert_eq!(actual, input);
}
Err(_) => assert!(!native_accepts, "{input}"),
}
}
}
#[cfg(unix)]
#[test]
fn non_unicode_home_is_rejected_by_the_shared_compiler() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let home = std::path::PathBuf::from(OsString::from_vec(b"/home/native-\xff".to_vec()));
AbsolutePathBufGuard::with_home_directory(&home, || {
let permissions = permissions_with_rule("~/read", Access(Read));
assert_invalid(compile_permission_profile(
Some(&permissions),
"remote",
&native_context(),
/*workspace_write*/ None,
&mut Vec::new(),
));
});
}
#[test]
fn deny_globs_validate_literal_home_and_scoped_directories() {
for mut facts in executor_contexts() {
let directory = facts.base_dir.join("sam[1]").unwrap();
facts.user_home_dir = Some(directory.clone());
for (outer, permission) in [
("~/private/*.key".into(), Access(Deny)),
("~/private".into(), scoped(&[("*.key", Deny)])),
(
directory.inferred_native_path_string(),
scoped(&[("private/*.key", Deny)]),
),
] {
assert_invalid(facts.compile(&permissions_with_rule(outer, permission)));
}
}
}
#[test]
fn compiler_applies_deny_globs_safely_to_literal_profile_workspace_roots() {
for facts in executor_contexts() {
let root = facts.base_dir.join("sam[1]").unwrap();
let mut permissions = permissions_with_rule(
":workspace_roots",
scoped(&[(".", Write), ("private/*.key", Deny)]),
);
permissions
.entries
.get_mut("remote")
.unwrap()
.workspace_roots = Some(WorkspaceRootsToml {
entries: BTreeMap::from([(root.inferred_native_path_string(), true)]),
});
let compiled = facts.compile(&permissions).unwrap();
assert_eq!(compiled.workspace_roots, vec![root.clone()]);
// Infallible materialization conservatively denies the literal root.
assert_read_denials(
&compiled.permission_profile.file_system_sandbox_policy(),
&facts.policy_context(),
&[
(root.join("private/a.key").unwrap(), true),
(root.join("public.txt").unwrap(), true),
(facts.base_dir.join("sam1/private/a.key").unwrap(), false),
],
);
}
}
#[test]
fn builtin_workspace_settings_use_executor_roots_in_the_compiled_profile() {
for facts in executor_contexts() {
let root = facts.base_dir.join("legacy-root").unwrap();
let settings = WorkspaceWriteSettings {
writable_roots: vec![root.clone(), root.clone()],
network_access: true,
exclude_tmpdir_env_var: true,
exclude_slash_tmp: true,
};
let compiled = compile_permission_profile(
/*permissions*/ None,
":workspace",
&facts.context(),
Some(&settings),
&mut Vec::new(),
)
.unwrap();
assert_eq!(compiled.workspace_roots, vec![root.clone()]);
assert_eq!(
compiled.permission_profile.network_sandbox_policy(),
NetworkSandboxPolicy::Enabled,
);
let policy_context = facts.policy_context();
assert!(
compiled
.permission_profile
.file_system_sandbox_policy()
.can_write_path(&root.join("output").unwrap(), &policy_context)
);
}
}

View File

@@ -0,0 +1,145 @@
use akode_config::ConfigLayerStack;
use akode_config::ConfigPathContext;
use akode_config::RequirementSource;
use akode_config::SandboxModeRequirement;
use akode_config::Sourced;
use akode_config::permissions_toml::PermissionsToml;
use akode_config::sandbox_mode_requirement_for_permission_profile;
use akode_protocol::models::PermissionProfile;
use super::ConstraintError;
use super::ConstraintResult;
use super::is_permission_allowed;
use super::merge_managed_permission_profiles;
use super::permissions::BUILT_IN_DANGER_FULL_ACCESS_PROFILE;
use super::permissions::BUILT_IN_READ_ONLY_PROFILE;
use super::permissions::BUILT_IN_WORKSPACE_PROFILE;
use super::permissions::compile_permission_profile;
use super::permissions::validate_user_permission_profile_names;
use super::validate_required_permission_profile_catalog;
/// A permission profile exposed to clients together with its effective availability.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionProfileCatalogEntry {
pub id: String,
pub description: Option<String>,
pub allowed: bool,
}
/// Builds the effective catalog using supplied execution-host path facts.
pub fn permission_profile_catalog(
config_layer_stack: &ConfigLayerStack,
context: &ConfigPathContext,
) -> std::io::Result<Vec<PermissionProfileCatalogEntry>> {
let permissions = config_layer_stack
.effective_config()
.get("permissions")
.cloned()
.map(toml::Value::try_into::<PermissionsToml>)
.transpose()
.map_err(std::io::Error::other)?;
let requirements_toml = config_layer_stack.requirements_toml();
let permissions = merge_managed_permission_profiles(permissions.as_ref(), requirements_toml)?;
permission_profile_catalog_from_permissions(config_layer_stack, permissions.as_ref(), context)
}
pub(super) fn permission_profile_catalog_from_permissions(
config_layer_stack: &ConfigLayerStack,
permissions: Option<&PermissionsToml>,
context: &ConfigPathContext,
) -> std::io::Result<Vec<PermissionProfileCatalogEntry>> {
let requirements_toml = config_layer_stack.requirements_toml();
validate_user_permission_profile_names(permissions)?;
validate_required_permission_profile_catalog(requirements_toml, permissions)?;
let entries = [
BUILT_IN_READ_ONLY_PROFILE,
BUILT_IN_WORKSPACE_PROFILE,
BUILT_IN_DANGER_FULL_ACCESS_PROFILE,
]
.into_iter()
.map(|id| (id, None))
.chain(
permissions
.into_iter()
.flat_map(|permissions| &permissions.entries)
.map(|(id, profile)| (id.as_str(), profile.description.clone())),
);
let catalog = entries
.map(|(id, description)| {
let allowed = compile_permission_profile(
permissions,
id,
context,
/*workspace_write*/ None,
&mut Vec::new(),
)
.is_ok_and(|compiled| {
permission_profile_is_allowed(config_layer_stack, id, &compiled.permission_profile)
});
PermissionProfileCatalogEntry {
id: id.to_string(),
description,
allowed,
}
})
.collect();
Ok(catalog)
}
pub(super) fn permission_profile_is_allowed(
config_layer_stack: &ConfigLayerStack,
profile_id: &str,
permission_profile: &PermissionProfile,
) -> bool {
let allowed_by_id = config_layer_stack
.requirements_toml()
.allowed_permission_profiles
.as_ref()
.is_none_or(|allowed| is_permission_allowed(allowed, profile_id));
allowed_by_id
&& permission_profile_satisfies_requirements(config_layer_stack, permission_profile)
}
pub(super) fn permission_profile_satisfies_requirements(
config_layer_stack: &ConfigLayerStack,
permission_profile: &PermissionProfile,
) -> bool {
let allowed_by_sandbox_mode = config_layer_stack
.requirements()
.permission_profile
.can_set(permission_profile)
.is_ok();
let allowed_by_filesystem = config_layer_stack
.requirements()
.filesystem
.as_ref()
.is_none_or(|Sourced { value, source }| {
value.deny_read.is_empty()
|| validate_permission_profile_for_deny_read(permission_profile, source).is_ok()
});
allowed_by_sandbox_mode && allowed_by_filesystem
}
/// Validates that a permission candidate can enforce managed filesystem denials.
/// Add this validator before applying profile requirements so the native
/// constrained fallback can replace full-access or external candidates.
pub fn validate_permission_profile_for_deny_read(
permission_profile: &PermissionProfile,
requirement_source: &RequirementSource,
) -> ConstraintResult<()> {
let mode = sandbox_mode_requirement_for_permission_profile(permission_profile);
match mode {
SandboxModeRequirement::ReadOnly | SandboxModeRequirement::WorkspaceWrite => Ok(()),
SandboxModeRequirement::DangerFullAccess | SandboxModeRequirement::ExternalSandbox => {
Err(ConstraintError::InvalidValue {
field_name: "sandbox_mode",
candidate: format!("{mode:?}"),
allowed: "[read-only, workspace-write]".to_string(),
requirement_source: requirement_source.clone(),
})
}
}
}

View File

@@ -0,0 +1,39 @@
use akode_config::ConfigRequirementsToml;
use akode_config::permissions_toml::PermissionsToml;
/// A selected permission profile and its uncompiled configured and managed catalog.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPermissionProfileSelection<'a> {
/// The effective profile selected by configuration and managed requirements.
pub profile_id: Option<&'a str>,
/// Configured and managed named profiles, without platform-specific compilation.
pub profiles: Option<PermissionsToml>,
}
/// Resolves the effective permission profile without interpreting profile paths.
///
/// Managed profiles and allowlists are applied using Core's normal selection rules,
/// while the merged profile catalog remains uncompiled for the executor to interpret.
pub fn resolve_permission_profile_selection<'a>(
configured_profiles: Option<&PermissionsToml>,
configured_default_profile_id: Option<&'a str>,
requirements: &'a ConfigRequirementsToml,
) -> std::io::Result<ResolvedPermissionProfileSelection<'a>> {
let selection = super::resolve_effective_permission_selection(
configured_profiles,
/*default_permissions_override*/ None,
/*persisted_profile_id*/ None,
configured_default_profile_id,
requirements,
&mut Vec::new(),
)?;
Ok(ResolvedPermissionProfileSelection {
profile_id: selection.selected_profile_id,
profiles: selection.profiles,
})
}
#[cfg(test)]
#[path = "permission_profile_selection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,96 @@
use crate::config::ResolvedPermissionProfileSelection;
use crate::config::resolve_permission_profile_selection;
use akode_config::ConfigRequirementsToml;
use akode_config::permissions_toml::PermissionsToml;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn resolves_managed_profile_without_compiling_executor_paths() -> anyhow::Result<()> {
let configured_profiles = toml::from_str::<PermissionsToml>(
r#"
[configured-windows]
extends = ":workspace"
[configured-windows.workspace_roots]
'C:\Users\agent\workspace' = true
[configured-windows.filesystem]
'C:\Users\agent\workspace' = "write"
"#,
)?;
let requirements = toml::from_str::<ConfigRequirementsToml>(
r#"
default_permissions = "managed-windows"
[allowed_permission_profiles]
configured-windows = false
managed-windows = true
[permissions.managed-windows.workspace_roots]
'D:\Managed\workspace' = true
[permissions.managed-windows.filesystem]
'D:\Managed\workspace' = "read"
"#,
)?;
let expected_profiles = PermissionsToml {
entries: BTreeMap::from([
(
"configured-windows".to_string(),
configured_profiles.entries["configured-windows"].clone(),
),
(
"managed-windows".to_string(),
requirements
.permissions
.as_ref()
.expect("managed profiles should deserialize")
.profiles["managed-windows"]
.clone(),
),
]),
};
let resolved = resolve_permission_profile_selection(
Some(&configured_profiles),
Some("configured-windows"),
&requirements,
)?;
assert_eq!(
resolved,
ResolvedPermissionProfileSelection {
profile_id: Some("managed-windows"),
profiles: Some(expected_profiles),
}
);
Ok(())
}
#[test]
fn rejects_undefined_allowlisted_permission_profile() -> anyhow::Result<()> {
let requirements = toml::from_str::<ConfigRequirementsToml>(
r#"
default_permissions = "missing-profile"
[allowed_permission_profiles]
missing-profile = true
"#,
)?;
let error = resolve_permission_profile_selection(
/*configured_profiles*/ None,
/*configured_default_profile_id*/ None,
&requirements,
)
.expect_err("undefined allowlisted profiles should be rejected");
assert_eq!(
error.to_string(),
"requirements.toml allowed_permission_profiles refers to undefined profile `missing-profile`"
);
Ok(())
}

View File

@@ -0,0 +1,883 @@
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::io;
use std::path::Path;
use akode_config::ConfigPathContext;
use akode_config::permissions_toml::FilesystemPermissionToml;
use akode_config::permissions_toml::FilesystemPermissionsToml;
use akode_config::permissions_toml::NetworkDomainPermissionToml;
use akode_config::permissions_toml::NetworkDomainPermissionsToml;
use akode_config::permissions_toml::NetworkToml;
use akode_config::permissions_toml::NetworkUnixSocketPermissionToml;
use akode_config::permissions_toml::NetworkUnixSocketPermissionsToml;
use akode_config::permissions_toml::PermissionProfileToml;
use akode_config::permissions_toml::PermissionsToml;
use akode_config::permissions_toml::WorkspaceRootsToml;
use akode_features::NetworkProxyConfigToml;
use akode_features::NetworkProxyDomainPermissionToml;
use akode_features::NetworkProxyModeToml;
use akode_features::NetworkProxyUnixSocketPermissionToml;
use akode_network_proxy::NetworkMode;
use akode_network_proxy::NetworkProxyConfig;
#[cfg(test)]
use akode_network_proxy::NetworkUnixSocketPermission as ProxyNetworkUnixSocketPermission;
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
use akode_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::permissions::project_roots_glob_pattern;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use super::ProjectConfig;
use super::permission_path;
#[cfg(test)]
use super::permission_path::contains_glob_chars_for_platform;
pub(crate) const BUILT_IN_READ_ONLY_PROFILE: &str = BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
pub(crate) const BUILT_IN_WORKSPACE_PROFILE: &str = BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
pub(crate) const BUILT_IN_DANGER_FULL_ACCESS_PROFILE: &str =
BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
/// Keep the active apply_patch aliases readable without granting access to other
/// sessions or the rest of AKODE_HOME. Preserve the alias directory, not its target.
pub(super) fn active_arg0_helper_dir(
codex_home: &Path,
path_env: &OsStr,
) -> Option<AbsolutePathBuf> {
let arg0_root = codex_home
.join("tmp")
.join(format!("arg0-{}", std::env::consts::OS));
let legacy_root = codex_home.join("tmp").join("arg0");
std::env::split_paths(path_env)
.find(|path| {
(path.parent() == Some(arg0_root.as_path())
|| path.parent() == Some(legacy_root.as_path()))
&& path
.file_name()
.is_some_and(|name| name.to_string_lossy().starts_with("akode-arg0"))
})
.and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
}
pub(crate) fn default_builtin_permission_profile_name(
active_project: &ProjectConfig,
windows_sandbox_level: WindowsSandboxLevel,
) -> &'static str {
if (active_project.is_trusted() || active_project.is_untrusted())
&& !(cfg!(target_os = "windows") && windows_sandbox_level == WindowsSandboxLevel::Disabled)
{
BUILT_IN_WORKSPACE_PROFILE
} else {
BUILT_IN_READ_ONLY_PROFILE
}
}
pub(crate) fn is_builtin_permission_profile_name(profile_name: &str) -> bool {
matches!(
profile_name,
BUILT_IN_READ_ONLY_PROFILE
| BUILT_IN_WORKSPACE_PROFILE
| BUILT_IN_DANGER_FULL_ACCESS_PROFILE
)
}
fn builtin_permission_profile(
profile_name: &str,
workspace_write: Option<&WorkspaceWriteSettings>,
) -> Option<PermissionProfile> {
match profile_name {
BUILT_IN_READ_ONLY_PROFILE => Some(PermissionProfile::read_only()),
BUILT_IN_WORKSPACE_PROFILE => Some(match workspace_write {
Some(WorkspaceWriteSettings {
writable_roots: _,
network_access,
exclude_tmpdir_env_var,
exclude_slash_tmp,
}) => PermissionProfile::workspace_write_with(
&[],
if *network_access {
NetworkSandboxPolicy::Enabled
} else {
NetworkSandboxPolicy::Restricted
},
*exclude_tmpdir_env_var,
*exclude_slash_tmp,
),
None => PermissionProfile::workspace_write(),
}),
BUILT_IN_DANGER_FULL_ACCESS_PROFILE => Some(PermissionProfile::Disabled),
_ => None,
}
}
pub(crate) fn validate_user_permission_profile_names(
permissions: Option<&PermissionsToml>,
) -> io::Result<()> {
let Some(permissions) = permissions else {
return Ok(());
};
for profile_name in permissions.entries.keys() {
if profile_name.starts_with(':') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"permissions profile `{profile_name}` uses a reserved built-in profile prefix"
),
));
}
}
Ok(())
}
pub fn network_proxy_config_from_profile_network(
network: Option<&NetworkToml>,
) -> NetworkProxyConfig {
let mut config = network.map_or_else(
NetworkProxyConfig::default,
NetworkToml::to_network_proxy_config,
);
// Profile `network.enabled` controls sandbox network access. Profiles may
// provide proxy settings for the feature gate to consume when that network
// access is enabled, but they do not start the managed proxy on their own.
config.enabled = false;
config
}
pub(crate) fn apply_network_proxy_feature_config(
config: &mut NetworkProxyConfig,
feature_config: &NetworkProxyConfigToml,
) {
NetworkToml {
enabled: feature_config.enabled,
proxy_url: feature_config.proxy_url.clone(),
enable_socks5: feature_config.enable_socks5,
socks_url: feature_config.socks_url.clone(),
enable_socks5_udp: feature_config.enable_socks5_udp,
allow_upstream_proxy: feature_config.allow_upstream_proxy,
dangerously_allow_non_loopback_proxy: feature_config.dangerously_allow_non_loopback_proxy,
dangerously_allow_all_unix_sockets: feature_config.dangerously_allow_all_unix_sockets,
mode: feature_config.mode.map(|mode| match mode {
NetworkProxyModeToml::Limited => NetworkMode::Limited,
NetworkProxyModeToml::Full => NetworkMode::Full,
}),
domains: feature_config
.domains
.as_ref()
.map(|domains| NetworkDomainPermissionsToml {
entries: domains
.iter()
.map(|(pattern, permission)| {
let permission = match permission {
NetworkProxyDomainPermissionToml::Allow => {
NetworkDomainPermissionToml::Allow
}
NetworkProxyDomainPermissionToml::Deny => {
NetworkDomainPermissionToml::Deny
}
};
(pattern.clone(), permission)
})
.collect(),
}),
unix_sockets: feature_config.unix_sockets.as_ref().map(|unix_sockets| {
NetworkUnixSocketPermissionsToml {
entries: unix_sockets
.iter()
.map(|(path, permission)| {
let permission = match permission {
NetworkProxyUnixSocketPermissionToml::Allow => {
NetworkUnixSocketPermissionToml::Allow
}
NetworkProxyUnixSocketPermissionToml::Deny => {
NetworkUnixSocketPermissionToml::Deny
}
};
(path.clone(), permission)
})
.collect(),
}
}),
allow_local_binding: feature_config.allow_local_binding,
mitm: None,
}
.apply_to_network_proxy_config(config);
if let Some(credential_broker) = feature_config.credential_broker {
config.set_credential_broker_enabled(credential_broker);
}
if let Some(credentials) = feature_config.credentials.as_ref() {
config.credential_providers.clone_from(credentials);
}
}
/// Resolves a named permission profile and its inherited configuration.
pub fn resolve_permission_profile(
permissions: &PermissionsToml,
profile_name: &str,
) -> io::Result<PermissionProfileToml> {
permissions
.resolve_profile(profile_name, extensible_builtin_parent_profile)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err.to_string()))
}
fn extensible_builtin_parent_profile(profile_name: &str) -> Option<PermissionProfileToml> {
let file_system = match profile_name {
BUILT_IN_READ_ONLY_PROFILE => FileSystemSandboxPolicy::read_only(),
BUILT_IN_WORKSPACE_PROFILE => FileSystemSandboxPolicy::workspace_write(
&[],
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ false,
),
_ => return None,
};
Some(permission_profile_toml_from_file_system_policy(file_system))
}
fn permission_profile_toml_from_file_system_policy(
file_system: FileSystemSandboxPolicy,
) -> PermissionProfileToml {
let mut filesystem = FilesystemPermissionsToml {
glob_scan_max_depth: file_system.glob_scan_max_depth,
entries: BTreeMap::new(),
};
for entry in file_system.entries {
insert_filesystem_permission_toml(&mut filesystem.entries, entry);
}
PermissionProfileToml {
description: None,
extends: None,
workspace_roots: None,
filesystem: Some(filesystem),
network: None,
}
}
fn insert_filesystem_permission_toml(
entries: &mut BTreeMap<String, FilesystemPermissionToml>,
entry: FileSystemSandboxEntry,
) {
if entry.skips_missing_path() {
return;
}
match entry.path {
FileSystemPath::Path { path } => {
entries.insert(
path.inferred_native_path_string(),
FilesystemPermissionToml::Access(entry.access),
);
}
FileSystemPath::GlobPattern { pattern } => {
entries.insert(pattern, FilesystemPermissionToml::Access(entry.access));
}
FileSystemPath::Special { value } => {
insert_special_filesystem_permission_toml(entries, value, entry.access);
}
}
}
fn insert_special_filesystem_permission_toml(
entries: &mut BTreeMap<String, FilesystemPermissionToml>,
value: FileSystemSpecialPath,
access: FileSystemAccessMode,
) {
match value {
FileSystemSpecialPath::Root => {
entries.insert(
":root".to_string(),
FilesystemPermissionToml::Access(access),
);
}
FileSystemSpecialPath::Minimal => {
entries.insert(
":minimal".to_string(),
FilesystemPermissionToml::Access(access),
);
}
FileSystemSpecialPath::ProjectRoots { subpath } => {
insert_scoped_filesystem_permission_toml(
entries,
":workspace_roots".to_string(),
subpath.unwrap_or_else(|| ".".to_string()),
access,
);
}
FileSystemSpecialPath::Tmpdir => {
entries.insert(
":tmpdir".to_string(),
FilesystemPermissionToml::Access(access),
);
}
FileSystemSpecialPath::SlashTmp => {
entries.insert(
":slash_tmp".to_string(),
FilesystemPermissionToml::Access(access),
);
}
FileSystemSpecialPath::Unknown { path, subpath } => {
if let Some(subpath) = subpath {
insert_scoped_filesystem_permission_toml(entries, path, subpath, access);
} else {
entries.insert(path, FilesystemPermissionToml::Access(access));
}
}
};
}
fn insert_scoped_filesystem_permission_toml(
entries: &mut BTreeMap<String, FilesystemPermissionToml>,
path: String,
subpath: String,
access: FileSystemAccessMode,
) {
let permission = entries
.entry(path)
.or_insert_with(|| FilesystemPermissionToml::Scoped(BTreeMap::new()));
match permission {
FilesystemPermissionToml::Scoped(scoped_entries) => {
scoped_entries.insert(subpath, access);
}
FilesystemPermissionToml::Access(_) => {
*permission = FilesystemPermissionToml::Scoped(BTreeMap::from([(subpath, access)]));
}
}
}
pub(crate) fn network_proxy_config_for_profile_selection(
permissions: Option<&PermissionsToml>,
profile_name: &str,
) -> io::Result<NetworkProxyConfig> {
if is_builtin_permission_profile_name(profile_name) {
return Ok(NetworkProxyConfig::default());
}
reject_unknown_builtin_permission_profile(profile_name)?;
let permissions = permissions.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"default_permissions requires a `[permissions]` table",
)
})?;
let profile = resolve_permission_profile(permissions, profile_name)?;
Ok(network_proxy_config_from_profile_network(
profile.network.as_ref(),
))
}
/// Supplied legacy workspace-write settings, using paths owned by the execution host.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WorkspaceWriteSettings {
pub writable_roots: Vec<PathUri>,
pub network_access: bool,
pub exclude_tmpdir_env_var: bool,
pub exclude_slash_tmp: bool,
}
/// A compiled profile with configured roots materialized and runtime root symbols retained.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompiledPermissionProfile {
pub permission_profile: PermissionProfile,
pub workspace_roots: Vec<PathUri>,
}
/// Resolves a selected profile and its roots using only supplied execution-host facts.
/// Configured roots are materialized before return; symbolic roots remain available
/// for runtime workspace selection. Callers retain URI roots until a native executor boundary.
pub fn compile_permission_profile(
permissions: Option<&PermissionsToml>,
profile_name: &str,
context: &ConfigPathContext,
workspace_write: Option<&WorkspaceWriteSettings>,
startup_warnings: &mut Vec<String>,
) -> io::Result<CompiledPermissionProfile> {
let builtin = builtin_permission_profile(profile_name, workspace_write);
let (file_system, network, mut workspace_roots) = if let Some(builtin) = &builtin {
let (file_system, network) = builtin.to_runtime_permissions();
let workspace_roots = if profile_name == BUILT_IN_WORKSPACE_PROFILE {
workspace_write
.into_iter()
.flat_map(|settings| &settings.writable_roots)
.map(|root| {
context
.resolve_against(".", root)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
})
.collect::<io::Result<Vec<_>>>()?
} else {
Vec::new()
};
(file_system, network, workspace_roots)
} else {
reject_unknown_builtin_permission_profile(profile_name)?;
let permissions = permissions.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"default_permissions requires a `[permissions]` table",
)
})?;
let profile = resolve_permission_profile(permissions, profile_name)?;
let (file_system, network) =
compile_resolved_permission_profile(&profile, profile_name, context, startup_warnings)?;
let workspace_roots = profile
.workspace_roots
.iter()
.flat_map(WorkspaceRootsToml::enabled_roots)
.map(|path| {
context
.resolve_path(path)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
})
.collect::<io::Result<Vec<_>>>()?;
(file_system, network, workspace_roots)
};
let mut seen = HashSet::new();
workspace_roots.retain(|root| seen.insert(root.clone()));
let file_system = file_system.with_materialized_project_roots_for_path_uris(&workspace_roots);
let permission_profile = match builtin {
Some(PermissionProfile::Disabled) => PermissionProfile::Disabled,
_ => PermissionProfile::from_runtime_permissions(&file_system, network),
};
Ok(CompiledPermissionProfile {
permission_profile,
workspace_roots,
})
}
fn compile_resolved_permission_profile(
profile: &PermissionProfileToml,
profile_name: &str,
context: &ConfigPathContext,
startup_warnings: &mut Vec<String>,
) -> io::Result<(FileSystemSandboxPolicy, NetworkSandboxPolicy)> {
let mut file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(Vec::new());
let base_network_sandbox_policy = NetworkSandboxPolicy::Restricted;
if let Some(filesystem) = profile.filesystem.as_ref() {
if filesystem.is_empty() && file_system_sandbox_policy.entries.is_empty() {
push_warning(
startup_warnings,
missing_filesystem_entries_warning(profile_name),
);
} else {
if cfg!(not(target_os = "macos")) {
for pattern in unsupported_read_write_glob_paths(filesystem, context)? {
push_warning(
startup_warnings,
format!(
"Filesystem glob `{pattern}` uses `read` or `write` access, which is not fully supported by this platform's sandboxing. Use an exact path or trailing `/**` subtree rule instead. `deny` globs are supported."
),
);
}
for pattern in unbounded_unreadable_globstar_paths(filesystem) {
push_warning(
startup_warnings,
format!(
"Filesystem deny-read glob `{pattern}` uses `**`. Non-macOS sandboxing does not support unbounded `**` natively; set `glob_scan_max_depth` in this filesystem profile to cap Linux glob expansion and silence this warning, or enumerate explicit depths such as `*.env`, `*/*.env`, and `*/*/*.env`."
),
);
}
}
for (path, permission) in &filesystem.entries {
file_system_sandbox_policy
.entries
.extend(compile_filesystem_permission(
path,
permission,
context,
startup_warnings,
)?);
}
}
} else if file_system_sandbox_policy.entries.is_empty() {
push_warning(
startup_warnings,
missing_filesystem_entries_warning(profile_name),
);
}
let glob_scan_max_depth = validate_glob_scan_max_depth(
profile
.filesystem
.as_ref()
.and_then(|filesystem| filesystem.glob_scan_max_depth),
)?;
if let Some(glob_scan_max_depth) = glob_scan_max_depth {
file_system_sandbox_policy.glob_scan_max_depth = Some(glob_scan_max_depth);
}
let network_sandbox_policy =
compile_network_sandbox_policy(profile.network.as_ref(), base_network_sandbox_policy);
Ok((file_system_sandbox_policy, network_sandbox_policy))
}
pub(crate) fn reject_unknown_builtin_permission_profile(profile_name: &str) -> io::Result<()> {
if profile_name.starts_with(':') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("default_permissions refers to unknown built-in profile `{profile_name}`"),
));
}
Ok(())
}
fn compile_network_sandbox_policy(
network: Option<&NetworkToml>,
base_network_sandbox_policy: NetworkSandboxPolicy,
) -> NetworkSandboxPolicy {
let Some(network) = network else {
return base_network_sandbox_policy;
};
match network.enabled {
Some(true) => NetworkSandboxPolicy::Enabled,
Some(false) => NetworkSandboxPolicy::Restricted,
None => base_network_sandbox_policy,
}
}
fn compile_filesystem_permission(
path: &str,
permission: &FilesystemPermissionToml,
context: &ConfigPathContext,
startup_warnings: &mut Vec<String>,
) -> io::Result<Vec<FileSystemSandboxEntry>> {
let mut entries = Vec::new();
match permission {
FilesystemPermissionToml::Access(access) => {
entries.push(FileSystemSandboxEntry {
path: compile_filesystem_access_path(path, *access, context, startup_warnings)?,
access: *access,
missing_path_behavior: None,
});
}
FilesystemPermissionToml::Scoped(scoped_entries) => {
for (subpath, access) in scoped_entries {
if matches!(
parse_special_path(path),
Some(FileSystemSpecialPath::ProjectRoots { .. })
) && context.convention().home_relative_suffix(subpath).is_some()
{
permission_path::relative_subpath(subpath, context)?;
entries.push(FileSystemSandboxEntry {
path: compile_filesystem_access_path(
subpath,
*access,
context,
startup_warnings,
)?,
access: *access,
missing_path_behavior: None,
});
continue;
}
let has_glob = permission_path::contains_glob(subpath, context)?;
let can_compile_as_pattern = match parse_special_path(path) {
Some(FileSystemSpecialPath::ProjectRoots { .. }) | None => true,
Some(_) => false,
};
if has_glob && *access == FileSystemAccessMode::Deny && can_compile_as_pattern {
// Scoped glob syntax is a first-class filesystem policy
// pattern entry. Literal scoped paths continue through the
// exact-path parser so existing path semantics stay intact.
let entry = FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: compile_scoped_filesystem_pattern(
path, subpath, *access, context,
)?,
},
access: *access,
missing_path_behavior: None,
};
entries.push(entry);
} else {
let subpath = compile_read_write_glob_path(subpath, *access, context)?;
entries.push(FileSystemSandboxEntry {
path: compile_scoped_filesystem_path(
path,
subpath,
context,
startup_warnings,
)?,
access: *access,
missing_path_behavior: None,
});
}
}
}
}
Ok(entries)
}
fn compile_filesystem_access_path(
path: &str,
access: FileSystemAccessMode,
context: &ConfigPathContext,
startup_warnings: &mut Vec<String>,
) -> io::Result<FileSystemPath> {
if !permission_path::contains_glob(path, context)? {
return compile_filesystem_path(path, context, startup_warnings);
}
if access == FileSystemAccessMode::Deny {
// At this point `path` is an unscoped filesystem table key. Top-level
// glob deny entries still go through the absolute-path parser before
// becoming policy patterns; relative project-root glob syntax is
// handled by `compile_scoped_filesystem_pattern`.
return Ok(FileSystemPath::GlobPattern {
pattern: permission_path::absolute_path(path, context)?
.to_config_path_string(context.convention())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?,
});
}
let path = compile_read_write_glob_path(path, access, context)?;
compile_filesystem_path(path, context, startup_warnings)
}
fn compile_filesystem_path(
path: &str,
context: &ConfigPathContext,
startup_warnings: &mut Vec<String>,
) -> io::Result<FileSystemPath> {
if let Some(special) = parse_special_path(path) {
maybe_push_unknown_special_path_warning(&special, startup_warnings);
return Ok(FileSystemPath::Special { value: special });
}
Ok(permission_path::absolute_path(path, context)?.into())
}
fn compile_scoped_filesystem_path(
path: &str,
subpath: &str,
context: &ConfigPathContext,
startup_warnings: &mut Vec<String>,
) -> io::Result<FileSystemPath> {
if subpath == "." {
return compile_filesystem_path(path, context, startup_warnings);
}
if let Some(special) = parse_special_path(path) {
let subpath = permission_path::relative_subpath(subpath, context)?;
let special = match special {
FileSystemSpecialPath::ProjectRoots { .. } => Ok(FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(Some(subpath)),
}),
FileSystemSpecialPath::Unknown { path, .. } => Ok(FileSystemPath::Special {
value: FileSystemSpecialPath::unknown(path, Some(subpath)),
}),
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("filesystem path `{path}` does not support nested entries"),
)),
}?;
if let FileSystemPath::Special { value } = &special {
maybe_push_unknown_special_path_warning(value, startup_warnings);
}
return Ok(special);
}
let subpath = permission_path::relative_subpath(subpath, context)?;
let base = permission_path::absolute_path(path, context)?;
let path = context
.resolve_against(&subpath, &base)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
Ok(path.into())
}
fn compile_scoped_filesystem_pattern(
path: &str,
subpath: &str,
access: FileSystemAccessMode,
context: &ConfigPathContext,
) -> io::Result<String> {
// Pattern entries currently mean deny-read only. Supporting broader access
// modes here would imply glob-based read/write allow semantics that the
// sandbox policy does not express yet.
if access != FileSystemAccessMode::Deny {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("filesystem glob subpath `{subpath}` only supports `deny` access"),
));
}
let subpath = permission_path::relative_subpath(subpath, context)?;
match parse_special_path(path) {
Some(FileSystemSpecialPath::ProjectRoots { .. }) => {
// Keep `:workspace_roots` glob patterns symbolic until the active
// workspace roots are known, then materialize them for cwd and any
// runtime/profile-added workspace roots together.
Ok(project_roots_glob_pattern(Path::new(&subpath)))
}
Some(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("filesystem path `{path}` does not support nested entries"),
)),
None => {
let base = permission_path::absolute_path(path, context)?;
context
.resolve_against(&subpath, &base)
.and_then(|path| path.to_config_path_string(context.convention()))
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
}
}
}
fn compile_read_write_glob_path<'a>(
path: &'a str,
access: FileSystemAccessMode,
context: &ConfigPathContext,
) -> io::Result<&'a str> {
if !permission_path::contains_glob(path, context)? {
return Ok(path);
}
let path_without_trailing_glob = remove_trailing_glob_suffix(path);
if !permission_path::contains_glob(path_without_trailing_glob, context)? {
return Ok(path_without_trailing_glob);
}
Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"filesystem glob path `{path}` only supports `deny` access; use an exact path or trailing `/**` for `{access}` subtree access"
),
))
}
fn unsupported_read_write_glob_paths(
filesystem: &FilesystemPermissionsToml,
context: &ConfigPathContext,
) -> io::Result<Vec<String>> {
let mut patterns = Vec::new();
for (path, permission) in &filesystem.entries {
match permission {
FilesystemPermissionToml::Access(access) => {
if *access != FileSystemAccessMode::Deny
&& permission_path::contains_glob(remove_trailing_glob_suffix(path), context)?
{
patterns.push(path.clone());
}
}
FilesystemPermissionToml::Scoped(scoped_entries) => {
for (subpath, access) in scoped_entries {
if *access != FileSystemAccessMode::Deny
&& permission_path::contains_glob(
remove_trailing_glob_suffix(subpath),
context,
)?
{
patterns.push(format!("{path}/{subpath}"));
}
}
}
}
}
Ok(patterns)
}
fn unbounded_unreadable_globstar_paths(filesystem: &FilesystemPermissionsToml) -> Vec<String> {
if filesystem.glob_scan_max_depth.is_some() {
return Vec::new();
}
let mut patterns = Vec::new();
for (path, permission) in &filesystem.entries {
match permission {
FilesystemPermissionToml::Access(FileSystemAccessMode::Deny) => {
if path.contains("**") {
patterns.push(path.clone());
}
}
FilesystemPermissionToml::Access(_) => {}
FilesystemPermissionToml::Scoped(scoped_entries) => {
for (subpath, access) in scoped_entries {
if *access == FileSystemAccessMode::Deny && subpath.contains("**") {
patterns.push(format!("{path}/{subpath}"));
}
}
}
}
}
patterns
}
fn validate_glob_scan_max_depth(max_depth: Option<usize>) -> io::Result<Option<usize>> {
match max_depth {
Some(0) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"glob_scan_max_depth must be at least 1",
)),
_ => Ok(max_depth),
}
}
fn remove_trailing_glob_suffix(path: &str) -> &str {
path.strip_suffix("/**").unwrap_or(path)
}
// WARNING: keep this parser forward-compatible.
// Adding a new `:special_path` must not make older Codex versions reject the
// config. Unknown values intentionally round-trip through
// `FileSystemSpecialPath::Unknown` so they can be surfaced as warnings and
// ignored, rather than aborting config load.
fn parse_special_path(path: &str) -> Option<FileSystemSpecialPath> {
match path {
":root" => Some(FileSystemSpecialPath::Root),
":minimal" => Some(FileSystemSpecialPath::Minimal),
// `:project_roots` shipped before the canonical rename; keep it as an alias.
":project_roots" | ":workspace_roots" => {
Some(FileSystemSpecialPath::project_roots(/*subpath*/ None))
}
":tmpdir" => Some(FileSystemSpecialPath::Tmpdir),
":slash_tmp" => Some(FileSystemSpecialPath::SlashTmp),
_ if path.starts_with(':') => {
Some(FileSystemSpecialPath::unknown(path, /*subpath*/ None))
}
_ => None,
}
}
fn push_warning(startup_warnings: &mut Vec<String>, message: String) {
tracing::warn!("{message}");
startup_warnings.push(message);
}
fn missing_filesystem_entries_warning(profile_name: &str) -> String {
format!(
"Permissions profile `{profile_name}` does not define any recognized filesystem entries for this version of aKode. Filesystem access will remain restricted. Upgrade aKode if this profile expects filesystem permissions."
)
}
fn maybe_push_unknown_special_path_warning(
special: &FileSystemSpecialPath,
startup_warnings: &mut Vec<String>,
) {
let FileSystemSpecialPath::Unknown { path, subpath } = special else {
return;
};
push_warning(
startup_warnings,
match subpath.as_deref() {
Some(subpath) => format!(
"Configured filesystem path `{path}` with nested entry `{subpath}` is not recognized by this version of aKode and will be ignored. Upgrade aKode if this path is required."
),
None => format!(
"Configured filesystem path `{path}` is not recognized by this version of aKode and will be ignored. Upgrade aKode if this path is required."
),
},
);
}
#[cfg(test)]
#[path = "permissions_tests.rs"]
mod tests;

View File

@@ -0,0 +1,655 @@
use super::*;
use akode_config::permissions_toml::FilesystemPermissionToml;
use akode_config::permissions_toml::FilesystemPermissionsToml;
use akode_config::permissions_toml::NetworkDomainPermissionToml;
use akode_config::permissions_toml::NetworkDomainPermissionsToml;
use akode_config::permissions_toml::NetworkToml;
use akode_config::permissions_toml::NetworkUnixSocketPermissionToml;
use akode_config::permissions_toml::NetworkUnixSocketPermissionsToml;
use akode_config::permissions_toml::PermissionProfileToml;
use akode_config::permissions_toml::PermissionsToml;
use akode_config::permissions_toml::WorkspaceRootsToml;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_utils_path_uri::PathConvention;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use tempfile::TempDir;
#[test]
fn active_arg0_helper_dir_selects_only_the_first_session_alias_directory() -> anyhow::Result<()> {
let home = TempDir::new()?;
let platform_root = home
.path()
.join("tmp")
.join(format!("arg0-{}", std::env::consts::OS));
let legacy_root = home.path().join("tmp/arg0");
let foreign_os = if cfg!(windows) { "linux" } else { "windows" };
let foreign_alias = home
.path()
.join("tmp")
.join(format!("arg0-{foreign_os}"))
.join("codex-arg0-foreign");
for arg0_root in [&platform_root, &legacy_root] {
let active = arg0_root.join("codex-arg0-active");
let paths = std::env::join_paths([
home.path().join("bin"),
foreign_alias.clone(),
arg0_root.clone(),
arg0_root.join("unrelated"),
active.clone(),
arg0_root.join("codex-arg0-parent"),
])?;
assert_eq!(
active_arg0_helper_dir(home.path(), &paths),
Some(AbsolutePathBuf::from_absolute_path(active)?)
);
}
Ok(())
}
#[test]
fn windows_verbatim_path_prefix_does_not_count_as_glob_syntax() {
assert!(!contains_glob_chars_for_platform(
r"\\?\D:\c\x\worktrees\2508\swift-base",
/*is_windows*/ true,
));
assert!(contains_glob_chars_for_platform(
r"\\?\D:\c\x\worktrees\2508\**\*.env",
/*is_windows*/ true,
));
}
#[test]
fn network_toml_ignores_legacy_network_list_keys() {
let parsed = toml::from_str::<NetworkToml>(
r#"
allowed_domains = ["openai.com"]
"#,
)
.expect("legacy network list keys should be ignored");
assert_eq!(parsed, NetworkToml::default());
}
#[test]
fn network_permission_containers_project_allowed_and_denied_entries() {
let domains = NetworkDomainPermissionsToml {
entries: BTreeMap::from([
(
"*.openai.com".to_string(),
NetworkDomainPermissionToml::Allow,
),
(
"api.example.com".to_string(),
NetworkDomainPermissionToml::Allow,
),
(
"blocked.example.com".to_string(),
NetworkDomainPermissionToml::Deny,
),
]),
};
let unix_sockets = NetworkUnixSocketPermissionsToml {
entries: BTreeMap::from([
(
"/tmp/example.sock".to_string(),
NetworkUnixSocketPermissionToml::Allow,
),
(
"/tmp/ignored.sock".to_string(),
NetworkUnixSocketPermissionToml::Deny,
),
]),
};
assert_eq!(
domains.allowed_domains(),
Some(vec![
"*.openai.com".to_string(),
"api.example.com".to_string()
])
);
assert_eq!(
domains.denied_domains(),
Some(vec!["blocked.example.com".to_string()])
);
assert_eq!(
NetworkDomainPermissionsToml {
entries: BTreeMap::from([(
"api.example.com".to_string(),
NetworkDomainPermissionToml::Allow,
)]),
}
.denied_domains(),
None
);
assert_eq!(
unix_sockets.allow_unix_sockets(),
vec!["/tmp/example.sock".to_string()]
);
}
#[test]
fn network_toml_overlays_unix_socket_permissions_by_path() {
let mut config = NetworkProxyConfig::default();
NetworkToml {
unix_sockets: Some(NetworkUnixSocketPermissionsToml {
entries: BTreeMap::from([
(
"/tmp/base.sock".to_string(),
NetworkUnixSocketPermissionToml::Allow,
),
(
"/tmp/override.sock".to_string(),
NetworkUnixSocketPermissionToml::Allow,
),
]),
}),
..Default::default()
}
.apply_to_network_proxy_config(&mut config);
NetworkToml {
unix_sockets: Some(NetworkUnixSocketPermissionsToml {
entries: BTreeMap::from([
(
"/tmp/extra.sock".to_string(),
NetworkUnixSocketPermissionToml::Allow,
),
(
"/tmp/override.sock".to_string(),
NetworkUnixSocketPermissionToml::Deny,
),
]),
}),
..Default::default()
}
.apply_to_network_proxy_config(&mut config);
assert_eq!(
config.unix_sockets,
Some(akode_network_proxy::NetworkUnixSocketPermissions {
entries: BTreeMap::from([
(
"/tmp/base.sock".to_string(),
ProxyNetworkUnixSocketPermission::Allow,
),
(
"/tmp/extra.sock".to_string(),
ProxyNetworkUnixSocketPermission::Allow,
),
(
"/tmp/override.sock".to_string(),
ProxyNetworkUnixSocketPermission::Deny,
),
]),
})
);
}
#[test]
fn permissions_profiles_resolve_extends_parent_first_with_child_overrides() {
let permissions = toml::from_str::<PermissionsToml>(
r#"
[base]
description = "Base profile"
[base.filesystem]
glob_scan_max_depth = 1
"/tmp/base" = "read"
"/tmp/shared" = "read"
[base.filesystem.":project_roots"]
"**/*.env" = "deny"
docs = "read"
[base.network]
enabled = true
[base.network.domains]
"base.example.com" = "allow"
"SHARED.EXAMPLE.COM." = "deny"
[base.network.unix_sockets]
"/tmp/base.sock" = "allow"
"/tmp/blocked.sock" = "deny"
[child]
extends = "base"
[child.filesystem]
glob_scan_max_depth = 3
"/tmp/shared" = "write"
[child.filesystem.":project_roots"]
docs = "write"
src = "read"
[child.network]
enabled = false
allow_local_binding = true
[child.network.domains]
"child.example.com" = "allow"
"shared.example.com" = "allow"
[child.network.unix_sockets]
"/tmp/child.sock" = "allow"
"#,
)
.expect("permissions should deserialize");
let resolved = permissions
.resolve_profile("child", |_| None)
.expect("child profile should resolve");
let expected_profile = toml::from_str::<PermissionProfileToml>(
r#"
extends = "base"
[filesystem]
glob_scan_max_depth = 3
"/tmp/base" = "read"
"/tmp/shared" = "write"
[filesystem.":project_roots"]
"**/*.env" = "deny"
docs = "write"
src = "read"
[network]
enabled = false
allow_local_binding = true
[network.domains]
"base.example.com" = "allow"
"child.example.com" = "allow"
"shared.example.com" = "allow"
[network.unix_sockets]
"/tmp/base.sock" = "allow"
"/tmp/blocked.sock" = "deny"
"/tmp/child.sock" = "allow"
"#,
)
.expect("expected profile should deserialize");
assert_eq!(resolved, expected_profile);
}
#[test]
fn permissions_profiles_reject_undefined_extends_parent() {
let permissions = toml::from_str::<PermissionsToml>(
r#"
[child]
extends = "base"
"#,
)
.expect("permissions should deserialize");
let err = permissions
.resolve_profile("child", |_| None)
.expect_err("missing parent should be rejected");
assert_eq!(
err.to_string(),
"permissions profile `child` extends undefined profile `base`"
);
}
#[test]
fn permissions_profiles_reject_unsupported_builtin_extends_parent() {
let permissions = toml::from_str::<PermissionsToml>(
r#"
[child]
extends = ":danger-full-access"
"#,
)
.expect("permissions should deserialize");
let err = permissions
.resolve_profile("child", |_| None)
.expect_err("unsupported built-in parent should be rejected");
assert_eq!(
err.to_string(),
"permissions profile `child` cannot extend unsupported built-in profile `:danger-full-access`"
);
}
#[test]
fn permissions_profiles_reject_extends_cycles() {
let permissions = toml::from_str::<PermissionsToml>(
r#"
[alpha]
extends = "beta"
[beta]
extends = "alpha"
"#,
)
.expect("permissions should deserialize");
let err = permissions
.resolve_profile("alpha", |_| None)
.expect_err("cycle should be rejected");
assert_eq!(
err.to_string(),
"permissions profile inheritance cycle detected: alpha -> beta -> alpha"
);
}
#[test]
fn profile_network_proxy_config_keeps_proxy_disabled_for_bare_network_access() {
let config = network_proxy_config_from_profile_network(Some(&NetworkToml {
enabled: Some(true),
..Default::default()
}));
assert!(!config.enabled);
}
#[test]
fn profile_network_proxy_config_keeps_proxy_disabled_for_proxy_policy() {
let config = network_proxy_config_from_profile_network(Some(&NetworkToml {
enabled: Some(true),
proxy_url: Some("http://127.0.0.1:43128".to_string()),
enable_socks5: Some(false),
domains: Some(NetworkDomainPermissionsToml {
entries: BTreeMap::from([(
"openai.com".to_string(),
NetworkDomainPermissionToml::Allow,
)]),
}),
..Default::default()
}));
assert!(!config.enabled);
assert_eq!(config.proxy_url, "http://127.0.0.1:43128");
assert!(!config.enable_socks5);
assert_eq!(
config.domains,
Some(akode_network_proxy::NetworkDomainPermissions {
entries: vec![akode_network_proxy::NetworkDomainPermissionEntry {
pattern: "openai.com".to_string(),
permission: akode_network_proxy::NetworkDomainPermission::Allow,
}],
})
);
}
#[test]
fn compile_permission_profile_resolves_enabled_workspace_roots() -> std::io::Result<()> {
let cwd = TempDir::new()?;
let compiled = compile_permission_profile(
Some(&PermissionsToml {
entries: BTreeMap::from([(
"workspace".to_string(),
PermissionProfileToml {
description: None,
extends: None,
workspace_roots: Some(WorkspaceRootsToml {
entries: BTreeMap::from([
("backend".to_string(), true),
("disabled".to_string(), false),
]),
}),
filesystem: None,
network: None,
},
)]),
}),
"workspace",
&ConfigPathContext::new(
PathConvention::native(),
Some(PathUri::from_host_native_path(cwd.path())?),
/*user_home_dir*/ None,
),
/*workspace_write*/ None,
&mut Vec::new(),
)?;
assert_eq!(
compiled.workspace_roots,
vec![
PathUri::from_host_native_path(cwd.path())?
.join("backend")
.unwrap()
]
);
Ok(())
}
#[test]
fn legacy_project_roots_restrictions_do_not_fail_open() -> std::io::Result<()> {
let permissions = toml::from_str::<PermissionsToml>(
r#"
[read_deny.filesystem]
":root" = "read"
":project_roots" = "none"
[write_deny.filesystem]
":root" = "write"
":project_roots" = "none"
[write_read.filesystem]
":root" = "write"
[write_read.filesystem.":project_roots"]
docs = "read"
"#,
)
.expect("legacy project roots profiles should deserialize");
let cwd = TempDir::new()?;
let docs = cwd.path().join("docs");
let mut startup_warnings = Vec::new();
let context = ConfigPathContext::new(
PathConvention::native(),
Some(PathUri::from_host_native_path(cwd.path())?),
/*user_home_dir*/ None,
);
let read_deny_policy = compile_permission_profile(
Some(&permissions),
"read_deny",
&context,
/*workspace_write*/ None,
&mut startup_warnings,
)?
.permission_profile
.file_system_sandbox_policy();
assert_eq!(
read_deny_policy.resolve_access_for_local_path_with_cwd(cwd.path(), cwd.path()),
FileSystemAccessMode::Deny
);
let write_deny_policy = compile_permission_profile(
Some(&permissions),
"write_deny",
&context,
/*workspace_write*/ None,
&mut startup_warnings,
)?
.permission_profile
.file_system_sandbox_policy();
assert!(!write_deny_policy.has_full_disk_write_access());
assert_eq!(
write_deny_policy.resolve_access_for_local_path_with_cwd(cwd.path(), cwd.path()),
FileSystemAccessMode::Deny
);
let write_read_policy = compile_permission_profile(
Some(&permissions),
"write_read",
&context,
/*workspace_write*/ None,
&mut startup_warnings,
)?
.permission_profile
.file_system_sandbox_policy();
assert!(!write_read_policy.has_full_disk_write_access());
assert_eq!(
write_read_policy.resolve_access_for_local_path_with_cwd(&docs, cwd.path()),
FileSystemAccessMode::Read
);
Ok(())
}
#[test]
fn read_write_glob_warnings_skip_supported_deny_read_globs_and_trailing_subpaths() {
let filesystem = FilesystemPermissionsToml {
glob_scan_max_depth: None,
entries: BTreeMap::from([
(
"/tmp/**/*.log".to_string(),
FilesystemPermissionToml::Access(FileSystemAccessMode::Read),
),
(
"/tmp/cache/**".to_string(),
FilesystemPermissionToml::Access(FileSystemAccessMode::Write),
),
(
":workspace_roots".to_string(),
FilesystemPermissionToml::Scoped(BTreeMap::from([
("**/*.env".to_string(), FileSystemAccessMode::Deny),
("docs/**".to_string(), FileSystemAccessMode::Read),
("src/**/*.rs".to_string(), FileSystemAccessMode::Write),
])),
),
]),
};
assert_eq!(
unsupported_read_write_glob_paths(
&filesystem,
&ConfigPathContext::new(
PathConvention::native(),
/*base_dir*/ None,
/*user_home_dir*/ None,
)
)
.unwrap(),
vec![
"/tmp/**/*.log".to_string(),
":workspace_roots/src/**/*.rs".to_string()
],
"`deny` glob patterns are supported as deny-read rules; only `read`/`write` globs should warn"
);
}
#[test]
fn unreadable_globstar_warning_is_suppressed_when_scan_depth_is_configured() {
let filesystem = FilesystemPermissionsToml {
glob_scan_max_depth: None,
entries: BTreeMap::from([(
":workspace_roots".to_string(),
FilesystemPermissionToml::Scoped(BTreeMap::from([
("**/*.env".to_string(), FileSystemAccessMode::Deny),
("*.pem".to_string(), FileSystemAccessMode::Deny),
])),
)]),
};
assert_eq!(
unbounded_unreadable_globstar_paths(&filesystem),
vec![":workspace_roots/**/*.env".to_string()]
);
let configured_filesystem = FilesystemPermissionsToml {
glob_scan_max_depth: Some(2),
..filesystem
};
assert_eq!(
unbounded_unreadable_globstar_paths(&configured_filesystem),
Vec::<String>::new()
);
}
#[test]
fn glob_scan_max_depth_must_be_positive() {
let err = validate_glob_scan_max_depth(Some(0))
.expect_err("zero depth would silently skip deny-read glob expansion");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
assert_eq!(err.to_string(), "glob_scan_max_depth must be at least 1");
assert_eq!(
validate_glob_scan_max_depth(Some(2)).expect("depth should be valid"),
Some(2)
);
}
#[test]
fn read_write_trailing_glob_suffix_compiles_as_subpath() -> std::io::Result<()> {
let mut startup_warnings = Vec::new();
let compiled = compile_permission_profile(
Some(&PermissionsToml {
entries: BTreeMap::from([(
"workspace".to_string(),
PermissionProfileToml {
description: None,
extends: None,
workspace_roots: None,
filesystem: Some(FilesystemPermissionsToml {
glob_scan_max_depth: None,
entries: BTreeMap::from([(
":workspace_roots".to_string(),
FilesystemPermissionToml::Scoped(BTreeMap::from([(
"docs/**".to_string(),
FileSystemAccessMode::Read,
)])),
)]),
}),
network: None,
},
)]),
}),
"workspace",
&ConfigPathContext::new(
PathConvention::native(),
/*base_dir*/ None,
/*user_home_dir*/ None,
),
/*workspace_write*/ None,
&mut startup_warnings,
)?;
assert_eq!(
compiled.permission_profile.file_system_sandbox_policy(),
FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(Some("docs".into())),
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]),
"trailing /** should compile as a subtree path instead of a glob pattern"
);
Ok(())
}
#[test]
fn read_write_glob_patterns_still_reject_non_subpath_globs() {
let err = compile_read_write_glob_path(
"src/**/*.rs",
FileSystemAccessMode::Read,
&ConfigPathContext::new(
PathConvention::native(),
/*base_dir*/ None,
/*user_home_dir*/ None,
),
)
.expect_err("non-subpath read/write glob should be rejected");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
assert!(
err.to_string()
.contains("filesystem glob path `src/**/*.rs` only supports `deny` access"),
"{err}"
);
}

View File

@@ -0,0 +1,183 @@
use akode_config::ConfigRequirements;
use akode_config::RequirementSource;
use akode_config::Sourced;
use akode_config::config_toml::ConfigToml;
use akode_config::types::ApprovalsReviewer;
use akode_config::types::FeedbackConfigToml;
use akode_features::FeatureToml;
use akode_login::default_client::RESIDENCY_HEADER_NAME;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::Path;
/// Applies managed requirements to regular config before final config construction.
///
/// Managed values replace their configured counterparts, and conflicts produce
/// source-aware startup warnings.
pub(super) fn apply_to_config(
config: &mut ConfigToml,
requirements: &ConfigRequirements,
startup_warnings: &mut Vec<String>,
) {
macro_rules! apply_exact {
($field:ident) => {
apply_exact_requirement(
stringify!($field),
&mut config.$field,
requirements.$field.as_ref(),
startup_warnings,
);
};
}
apply_exact!(cli_auth_credentials_store);
apply_exact!(chatgpt_base_url);
apply_exact!(sqlite_home);
apply_exact!(log_dir);
apply_exact!(model_catalog_json);
apply_exact!(model_provider);
if let Some(providers) = &requirements.model_providers {
config.model_providers.extend(providers.value.clone());
}
apply_exact!(check_for_update_on_startup);
apply_exact!(allow_login_shell);
if requirements
.approvals_reviewer
.can_set(&ApprovalsReviewer::User)
.is_err()
{
config.features.get_or_insert_default().guardianv2 = Some(FeatureToml::Enabled(false));
}
apply_feedback_requirement(
&mut config.feedback,
requirements.feedback.as_ref(),
startup_warnings,
);
if requirements.enforce_residency.value().is_some() {
for (provider_name, provider) in &config.model_providers {
let has_residency_header = provider
.http_headers
.iter()
.flat_map(HashMap::keys)
.chain(provider.env_http_headers.iter().flat_map(HashMap::keys))
.any(|name| name.eq_ignore_ascii_case(RESIDENCY_HEADER_NAME));
if has_residency_header {
let warning = format!(
"Ignoring `{RESIDENCY_HEADER_NAME}` in `model_providers.{provider_name}` because managed residency is required."
);
tracing::warn!(provider = provider_name, "{warning}");
startup_warnings.push(warning);
}
}
}
if let Some(Sourced { value, source }) = requirements.otel.as_deref() {
let conflict =
akode_config::apply_otel_requirements(config.otel.get_or_insert_default(), value);
push_structured_requirement_override_warning("otel", conflict, source, startup_warnings);
}
}
fn apply_exact_requirement<T>(
field_name: &'static str,
configured_value: &mut Option<T>,
requirement: Option<&Sourced<T>>,
startup_warnings: &mut Vec<String>,
) where
T: Clone + PartialEq + std::fmt::Debug,
{
let Some(Sourced { value, source }) = requirement else {
return;
};
if configured_value
.as_ref()
.is_some_and(|configured| configured != value)
{
tracing::warn!(
?source,
?value,
"configured value is overridden by an exact requirement for {field_name}"
);
startup_warnings.push(format!(
"Configured value for `{field_name}` is overridden by the required value {value:?} from {source}."
));
}
*configured_value = Some(value.clone());
}
fn replace_required_leaf<T: Clone + PartialEq>(
configured: &mut Option<T>,
required: &Option<T>,
) -> bool {
let Some(required) = required else {
return false;
};
let conflict = configured
.as_ref()
.is_some_and(|configured| configured != required);
*configured = Some(required.clone());
conflict
}
fn apply_feedback_requirement(
configured: &mut Option<FeedbackConfigToml>,
requirement: Option<&Sourced<FeedbackConfigToml>>,
startup_warnings: &mut Vec<String>,
) {
let Some(Sourced { value, source }) = requirement else {
return;
};
let FeedbackConfigToml { enabled } = value;
let configured = configured.get_or_insert_default();
let conflict = replace_required_leaf(&mut configured.enabled, enabled);
push_structured_requirement_override_warning("feedback", conflict, source, startup_warnings);
}
pub(super) fn push_sqlite_home_env_override_warning(
configured_sqlite_home: Option<&AbsolutePathBuf>,
sqlite_home_env: Option<&Path>,
requirement: Option<&Sourced<AbsolutePathBuf>>,
startup_warnings: &mut Vec<String>,
) {
if configured_sqlite_home.is_some() {
return;
}
let Some(sqlite_home_env) = sqlite_home_env else {
return;
};
let Some(Sourced { value, source }) = requirement else {
return;
};
if sqlite_home_env == value.as_path() {
return;
}
tracing::warn!(
?source,
?value,
"`AKODE_SQLITE_HOME` is overridden by an exact requirement for sqlite_home"
);
startup_warnings.push(format!(
"Environment value for `$AKODE_SQLITE_HOME` is overridden by the required `sqlite_home` value {value:?} from {source}."
));
}
/// Emits one source-aware warning when a structured requirement replaces one
/// or more configured values.
fn push_structured_requirement_override_warning(
field_name: &str,
conflict: bool,
source: &RequirementSource,
startup_warnings: &mut Vec<String>,
) {
if !conflict {
return;
}
tracing::warn!(
?source,
"configured values are overridden by requirements for {field_name}"
);
startup_warnings.push(format!(
"Configured values under `{field_name}` are overridden by requirements from {source}."
));
}

View File

@@ -0,0 +1,93 @@
use akode_config::Constrained;
use akode_config::ConstraintResult;
use akode_protocol::models::ActivePermissionProfile;
use akode_protocol::models::PermissionProfile;
use akode_protocol::models::PermissionProfileSnapshot;
use akode_protocol::models::ProfileWorkspaceRoot;
use akode_utils_path_uri::PathUri;
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PermissionProfileState {
permission_profile: Constrained<PermissionProfileSnapshot>,
}
impl PermissionProfileState {
pub(crate) fn from_constrained_legacy(
constrained_permission_profile: Constrained<PermissionProfile>,
) -> ConstraintResult<Self> {
let snapshot =
PermissionProfileSnapshot::legacy(constrained_permission_profile.get().clone());
Self::from_constrained_snapshot(constrained_permission_profile, snapshot)
}
pub(crate) fn from_constrained_active_profile(
constrained_permission_profile: Constrained<PermissionProfile>,
active_permission_profile: Option<ActivePermissionProfile>,
profile_workspace_roots: Vec<PathUri>,
) -> ConstraintResult<Self> {
let permission_profile = constrained_permission_profile.get().clone();
let snapshot = match active_permission_profile {
Some(active_permission_profile) => {
PermissionProfileSnapshot::active_with_profile_workspace_roots(
permission_profile,
active_permission_profile,
profile_workspace_roots
.into_iter()
.map(ProfileWorkspaceRoot::from)
.collect(),
)
}
None => PermissionProfileSnapshot::legacy(permission_profile),
};
Self::from_constrained_snapshot(constrained_permission_profile, snapshot)
}
pub(crate) fn from_constrained_snapshot(
constrained_permission_profile: Constrained<PermissionProfile>,
permission_profile: PermissionProfileSnapshot,
) -> ConstraintResult<Self> {
let permission_profile = Constrained::new(permission_profile, move |candidate| {
constrained_permission_profile.can_set(candidate.permission_profile())
})?;
Ok(Self { permission_profile })
}
pub(crate) fn permission_profile(&self) -> &PermissionProfile {
self.permission_profile.get().permission_profile()
}
pub(crate) fn snapshot(&self) -> PermissionProfileSnapshot {
self.permission_profile.get().clone()
}
pub(crate) fn active_permission_profile(&self) -> Option<ActivePermissionProfile> {
self.permission_profile.get().active_permission_profile()
}
pub(crate) fn profile_workspace_roots(&self) -> &[ProfileWorkspaceRoot] {
self.permission_profile.get().profile_workspace_roots()
}
pub(crate) fn can_set_legacy_permission_profile(
&self,
permission_profile: &PermissionProfile,
) -> ConstraintResult<()> {
let candidate = PermissionProfileSnapshot::legacy(permission_profile.clone());
self.permission_profile.can_set(&candidate)
}
pub(crate) fn set_legacy_permission_profile(
&mut self,
permission_profile: PermissionProfile,
) -> ConstraintResult<()> {
self.permission_profile
.set(PermissionProfileSnapshot::legacy(permission_profile))
}
pub(crate) fn set_permission_profile_snapshot(
&mut self,
snapshot: PermissionProfileSnapshot,
) -> ConstraintResult<()> {
self.permission_profile.set(snapshot)
}
}

View File

@@ -0,0 +1,101 @@
//! Verifies managed runtime-auth defaults and rejection of conflicting user overrides.
#![cfg(test)]
use super::*;
use akode_config::RequirementSource;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[tokio::test]
async fn managed_runtime_mode_pins_defaults_and_rejects_overrides() -> anyhow::Result<()> {
for (name, mode) in [
("dual_header", RuntimeAuthMode::DualHeader),
("assertion_only", RuntimeAuthMode::AssertionOnly),
] {
let requirement: akode_config::ConfigRequirementsToml = toml::from_str(&format!(
"[features.runtime_agent_instances]\nenabled = true\nmode = '{name}'"
))?;
for local in ["", "[features]\nruntime_agent_instances = true"] {
let mut sourced = akode_config::ConfigRequirementsWithSources::default();
sourced.merge_unset_fields(RequirementSource::Unknown, requirement.clone());
let stack = akode_config::ConfigLayerStack::new(
Vec::new(),
sourced.try_into()?,
requirement.clone(),
)?;
let home = tempdir()?;
let config = Config::load_config_with_layer_stack(
LOCAL_FS.as_ref(),
toml::from_str(local)?,
ConfigOverrides::default(),
AbsolutePathBuf::try_from(home.path())?,
stack,
)
.await?;
assert_eq!(config.runtime_auth_mode, mode);
assert!(config.features.enabled(Feature::RuntimeAgentInstances));
}
let different = if name == "dual_header" {
"assertion_only"
} else {
"dual_header"
};
let configured = toml::from_str(&format!(
"[features.runtime_agent_instances]\nmode = '{different}'"
))?;
let requirements = Sourced::new(
requirement.feature_requirements.clone().unwrap(),
RequirementSource::Unknown,
);
assert!(
managed_features::resolve_runtime_auth_mode(&configured, Some(&requirements)).is_err()
);
assert!(
managed_features::validate_explicit_feature_settings_in_config_toml(
&configured,
Some(&requirements)
)
.is_err()
);
}
Ok(())
}
#[test]
fn unmanaged_runtime_modes_and_legacy_boolean_requirements_work() -> anyhow::Result<()> {
for (text, expected) in [
("", RuntimeAuthMode::DualHeader),
(
"[features]\nruntime_agent_instances = true",
RuntimeAuthMode::DualHeader,
),
(
"[features.runtime_agent_instances]\nmode = 'assertion_only'",
RuntimeAuthMode::AssertionOnly,
),
] {
assert_eq!(
managed_features::resolve_runtime_auth_mode(
&toml::from_str(text)?,
/*requirements*/ None
)?,
expected
);
}
let requirement: akode_config::ConfigRequirementsToml =
toml::from_str("[features]\nruntime_agent_instances = false")?;
let requirement = requirement.feature_requirements.unwrap();
assert_eq!(
requirement.entries.get("runtime_agent_instances"),
Some(&false)
);
assert_eq!(requirement.runtime_auth_mode, None);
assert!(
toml::from_str::<akode_config::ConfigRequirementsToml>(
"[features.runtime_agent_instances]\nmode = 'unknown'"
)
.is_err()
);
Ok(())
}

View File

@@ -0,0 +1,140 @@
//! Resolves refreshable MCP inputs without rebuilding unrelated session configuration.
//! Validate the retained backend after applying the refreshable requirements.
use crate::config::Config;
use crate::config::ManagedFeatures;
use crate::config::constrain_mcp_servers;
use crate::config::resolve_tool_suggest_config_from_layer_stack;
use akode_features::Feature;
use akode_features::FeatureConfigSource;
use akode_features::FeatureOverrides;
use akode_features::Features;
use akode_features::FeaturesToml;
use serde::Deserialize;
use std::collections::HashMap;
#[cfg(test)]
#[path = "runtime_refresh_tests.rs"]
mod tests;
#[derive(Clone, Copy)]
pub(crate) enum RuntimeConfigRefresh {
User,
Mcp,
UserFiles,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct McpRefreshToml {
features: Option<FeaturesToml>,
plugins: akode_config::types::PluginsConfigToml,
}
impl Config {
pub(crate) fn resolve_runtime_refresh(
&self,
incoming: &Self,
scope: RuntimeConfigRefresh,
) -> std::io::Result<Self> {
let mut layers = match scope {
RuntimeConfigRefresh::User | RuntimeConfigRefresh::UserFiles => self
.config_layer_stack
.with_user_layer_from(&incoming.config_layer_stack),
RuntimeConfigRefresh::Mcp => Self::layer_stack_preserving_session(
&self.config_layer_stack,
&incoming.config_layer_stack,
)?
.with_user_layer_from(&self.config_layer_stack),
};
if matches!(scope, RuntimeConfigRefresh::Mcp) {
let plugins = incoming
.config_layer_stack
.all_layers_low_to_high()
.filter(|layer| {
layer.name == akode_config::ConfigLayerSource::SessionFlags
&& !layer.is_disabled()
})
.filter_map(|layer| layer.config.get("plugins").cloned())
.reduce(|mut plugins, overlay| {
akode_config::merge_toml_values(&mut plugins, &overlay);
plugins
});
if let Some(plugins) = plugins {
layers = layers.with_session_plugins(plugins)?;
}
}
// User refreshes retain the session's managed configuration.
layers.ensure_config_server_applied()?;
let cfg: McpRefreshToml = layers
.effective_config()
.try_into()
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
let mut configured_features = Features::from_sources(
FeatureConfigSource {
features: cfg.features.as_ref(),
..Default::default()
},
FeatureConfigSource::default(),
FeatureOverrides::default(),
);
// These operational controls accept host defaults beneath explicit layer values.
// Enterprise opt-in always comes from trusted layers instead.
for feature in [
Feature::McpConnectionSharing,
Feature::McpLazyStdioStartup,
Feature::SecretAuthStorage,
Feature::McpOAuthRefreshCoordination,
] {
if matches!(scope, RuntimeConfigRefresh::UserFiles) {
let explicitly_configured = cfg.features.as_ref().is_some_and(|features| {
features
.entries()
.keys()
.any(|key| akode_features::feature_for_key(key) == Some(feature))
});
if !explicitly_configured
&& let Some(enabled) = self.runtime_feature_defaults.get(&feature)
{
configured_features.set_enabled(feature, *enabled);
}
} else {
// A publication wait may have allowed a newer host/user override.
configured_features.set_enabled(feature, incoming.features.enabled(feature));
}
}
let features = ManagedFeatures::from_configured(
configured_features,
layers.requirements().feature_requirements.clone(),
)?;
let servers: HashMap<_, _> = incoming
.mcp_servers
.get()
.iter()
.map(|(name, server)| (name.clone(), server.clone()))
.collect();
let mut config = self.clone();
if !matches!(scope, RuntimeConfigRefresh::UserFiles) {
config.runtime_feature_defaults = incoming.runtime_feature_defaults.clone();
config.mcp_optional_startup_grace = incoming.mcp_optional_startup_grace;
config.mcp_oauth_credentials_store_mode = incoming.mcp_oauth_credentials_store_mode;
}
config
.features
.refresh_mcp_features(&features)
.map_err(std::io::Error::other)?;
config.mcp_servers =
constrain_mcp_servers(servers, layers.requirements().mcp_servers.as_ref())
.map_err(std::io::Error::other)?;
if matches!(scope, RuntimeConfigRefresh::User) {
config.active_project = incoming.active_project.clone();
}
if !matches!(scope, RuntimeConfigRefresh::Mcp) {
config.tool_suggest = resolve_tool_suggest_config_from_layer_stack(&layers);
}
config.config_layer_stack = layers;
config.plugins = cfg.plugins;
config.validate_windows_mxc_requirement()?;
Ok(config)
}
}

View File

@@ -0,0 +1,186 @@
//! Ordinary refresh resolution without Session construction.
use super::*;
use crate::config::ConfigBuilder;
use akode_config::CONFIG_TOML_FILE;
use akode_config::ConfigLayerSource;
use akode_config::test_support::ManagedConfigFixture;
use pretty_assertions::assert_eq;
async fn base_config() -> (tempfile::TempDir, Config) {
let home = tempfile::tempdir().unwrap();
let config = ConfigBuilder::without_managed_config_for_tests()
.codex_home(home.path().to_path_buf())
.fallback_cwd(Some(home.path().to_path_buf()))
.build()
.await
.unwrap();
(home, config)
}
async fn layered_config(
base: &Config,
user: &str,
managed: &str,
requirements: &str,
session: &str,
) -> Config {
std::fs::write(base.codex_home.join(CONFIG_TOML_FILE), user).unwrap();
let overrides: toml::Table = toml::from_str(session).unwrap();
ConfigBuilder::without_managed_config_for_tests()
.codex_home(base.codex_home.to_path_buf())
.fallback_cwd(Some(base.cwd.to_path_buf()))
.cli_overrides(overrides.into_iter().collect())
.loader_overrides(
ManagedConfigFixture::config(managed)
.with_requirements(format!("[features]\n{requirements}"))
.loader_overrides_for_tests(&base.codex_home)
.expect("write managed config fixture"),
)
.build()
.await
.unwrap()
}
#[tokio::test]
async fn plugin_refresh_resolves_only_the_final_layer_combination() {
let (_home, base) = base_config().await;
let snapshot = |user: &str, project: &str| {
let mut config = base.clone();
config.config_layer_stack = akode_config::ConfigLayerStack::new(
vec![
akode_config::ConfigLayerEntry::new(
ConfigLayerSource::User {
file: base.codex_home.join(CONFIG_TOML_FILE),
profile: None,
},
toml::from_str(user).unwrap(),
),
akode_config::ConfigLayerEntry::new(
ConfigLayerSource::Project {
dot_codex_folder: base.codex_home.join(".akode"),
},
toml::from_str(project).unwrap(),
),
],
Default::default(),
Default::default(),
)
.unwrap();
config.plugins = config
.config_layer_stack
.effective_config()
.try_into::<akode_config::config_toml::ConfigToml>()
.unwrap()
.plugins;
config
};
let current = snapshot("[plugins._default]\nenabled = false", "");
let incoming = snapshot(
"[plugins._default]\nenabled = false\n[plugins.\"example@marketplace\"]\nenabled = 'invalid'",
"[plugins.\"example@marketplace\"]\nenabled = false",
);
for (current, incoming, scope) in [
(&current, &incoming, RuntimeConfigRefresh::User),
(&current, &incoming, RuntimeConfigRefresh::UserFiles),
(&incoming, &current, RuntimeConfigRefresh::Mcp),
] {
assert!(current.resolve_runtime_refresh(incoming, scope).is_err());
assert!(!current.plugins.allows_plugin("example@marketplace"));
}
let corrected = snapshot("[plugins._default]\nenabled = true", "");
let refreshed = current
.resolve_runtime_refresh(&corrected, RuntimeConfigRefresh::User)
.unwrap();
assert_eq!(refreshed.plugins, corrected.plugins);
assert!(refreshed.plugins.allows_plugin("example@marketplace"));
}
#[tokio::test]
async fn ordinary_transport_transitions_use_the_resolved_incoming_map() {
let (_home, base) = base_config().await;
let command = "[mcp_servers.ordinary]\ncommand = 'ordinary-server'";
let url = "[mcp_servers.ordinary]\nurl = 'https://ordinary.example/mcp'";
for scope in [RuntimeConfigRefresh::User, RuntimeConfigRefresh::Mcp] {
let (current, incoming) = match scope {
RuntimeConfigRefresh::User => (
layered_config(&base, "", "", "", url).await,
layered_config(&base, command, "", "", "").await,
),
RuntimeConfigRefresh::Mcp => (
layered_config(&base, command, "", "", "").await,
layered_config(&base, "", url, "", "").await,
),
RuntimeConfigRefresh::UserFiles => unreachable!(),
};
let refreshed = current.resolve_runtime_refresh(&incoming, scope).unwrap();
assert_eq!(refreshed.mcp_servers.get(), incoming.mcp_servers.get());
}
}
#[tokio::test]
async fn mcp_refresh_preserves_apps_until_new_session() {
let (_home, base) = base_config().await;
let current = layered_config(&base, "[features]\napps = true", "", "", "").await;
let next = layered_config(&base, "[features]\napps = true", "", "apps = false", "").await;
let refreshed = current
.resolve_runtime_refresh(&next, RuntimeConfigRefresh::Mcp)
.unwrap();
assert!(refreshed.features.enabled(Feature::Apps));
let reloaded = refreshed
.resolve_runtime_refresh(&next, RuntimeConfigRefresh::User)
.unwrap();
assert!(reloaded.features.enabled(Feature::Apps));
assert!(!next.features.enabled(Feature::Apps));
}
/// Explicit plugin updates replace only their session override, retaining other thread settings.
#[tokio::test]
async fn plugin_override_refresh_preserves_session_and_restores_inheritance() {
let (_home, base) = base_config().await;
let mut current = layered_config(
&base,
"[plugins.browser]\nenabled = false",
"",
"",
"[apps.calendar]\nenabled = false\n[plugins.browser]\nenabled = true",
)
.await;
let incoming = layered_config(
&base,
"[plugins.browser]\nenabled = false",
"",
"",
"[apps.calendar]\nenabled = true",
)
.await;
let original_apps = current.config_layer_stack.effective_config()["apps"].clone();
let layer_count = current.config_layer_stack.all_layers_low_to_high().count();
let unchanged = current
.resolve_runtime_refresh(&incoming, RuntimeConfigRefresh::Mcp)
.unwrap();
assert_eq!(unchanged.plugins, current.plugins);
for (override_text, expected) in [
("[browser]\nenabled = false", false),
("[browser]\nenabled = true", true),
("", false),
] {
let mut incoming = incoming.clone();
incoming.config_layer_stack = incoming
.config_layer_stack
.with_session_plugins(toml::from_str(override_text).unwrap())
.unwrap();
current = current
.resolve_runtime_refresh(&incoming, RuntimeConfigRefresh::Mcp)
.unwrap();
assert_eq!(current.plugins.plugins["browser"].enabled, Some(expected));
assert_eq!(
current.config_layer_stack.effective_config()["apps"],
original_apps
);
assert_eq!(
current.config_layer_stack.all_layers_low_to_high().count(),
layer_count
);
}
}

View File

@@ -0,0 +1,11 @@
# Config JSON Schema
We generate a JSON Schema for `~/.akode/config.toml` from the `ConfigToml` type
and commit it at `akode-rs/core/config.schema.json` for editor integration.
When you change any fields included in `ConfigToml` (or nested config types),
regenerate the schema:
```
just write-config-schema
```

View File

@@ -0,0 +1,7 @@
use akode_config::schema::canonicalize;
use akode_config::schema::config_schema_json;
use akode_config::schema::write_config_schema;
#[cfg(test)]
#[path = "schema_tests.rs"]
mod tests;

View File

@@ -0,0 +1,103 @@
use super::canonicalize;
use super::config_schema_json;
use super::write_config_schema;
use pretty_assertions::assert_eq;
use similar::TextDiff;
use tempfile::TempDir;
fn trim_single_trailing_newline(contents: &str) -> &str {
contents.strip_suffix('\n').unwrap_or(contents)
}
#[test]
fn config_schema_matches_fixture() {
let fixture_path = akode_utils_cargo_bin::find_resource!("config.schema.json")
.expect("resolve config schema fixture path");
let fixture = std::fs::read_to_string(fixture_path).expect("read config schema fixture");
let fixture_value: serde_json::Value =
serde_json::from_str(&fixture).expect("parse config schema fixture");
let schema_json = config_schema_json().expect("serialize config schema");
let schema_value: serde_json::Value =
serde_json::from_slice(&schema_json).expect("decode schema json");
let fixture_value = canonicalize(&fixture_value);
let schema_value = canonicalize(&schema_value);
if fixture_value != schema_value {
let expected =
serde_json::to_string_pretty(&fixture_value).expect("serialize fixture json");
let actual = serde_json::to_string_pretty(&schema_value).expect("serialize schema json");
let diff = TextDiff::from_lines(&expected, &actual)
.unified_diff()
.header("fixture", "generated")
.to_string();
panic!(
"Current schema for `config.toml` doesn't match the fixture. \
Run `just write-config-schema` to overwrite with your changes.\n\n{diff}"
);
}
// Make sure the version in the repo matches exactly: https://github.com/openai/codex/pull/10977.
let tmp = TempDir::new().expect("create temp dir");
let tmp_path = tmp.path().join("config.schema.json");
write_config_schema(&tmp_path).expect("write config schema to temp path");
let tmp_contents =
std::fs::read_to_string(&tmp_path).expect("read back config schema from temp path");
#[cfg(windows)]
let fixture = fixture.replace("\r\n", "\n");
#[cfg(windows)]
let tmp_contents = tmp_contents.replace("\r\n", "\n");
assert_eq!(
trim_single_trailing_newline(&fixture),
trim_single_trailing_newline(&tmp_contents),
"fixture should match exactly with generated schema"
);
}
#[test]
fn config_schema_hides_unsupported_inline_mcp_bearer_token() {
let schema_json = config_schema_json().expect("serialize config schema");
let schema_value: serde_json::Value =
serde_json::from_slice(&schema_json).expect("decode schema json");
let properties = schema_value
.pointer("/definitions/RawMcpServerConfig/properties")
.expect("RawMcpServerConfig properties should exist")
.as_object()
.expect("RawMcpServerConfig properties should be an object");
assert_eq!(
(
properties.contains_key("bearer_token"),
properties.contains_key("bearer_token_env_var"),
),
(false, true),
);
}
#[test]
fn shell_environment_policy_schema_rejects_mixed_filter_representations() {
let schema_json = config_schema_json().expect("serialize config schema");
let schema_value: serde_json::Value =
serde_json::from_slice(&schema_json).expect("decode schema json");
let constraints = schema_value
.pointer("/definitions/ShellEnvironmentPolicyToml/allOf")
.and_then(serde_json::Value::as_array)
.expect("shell environment policy constraints should be an array");
let required_pairs = constraints
.iter()
.map(|constraint| {
constraint
.pointer("/not/required")
.expect("constraint should prohibit a required-field pair")
.clone()
})
.collect::<Vec<_>>();
assert_eq!(
required_pairs,
vec![
serde_json::json!(["exclude", "filters"]),
serde_json::json!(["filters", "include_only"]),
]
);
}

View File

@@ -0,0 +1,31 @@
//! Keeps configured token-budget preferences separate from session startup activation.
//! Fresh child sessions restore this snapshot before applying their starting model's defaults;
//! history forks retain their parent's effective activation and the original snapshot.
use super::Config;
use super::ConstraintResult;
use super::TokenBudgetConfig;
use akode_features::Feature;
/// Token-budget preferences before a session applies experimental or model-owned activation.
#[derive(Debug, Clone, PartialEq)]
pub struct TokenBudgetStartupConfig {
enabled: bool,
token_budget: Option<TokenBudgetConfig>,
}
impl Config {
/// Captures configured preferences, removing any inherited startup activation first.
pub(crate) fn prepare_token_budget_for_startup(&mut self) -> ConstraintResult<()> {
if let Some(snapshot) = self.token_budget_startup_config.as_ref() {
self.features
.set_enabled(Feature::TokenBudget, snapshot.enabled)?;
self.token_budget = snapshot.token_budget.clone();
}
self.token_budget_startup_config = Some(TokenBudgetStartupConfig {
enabled: self.features.enabled(Feature::TokenBudget),
token_budget: self.token_budget.clone(),
});
Ok(())
}
}

View File

@@ -0,0 +1,191 @@
//! Configured Windows sandbox modes and the effective local backend.
//! Keep the configured backend for remote inheritance; apply the local rollout
//! using the preference resolved during config loading.
//! Validate MXC requirements only after bootstrap has loaded the complete config.
use super::Config;
use super::EffectivePermissionSelection;
use super::apply_requirement_constrained_value;
use super::network_proxy_toml_config;
use super::permissions::network_proxy_config_for_profile_selection;
use super::profile_allows_configured_network_proxy;
use akode_config::ConstrainedWithSource;
use akode_config::NetworkConstraints;
use akode_config::Sourced;
use akode_config::config_toml::ConfigToml;
use akode_config::types::WindowsSandboxModeToml;
use akode_features::FeaturesToml;
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::models::PermissionProfile;
use akode_sandboxing::SandboxType;
impl Config {
/// Reject a non-MXC selection without changing the final configuration.
/// Call after configuration loads and outside config-recovery fallbacks.
pub fn validate_windows_mxc_requirement(&self) -> std::io::Result<()> {
self.validate_windows_mxc_requirement_from(self)
}
/// Check this execution config against separately loaded managed requirements.
pub fn validate_windows_mxc_requirement_from(
&self,
policy_config: &Self,
) -> std::io::Result<()> {
if cfg!(windows)
&& policy_config
.config_layer_stack
.requirements_toml()
.windows
.as_ref()
.and_then(|windows| windows.require_mxc)
== Some(true)
&& self.effective_local_windows_sandbox_type() != SandboxType::WindowsMxc
{
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"windows.require_mxc = true requires MXC to be selected on this Windows host",
));
}
Ok(())
}
/// Configured backend, without the local rollout preference. Remote executors inherit this.
pub fn windows_sandbox_type_from_config(&self) -> SandboxType {
self.permissions.windows_sandbox_type
}
/// Effective local backend, using eligibility and availability resolved at config load.
pub fn effective_local_windows_sandbox_type(&self) -> SandboxType {
resolve_windows_sandbox_type(self.windows_sandbox_type_from_config(), self.prefer_mxc)
}
}
pub(super) fn resolve_windows_sandbox_type(
configured: SandboxType,
prefer_mxc: bool,
) -> SandboxType {
if prefer_mxc {
SandboxType::WindowsMxc
} else {
configured
}
}
#[derive(Debug, PartialEq)]
pub struct PreparedWindowsSandboxConfig {
/// Explicit or requirement-constrained mode; excludes feature-only fallback.
pub mode: Option<WindowsSandboxModeToml>,
/// Selected implementation, kept separate from the legacy setup level.
pub sandbox_type: SandboxType,
/// Effective sandbox level after Windows requirements have been applied.
pub level: WindowsSandboxLevel,
}
/// Applies Windows requirements to the configured mode or feature-derived level.
/// The feature-derived level must already reflect managed feature requirements.
pub fn prepare_windows_sandbox_config(
configured_mode: Option<WindowsSandboxModeToml>,
feature_level: WindowsSandboxLevel,
constraint: &mut ConstrainedWithSource<Option<WindowsSandboxModeToml>>,
warnings: &mut Vec<String>,
) -> std::io::Result<PreparedWindowsSandboxConfig> {
if configured_mode == Some(WindowsSandboxModeToml::Mxc) {
constraint.can_set(&configured_mode)?;
}
let selected_mode = configured_mode.or(match feature_level {
WindowsSandboxLevel::Elevated => Some(WindowsSandboxModeToml::Elevated),
WindowsSandboxLevel::RestrictedToken => Some(WindowsSandboxModeToml::Unelevated),
WindowsSandboxLevel::Disabled => None,
});
apply_requirement_constrained_value("windows.sandbox", selected_mode, constraint, warnings)?;
let effective_mode = *constraint.get();
let mode = if constraint.source.is_some() {
effective_mode
} else {
configured_mode
};
let (sandbox_type, level) = match effective_mode {
Some(WindowsSandboxModeToml::Elevated) => (
SandboxType::WindowsRestrictedToken,
WindowsSandboxLevel::Elevated,
),
Some(WindowsSandboxModeToml::Unelevated) => (
SandboxType::WindowsRestrictedToken,
WindowsSandboxLevel::RestrictedToken,
),
Some(WindowsSandboxModeToml::Mxc) => {
(SandboxType::WindowsMxc, WindowsSandboxLevel::Disabled)
}
None => (SandboxType::None, WindowsSandboxLevel::Disabled),
};
Ok(PreparedWindowsSandboxConfig {
mode,
sandbox_type,
level,
})
}
/// Preserve ordinary and managed MXC opt-outs plus network binding denials.
pub(super) fn config_allows_mxc(
windows_sandbox_mode: &ConstrainedWithSource<Option<WindowsSandboxModeToml>>,
permission_selection: &EffectivePermissionSelection<'_>,
profiles_are_active: bool,
permission_profile: Option<&PermissionProfile>,
network_requirements: Option<&Sourced<NetworkConstraints>>,
cfg: &ConfigToml,
enable_network_proxy: bool,
) -> std::io::Result<bool> {
if cfg.windows.as_ref().and_then(|windows| windows.allow_mxc) == Some(false)
|| windows_sandbox_mode
.can_set(&Some(WindowsSandboxModeToml::Mxc))
.is_err()
{
return Ok(false);
}
let profile_local_binding = if profiles_are_active
&& permission_profile.is_none_or(profile_allows_configured_network_proxy)
&& let Some(profile) = permission_selection.selected_profile_id
{
network_proxy_config_for_profile_selection(permission_selection.profiles.as_ref(), profile)?
.allow_local_binding
} else {
None
};
Ok(windows_mxc_allowed_by_config(
windows_sandbox_mode,
network_requirements,
cfg.features.as_ref(),
enable_network_proxy,
profile_local_binding,
))
}
/// Eligibility shared with remote selection after the caller resolves its active profile.
/// Managed network requirements outrank feature and profile binding restrictions.
pub fn windows_mxc_allowed_by_config(
windows_sandbox_mode: &ConstrainedWithSource<Option<WindowsSandboxModeToml>>,
network_requirements: Option<&Sourced<NetworkConstraints>>,
features: Option<&FeaturesToml>,
enable_network_proxy: bool,
profile_local_binding: Option<bool>,
) -> bool {
if windows_sandbox_mode
.can_set(&Some(WindowsSandboxModeToml::Mxc))
.is_err()
{
return false;
}
let allow_local_binding = network_requirements
.and_then(|requirements| requirements.value.allow_local_binding)
.or_else(|| {
network_proxy_toml_config(features)
.filter(|config| enable_network_proxy && config.allow_local_binding == Some(false))
.and_then(|config| config.allow_local_binding)
})
.or(profile_local_binding);
allow_local_binding != Some(false)
}
#[cfg(test)]
#[path = "windows_sandbox_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,44 @@
//! Preserve explicit Windows mode priority without persisting feature fallbacks.
use super::*;
use akode_config::ConfigRequirements;
use pretty_assertions::assert_eq;
#[test]
fn configured_mode_takes_priority_without_persisting_feature_fallback() -> std::io::Result<()> {
for (configured_mode, expected) in [
(
None,
PreparedWindowsSandboxConfig {
mode: None,
sandbox_type: SandboxType::WindowsRestrictedToken,
level: WindowsSandboxLevel::Elevated,
},
),
(
Some(WindowsSandboxModeToml::Unelevated),
PreparedWindowsSandboxConfig {
mode: Some(WindowsSandboxModeToml::Unelevated),
sandbox_type: SandboxType::WindowsRestrictedToken,
level: WindowsSandboxLevel::RestrictedToken,
},
),
(
Some(WindowsSandboxModeToml::Mxc),
PreparedWindowsSandboxConfig {
mode: Some(WindowsSandboxModeToml::Mxc),
sandbox_type: SandboxType::WindowsMxc,
level: WindowsSandboxLevel::Disabled,
},
),
] {
let actual = prepare_windows_sandbox_config(
configured_mode,
WindowsSandboxLevel::Elevated,
&mut ConfigRequirements::default().windows_sandbox_mode,
&mut Vec::new(),
)?;
assert_eq!(actual, expected);
}
Ok(())
}