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))
Comment on lines +87 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Approval URL validation accepts same-origin blob: URLs

approval_page promises to reject custom schemes, but compares only origins. A blob: URL inherits its embedded URL’s origin and passes when that origin matches the console.

The CLI accepts an unsupported approval URL and may pass it to the browser.

Require the outer scheme to be http or https before comparing origins.

Details

Before this change, both fields were passed through without validation. This change introduces the scheme-rejection contract but does not enforce it for either field.

View finding in Proofline

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c1f35f9. Agreed: Url::origin() returns the inner URL's origin for blob:, so blob:<console origin>/id passed. I reproduced it first (new case in a_sign_in_page_on_another_origin_is_refused returned Ok), then made approval_page also require the http/https scheme. Same-origin plus an http(s) scheme means the scheme equals the console's.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marked fixed.

Comment on lines +87 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Device sign-in tests miss a required-complete-URL regression

Every device-code fixture supplies verification_uri_complete, so the new URL-validation coverage would still pass if device::start rejected responses that omit it.

Sign-in could fail before falling back to verification_uri without a test failing.

Add a successful response that omits verification_uri_complete and assert that the returned field is None.

Details

The base fixture also supplied both URLs, but it did not exercise the approval-URL validation added by this change.

View finding in Proofline

.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),
Comment on lines +438 to 441

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Successful sign-in test misses approval URL regressions

The fixture supplies already-serialized URLs, and the success test asserts neither URL returned by device::start.

The test still passes if validation succeeds but the complete URL is dropped or the original URL strings are returned unchanged.

Supply same-origin URLs that change on serialization and assert both exact serialized values, including the complete URL’s query.

View finding in Proofline

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c1f35f9 (placeholder renamed in c8eeeee). Agreed. The stub now accepts an ORIGIN placeholder, and the success test sends same-origin pages with dot segments (ORIGIN/auth/./device, ORIGIN/auth/x/../device?user_code=WDJB-MJHT) and asserts the exact cleaned-up values of both fields, including the query. Checked by mutation: making approval_page return the raw string fails the test (/auth/./device vs /auth/device).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marked fixed.

"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"),
Comment on lines +628 to +631

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Approval URL test misses port-only origin mismatches

Both HTTP(S) rejection cases change the scheme and hostname, so the test still passes if approval_page compares those components but ignores the port.

The test would miss a regression that accepts approval URLs on a different port.

Add a URL with the fixture’s scheme and hostname but a guaranteed different port, and assert a field-specific Protocol error.

View finding in Proofline

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5ea12ba. Agreed. Added http://127.0.0.1:1/auth/device: same scheme and host as the stand-in, port 1, which the ephemeral test port never is. It goes through the same field-specific Protocol assertion. Checked by mutation: comparing only the host makes the test fail.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marked fixed.

(
"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