Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(auth): enforce device authorization polling deadlines
Samir Hanna Verza61c702ccb693
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d7569b73..07773123 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,14 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed++- Made `auth login --timeout-secs` stop device-authorization polling requests+ and waits at the deadline for OpenAI OAuth, GitHub Copilot and OIDC device+ login. Late polling results no longer reach credential storage; provider+ intervals and `slow_down` backoff are preserved. OpenAI's subsequent exchange+ of an authorized code keeps its own HTTP request timeout (#PR).+## [3.2.10] - 2026-10-29### Changeddiff --git a/crates/ai-memory-cli/src/commands/auth.rs b/crates/ai-memory-cli/src/commands/auth.rsindex 2367b1b1..20696930 100644--- a/crates/ai-memory-cli/src/commands/auth.rs+++ b/crates/ai-memory-cli/src/commands/auth.rs@@ -2,7 +2,7 @@//! bearer token on this install's own server (`auth enable`).use std::path::Path;-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};+use std::time::{Duration, SystemTime, UNIX_EPOCH};use ai_memory_llm::{CODEX_CLIENT_ID, CopilotToken, DeviceAuthorizationResponse, GITHUB_ACCESS_TOKEN_URL,@@ -120,7 +120,6 @@ async fn poll_oidc_device(device: &DeviceAuthorizationResponse,timeout: Duration,) -> Result<OidcTokenResponse> {- let started = Instant::now();let mut interval = Duration::from_secs(device.interval@@ -130,19 +129,37 @@ async fn poll_oidc_device();let device_timeout = Duration::from_secs(device.expires_in.unwrap_or(600).max(1));let timeout = timeout.min(device_timeout);- loop {- if started.elapsed() >= timeout {- bail!("timed out waiting for oidc-device authorization");- }- match poll_token_once(client, discovery, client_id, &device.device_code).await? {- PollOutcome::Token(token) => return Ok(*token),- PollOutcome::Pending => {}- PollOutcome::SlowDown => interval = interval.saturating_add(Duration::from_secs(5)),- PollOutcome::Denied => bail!("oidc-device authorization denied"),- PollOutcome::Expired => bail!("oidc-device code expired before authorization"),- PollOutcome::Other(error) => bail!("oidc-device authorization failed: {error}"),+ with_authorization_timeout(timeout, "oidc-device", async {+ loop {+ match poll_token_once(client, discovery, client_id, &device.device_code).await? {+ PollOutcome::Token(token) => return Ok(*token),+ PollOutcome::Pending => {}+ PollOutcome::SlowDown => interval = interval.saturating_add(Duration::from_secs(5)),+ PollOutcome::Denied => bail!("oidc-device authorization denied"),+ PollOutcome::Expired => bail!("oidc-device code expired before authorization"),+ PollOutcome::Other(error) => bail!("oidc-device authorization failed: {error}"),+ }+ sleep(interval).await;}- sleep(interval).await;+ })+ .await+}++/// Cancel the whole poll, including a response body or provider-directed sleep.+/// A ready deadline wins over a simultaneously ready token, so a late result+/// cannot reach the credential store. The interval between requests is unchanged.+async fn with_authorization_timeout<T>(+ timeout: Duration,+ provider: &str,+ authorization: impl std::future::Future<Output = Result<T>>,+) -> Result<T> {+ if timeout.is_zero() {+ bail!("timed out waiting for {provider} authorization");+ }+ tokio::select! {+ biased;+ () = sleep(timeout) => bail!("timed out waiting for {provider} authorization"),+ result = authorization => result,}}@@ -350,7 +367,6 @@ async fn poll_device_authorization(device: &DeviceAuthorization,timeout: Duration,) -> Result<DeviceAuthorizationCode> {- let started = Instant::now();let interval = Duration::from_secs(device.interval@@ -359,34 +375,34 @@ async fn poll_device_authorization(.max(1).saturating_add(POLLING_SAFETY_MARGIN_SECS),);- loop {- if started.elapsed() >= timeout {- bail!("timed out waiting for openai-oauth authorization");- }- let resp = client- .post(DEVICE_TOKEN_URL)- .json(&DeviceTokenRequest {- device_auth_id: &device.device_auth_id,- user_code: &device.user_code,- })- .send()- .await- .context("polling openai-oauth device authorization")?;- if resp.status().is_success() {- return resp- .json::<DeviceAuthorizationCode>()+ with_authorization_timeout(timeout, "openai-oauth", async {+ loop {+ let resp = client+ .post(DEVICE_TOKEN_URL)+ .json(&DeviceTokenRequest {+ device_auth_id: &device.device_auth_id,+ user_code: &device.user_code,+ })+ .send().await- .context("parsing openai-oauth authorization code");- }- if resp.status() != reqwest::StatusCode::FORBIDDEN- && resp.status() != reqwest::StatusCode::NOT_FOUND- {- let status = resp.status();- let body = provider_error_body(resp).await;- bail!("openai-oauth authorization polling failed ({status}): {body}");+ .context("polling openai-oauth device authorization")?;+ if resp.status().is_success() {+ return resp+ .json::<DeviceAuthorizationCode>()+ .await+ .context("parsing openai-oauth authorization code");+ }+ if resp.status() != reqwest::StatusCode::FORBIDDEN+ && resp.status() != reqwest::StatusCode::NOT_FOUND+ {+ let status = resp.status();+ let body = provider_error_body(resp).await;+ bail!("openai-oauth authorization polling failed ({status}): {body}");+ }+ sleep(interval).await;}- sleep(interval).await;- }+ })+ .await}async fn exchange_authorization_code(@@ -442,52 +458,51 @@ async fn poll_github_device_authorization(device: &GitHubDeviceAuthorization,timeout: Duration,) -> Result<String> {- let started = Instant::now();let mut interval = Duration::from_secs(device.interval.unwrap_or(5).max(1));let device_timeout = Duration::from_secs(device.expires_in.max(1));let timeout = timeout.min(device_timeout);- loop {- if started.elapsed() >= timeout {- bail!("timed out waiting for copilot GitHub authorization");- }- let resp = client- .post(GITHUB_ACCESS_TOKEN_URL)- .header(reqwest::header::ACCEPT, "application/json")- .form(&[- ("client_id", client_id),- ("device_code", device.device_code.as_str()),- ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),- ])- .send()- .await- .context("polling copilot GitHub device authorization")?;- let status = resp.status();- if !status.is_success() {- let body = provider_error_body(resp).await;- bail!("copilot GitHub authorization polling failed ({status}): {body}");- }- let body = resp- .json::<GitHubDeviceAccessToken>()- .await- .context("parsing copilot GitHub token response")?;- if let Some(token) = body.access_token {- return Ok(token);- }- match body.error.as_deref() {- Some("authorization_pending") => {}- Some("slow_down") => interval = interval.saturating_add(Duration::from_secs(5)),- Some("expired_token") => bail!("copilot GitHub device code expired"),- Some("access_denied") => bail!("copilot GitHub authorization denied"),- Some(error) => {- let description = body.error_description.unwrap_or_default();- return Err(anyhow!(- "copilot GitHub authorization failed: {error} {description}"- ));+ with_authorization_timeout(timeout, "copilot GitHub", async {+ loop {+ let resp = client+ .post(GITHUB_ACCESS_TOKEN_URL)+ .header(reqwest::header::ACCEPT, "application/json")+ .form(&[+ ("client_id", client_id),+ ("device_code", device.device_code.as_str()),+ ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),+ ])+ .send()+ .await+ .context("polling copilot GitHub device authorization")?;+ let status = resp.status();+ if !status.is_success() {+ let body = provider_error_body(resp).await;+ bail!("copilot GitHub authorization polling failed ({status}): {body}");+ }+ let body = resp+ .json::<GitHubDeviceAccessToken>()+ .await+ .context("parsing copilot GitHub token response")?;+ if let Some(token) = body.access_token {+ return Ok(token);+ }+ match body.error.as_deref() {+ Some("authorization_pending") => {}+ Some("slow_down") => interval = interval.saturating_add(Duration::from_secs(5)),+ Some("expired_token") => bail!("copilot GitHub device code expired"),+ Some("access_denied") => bail!("copilot GitHub authorization denied"),+ Some(error) => {+ let description = body.error_description.unwrap_or_default();+ return Err(anyhow!(+ "copilot GitHub authorization failed: {error} {description}"+ ));+ }+ None => bail!("copilot GitHub token response did not include access_token"),}- None => bail!("copilot GitHub token response did not include access_token"),+ sleep(interval).await;}- sleep(interval).await;- }+ })+ .await}fn format_duration_until(expires_at_ms: u64) -> String {@@ -563,6 +578,60 @@ mod tests {assert_eq!(format_duration_until(0), "expired");}+ #[tokio::test(start_paused = true)]+ async fn authorization_timeout_covers_pending_work_and_keeps_provider_error_messages() {+ for provider in ["oidc-device", "openai-oauth", "copilot GitHub"] {+ let started = tokio::time::Instant::now();+ let result = with_authorization_timeout(Duration::from_secs(1), provider, async {+ sleep(Duration::from_secs(60)).await;+ Ok(())+ })+ .await;+ assert_eq!(+ result.unwrap_err().to_string(),+ format!("timed out waiting for {provider} authorization"),+ );+ assert_eq!(started.elapsed(), Duration::from_secs(1));+ }+ }++ #[tokio::test(start_paused = true)]+ async fn authorization_timeout_wins_when_the_token_and_deadline_are_ready() {+ let result = with_authorization_timeout(Duration::from_secs(1), "oidc-device", async {+ sleep(Duration::from_secs(1)).await;+ Ok("late token")+ })+ .await;+ assert!(result.is_err());+ }++ #[tokio::test(start_paused = true)]+ async fn authorization_timeout_zero_does_not_start_a_request() {+ let requested = std::cell::Cell::new(false);+ let result = with_authorization_timeout(Duration::ZERO, "oidc-device", async {+ requested.set(true);+ Ok(())+ })+ .await;+ assert!(result.is_err());+ assert!(!requested.get());+ }++ #[tokio::test(start_paused = true)]+ async fn authorization_timeout_preserves_a_prompt_provider_error() {+ let started = tokio::time::Instant::now();+ let result: Result<()> =+ with_authorization_timeout(Duration::from_secs(60), "oidc-device", async {+ bail!("oidc-device authorization denied")+ })+ .await;+ assert_eq!(+ result.unwrap_err().to_string(),+ "oidc-device authorization denied"+ );+ assert_eq!(started.elapsed(), Duration::ZERO);+ }+#[tokio::test]async fn auth_client_never_forwards_credentials_through_redirects() {use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};diff --git a/crates/ai-memory-cli/tests/suite/auth_device_timeout.rs b/crates/ai-memory-cli/tests/suite/auth_device_timeout.rsnew file mode 100644index 00000000..bd9696d2--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/auth_device_timeout.rs@@ -0,0 +1,191 @@+//! Device-login deadlines cover HTTP polling and provider-directed waits.++mod slow {+ use std::path::Path;+ use std::process::Output;+ use std::sync::Arc;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use std::time::Duration;++ use axum::http::StatusCode;+ use axum::routing::{get, post};+ use axum::{Json, Router};+ use serde_json::json;+ use tokio::sync::Notify;++ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++ #[derive(Clone, Copy)]+ enum Reply {+ Error(&'static str),+ Token(Duration),+ }++ struct Issuer {+ url: String,+ polled: Arc<Notify>,+ polls: Arc<AtomicUsize>,+ task: tokio::task::JoinHandle<()>,+ }++ impl Drop for Issuer {+ fn drop(&mut self) {+ self.task.abort();+ }+ }++ async fn issuer(reply: Reply) -> Issuer {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let discovery = json!({+ "device_authorization_endpoint": format!("{url}/device"),+ "token_endpoint": format!("{url}/token"),+ });+ let device = json!({+ "device_code": "synthetic-device-code",+ "user_code": "TEST-CODE",+ "verification_uri": format!("{url}/verify"),+ "interval": 20,+ "expires_in": 600,+ });+ let polled = Arc::new(Notify::new());+ let polls = Arc::new(AtomicUsize::new(0));+ let notify = Arc::clone(&polled);+ let count = Arc::clone(&polls);+ let app = Router::new()+ .route(+ "/.well-known/openid-configuration",+ get(move || async move { Json(discovery) }),+ )+ .route("/device", post(move || async move { Json(device) }))+ .route(+ "/token",+ post(move || {+ let notify = Arc::clone(¬ify);+ let count = Arc::clone(&count);+ async move {+ count.fetch_add(1, Ordering::SeqCst);+ notify.notify_one();+ match reply {+ Reply::Error(error) => {+ (StatusCode::BAD_REQUEST, Json(json!({ "error": error })))+ }+ Reply::Token(delay) => {+ tokio::time::sleep(delay).await;+ (+ StatusCode::OK,+ Json(json!({+ "access_token": "synthetic-access",+ "refresh_token": "synthetic-refresh",+ "expires_in": 600,+ })),+ )+ }+ }+ }+ }),+ );+ let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ Issuer {+ url,+ polled,+ polls,+ task,+ }+ }++ async fn login(root: &Path, issuer: &Issuer, timeout_secs: &str) -> Output {+ let mut command = crate::e2e_support::hermetic(BIN);+ command+ .env("HOME", root)+ .env("USERPROFILE", root)+ .env("AI_MEMORY_HOME", root)+ .env("XDG_CONFIG_HOME", root.join("config"))+ .env("NO_PROXY", "127.0.0.1,localhost")+ .env("no_proxy", "127.0.0.1,localhost")+ .current_dir(root)+ .arg("--data-dir")+ .arg(root.join("data"))+ .args([+ "auth",+ "login",+ "oidc-device",+ "--issuer",+ &issuer.url,+ "--client-id",+ "synthetic-client",+ "--timeout-secs",+ timeout_secs,+ ]);+ let mut command = tokio::process::Command::from(command);+ command.kill_on_drop(true);+ let output = command.output();+ tokio::pin!(output);+ // Budget process startup separately: the product deadline starts only+ // once the device code is issued, not while macOS scans the binary.+ tokio::select! {+ biased;+ result = tokio::time::timeout(Duration::from_secs(30), issuer.polled.notified()) => {+ result.expect("login never reached the loopback token endpoint");+ }+ result = &mut output => panic!("login ended before polling: {result:?}"),+ }+ tokio::time::timeout(Duration::from_secs(5), &mut output)+ .await+ .expect("the one-second login deadline did not cancel polling")+ .unwrap()+ }++ #[rstest::rstest]+ #[case("authorization_pending")]+ #[case("slow_down")]+ #[tokio::test]+ async fn deadline_interrupts_provider_polling_waits(#[case] error: &'static str) {+ let root = tempfile::tempdir().unwrap();+ let issuer = issuer(Reply::Error(error)).await;+ let output = login(root.path(), &issuer, "1").await;+ assert!(!output.status.success(), "{output:?}");+ assert!(+ String::from_utf8_lossy(&output.stderr)+ .contains("timed out waiting for oidc-device authorization"),+ "{output:?}",+ );+ assert_eq!(issuer.polls.load(Ordering::SeqCst), 1);+ assert!(!root.path().join("data/auth.json").exists());+ }++ #[tokio::test]+ async fn deadline_discards_a_late_token_without_changing_stored_credentials() {+ let root = tempfile::tempdir().unwrap();+ std::fs::create_dir(root.path().join("data")).unwrap();+ let token_path = root.path().join("data/auth.json");+ let original = r#"{"fixture":{"keep":"unrelated-provider"}}"#;+ std::fs::write(&token_path, original).unwrap();+ let issuer = issuer(Reply::Token(Duration::from_secs(3))).await;+ let output = login(root.path(), &issuer, "1").await;+ assert!(+ !output.status.success(),+ "late authorization succeeded: {output:?}"+ );+ assert!(+ String::from_utf8_lossy(&output.stderr)+ .contains("timed out waiting for oidc-device authorization"),+ "{output:?}",+ );+ assert_eq!(std::fs::read_to_string(token_path).unwrap(), original);+ assert_eq!(issuer.polls.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn authorization_before_the_deadline_still_saves_the_token() {+ let root = tempfile::tempdir().unwrap();+ let issuer = issuer(Reply::Token(Duration::ZERO)).await;+ let output = login(root.path(), &issuer, "10").await;+ assert!(output.status.success(), "{output:?}");+ let stored: serde_json::Value =+ serde_json::from_slice(&std::fs::read(root.path().join("data/auth.json")).unwrap())+ .unwrap();+ assert_eq!(stored["oidc"]["access"], "synthetic-access");+ assert_eq!(issuer.polls.load(Ordering::SeqCst), 1);+ }+}diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex e5d12747..6ba14322 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -6,6 +6,7 @@//! so a new file must be declared here (`scripts/check-test-suites.*` enforces it).mod auth_default_e2e;+mod auth_device_timeout;mod autoscope_env;mod backfill_dry_run;mod backfill_e2e;diff --git a/docs/usage.md b/docs/usage.mdindex a0de1c9e..66885992 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -637,6 +637,14 @@ ai-memory auth statusCopilot auth stores a GitHub user token, then the provider exchanges it for ashort-lived Copilot API token before each LLM call.+Device login (`openai-oauth`, `copilot` and `oidc-device`) waits up to+`--timeout-secs` seconds for authorization after the device code is issued+(default: 600). The limit covers device-authorization polling requests,+response reads and pauses between polls, including a provider's `slow_down`+backoff. Reaching it discards the polling result without changing stored+credentials. Discovery, the initial device-code request and OpenAI's exchange+of a code authorized within the deadline keep their own HTTP request timeout.+## Browse the wiki in a browserStart the server with `--enable-web` and open