Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -47,6 +48,35 @@ struct TokenBody {
#[derive(Deserialize)]
struct OAuthError {
error: String,
error_description: Option<String>,
}

impl OAuthError {
/// 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 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,
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::<OAuthError>(&reply.body)
.map_or_else(|_| http.problem(reply), |error| error.refusal(http, reply))
}

#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -79,7 +109,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()))?;
Expand Down Expand Up @@ -128,10 +158,10 @@ pub async fn finish(
source: Source::Keychain,
});
}
let Ok(OAuthError { error }) = serde_json::from_slice::<OAuthError>(&reply.body) else {
let Ok(error) = serde_json::from_slice::<OAuthError>(&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),
Expand All @@ -140,7 +170,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()),
}
}
}
Expand Down
83 changes: 83 additions & 0 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,89 @@ 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<Value>| 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}");
}
// 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]
async fn a_review_reads_with_unknown_fields_and_keeps_its_gap() {
let published = json!({
Expand Down