mirror of
https://github.com/openai/codex.git
synced 2026-11-24 15:21:20 +00:00
Bind remote-control sessions to their authentication owner (#44341)
## Why Remote-control connections and queued operations must not carry over to a different signed-in user or account. Token refreshes for the same identity should preserve the live relay connection. ## What changed - Scope relay state and authentication recovery to a login lifetime. Retire the session on logout or identity changes and leave remote control disabled until enabled again. - Reject stale incoming messages and queued RPCs, and cancel pending remote-control operations when their authentication owner changes. - Start replacement sessions with fresh client, replay, and enrollment state, and prevent retired sessions from publishing status into their replacements. - Serialize enrollment and preference persistence across sessions, retaining write permits through caller cancellation and draining admitted writes on shutdown. ## Testing Add regression coverage for same-owner refreshes, user and account changes, stale pairing and client-revocation work, unauthorized enrollment recovery after logging in again, and persistence during cancellation. GitOrigin-RevId: 5e6ecd23588aab1e2e6168a21f575fb24bbb341c
This commit is contained in:
1 parent
d390f0a09c
commit
1bff94edb6
24 files changed
+1487
-441
No files matched your search
@@ -0,0 +1,51 @@
|
|||||||
|
//! Binds a transport connection to the authentication owner that established it.
|
||||||
|
//! Owner revisions invalidate queued work even before transport closure is delivered.
|
||||||
|
|
||||||
|
use codex_login::AuthChangeState;
|
||||||
|
use codex_login::AuthManager;
|
||||||
|
use std::io;
|
||||||
|
use tokio::sync::watch;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ConnectionAuth {
|
||||||
|
changes: watch::Receiver<AuthChangeState>,
|
||||||
|
owner_generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnectionAuth {
|
||||||
|
pub(crate) fn capture(auth_manager: &AuthManager) -> Self {
|
||||||
|
let changes = auth_manager.auth_change_state_receiver();
|
||||||
|
let owner_generation = changes.borrow().owner_generation;
|
||||||
|
Self::new(changes, owner_generation)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_current(&self) -> io::Result<()> {
|
||||||
|
if self.is_current() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::new(
|
||||||
|
io::ErrorKind::Interrupted,
|
||||||
|
"remote control authentication changed",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn new(changes: watch::Receiver<AuthChangeState>, owner_generation: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
changes,
|
||||||
|
owner_generation,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_current(&self) -> bool {
|
||||||
|
self.changes.borrow().owner_generation == self.owner_generation
|
||||||
|
&& self.changes.has_changed().is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn invalidated(&self) {
|
||||||
|
let mut changes = self.changes.clone();
|
||||||
|
let _ = changes
|
||||||
|
.wait_for(|state| state.owner_generation != self.owner_generation)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,9 +7,11 @@ pub use daemon_shutdown::DAEMON_SHUTDOWN_FILE_ENV;
|
|||||||
pub use daemon_shutdown::daemon_shutdown_signal;
|
pub use daemon_shutdown::daemon_shutdown_signal;
|
||||||
/// Only managed app-server launches accept the local socket shutdown request.
|
/// Only managed app-server launches accept the local socket shutdown request.
|
||||||
pub const DAEMON_SHUTDOWN_SOCKET_ENV: &str = "CODEX_DAEMON_SHUTDOWN_SOCKET";
|
pub const DAEMON_SHUTDOWN_SOCKET_ENV: &str = "CODEX_DAEMON_SHUTDOWN_SOCKET";
|
||||||
|
mod connection_auth;
|
||||||
mod outgoing_message;
|
mod outgoing_message;
|
||||||
mod transport;
|
mod transport;
|
||||||
|
|
||||||
|
pub use connection_auth::ConnectionAuth;
|
||||||
pub use outgoing_message::ConnectionId;
|
pub use outgoing_message::ConnectionId;
|
||||||
pub use outgoing_message::OutgoingError;
|
pub use outgoing_message::OutgoingError;
|
||||||
pub use outgoing_message::OutgoingMessage;
|
pub use outgoing_message::OutgoingMessage;
|
||||||
|
|||||||
@@ -184,6 +184,7 @@ pub enum TransportEvent {
|
|||||||
ConnectionOpened {
|
ConnectionOpened {
|
||||||
connection_id: ConnectionId,
|
connection_id: ConnectionId,
|
||||||
origin: ConnectionOrigin,
|
origin: ConnectionOrigin,
|
||||||
|
auth: Option<crate::ConnectionAuth>,
|
||||||
writer: mpsc::Sender<QueuedOutgoingMessage>,
|
writer: mpsc::Sender<QueuedOutgoingMessage>,
|
||||||
disconnect_sender: Option<CancellationToken>,
|
disconnect_sender: Option<CancellationToken>,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
//! Credentials and recovery bound to one remote-control login lifetime.
|
||||||
|
//! A request can refresh credentials, but cannot adopt a replacement authentication owner.
|
||||||
|
|
||||||
use axum::http::HeaderMap;
|
use axum::http::HeaderMap;
|
||||||
use axum::http::HeaderValue;
|
use axum::http::HeaderValue;
|
||||||
use codex_api::SharedAuthProvider;
|
use codex_api::SharedAuthProvider;
|
||||||
@@ -10,6 +13,46 @@ use tokio::sync::watch;
|
|||||||
use tracing::info;
|
use tracing::info;
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(super) struct RemoteControlAuth {
|
||||||
|
manager: Arc<AuthManager>,
|
||||||
|
pub(super) owner: crate::ConnectionAuth,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct RemoteControlRecovery {
|
||||||
|
auth: RemoteControlAuth,
|
||||||
|
recovery: UnauthorizedRecovery,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControlAuth {
|
||||||
|
pub(super) fn capture(manager: Arc<AuthManager>) -> (Self, bool) {
|
||||||
|
loop {
|
||||||
|
let owner = crate::ConnectionAuth::capture(&manager);
|
||||||
|
let authenticated = manager
|
||||||
|
.auth_cached()
|
||||||
|
.is_some_and(|auth| auth.uses_codex_backend() && auth.get_account_id().is_some());
|
||||||
|
if owner.is_current() {
|
||||||
|
return (Self { manager, owner }, authenticated);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn ensure_current(&self) -> io::Result<()> {
|
||||||
|
self.owner.ensure_current()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn unauthorized_recovery(&self) -> RemoteControlRecovery {
|
||||||
|
RemoteControlRecovery {
|
||||||
|
auth: self.clone(),
|
||||||
|
recovery: self.manager.unauthorized_recovery(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn auth_change_receiver(&self) -> watch::Receiver<u64> {
|
||||||
|
self.manager.auth_change_receiver()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id";
|
pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id";
|
||||||
|
|
||||||
pub(super) struct RemoteControlConnectionAuth {
|
pub(super) struct RemoteControlConnectionAuth {
|
||||||
@@ -35,6 +78,15 @@ impl RemoteControlConnectionAuth {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn load_remote_control_auth(
|
pub(super) async fn load_remote_control_auth(
|
||||||
|
auth: &RemoteControlAuth,
|
||||||
|
) -> io::Result<RemoteControlConnectionAuth> {
|
||||||
|
auth.ensure_current()?;
|
||||||
|
let credentials = load_auth_manager(&auth.manager).await?;
|
||||||
|
auth.ensure_current()?;
|
||||||
|
Ok(credentials)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load_auth_manager(
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &Arc<AuthManager>,
|
||||||
) -> io::Result<RemoteControlConnectionAuth> {
|
) -> io::Result<RemoteControlConnectionAuth> {
|
||||||
let mut reloaded = false;
|
let mut reloaded = false;
|
||||||
@@ -80,9 +132,13 @@ pub(super) async fn load_remote_control_auth(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn recover_remote_control_auth(
|
pub(super) async fn recover_remote_control_auth(
|
||||||
auth_recovery: &mut UnauthorizedRecovery,
|
recovery: &mut RemoteControlRecovery,
|
||||||
auth_change_rx: &mut watch::Receiver<u64>,
|
auth_change_rx: &mut watch::Receiver<u64>,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
|
if recovery.auth.ensure_current().is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let auth_recovery = &mut recovery.recovery;
|
||||||
if !auth_recovery.has_next() {
|
if !auth_recovery.has_next() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -92,6 +148,9 @@ pub(super) async fn recover_remote_control_auth(
|
|||||||
let auth_change_revision_before_recovery = *auth_change_rx.borrow();
|
let auth_change_revision_before_recovery = *auth_change_rx.borrow();
|
||||||
match auth_recovery.next().await {
|
match auth_recovery.next().await {
|
||||||
Ok(step_result) => {
|
Ok(step_result) => {
|
||||||
|
if recovery.auth.ensure_current().is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if step_result.auth_state_changed() == Some(true) {
|
if step_result.auth_state_changed() == Some(true) {
|
||||||
mark_recovery_auth_change_seen(
|
mark_recovery_auth_change_seen(
|
||||||
auth_change_rx,
|
auth_change_rx,
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ struct ClientState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct ClientTracker {
|
pub(crate) struct ClientTracker {
|
||||||
|
pub(super) auth: Option<crate::ConnectionAuth>,
|
||||||
clients: HashMap<(ClientId, StreamId), ClientState>,
|
clients: HashMap<(ClientId, StreamId), ClientState>,
|
||||||
legacy_stream_ids: HashMap<ClientId, StreamId>,
|
legacy_stream_ids: HashMap<ClientId, StreamId>,
|
||||||
join_set: JoinSet<(ClientId, StreamId)>,
|
join_set: JoinSet<(ClientId, StreamId)>,
|
||||||
@@ -58,6 +59,7 @@ impl ClientTracker {
|
|||||||
shutdown_token: &CancellationToken,
|
shutdown_token: &CancellationToken,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
auth: None,
|
||||||
clients: HashMap::new(),
|
clients: HashMap::new(),
|
||||||
legacy_stream_ids: HashMap::new(),
|
legacy_stream_ids: HashMap::new(),
|
||||||
join_set: JoinSet::new(),
|
join_set: JoinSet::new(),
|
||||||
@@ -168,6 +170,7 @@ impl ClientTracker {
|
|||||||
self.send_transport_event(TransportEvent::ConnectionOpened {
|
self.send_transport_event(TransportEvent::ConnectionOpened {
|
||||||
connection_id,
|
connection_id,
|
||||||
origin: ConnectionOrigin::RemoteControl,
|
origin: ConnectionOrigin::RemoteControl,
|
||||||
|
auth: self.auth.clone(),
|
||||||
writer: writer_tx,
|
writer: writer_tx,
|
||||||
disconnect_sender: Some(disconnect_token.clone()),
|
disconnect_sender: Some(disconnect_token.clone()),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use super::auth::RemoteControlAuth;
|
||||||
use super::auth::RemoteControlConnectionAuth;
|
use super::auth::RemoteControlConnectionAuth;
|
||||||
use super::auth::load_remote_control_auth;
|
use super::auth::load_remote_control_auth;
|
||||||
use super::auth::recover_remote_control_auth;
|
use super::auth::recover_remote_control_auth;
|
||||||
@@ -11,12 +12,10 @@ use codex_app_server_protocol::RemoteControlClientsListParams;
|
|||||||
use codex_app_server_protocol::RemoteControlClientsListResponse;
|
use codex_app_server_protocol::RemoteControlClientsListResponse;
|
||||||
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
|
||||||
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||||
use codex_login::AuthManager;
|
|
||||||
use codex_login::default_client::create_client_without_request_logging;
|
use codex_login::default_client::create_client_without_request_logging;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::io::ErrorKind;
|
use std::io::ErrorKind;
|
||||||
use std::sync::Arc;
|
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use time::format_description::well_known::Rfc3339;
|
use time::format_description::well_known::Rfc3339;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
@@ -68,7 +67,7 @@ struct ClientManagementResponse {
|
|||||||
|
|
||||||
pub(super) async fn list_remote_control_clients(
|
pub(super) async fn list_remote_control_clients(
|
||||||
remote_control_url: &str,
|
remote_control_url: &str,
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &RemoteControlAuth,
|
||||||
params: RemoteControlClientsListParams,
|
params: RemoteControlClientsListParams,
|
||||||
) -> io::Result<RemoteControlClientsListResponse> {
|
) -> io::Result<RemoteControlClientsListResponse> {
|
||||||
if params.environment_id.is_empty() {
|
if params.environment_id.is_empty() {
|
||||||
@@ -123,7 +122,7 @@ pub(super) async fn list_remote_control_clients(
|
|||||||
|
|
||||||
pub(super) async fn revoke_remote_control_client(
|
pub(super) async fn revoke_remote_control_client(
|
||||||
remote_control_url: &str,
|
remote_control_url: &str,
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &RemoteControlAuth,
|
||||||
params: RemoteControlClientsRevokeParams,
|
params: RemoteControlClientsRevokeParams,
|
||||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||||
if params.environment_id.is_empty() {
|
if params.environment_id.is_empty() {
|
||||||
@@ -164,7 +163,7 @@ pub(super) async fn revoke_remote_control_client(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn send_client_management_request(
|
async fn send_client_management_request(
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &RemoteControlAuth,
|
||||||
request: ClientManagementRequest<'_>,
|
request: ClientManagementRequest<'_>,
|
||||||
action: &str,
|
action: &str,
|
||||||
) -> io::Result<ClientManagementResponse> {
|
) -> io::Result<ClientManagementResponse> {
|
||||||
|
|||||||
@@ -0,0 +1,368 @@
|
|||||||
|
//! Owns the current login's relay session and the process-facing handle.
|
||||||
|
//! Replacement happens before cleanup; retired sessions cannot publish into their replacements.
|
||||||
|
|
||||||
|
use super::auth::RemoteControlAuth;
|
||||||
|
use super::*;
|
||||||
|
use futures::FutureExt;
|
||||||
|
use std::panic::AssertUnwindSafe;
|
||||||
|
use tokio_util::task::TaskTracker;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RemoteControlHandle {
|
||||||
|
pub(super) inner: Arc<RemoteControl>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CurrentSession {
|
||||||
|
authenticated: bool,
|
||||||
|
session: Arc<RemoteControlSession>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct RemoteControl {
|
||||||
|
config: RemoteControlStartConfig,
|
||||||
|
state_db: Option<Arc<StateRuntime>>,
|
||||||
|
auth_manager: Arc<AuthManager>,
|
||||||
|
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||||
|
shutdown: CancellationToken,
|
||||||
|
tasks: TaskTracker,
|
||||||
|
current: StdMutex<Option<CurrentSession>>,
|
||||||
|
startup: RemoteControlDesiredState,
|
||||||
|
persistence: RemoteControlPersistence,
|
||||||
|
client_name: RemoteControlPairingPersistenceKey,
|
||||||
|
requires_client_name: bool,
|
||||||
|
status: watch::Sender<RemoteControlStatusChangedNotification>,
|
||||||
|
session_changed: watch::Sender<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControl {
|
||||||
|
pub(super) fn session(&self) -> Arc<RemoteControlSession> {
|
||||||
|
let mut current = self
|
||||||
|
.current
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
if let Some(current) = current.as_ref()
|
||||||
|
&& current.session.auth_manager.owner.is_current()
|
||||||
|
{
|
||||||
|
return current.session.clone();
|
||||||
|
}
|
||||||
|
let (auth, authenticated) = RemoteControlAuth::capture(self.auth_manager.clone());
|
||||||
|
let desired = match current.take() {
|
||||||
|
Some(previous) => {
|
||||||
|
previous.session.shutdown_token.cancel();
|
||||||
|
if previous.authenticated {
|
||||||
|
RemoteControlDesiredState::Disabled
|
||||||
|
} else {
|
||||||
|
// Startup or an explicit enable while signed out may wait for first login.
|
||||||
|
*previous.session.desired_state_tx.borrow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => self.startup,
|
||||||
|
};
|
||||||
|
let session = self.start_session(auth, desired);
|
||||||
|
self.status.send_replace(session.status());
|
||||||
|
*current = Some(CurrentSession {
|
||||||
|
authenticated,
|
||||||
|
session: session.clone(),
|
||||||
|
});
|
||||||
|
self.session_changed.send_replace(());
|
||||||
|
session
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_session(
|
||||||
|
&self,
|
||||||
|
auth_manager: RemoteControlAuth,
|
||||||
|
desired: RemoteControlDesiredState,
|
||||||
|
) -> Arc<RemoteControlSession> {
|
||||||
|
let shutdown = self.shutdown.child_token();
|
||||||
|
let (desired_state_tx, _) = watch::channel(desired);
|
||||||
|
let desired_state_tx = Arc::new(desired_state_tx);
|
||||||
|
let current_enrollment =
|
||||||
|
Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None));
|
||||||
|
let server_name = gethostname().to_string_lossy().trim().to_string();
|
||||||
|
let (status_tx, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||||
|
status: if desired.is_enabled() {
|
||||||
|
RemoteControlConnectionStatus::Connecting
|
||||||
|
} else {
|
||||||
|
RemoteControlConnectionStatus::Disabled
|
||||||
|
},
|
||||||
|
server_name: server_name.clone(),
|
||||||
|
installation_id: self.config.installation_id.clone(),
|
||||||
|
environment_id: None,
|
||||||
|
});
|
||||||
|
let session = Arc::new(RemoteControlSession {
|
||||||
|
policy: self.config.policy,
|
||||||
|
shutdown_token: shutdown.clone(),
|
||||||
|
desired_state_tx: desired_state_tx.clone(),
|
||||||
|
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||||
|
persistence: self.persistence.clone(),
|
||||||
|
status_tx: Arc::new(status_tx.clone()),
|
||||||
|
state_db: self.state_db.clone(),
|
||||||
|
remote_control_url: self.config.remote_control_url.clone(),
|
||||||
|
current_enrollment: current_enrollment.clone(),
|
||||||
|
pairing_persistence_key: self.client_name.clone(),
|
||||||
|
pairing_persistence_key_required: self.requires_client_name,
|
||||||
|
auth_manager: auth_manager.clone(),
|
||||||
|
});
|
||||||
|
let websocket = RemoteControlWebsocket::new(
|
||||||
|
websocket::RemoteControlWebsocketConfig {
|
||||||
|
remote_control_url: self.config.remote_control_url.clone(),
|
||||||
|
installation_id: self.config.installation_id.clone(),
|
||||||
|
remote_control_target: None,
|
||||||
|
server_name,
|
||||||
|
},
|
||||||
|
self.state_db.clone(),
|
||||||
|
auth_manager,
|
||||||
|
RemoteControlChannels {
|
||||||
|
transport_event_tx: self.transport_event_tx.clone(),
|
||||||
|
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
||||||
|
current_enrollment,
|
||||||
|
pairing_persistence_key: self.client_name.clone(),
|
||||||
|
persistence: self.persistence.clone(),
|
||||||
|
},
|
||||||
|
shutdown.clone(),
|
||||||
|
desired_state_tx,
|
||||||
|
);
|
||||||
|
let client_name_rx = if self.requires_client_name {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
let mut names = self.client_name.subscribe();
|
||||||
|
self.tasks.spawn(async move {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.cancelled() => {}
|
||||||
|
name = names.wait_for(Option::is_some) => {
|
||||||
|
if let Ok(name) = name
|
||||||
|
&& let Some(name) = name.as_ref()
|
||||||
|
{
|
||||||
|
let _ = tx.send(name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Some(rx)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let process_shutdown = self.shutdown.clone();
|
||||||
|
let failed_session = session.clone();
|
||||||
|
self.tasks.spawn(async move {
|
||||||
|
if let Err(panic) = AssertUnwindSafe(websocket.run(client_name_rx))
|
||||||
|
.catch_unwind()
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!("remote control websocket task panicked");
|
||||||
|
failed_session.publish_status(RemoteControlConnectionStatus::Disabled);
|
||||||
|
process_shutdown.cancel();
|
||||||
|
std::panic::resume_unwind(panic);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
session
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControlSession {
|
||||||
|
async fn run<T>(
|
||||||
|
&self,
|
||||||
|
operation: impl std::future::Future<Output = io::Result<T>>,
|
||||||
|
) -> io::Result<T> {
|
||||||
|
self.auth_manager.ensure_current()?;
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = self.auth_manager.owner.invalidated() => {
|
||||||
|
Err(io::Error::new(io::ErrorKind::Interrupted, "remote control authentication changed"))
|
||||||
|
}
|
||||||
|
result = operation => {
|
||||||
|
self.auth_manager.ensure_current()?;
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControlHandle {
|
||||||
|
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||||
|
self.inner.session().ensure_remote_control_allowed()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(&self) -> RemoteControlStatusChangedNotification {
|
||||||
|
self.inner.session().status()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status_receiver(&self) -> watch::Receiver<RemoteControlStatusChangedNotification> {
|
||||||
|
self.inner.session();
|
||||||
|
self.inner.status.subscribe()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn enable_ephemeral(
|
||||||
|
&self,
|
||||||
|
) -> Result<RemoteControlStatusChangedNotification, RemoteControlEnableError> {
|
||||||
|
self.inner.session().enable_ephemeral()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn disable_ephemeral(&self) -> RemoteControlStatusChangedNotification {
|
||||||
|
self.inner.session().disable_ephemeral().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn enable(
|
||||||
|
&self,
|
||||||
|
app_server_client_name: Option<&str>,
|
||||||
|
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session.run(session.enable(app_server_client_name)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn disable(
|
||||||
|
&self,
|
||||||
|
app_server_client_name: Option<&str>,
|
||||||
|
) -> io::Result<RemoteControlStatusChangedNotification> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session.run(session.disable(app_server_client_name)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn resolve_persisted_preference(
|
||||||
|
&self,
|
||||||
|
app_server_client_name: Option<&str>,
|
||||||
|
) -> io::Result<bool> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session
|
||||||
|
.run(session.resolve_persisted_preference(app_server_client_name))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start_pairing(
|
||||||
|
&self,
|
||||||
|
params: RemoteControlPairingStartParams,
|
||||||
|
app_server_client_name: Option<&str>,
|
||||||
|
) -> io::Result<RemoteControlPairingStartResponse> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session
|
||||||
|
.run(session.start_pairing(params, app_server_client_name))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn pairing_status(
|
||||||
|
&self,
|
||||||
|
params: RemoteControlPairingStatusParams,
|
||||||
|
) -> io::Result<RemoteControlPairingStatusResponse> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session.run(session.pairing_status(params)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_clients(
|
||||||
|
&self,
|
||||||
|
params: RemoteControlClientsListParams,
|
||||||
|
) -> io::Result<RemoteControlClientsListResponse> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session.run(session.list_clients(params)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_client(
|
||||||
|
&self,
|
||||||
|
params: RemoteControlClientsRevokeParams,
|
||||||
|
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||||
|
let session = self.inner.session();
|
||||||
|
session.run(session.revoke_client(params)).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start_remote_control(
|
||||||
|
config: RemoteControlStartConfig,
|
||||||
|
state_db: Option<Arc<StateRuntime>>,
|
||||||
|
auth_manager: Arc<AuthManager>,
|
||||||
|
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||||
|
shutdown_token: CancellationToken,
|
||||||
|
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||||
|
startup_mode: RemoteControlStartupMode,
|
||||||
|
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||||
|
let startup =
|
||||||
|
if config.policy == RemoteControlPolicy::DisabledByRequirements || state_db.is_none() {
|
||||||
|
RemoteControlDesiredState::Disabled
|
||||||
|
} else {
|
||||||
|
match startup_mode {
|
||||||
|
RemoteControlStartupMode::ResolvePersisted => RemoteControlDesiredState::Unknown,
|
||||||
|
RemoteControlStartupMode::DisabledEphemeral => RemoteControlDesiredState::Disabled,
|
||||||
|
RemoteControlStartupMode::EnabledEphemeral => {
|
||||||
|
normalize_remote_control_url(&config.remote_control_url)?;
|
||||||
|
RemoteControlDesiredState::Enabled {
|
||||||
|
persistence_preference: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (status, _) = watch::channel(RemoteControlStatusChangedNotification {
|
||||||
|
status: RemoteControlConnectionStatus::Disabled,
|
||||||
|
server_name: gethostname().to_string_lossy().trim().to_string(),
|
||||||
|
installation_id: config.installation_id.clone(),
|
||||||
|
environment_id: None,
|
||||||
|
});
|
||||||
|
let inner = Arc::new(RemoteControl {
|
||||||
|
config,
|
||||||
|
state_db,
|
||||||
|
auth_manager,
|
||||||
|
transport_event_tx,
|
||||||
|
shutdown: shutdown_token,
|
||||||
|
tasks: TaskTracker::new(),
|
||||||
|
current: StdMutex::new(None),
|
||||||
|
startup,
|
||||||
|
persistence: RemoteControlPersistence::default(),
|
||||||
|
client_name: watch::channel(None).0,
|
||||||
|
requires_client_name: app_server_client_name_rx.is_some(),
|
||||||
|
status,
|
||||||
|
session_changed: watch::channel(()).0,
|
||||||
|
});
|
||||||
|
inner.session();
|
||||||
|
if let Some(rx) = app_server_client_name_rx {
|
||||||
|
let names = inner.client_name.clone();
|
||||||
|
let shutdown = inner.shutdown.clone();
|
||||||
|
inner.tasks.spawn(async move {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.cancelled() => {}
|
||||||
|
name = rx => match name {
|
||||||
|
Ok(name) => { names.send_replace(Some(name)); }
|
||||||
|
Err(_) => shutdown.cancel(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let handle = RemoteControlHandle {
|
||||||
|
inner: inner.clone(),
|
||||||
|
};
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
let mut session_changed = inner.session_changed.subscribe();
|
||||||
|
loop {
|
||||||
|
// Reconcile on both API entry and notification delivery, so watcher latency is harmless.
|
||||||
|
let session = inner.session();
|
||||||
|
let mut status = session.status_receiver();
|
||||||
|
session_changed.borrow_and_update();
|
||||||
|
{
|
||||||
|
let current = inner
|
||||||
|
.current
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
if current
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|current| Arc::ptr_eq(¤t.session, &session))
|
||||||
|
&& session.auth_manager.owner.is_current()
|
||||||
|
{
|
||||||
|
inner.status.send_if_modified(|current| {
|
||||||
|
let next = status.borrow_and_update().clone();
|
||||||
|
if *current == next {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*current = next;
|
||||||
|
true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = inner.shutdown.cancelled() => break,
|
||||||
|
_ = session.auth_manager.owner.invalidated() => {}
|
||||||
|
_ = session_changed.changed() => {}
|
||||||
|
_ = status.changed() => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inner.tasks.close();
|
||||||
|
inner.tasks.wait().await;
|
||||||
|
inner.persistence.tasks.close();
|
||||||
|
inner.persistence.tasks.wait().await;
|
||||||
|
});
|
||||||
|
Ok((task, handle))
|
||||||
|
}
|
||||||
@@ -1,15 +1,12 @@
|
|||||||
use super::RemoteControlEnableError;
|
use super::RemoteControlEnableError;
|
||||||
use super::RemoteControlHandle;
|
use super::RemoteControlSession;
|
||||||
use super::RemoteControlUnavailable;
|
use super::RemoteControlUnavailable;
|
||||||
use super::enroll::update_persisted_remote_control_enrollment;
|
|
||||||
use super::protocol::normalize_remote_control_url;
|
use super::protocol::normalize_remote_control_url;
|
||||||
use super::publish_current_enrollment;
|
use super::publish_current_enrollment;
|
||||||
use super::websocket::RemoteControlStatusPublisher;
|
use super::websocket::RemoteControlStatusPublisher;
|
||||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||||
use codex_state::RemoteControlEnrollmentRecord;
|
use codex_state::RemoteControlEnrollmentRecord;
|
||||||
use std::io;
|
use std::io;
|
||||||
use tokio::sync::Semaphore;
|
|
||||||
use tokio::sync::SemaphorePermit;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub(super) enum RemoteControlDesiredState {
|
pub(super) enum RemoteControlDesiredState {
|
||||||
@@ -31,10 +28,6 @@ impl RemoteControlDesiredState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn acquire_persistence_lock(lock: &Semaphore) -> SemaphorePermit<'_> {
|
|
||||||
lock.acquire().await.unwrap_or_else(|_| unreachable!())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn desired_state_from_persisted_enrollment(
|
pub(super) fn desired_state_from_persisted_enrollment(
|
||||||
enrollment: Option<RemoteControlEnrollmentRecord>,
|
enrollment: Option<RemoteControlEnrollmentRecord>,
|
||||||
) -> RemoteControlDesiredState {
|
) -> RemoteControlDesiredState {
|
||||||
@@ -47,7 +40,7 @@ pub(super) fn desired_state_from_persisted_enrollment(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RemoteControlHandle {
|
impl RemoteControlSession {
|
||||||
pub async fn resolve_persisted_preference(
|
pub async fn resolve_persisted_preference(
|
||||||
&self,
|
&self,
|
||||||
app_server_client_name: Option<&str>,
|
app_server_client_name: Option<&str>,
|
||||||
@@ -74,6 +67,8 @@ impl RemoteControlHandle {
|
|||||||
let auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
let auth = super::auth::load_remote_control_auth(&self.auth_manager).await?;
|
||||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||||
|
let _persistence =
|
||||||
|
super::persistence::read_lock(&self.auth_manager, &self.persistence).await?;
|
||||||
let enrollment = state_db
|
let enrollment = state_db
|
||||||
.get_remote_control_enrollment(
|
.get_remote_control_enrollment(
|
||||||
&remote_control_target.websocket_url,
|
&remote_control_target.websocket_url,
|
||||||
@@ -133,31 +128,20 @@ impl RemoteControlHandle {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
self.set_preference(
|
||||||
let updated = state_db
|
state_db,
|
||||||
.set_remote_control_enabled(
|
&remote_control_target,
|
||||||
&remote_control_target.websocket_url,
|
&auth.account_id,
|
||||||
&auth.account_id,
|
app_server_client_name,
|
||||||
app_server_client_name,
|
/*enabled*/ true,
|
||||||
/*remote_control_enabled*/ true,
|
Some(&enrollment),
|
||||||
)
|
)
|
||||||
.await
|
.await?;
|
||||||
.map_err(io::Error::other)?;
|
|
||||||
if updated == 0 {
|
|
||||||
update_persisted_remote_control_enrollment(
|
|
||||||
Some(state_db),
|
|
||||||
&remote_control_target,
|
|
||||||
&auth.account_id,
|
|
||||||
app_server_client_name,
|
|
||||||
Some(&enrollment),
|
|
||||||
Some(true),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
publish_current_enrollment(&mut current_enrollment, &enrollment);
|
publish_current_enrollment(&mut current_enrollment, &enrollment);
|
||||||
self.enable_with_preference(Some(true)).map_err(|err| {
|
self.enable_with_preference(Some(true)).map_err(|err| {
|
||||||
let kind = match err {
|
let kind = match err {
|
||||||
RemoteControlEnableError::Unavailable(_) => io::ErrorKind::NotFound,
|
RemoteControlEnableError::Unavailable(_) => io::ErrorKind::NotFound,
|
||||||
|
RemoteControlEnableError::AuthenticationChanged => io::ErrorKind::Interrupted,
|
||||||
RemoteControlEnableError::DisabledByRequirements(_) => {
|
RemoteControlEnableError::DisabledByRequirements(_) => {
|
||||||
io::ErrorKind::PermissionDenied
|
io::ErrorKind::PermissionDenied
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
mod auth;
|
mod auth;
|
||||||
mod client_tracker;
|
mod client_tracker;
|
||||||
mod clients;
|
mod clients;
|
||||||
|
mod controller;
|
||||||
|
mod persistence;
|
||||||
|
pub use controller::RemoteControlHandle;
|
||||||
|
pub use controller::start_remote_control;
|
||||||
mod desired_state;
|
mod desired_state;
|
||||||
mod enroll;
|
mod enroll;
|
||||||
mod host_device;
|
mod host_device;
|
||||||
@@ -12,10 +16,9 @@ mod websocket;
|
|||||||
use self::auth::load_remote_control_auth;
|
use self::auth::load_remote_control_auth;
|
||||||
use self::auth::recover_remote_control_auth;
|
use self::auth::recover_remote_control_auth;
|
||||||
use self::desired_state::RemoteControlDesiredState;
|
use self::desired_state::RemoteControlDesiredState;
|
||||||
use self::desired_state::acquire_persistence_lock;
|
|
||||||
use self::enroll::RemoteControlEnrollment;
|
use self::enroll::RemoteControlEnrollment;
|
||||||
use self::enroll::load_persisted_remote_control_enrollment;
|
use self::enroll::load_persisted_remote_control_enrollment;
|
||||||
use self::enroll::update_persisted_remote_control_enrollment;
|
use self::persistence::RemoteControlPersistence;
|
||||||
use self::server_api::enroll_remote_control_server;
|
use self::server_api::enroll_remote_control_server;
|
||||||
use self::server_api::refresh_remote_control_server;
|
use self::server_api::refresh_remote_control_server;
|
||||||
use crate::transport::remote_control::websocket::RemoteControlChannels;
|
use crate::transport::remote_control::websocket::RemoteControlChannels;
|
||||||
@@ -42,14 +45,12 @@ use codex_app_server_protocol::RemoteControlPairingStatusResponse;
|
|||||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||||
use codex_login::AuthManager;
|
use codex_login::AuthManager;
|
||||||
use codex_state::StateRuntime;
|
use codex_state::StateRuntime;
|
||||||
use futures::FutureExt;
|
|
||||||
use gethostname::gethostname;
|
use gethostname::gethostname;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::ops::DerefMut;
|
use std::ops::DerefMut;
|
||||||
use std::panic::AssertUnwindSafe;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::Mutex as StdMutex;
|
use std::sync::Mutex as StdMutex;
|
||||||
use tokio::sync::Semaphore;
|
use tokio::sync::Semaphore;
|
||||||
@@ -59,7 +60,6 @@ use tokio::sync::oneshot;
|
|||||||
use tokio::sync::watch;
|
use tokio::sync::watch;
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use tracing::error;
|
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
@@ -104,19 +104,19 @@ pub(super) struct QueuedServerEnvelope {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RemoteControlHandle {
|
struct RemoteControlSession {
|
||||||
policy: RemoteControlPolicy,
|
policy: RemoteControlPolicy,
|
||||||
shutdown_token: CancellationToken,
|
shutdown_token: CancellationToken,
|
||||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||||
desired_state_rpc_lock: Arc<Semaphore>,
|
desired_state_rpc_lock: Arc<Semaphore>,
|
||||||
desired_state_persistence_lock: Arc<Semaphore>,
|
persistence: RemoteControlPersistence,
|
||||||
status_tx: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
status_tx: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
||||||
state_db: Option<Arc<StateRuntime>>,
|
state_db: Option<Arc<StateRuntime>>,
|
||||||
remote_control_url: String,
|
remote_control_url: String,
|
||||||
current_enrollment: CurrentRemoteControlEnrollment,
|
current_enrollment: CurrentRemoteControlEnrollment,
|
||||||
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||||
pairing_persistence_key_required: bool,
|
pairing_persistence_key_required: bool,
|
||||||
auth_manager: Arc<AuthManager>,
|
auth_manager: auth::RemoteControlAuth,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pairing and websocket connect share one selected server so they cannot enroll or replace
|
// Pairing and websocket connect share one selected server so they cannot enroll or replace
|
||||||
@@ -262,6 +262,7 @@ impl Error for RemoteControlDisabledByRequirements {}
|
|||||||
pub enum RemoteControlEnableError {
|
pub enum RemoteControlEnableError {
|
||||||
Unavailable(RemoteControlUnavailable),
|
Unavailable(RemoteControlUnavailable),
|
||||||
DisabledByRequirements(RemoteControlDisabledByRequirements),
|
DisabledByRequirements(RemoteControlDisabledByRequirements),
|
||||||
|
AuthenticationChanged,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for RemoteControlEnableError {
|
impl fmt::Display for RemoteControlEnableError {
|
||||||
@@ -269,13 +270,14 @@ impl fmt::Display for RemoteControlEnableError {
|
|||||||
match self {
|
match self {
|
||||||
Self::Unavailable(err) => err.fmt(f),
|
Self::Unavailable(err) => err.fmt(f),
|
||||||
Self::DisabledByRequirements(err) => err.fmt(f),
|
Self::DisabledByRequirements(err) => err.fmt(f),
|
||||||
|
Self::AuthenticationChanged => f.write_str("remote control authentication changed"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for RemoteControlEnableError {}
|
impl Error for RemoteControlEnableError {}
|
||||||
|
|
||||||
impl RemoteControlHandle {
|
impl RemoteControlSession {
|
||||||
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||||
match self.policy {
|
match self.policy {
|
||||||
RemoteControlPolicy::Allowed => Ok(()),
|
RemoteControlPolicy::Allowed => Ok(()),
|
||||||
@@ -308,6 +310,9 @@ impl RemoteControlHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut effective_persistence_preference = persistence_preference;
|
let mut effective_persistence_preference = persistence_preference;
|
||||||
|
self.auth_manager
|
||||||
|
.ensure_current()
|
||||||
|
.map_err(|_| RemoteControlEnableError::AuthenticationChanged)?;
|
||||||
let desired_state_changed = self.desired_state_tx.send_if_modified(|state| {
|
let desired_state_changed = self.desired_state_tx.send_if_modified(|state| {
|
||||||
if effective_persistence_preference.is_none()
|
if effective_persistence_preference.is_none()
|
||||||
&& matches!(
|
&& matches!(
|
||||||
@@ -357,7 +362,6 @@ impl RemoteControlHandle {
|
|||||||
.acquire()
|
.acquire()
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| unreachable!());
|
.unwrap_or_else(|_| unreachable!());
|
||||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
|
||||||
self.persist_preference(
|
self.persist_preference(
|
||||||
app_server_client_name,
|
app_server_client_name,
|
||||||
/*remote_control_enabled*/ false,
|
/*remote_control_enabled*/ false,
|
||||||
@@ -372,7 +376,7 @@ impl RemoteControlHandle {
|
|||||||
.acquire()
|
.acquire()
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| unreachable!());
|
.unwrap_or_else(|_| unreachable!());
|
||||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
let _persistence = self.persistence.lock().await;
|
||||||
self.transition_disabled()
|
self.transition_disabled()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,15 +410,15 @@ impl RemoteControlHandle {
|
|||||||
let auth = load_remote_control_auth(&self.auth_manager).await?;
|
let auth = load_remote_control_auth(&self.auth_manager).await?;
|
||||||
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
let remote_control_target = normalize_remote_control_url(&self.remote_control_url)?;
|
||||||
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
let app_server_client_name = self.pairing_persistence_key(app_server_client_name)?;
|
||||||
state_db
|
self.set_preference(
|
||||||
.set_remote_control_enabled(
|
state_db,
|
||||||
&remote_control_target.websocket_url,
|
&remote_control_target,
|
||||||
&auth.account_id,
|
&auth.account_id,
|
||||||
app_server_client_name.as_deref(),
|
app_server_client_name.as_deref(),
|
||||||
remote_control_enabled,
|
remote_control_enabled,
|
||||||
)
|
/*fallback_enrollment*/ None,
|
||||||
.await
|
)
|
||||||
.map_err(io::Error::other)?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -578,22 +582,13 @@ impl RemoteControlHandle {
|
|||||||
.state_db
|
.state_db
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.ok_or_else(pairing_unavailable_error)?;
|
.ok_or_else(pairing_unavailable_error)?;
|
||||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
persistence::save_enrollment(
|
||||||
let persistence_preference = match *self.desired_state_tx.borrow() {
|
&self.auth_manager,
|
||||||
RemoteControlDesiredState::Enabled {
|
&self.persistence,
|
||||||
persistence_preference,
|
state_db,
|
||||||
} => persistence_preference,
|
&enrollment,
|
||||||
RemoteControlDesiredState::Unknown | RemoteControlDesiredState::Disabled => {
|
|
||||||
return Err(Self::pairing_disabled_error());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
update_persisted_remote_control_enrollment(
|
|
||||||
Some(state_db),
|
|
||||||
&enrollment.remote_control_target,
|
|
||||||
&auth.account_id,
|
|
||||||
app_server_client_name,
|
app_server_client_name,
|
||||||
Some(&enrollment),
|
&self.desired_state_tx,
|
||||||
persistence_preference,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
publish_current_enrollment(current_enrollment, &enrollment);
|
publish_current_enrollment(current_enrollment, &enrollment);
|
||||||
@@ -624,6 +619,8 @@ impl RemoteControlHandle {
|
|||||||
.state_db
|
.state_db
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.ok_or_else(pairing_unavailable_error)?;
|
.ok_or_else(pairing_unavailable_error)?;
|
||||||
|
let _persistence =
|
||||||
|
persistence::read_lock(&self.auth_manager, &self.persistence).await?;
|
||||||
if let Some(mut enrollment) = load_persisted_remote_control_enrollment(
|
if let Some(mut enrollment) = load_persisted_remote_control_enrollment(
|
||||||
Some(state_db),
|
Some(state_db),
|
||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
@@ -840,7 +837,7 @@ impl RemoteControlHandle {
|
|||||||
|
|
||||||
async fn enroll_pairing_server(
|
async fn enroll_pairing_server(
|
||||||
current_enrollment: &RemoteControlEnrollmentState,
|
current_enrollment: &RemoteControlEnrollmentState,
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &auth::RemoteControlAuth,
|
||||||
auth: &mut auth::RemoteControlConnectionAuth,
|
auth: &mut auth::RemoteControlConnectionAuth,
|
||||||
remote_control_target: &protocol::RemoteControlTarget,
|
remote_control_target: &protocol::RemoteControlTarget,
|
||||||
installation_id: &str,
|
installation_id: &str,
|
||||||
@@ -889,7 +886,7 @@ fn remote_control_pairing_status_code(
|
|||||||
|
|
||||||
async fn refresh_pairing_enrollment(
|
async fn refresh_pairing_enrollment(
|
||||||
current_enrollment: &mut RemoteControlEnrollmentLease<'_>,
|
current_enrollment: &mut RemoteControlEnrollmentLease<'_>,
|
||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &auth::RemoteControlAuth,
|
||||||
auth: &mut auth::RemoteControlConnectionAuth,
|
auth: &mut auth::RemoteControlConnectionAuth,
|
||||||
installation_id: &str,
|
installation_id: &str,
|
||||||
enrollment: &mut RemoteControlEnrollment,
|
enrollment: &mut RemoteControlEnrollment,
|
||||||
@@ -999,162 +996,6 @@ fn same_remote_control_enrollment(
|
|||||||
&& left.environment_id == right.environment_id
|
&& left.environment_id == right.environment_id
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_remote_control(
|
|
||||||
config: RemoteControlStartConfig,
|
|
||||||
state_db: Option<Arc<StateRuntime>>,
|
|
||||||
auth_manager: Arc<AuthManager>,
|
|
||||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
|
||||||
shutdown_token: CancellationToken,
|
|
||||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
|
||||||
startup_mode: RemoteControlStartupMode,
|
|
||||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
|
||||||
let policy = config.policy;
|
|
||||||
let state_db_available = state_db.is_some();
|
|
||||||
let requested_initial_enabled = startup_mode == RemoteControlStartupMode::EnabledEphemeral;
|
|
||||||
let desired_state =
|
|
||||||
if policy == RemoteControlPolicy::DisabledByRequirements || !state_db_available {
|
|
||||||
RemoteControlDesiredState::Disabled
|
|
||||||
} else {
|
|
||||||
match startup_mode {
|
|
||||||
RemoteControlStartupMode::ResolvePersisted => RemoteControlDesiredState::Unknown,
|
|
||||||
RemoteControlStartupMode::DisabledEphemeral => RemoteControlDesiredState::Disabled,
|
|
||||||
RemoteControlStartupMode::EnabledEphemeral => RemoteControlDesiredState::Enabled {
|
|
||||||
persistence_preference: None,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let initial_enabled = desired_state.is_enabled();
|
|
||||||
if requested_initial_enabled && !state_db_available {
|
|
||||||
warn!("remote control disabled because sqlite state db is unavailable");
|
|
||||||
}
|
|
||||||
let remote_control_target = if initial_enabled {
|
|
||||||
Some(normalize_remote_control_url(&config.remote_control_url)?)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let (desired_state_tx, _desired_state_rx) = watch::channel(desired_state);
|
|
||||||
let desired_state_tx = Arc::new(desired_state_tx);
|
|
||||||
let desired_state_rpc_lock = Arc::new(Semaphore::new(1));
|
|
||||||
let desired_state_persistence_lock = Arc::new(Semaphore::new(1));
|
|
||||||
let websocket_desired_state_tx = desired_state_tx.clone();
|
|
||||||
let websocket_desired_state_persistence_lock = desired_state_persistence_lock.clone();
|
|
||||||
let current_enrollment = Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None));
|
|
||||||
let websocket_current_enrollment = current_enrollment.clone();
|
|
||||||
let pairing_persistence_key_required = app_server_client_name_rx.is_some();
|
|
||||||
let (pairing_persistence_key, _pairing_persistence_key_rx) = watch::channel(None);
|
|
||||||
let websocket_pairing_persistence_key = pairing_persistence_key.clone();
|
|
||||||
let handle_auth_manager = auth_manager.clone();
|
|
||||||
let handle_state_db = state_db.clone();
|
|
||||||
let server_name = gethostname().to_string_lossy().trim().to_string();
|
|
||||||
let remote_control_url = config.remote_control_url;
|
|
||||||
let installation_id = config.installation_id;
|
|
||||||
let initial_status = RemoteControlStatusChangedNotification {
|
|
||||||
status: if initial_enabled {
|
|
||||||
RemoteControlConnectionStatus::Connecting
|
|
||||||
} else {
|
|
||||||
RemoteControlConnectionStatus::Disabled
|
|
||||||
},
|
|
||||||
server_name: server_name.clone(),
|
|
||||||
installation_id: installation_id.clone(),
|
|
||||||
environment_id: None,
|
|
||||||
};
|
|
||||||
let (status_tx, _status_rx) = watch::channel(initial_status);
|
|
||||||
let status_publisher = RemoteControlStatusPublisher::new(status_tx.clone());
|
|
||||||
info!(
|
|
||||||
remote_control_url = %remote_control_url,
|
|
||||||
installation_id = %installation_id,
|
|
||||||
server_name = %server_name,
|
|
||||||
state_db_available,
|
|
||||||
?desired_state,
|
|
||||||
"starting app-server remote control websocket task"
|
|
||||||
);
|
|
||||||
let remote_control_url_for_log = remote_control_url.clone();
|
|
||||||
let handle_remote_control_url = remote_control_url.clone();
|
|
||||||
let installation_id_for_log = installation_id.clone();
|
|
||||||
let server_name_for_log = server_name.clone();
|
|
||||||
let shutdown_token_for_log = shutdown_token.clone();
|
|
||||||
let handle_shutdown_token = shutdown_token.clone();
|
|
||||||
let join_handle = tokio::spawn(async move {
|
|
||||||
info!(
|
|
||||||
remote_control_url = %remote_control_url_for_log,
|
|
||||||
installation_id = %installation_id_for_log,
|
|
||||||
server_name = %server_name_for_log,
|
|
||||||
?desired_state,
|
|
||||||
"app-server remote control websocket task started"
|
|
||||||
);
|
|
||||||
let websocket_task = RemoteControlWebsocket::new(
|
|
||||||
websocket::RemoteControlWebsocketConfig {
|
|
||||||
remote_control_url,
|
|
||||||
installation_id,
|
|
||||||
remote_control_target,
|
|
||||||
server_name,
|
|
||||||
},
|
|
||||||
state_db,
|
|
||||||
auth_manager,
|
|
||||||
RemoteControlChannels {
|
|
||||||
transport_event_tx,
|
|
||||||
status_publisher,
|
|
||||||
current_enrollment: websocket_current_enrollment,
|
|
||||||
pairing_persistence_key: websocket_pairing_persistence_key,
|
|
||||||
desired_state_persistence_lock: websocket_desired_state_persistence_lock,
|
|
||||||
},
|
|
||||||
shutdown_token,
|
|
||||||
websocket_desired_state_tx,
|
|
||||||
)
|
|
||||||
.run(app_server_client_name_rx);
|
|
||||||
match AssertUnwindSafe(websocket_task).catch_unwind().await {
|
|
||||||
Ok(()) => {
|
|
||||||
let shutdown_requested = shutdown_token_for_log.is_cancelled();
|
|
||||||
if shutdown_requested {
|
|
||||||
info!(
|
|
||||||
remote_control_url = %remote_control_url_for_log,
|
|
||||||
installation_id = %installation_id_for_log,
|
|
||||||
server_name = %server_name_for_log,
|
|
||||||
shutdown_requested,
|
|
||||||
"app-server remote control websocket task exited"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
warn!(
|
|
||||||
remote_control_url = %remote_control_url_for_log,
|
|
||||||
installation_id = %installation_id_for_log,
|
|
||||||
server_name = %server_name_for_log,
|
|
||||||
shutdown_requested,
|
|
||||||
"app-server remote control websocket task exited without shutdown"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(panic) => {
|
|
||||||
error!(
|
|
||||||
remote_control_url = %remote_control_url_for_log,
|
|
||||||
installation_id = %installation_id_for_log,
|
|
||||||
server_name = %server_name_for_log,
|
|
||||||
"app-server remote control websocket task panicked"
|
|
||||||
);
|
|
||||||
std::panic::resume_unwind(panic);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok((
|
|
||||||
join_handle,
|
|
||||||
RemoteControlHandle {
|
|
||||||
policy,
|
|
||||||
shutdown_token: handle_shutdown_token,
|
|
||||||
desired_state_tx,
|
|
||||||
desired_state_rpc_lock,
|
|
||||||
desired_state_persistence_lock,
|
|
||||||
status_tx: Arc::new(status_tx),
|
|
||||||
state_db: handle_state_db,
|
|
||||||
remote_control_url: handle_remote_control_url,
|
|
||||||
current_enrollment,
|
|
||||||
pairing_persistence_key,
|
|
||||||
pairing_persistence_key_required,
|
|
||||||
auth_manager: handle_auth_manager,
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod segment_tests;
|
mod segment_tests;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
//! Serializes enrollment storage across login sessions.
|
||||||
|
//! An admitted SQLite write keeps its permit until completion even if its caller is cancelled.
|
||||||
|
//! Process shutdown drains admitted writes after stopping the session workers.
|
||||||
|
|
||||||
|
use super::RemoteControlSession;
|
||||||
|
use super::auth::RemoteControlAuth;
|
||||||
|
use super::desired_state::RemoteControlDesiredState;
|
||||||
|
use super::enroll::RemoteControlEnrollment;
|
||||||
|
use super::enroll::update_persisted_remote_control_enrollment;
|
||||||
|
use super::protocol::RemoteControlTarget;
|
||||||
|
use codex_state::StateRuntime;
|
||||||
|
use std::future::Future;
|
||||||
|
use std::io;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::sync::Semaphore;
|
||||||
|
use tokio::sync::SemaphorePermit;
|
||||||
|
use tokio::sync::watch;
|
||||||
|
use tokio_util::task::TaskTracker;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "persistence_tests.rs"]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(super) struct RemoteControlPersistence {
|
||||||
|
semaphore: Arc<Semaphore>,
|
||||||
|
pub(super) tasks: TaskTracker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RemoteControlPersistence {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
semaphore: Arc::new(Semaphore::new(1)),
|
||||||
|
tasks: TaskTracker::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControlPersistence {
|
||||||
|
pub(super) async fn lock(&self) -> SemaphorePermit<'_> {
|
||||||
|
self.semaphore
|
||||||
|
.acquire()
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| unreachable!())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn read_lock<'a>(
|
||||||
|
auth: &RemoteControlAuth,
|
||||||
|
lock: &'a RemoteControlPersistence,
|
||||||
|
) -> io::Result<SemaphorePermit<'a>> {
|
||||||
|
let permit = lock.lock().await;
|
||||||
|
auth.ensure_current()?;
|
||||||
|
Ok(permit)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn commit<T: Send + 'static>(
|
||||||
|
auth: &RemoteControlAuth,
|
||||||
|
lock: &RemoteControlPersistence,
|
||||||
|
operation: impl Future<Output = io::Result<T>> + Send + 'static,
|
||||||
|
) -> io::Result<T> {
|
||||||
|
// Register before checking admission. Shutdown either observes this token or rejects us.
|
||||||
|
let task = lock.tasks.token();
|
||||||
|
if lock.tasks.is_closed() {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::Interrupted,
|
||||||
|
"remote control is shutting down",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let auth = auth.clone();
|
||||||
|
let semaphore = lock.semaphore.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _task = task;
|
||||||
|
let _permit = semaphore.acquire_owned().await.map_err(io::Error::other)?;
|
||||||
|
auth.ensure_current()?;
|
||||||
|
operation.await
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(io::Error::other)?
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn save_enrollment(
|
||||||
|
auth: &RemoteControlAuth,
|
||||||
|
lock: &RemoteControlPersistence,
|
||||||
|
state_db: &StateRuntime,
|
||||||
|
enrollment: &RemoteControlEnrollment,
|
||||||
|
client_name: Option<&str>,
|
||||||
|
desired: &watch::Sender<RemoteControlDesiredState>,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let state_db = state_db.clone();
|
||||||
|
let enrollment = enrollment.clone();
|
||||||
|
let client_name = client_name.map(str::to_owned);
|
||||||
|
let desired = desired.clone();
|
||||||
|
commit(auth, lock, async move {
|
||||||
|
let preference = match *desired.borrow() {
|
||||||
|
RemoteControlDesiredState::Enabled {
|
||||||
|
persistence_preference,
|
||||||
|
} => persistence_preference,
|
||||||
|
RemoteControlDesiredState::Disabled | RemoteControlDesiredState::Unknown => {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::Interrupted,
|
||||||
|
"remote control disabled during enrollment",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
update_persisted_remote_control_enrollment(
|
||||||
|
Some(&state_db),
|
||||||
|
&enrollment.remote_control_target,
|
||||||
|
&enrollment.account_id,
|
||||||
|
client_name.as_deref(),
|
||||||
|
Some(&enrollment),
|
||||||
|
preference,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemoteControlSession {
|
||||||
|
pub(super) async fn set_preference(
|
||||||
|
&self,
|
||||||
|
state_db: &StateRuntime,
|
||||||
|
target: &RemoteControlTarget,
|
||||||
|
account_id: &str,
|
||||||
|
client_name: Option<&str>,
|
||||||
|
enabled: bool,
|
||||||
|
fallback_enrollment: Option<&RemoteControlEnrollment>,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let state_db = state_db.clone();
|
||||||
|
let target = target.clone();
|
||||||
|
let account_id = account_id.to_owned();
|
||||||
|
let client_name = client_name.map(str::to_owned);
|
||||||
|
let enrollment = fallback_enrollment.cloned();
|
||||||
|
let desired = self.desired_state_tx.as_ref().clone();
|
||||||
|
commit(&self.auth_manager, &self.persistence, async move {
|
||||||
|
let updated = state_db
|
||||||
|
.set_remote_control_enabled(
|
||||||
|
&target.websocket_url,
|
||||||
|
&account_id,
|
||||||
|
client_name.as_deref(),
|
||||||
|
enabled,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
if updated == 0
|
||||||
|
&& let Some(enrollment) = enrollment
|
||||||
|
{
|
||||||
|
update_persisted_remote_control_enrollment(
|
||||||
|
Some(&state_db),
|
||||||
|
&target,
|
||||||
|
&account_id,
|
||||||
|
client_name.as_deref(),
|
||||||
|
Some(&enrollment),
|
||||||
|
Some(enabled),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
if !enabled {
|
||||||
|
desired.send_replace(RemoteControlDesiredState::Disabled);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
//! Checks the persistence boundary when an operation loses its caller.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use codex_core::test_support::auth_manager_from_auth;
|
||||||
|
use codex_login::CodexAuth;
|
||||||
|
use futures::poll;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cancelled_commit_keeps_its_permit_and_is_drained() -> io::Result<()> {
|
||||||
|
let auth = RemoteControlAuth::capture(auth_manager_from_auth(
|
||||||
|
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||||
|
))
|
||||||
|
.0;
|
||||||
|
let persistence = RemoteControlPersistence::default();
|
||||||
|
let writes = Arc::new(tokio::sync::Mutex::new(Vec::new()));
|
||||||
|
let (started_tx, started_rx) = oneshot::channel();
|
||||||
|
let (release_tx, release_rx) = oneshot::channel();
|
||||||
|
let old_writes = writes.clone();
|
||||||
|
let mut old = Box::pin(commit(&auth, &persistence, async move {
|
||||||
|
started_tx.send(()).expect("test receiver is open");
|
||||||
|
release_rx.await.map_err(io::Error::other)?;
|
||||||
|
old_writes.lock().await.push("old");
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
assert!(poll!(&mut old).is_pending());
|
||||||
|
started_rx.await.map_err(io::Error::other)?;
|
||||||
|
drop(old);
|
||||||
|
|
||||||
|
let new_writes = writes.clone();
|
||||||
|
let mut new = Box::pin(commit(&auth, &persistence, async move {
|
||||||
|
new_writes.lock().await.push("new");
|
||||||
|
Ok(())
|
||||||
|
}));
|
||||||
|
assert!(poll!(&mut new).is_pending());
|
||||||
|
persistence.tasks.close();
|
||||||
|
let mut drained = Box::pin(persistence.tasks.wait());
|
||||||
|
assert!(poll!(&mut drained).is_pending());
|
||||||
|
release_tx.send(()).expect("commit still owns its receiver");
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(5), drained).await?;
|
||||||
|
new.await?;
|
||||||
|
assert_eq!(*writes.lock().await, vec!["old", "new"]);
|
||||||
|
let error = commit::<()>(&auth, &persistence, async {
|
||||||
|
panic!("closed storage must reject new work")
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect_err("shutdown closes admission");
|
||||||
|
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -138,6 +138,55 @@ async fn remote_control_state_runtime(codex_home: &TempDir) -> Arc<StateRuntime>
|
|||||||
.expect("state runtime should initialize")
|
.expect("state runtime should initialize")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn committed_disable_prevents_later_enrollment_from_restoring_preference() {
|
||||||
|
let home = TempDir::new().expect("temp dir");
|
||||||
|
let state_db = remote_control_state_runtime(&home).await;
|
||||||
|
let session = remote_control_handle_with_current_enrollment(
|
||||||
|
TEST_REMOTE_CONTROL_URL,
|
||||||
|
remote_control_auth_manager(),
|
||||||
|
);
|
||||||
|
let enrollment = session.current_enrollment.snapshot().expect("enrollment");
|
||||||
|
session
|
||||||
|
.desired_state_tx
|
||||||
|
.send_replace(RemoteControlDesiredState::Enabled {
|
||||||
|
persistence_preference: Some(true),
|
||||||
|
});
|
||||||
|
session
|
||||||
|
.set_preference(
|
||||||
|
&state_db,
|
||||||
|
&enrollment.remote_control_target,
|
||||||
|
&enrollment.account_id,
|
||||||
|
/*client_name*/ None,
|
||||||
|
/*enabled*/ false,
|
||||||
|
Some(&enrollment),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("disable commits");
|
||||||
|
// This is the window before the disable RPC resumes and publishes its status.
|
||||||
|
let error = persistence::save_enrollment(
|
||||||
|
&session.auth_manager,
|
||||||
|
&session.persistence,
|
||||||
|
&state_db,
|
||||||
|
&enrollment,
|
||||||
|
/*client_name*/ None,
|
||||||
|
&session.desired_state_tx,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect_err("enrollment cannot re-enable a committed disable");
|
||||||
|
assert_eq!(error.kind(), std::io::ErrorKind::Interrupted);
|
||||||
|
let saved = state_db
|
||||||
|
.get_remote_control_enrollment(
|
||||||
|
&enrollment.remote_control_target.websocket_url,
|
||||||
|
&enrollment.account_id,
|
||||||
|
/*app_server_client_name*/ None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("read preference")
|
||||||
|
.expect("saved enrollment");
|
||||||
|
assert_eq!(saved.remote_control_enabled, Some(false));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn plain_start_resolves_persisted_remote_control_preference() {
|
async fn plain_start_resolves_persisted_remote_control_preference() {
|
||||||
let cases = [
|
let cases = [
|
||||||
@@ -184,7 +233,7 @@ async fn plain_start_resolves_persisted_remote_control_preference() {
|
|||||||
server_name: test_server_name(),
|
server_name: test_server_name(),
|
||||||
},
|
},
|
||||||
Some(state_db),
|
Some(state_db),
|
||||||
remote_control_auth_manager(),
|
auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||||
RemoteControlChannels {
|
RemoteControlChannels {
|
||||||
transport_event_tx,
|
transport_event_tx,
|
||||||
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
||||||
@@ -192,7 +241,7 @@ async fn plain_start_resolves_persisted_remote_control_preference() {
|
|||||||
/*enrollment*/ None,
|
/*enrollment*/ None,
|
||||||
)),
|
)),
|
||||||
pairing_persistence_key: watch::channel(None).0,
|
pairing_persistence_key: watch::channel(None).0,
|
||||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
persistence: RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
CancellationToken::new(),
|
CancellationToken::new(),
|
||||||
desired_state_tx.clone(),
|
desired_state_tx.clone(),
|
||||||
@@ -251,8 +300,8 @@ async fn explicit_disabled_start_ignores_persisted_enable() {
|
|||||||
.expect("remote control should start disabled");
|
.expect("remote control should start disabled");
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
*remote_handle.desired_state_tx.borrow(),
|
remote_handle.status().status,
|
||||||
RemoteControlDesiredState::Disabled
|
RemoteControlConnectionStatus::Disabled
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
state_db
|
state_db
|
||||||
@@ -383,7 +432,7 @@ fn test_server_name() -> String {
|
|||||||
pub(super) fn remote_control_handle_with_current_enrollment(
|
pub(super) fn remote_control_handle_with_current_enrollment(
|
||||||
remote_control_url: &str,
|
remote_control_url: &str,
|
||||||
auth_manager: Arc<AuthManager>,
|
auth_manager: Arc<AuthManager>,
|
||||||
) -> RemoteControlHandle {
|
) -> RemoteControlSession {
|
||||||
let (desired_state_tx, _desired_state_rx) =
|
let (desired_state_tx, _desired_state_rx) =
|
||||||
watch::channel(RemoteControlDesiredState::Enabled {
|
watch::channel(RemoteControlDesiredState::Enabled {
|
||||||
persistence_preference: None,
|
persistence_preference: None,
|
||||||
@@ -411,19 +460,19 @@ pub(super) fn remote_control_handle_with_current_enrollment(
|
|||||||
next_refresh_at: None,
|
next_refresh_at: None,
|
||||||
},
|
},
|
||||||
)));
|
)));
|
||||||
RemoteControlHandle {
|
RemoteControlSession {
|
||||||
policy: RemoteControlPolicy::Allowed,
|
policy: RemoteControlPolicy::Allowed,
|
||||||
shutdown_token: CancellationToken::new(),
|
shutdown_token: CancellationToken::new(),
|
||||||
desired_state_tx: Arc::new(desired_state_tx),
|
desired_state_tx: Arc::new(desired_state_tx),
|
||||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
persistence: RemoteControlPersistence::default(),
|
||||||
status_tx: Arc::new(status_tx),
|
status_tx: Arc::new(status_tx),
|
||||||
state_db: None,
|
state_db: None,
|
||||||
remote_control_url: remote_control_url.to_string(),
|
remote_control_url: remote_control_url.to_string(),
|
||||||
current_enrollment,
|
current_enrollment,
|
||||||
pairing_persistence_key: watch::channel(None).0,
|
pairing_persistence_key: watch::channel(None).0,
|
||||||
pairing_persistence_key_required: false,
|
pairing_persistence_key_required: false,
|
||||||
auth_manager,
|
auth_manager: auth::RemoteControlAuth::capture(auth_manager).0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2291,15 +2340,18 @@ async fn persisted_enable_does_not_follow_auth_to_an_account_without_a_preferenc
|
|||||||
)
|
)
|
||||||
.expect("account B auth should save");
|
.expect("account B auth should save");
|
||||||
auth_manager.reload().await;
|
auth_manager.reload().await;
|
||||||
websocket
|
let closed = timeout(Duration::from_secs(1), websocket.next())
|
||||||
.close(None)
|
|
||||||
.await
|
.await
|
||||||
.expect("backend websocket should close");
|
.expect("account switch should close the backend websocket");
|
||||||
|
assert!(matches!(
|
||||||
|
closed,
|
||||||
|
None | Some(Err(_)) | Some(Ok(tungstenite::Message::Close(_)))
|
||||||
|
));
|
||||||
|
|
||||||
let mut desired_state_rx = remote_handle.desired_state_tx.subscribe();
|
let mut desired_state_rx = remote_handle.status_receiver();
|
||||||
timeout(
|
timeout(
|
||||||
Duration::from_secs(1),
|
Duration::from_secs(1),
|
||||||
desired_state_rx.wait_for(|state| *state == RemoteControlDesiredState::Disabled),
|
desired_state_rx.wait_for(|state| state.status == RemoteControlConnectionStatus::Disabled),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("account B missing preference should disable remote control")
|
.expect("account B missing preference should disable remote control")
|
||||||
@@ -2675,6 +2727,8 @@ async fn remote_control_http_mode_preserves_stale_enrollment_when_reenrollment_f
|
|||||||
.await;
|
.await;
|
||||||
|
|
||||||
let current_enrollment = remote_handle
|
let current_enrollment = remote_handle
|
||||||
|
.inner
|
||||||
|
.session()
|
||||||
.current_enrollment
|
.current_enrollment
|
||||||
.lock()
|
.lock()
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use pretty_assertions::assert_eq;
|
|||||||
fn client_management_handle(
|
fn client_management_handle(
|
||||||
remote_control_url: String,
|
remote_control_url: String,
|
||||||
auth_manager: Arc<AuthManager>,
|
auth_manager: Arc<AuthManager>,
|
||||||
) -> RemoteControlHandle {
|
) -> RemoteControlSession {
|
||||||
let desired_state_tx = watch::channel(RemoteControlDesiredState::Disabled).0;
|
let desired_state_tx = watch::channel(RemoteControlDesiredState::Disabled).0;
|
||||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||||
status: RemoteControlConnectionStatus::Disabled,
|
status: RemoteControlConnectionStatus::Disabled,
|
||||||
@@ -21,19 +21,19 @@ fn client_management_handle(
|
|||||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||||
environment_id: None,
|
environment_id: None,
|
||||||
});
|
});
|
||||||
RemoteControlHandle {
|
RemoteControlSession {
|
||||||
policy: RemoteControlPolicy::Allowed,
|
policy: RemoteControlPolicy::Allowed,
|
||||||
shutdown_token: CancellationToken::new(),
|
shutdown_token: CancellationToken::new(),
|
||||||
desired_state_tx: Arc::new(desired_state_tx),
|
desired_state_tx: Arc::new(desired_state_tx),
|
||||||
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
desired_state_rpc_lock: Arc::new(Semaphore::new(1)),
|
||||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
persistence: RemoteControlPersistence::default(),
|
||||||
status_tx: Arc::new(status_tx),
|
status_tx: Arc::new(status_tx),
|
||||||
state_db: None,
|
state_db: None,
|
||||||
remote_control_url,
|
remote_control_url,
|
||||||
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None)),
|
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None)),
|
||||||
pairing_persistence_key: watch::channel(None).0,
|
pairing_persistence_key: watch::channel(None).0,
|
||||||
pairing_persistence_key_required: false,
|
pairing_persistence_key_required: false,
|
||||||
auth_manager,
|
auth_manager: auth::RemoteControlAuth::capture(auth_manager).0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +225,7 @@ async fn list_remote_control_clients_recovers_auth_after_unauthorized() {
|
|||||||
|
|
||||||
let response = list_remote_control_clients(
|
let response = list_remote_control_clients(
|
||||||
&remote_control_url,
|
&remote_control_url,
|
||||||
&auth_manager,
|
&auth::RemoteControlAuth::capture(auth_manager.clone()).0,
|
||||||
RemoteControlClientsListParams {
|
RemoteControlClientsListParams {
|
||||||
environment_id: "env-123".to_string(),
|
environment_id: "env-123".to_string(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -323,7 +323,7 @@ async fn list_remote_control_clients_retries_unauthorized_only_once() {
|
|||||||
|
|
||||||
let err = list_remote_control_clients(
|
let err = list_remote_control_clients(
|
||||||
&remote_control_url,
|
&remote_control_url,
|
||||||
&auth_manager,
|
&auth::RemoteControlAuth::capture(auth_manager.clone()).0,
|
||||||
RemoteControlClientsListParams {
|
RemoteControlClientsListParams {
|
||||||
environment_id: "env-123".to_string(),
|
environment_id: "env-123".to_string(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -363,7 +363,7 @@ async fn revoke_remote_control_client_does_not_retry_forbidden() {
|
|||||||
|
|
||||||
let err = revoke_remote_control_client(
|
let err = revoke_remote_control_client(
|
||||||
&remote_control_url,
|
&remote_control_url,
|
||||||
&remote_control_auth_manager(),
|
&auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||||
RemoteControlClientsRevokeParams {
|
RemoteControlClientsRevokeParams {
|
||||||
environment_id: "env-123".to_string(),
|
environment_id: "env-123".to_string(),
|
||||||
client_id: "client-123".to_string(),
|
client_id: "client-123".to_string(),
|
||||||
@@ -395,7 +395,7 @@ async fn list_remote_control_clients_preserves_decode_error_context() {
|
|||||||
|
|
||||||
let err = list_remote_control_clients(
|
let err = list_remote_control_clients(
|
||||||
&remote_control_url,
|
&remote_control_url,
|
||||||
&remote_control_auth_manager(),
|
&auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||||
RemoteControlClientsListParams {
|
RemoteControlClientsListParams {
|
||||||
environment_id: "env-123".to_string(),
|
environment_id: "env-123".to_string(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
|||||||
@@ -33,6 +33,20 @@ async fn assert_overload_retry_after(status: &str, reject_enrollment: bool) {
|
|||||||
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
let (transport_event_tx, _transport_event_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||||
let shutdown_token = CancellationToken::new();
|
let shutdown_token = CancellationToken::new();
|
||||||
let auth_manager = remote_control_auth_manager_with_home(&codex_home);
|
let auth_manager = remote_control_auth_manager_with_home(&codex_home);
|
||||||
|
let mut initial_auth = remote_control_auth_dot_json(Some("account_id"));
|
||||||
|
initial_auth
|
||||||
|
.tokens
|
||||||
|
.as_mut()
|
||||||
|
.expect("fixture should contain tokens")
|
||||||
|
.access_token = "Initial Access Token".to_string();
|
||||||
|
save_auth(
|
||||||
|
codex_home.path(),
|
||||||
|
&initial_auth,
|
||||||
|
AuthCredentialsStoreMode::File,
|
||||||
|
AuthKeyringBackendKind::default(),
|
||||||
|
)
|
||||||
|
.expect("initial credentials should save");
|
||||||
|
auth_manager.reload().await;
|
||||||
let (remote_task, remote_handle) = start_remote_control(
|
let (remote_task, remote_handle) = start_remote_control(
|
||||||
RemoteControlStartConfig {
|
RemoteControlStartConfig {
|
||||||
remote_control_url: remote_control_url_for_listener(&listener),
|
remote_control_url: remote_control_url_for_listener(&listener),
|
||||||
@@ -144,6 +158,8 @@ async fn assert_overload_retry_after(status: &str, reject_enrollment: bool) {
|
|||||||
if !reject_enrollment {
|
if !reject_enrollment {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
remote_handle
|
remote_handle
|
||||||
|
.inner
|
||||||
|
.session()
|
||||||
.current_enrollment
|
.current_enrollment
|
||||||
.snapshot()
|
.snapshot()
|
||||||
.and_then(|enrollment| enrollment.remote_control_token),
|
.and_then(|enrollment| enrollment.remote_control_token),
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
use super::CurrentRemoteControlEnrollment;
|
use super::CurrentRemoteControlEnrollment;
|
||||||
use super::RemoteControlEnrollmentSelection;
|
use super::RemoteControlEnrollmentSelection;
|
||||||
use super::RemoteControlPairingPersistenceKey;
|
use super::RemoteControlPairingPersistenceKey;
|
||||||
|
use super::auth::RemoteControlAuth;
|
||||||
|
use super::auth::RemoteControlRecovery;
|
||||||
use super::desired_state::RemoteControlDesiredState;
|
use super::desired_state::RemoteControlDesiredState;
|
||||||
use super::desired_state::acquire_persistence_lock;
|
|
||||||
use super::desired_state::desired_state_from_persisted_enrollment;
|
use super::desired_state::desired_state_from_persisted_enrollment;
|
||||||
|
use super::persistence::RemoteControlPersistence;
|
||||||
use super::protocol::ClientEnvelope;
|
use super::protocol::ClientEnvelope;
|
||||||
use super::protocol::ClientEvent;
|
use super::protocol::ClientEvent;
|
||||||
use super::protocol::ClientId;
|
use super::protocol::ClientId;
|
||||||
@@ -26,7 +28,6 @@ use crate::transport::remote_control::enroll::RemoteControlEnrollment;
|
|||||||
use crate::transport::remote_control::enroll::format_headers;
|
use crate::transport::remote_control::enroll::format_headers;
|
||||||
use crate::transport::remote_control::enroll::load_persisted_remote_control_enrollment;
|
use crate::transport::remote_control::enroll::load_persisted_remote_control_enrollment;
|
||||||
use crate::transport::remote_control::enroll::preview_remote_control_response_body;
|
use crate::transport::remote_control::enroll::preview_remote_control_response_body;
|
||||||
use crate::transport::remote_control::enroll::update_persisted_remote_control_enrollment;
|
|
||||||
use crate::transport::remote_control::host_device::REMOTE_CONTROL_HOST_DEVICE_KIND_HEADER;
|
use crate::transport::remote_control::host_device::REMOTE_CONTROL_HOST_DEVICE_KIND_HEADER;
|
||||||
use crate::transport::remote_control::host_device::host_device_kind;
|
use crate::transport::remote_control::host_device::host_device_kind;
|
||||||
use crate::transport::remote_control::server_api::RemoteControlServerRequestError;
|
use crate::transport::remote_control::server_api::RemoteControlServerRequestError;
|
||||||
@@ -39,8 +40,6 @@ use base64::Engine;
|
|||||||
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
use codex_app_server_protocol::RemoteControlConnectionStatus;
|
||||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||||
use codex_core::util::backoff;
|
use codex_core::util::backoff;
|
||||||
use codex_login::AuthManager;
|
|
||||||
use codex_login::UnauthorizedRecovery;
|
|
||||||
use codex_state::StateRuntime;
|
use codex_state::StateRuntime;
|
||||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||||
use futures::SinkExt;
|
use futures::SinkExt;
|
||||||
@@ -54,7 +53,6 @@ use std::io::ErrorKind;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
use tokio::sync::Semaphore;
|
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use tokio::sync::oneshot;
|
use tokio::sync::oneshot;
|
||||||
use tokio::sync::watch;
|
use tokio::sync::watch;
|
||||||
@@ -256,17 +254,17 @@ impl WebsocketState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct RemoteControlWebsocket {
|
pub(super) struct RemoteControlWebsocket {
|
||||||
remote_control_url: String,
|
remote_control_url: String,
|
||||||
installation_id: String,
|
installation_id: String,
|
||||||
server_name: String,
|
server_name: String,
|
||||||
remote_control_target: Option<RemoteControlTarget>,
|
remote_control_target: Option<RemoteControlTarget>,
|
||||||
state_db: Option<Arc<StateRuntime>>,
|
state_db: Option<Arc<StateRuntime>>,
|
||||||
auth_manager: Arc<AuthManager>,
|
auth_manager: RemoteControlAuth,
|
||||||
status_publisher: RemoteControlStatusPublisher,
|
status_publisher: RemoteControlStatusPublisher,
|
||||||
shutdown_token: CancellationToken,
|
shutdown_token: CancellationToken,
|
||||||
reconnect_attempt: u64,
|
reconnect_attempt: u64,
|
||||||
auth_recovery: UnauthorizedRecovery,
|
auth_recovery: RemoteControlRecovery,
|
||||||
auth_change_rx: watch::Receiver<u64>,
|
auth_change_rx: watch::Receiver<u64>,
|
||||||
current_enrollment: CurrentRemoteControlEnrollment,
|
current_enrollment: CurrentRemoteControlEnrollment,
|
||||||
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||||
@@ -276,10 +274,10 @@ pub(crate) struct RemoteControlWebsocket {
|
|||||||
used_rx: watch::Receiver<usize>,
|
used_rx: watch::Receiver<usize>,
|
||||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||||
desired_state_rx: watch::Receiver<RemoteControlDesiredState>,
|
desired_state_rx: watch::Receiver<RemoteControlDesiredState>,
|
||||||
desired_state_persistence_lock: Arc<Semaphore>,
|
persistence: RemoteControlPersistence,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct RemoteControlWebsocketConfig {
|
pub(super) struct RemoteControlWebsocketConfig {
|
||||||
pub(crate) remote_control_url: String,
|
pub(crate) remote_control_url: String,
|
||||||
pub(crate) installation_id: String,
|
pub(crate) installation_id: String,
|
||||||
pub(crate) remote_control_target: Option<RemoteControlTarget>,
|
pub(crate) remote_control_target: Option<RemoteControlTarget>,
|
||||||
@@ -287,8 +285,8 @@ pub(crate) struct RemoteControlWebsocketConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) struct RemoteControlAuthContext<'a> {
|
pub(super) struct RemoteControlAuthContext<'a> {
|
||||||
auth_manager: &'a Arc<AuthManager>,
|
auth_manager: &'a RemoteControlAuth,
|
||||||
auth_recovery: &'a mut UnauthorizedRecovery,
|
auth_recovery: &'a mut RemoteControlRecovery,
|
||||||
auth_change_rx: &'a mut watch::Receiver<u64>,
|
auth_change_rx: &'a mut watch::Receiver<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,6 +303,7 @@ enum ConnectOutcome {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
enum ConnectionEndReason {
|
enum ConnectionEndReason {
|
||||||
|
AuthOwnerChanged,
|
||||||
Shutdown,
|
Shutdown,
|
||||||
Disabled,
|
Disabled,
|
||||||
EnabledWatchClosed,
|
EnabledWatchClosed,
|
||||||
@@ -316,7 +315,7 @@ pub(super) struct RemoteControlChannels {
|
|||||||
pub(super) status_publisher: RemoteControlStatusPublisher,
|
pub(super) status_publisher: RemoteControlStatusPublisher,
|
||||||
pub(super) current_enrollment: CurrentRemoteControlEnrollment,
|
pub(super) current_enrollment: CurrentRemoteControlEnrollment,
|
||||||
pub(super) pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
pub(super) pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||||
pub(super) desired_state_persistence_lock: Arc<Semaphore>,
|
pub(super) persistence: RemoteControlPersistence,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -399,14 +398,14 @@ pub(super) struct RemoteControlConnectOptions<'a> {
|
|||||||
subscribe_cursor: Option<&'a str>,
|
subscribe_cursor: Option<&'a str>,
|
||||||
app_server_client_name: Option<&'a str>,
|
app_server_client_name: Option<&'a str>,
|
||||||
desired_state_tx: &'a watch::Sender<RemoteControlDesiredState>,
|
desired_state_tx: &'a watch::Sender<RemoteControlDesiredState>,
|
||||||
desired_state_persistence_lock: &'a Semaphore,
|
persistence: &'a RemoteControlPersistence,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RemoteControlWebsocket {
|
impl RemoteControlWebsocket {
|
||||||
pub(crate) fn new(
|
pub(super) fn new(
|
||||||
config: RemoteControlWebsocketConfig,
|
config: RemoteControlWebsocketConfig,
|
||||||
state_db: Option<Arc<StateRuntime>>,
|
state_db: Option<Arc<StateRuntime>>,
|
||||||
auth_manager: Arc<AuthManager>,
|
auth_manager: RemoteControlAuth,
|
||||||
channels: RemoteControlChannels,
|
channels: RemoteControlChannels,
|
||||||
shutdown_token: CancellationToken,
|
shutdown_token: CancellationToken,
|
||||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||||
@@ -449,7 +448,7 @@ impl RemoteControlWebsocket {
|
|||||||
used_rx,
|
used_rx,
|
||||||
desired_state_tx,
|
desired_state_tx,
|
||||||
desired_state_rx,
|
desired_state_rx,
|
||||||
desired_state_persistence_lock: channels.desired_state_persistence_lock,
|
persistence: channels.persistence,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -457,10 +456,11 @@ impl RemoteControlWebsocket {
|
|||||||
clippy::await_holding_invalid_type,
|
clippy::await_holding_invalid_type,
|
||||||
reason = "remote-control client shutdown must serialize tracker state"
|
reason = "remote-control client shutdown must serialize tracker state"
|
||||||
)]
|
)]
|
||||||
pub(crate) async fn run(
|
pub(super) async fn run(
|
||||||
mut self,
|
mut self,
|
||||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||||
) {
|
) {
|
||||||
|
let auth_owner = self.auth_manager.owner.clone();
|
||||||
info!(
|
info!(
|
||||||
remote_control_url = %self.remote_control_url,
|
remote_control_url = %self.remote_control_url,
|
||||||
installation_id = %self.installation_id,
|
installation_id = %self.installation_id,
|
||||||
@@ -487,30 +487,7 @@ impl RemoteControlWebsocket {
|
|||||||
};
|
};
|
||||||
self.pairing_persistence_key
|
self.pairing_persistence_key
|
||||||
.send_replace(app_server_client_name.clone());
|
.send_replace(app_server_client_name.clone());
|
||||||
if matches!(
|
|
||||||
*self.desired_state_rx.borrow(),
|
|
||||||
RemoteControlDesiredState::Unknown
|
|
||||||
) && !self
|
|
||||||
.resolve_unknown_desired_state(app_server_client_name.as_deref())
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
self.client_tracker.lock().await.shutdown().await;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if !self.wait_until_enabled().await {
|
|
||||||
info!(
|
|
||||||
remote_control_url = %self.remote_control_url,
|
|
||||||
installation_id = %self.installation_id,
|
|
||||||
server_name = %self.server_name,
|
|
||||||
shutdown_requested = self.shutdown_token.is_cancelled(),
|
|
||||||
current_status = ?self.status_publisher.status().status,
|
|
||||||
"app-server remote control websocket loop exiting while waiting for enablement"
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
let status = self.status_publisher.status();
|
let status = self.status_publisher.status();
|
||||||
info!(
|
info!(
|
||||||
remote_control_url = %self.remote_control_url,
|
remote_control_url = %self.remote_control_url,
|
||||||
@@ -522,10 +499,23 @@ impl RemoteControlWebsocket {
|
|||||||
"starting app-server remote control websocket connection cycle"
|
"starting app-server remote control websocket connection cycle"
|
||||||
);
|
);
|
||||||
let shutdown_token = self.shutdown_token.child_token();
|
let shutdown_token = self.shutdown_token.child_token();
|
||||||
let websocket_connection = match self
|
let connect_outcome = tokio::select! {
|
||||||
.connect(&shutdown_token, app_server_client_name.as_deref())
|
biased;
|
||||||
.await
|
_ = shutdown_token.cancelled() => break,
|
||||||
{
|
_ = auth_owner.invalidated() => break,
|
||||||
|
outcome = async {
|
||||||
|
if matches!(*self.desired_state_rx.borrow(), RemoteControlDesiredState::Unknown)
|
||||||
|
&& !self.resolve_unknown_desired_state(app_server_client_name.as_deref()).await
|
||||||
|
{
|
||||||
|
return ConnectOutcome::Shutdown;
|
||||||
|
}
|
||||||
|
if !self.wait_until_enabled().await {
|
||||||
|
return ConnectOutcome::Shutdown;
|
||||||
|
}
|
||||||
|
self.connect(&shutdown_token, app_server_client_name.as_deref()).await
|
||||||
|
} => outcome,
|
||||||
|
};
|
||||||
|
let websocket_connection = match connect_outcome {
|
||||||
ConnectOutcome::Connected(websocket_connection) => *websocket_connection,
|
ConnectOutcome::Connected(websocket_connection) => *websocket_connection,
|
||||||
ConnectOutcome::Disabled => {
|
ConnectOutcome::Disabled => {
|
||||||
self.status_publisher
|
self.status_publisher
|
||||||
@@ -621,14 +611,20 @@ impl RemoteControlWebsocket {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let enrollment = match state_db
|
let _persistence =
|
||||||
|
match super::persistence::read_lock(&self.auth_manager, &self.persistence).await {
|
||||||
|
Ok(permit) => permit,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let enrollment = state_db
|
||||||
.get_remote_control_enrollment(
|
.get_remote_control_enrollment(
|
||||||
&remote_control_target.websocket_url,
|
&remote_control_target.websocket_url,
|
||||||
&auth.account_id,
|
&auth.account_id,
|
||||||
app_server_client_name,
|
app_server_client_name,
|
||||||
)
|
)
|
||||||
.await
|
.await;
|
||||||
{
|
drop(_persistence);
|
||||||
|
let enrollment = match enrollment {
|
||||||
Ok(enrollment) => enrollment,
|
Ok(enrollment) => enrollment,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!(
|
warn!(
|
||||||
@@ -724,7 +720,7 @@ impl RemoteControlWebsocket {
|
|||||||
subscribe_cursor: subscribe_cursor.as_deref(),
|
subscribe_cursor: subscribe_cursor.as_deref(),
|
||||||
app_server_client_name,
|
app_server_client_name,
|
||||||
desired_state_tx: &self.desired_state_tx,
|
desired_state_tx: &self.desired_state_tx,
|
||||||
desired_state_persistence_lock: &self.desired_state_persistence_lock,
|
persistence: &self.persistence,
|
||||||
};
|
};
|
||||||
let auth_context = RemoteControlAuthContext {
|
let auth_context = RemoteControlAuthContext {
|
||||||
auth_manager: &self.auth_manager,
|
auth_manager: &self.auth_manager,
|
||||||
@@ -846,6 +842,10 @@ impl RemoteControlWebsocket {
|
|||||||
websocket_connection: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
websocket_connection: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||||
shutdown_token: CancellationToken,
|
shutdown_token: CancellationToken,
|
||||||
) -> ConnectionEndReason {
|
) -> ConnectionEndReason {
|
||||||
|
if !self.auth_manager.owner.is_current() {
|
||||||
|
return ConnectionEndReason::AuthOwnerChanged;
|
||||||
|
}
|
||||||
|
self.client_tracker.lock().await.auth = Some(self.auth_manager.owner.clone());
|
||||||
let (websocket_writer, websocket_reader) = websocket_connection.split();
|
let (websocket_writer, websocket_reader) = websocket_connection.split();
|
||||||
let mut join_set = tokio::task::JoinSet::new();
|
let mut join_set = tokio::task::JoinSet::new();
|
||||||
|
|
||||||
@@ -867,7 +867,9 @@ impl RemoteControlWebsocket {
|
|||||||
|
|
||||||
let mut desired_state_rx = self.desired_state_rx.clone();
|
let mut desired_state_rx = self.desired_state_rx.clone();
|
||||||
let connection_end_reason = tokio::select! {
|
let connection_end_reason = tokio::select! {
|
||||||
|
biased;
|
||||||
_ = shutdown_token.cancelled() => ConnectionEndReason::Shutdown,
|
_ = shutdown_token.cancelled() => ConnectionEndReason::Shutdown,
|
||||||
|
_ = self.auth_manager.owner.invalidated() => ConnectionEndReason::AuthOwnerChanged,
|
||||||
changed = desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
changed = desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
||||||
if changed.is_ok() {
|
if changed.is_ok() {
|
||||||
self.status_publisher
|
self.status_publisher
|
||||||
@@ -1505,32 +1507,14 @@ async fn prepare_remote_control_enrollment(
|
|||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let enrollment_account_id = enrollment.as_ref().map(|enrollment| &enrollment.account_id);
|
if enrollment
|
||||||
if enrollment_account_id.is_some_and(|account_id| account_id != &auth.account_id) {
|
.as_ref()
|
||||||
resolve_desired_state_after_account_change(
|
.is_some_and(|enrollment| enrollment.account_id != auth.account_id)
|
||||||
state_db,
|
{
|
||||||
remote_control_target,
|
return Err(io::Error::new(
|
||||||
auth_context.auth_manager,
|
ErrorKind::Interrupted,
|
||||||
&auth.account_id,
|
"enrollment belongs to another remote session",
|
||||||
connect_options,
|
));
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
info!(
|
|
||||||
"clearing in-memory remote control enrollment because account id changed: websocket_url={}, previous_account_id={:?}, current_account_id={:?}",
|
|
||||||
remote_control_target.websocket_url,
|
|
||||||
enrollment
|
|
||||||
.as_ref()
|
|
||||||
.map(|enrollment| enrollment.account_id.as_str()),
|
|
||||||
auth.account_id
|
|
||||||
);
|
|
||||||
*enrollment = None;
|
|
||||||
status_publisher.publish_environment_id(/*environment_id*/ None);
|
|
||||||
if !connect_options.desired_state_tx.borrow().is_enabled() {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
ErrorKind::Interrupted,
|
|
||||||
"remote control disabled after account changed",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if let Some(enrollment) = enrollment.as_mut() {
|
if let Some(enrollment) = enrollment.as_mut() {
|
||||||
enrollment.remote_control_target = remote_control_target.clone();
|
enrollment.remote_control_target = remote_control_target.clone();
|
||||||
@@ -1541,6 +1525,9 @@ async fn prepare_remote_control_enrollment(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if enrollment.is_none() {
|
if enrollment.is_none() {
|
||||||
|
let _persistence =
|
||||||
|
super::persistence::read_lock(auth_context.auth_manager, connect_options.persistence)
|
||||||
|
.await?;
|
||||||
let loaded_enrollment = load_persisted_remote_control_enrollment(
|
let loaded_enrollment = load_persisted_remote_control_enrollment(
|
||||||
Some(state_db),
|
Some(state_db),
|
||||||
remote_control_target,
|
remote_control_target,
|
||||||
@@ -1637,51 +1624,6 @@ async fn prepare_remote_control_enrollment(
|
|||||||
Ok(auth)
|
Ok(auth)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn resolve_desired_state_after_account_change(
|
|
||||||
state_db: &StateRuntime,
|
|
||||||
remote_control_target: &RemoteControlTarget,
|
|
||||||
auth_manager: &Arc<AuthManager>,
|
|
||||||
account_id: &str,
|
|
||||||
connect_options: RemoteControlConnectOptions<'_>,
|
|
||||||
) -> io::Result<()> {
|
|
||||||
let durable_enabled = RemoteControlDesiredState::Enabled {
|
|
||||||
persistence_preference: Some(true),
|
|
||||||
};
|
|
||||||
if *connect_options.desired_state_tx.borrow() != durable_enabled {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let _persistence =
|
|
||||||
acquire_persistence_lock(connect_options.desired_state_persistence_lock).await;
|
|
||||||
if *connect_options.desired_state_tx.borrow() != durable_enabled {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let enrollment = state_db
|
|
||||||
.get_remote_control_enrollment(
|
|
||||||
&remote_control_target.websocket_url,
|
|
||||||
account_id,
|
|
||||||
connect_options.app_server_client_name,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(io::Error::other)?;
|
|
||||||
let current_auth = load_remote_control_auth(auth_manager).await?;
|
|
||||||
if current_auth.account_id != account_id {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
ErrorKind::WouldBlock,
|
|
||||||
"remote control account changed while resolving persisted preference",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let resolved_state = desired_state_from_persisted_enrollment(enrollment);
|
|
||||||
connect_options.desired_state_tx.send_if_modified(|state| {
|
|
||||||
if *state != durable_enabled || *state == resolved_state {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
*state = resolved_state;
|
|
||||||
true
|
|
||||||
});
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn websocket_response_reports_missing_remote_app_server(
|
fn websocket_response_reports_missing_remote_app_server(
|
||||||
response: &tungstenite::http::Response<Option<Vec<u8>>>,
|
response: &tungstenite::http::Response<Option<Vec<u8>>>,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
@@ -1799,33 +1741,15 @@ async fn enroll_and_persist_remote_control_server(
|
|||||||
}
|
}
|
||||||
Err(err) => return Err(err),
|
Err(err) => return Err(err),
|
||||||
};
|
};
|
||||||
let _persistence =
|
super::persistence::save_enrollment(
|
||||||
acquire_persistence_lock(connect_options.desired_state_persistence_lock).await;
|
auth_context.recovery.auth_manager,
|
||||||
let persistence_preference = match *connect_options.desired_state_tx.borrow() {
|
connect_options.persistence,
|
||||||
RemoteControlDesiredState::Enabled {
|
state_db,
|
||||||
persistence_preference,
|
&new_enrollment,
|
||||||
} => persistence_preference,
|
|
||||||
RemoteControlDesiredState::Unknown | RemoteControlDesiredState::Disabled => {
|
|
||||||
return Err(io::Error::new(
|
|
||||||
ErrorKind::Interrupted,
|
|
||||||
"remote control disabled during enrollment",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Err(err) = update_persisted_remote_control_enrollment(
|
|
||||||
Some(state_db),
|
|
||||||
remote_control_target,
|
|
||||||
&auth_context.auth.account_id,
|
|
||||||
connect_options.app_server_client_name,
|
connect_options.app_server_client_name,
|
||||||
Some(&new_enrollment),
|
connect_options.desired_state_tx,
|
||||||
persistence_preference,
|
|
||||||
)
|
)
|
||||||
.await
|
.await?;
|
||||||
{
|
|
||||||
return Err(io::Error::other(format!(
|
|
||||||
"failed to persist remote control enrollment in sqlite state db: {err}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
info!(
|
info!(
|
||||||
"created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
"created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||||
remote_control_target.websocket_url,
|
remote_control_target.websocket_url,
|
||||||
@@ -1881,6 +1805,7 @@ mod tests {
|
|||||||
use codex_core::test_support::auth_manager_from_auth;
|
use codex_core::test_support::auth_manager_from_auth;
|
||||||
use codex_login::AuthDotJson;
|
use codex_login::AuthDotJson;
|
||||||
use codex_login::AuthKeyringBackendKind;
|
use codex_login::AuthKeyringBackendKind;
|
||||||
|
use codex_login::AuthManager;
|
||||||
use codex_login::CodexAuth;
|
use codex_login::CodexAuth;
|
||||||
use codex_login::save_auth;
|
use codex_login::save_auth;
|
||||||
use codex_login::token_data::TokenData;
|
use codex_login::token_data::TokenData;
|
||||||
@@ -2155,7 +2080,8 @@ mod tests {
|
|||||||
let codex_home = TempDir::new().expect("temp dir should create");
|
let codex_home = TempDir::new().expect("temp dir should create");
|
||||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||||
let auth_manager = remote_control_auth_manager();
|
let auth_manager = remote_control_auth_manager();
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||||
@@ -2166,7 +2092,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
Some(state_db.as_ref()),
|
Some(state_db.as_ref()),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2177,7 +2103,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2212,7 +2138,8 @@ mod tests {
|
|||||||
let codex_home = TempDir::new().expect("temp dir should create");
|
let codex_home = TempDir::new().expect("temp dir should create");
|
||||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||||
let auth_manager = remote_control_auth_manager();
|
let auth_manager = remote_control_auth_manager();
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let next_refresh_at = time::OffsetDateTime::now_utc() + time::Duration::minutes(2);
|
let next_refresh_at = time::OffsetDateTime::now_utc() + time::Duration::minutes(2);
|
||||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||||
@@ -2233,7 +2160,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
Some(state_db.as_ref()),
|
Some(state_db.as_ref()),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2244,7 +2171,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2307,7 +2234,8 @@ mod tests {
|
|||||||
codex_login::test_support::transport_default_auth_route_config(),
|
codex_login::test_support::transport_default_auth_route_config(),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let current_enrollment = test_current_enrollment(/*enrollment*/ None);
|
let current_enrollment = test_current_enrollment(/*enrollment*/ None);
|
||||||
let (status_publisher, status_rx) = remote_control_status_channel();
|
let (status_publisher, status_rx) = remote_control_status_channel();
|
||||||
@@ -2323,7 +2251,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
Some(state_db.as_ref()),
|
Some(state_db.as_ref()),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2334,7 +2262,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2406,7 +2334,8 @@ mod tests {
|
|||||||
codex_login::test_support::transport_default_auth_route_config(),
|
codex_login::test_support::transport_default_auth_route_config(),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let mut expected_enrollment =
|
let mut expected_enrollment =
|
||||||
remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||||
@@ -2427,7 +2356,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
Some(state_db.as_ref()),
|
Some(state_db.as_ref()),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2438,7 +2367,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2484,7 +2413,8 @@ mod tests {
|
|||||||
let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/")
|
let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/")
|
||||||
.expect("target should parse");
|
.expect("target should parse");
|
||||||
let auth_manager = remote_control_auth_manager();
|
let auth_manager = remote_control_auth_manager();
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||||
@@ -2495,7 +2425,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
/*state_db*/ None,
|
/*state_db*/ None,
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2506,7 +2436,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2534,7 +2464,8 @@ mod tests {
|
|||||||
codex_login::test_support::transport_default_auth_route_config(),
|
codex_login::test_support::transport_default_auth_route_config(),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
let current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||||
@@ -2550,7 +2481,7 @@ mod tests {
|
|||||||
&remote_control_target,
|
&remote_control_target,
|
||||||
Some(state_db.as_ref()),
|
Some(state_db.as_ref()),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager: &auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -2561,7 +2492,7 @@ mod tests {
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &enabled_desired_state_sender(),
|
desired_state_tx: &enabled_desired_state_sender(),
|
||||||
desired_state_persistence_lock: &Semaphore::new(1),
|
persistence: &RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
@@ -2614,13 +2545,13 @@ mod tests {
|
|||||||
server_name: "test-server".to_string(),
|
server_name: "test-server".to_string(),
|
||||||
},
|
},
|
||||||
/*state_db*/ None,
|
/*state_db*/ None,
|
||||||
remote_control_auth_manager(),
|
RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||||
RemoteControlChannels {
|
RemoteControlChannels {
|
||||||
transport_event_tx,
|
transport_event_tx,
|
||||||
status_publisher,
|
status_publisher,
|
||||||
current_enrollment: test_current_enrollment(/*enrollment*/ None),
|
current_enrollment: test_current_enrollment(/*enrollment*/ None),
|
||||||
pairing_persistence_key: watch::channel(None).0,
|
pairing_persistence_key: watch::channel(None).0,
|
||||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
persistence: RemoteControlPersistence::default(),
|
||||||
},
|
},
|
||||||
shutdown_token,
|
shutdown_token,
|
||||||
Arc::new(desired_state_tx),
|
Arc::new(desired_state_tx),
|
||||||
|
|||||||
+6
-4
@@ -19,6 +19,7 @@ use codex_app_server_protocol::RemoteControlPairingStartParams;
|
|||||||
use codex_app_server_protocol::RemoteControlPairingStatusParams;
|
use codex_app_server_protocol::RemoteControlPairingStatusParams;
|
||||||
use codex_config::types::AuthCredentialsStoreMode;
|
use codex_config::types::AuthCredentialsStoreMode;
|
||||||
use codex_login::AuthKeyringBackendKind;
|
use codex_login::AuthKeyringBackendKind;
|
||||||
|
use codex_login::AuthManager;
|
||||||
use codex_login::save_auth;
|
use codex_login::save_auth;
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
@@ -36,16 +37,17 @@ async fn connect_test_websocket(
|
|||||||
auth_manager: &Arc<AuthManager>,
|
auth_manager: &Arc<AuthManager>,
|
||||||
current_enrollment: &CurrentRemoteControlEnrollment,
|
current_enrollment: &CurrentRemoteControlEnrollment,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
let session_auth = RemoteControlAuth::capture(auth_manager.clone()).0;
|
||||||
|
let mut auth_recovery = session_auth.unauthorized_recovery();
|
||||||
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
let mut auth_change_rx = auth_manager.auth_change_receiver();
|
||||||
let (status_publisher, _) = remote_control_status_channel();
|
let (status_publisher, _) = remote_control_status_channel();
|
||||||
let desired_state_tx = enabled_desired_state_sender();
|
let desired_state_tx = enabled_desired_state_sender();
|
||||||
let desired_state_persistence_lock = Semaphore::new(1);
|
let persistence = RemoteControlPersistence::default();
|
||||||
connect_remote_control_websocket(
|
connect_remote_control_websocket(
|
||||||
remote_control_target,
|
remote_control_target,
|
||||||
Some(state_db),
|
Some(state_db),
|
||||||
RemoteControlAuthContext {
|
RemoteControlAuthContext {
|
||||||
auth_manager,
|
auth_manager: &session_auth,
|
||||||
auth_recovery: &mut auth_recovery,
|
auth_recovery: &mut auth_recovery,
|
||||||
auth_change_rx: &mut auth_change_rx,
|
auth_change_rx: &mut auth_change_rx,
|
||||||
},
|
},
|
||||||
@@ -56,7 +58,7 @@ async fn connect_test_websocket(
|
|||||||
subscribe_cursor: None,
|
subscribe_cursor: None,
|
||||||
app_server_client_name: None,
|
app_server_client_name: None,
|
||||||
desired_state_tx: &desired_state_tx,
|
desired_state_tx: &desired_state_tx,
|
||||||
desired_state_persistence_lock: &desired_state_persistence_lock,
|
persistence: &persistence,
|
||||||
},
|
},
|
||||||
&status_publisher,
|
&status_publisher,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ pub async fn start_stdio_connection(
|
|||||||
.send(TransportEvent::ConnectionOpened {
|
.send(TransportEvent::ConnectionOpened {
|
||||||
connection_id,
|
connection_id,
|
||||||
origin: ConnectionOrigin::Stdio,
|
origin: ConnectionOrigin::Stdio,
|
||||||
|
auth: None,
|
||||||
writer: writer_tx,
|
writer: writer_tx,
|
||||||
disconnect_sender: None,
|
disconnect_sender: None,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -187,6 +187,7 @@ pub(crate) async fn run_websocket_connection<M, SinkError, StreamError>(
|
|||||||
.send(TransportEvent::ConnectionOpened {
|
.send(TransportEvent::ConnectionOpened {
|
||||||
connection_id,
|
connection_id,
|
||||||
origin: ConnectionOrigin::WebSocket,
|
origin: ConnectionOrigin::WebSocket,
|
||||||
|
auth: None,
|
||||||
writer: writer_tx,
|
writer: writer_tx,
|
||||||
disconnect_sender: Some(disconnect_token.clone()),
|
disconnect_sender: Some(disconnect_token.clone()),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,14 +1,20 @@
|
|||||||
|
//! Controls RPC admission and draining for each connection.
|
||||||
|
//! Auth ownership changes reject queued work while started handlers finish cleanup.
|
||||||
|
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
|
|
||||||
|
use codex_app_server_transport::ConnectionAuth;
|
||||||
|
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
use tokio_util::task::TaskTracker;
|
use tokio_util::task::TaskTracker;
|
||||||
|
|
||||||
/// Per-connection gate for initialized RPC handler execution.
|
/// Per-connection gate for incoming messages and initialized RPC handler execution.
|
||||||
///
|
///
|
||||||
/// Closing the gate prevents queued handlers from starting while allowing
|
/// Closing the gate prevents queued handlers from starting while allowing
|
||||||
/// handlers that already acquired a token to finish.
|
/// handlers that already acquired a token to finish.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(crate) struct ConnectionRpcGate {
|
pub(crate) struct ConnectionRpcGate {
|
||||||
|
pub(crate) auth: Option<ConnectionAuth>,
|
||||||
accepting: Mutex<bool>,
|
accepting: Mutex<bool>,
|
||||||
tasks: TaskTracker,
|
tasks: TaskTracker,
|
||||||
}
|
}
|
||||||
@@ -17,6 +23,7 @@ impl ConnectionRpcGate {
|
|||||||
pub(crate) fn new() -> Self {
|
pub(crate) fn new() -> Self {
|
||||||
let accepting = true;
|
let accepting = true;
|
||||||
Self {
|
Self {
|
||||||
|
auth: None,
|
||||||
accepting: Mutex::new(accepting),
|
accepting: Mutex::new(accepting),
|
||||||
tasks: TaskTracker::new(),
|
tasks: TaskTracker::new(),
|
||||||
}
|
}
|
||||||
@@ -28,7 +35,7 @@ impl ConnectionRpcGate {
|
|||||||
{
|
{
|
||||||
let token = {
|
let token = {
|
||||||
let accepting = self.accepting.lock().await;
|
let accepting = self.accepting.lock().await;
|
||||||
if !*accepting {
|
if !*accepting || self.is_closed() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.tasks.token()
|
self.tasks.token()
|
||||||
@@ -39,7 +46,7 @@ impl ConnectionRpcGate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn is_closed(&self) -> bool {
|
pub(crate) fn is_closed(&self) -> bool {
|
||||||
self.tasks.is_closed()
|
self.tasks.is_closed() || self.auth.as_ref().is_some_and(|auth| !auth.is_current())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn close(&self) {
|
pub(crate) async fn close(&self) {
|
||||||
|
|||||||
@@ -1087,6 +1087,7 @@ pub async fn run_main_with_transport_options(
|
|||||||
TransportEvent::ConnectionOpened {
|
TransportEvent::ConnectionOpened {
|
||||||
connection_id,
|
connection_id,
|
||||||
origin,
|
origin,
|
||||||
|
auth,
|
||||||
writer,
|
writer,
|
||||||
disconnect_sender,
|
disconnect_sender,
|
||||||
} => {
|
} => {
|
||||||
@@ -1117,6 +1118,7 @@ pub async fn run_main_with_transport_options(
|
|||||||
connection_id,
|
connection_id,
|
||||||
ConnectionState::new(
|
ConnectionState::new(
|
||||||
origin,
|
origin,
|
||||||
|
auth,
|
||||||
outbound_initialized,
|
outbound_initialized,
|
||||||
outbound_experimental_api_enabled,
|
outbound_experimental_api_enabled,
|
||||||
outbound_opted_out_notification_methods,
|
outbound_opted_out_notification_methods,
|
||||||
@@ -1149,12 +1151,15 @@ pub async fn run_main_with_transport_options(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
TransportEvent::IncomingMessage { connection_id, message } => {
|
TransportEvent::IncomingMessage { connection_id, message } => {
|
||||||
|
let Some(connection_state) = connections.get_mut(&connection_id) else {
|
||||||
|
warn!("dropping message from unknown connection: {connection_id:?}");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if connection_state.session.rpc_gate.is_closed() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
match message {
|
match message {
|
||||||
JSONRPCMessage::Request(request) => {
|
JSONRPCMessage::Request(request) => {
|
||||||
let Some(connection_state) = connections.get_mut(&connection_id) else {
|
|
||||||
warn!("dropping request from unknown connection: {connection_id:?}");
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let was_initialized =
|
let was_initialized =
|
||||||
connection_state.session.initialized();
|
connection_state.session.initialized();
|
||||||
processor
|
processor
|
||||||
@@ -1216,24 +1221,12 @@ pub async fn run_main_with_transport_options(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
JSONRPCMessage::Response(response) => {
|
JSONRPCMessage::Response(response) => {
|
||||||
if !connections.contains_key(&connection_id) {
|
|
||||||
warn!("dropping response from unknown connection: {connection_id:?}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
processor.process_response(connection_id, response).await;
|
processor.process_response(connection_id, response).await;
|
||||||
}
|
}
|
||||||
JSONRPCMessage::Notification(notification) => {
|
JSONRPCMessage::Notification(notification) => {
|
||||||
if !connections.contains_key(&connection_id) {
|
|
||||||
warn!("dropping notification from unknown connection: {connection_id:?}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
processor.process_notification(notification).await;
|
processor.process_notification(notification).await;
|
||||||
}
|
}
|
||||||
JSONRPCMessage::Error(err) => {
|
JSONRPCMessage::Error(err) => {
|
||||||
if !connections.contains_key(&connection_id) {
|
|
||||||
warn!("dropping error from unknown connection: {connection_id:?}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
processor.process_error(connection_id, err).await;
|
processor.process_error(connection_id, err).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -132,6 +132,7 @@ fn map_enable_error(err: RemoteControlEnableError) -> JSONRPCErrorError {
|
|||||||
match err {
|
match err {
|
||||||
RemoteControlEnableError::Unavailable(err) => map_unavailable(err),
|
RemoteControlEnableError::Unavailable(err) => map_unavailable(err),
|
||||||
RemoteControlEnableError::DisabledByRequirements(err) => invalid_request(err.to_string()),
|
RemoteControlEnableError::DisabledByRequirements(err) => invalid_request(err.to_string()),
|
||||||
|
RemoteControlEnableError::AuthenticationChanged => internal_error(err.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,16 +48,21 @@ pub(crate) struct ConnectionState {
|
|||||||
impl ConnectionState {
|
impl ConnectionState {
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
origin: ConnectionOrigin,
|
origin: ConnectionOrigin,
|
||||||
|
auth: Option<codex_app_server_transport::ConnectionAuth>,
|
||||||
outbound_initialized: Arc<AtomicBool>,
|
outbound_initialized: Arc<AtomicBool>,
|
||||||
outbound_experimental_api_enabled: Arc<AtomicBool>,
|
outbound_experimental_api_enabled: Arc<AtomicBool>,
|
||||||
outbound_opted_out_notification_methods: Arc<RwLock<HashSet<String>>>,
|
outbound_opted_out_notification_methods: Arc<RwLock<HashSet<String>>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let mut session = ConnectionSessionState::new(origin);
|
||||||
|
let mut rpc_gate = crate::connection_rpc_gate::ConnectionRpcGate::new();
|
||||||
|
rpc_gate.auth = auth;
|
||||||
|
session.rpc_gate = Arc::new(rpc_gate);
|
||||||
Self {
|
Self {
|
||||||
origin,
|
origin,
|
||||||
outbound_initialized,
|
outbound_initialized,
|
||||||
outbound_experimental_api_enabled,
|
outbound_experimental_api_enabled,
|
||||||
outbound_opted_out_notification_methods,
|
outbound_opted_out_notification_methods,
|
||||||
session: Arc::new(ConnectionSessionState::new(origin)),
|
session: Arc::new(session),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,9 @@ use tokio_tungstenite::accept_async;
|
|||||||
use tokio_tungstenite::tungstenite::Message;
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
|
|
||||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
|
#[path = "remote_control_auth.rs"]
|
||||||
|
mod auth_tests;
|
||||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
const REMOTE_CONTROL_DISABLED_BY_REQUIREMENTS_MESSAGE: &str =
|
const REMOTE_CONTROL_DISABLED_BY_REQUIREMENTS_MESSAGE: &str =
|
||||||
"remote control is disabled by managed requirements";
|
"remote control is disabled by managed requirements";
|
||||||
@@ -501,12 +504,18 @@ async fn stdio_eof_releases_thread_writer_with_pending_remote_control_enable() -
|
|||||||
let codex_home = TempDir::new()?;
|
let codex_home = TempDir::new()?;
|
||||||
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
let mut backend = BlockingRemoteControlBackend::start(codex_home.path()).await?;
|
||||||
let config_path = codex_home.path().join("config.toml");
|
let config_path = codex_home.path().join("config.toml");
|
||||||
let config = std::fs::read_to_string(&config_path)?;
|
let mut config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
|
||||||
// Keep thread initialization from using the enrollment-only backend for unrelated requests.
|
// Keep thread initialization from using the enrollment-only backend for unrelated requests.
|
||||||
|
let features = config["features"]
|
||||||
|
.as_table_mut()
|
||||||
|
.context("fixture features should be a table")?;
|
||||||
|
features.insert("apps".to_string(), toml::Value::Boolean(false));
|
||||||
|
features.insert("remote_plugin".to_string(), toml::Value::Boolean(false));
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
config_path,
|
config_path,
|
||||||
format!(
|
format!(
|
||||||
"{config}\n[features]\napps = false\nremote_plugin = false\n\n[analytics]\nenabled = false\n"
|
"{}\n[analytics]\nenabled = false\n",
|
||||||
|
toml::to_string(&config)?
|
||||||
),
|
),
|
||||||
)?;
|
)?;
|
||||||
let thread_id = create_fake_paginated_rollout(
|
let thread_id = create_fake_paginated_rollout(
|
||||||
@@ -1322,8 +1331,18 @@ struct HttpRequest {
|
|||||||
async fn configured_remote_control_listener(codex_home: &std::path::Path) -> Result<TcpListener> {
|
async fn configured_remote_control_listener(codex_home: &std::path::Path) -> Result<TcpListener> {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||||
let remote_control_url = format!("http://{}/backend-api/", listener.local_addr()?);
|
let remote_control_url = format!("http://{}/backend-api/", listener.local_addr()?);
|
||||||
|
let catalog_path = codex_home.join("models.json");
|
||||||
|
std::fs::write(
|
||||||
|
&catalog_path,
|
||||||
|
serde_json::to_vec(&codex_models_manager::bundled_models_response()?)?,
|
||||||
|
)?;
|
||||||
MockResponsesConfig::new(&remote_control_url)
|
MockResponsesConfig::new(&remote_control_url)
|
||||||
.with_root_config(&format!("chatgpt_base_url = \"{remote_control_url}\""))
|
.with_root_config(&format!("chatgpt_base_url = \"{remote_control_url}\""))
|
||||||
|
.with_root_config(&format!(
|
||||||
|
"model_catalog_json = {}",
|
||||||
|
serde_json::to_string(&catalog_path)?
|
||||||
|
))
|
||||||
|
.disable_feature(codex_features::Feature::Plugins)
|
||||||
.write(codex_home)?;
|
.write(codex_home)?;
|
||||||
write_chatgpt_auth(
|
write_chatgpt_auth(
|
||||||
codex_home,
|
codex_home,
|
||||||
|
|||||||
@@ -0,0 +1,492 @@
|
|||||||
|
//! Exercises login lifetime boundaries through public RPCs and a real relay websocket.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use app_test_support::ChatGptIdTokenClaims;
|
||||||
|
use app_test_support::encode_id_token;
|
||||||
|
use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse;
|
||||||
|
use codex_app_server_protocol::ServerRequest;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
use serde_json::Value;
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio_tungstenite::WebSocketStream;
|
||||||
|
|
||||||
|
struct RelayClient {
|
||||||
|
socket: WebSocketStream<TcpStream>,
|
||||||
|
next_seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RelayClient {
|
||||||
|
async fn send(&mut self, message: Value) -> Result<()> {
|
||||||
|
self.socket
|
||||||
|
.send(Message::Text(
|
||||||
|
json!({
|
||||||
|
"type": "client_message", "client_id": "client-a", "stream_id": "stream-a",
|
||||||
|
"seq_id": self.next_seq, "cursor": format!("cursor-{}", self.next_seq),
|
||||||
|
"message": message,
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
.into(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
self.next_seq += 1;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn response(&mut self, id: i64) -> Result<Value> {
|
||||||
|
timeout(DEFAULT_TIMEOUT, async {
|
||||||
|
loop {
|
||||||
|
let message = self.socket.next().await.context("relay disconnected")??;
|
||||||
|
if let Message::Text(text) = message {
|
||||||
|
let envelope: Value = serde_json::from_str(&text)?;
|
||||||
|
if envelope["type"] == "server_message" && envelope["message"]["id"] == id {
|
||||||
|
return Ok(envelope["message"].clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn closed(&mut self) -> Result<()> {
|
||||||
|
timeout(DEFAULT_TIMEOUT, async {
|
||||||
|
loop {
|
||||||
|
match self.socket.next().await {
|
||||||
|
None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return,
|
||||||
|
Some(Ok(_)) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn assert_account(&mut self, app: &mut TestAppServer) -> Result<()> {
|
||||||
|
let local = app.send_request("account/read", Some(json!({}))).await?;
|
||||||
|
let expected: Value = timeout(DEFAULT_TIMEOUT, app.read_response(local)).await??;
|
||||||
|
self.send(json!({"id": 2, "method": "account/read", "params": {}}))
|
||||||
|
.await?;
|
||||||
|
assert_eq!(
|
||||||
|
self.response(/*id*/ 2).await?.get("result"),
|
||||||
|
Some(&expected)
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn external_token(user: &str, account: &str, revision: &str) -> Result<String> {
|
||||||
|
encode_id_token(
|
||||||
|
&ChatGptIdTokenClaims::new()
|
||||||
|
.chatgpt_account_id(account)
|
||||||
|
.chatgpt_user_id(user)
|
||||||
|
.plan_type("pro")
|
||||||
|
.email(format!("{revision}@example.com")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(app: &mut TestAppServer, user: &str, account: &str, revision: &str) -> Result<()> {
|
||||||
|
let id = app
|
||||||
|
.send_chatgpt_auth_tokens_login_request(
|
||||||
|
external_token(user, account, revision)?,
|
||||||
|
account.to_string(),
|
||||||
|
Some("pro".to_string()),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
wait_for_response(app, id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_relay(app: &mut TestAppServer, listener: &TcpListener) -> Result<RelayClient> {
|
||||||
|
let id = app.send_remote_control_ephemeral_enable_request().await?;
|
||||||
|
wait_for_response(app, id).await?;
|
||||||
|
let request = timeout(DEFAULT_TIMEOUT, read_http_request(listener)).await??;
|
||||||
|
assert!(
|
||||||
|
request.request_line.contains("/server/enroll ")
|
||||||
|
|| request.request_line.contains("/server/refresh "),
|
||||||
|
"{}",
|
||||||
|
request.request_line
|
||||||
|
);
|
||||||
|
respond_with_json(
|
||||||
|
request.reader.into_inner(),
|
||||||
|
json!({
|
||||||
|
"server_id": "server-id", "environment_id": "environment-id",
|
||||||
|
"remote_control_token": "remote-control-token", "expires_at": "3026-05-22T12:34:56Z",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||||
|
let socket = timeout(
|
||||||
|
DEFAULT_TIMEOUT,
|
||||||
|
tokio_tungstenite::accept_hdr_async(
|
||||||
|
stream,
|
||||||
|
|request: &tokio_tungstenite::tungstenite::handshake::server::Request, response| {
|
||||||
|
assert!(!request.headers().contains_key("x-codex-subscribe-cursor"));
|
||||||
|
Ok(response)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await??;
|
||||||
|
let mut relay = RelayClient {
|
||||||
|
socket,
|
||||||
|
next_seq: 0,
|
||||||
|
};
|
||||||
|
// A replacement must not retain the old logical client or replay its unacknowledged results.
|
||||||
|
relay
|
||||||
|
.socket
|
||||||
|
.send(Message::Text(
|
||||||
|
json!({
|
||||||
|
"type": "ping", "client_id": "client-a", "stream_id": "stream-a",
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
.into(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
timeout(DEFAULT_TIMEOUT, async {
|
||||||
|
loop {
|
||||||
|
let message = relay
|
||||||
|
.socket
|
||||||
|
.next()
|
||||||
|
.await
|
||||||
|
.context("relay disconnected before pong")??;
|
||||||
|
if let Message::Text(text) = message {
|
||||||
|
let envelope: Value = serde_json::from_str(&text)?;
|
||||||
|
assert_ne!(envelope["type"], "server_message");
|
||||||
|
if envelope["type"] == "pong" {
|
||||||
|
assert_eq!(envelope["status"], "unknown");
|
||||||
|
return Ok::<(), anyhow::Error>(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
relay
|
||||||
|
.send(json!({"id": 1, "method": "initialize", "params": {
|
||||||
|
"clientInfo": {"name": "remote-auth-test", "version": "0.1.0"},
|
||||||
|
"capabilities": {"experimentalApi": true},
|
||||||
|
}}))
|
||||||
|
.await?;
|
||||||
|
assert!(relay.response(/*id*/ 1).await?.get("result").is_some());
|
||||||
|
relay.send(json!({"method": "initialized"})).await?;
|
||||||
|
Ok(relay)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn same_owner_refresh_preserves_live_relay() -> Result<()> {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||||
|
let mut relay = open_relay(&mut app, &listener).await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "refreshed").await?;
|
||||||
|
relay.assert_account(&mut app).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn owner_change_retires_live_relay() -> Result<()> {
|
||||||
|
for (user, account) in [("user-b", "account-a"), ("user-a", "account-b")] {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||||
|
let mut old = open_relay(&mut app, &listener).await?;
|
||||||
|
old.assert_account(&mut app).await?;
|
||||||
|
login(&mut app, user, account, "replacement").await?;
|
||||||
|
old.closed().await?;
|
||||||
|
let id = app.send_remote_control_status_read_request().await?;
|
||||||
|
let status: RemoteControlStatusReadResponse =
|
||||||
|
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
|
||||||
|
assert_eq!(status.status, RemoteControlConnectionStatus::Disabled);
|
||||||
|
let mut fresh = open_relay(&mut app, &listener).await?;
|
||||||
|
fresh.assert_account(&mut app).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn owner_change_discards_pending_and_queued_pairing() -> Result<()> {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||||
|
let mut old = open_relay(&mut app, &listener).await?;
|
||||||
|
let pending = app
|
||||||
|
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||||
|
manual_code: false,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
assert!(held.request_line.contains("/server/pair "));
|
||||||
|
old.send(
|
||||||
|
json!({"id": 3, "method": "remoteControl/pairing/start", "params": {"manualCode": false}}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
// account/read uses another queue. Its response proves the prior pairing RPC was received.
|
||||||
|
old.assert_account(&mut app).await?;
|
||||||
|
login(&mut app, "user-b", "account-a", "replacement").await?;
|
||||||
|
let mut fresh = open_relay(&mut app, &listener).await?;
|
||||||
|
let sentinel = app
|
||||||
|
.send_remote_control_pairing_start_request(RemoteControlPairingStartParams {
|
||||||
|
manual_code: true,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
// The old socket can already be cancelled, so delivery of this obsolete response is optional.
|
||||||
|
let _ = respond_with_json(held.reader.into_inner(), json!({
|
||||||
|
"pairing_code": "obsolete", "server_id": "server-id", "environment_id": "environment-id",
|
||||||
|
"expires_at": "3026-05-22T12:34:56Z",
|
||||||
|
})).await;
|
||||||
|
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
assert!(next.request_line.contains("/server/pair "));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_str::<Value>(&next.body)?,
|
||||||
|
json!({"manual_code": true})
|
||||||
|
);
|
||||||
|
respond_with_json(
|
||||||
|
next.reader.into_inner(),
|
||||||
|
json!({
|
||||||
|
"pairing_code": "current", "server_id": "server-id", "manual_pairing_code": "ABCD-EFGH",
|
||||||
|
"environment_id": "environment-id", "expires_at": "3026-05-22T12:34:56Z",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
timeout(
|
||||||
|
DEFAULT_TIMEOUT,
|
||||||
|
app.read_stream_until_error_message(RequestId::Integer(pending)),
|
||||||
|
)
|
||||||
|
.await??;
|
||||||
|
wait_for_response(&mut app, sentinel).await?;
|
||||||
|
old.closed().await?;
|
||||||
|
fresh.assert_account(&mut app).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn client_revoke_retry_stays_with_original_owner() -> Result<()> {
|
||||||
|
for refreshed_user in ["user-a", "user-b"] {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||||
|
let old = app
|
||||||
|
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||||
|
environment_id: "environment-id".to_string(),
|
||||||
|
client_id: "old-client".to_string(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let first = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
assert_eq!(
|
||||||
|
first.request_line,
|
||||||
|
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/old-client HTTP/1.1"
|
||||||
|
);
|
||||||
|
respond_with_status(first.reader.into_inner(), "401 Unauthorized", "expired").await?;
|
||||||
|
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
|
||||||
|
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
|
||||||
|
anyhow::bail!("expected external authentication refresh");
|
||||||
|
};
|
||||||
|
app.send_response(
|
||||||
|
request_id,
|
||||||
|
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
|
||||||
|
access_token: external_token(refreshed_user, "account-a", "refreshed")?,
|
||||||
|
chatgpt_account_id: "account-a".to_string(),
|
||||||
|
chatgpt_plan_type: Some("pro".to_string()),
|
||||||
|
})?,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (next_id, client) = if refreshed_user == "user-a" {
|
||||||
|
(old, "old-client")
|
||||||
|
} else {
|
||||||
|
timeout(
|
||||||
|
DEFAULT_TIMEOUT,
|
||||||
|
app.read_stream_until_error_message(RequestId::Integer(old)),
|
||||||
|
)
|
||||||
|
.await??;
|
||||||
|
let id = app
|
||||||
|
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||||
|
environment_id: "environment-id".to_string(),
|
||||||
|
client_id: "new-client".to_string(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
(id, "new-client")
|
||||||
|
};
|
||||||
|
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
assert_eq!(
|
||||||
|
next.request_line,
|
||||||
|
format!(
|
||||||
|
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/{client} HTTP/1.1"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
respond_with_json(next.reader.into_inner(), json!({})).await?;
|
||||||
|
let result: RemoteControlClientsRevokeResponse =
|
||||||
|
timeout(DEFAULT_TIMEOUT, app.read_response(next_id)).await??;
|
||||||
|
assert_eq!(result, RemoteControlClientsRevokeResponse {});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn owner_change_rejects_queued_client_revoke() -> Result<()> {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
login(&mut app, "user-a", "account-a", "initial").await?;
|
||||||
|
let mut relay = open_relay(&mut app, &listener).await?;
|
||||||
|
let pending = app
|
||||||
|
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||||
|
environment_id: "environment-id".to_string(),
|
||||||
|
client_id: "pending".to_string(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let held = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
relay
|
||||||
|
.send(
|
||||||
|
json!({"id": 3, "method": "remoteControl/client/revoke", "params": {
|
||||||
|
"environmentId": "environment-id", "clientId": "obsolete",
|
||||||
|
}}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
relay.assert_account(&mut app).await?;
|
||||||
|
login(&mut app, "user-b", "account-a", "replacement").await?;
|
||||||
|
let sentinel = app
|
||||||
|
.send_remote_control_clients_revoke_request(RemoteControlClientsRevokeParams {
|
||||||
|
environment_id: "environment-id".to_string(),
|
||||||
|
client_id: "current".to_string(),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let _ = respond_with_json(held.reader.into_inner(), json!({})).await;
|
||||||
|
// Client management works even while disabled, so disablement cannot mask a missing gate.
|
||||||
|
let next = timeout(DEFAULT_TIMEOUT, read_http_request(&listener)).await??;
|
||||||
|
assert_eq!(
|
||||||
|
next.request_line,
|
||||||
|
"DELETE /backend-api/wham/remote/control/environments/environment-id/clients/current HTTP/1.1"
|
||||||
|
);
|
||||||
|
respond_with_json(next.reader.into_inner(), json!({})).await?;
|
||||||
|
timeout(
|
||||||
|
DEFAULT_TIMEOUT,
|
||||||
|
app.read_stream_until_error_message(RequestId::Integer(pending)),
|
||||||
|
)
|
||||||
|
.await??;
|
||||||
|
wait_for_response(&mut app, sentinel).await?;
|
||||||
|
relay.closed().await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn logout_login_enable_recovers_first_unauthorized_enrollment() -> Result<()> {
|
||||||
|
let home = TempDir::new()?;
|
||||||
|
let listener = configured_remote_control_listener(home.path()).await?;
|
||||||
|
let oauth = wiremock::MockServer::start().await;
|
||||||
|
wiremock::Mock::given(wiremock::matchers::path("/oauth/revoke"))
|
||||||
|
.respond_with(wiremock::ResponseTemplate::new(/*s*/ 200))
|
||||||
|
.expect(1)
|
||||||
|
.mount(&oauth)
|
||||||
|
.await;
|
||||||
|
let revoke_url = format!("{}/oauth/revoke", oauth.uri());
|
||||||
|
let mut app = TestAppServer::builder()
|
||||||
|
.with_codex_home(home.path())
|
||||||
|
.with_env_overrides(&[("CODEX_REVOKE_TOKEN_URL_OVERRIDE", Some(revoke_url.as_str()))])
|
||||||
|
.without_auto_env()
|
||||||
|
.build_initialized()
|
||||||
|
.await?;
|
||||||
|
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
|
||||||
|
wait_for_response(&mut app, enabled).await?;
|
||||||
|
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||||
|
respond_with_json(
|
||||||
|
reader.into_inner(),
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": "server-a", "environment_id": "environment-a",
|
||||||
|
"remote_control_token": "token-a", "expires_at": "3026-05-22T12:34:56Z",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||||
|
let mut websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
|
||||||
|
let logout = app.send_logout_account_request().await?;
|
||||||
|
wait_for_response(&mut app, logout).await?;
|
||||||
|
timeout(DEFAULT_TIMEOUT, async {
|
||||||
|
loop {
|
||||||
|
let notification = app
|
||||||
|
.read_stream_until_notification_message("remoteControl/status/changed")
|
||||||
|
.await?;
|
||||||
|
let status: RemoteControlStatusChangedNotification =
|
||||||
|
serde_json::from_value(notification.params.context("status params")?)?;
|
||||||
|
if status.status == RemoteControlConnectionStatus::Disabled {
|
||||||
|
return Ok::<(), anyhow::Error>(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
assert!(matches!(
|
||||||
|
timeout(DEFAULT_TIMEOUT, websocket.next()).await?,
|
||||||
|
None | Some(Err(_)) | Some(Ok(Message::Close(_)))
|
||||||
|
));
|
||||||
|
|
||||||
|
let token = encode_id_token(
|
||||||
|
&ChatGptIdTokenClaims::new()
|
||||||
|
.chatgpt_account_id("account_b")
|
||||||
|
.chatgpt_user_id("user_b")
|
||||||
|
.plan_type("pro"),
|
||||||
|
)?;
|
||||||
|
let login = app
|
||||||
|
.send_chatgpt_auth_tokens_login_request(
|
||||||
|
token.clone(),
|
||||||
|
"account_b".to_string(),
|
||||||
|
Some("pro".to_string()),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
wait_for_response(&mut app, login).await?;
|
||||||
|
let enabled = app.send_remote_control_ephemeral_enable_request().await?;
|
||||||
|
wait_for_response(&mut app, enabled).await?;
|
||||||
|
let (line, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||||
|
assert_eq!(
|
||||||
|
line,
|
||||||
|
"POST /backend-api/wham/remote/control/server/enroll HTTP/1.1"
|
||||||
|
);
|
||||||
|
respond_with_status(reader.into_inner(), "401 Unauthorized", "expired token").await?;
|
||||||
|
let request = timeout(DEFAULT_TIMEOUT, app.read_stream_until_request_message()).await??;
|
||||||
|
let ServerRequest::ChatgptAuthTokensRefresh { request_id, .. } = request else {
|
||||||
|
anyhow::bail!("expected token refresh after the new owner's 401");
|
||||||
|
};
|
||||||
|
let refreshed_token = encode_id_token(
|
||||||
|
&ChatGptIdTokenClaims::new()
|
||||||
|
.chatgpt_account_id("account_b")
|
||||||
|
.chatgpt_user_id("user_b")
|
||||||
|
.plan_type("pro")
|
||||||
|
.email("refreshed@example.com"),
|
||||||
|
)?;
|
||||||
|
app.send_response(
|
||||||
|
request_id,
|
||||||
|
serde_json::to_value(ChatgptAuthTokensRefreshResponse {
|
||||||
|
access_token: refreshed_token,
|
||||||
|
chatgpt_account_id: "account_b".to_string(),
|
||||||
|
chatgpt_plan_type: Some("pro".to_string()),
|
||||||
|
})?,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (_, reader) = timeout(DEFAULT_TIMEOUT, read_enroll_request(&listener)).await??;
|
||||||
|
respond_with_json(
|
||||||
|
reader.into_inner(),
|
||||||
|
serde_json::json!({
|
||||||
|
"server_id": "server-b", "environment_id": "environment-b",
|
||||||
|
"remote_control_token": "token-b", "expires_at": "3026-05-22T12:34:56Z",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (stream, _) = timeout(DEFAULT_TIMEOUT, listener.accept()).await??;
|
||||||
|
let _websocket = timeout(DEFAULT_TIMEOUT, accept_async(stream)).await??;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Reference in new issue
Block a user