Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
711 lines
26 KiB
Rust
711 lines
26 KiB
Rust
//! Sandbox coverage for extension-contributed tools.
|
|
//!
|
|
//! A test-only probe extension reads and writes files through the turn's environment
|
|
//! filesystem and issues HTTP requests through the configured client factory, so these
|
|
//! tests exercise the permissions and network policy every extension tool inherits.
|
|
|
|
use core_test_support::test_codex::local_requests;
|
|
use std::collections::BTreeSet;
|
|
use std::sync::Arc;
|
|
|
|
use anyhow::Context;
|
|
use anyhow::Result;
|
|
use akode_core::TurnInputRequest;
|
|
use akode_core::config::Config;
|
|
use akode_core::config::Constrained;
|
|
use akode_extension_api::ExtensionData;
|
|
use akode_extension_api::ExtensionFuture;
|
|
use akode_extension_api::ExtensionRegistry;
|
|
use akode_extension_api::ExtensionRegistryBuilder;
|
|
use akode_extension_api::FunctionCallError;
|
|
use akode_extension_api::JsonToolOutput;
|
|
use akode_extension_api::ResponsesApiTool;
|
|
use akode_extension_api::ThreadLifecycleContributor;
|
|
use akode_extension_api::ThreadStartInput;
|
|
use akode_extension_api::ToolCall;
|
|
use akode_extension_api::ToolContributor;
|
|
use akode_extension_api::ToolExecutor;
|
|
use akode_extension_api::ToolExecutorFuture;
|
|
use akode_extension_api::ToolName;
|
|
use akode_extension_api::ToolOutput;
|
|
use akode_extension_api::ToolSpec;
|
|
use akode_features::Feature;
|
|
use akode_http_client::ClientRouteClass;
|
|
use akode_http_client::DestinationPolicy;
|
|
use akode_http_client::HttpClientFactory;
|
|
use akode_http_client::NetworkPolicyController;
|
|
use akode_login::CodexAuth;
|
|
use akode_protocol::config_types::ApprovalsReviewer;
|
|
use akode_protocol::config_types::CollaborationMode;
|
|
use akode_protocol::config_types::ModeKind;
|
|
use akode_protocol::config_types::Settings;
|
|
use akode_protocol::config_types::WebSearchMode;
|
|
use akode_protocol::models::FileSystemPermissions;
|
|
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::protocol::AskForApproval;
|
|
use akode_protocol::protocol::EventMsg;
|
|
use akode_protocol::protocol::Op;
|
|
use akode_protocol::protocol::ThreadSettingsOverrides;
|
|
use akode_protocol::request_permissions::PermissionGrantScope;
|
|
use akode_protocol::request_permissions::RequestPermissionProfile;
|
|
use akode_protocol::request_permissions::RequestPermissionsResponse;
|
|
use akode_protocol::user_input::UserInput;
|
|
use akode_tools::JsonSchema;
|
|
use akode_utils_absolute_path::AbsolutePathBuf;
|
|
use akode_utils_path_uri::PathUri;
|
|
use core_test_support::responses;
|
|
use core_test_support::skip_if_no_network;
|
|
use core_test_support::skip_if_sandbox;
|
|
use core_test_support::skip_if_target_windows;
|
|
use core_test_support::test_codex::test_codex;
|
|
use core_test_support::test_codex::turn_permission_fields;
|
|
use core_test_support::wait_for_event;
|
|
use pretty_assertions::assert_eq;
|
|
use serde::Deserialize;
|
|
use serde_json::json;
|
|
use test_case::test_case;
|
|
|
|
const PROBE_TOOL_NAME: &str = "sandbox_probe";
|
|
const PROBE_FETCH_PATH: &str = "/probe/fetch";
|
|
const PROBE_FILE_BYTES: &[u8] = b"sandbox probe payload";
|
|
|
|
#[derive(Clone)]
|
|
struct ProbeConfig {
|
|
http_client_factory: HttpClientFactory,
|
|
}
|
|
|
|
struct SandboxProbeExtension;
|
|
|
|
impl ThreadLifecycleContributor<Config> for SandboxProbeExtension {
|
|
fn on_thread_start<'a>(
|
|
&'a self,
|
|
input: ThreadStartInput<'a, Config>,
|
|
) -> ExtensionFuture<'a, ()> {
|
|
Box::pin(async move {
|
|
input.thread_store.insert(ProbeConfig {
|
|
http_client_factory: input.config.http_client_factory(),
|
|
});
|
|
})
|
|
}
|
|
}
|
|
|
|
impl ToolContributor for SandboxProbeExtension {
|
|
fn tools(
|
|
&self,
|
|
_session_store: &ExtensionData,
|
|
thread_store: &ExtensionData,
|
|
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
|
let Some(config) = thread_store.get::<ProbeConfig>() else {
|
|
return Vec::new();
|
|
};
|
|
vec![Arc::new(SandboxProbeTool {
|
|
http_client_factory: config.http_client_factory.clone(),
|
|
})]
|
|
}
|
|
}
|
|
|
|
/// Reads `path` through the turn environment, copies it to `copy_to`, and optionally fetches
|
|
/// `fetch_url` through the configured HTTP client factory first.
|
|
struct SandboxProbeTool {
|
|
http_client_factory: HttpClientFactory,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct ProbeArgs {
|
|
path: AbsolutePathBuf,
|
|
copy_to: Option<AbsolutePathBuf>,
|
|
fetch_url: Option<String>,
|
|
}
|
|
|
|
impl<'call> ToolExecutor<ToolCall<'call>> for SandboxProbeTool {
|
|
fn tool_name(&self) -> ToolName {
|
|
ToolName::plain(PROBE_TOOL_NAME)
|
|
}
|
|
|
|
fn spec(&self) -> ToolSpec {
|
|
let properties = ["path", "copy_to", "fetch_url"]
|
|
.into_iter()
|
|
.map(|name| (name.to_string(), JsonSchema::string(/*description*/ None)))
|
|
.collect();
|
|
ToolSpec::Function(ResponsesApiTool {
|
|
name: PROBE_TOOL_NAME.to_string(),
|
|
description: "Test probe for extension sandboxing.".to_string(),
|
|
strict: false,
|
|
defer_loading: None,
|
|
parameters: JsonSchema::object(
|
|
properties,
|
|
Some(vec!["path".to_string()]),
|
|
Some(false.into()),
|
|
),
|
|
output_schema: None,
|
|
})
|
|
}
|
|
|
|
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
|
|
where
|
|
'call: 'a,
|
|
{
|
|
Box::pin(async move {
|
|
let args: ProbeArgs = serde_json::from_str(call.function_arguments()?)
|
|
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
|
if let Some(fetch_url) = args.fetch_url.as_deref() {
|
|
let client = self
|
|
.http_client_factory
|
|
.build_client(fetch_url, ClientRouteClass::Api)
|
|
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
|
client.get(fetch_url).send().await.map_err(|error| {
|
|
FunctionCallError::RespondToModel(format!("probe fetch failed: {error}"))
|
|
})?;
|
|
}
|
|
let Some(environment) = call.environments.first() else {
|
|
return Err(FunctionCallError::RespondToModel(
|
|
"no environment available".to_string(),
|
|
));
|
|
};
|
|
let bytes = environment
|
|
.fs()
|
|
.read_file(&PathUri::from_abs_path(&args.path), Default::default())
|
|
.await
|
|
.map_err(|error| {
|
|
FunctionCallError::RespondToModel(format!(
|
|
"unable to read file at `{}`: {error}",
|
|
args.path.display()
|
|
))
|
|
})?;
|
|
if let Some(copy_to) = args.copy_to.as_ref() {
|
|
environment
|
|
.fs()
|
|
.write_file(
|
|
&PathUri::from_abs_path(copy_to),
|
|
bytes.clone(),
|
|
Default::default(),
|
|
)
|
|
.await
|
|
.map_err(|error| {
|
|
FunctionCallError::RespondToModel(format!(
|
|
"unable to write file at `{}`: {error}",
|
|
copy_to.display()
|
|
))
|
|
})?;
|
|
}
|
|
let output = json!({ "contents": String::from_utf8_lossy(&bytes) });
|
|
Ok(Box::new(JsonToolOutput::new(output)) as Box<dyn ToolOutput>)
|
|
})
|
|
}
|
|
}
|
|
|
|
fn probe_extensions() -> Arc<ExtensionRegistry<Config>> {
|
|
let extension = Arc::new(SandboxProbeExtension);
|
|
let mut extension_builder = ExtensionRegistryBuilder::<Config>::new();
|
|
extension_builder.thread_lifecycle_contributor(extension.clone());
|
|
extension_builder.tool_contributor(extension);
|
|
Arc::new(extension_builder.build())
|
|
}
|
|
|
|
fn probe_output_contents(output: &serde_json::Value) -> Option<String> {
|
|
let text = output["output"].as_str()?;
|
|
let value: serde_json::Value = serde_json::from_str(text).ok()?;
|
|
value["contents"].as_str().map(str::to_string)
|
|
}
|
|
|
|
#[test_case(false; "file_access")]
|
|
#[test_case(true; "application_network")]
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn extension_tool_respects_restrictions(deny_network: bool) -> Result<()> {
|
|
skip_if_no_network!(Ok(()));
|
|
|
|
let server = responses::start_mock_server().await;
|
|
let responses_url = format!("{}/v1/responses", server.uri()).parse()?;
|
|
let auth = CodexAuth::from_api_key("Test API Key");
|
|
let mut builder = test_codex()
|
|
.with_auth(auth)
|
|
.with_extensions(probe_extensions())
|
|
.with_config(move |config| {
|
|
assert!(config.web_search_mode.set(WebSearchMode::Live).is_ok());
|
|
if deny_network {
|
|
let controller = NetworkPolicyController::default();
|
|
let policy = controller
|
|
.policy()
|
|
.restrict_to_endpoints(BTreeSet::from([responses_url]));
|
|
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
|
config.application_network_policy = policy;
|
|
config.respect_system_proxy = false;
|
|
}
|
|
});
|
|
let test = builder.build(&server).await?;
|
|
let denied_path = test.config.cwd.join("denied.txt");
|
|
std::fs::write(&denied_path, PROBE_FILE_BYTES)?;
|
|
let fetch_url = format!("{}{PROBE_FETCH_PATH}", server.uri());
|
|
|
|
let call_id = "probe-denied";
|
|
let response_mock = responses::mount_sse_sequence(
|
|
&server,
|
|
vec![
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_function_call(
|
|
call_id,
|
|
PROBE_TOOL_NAME,
|
|
&if deny_network {
|
|
json!({
|
|
"path": denied_path.display().to_string(),
|
|
"fetch_url": fetch_url,
|
|
})
|
|
} else {
|
|
json!({ "path": denied_path.display().to_string() })
|
|
}
|
|
.to_string(),
|
|
),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-2"),
|
|
responses::ev_assistant_message("msg-1", "done"),
|
|
responses::ev_completed("resp-2"),
|
|
]),
|
|
],
|
|
)
|
|
.await;
|
|
|
|
let mut file_system_sandbox_policy = FileSystemSandboxPolicy::default();
|
|
if !deny_network {
|
|
file_system_sandbox_policy
|
|
.entries
|
|
.push(FileSystemSandboxEntry {
|
|
path: FileSystemPath::Path {
|
|
path: denied_path.clone().into(),
|
|
},
|
|
access: FileSystemAccessMode::Deny,
|
|
missing_path_behavior: None,
|
|
});
|
|
}
|
|
let permission_profile = PermissionProfile::from_runtime_permissions(
|
|
&file_system_sandbox_policy,
|
|
NetworkSandboxPolicy::Restricted,
|
|
);
|
|
|
|
test.submit_turn_with_permission_profile("read the denied file", permission_profile)
|
|
.await?;
|
|
|
|
let request = response_mock
|
|
.last_request()
|
|
.context("missing request containing extension output")?;
|
|
let output = request
|
|
.function_call_output_content_and_success(call_id)
|
|
.and_then(|(content, _)| content)
|
|
.context("extension error text should be present")?;
|
|
if deny_network {
|
|
assert!(
|
|
output.contains("destination denied by application network policy"),
|
|
"{output}"
|
|
);
|
|
let requests = server
|
|
.received_requests()
|
|
.await
|
|
.context("request history should be recorded")?;
|
|
assert!(
|
|
requests
|
|
.iter()
|
|
.all(|request| request.url.path() != PROBE_FETCH_PATH)
|
|
);
|
|
} else {
|
|
assert!(
|
|
output.starts_with(&format!(
|
|
"unable to read file at `{}`:",
|
|
denied_path.display()
|
|
)),
|
|
"unexpected extension error: {output}"
|
|
);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn extension_tool_uses_granted_turn_permissions_without_host_local_persistence() -> Result<()>
|
|
{
|
|
skip_if_no_network!(Ok(()));
|
|
skip_if_sandbox!(Ok(()));
|
|
|
|
let server = responses::start_mock_server().await;
|
|
|
|
let auth = CodexAuth::from_api_key("Test API Key");
|
|
let base_permission_profile = PermissionProfile::workspace_write_with(
|
|
&[],
|
|
NetworkSandboxPolicy::Restricted,
|
|
/*exclude_tmpdir_env_var*/ true,
|
|
/*exclude_slash_tmp*/ true,
|
|
);
|
|
let permission_profile_for_config = base_permission_profile.clone();
|
|
let mut builder = test_codex()
|
|
.with_auth(auth)
|
|
.with_extensions(probe_extensions())
|
|
.with_config(move |config| {
|
|
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
|
|
config
|
|
.permissions
|
|
.set_permission_profile(permission_profile_for_config)
|
|
.expect("set permission profile");
|
|
assert!(config.web_search_mode.set(WebSearchMode::Live).is_ok());
|
|
assert!(
|
|
config
|
|
.features
|
|
.enable(Feature::RequestPermissionsTool)
|
|
.is_ok()
|
|
);
|
|
});
|
|
let test = builder.build(&server).await?;
|
|
|
|
let probe_dir = tempfile::tempdir()?;
|
|
let probe_path = probe_dir.path().canonicalize()?.join("granted.txt");
|
|
std::fs::write(&probe_path, PROBE_FILE_BYTES)?;
|
|
let requested_permissions = RequestPermissionProfile {
|
|
file_system: Some(FileSystemPermissions::from_read_write_roots(
|
|
Some(vec![AbsolutePathBuf::try_from(
|
|
probe_dir.path().canonicalize()?,
|
|
)?]),
|
|
Some(Vec::new()),
|
|
)),
|
|
..RequestPermissionProfile::default()
|
|
};
|
|
let permissions_call_id = "permissions-call";
|
|
let probe_call_id = "probe-granted";
|
|
let copy_path = test
|
|
.config
|
|
.cwd
|
|
.join("probe_output")
|
|
.join("probe-granted.txt");
|
|
std::fs::create_dir_all(test.config.cwd.join("probe_output"))?;
|
|
let response_mock = responses::mount_sse_sequence(
|
|
&server,
|
|
vec![
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_function_call(
|
|
permissions_call_id,
|
|
"request_permissions",
|
|
&serde_json::to_string(&json!({
|
|
"reason": "Read a file outside the workspace",
|
|
"permissions": requested_permissions,
|
|
}))?,
|
|
),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-2"),
|
|
responses::ev_function_call(
|
|
probe_call_id,
|
|
PROBE_TOOL_NAME,
|
|
&json!({
|
|
"path": probe_path.display().to_string(),
|
|
"copy_to": copy_path.display().to_string(),
|
|
})
|
|
.to_string(),
|
|
),
|
|
responses::ev_completed("resp-2"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-3"),
|
|
responses::ev_assistant_message("msg-1", "done"),
|
|
responses::ev_completed("resp-3"),
|
|
]),
|
|
],
|
|
)
|
|
.await;
|
|
|
|
let (sandbox_policy, permission_profile) =
|
|
turn_permission_fields(base_permission_profile, test.config.cwd.as_path());
|
|
test.codex
|
|
.start_or_steer_turn(
|
|
TurnInputRequest::user_input(vec![UserInput::Text {
|
|
text: "request access and read the file".to_string(),
|
|
text_elements: Vec::new(),
|
|
}])
|
|
.with_thread_settings(ThreadSettingsOverrides {
|
|
environments: Some(local_requests(test.config.cwd.clone())),
|
|
approval_policy: Some(AskForApproval::OnRequest),
|
|
approvals_reviewer: Some(ApprovalsReviewer::User),
|
|
sandbox_policy: Some(sandbox_policy),
|
|
permission_profile,
|
|
collaboration_mode: Some(CollaborationMode {
|
|
mode: ModeKind::Default,
|
|
settings: Settings {
|
|
model: test.session_configured.model.clone(),
|
|
reasoning_effort: None,
|
|
developer_instructions: None,
|
|
},
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
)
|
|
.await?;
|
|
let event = wait_for_event(&test.codex, |event| {
|
|
matches!(
|
|
event,
|
|
EventMsg::RequestPermissions(_) | EventMsg::TurnComplete(_)
|
|
)
|
|
})
|
|
.await;
|
|
let EventMsg::RequestPermissions(request) = event else {
|
|
panic!("expected request_permissions before turn completion");
|
|
};
|
|
assert_eq!(request.call_id, permissions_call_id);
|
|
test.codex
|
|
.submit(Op::RequestPermissionsResponse {
|
|
id: permissions_call_id.to_string(),
|
|
response: RequestPermissionsResponse {
|
|
permissions: request.permissions,
|
|
scope: PermissionGrantScope::Turn,
|
|
strict_auto_review: false,
|
|
},
|
|
})
|
|
.await?;
|
|
wait_for_event(&test.codex, |event| {
|
|
matches!(event, EventMsg::TurnComplete(_))
|
|
})
|
|
.await;
|
|
|
|
let request = response_mock
|
|
.last_request()
|
|
.context("missing request containing extension output")?;
|
|
let output = request.function_call_output(probe_call_id);
|
|
assert_eq!(
|
|
probe_output_contents(&output).as_deref(),
|
|
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
|
|
"{output}"
|
|
);
|
|
assert_eq!(std::fs::read(copy_path.as_path())?, PROBE_FILE_BYTES);
|
|
assert!(!test.config.codex_home.join("probe_output").exists());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Rebinding extension access each turn preserves session grants but expires turn-only grants.
|
|
#[test_case(PermissionGrantScope::Turn; "turn grant")]
|
|
#[test_case(PermissionGrantScope::Session; "session grant")]
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn extension_tool_rebinds_granted_permissions_on_each_turn(
|
|
grant_scope: PermissionGrantScope,
|
|
) -> Result<()> {
|
|
skip_if_no_network!(Ok(()));
|
|
skip_if_sandbox!(Ok(()));
|
|
skip_if_target_windows!(
|
|
Ok(()),
|
|
"restricted reads require the elevated Windows sandbox backend, unavailable in this fixture"
|
|
);
|
|
|
|
let server = responses::start_mock_server().await;
|
|
|
|
let auth = CodexAuth::from_api_key("Test API Key");
|
|
let base_permission_profile = PermissionProfile::from_runtime_permissions(
|
|
&FileSystemSandboxPolicy::restricted(vec![
|
|
FileSystemSandboxEntry::new(
|
|
FileSystemPath::Special {
|
|
value: FileSystemSpecialPath::Minimal,
|
|
},
|
|
FileSystemAccessMode::Read,
|
|
),
|
|
FileSystemSandboxEntry::new(
|
|
FileSystemPath::Special {
|
|
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
|
|
},
|
|
FileSystemAccessMode::Write,
|
|
),
|
|
]),
|
|
NetworkSandboxPolicy::Restricted,
|
|
);
|
|
let permission_profile_for_config = base_permission_profile.clone();
|
|
let mut builder = test_codex()
|
|
.with_auth(auth)
|
|
.with_extensions(probe_extensions())
|
|
.with_config(move |config| {
|
|
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
|
|
config
|
|
.permissions
|
|
.set_permission_profile(permission_profile_for_config)
|
|
.expect("set permission profile");
|
|
assert!(config.web_search_mode.set(WebSearchMode::Live).is_ok());
|
|
assert!(
|
|
config
|
|
.features
|
|
.enable(Feature::RequestPermissionsTool)
|
|
.is_ok()
|
|
);
|
|
});
|
|
let test = builder.build(&server).await?;
|
|
|
|
let probe_dir = tempfile::tempdir()?;
|
|
let probe_path = probe_dir.path().canonicalize()?.join("granted.txt");
|
|
std::fs::write(&probe_path, PROBE_FILE_BYTES)?;
|
|
let requested_permissions = RequestPermissionProfile {
|
|
file_system: Some(FileSystemPermissions::from_read_write_roots(
|
|
Some(vec![AbsolutePathBuf::try_from(
|
|
probe_dir.path().canonicalize()?,
|
|
)?]),
|
|
Some(Vec::new()),
|
|
)),
|
|
..RequestPermissionProfile::default()
|
|
};
|
|
let permissions_call_id = "permissions-call";
|
|
let probe_call_id = "probe-granted";
|
|
let next_probe_call_id = "probe-next-turn";
|
|
let copy_path = test.config.cwd.join("probe-granted.txt");
|
|
let next_copy_path = test.config.cwd.join("probe-next-turn.txt");
|
|
let response_mock = responses::mount_sse_sequence(
|
|
&server,
|
|
vec![
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-1"),
|
|
responses::ev_function_call(
|
|
permissions_call_id,
|
|
"request_permissions",
|
|
&serde_json::to_string(&json!({
|
|
"reason": "Read a file outside the workspace",
|
|
"permissions": requested_permissions,
|
|
}))?,
|
|
),
|
|
responses::ev_completed("resp-1"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-2"),
|
|
responses::ev_function_call(
|
|
probe_call_id,
|
|
PROBE_TOOL_NAME,
|
|
&json!({
|
|
"path": probe_path.display().to_string(),
|
|
"copy_to": copy_path.display().to_string(),
|
|
})
|
|
.to_string(),
|
|
),
|
|
responses::ev_completed("resp-2"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-3"),
|
|
responses::ev_assistant_message("msg-1", "done"),
|
|
responses::ev_completed("resp-3"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-4"),
|
|
responses::ev_function_call(
|
|
next_probe_call_id,
|
|
PROBE_TOOL_NAME,
|
|
&json!({
|
|
"path": probe_path.display().to_string(),
|
|
"copy_to": next_copy_path.display().to_string(),
|
|
})
|
|
.to_string(),
|
|
),
|
|
responses::ev_completed("resp-4"),
|
|
]),
|
|
responses::sse(vec![
|
|
responses::ev_response_created("resp-5"),
|
|
responses::ev_assistant_message("msg-2", "done again"),
|
|
responses::ev_completed("resp-5"),
|
|
]),
|
|
],
|
|
)
|
|
.await;
|
|
|
|
let (sandbox_policy, permission_profile) =
|
|
turn_permission_fields(base_permission_profile, test.config.cwd.as_path());
|
|
test.codex
|
|
.start_or_steer_turn(
|
|
TurnInputRequest::user_input(vec![UserInput::Text {
|
|
text: "request access and read the file".to_string(),
|
|
text_elements: Vec::new(),
|
|
}])
|
|
.with_thread_settings(ThreadSettingsOverrides {
|
|
environments: Some(local_requests(test.config.cwd.clone())),
|
|
approval_policy: Some(AskForApproval::OnRequest),
|
|
approvals_reviewer: Some(ApprovalsReviewer::User),
|
|
sandbox_policy: Some(sandbox_policy),
|
|
permission_profile,
|
|
collaboration_mode: Some(CollaborationMode {
|
|
mode: ModeKind::Default,
|
|
settings: Settings {
|
|
model: test.session_configured.model.clone(),
|
|
reasoning_effort: None,
|
|
developer_instructions: None,
|
|
},
|
|
}),
|
|
..Default::default()
|
|
}),
|
|
)
|
|
.await?;
|
|
let event = wait_for_event(&test.codex, |event| {
|
|
matches!(
|
|
event,
|
|
EventMsg::RequestPermissions(_) | EventMsg::TurnComplete(_)
|
|
)
|
|
})
|
|
.await;
|
|
let EventMsg::RequestPermissions(request) = event else {
|
|
panic!("expected request_permissions before turn completion");
|
|
};
|
|
assert_eq!(request.call_id, permissions_call_id);
|
|
test.codex
|
|
.submit(Op::RequestPermissionsResponse {
|
|
id: permissions_call_id.to_string(),
|
|
response: RequestPermissionsResponse {
|
|
permissions: request.permissions,
|
|
scope: grant_scope,
|
|
strict_auto_review: false,
|
|
},
|
|
})
|
|
.await?;
|
|
wait_for_event(&test.codex, |event| {
|
|
matches!(event, EventMsg::TurnComplete(_))
|
|
})
|
|
.await;
|
|
|
|
let request = response_mock
|
|
.last_request()
|
|
.context("missing request containing extension output")?;
|
|
let output = request.function_call_output(probe_call_id);
|
|
assert_eq!(
|
|
probe_output_contents(&output).as_deref(),
|
|
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
|
|
"{output}"
|
|
);
|
|
|
|
test.submit_text_turn("read the same file in a new turn")
|
|
.await?;
|
|
let next_request = response_mock
|
|
.last_request()
|
|
.context("missing request containing next-turn extension output")?;
|
|
match grant_scope {
|
|
PermissionGrantScope::Turn => {
|
|
let output = next_request
|
|
.function_call_output_content_and_success(next_probe_call_id)
|
|
.and_then(|(content, _)| content)
|
|
.context("expired turn grant should produce an extension error")?;
|
|
assert!(
|
|
output.starts_with(&format!(
|
|
"unable to read file at `{}`:",
|
|
probe_path.display()
|
|
)),
|
|
"unexpected extension error: {output}"
|
|
);
|
|
assert!(!next_copy_path.exists());
|
|
}
|
|
PermissionGrantScope::Session => {
|
|
let output = next_request.function_call_output(next_probe_call_id);
|
|
assert_eq!(
|
|
probe_output_contents(&output).as_deref(),
|
|
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
|
|
"{output}"
|
|
);
|
|
assert_eq!(std::fs::read(next_copy_path.as_path())?, PROBE_FILE_BYTES);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|