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;
|
||||
/// Only managed app-server launches accept the local socket shutdown request.
|
||||
pub const DAEMON_SHUTDOWN_SOCKET_ENV: &str = "CODEX_DAEMON_SHUTDOWN_SOCKET";
|
||||
mod connection_auth;
|
||||
mod outgoing_message;
|
||||
mod transport;
|
||||
|
||||
pub use connection_auth::ConnectionAuth;
|
||||
pub use outgoing_message::ConnectionId;
|
||||
pub use outgoing_message::OutgoingError;
|
||||
pub use outgoing_message::OutgoingMessage;
|
||||
|
||||
@@ -184,6 +184,7 @@ pub enum TransportEvent {
|
||||
ConnectionOpened {
|
||||
connection_id: ConnectionId,
|
||||
origin: ConnectionOrigin,
|
||||
auth: Option<crate::ConnectionAuth>,
|
||||
writer: mpsc::Sender<QueuedOutgoingMessage>,
|
||||
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::HeaderValue;
|
||||
use codex_api::SharedAuthProvider;
|
||||
@@ -10,6 +13,46 @@ use tokio::sync::watch;
|
||||
use tracing::info;
|
||||
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) struct RemoteControlConnectionAuth {
|
||||
@@ -35,6 +78,15 @@ impl RemoteControlConnectionAuth {
|
||||
}
|
||||
|
||||
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>,
|
||||
) -> io::Result<RemoteControlConnectionAuth> {
|
||||
let mut reloaded = false;
|
||||
@@ -80,9 +132,13 @@ pub(super) async fn load_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>,
|
||||
) -> bool {
|
||||
if recovery.auth.ensure_current().is_err() {
|
||||
return false;
|
||||
}
|
||||
let auth_recovery = &mut recovery.recovery;
|
||||
if !auth_recovery.has_next() {
|
||||
return false;
|
||||
}
|
||||
@@ -92,6 +148,9 @@ pub(super) async fn recover_remote_control_auth(
|
||||
let auth_change_revision_before_recovery = *auth_change_rx.borrow();
|
||||
match auth_recovery.next().await {
|
||||
Ok(step_result) => {
|
||||
if recovery.auth.ensure_current().is_err() {
|
||||
return false;
|
||||
}
|
||||
if step_result.auth_state_changed() == Some(true) {
|
||||
mark_recovery_auth_change_seen(
|
||||
auth_change_rx,
|
||||
|
||||
@@ -43,6 +43,7 @@ struct ClientState {
|
||||
}
|
||||
|
||||
pub(crate) struct ClientTracker {
|
||||
pub(super) auth: Option<crate::ConnectionAuth>,
|
||||
clients: HashMap<(ClientId, StreamId), ClientState>,
|
||||
legacy_stream_ids: HashMap<ClientId, StreamId>,
|
||||
join_set: JoinSet<(ClientId, StreamId)>,
|
||||
@@ -58,6 +59,7 @@ impl ClientTracker {
|
||||
shutdown_token: &CancellationToken,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth: None,
|
||||
clients: HashMap::new(),
|
||||
legacy_stream_ids: HashMap::new(),
|
||||
join_set: JoinSet::new(),
|
||||
@@ -168,6 +170,7 @@ impl ClientTracker {
|
||||
self.send_transport_event(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::RemoteControl,
|
||||
auth: self.auth.clone(),
|
||||
writer: writer_tx,
|
||||
disconnect_sender: Some(disconnect_token.clone()),
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::auth::RemoteControlConnectionAuth;
|
||||
use super::auth::load_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::RemoteControlClientsRevokeParams;
|
||||
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::default_client::create_client_without_request_logging;
|
||||
use serde::Deserialize;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::sync::Arc;
|
||||
use time::OffsetDateTime;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use url::Url;
|
||||
@@ -68,7 +67,7 @@ struct ClientManagementResponse {
|
||||
|
||||
pub(super) async fn list_remote_control_clients(
|
||||
remote_control_url: &str,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth_manager: &RemoteControlAuth,
|
||||
params: RemoteControlClientsListParams,
|
||||
) -> io::Result<RemoteControlClientsListResponse> {
|
||||
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(
|
||||
remote_control_url: &str,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth_manager: &RemoteControlAuth,
|
||||
params: RemoteControlClientsRevokeParams,
|
||||
) -> io::Result<RemoteControlClientsRevokeResponse> {
|
||||
if params.environment_id.is_empty() {
|
||||
@@ -164,7 +163,7 @@ pub(super) async fn revoke_remote_control_client(
|
||||
}
|
||||
|
||||
async fn send_client_management_request(
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth_manager: &RemoteControlAuth,
|
||||
request: ClientManagementRequest<'_>,
|
||||
action: &str,
|
||||
) -> 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::RemoteControlHandle;
|
||||
use super::RemoteControlSession;
|
||||
use super::RemoteControlUnavailable;
|
||||
use super::enroll::update_persisted_remote_control_enrollment;
|
||||
use super::protocol::normalize_remote_control_url;
|
||||
use super::publish_current_enrollment;
|
||||
use super::websocket::RemoteControlStatusPublisher;
|
||||
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
|
||||
use codex_state::RemoteControlEnrollmentRecord;
|
||||
use std::io;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
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(
|
||||
enrollment: Option<RemoteControlEnrollmentRecord>,
|
||||
) -> RemoteControlDesiredState {
|
||||
@@ -47,7 +40,7 @@ pub(super) fn desired_state_from_persisted_enrollment(
|
||||
}
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
impl RemoteControlSession {
|
||||
pub async fn resolve_persisted_preference(
|
||||
&self,
|
||||
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 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 _persistence =
|
||||
super::persistence::read_lock(&self.auth_manager, &self.persistence).await?;
|
||||
let enrollment = state_db
|
||||
.get_remote_control_enrollment(
|
||||
&remote_control_target.websocket_url,
|
||||
@@ -133,31 +128,20 @@ impl RemoteControlHandle {
|
||||
));
|
||||
}
|
||||
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
let updated = state_db
|
||||
.set_remote_control_enabled(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
/*remote_control_enabled*/ true,
|
||||
)
|
||||
.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?;
|
||||
}
|
||||
self.set_preference(
|
||||
state_db,
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
/*enabled*/ true,
|
||||
Some(&enrollment),
|
||||
)
|
||||
.await?;
|
||||
publish_current_enrollment(&mut current_enrollment, &enrollment);
|
||||
self.enable_with_preference(Some(true)).map_err(|err| {
|
||||
let kind = match err {
|
||||
RemoteControlEnableError::Unavailable(_) => io::ErrorKind::NotFound,
|
||||
RemoteControlEnableError::AuthenticationChanged => io::ErrorKind::Interrupted,
|
||||
RemoteControlEnableError::DisabledByRequirements(_) => {
|
||||
io::ErrorKind::PermissionDenied
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
mod auth;
|
||||
mod client_tracker;
|
||||
mod clients;
|
||||
mod controller;
|
||||
mod persistence;
|
||||
pub use controller::RemoteControlHandle;
|
||||
pub use controller::start_remote_control;
|
||||
mod desired_state;
|
||||
mod enroll;
|
||||
mod host_device;
|
||||
@@ -12,10 +16,9 @@ mod websocket;
|
||||
use self::auth::load_remote_control_auth;
|
||||
use self::auth::recover_remote_control_auth;
|
||||
use self::desired_state::RemoteControlDesiredState;
|
||||
use self::desired_state::acquire_persistence_lock;
|
||||
use self::enroll::RemoteControlEnrollment;
|
||||
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::refresh_remote_control_server;
|
||||
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_login::AuthManager;
|
||||
use codex_state::StateRuntime;
|
||||
use futures::FutureExt;
|
||||
use gethostname::gethostname;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -59,7 +60,6 @@ use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::error;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
@@ -104,19 +104,19 @@ pub(super) struct QueuedServerEnvelope {
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RemoteControlHandle {
|
||||
struct RemoteControlSession {
|
||||
policy: RemoteControlPolicy,
|
||||
shutdown_token: CancellationToken,
|
||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||
desired_state_rpc_lock: Arc<Semaphore>,
|
||||
desired_state_persistence_lock: Arc<Semaphore>,
|
||||
persistence: RemoteControlPersistence,
|
||||
status_tx: Arc<watch::Sender<RemoteControlStatusChangedNotification>>,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
remote_control_url: String,
|
||||
current_enrollment: CurrentRemoteControlEnrollment,
|
||||
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||
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
|
||||
@@ -262,6 +262,7 @@ impl Error for RemoteControlDisabledByRequirements {}
|
||||
pub enum RemoteControlEnableError {
|
||||
Unavailable(RemoteControlUnavailable),
|
||||
DisabledByRequirements(RemoteControlDisabledByRequirements),
|
||||
AuthenticationChanged,
|
||||
}
|
||||
|
||||
impl fmt::Display for RemoteControlEnableError {
|
||||
@@ -269,13 +270,14 @@ impl fmt::Display for RemoteControlEnableError {
|
||||
match self {
|
||||
Self::Unavailable(err) => err.fmt(f),
|
||||
Self::DisabledByRequirements(err) => err.fmt(f),
|
||||
Self::AuthenticationChanged => f.write_str("remote control authentication changed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RemoteControlEnableError {}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
impl RemoteControlSession {
|
||||
pub fn ensure_remote_control_allowed(&self) -> Result<(), RemoteControlDisabledByRequirements> {
|
||||
match self.policy {
|
||||
RemoteControlPolicy::Allowed => Ok(()),
|
||||
@@ -308,6 +310,9 @@ impl RemoteControlHandle {
|
||||
}
|
||||
|
||||
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| {
|
||||
if effective_persistence_preference.is_none()
|
||||
&& matches!(
|
||||
@@ -357,7 +362,6 @@ impl RemoteControlHandle {
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
self.persist_preference(
|
||||
app_server_client_name,
|
||||
/*remote_control_enabled*/ false,
|
||||
@@ -372,7 +376,7 @@ impl RemoteControlHandle {
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
let _persistence = self.persistence.lock().await;
|
||||
self.transition_disabled()
|
||||
}
|
||||
|
||||
@@ -406,15 +410,15 @@ impl RemoteControlHandle {
|
||||
let auth = load_remote_control_auth(&self.auth_manager).await?;
|
||||
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)?;
|
||||
state_db
|
||||
.set_remote_control_enabled(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name.as_deref(),
|
||||
remote_control_enabled,
|
||||
)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
self.set_preference(
|
||||
state_db,
|
||||
&remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name.as_deref(),
|
||||
remote_control_enabled,
|
||||
/*fallback_enrollment*/ None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -578,22 +582,13 @@ impl RemoteControlHandle {
|
||||
.state_db
|
||||
.as_deref()
|
||||
.ok_or_else(pairing_unavailable_error)?;
|
||||
let _persistence = acquire_persistence_lock(&self.desired_state_persistence_lock).await;
|
||||
let persistence_preference = match *self.desired_state_tx.borrow() {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference,
|
||||
} => persistence_preference,
|
||||
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,
|
||||
persistence::save_enrollment(
|
||||
&self.auth_manager,
|
||||
&self.persistence,
|
||||
state_db,
|
||||
&enrollment,
|
||||
app_server_client_name,
|
||||
Some(&enrollment),
|
||||
persistence_preference,
|
||||
&self.desired_state_tx,
|
||||
)
|
||||
.await?;
|
||||
publish_current_enrollment(current_enrollment, &enrollment);
|
||||
@@ -624,6 +619,8 @@ impl RemoteControlHandle {
|
||||
.state_db
|
||||
.as_deref()
|
||||
.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(
|
||||
Some(state_db),
|
||||
&remote_control_target,
|
||||
@@ -840,7 +837,7 @@ impl RemoteControlHandle {
|
||||
|
||||
async fn enroll_pairing_server(
|
||||
current_enrollment: &RemoteControlEnrollmentState,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth_manager: &auth::RemoteControlAuth,
|
||||
auth: &mut auth::RemoteControlConnectionAuth,
|
||||
remote_control_target: &protocol::RemoteControlTarget,
|
||||
installation_id: &str,
|
||||
@@ -889,7 +886,7 @@ fn remote_control_pairing_status_code(
|
||||
|
||||
async fn refresh_pairing_enrollment(
|
||||
current_enrollment: &mut RemoteControlEnrollmentLease<'_>,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
auth_manager: &auth::RemoteControlAuth,
|
||||
auth: &mut auth::RemoteControlConnectionAuth,
|
||||
installation_id: &str,
|
||||
enrollment: &mut RemoteControlEnrollment,
|
||||
@@ -999,162 +996,6 @@ fn same_remote_control_enrollment(
|
||||
&& 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)]
|
||||
mod segment_tests;
|
||||
#[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")
|
||||
}
|
||||
|
||||
#[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]
|
||||
async fn plain_start_resolves_persisted_remote_control_preference() {
|
||||
let cases = [
|
||||
@@ -184,7 +233,7 @@ async fn plain_start_resolves_persisted_remote_control_preference() {
|
||||
server_name: test_server_name(),
|
||||
},
|
||||
Some(state_db),
|
||||
remote_control_auth_manager(),
|
||||
auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||
RemoteControlChannels {
|
||||
transport_event_tx,
|
||||
status_publisher: RemoteControlStatusPublisher::new(status_tx),
|
||||
@@ -192,7 +241,7 @@ async fn plain_start_resolves_persisted_remote_control_preference() {
|
||||
/*enrollment*/ None,
|
||||
)),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
persistence: RemoteControlPersistence::default(),
|
||||
},
|
||||
CancellationToken::new(),
|
||||
desired_state_tx.clone(),
|
||||
@@ -251,8 +300,8 @@ async fn explicit_disabled_start_ignores_persisted_enable() {
|
||||
.expect("remote control should start disabled");
|
||||
|
||||
assert_eq!(
|
||||
*remote_handle.desired_state_tx.borrow(),
|
||||
RemoteControlDesiredState::Disabled
|
||||
remote_handle.status().status,
|
||||
RemoteControlConnectionStatus::Disabled
|
||||
);
|
||||
assert_eq!(
|
||||
state_db
|
||||
@@ -383,7 +432,7 @@ fn test_server_name() -> String {
|
||||
pub(super) fn remote_control_handle_with_current_enrollment(
|
||||
remote_control_url: &str,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> RemoteControlHandle {
|
||||
) -> RemoteControlSession {
|
||||
let (desired_state_tx, _desired_state_rx) =
|
||||
watch::channel(RemoteControlDesiredState::Enabled {
|
||||
persistence_preference: None,
|
||||
@@ -411,19 +460,19 @@ pub(super) fn remote_control_handle_with_current_enrollment(
|
||||
next_refresh_at: None,
|
||||
},
|
||||
)));
|
||||
RemoteControlHandle {
|
||||
RemoteControlSession {
|
||||
policy: RemoteControlPolicy::Allowed,
|
||||
shutdown_token: CancellationToken::new(),
|
||||
desired_state_tx: Arc::new(desired_state_tx),
|
||||
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),
|
||||
state_db: None,
|
||||
remote_control_url: remote_control_url.to_string(),
|
||||
current_enrollment,
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
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");
|
||||
auth_manager.reload().await;
|
||||
websocket
|
||||
.close(None)
|
||||
let closed = timeout(Duration::from_secs(1), websocket.next())
|
||||
.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(
|
||||
Duration::from_secs(1),
|
||||
desired_state_rx.wait_for(|state| *state == RemoteControlDesiredState::Disabled),
|
||||
desired_state_rx.wait_for(|state| state.status == RemoteControlConnectionStatus::Disabled),
|
||||
)
|
||||
.await
|
||||
.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;
|
||||
|
||||
let current_enrollment = remote_handle
|
||||
.inner
|
||||
.session()
|
||||
.current_enrollment
|
||||
.lock()
|
||||
.await
|
||||
|
||||
@@ -13,7 +13,7 @@ use pretty_assertions::assert_eq;
|
||||
fn client_management_handle(
|
||||
remote_control_url: String,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> RemoteControlHandle {
|
||||
) -> RemoteControlSession {
|
||||
let desired_state_tx = watch::channel(RemoteControlDesiredState::Disabled).0;
|
||||
let (status_tx, _status_rx) = watch::channel(RemoteControlStatusChangedNotification {
|
||||
status: RemoteControlConnectionStatus::Disabled,
|
||||
@@ -21,19 +21,19 @@ fn client_management_handle(
|
||||
installation_id: TEST_INSTALLATION_ID.to_string(),
|
||||
environment_id: None,
|
||||
});
|
||||
RemoteControlHandle {
|
||||
RemoteControlSession {
|
||||
policy: RemoteControlPolicy::Allowed,
|
||||
shutdown_token: CancellationToken::new(),
|
||||
desired_state_tx: Arc::new(desired_state_tx),
|
||||
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),
|
||||
state_db: None,
|
||||
remote_control_url,
|
||||
current_enrollment: Arc::new(RemoteControlEnrollmentState::new(/*enrollment*/ None)),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
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(
|
||||
&remote_control_url,
|
||||
&auth_manager,
|
||||
&auth::RemoteControlAuth::capture(auth_manager.clone()).0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..Default::default()
|
||||
@@ -323,7 +323,7 @@ async fn list_remote_control_clients_retries_unauthorized_only_once() {
|
||||
|
||||
let err = list_remote_control_clients(
|
||||
&remote_control_url,
|
||||
&auth_manager,
|
||||
&auth::RemoteControlAuth::capture(auth_manager.clone()).0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..Default::default()
|
||||
@@ -363,7 +363,7 @@ async fn revoke_remote_control_client_does_not_retry_forbidden() {
|
||||
|
||||
let err = revoke_remote_control_client(
|
||||
&remote_control_url,
|
||||
&remote_control_auth_manager(),
|
||||
&auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||
RemoteControlClientsRevokeParams {
|
||||
environment_id: "env-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(
|
||||
&remote_control_url,
|
||||
&remote_control_auth_manager(),
|
||||
&auth::RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||
RemoteControlClientsListParams {
|
||||
environment_id: "env-123".to_string(),
|
||||
..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 shutdown_token = CancellationToken::new();
|
||||
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(
|
||||
RemoteControlStartConfig {
|
||||
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 {
|
||||
assert_eq!(
|
||||
remote_handle
|
||||
.inner
|
||||
.session()
|
||||
.current_enrollment
|
||||
.snapshot()
|
||||
.and_then(|enrollment| enrollment.remote_control_token),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use super::CurrentRemoteControlEnrollment;
|
||||
use super::RemoteControlEnrollmentSelection;
|
||||
use super::RemoteControlPairingPersistenceKey;
|
||||
use super::auth::RemoteControlAuth;
|
||||
use super::auth::RemoteControlRecovery;
|
||||
use super::desired_state::RemoteControlDesiredState;
|
||||
use super::desired_state::acquire_persistence_lock;
|
||||
use super::desired_state::desired_state_from_persisted_enrollment;
|
||||
use super::persistence::RemoteControlPersistence;
|
||||
use super::protocol::ClientEnvelope;
|
||||
use super::protocol::ClientEvent;
|
||||
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::load_persisted_remote_control_enrollment;
|
||||
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::host_device_kind;
|
||||
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::RemoteControlStatusChangedNotification;
|
||||
use codex_core::util::backoff;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::UnauthorizedRecovery;
|
||||
use codex_state::StateRuntime;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use futures::SinkExt;
|
||||
@@ -54,7 +53,6 @@ use std::io::ErrorKind;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
@@ -256,17 +254,17 @@ impl WebsocketState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteControlWebsocket {
|
||||
pub(super) struct RemoteControlWebsocket {
|
||||
remote_control_url: String,
|
||||
installation_id: String,
|
||||
server_name: String,
|
||||
remote_control_target: Option<RemoteControlTarget>,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
auth_manager: RemoteControlAuth,
|
||||
status_publisher: RemoteControlStatusPublisher,
|
||||
shutdown_token: CancellationToken,
|
||||
reconnect_attempt: u64,
|
||||
auth_recovery: UnauthorizedRecovery,
|
||||
auth_recovery: RemoteControlRecovery,
|
||||
auth_change_rx: watch::Receiver<u64>,
|
||||
current_enrollment: CurrentRemoteControlEnrollment,
|
||||
pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||
@@ -276,10 +274,10 @@ pub(crate) struct RemoteControlWebsocket {
|
||||
used_rx: watch::Receiver<usize>,
|
||||
desired_state_tx: Arc<watch::Sender<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) installation_id: String,
|
||||
pub(crate) remote_control_target: Option<RemoteControlTarget>,
|
||||
@@ -287,8 +285,8 @@ pub(crate) struct RemoteControlWebsocketConfig {
|
||||
}
|
||||
|
||||
pub(super) struct RemoteControlAuthContext<'a> {
|
||||
auth_manager: &'a Arc<AuthManager>,
|
||||
auth_recovery: &'a mut UnauthorizedRecovery,
|
||||
auth_manager: &'a RemoteControlAuth,
|
||||
auth_recovery: &'a mut RemoteControlRecovery,
|
||||
auth_change_rx: &'a mut watch::Receiver<u64>,
|
||||
}
|
||||
|
||||
@@ -305,6 +303,7 @@ enum ConnectOutcome {
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ConnectionEndReason {
|
||||
AuthOwnerChanged,
|
||||
Shutdown,
|
||||
Disabled,
|
||||
EnabledWatchClosed,
|
||||
@@ -316,7 +315,7 @@ pub(super) struct RemoteControlChannels {
|
||||
pub(super) status_publisher: RemoteControlStatusPublisher,
|
||||
pub(super) current_enrollment: CurrentRemoteControlEnrollment,
|
||||
pub(super) pairing_persistence_key: RemoteControlPairingPersistenceKey,
|
||||
pub(super) desired_state_persistence_lock: Arc<Semaphore>,
|
||||
pub(super) persistence: RemoteControlPersistence,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -399,14 +398,14 @@ pub(super) struct RemoteControlConnectOptions<'a> {
|
||||
subscribe_cursor: Option<&'a str>,
|
||||
app_server_client_name: Option<&'a str>,
|
||||
desired_state_tx: &'a watch::Sender<RemoteControlDesiredState>,
|
||||
desired_state_persistence_lock: &'a Semaphore,
|
||||
persistence: &'a RemoteControlPersistence,
|
||||
}
|
||||
|
||||
impl RemoteControlWebsocket {
|
||||
pub(crate) fn new(
|
||||
pub(super) fn new(
|
||||
config: RemoteControlWebsocketConfig,
|
||||
state_db: Option<Arc<StateRuntime>>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
auth_manager: RemoteControlAuth,
|
||||
channels: RemoteControlChannels,
|
||||
shutdown_token: CancellationToken,
|
||||
desired_state_tx: Arc<watch::Sender<RemoteControlDesiredState>>,
|
||||
@@ -449,7 +448,7 @@ impl RemoteControlWebsocket {
|
||||
used_rx,
|
||||
desired_state_tx,
|
||||
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,
|
||||
reason = "remote-control client shutdown must serialize tracker state"
|
||||
)]
|
||||
pub(crate) async fn run(
|
||||
pub(super) async fn run(
|
||||
mut self,
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
) {
|
||||
let auth_owner = self.auth_manager.owner.clone();
|
||||
info!(
|
||||
remote_control_url = %self.remote_control_url,
|
||||
installation_id = %self.installation_id,
|
||||
@@ -487,30 +487,7 @@ impl RemoteControlWebsocket {
|
||||
};
|
||||
self.pairing_persistence_key
|
||||
.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 {
|
||||
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();
|
||||
info!(
|
||||
remote_control_url = %self.remote_control_url,
|
||||
@@ -522,10 +499,23 @@ impl RemoteControlWebsocket {
|
||||
"starting app-server remote control websocket connection cycle"
|
||||
);
|
||||
let shutdown_token = self.shutdown_token.child_token();
|
||||
let websocket_connection = match self
|
||||
.connect(&shutdown_token, app_server_client_name.as_deref())
|
||||
.await
|
||||
{
|
||||
let connect_outcome = tokio::select! {
|
||||
biased;
|
||||
_ = 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::Disabled => {
|
||||
self.status_publisher
|
||||
@@ -621,14 +611,20 @@ impl RemoteControlWebsocket {
|
||||
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(
|
||||
&remote_control_target.websocket_url,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await
|
||||
{
|
||||
.await;
|
||||
drop(_persistence);
|
||||
let enrollment = match enrollment {
|
||||
Ok(enrollment) => enrollment,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
@@ -724,7 +720,7 @@ impl RemoteControlWebsocket {
|
||||
subscribe_cursor: subscribe_cursor.as_deref(),
|
||||
app_server_client_name,
|
||||
desired_state_tx: &self.desired_state_tx,
|
||||
desired_state_persistence_lock: &self.desired_state_persistence_lock,
|
||||
persistence: &self.persistence,
|
||||
};
|
||||
let auth_context = RemoteControlAuthContext {
|
||||
auth_manager: &self.auth_manager,
|
||||
@@ -846,6 +842,10 @@ impl RemoteControlWebsocket {
|
||||
websocket_connection: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||
shutdown_token: CancellationToken,
|
||||
) -> 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 mut join_set = tokio::task::JoinSet::new();
|
||||
|
||||
@@ -867,7 +867,9 @@ impl RemoteControlWebsocket {
|
||||
|
||||
let mut desired_state_rx = self.desired_state_rx.clone();
|
||||
let connection_end_reason = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown_token.cancelled() => ConnectionEndReason::Shutdown,
|
||||
_ = self.auth_manager.owner.invalidated() => ConnectionEndReason::AuthOwnerChanged,
|
||||
changed = desired_state_rx.wait_for(|state| !state.is_enabled()) => {
|
||||
if changed.is_ok() {
|
||||
self.status_publisher
|
||||
@@ -1505,32 +1507,14 @@ async fn prepare_remote_control_enrollment(
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let enrollment_account_id = enrollment.as_ref().map(|enrollment| &enrollment.account_id);
|
||||
if enrollment_account_id.is_some_and(|account_id| account_id != &auth.account_id) {
|
||||
resolve_desired_state_after_account_change(
|
||||
state_db,
|
||||
remote_control_target,
|
||||
auth_context.auth_manager,
|
||||
&auth.account_id,
|
||||
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 enrollment
|
||||
.as_ref()
|
||||
.is_some_and(|enrollment| enrollment.account_id != auth.account_id)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::Interrupted,
|
||||
"enrollment belongs to another remote session",
|
||||
));
|
||||
}
|
||||
if let Some(enrollment) = enrollment.as_mut() {
|
||||
enrollment.remote_control_target = remote_control_target.clone();
|
||||
@@ -1541,6 +1525,9 @@ async fn prepare_remote_control_enrollment(
|
||||
}
|
||||
|
||||
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(
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
@@ -1637,51 +1624,6 @@ async fn prepare_remote_control_enrollment(
|
||||
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(
|
||||
response: &tungstenite::http::Response<Option<Vec<u8>>>,
|
||||
) -> bool {
|
||||
@@ -1799,33 +1741,15 @@ async fn enroll_and_persist_remote_control_server(
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let _persistence =
|
||||
acquire_persistence_lock(connect_options.desired_state_persistence_lock).await;
|
||||
let persistence_preference = match *connect_options.desired_state_tx.borrow() {
|
||||
RemoteControlDesiredState::Enabled {
|
||||
persistence_preference,
|
||||
} => 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,
|
||||
super::persistence::save_enrollment(
|
||||
auth_context.recovery.auth_manager,
|
||||
connect_options.persistence,
|
||||
state_db,
|
||||
&new_enrollment,
|
||||
connect_options.app_server_client_name,
|
||||
Some(&new_enrollment),
|
||||
persistence_preference,
|
||||
connect_options.desired_state_tx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to persist remote control enrollment in sqlite state db: {err}"
|
||||
)));
|
||||
}
|
||||
.await?;
|
||||
info!(
|
||||
"created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
remote_control_target.websocket_url,
|
||||
@@ -1881,6 +1805,7 @@ mod tests {
|
||||
use codex_core::test_support::auth_manager_from_auth;
|
||||
use codex_login::AuthDotJson;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::save_auth;
|
||||
use codex_login::token_data::TokenData;
|
||||
@@ -2155,7 +2080,8 @@ mod tests {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
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 current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
@@ -2166,7 +2092,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
Some(state_db.as_ref()),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2177,7 +2103,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2212,7 +2138,8 @@ mod tests {
|
||||
let codex_home = TempDir::new().expect("temp dir should create");
|
||||
let state_db = remote_control_state_runtime(&codex_home).await;
|
||||
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 next_refresh_at = time::OffsetDateTime::now_utc() + time::Duration::minutes(2);
|
||||
let mut enrollment = remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
@@ -2233,7 +2160,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
Some(state_db.as_ref()),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2244,7 +2171,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2307,7 +2234,8 @@ mod tests {
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.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 current_enrollment = test_current_enrollment(/*enrollment*/ None);
|
||||
let (status_publisher, status_rx) = remote_control_status_channel();
|
||||
@@ -2323,7 +2251,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
Some(state_db.as_ref()),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2334,7 +2262,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2406,7 +2334,8 @@ mod tests {
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.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 expected_enrollment =
|
||||
remote_control_enrollment(Some(TEST_REMOTE_CONTROL_SERVER_TOKEN));
|
||||
@@ -2427,7 +2356,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
Some(state_db.as_ref()),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2438,7 +2367,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2484,7 +2413,8 @@ mod tests {
|
||||
let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/")
|
||||
.expect("target should parse");
|
||||
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 current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
@@ -2495,7 +2425,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
/*state_db*/ None,
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2506,7 +2436,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2534,7 +2464,8 @@ mod tests {
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.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 current_enrollment = test_current_enrollment(Some(remote_control_enrollment(Some(
|
||||
TEST_REMOTE_CONTROL_SERVER_TOKEN,
|
||||
@@ -2550,7 +2481,7 @@ mod tests {
|
||||
&remote_control_target,
|
||||
Some(state_db.as_ref()),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager: &auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -2561,7 +2492,7 @@ mod tests {
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &enabled_desired_state_sender(),
|
||||
desired_state_persistence_lock: &Semaphore::new(1),
|
||||
persistence: &RemoteControlPersistence::default(),
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
@@ -2614,13 +2545,13 @@ mod tests {
|
||||
server_name: "test-server".to_string(),
|
||||
},
|
||||
/*state_db*/ None,
|
||||
remote_control_auth_manager(),
|
||||
RemoteControlAuth::capture(remote_control_auth_manager()).0,
|
||||
RemoteControlChannels {
|
||||
transport_event_tx,
|
||||
status_publisher,
|
||||
current_enrollment: test_current_enrollment(/*enrollment*/ None),
|
||||
pairing_persistence_key: watch::channel(None).0,
|
||||
desired_state_persistence_lock: Arc::new(Semaphore::new(1)),
|
||||
persistence: RemoteControlPersistence::default(),
|
||||
},
|
||||
shutdown_token,
|
||||
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_config::types::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::save_auth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
@@ -36,16 +37,17 @@ async fn connect_test_websocket(
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
current_enrollment: &CurrentRemoteControlEnrollment,
|
||||
) -> 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 (status_publisher, _) = remote_control_status_channel();
|
||||
let desired_state_tx = enabled_desired_state_sender();
|
||||
let desired_state_persistence_lock = Semaphore::new(1);
|
||||
let persistence = RemoteControlPersistence::default();
|
||||
connect_remote_control_websocket(
|
||||
remote_control_target,
|
||||
Some(state_db),
|
||||
RemoteControlAuthContext {
|
||||
auth_manager,
|
||||
auth_manager: &session_auth,
|
||||
auth_recovery: &mut auth_recovery,
|
||||
auth_change_rx: &mut auth_change_rx,
|
||||
},
|
||||
@@ -56,7 +58,7 @@ async fn connect_test_websocket(
|
||||
subscribe_cursor: None,
|
||||
app_server_client_name: None,
|
||||
desired_state_tx: &desired_state_tx,
|
||||
desired_state_persistence_lock: &desired_state_persistence_lock,
|
||||
persistence: &persistence,
|
||||
},
|
||||
&status_publisher,
|
||||
)
|
||||
|
||||
@@ -33,6 +33,7 @@ pub async fn start_stdio_connection(
|
||||
.send(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::Stdio,
|
||||
auth: None,
|
||||
writer: writer_tx,
|
||||
disconnect_sender: None,
|
||||
})
|
||||
|
||||
@@ -187,6 +187,7 @@ pub(crate) async fn run_websocket_connection<M, SinkError, StreamError>(
|
||||
.send(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::WebSocket,
|
||||
auth: None,
|
||||
writer: writer_tx,
|
||||
disconnect_sender: Some(disconnect_token.clone()),
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user