Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,178 @@
//! Verify authentication updates across the running CLI executor process.
use std::process::Stdio;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_login::AuthCredentialsStoreMode;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::path;
#[tokio::test]
async fn executor_startup_rejects_agent_identity_before_cloud_config() -> Result<()> {
let home = TempDir::new()?;
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(ResponseTemplate::new(503))
.expect(0)
.mount(&server)
.await;
let manager = codex_login::test_support::auth_manager_with_agent_identity().await?;
let Some(codex_login::CodexAuth::AgentIdentity(agent)) = manager.auth_cached() else {
anyhow::bail!("expected Agent Identity fixture");
};
let mut record = agent.record().clone();
record.task_id = None;
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&serde_json::json!({
"auth_mode": codex_protocol::auth::AuthMode::AgentIdentity,
"agent_identity": record,
}))?,
)?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_AGENT_IDENTITY_AUTHAPI_BASE_URL", server.uri())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"env",
])
.kill_on_drop(true);
let output =
tokio::time::timeout(std::time::Duration::from_secs(20), command.output()).await??;
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("requires ChatGPT authentication or API key authentication"),
"{stderr}"
);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn noise_executor_refreshes_on_401_and_reloads_rotated_credentials() -> Result<()> {
let home = TempDir::new()?;
let registry = MockServer::start().await;
let listener = TcpListener::bind("127.0.0.1:0").await?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("old-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(path("/refresh"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"access_token": "refreshed-token", "refresh_token": "new-refresh-token",
})))
.expect(1)
.mount(&registry)
.await;
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer old-token"))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&registry)
.await;
for token in ["refreshed-token", "rotated-token"] {
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", format!("Bearer {token}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "env", "url": format!("ws://{}", listener.local_addr()?),
"executor_registration_id": "registration", "security_profile": "noise_hybrid_ik_v1",
})))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
}
// The later registration sees the stored rotation before sending a stale
// request. The initial 401 above still exercises bounded auth recovery.
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer refreshed-token"))
.respond_with(ResponseTemplate::new(401))
.expect(0)
.mount(&registry)
.await;
let mut child = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", registry.uri()),
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"env",
"--exit-on-stdin-close",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let stdin = child.stdin.take();
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
// Update storage while the executor is alive, then force a new registration.
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("rotated-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
websocket.close(None).await?;
drop(websocket);
let (socket, _) = listener.accept().await?;
let rejected = accept_hdr_async(socket, |_: &_, _: _| {
Err(http::Response::builder().status(401).body(None).unwrap())
})
.await;
assert!(rejected.is_err());
let (socket, _) = listener.accept().await?;
let _websocket = accept_async(socket).await?;
drop(stdin);
let output = child.wait_with_output().await?;
anyhow::ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}

View File

@@ -0,0 +1,155 @@
//! End-to-end checks that only executor startup can opt into PID inheritance.
use super::*;
use codex_exec_server::FileSystemSandboxContext;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn pid_inheritance_is_startup_only_for_process_and_filesystem_helpers() -> Result<()> {
let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path(
&PermissionProfile::read_only().file_system_sandbox_policy(),
&std::env::current_dir()?,
) else {
eprintln!("skipping PID namespace test: no system bubblewrap");
return Ok(());
};
let available = tokio::process::Command::new(&bwrap)
.args(["--unshare-user", "--ro-bind", "/", "/", "--", "/bin/true"])
.output()
.await?;
if !available.status.success() {
eprintln!(
"skipping PID namespace test: {}",
String::from_utf8_lossy(&available.stderr)
);
return Ok(());
}
tokio::time::timeout(Duration::from_secs(30), async {
let fixture = TempDir::new()?;
let wrapper = fixture.path().join("bwrap");
std::os::unix::fs::symlink(bwrap, fixture.path().join("real-bwrap"))?;
codex_utils_cargo_bin::write_executable(&wrapper, r#"#!/bin/sh
for arg in "$@"; do
[ "$arg" = "--" ] && break
if [ "$arg" = "--proc" ]; then
echo "bwrap: Can't mount proc on /newroot/proc: Operation not permitted" >&2
exit 1
fi
done
exec "${0%/*}/real-bwrap" "$@"
"#)?;
let path = format!("{}:{}", fixture.path().display(), std::env::var("PATH")?);
// System bubblewrap discovery intentionally excludes executables under the command cwd.
let workspace = TempDir::new()?;
let file = workspace.path().join("readable");
std::fs::write(&file, "ok")?;
let file_uri = url::Url::from_file_path(&file).unwrap();
let cwd = url::Url::from_directory_path(workspace.path()).unwrap();
let minimal_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special { value: FileSystemSpecialPath::Minimal },
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(workspace.path())?.into(), FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::from_absolute_path("/proc/version")?.into(), FileSystemAccessMode::Deny,
),
]);
let minimal_profile = PermissionProfile::from_runtime_permissions(
&minimal_policy, NetworkSandboxPolicy::Restricted,
);
for (inherit, profile) in [
(false, PermissionProfile::read_only()),
(true, PermissionProfile::read_only()),
(true, minimal_profile),
] {
let minimal = profile.file_system_sandbox_policy().include_platform_defaults();
let sandbox = FileSystemSandboxContext::from_permission_profile(
profile, cwd.as_str().parse()?,
);
let codex_home = TempDir::new()?;
// Neither a config key nor executor/request environment variables may opt in.
std::fs::write(codex_home.path().join("config.toml"),
"linux_sandbox_pid_namespace = 'inherit'\n")?;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command.args(["exec-server", "--listen", "stdio"])
.env("CODEX_HOME", codex_home.path())
.env("PATH", &path)
.env("CODEX_LINUX_SANDBOX_PID_NAMESPACE", "inherit")
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.kill_on_drop(true);
if inherit {
command.arg("--linux-sandbox-pid-namespace=inherit");
}
let mut child = command.spawn()?;
let mut stdin = child.stdin.take().context("executor stdin")?;
let mut stdout = BufReader::new(child.stdout.take().context("executor stdout")?);
send_json_line(&mut stdin, &serde_json::json!({
"id": 1, "method": "initialize",
"params": {"clientName": "pid-namespace-test", "resumeSessionId": null}
})).await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(&mut stdin, &serde_json::json!({"method": "initialized", "params": {}})).await?;
send_json_line(&mut stdin, &serde_json::json!({
"id": 2, "method": "process/start", "params": {
"processId": "pid-test", "cwd": cwd, "sandbox": sandbox,
"argv": ["/bin/bash", "-lc", r#"
set -e
IFS=' ' read -r pid rest < /proc/self/stat
test "$$" = "$pid"
test "$(cat <(printf shell-ok))" = shell-ok
if [ "$MINIMAL" = true ]; then
! cat /proc/version
fi
"#],
"env": {"PATH": path, "MINIMAL": minimal.to_string(), "CODEX_LINUX_SANDBOX_PID_NAMESPACE": "inherit"},
"tty": false, "pipeStdin": false, "arg0": null
}
})).await?;
// Notifications may precede the process/start response, so consume both.
let mut started = false;
let mut exit_code = None;
while !started || exit_code.is_none() {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] == 2 {
anyhow::ensure!(message.get("error").is_none(), "start failed: {message}");
started = true;
}
if message["method"] == "process/exited" {
exit_code = message["params"]["exitCode"].as_i64();
}
}
assert_eq!(exit_code, Some(if inherit { 0 } else { 1 }));
send_json_line(&mut stdin, &serde_json::json!({
"id": 3, "method": "fs/readFile", "params": {"path": file_uri, "sandbox": sandbox}
})).await?;
loop {
let mut line = String::new();
anyhow::ensure!(stdout.read_line(&mut line).await? > 0, "executor closed");
let message: serde_json::Value = serde_json::from_str(&line)?;
if message["id"] != 3 { continue; }
assert_eq!(message["result"], serde_json::json!({"dataBase64": "b2s="}));
break;
}
drop(stdin);
// Drain notifications while the executor shuts down.
let mut remaining = String::new();
stdout.read_to_string(&mut remaining).await?;
let output = child.wait_with_output().await?;
anyhow::ensure!(output.status.success(), "executor failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
}).await?
}