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,106 @@
use super::ExecApprovalRequest;
use super::ExecPolicyCommandOrigin;
use super::ExecPolicyCommands;
use super::ExecPolicyManager;
use super::commands_for_exec_policy_for_platform;
use super::powershell_command_origin;
use crate::shell::Shell;
use crate::tools::sandboxing::ExecApprovalRequirement;
use akode_shell_command::is_dangerous_command::DangerousCommandPlatform;
use akode_shell_command::powershell::extract_powershell_command;
use akode_shell_command::powershell::parse_powershell_script_into_plain_commands;
use std::path::Path;
impl ExecPolicyManager {
pub(crate) async fn create_exec_approval_requirement_for_shell(
&self,
mut request: ExecApprovalRequest<'_>,
configured_shell: &Shell,
command_platform: DangerousCommandPlatform,
) -> ExecApprovalRequirement {
let command = request.command;
let executable = shell_approval_command(command, configured_shell);
if executable.len() == command.len() {
return self
.create_exec_approval_requirement_for_command_platform(request, command_platform)
.await;
}
let mut policy_commands = if command_platform == DangerousCommandPlatform::Windows {
match extract_powershell_command(command) {
Some((_, script)) => {
let commands = parse_powershell_script_into_plain_commands(script);
let command_origin = commands
.as_ref()
.map_or(ExecPolicyCommandOrigin::PowerShell, |commands| {
powershell_command_origin(script, commands)
});
ExecPolicyCommands {
commands: commands.unwrap_or_else(|| vec![command.to_vec()]),
command_origin,
}
}
None => commands_for_exec_policy_for_platform(command, command_platform),
}
} else {
commands_for_exec_policy_for_platform(command, command_platform)
};
// Evaluate the executable alongside its apparent commands. Inner
// commands can add restrictions, but cannot grant the executable trust.
policy_commands.commands.insert(0, executable.to_vec());
request.command = executable;
self.create_exec_approval_requirement_for_parsed_commands(
request,
policy_commands,
command_platform,
)
.await
}
}
fn shell_approval_command<'a>(command: &'a [String], configured_shell: &Shell) -> &'a [String] {
let Some(executable) = command.first() else {
return command;
};
let executable_path = Path::new(executable);
#[cfg(windows)]
let is_system_shell = std::env::var_os("SystemRoot").is_some_and(|system_root| {
let system_directory = Path::new(&system_root).join("System32");
let powershell_directory = system_directory.join("WindowsPowerShell").join("v1.0");
executable_path.parent().is_some_and(|parent| {
parent
.as_os_str()
.eq_ignore_ascii_case(system_directory.as_os_str())
|| parent
.as_os_str()
.eq_ignore_ascii_case(powershell_directory.as_os_str())
})
});
#[cfg(not(windows))]
let is_system_shell = executable_path
.parent()
.is_some_and(|parent| parent == Path::new("/bin") || parent == Path::new("/usr/bin"));
#[cfg(windows)]
let is_configured_shell = executable_path
.as_os_str()
.eq_ignore_ascii_case(configured_shell.shell_path.as_os_str());
#[cfg(not(windows))]
let is_configured_shell = executable_path == configured_shell.shell_path.as_path();
if is_configured_shell || is_system_shell {
command
} else {
// An unfamiliar executable can ignore its arguments, so evaluate the
// executable separately from any restrictions on its apparent command.
std::slice::from_ref(executable)
}
}
#[cfg(test)]
#[path = "executable_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,68 @@
use super::shell_approval_command;
use crate::shell::Shell;
use crate::shell::ShellType;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[test]
fn parent_directory_traversal_is_not_a_trusted_system_shell() {
let (configured_executable, unfamiliar_executable) = if cfg!(windows) {
let system_root = std::env::var_os("SystemRoot").expect("Windows SystemRoot");
let system_directory = PathBuf::from(system_root).join("System32");
(
system_directory.join("cmd.exe"),
system_directory
.join("..")
.join("workspace")
.join("powershell.exe"),
)
} else {
(
PathBuf::from("/bin/sh"),
PathBuf::from("/bin/../workspace/bash"),
)
};
let shell = Shell {
shell_type: if cfg!(windows) {
ShellType::Cmd
} else {
ShellType::Sh
},
shell_path: configured_executable,
};
let command = vec![
unfamiliar_executable.to_string_lossy().into_owned(),
"-c".to_string(),
"ls".to_string(),
];
assert_eq!(shell_approval_command(&command, &shell), &command[..1],);
}
#[cfg(windows)]
#[test]
fn windows_shell_identity_is_case_insensitive() {
let configured_executable = PathBuf::from(r"C:\Custom\pwsh.exe");
let configured_shell = Shell {
shell_type: ShellType::PowerShell,
shell_path: configured_executable.clone(),
};
let system_root = std::env::var_os("SystemRoot").expect("Windows SystemRoot");
let system_executable = PathBuf::from(system_root.to_string_lossy().to_ascii_uppercase())
.join("SYSTEM32")
.join("WINDOWSPOWERSHELL")
.join("V1.0")
.join("POWERSHELL.EXE");
for executable in [
configured_executable.to_string_lossy().to_ascii_uppercase(),
system_executable.to_string_lossy().into_owned(),
] {
let command = vec![executable, "-Command".to_string(), "echo safe".to_string()];
assert_eq!(
shell_approval_command(&command, &configured_shell),
command.as_slice(),
);
}
}

View File

@@ -0,0 +1,61 @@
//! Validate a trusted host's policy snapshot against the destination's managed requirements.
use super::ExecPolicyManager;
use super::policy_files;
use akode_config::ConfigLayerStack;
use akode_execpolicy::Policy;
use akode_execpolicy::RequirementsExecPolicy;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use std::sync::Arc;
/// Point-in-time session policy and the managed requirements it was loaded with.
/// A trusted host transports these together and reapplies them on cold resume.
pub(crate) struct InheritedExecPolicy {
pub(crate) policy: Arc<Policy>,
pub(crate) source_requirements: Option<Arc<RequirementsExecPolicy>>,
}
impl ExecPolicyManager {
pub(crate) async fn from_inherited(
snapshot: &InheritedExecPolicy,
stack: &ConfigLayerStack,
) -> CodexResult<Self> {
if !stack.ignore_user_and_project_exec_policy_rules()
|| !policy_files(stack)
.await
.map_err(|err| CodexErr::Fatal(format!("failed to load rules: {err}")))?
.is_empty()
{
return Err(CodexErr::InvalidRequest(
"inherited execution policy requires a managed-only destination".to_string(),
));
}
let destination = stack.requirements().exec_policy.as_deref();
let compatible = match (snapshot.source_requirements.as_deref(), destination) {
(None, None) => true,
(Some(source), Some(target)) => {
source == target
&& source.as_ref().network_rules() == target.as_ref().network_rules()
&& source.as_ref().host_executables() == target.as_ref().host_executables()
}
_ => false,
};
if !compatible {
return Err(CodexErr::InvalidRequest(
"inherited execution policy requirements differ from the destination".to_string(),
));
}
if let Some(requirements) = destination
&& !snapshot.policy.preserves_managed_requirements(requirements)
{
return Err(CodexErr::InvalidRequest(
"inherited execution policy does not preserve destination requirements".to_string(),
));
}
Ok(Self::from_snapshot(
Arc::clone(&snapshot.policy),
snapshot.source_requirements.clone(),
))
}
}

View File

@@ -0,0 +1,60 @@
use super::ExecPolicyManager;
use akode_execpolicy::Decision;
use akode_execpolicy::Policy;
use akode_execpolicy::PrefixRule;
use akode_execpolicy::RequirementsExecPolicy;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AllowPrefixRules {
Honor,
Ignore,
}
impl ExecPolicyManager {
pub(crate) fn current_for_environment(
&self,
environment_policy: Option<&RequirementsExecPolicy>,
allow_prefix_rules: AllowPrefixRules,
) -> Arc<Policy> {
let policy = self.current_for_prefix_rules(allow_prefix_rules);
match environment_policy {
Some(environment_policy) => Arc::new(policy.merge_overlay(environment_policy.as_ref())),
None => policy,
}
}
pub(crate) fn current_for_prefix_rules(
&self,
allow_prefix_rules: AllowPrefixRules,
) -> Arc<Policy> {
let policy = self.current();
if allow_prefix_rules == AllowPrefixRules::Honor {
return policy;
}
let rules = policy
.rules()
.iter_all()
.flat_map(|(program, rules)| {
rules.iter().filter_map(move |rule| {
let is_allow_prefix = rule
.as_any()
.downcast_ref::<PrefixRule>()
.is_some_and(|prefix| prefix.decision == Decision::Allow);
(!is_allow_prefix).then(|| (program.clone(), Arc::clone(rule)))
})
})
.collect();
Arc::new(Policy::from_parts(
rules,
policy.network_rules().to_vec(),
policy.host_executables().clone(),
))
}
}
#[cfg(test)]
#[path = "model_policy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,207 @@
use super::AllowPrefixRules;
use super::ExecPolicyManager;
use crate::exec_policy::ExecApprovalRequest;
use crate::sandboxing::SandboxPermissions;
use crate::tools::sandboxing::ExecApprovalRequirement;
use akode_execpolicy::Decision;
use akode_execpolicy::MatchOptions;
use akode_execpolicy::Policy;
use akode_execpolicy::PolicyParser;
use akode_execpolicy::RequirementsExecPolicy;
use akode_protocol::config_types::WindowsSandboxLevel;
use akode_protocol::models::PermissionProfile;
use akode_protocol::protocol::AskForApproval;
use pretty_assertions::assert_eq;
use std::sync::Arc;
fn policy_with_broad_allow_prefix() -> (Arc<Policy>, String) {
let program_name = if cfg!(windows) { "cargo.exe" } else { "cargo" };
let program_path = std::env::temp_dir()
.join(program_name)
.to_string_lossy()
.into_owned();
let escaped_program_path = program_path.replace('\\', "\\\\");
let source = format!(
r#"
host_executable(name="cargo", paths=["{escaped_program_path}"])
prefix_rule(pattern=["cargo"], decision="allow")
prefix_rule(pattern=["cargo", "publish"], decision="prompt")
prefix_rule(pattern=["rm"], decision="forbidden")
network_rule(host="example.com", protocol="https", decision="allow")
"#
);
let mut parser = PolicyParser::new();
parser.parse("test.rules", &source).expect("parse policy");
(Arc::new(parser.build()), program_path)
}
#[test]
fn ignored_rules_policy_filters_allow_prefixes_but_preserves_restrictive_and_network_rules() {
let (policy, program_path) = policy_with_broad_allow_prefix();
let manager = ExecPolicyManager::new(Arc::clone(&policy));
let standard_policy = manager.current_for_prefix_rules(AllowPrefixRules::Honor);
assert!(Arc::ptr_eq(&standard_policy, &policy));
let ignored_policy = manager.current_for_prefix_rules(AllowPrefixRules::Ignore);
assert!(ignored_policy.get_allowed_prefixes().is_empty());
assert_eq!(ignored_policy.network_rules(), policy.network_rules());
assert_eq!(ignored_policy.host_executables(), policy.host_executables());
let cargo_install = vec!["cargo".to_string(), "install".to_string()];
assert_eq!(
ignored_policy
.check(&cargo_install, &|_| Decision::Prompt)
.decision,
Decision::Prompt,
);
let cargo_publish = vec!["cargo".to_string(), "publish".to_string()];
assert_eq!(
ignored_policy
.check(&cargo_publish, &|_| Decision::Allow)
.decision,
Decision::Prompt,
);
let resolved_cargo_publish = vec![program_path, "publish".to_string()];
assert_eq!(
ignored_policy
.check_with_options(
&resolved_cargo_publish,
&|_| Decision::Allow,
&MatchOptions {
resolve_host_executables: true,
},
)
.decision,
Decision::Prompt,
);
let forbidden_command = vec!["rm".to_string(), "target".to_string()];
assert_eq!(
ignored_policy
.check(&forbidden_command, &|_| Decision::Allow)
.decision,
Decision::Forbidden,
);
}
#[test]
fn environment_restrictions_apply_after_model_prefix_filtering() {
let (thread_policy, _) = policy_with_broad_allow_prefix();
let manager = ExecPolicyManager::new(thread_policy);
let mut environment_policy = Policy::empty();
environment_policy
.add_prefix_rule(
&["cargo".to_string(), "install".to_string()],
Decision::Forbidden,
)
.expect("add environment restriction");
let environment_policy = RequirementsExecPolicy::new(environment_policy);
let command = vec!["cargo".to_string(), "install".to_string()];
for allow_prefix_rules in [AllowPrefixRules::Honor, AllowPrefixRules::Ignore] {
let policy = manager.current_for_environment(Some(&environment_policy), allow_prefix_rules);
assert_eq!(
policy.check(&command, &|_| Decision::Allow).decision,
Decision::Forbidden,
);
if allow_prefix_rules == AllowPrefixRules::Ignore {
assert!(policy.get_allowed_prefixes().is_empty());
}
}
}
#[tokio::test]
async fn ignored_rules_policy_requires_approval_for_broad_wrapped_and_resolved_prefixes() {
let (policy, program_path) = policy_with_broad_allow_prefix();
let manager = ExecPolicyManager::new(policy);
let commands = [
vec![
"cargo".to_string(),
"install".to_string(),
"example".to_string(),
],
vec![
"bash".to_string(),
"-lc".to_string(),
"cargo install example".to_string(),
],
vec![program_path, "install".to_string(), "example".to_string()],
];
for command in commands {
let requirement = manager
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &command,
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::read_only(),
environment_policy: None,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
sandbox_permissions: SandboxPermissions::RequireEscalated,
prefix_rule: Some(vec!["cargo".to_string(), "install".to_string()]),
allow_prefix_rules: AllowPrefixRules::Ignore,
})
.await;
assert_eq!(
requirement,
ExecApprovalRequirement::NeedsApproval {
reason: None,
proposed_execpolicy_amendment: None,
},
"command {command:?} must not inherit a saved prefix approval",
);
}
}
#[tokio::test]
async fn ignored_rules_policy_keeps_heuristically_safe_commands_inside_the_sandbox() {
let mut policy = Policy::empty();
policy
.add_prefix_rule(&["echo".to_string()], Decision::Allow)
.expect("add broad allow prefix");
let manager = ExecPolicyManager::new(Arc::new(policy));
let command = vec!["echo".to_string(), "hello".to_string()];
let ignored_rules_requirement = manager
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &command,
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::read_only(),
environment_policy: None,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
sandbox_permissions: SandboxPermissions::UseDefault,
prefix_rule: None,
allow_prefix_rules: AllowPrefixRules::Ignore,
})
.await;
assert_eq!(
ignored_rules_requirement,
ExecApprovalRequirement::Skip {
bypass_sandbox: false,
proposed_execpolicy_amendment: None,
},
);
let standard_requirement = manager
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &command,
approval_policy: AskForApproval::OnRequest,
permission_profile: PermissionProfile::read_only(),
environment_policy: None,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
sandbox_permissions: SandboxPermissions::UseDefault,
prefix_rule: None,
allow_prefix_rules: AllowPrefixRules::Honor,
})
.await;
assert_eq!(
standard_requirement,
ExecApprovalRequirement::Skip {
bypass_sandbox: true,
proposed_execpolicy_amendment: None,
},
);
}