feat(app-server): enforce managed remote control disable (#27961)

## Why

Managed deployments need a reliable deny gate for remote control.
Persisted enablement and explicit startup requests currently remain able
to start the transport, while the removed `features.remote_control` key
is intentionally only a compatibility no-op.

This adds a dedicated requirement that administrators can use to force
remote control off without deleting the user's persisted preference.
Removing the requirement and restarting restores the prior choice.

## What Changed

- Added top-level `allow_remote_control` requirements parsing, sourced
layer precedence, debug output, and `configRequirements/read` exposure
as `allowRemoteControl`.
- Added a typed transport policy captured from the startup requirements
snapshot. Managed disable forces the initial state to disabled and
prevents enrollment, refresh, connection, and persisted-preference
mutation.
- Rejected every `remoteControl/*` RPC before parameter deserialization
with JSON-RPC `-32600` and `remote control is disabled by managed
requirements`.
- Preserved the existing disabled status notification and the previous
behavior when the requirement is `true` or omitted.
- Regenerated app-server protocol schemas and documented the new
requirement.

## Verification

- Confirmed all remote-control RPCs, including a malformed request,
return the managed-policy error while the initial status notification
remains `disabled`.
- Confirmed explicit ephemeral startup and persisted enablement make no
backend connection and leave the SQLite preference unchanged.
- Confirmed `allow_remote_control = true` does not enable or block
remote control and `configRequirements/read` returns
`allowRemoteControl: false` for the deny policy.

Related issue: N/A (managed-policy hardening).
This commit is contained in:
Anton Panasenko
2026-06-12 20:10:12 -07:00
committed by GitHub
parent 5d7db08b61
commit b9dc3b7a8b
29 changed files with 691 additions and 38 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ Example with notification opt-out:
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes (immediately after the response when everything completed synchronously, or after background imports finish).
- `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface.
- `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk, with optional `reloadUserConfig: true` to hot-reload loaded threads, including multiple `desktop.*` edits.
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`.
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`.
### Example: Start or resume a thread
+35 -6
View File
@@ -32,6 +32,7 @@ use crate::outgoing_message::QueuedOutgoingMessage;
use crate::transport::CHANNEL_CAPACITY;
use crate::transport::ConnectionState;
use crate::transport::OutboundConnectionState;
use crate::transport::RemoteControlPolicy;
use crate::transport::RemoteControlStartConfig;
use crate::transport::TransportEvent;
use crate::transport::acquire_app_server_startup_lock;
@@ -672,6 +673,28 @@ pub async fn run_main_with_transport_options(
None => error!("{}", warning.summary),
}
}
let remote_control_policy = if config
.config_layer_stack
.requirements()
.allow_remote_control
.as_ref()
.is_some_and(|requirement| !requirement.value)
{
RemoteControlPolicy::DisabledByRequirements
} else {
RemoteControlPolicy::Allowed
};
let remote_control_startup_mode = runtime_options.remote_control_startup_mode;
let remote_control_explicitly_requested =
remote_control_startup_mode == RemoteControlStartupMode::EnabledEphemeral;
if remote_control_explicitly_requested
&& remote_control_policy == RemoteControlPolicy::DisabledByRequirements
{
return Err(std::io::Error::new(
ErrorKind::InvalidInput,
"remote control is disabled by managed requirements",
));
}
let installation_id = resolve_installation_id(&config.codex_home).await?;
let transport_shutdown_token = CancellationToken::new();
let mut transport_accept_handles = Vec::<JoinHandle<()>>::new();
@@ -719,10 +742,9 @@ pub async fn run_main_with_transport_options(
let auth_manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await;
let remote_control_startup_mode = runtime_options.remote_control_startup_mode;
let remote_control_explicitly_requested =
remote_control_startup_mode == RemoteControlStartupMode::EnabledEphemeral;
let remote_control_enabled = remote_control_explicitly_requested && state_db.is_some();
let remote_control_enabled = remote_control_policy == RemoteControlPolicy::Allowed
&& remote_control_explicitly_requested
&& state_db.is_some();
if remote_control_explicitly_requested && state_db.is_none() {
error!("remote control disabled because sqlite state db is unavailable");
}
@@ -733,7 +755,9 @@ pub async fn run_main_with_transport_options(
{
return Err(std::io::Error::new(
ErrorKind::InvalidInput,
if remote_control_explicitly_requested && state_db.is_none() {
if remote_control_policy == RemoteControlPolicy::DisabledByRequirements {
"no transport configured; remote control disabled by managed requirements"
} else if remote_control_explicitly_requested && state_db.is_none() {
"no transport configured; remote control disabled because sqlite state db is unavailable"
} else {
"no transport configured; use --listen or enable remote control"
@@ -745,6 +769,7 @@ pub async fn run_main_with_transport_options(
RemoteControlStartConfig {
remote_control_url: config.chatgpt_base_url.clone(),
installation_id: installation_id.clone(),
policy: remote_control_policy,
},
state_db.clone(),
auth_manager.clone(),
@@ -772,7 +797,11 @@ pub async fn run_main_with_transport_options(
let _ = remote_control_accept_handle.await;
return Err(std::io::Error::new(
ErrorKind::InvalidInput,
"no transport configured; use --listen or enable remote control",
if remote_control_policy == RemoteControlPolicy::DisabledByRequirements {
"no transport configured; remote control disabled by managed requirements"
} else {
"no transport configured; use --listen or enable remote control"
},
));
}
}
+12 -6
View File
@@ -94,6 +94,17 @@ use tracing::Instrument;
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
const CONNECTION_RPC_DRAIN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
fn deserialize_client_request(
request: &JSONRPCRequest,
) -> Result<ClientRequest, JSONRPCErrorError> {
serde_json::to_value(request)
.map_err(|err| invalid_request(format!("Invalid request: {err}")))
.and_then(|request_json| {
serde_json::from_value(request_json)
.map_err(|err| invalid_request(format!("Invalid request: {err}")))
})
}
#[derive(Clone)]
struct ExternalAuthRefreshBridge {
outgoing: Arc<OutgoingMessageSender>,
@@ -582,12 +593,7 @@ impl MessageProcessor {
Arc::clone(&self.outgoing),
request_context.clone(),
async {
let codex_request = serde_json::to_value(&request)
.map_err(|err| invalid_request(format!("Invalid request: {err}")))
.and_then(|request_json| {
serde_json::from_value::<ClientRequest>(request_json)
.map_err(|err| invalid_request(format!("Invalid request: {err}")))
});
let codex_request = deserialize_client_request(&request);
let result = match codex_request {
Ok(codex_request) => {
// Websocket callers finalize outbound readiness in lib.rs after mirroring
@@ -364,6 +364,7 @@ fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigR
}),
allow_managed_hooks_only: requirements.allow_managed_hooks_only,
allow_appshots: requirements.allow_appshots,
allow_remote_control: requirements.allow_remote_control,
computer_use: requirements
.computer_use
.map(map_computer_use_requirements_to_api),
@@ -618,6 +619,16 @@ mod tests {
assert_eq!(mapped.hooks, None);
}
#[test]
fn requirements_api_includes_allow_remote_control() {
let mapped = map_requirements_toml_to_api(ConfigRequirementsToml {
allow_remote_control: Some(false),
..ConfigRequirementsToml::default()
});
assert_eq!(mapped.allow_remote_control, Some(false));
}
#[test]
fn requirements_api_includes_computer_use_requirements() {
let mapped = map_requirements_toml_to_api(ConfigRequirementsToml {
@@ -1,5 +1,6 @@
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::transport::RemoteControlEnableError;
use crate::transport::RemoteControlHandle;
use crate::transport::RemoteControlUnavailable;
use codex_app_server_protocol::JSONRPCErrorError;
@@ -35,7 +36,7 @@ impl RemoteControlRequestProcessor {
) -> Result<RemoteControlEnableResponse, JSONRPCErrorError> {
let handle = self.handle()?;
let status = if ephemeral {
handle.enable_ephemeral().map_err(map_unavailable)?
handle.enable_ephemeral().map_err(map_enable_error)?
} else {
handle
.enable(app_server_client_name)
@@ -88,7 +89,8 @@ impl RemoteControlRequestProcessor {
params: RemoteControlPairingStatusParams,
) -> Result<RemoteControlPairingStatusResponse, JSONRPCErrorError> {
validate_pairing_status_params(&params)?;
self.handle()?
let handle = self.handle()?;
handle
.pairing_status(params)
.await
.map_err(map_pairing_start_error)
@@ -115,9 +117,21 @@ impl RemoteControlRequestProcessor {
}
fn handle(&self) -> Result<&RemoteControlHandle, JSONRPCErrorError> {
self.remote_control_handle
let handle = self
.remote_control_handle
.as_ref()
.ok_or_else(|| internal_error("remote control is unavailable for this app-server"))
.ok_or_else(|| internal_error("remote control is unavailable for this app-server"))?;
handle
.ensure_remote_control_allowed()
.map_err(|err| invalid_request(err.to_string()))?;
Ok(handle)
}
}
fn map_enable_error(err: RemoteControlEnableError) -> JSONRPCErrorError {
match err {
RemoteControlEnableError::Unavailable(err) => map_unavailable(err),
RemoteControlEnableError::DisabledByRequirements(err) => invalid_request(err.to_string()),
}
}
@@ -126,7 +140,10 @@ fn map_unavailable(err: RemoteControlUnavailable) -> JSONRPCErrorError {
}
fn map_update_error(err: io::Error) -> JSONRPCErrorError {
if err.kind() == io::ErrorKind::NotFound {
if matches!(
err.kind(),
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
) {
invalid_request(err.to_string())
} else {
internal_error(err.to_string())
+2
View File
@@ -18,7 +18,9 @@ pub(crate) use codex_app_server_transport::ConnectionId;
pub(crate) use codex_app_server_transport::ConnectionOrigin;
pub(crate) use codex_app_server_transport::OutgoingMessage;
pub(crate) use codex_app_server_transport::QueuedOutgoingMessage;
pub(crate) use codex_app_server_transport::RemoteControlEnableError;
pub(crate) use codex_app_server_transport::RemoteControlHandle;
pub(crate) use codex_app_server_transport::RemoteControlPolicy;
pub(crate) use codex_app_server_transport::RemoteControlStartConfig;
pub use codex_app_server_transport::RemoteControlStartupMode;
pub(crate) use codex_app_server_transport::RemoteControlUnavailable;
@@ -1133,6 +1133,11 @@ impl TestAppServer {
self.send_request("config/read", params).await
}
pub async fn send_config_requirements_read_request(&mut self) -> anyhow::Result<i64> {
self.send_request("configRequirements/read", /*params*/ None)
.await
}
pub async fn send_config_value_write_request(
&mut self,
params: ConfigValueWriteParams,
@@ -14,6 +14,7 @@ use codex_app_server_protocol::ConfigEdit;
use codex_app_server_protocol::ConfigLayerSource;
use codex_app_server_protocol::ConfigReadParams;
use codex_app_server_protocol::ConfigReadResponse;
use codex_app_server_protocol::ConfigRequirementsReadResponse;
use codex_app_server_protocol::ConfigValueWriteParams;
use codex_app_server_protocol::ConfigWriteResponse;
use codex_app_server_protocol::ForcedChatgptWorkspaceIds;
@@ -47,6 +48,33 @@ fn write_config(codex_home: &TempDir, contents: &str) -> Result<()> {
)?)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_requirements_read_includes_allow_remote_control() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"allow_remote_control = false\n",
)?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp.send_config_requirements_read_request().await?;
let response = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: ConfigRequirementsReadResponse = to_response(response)?;
assert_eq!(
response
.requirements
.expect("managed requirements should be returned")
.allow_remote_control,
Some(false)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_read_returns_effective_and_layers() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -1,3 +1,6 @@
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::ErrorKind;
use std::time::Duration;
use anyhow::Context;
@@ -8,6 +11,13 @@ use app_test_support::TestAppServer;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
use codex_app_server::AppServerRuntimeOptions;
use codex_app_server::AppServerTransport;
use codex_app_server::AppServerWebsocketAuthSettings;
use codex_app_server::PluginStartupTasks;
use codex_app_server::RemoteControlStartupMode;
use codex_app_server::run_main_with_transport_options;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::RemoteControlClient;
use codex_app_server_protocol::RemoteControlClientsListOrder;
@@ -22,12 +32,18 @@ use codex_app_server_protocol::RemoteControlPairingStartParams;
use codex_app_server_protocol::RemoteControlPairingStartResponse;
use codex_app_server_protocol::RemoteControlPairingStatusParams;
use codex_app_server_protocol::RemoteControlPairingStatusResponse;
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
use codex_app_server_protocol::RemoteControlStatusReadResponse;
use codex_app_server_protocol::RequestId;
use codex_arg0::Arg0DispatchPaths;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_protocol::protocol::SessionSource;
use codex_state::RemoteControlEnrollmentRecord;
use codex_state::StateRuntime;
use codex_utils_cli::CliConfigOverrides;
use pretty_assertions::assert_eq;
use serial_test::serial;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
@@ -41,6 +57,34 @@ use tokio::time::timeout;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const REMOTE_CONTROL_DISABLED_BY_REQUIREMENTS_MESSAGE: &str =
"remote control is disabled by managed requirements";
struct EnvVarGuard {
key: &'static str,
original: Option<OsString>,
}
impl EnvVarGuard {
fn set(key: &'static str, value: &OsStr) -> Self {
let original = std::env::var_os(key);
unsafe {
std::env::set_var(key, value);
}
Self { key, original }
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
unsafe {
match &self.original {
Some(value) => std::env::set_var(self.key, value),
None => std::env::remove_var(self.key),
}
}
}
}
async fn remote_control_preference(
state_db: &StateRuntime,
@@ -61,6 +105,149 @@ async fn wait_for_response(mcp: &mut TestAppServer, request_id: i64) -> Result<J
.await?
}
async fn assert_remote_control_disabled_by_requirements(
mcp: &mut TestAppServer,
request_id: i64,
) -> Result<()> {
let JSONRPCError { error, .. } = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.code, -32600);
assert_eq!(
error.message,
REMOTE_CONTROL_DISABLED_BY_REQUIREMENTS_MESSAGE
);
Ok(())
}
#[tokio::test]
async fn managed_requirements_reject_all_remote_control_rpcs() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"allow_remote_control = false\n",
)?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let notification = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_notification_message("remoteControl/status/changed"),
)
.await??;
let status: RemoteControlStatusChangedNotification = serde_json::from_value(
notification
.params
.context("remote-control status notification should include params")?,
)?;
assert_eq!(status.status, RemoteControlConnectionStatus::Disabled);
assert_eq!(status.environment_id, None);
let request_ids = [
mcp.send_remote_control_enable_request().await?,
mcp.send_remote_control_disable_request().await?,
mcp.send_remote_control_status_read_request().await?,
mcp.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
manual_code: false,
})
.await?,
mcp.send_remote_control_pairing_status_request(RemoteControlPairingStatusParams {
pairing_code: Some("pairing-code".to_string()),
manual_pairing_code: None,
})
.await?,
mcp.send_remote_control_clients_list_request(RemoteControlClientsListParams {
environment_id: "environment-id".to_string(),
cursor: None,
limit: None,
order: None,
})
.await?,
mcp.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
environment_id: "environment-id".to_string(),
client_id: "client-id".to_string(),
})
.await?,
];
for request_id in request_ids {
assert_remote_control_disabled_by_requirements(&mut mcp, request_id).await?;
}
Ok(())
}
#[tokio::test]
async fn managed_requirements_allow_remote_control_true_does_not_enable_or_block_it() -> Result<()>
{
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"allow_remote_control = true\n",
)?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp.send_remote_control_status_read_request().await?;
let response = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let received: RemoteControlStatusReadResponse = to_response(response)?;
assert_eq!(received.status, RemoteControlConnectionStatus::Disabled);
Ok(())
}
#[tokio::test]
#[serial]
async fn explicit_remote_control_startup_fails_when_disabled_by_requirements() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"allow_remote_control = false\n",
)?;
let managed_config_path = codex_home.path().join("managed_config.toml");
let socket_path = codex_home.path().join("app-server.sock");
let transport =
AppServerTransport::from_listen_url(&format!("unix://{}", socket_path.display()))?;
let _codex_home_guard = EnvVarGuard::set("CODEX_HOME", codex_home.path().as_os_str());
let result = timeout(
STARTUP_TIMEOUT,
run_main_with_transport_options(
Arg0DispatchPaths {
codex_self_exe: Some(std::env::current_exe()?),
codex_linux_sandbox_exe: None,
main_execve_wrapper_exe: None,
},
CliConfigOverrides::default(),
LoaderOverrides::with_managed_config_path_for_tests(managed_config_path),
/*strict_config*/ false,
/*default_analytics_enabled*/ false,
transport,
SessionSource::VSCode,
AppServerWebsocketAuthSettings::default(),
AppServerRuntimeOptions {
plugin_startup_tasks: PluginStartupTasks::Skip,
remote_control_startup_mode: RemoteControlStartupMode::EnabledEphemeral,
install_shutdown_signal_handler: false,
},
),
)
.await?;
let err = result.expect_err("managed requirements should reject explicit remote control");
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(
err.to_string(),
REMOTE_CONTROL_DISABLED_BY_REQUIREMENTS_MESSAGE
);
assert!(!socket_path.exists());
Ok(())
}
#[tokio::test]
async fn listen_off_honors_persisted_remote_control_enable() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -88,6 +275,54 @@ async fn listen_off_honors_persisted_remote_control_enable() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn listen_off_ignores_persisted_enable_when_disabled_by_requirements() -> Result<()> {
let codex_home = TempDir::new()?;
let listener = configured_remote_control_listener(codex_home.path()).await?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"allow_remote_control = false\n",
)?;
let websocket_url = format!(
"ws://{}/backend-api/wham/remote/control/server",
listener.local_addr()?
);
let state_db =
StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".to_string()).await?;
state_db
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
websocket_url: websocket_url.clone(),
account_id: "account_id".to_string(),
app_server_client_name: None,
server_id: "server-id".to_string(),
environment_id: "environment-id".to_string(),
server_name: "server-name".to_string(),
remote_control_enabled: Some(true),
})
.await?;
let mut app_server =
TestAppServer::new_with_args(codex_home.path(), &["--listen", "off"]).await?;
let status = timeout(STARTUP_TIMEOUT, app_server.wait_for_exit()).await??;
assert!(!status.success());
timeout(Duration::from_millis(100), listener.accept())
.await
.expect_err("managed requirements should prevent a remote-control connection");
assert_eq!(
state_db
.get_remote_control_enrollment(
&websocket_url,
"account_id",
/*app_server_client_name*/ None
)
.await?
.context("enrollment should remain persisted")?
.remote_control_enabled,
Some(true)
);
Ok(())
}
#[tokio::test]
async fn listen_off_exits_without_persisted_remote_control_enable() -> Result<()> {
for persisted_preference in [None, Some(false)] {