From 691e75844fcb7e4d7ad54362595fdfe00a2396bb Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Thu, 3 Dec 2026 20:53:31 +0200 Subject: [PATCH 1/2] Show the server's OAuth error when sign-in is refused --- src/device.rs | 36 ++++++++++++++++++++++---- tests/http.rs | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 5 deletions(-) diff --git a/src/device.rs b/src/device.rs index a3dc2c5..ce813c0 100644 --- a/src/device.rs +++ b/src/device.rs @@ -8,8 +8,9 @@ use secrecy::{ExposeSecret as _, SecretString}; use serde::Deserialize; use uuid::Uuid; -use crate::api::{ApiError, Http}; +use crate::api::{ApiError, Http, Reply}; use crate::credentials::{Credential, Source}; +use crate::text::terminal_safe; const GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code"; const SLOW_DOWN_SECONDS: u64 = 5; @@ -47,6 +48,31 @@ struct TokenBody { #[derive(Deserialize)] struct OAuthError { error: String, + error_description: Option, +} + +impl OAuthError { + /// The refusal in the server's own words: its description, else its code. + fn refusal(self, http: &Http, reply: &Reply) -> ApiError { + let detail = self + .error_description + .as_deref() + .filter(|description| !description.trim().is_empty()) + .unwrap_or(&self.error); + ApiError::Problem { + origin: http.origin().to_string(), + status: reply.status.as_u16(), + detail: terminal_safe(detail), + code: Some(self.error), + } + } +} + +/// Sign-in refusals use OAuth's error body (RFC 6749 section 5.2), not the +/// API's problem details. +fn refused(http: &Http, reply: &Reply) -> ApiError { + serde_json::from_slice::(&reply.body) + .map_or_else(|_| http.problem(reply), |error| error.refusal(http, reply)) } #[derive(Debug, thiserror::Error)] @@ -79,7 +105,7 @@ pub async fn start( } let (reply, _) = http.send(http.post(url).json(&body)).await?; if !reply.status.is_success() { - return Err(http.problem(&reply).into()); + return Err(refused(http, &reply).into()); } let body: ChallengeBody = serde_json::from_slice(&reply.body).map_err(|error| http.protocol(error.to_string()))?; @@ -128,10 +154,10 @@ pub async fn finish( source: Source::Keychain, }); } - let Ok(OAuthError { error }) = serde_json::from_slice::(&reply.body) else { + let Ok(error) = serde_json::from_slice::(&reply.body) else { return Err(http.problem(&reply).into()); }; - match error.as_str() { + match error.error.as_str() { "authorization_pending" => {} "slow_down" => interval += SLOW_DOWN_SECONDS, "expired_token" => return Err(DeviceError::Expired), @@ -140,7 +166,7 @@ pub async fn finish( "the approving user no longer has access to that organization".to_owned(), )); } - _ => return Err(http.problem(&reply).into()), + _ => return Err(error.refusal(http, &reply).into()), } } } diff --git a/tests/http.rs b/tests/http.rs index eb15b98..7bc37c8 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -617,6 +617,78 @@ async fn a_server_that_omits_the_organization_needs_one_named() { assert_eq!(named.organization_id, org()); } +/// A sign-in server that refuses `knowledge:read` and every token poll with +/// OAuth error bodies (RFC 6749 section 5.2). +async fn refusing_sign_in(token_error: Value) -> Http { + let app = Router::new() + .route( + "/auth/device/code", + post(|Json(body): Json| async move { + if body["scopes"] != json!(["knowledge:read"]) { + return code().await.into_response(); + } + let error = json!({ + "error": "invalid_scope", + "error_description": "Choose one to ten supported API permissions.\u{1b}[2J", + }); + (StatusCode::BAD_REQUEST, Json(error)).into_response() + }), + ) + .route( + "/auth/device/token", + post(move || async move { (StatusCode::BAD_REQUEST, Json(token_error)) }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + Http::new(Origin::parse(&format!("http://{address}")).unwrap()).unwrap() +} + +#[tokio::test] +async fn a_refused_sign_in_shows_the_servers_oauth_error() { + let refusal = |error: DeviceError| { + let text = error.to_string(); + match error { + DeviceError::Api(ApiError::Problem { status, code, .. }) => (status, code, text), + other => panic!("expected the server's refusal, got {other}"), + } + }; + let http = refusing_sign_in(json!({ + "error": "invalid_grant", + "error_description": "This sign-in code was already used.", + })) + .await; + let (status, code, text) = refusal( + device::start(&http, &["knowledge:read".to_owned()], None) + .await + .unwrap_err(), + ); + assert_eq!((status, code.as_deref()), (400, Some("invalid_scope"))); + // The description is server text, so terminal controls stay escaped. + assert!( + text.ends_with("HTTP 400: Choose one to ten supported API permissions.\u{FFFD}[2J"), + "{text}" + ); + let challenge = device::start(&http, &[], None).await.unwrap(); + let (_, code, text) = refusal(device::finish(&http, &challenge, None).await.unwrap_err()); + assert_eq!(code.as_deref(), Some("invalid_grant")); + assert!( + text.ends_with("HTTP 400: This sign-in code was already used."), + "{text}" + ); + // Without a description, the error code says more than the status text. + for error in [ + json!({ "error": "invalid_request" }), + json!({ "error": "invalid_request", "error_description": " " }), + ] { + let http = refusing_sign_in(error).await; + let challenge = device::start(&http, &[], None).await.unwrap(); + let (_, code, text) = refusal(device::finish(&http, &challenge, None).await.unwrap_err()); + assert_eq!(code.as_deref(), Some("invalid_request")); + assert!(text.ends_with("HTTP 400: invalid_request"), "{text}"); + } +} + #[tokio::test] async fn a_review_reads_with_unknown_fields_and_keeps_its_gap() { let published = json!({ From a7f7fe4322e81b35970ad223b550f13667533738 Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Thu, 3 Dec 2026 21:14:54 +0200 Subject: [PATCH 2/2] Fall back to the status text when a sign-in refusal is blank --- src/device.rs | 18 +++++++++++------- tests/http.rs | 11 +++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/device.rs b/src/device.rs index ce813c0..1a42140 100644 --- a/src/device.rs +++ b/src/device.rs @@ -52,17 +52,21 @@ struct OAuthError { } impl OAuthError { - /// The refusal in the server's own words: its description, else its code. + /// The refusal in the server's own words: its description, else its code, + /// else the status text when both are blank. fn refusal(self, http: &Http, reply: &Reply) -> ApiError { - let detail = self - .error_description - .as_deref() - .filter(|description| !description.trim().is_empty()) - .unwrap_or(&self.error); + let Some(detail) = [self.error_description.as_deref(), Some(&self.error)] + .into_iter() + .flatten() + .find(|text| !text.trim().is_empty()) + .map(terminal_safe) + else { + return http.problem(reply); + }; ApiError::Problem { origin: http.origin().to_string(), status: reply.status.as_u16(), - detail: terminal_safe(detail), + detail, code: Some(self.error), } } diff --git a/tests/http.rs b/tests/http.rs index 7bc37c8..f9fb3e7 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -687,6 +687,17 @@ async fn a_refused_sign_in_shows_the_servers_oauth_error() { assert_eq!(code.as_deref(), Some("invalid_request")); assert!(text.ends_with("HTTP 400: invalid_request"), "{text}"); } + // With nothing to show, the status text stays, as before. + for error in [ + json!({ "error": " " }), + json!({ "error": "", "error_description": " " }), + ] { + let http = refusing_sign_in(error).await; + let challenge = device::start(&http, &[], None).await.unwrap(); + let (_, code, text) = refusal(device::finish(&http, &challenge, None).await.unwrap_err()); + assert_eq!(code, None); + assert!(text.ends_with("HTTP 400: Bad Request"), "{text}"); + } } #[tokio::test]