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
33 changes: 31 additions & 2 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};

use secrecy::{ExposeSecret as _, SecretString};
use serde::Deserialize;
use url::Url;
use uuid::Uuid;

use crate::api::{ApiError, Http};
use crate::credentials::{Credential, Source};
use crate::text;

const GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
const SLOW_DOWN_SECONDS: u64 = 5;
Expand Down Expand Up @@ -75,16 +77,43 @@ pub async fn start(http: &Http, scopes: &[String]) -> Result<Challenge, DeviceEr
}
let body: ChallengeBody =
serde_json::from_slice(&reply.body).map_err(|error| http.protocol(error.to_string()))?;
// The code is printed for the person to type, so it must not carry
// characters that could move the cursor or reorder the text.
if text::one_line(&body.user_code) != body.user_code {
return Err(http
.protocol("user_code contains control characters")
.into());
}
let verification_uri = approval_page(http, "verification_uri", &body.verification_uri)?;
let verification_uri_complete = body
.verification_uri_complete
.map(|address| approval_page(http, "verification_uri_complete", &address))
.transpose()?;
Ok(Challenge {
device_code: SecretString::from(body.device_code),
user_code: SecretString::from(body.user_code),
verification_uri: body.verification_uri,
verification_uri_complete: body.verification_uri_complete.map(SecretString::from),
verification_uri,
verification_uri_complete: verification_uri_complete.map(SecretString::from),
expires_in: body.expires_in,
interval: body.interval.max(1),
})
}

/// Returns `address` when it is a page on the console's own origin. The CLI
/// opens it in a browser, so a page on another site, or a `file:` or custom
/// scheme, is refused. The scheme is checked too, because a `blob:` URL takes
/// the origin of the URL inside it. The serialized URL is ASCII, so it is safe
/// to print.
fn approval_page(http: &Http, field: &str, address: &str) -> Result<String, ApiError> {
let page = Url::parse(address).map_err(|_| http.protocol(format!("{field} is not a URL")))?;
if !matches!(page.scheme(), "http" | "https")
|| page.origin().ascii_serialization() != http.origin().as_key()
{
return Err(http.protocol(format!("{field} is not on {}", http.origin())));
}
Ok(page.into())
}

/// Polls until the person approves, refuses or the code expires.
/// `organization` names the organization when the server does not report it.
pub async fn finish(
Expand Down
95 changes: 89 additions & 6 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,17 +429,31 @@ struct Fake {
polls: Arc<AtomicUsize>,
report_organization: bool,
summary: Option<Value>,
/// Fields that replace the stand-in's own device-code reply.
challenge: Option<Value>,
}

async fn code() -> Json<Value> {
Json(json!({
/// Answers with approval pages on the stand-in's own origin, as the console does.
/// `ORIGIN` in an overriding field stands for that origin.
async fn code(State(fake): State<Fake>, headers: HeaderMap) -> Json<Value> {
let origin = format!("http://{}", headers[header::HOST].to_str().unwrap());
let mut body = json!({
"device_code": "d".repeat(52),
"user_code": "WDJB-MJHT",
"verification_uri": "http://127.0.0.1/auth/device",
"verification_uri_complete": "http://127.0.0.1/auth/device?user_code=WDJB-MJHT",
"verification_uri": format!("{origin}/auth/device"),
"verification_uri_complete": format!("{origin}/auth/device?user_code=WDJB-MJHT"),
"expires_in": 600,
"interval": 1,
}))
});
if let Some(Value::Object(fields)) = fake.challenge {
for (name, value) in fields {
body[name] = match value {
Value::String(text) => Value::String(text.replace("ORIGIN", &origin)),
other => other,
};
}
}
Json(body)
}

async fn token(State(fake): State<Fake>, Json(body): Json<Value>) -> Response {
Expand Down Expand Up @@ -579,11 +593,25 @@ fn org() -> Uuid {
async fn device_sign_in_waits_for_approval_and_keeps_the_organization() {
let fake = Fake {
report_organization: true,
// Same-origin pages whose dot segments the parsed URL removes.
challenge: Some(json!({
"verification_uri": "ORIGIN/auth/./device",
"verification_uri_complete": "ORIGIN/auth/x/../device?user_code=WDJB-MJHT",
})),
..Fake::default()
};
let http = Http::new(serve(fake.clone()).await).unwrap();
let origin = serve(fake.clone()).await;
let http = Http::new(origin.clone()).unwrap();
let challenge = device::start(&http, &[]).await.unwrap();
assert_eq!(challenge.user_code.expose_secret(), "WDJB-MJHT");
assert_eq!(challenge.verification_uri, format!("{origin}/auth/device"));
assert_eq!(
challenge
.verification_uri_complete
.as_ref()
.map(|complete| complete.expose_secret().to_owned()),
Some(format!("{origin}/auth/device?user_code=WDJB-MJHT"))
);
assert!(format!("{challenge:?}").contains("REDACTED"));
assert!(!format!("{challenge:?}").contains("WDJB"));
let credential = device::finish(&http, &challenge, None).await.unwrap();
Expand All @@ -597,6 +625,61 @@ async fn device_sign_in_waits_for_approval_and_keeps_the_organization() {
assert!(!format!("{credential:?}").contains(TOKEN));
}

#[tokio::test]
async fn a_sign_in_page_on_another_origin_is_refused() {
for (field, address) in [
("verification_uri", "https://proofline.example/auth/device"),
(
"verification_uri_complete",
"https://proofline.example/auth/device?user_code=WDJB-MJHT",
),
(
"verification_uri_complete",
"file:///C:/Windows/System32/calc.exe",
),
// Same scheme and host as the stand-in, whose port is never 1.
("verification_uri", "http://127.0.0.1:1/auth/device"),
("verification_uri", "not a url"),
// A blob: URL takes the origin of the URL inside it.
("verification_uri_complete", "blob:ORIGIN/0190f3a0"),
] {
let http = Http::new(
serve(Fake {
challenge: Some(json!({ field: address })),
..Fake::default()
})
.await,
)
.unwrap();
let refusal = device::start(&http, &[]).await.unwrap_err();
assert!(
matches!(&refusal, DeviceError::Api(ApiError::Protocol { .. })),
"{field} = {address}: {refusal:?}"
);
assert!(refusal.to_string().contains(field), "{refusal}");
}
}

#[tokio::test]
async fn a_sign_in_code_that_could_rewrite_the_terminal_is_refused() {
for code in ["WDJB-MJHT\u{1b}[2J", "WDJB-\u{202E}THJM", "WDJB\nMJHT"] {
let http = Http::new(
serve(Fake {
challenge: Some(json!({ "user_code": code })),
..Fake::default()
})
.await,
)
.unwrap();
let refusal = device::start(&http, &[]).await.unwrap_err();
assert!(
matches!(&refusal, DeviceError::Api(ApiError::Protocol { .. })),
"{code:?}: {refusal:?}"
);
assert!(!refusal.to_string().contains(code), "{refusal}");
}
}

#[tokio::test]
async fn a_server_that_omits_the_organization_needs_one_named() {
let http = Http::new(serve(Fake::default()).await).unwrap();
Expand Down