Skip to content
Open
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
120 changes: 116 additions & 4 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,20 @@ pub async fn finish(
organization: Option<Uuid>,
) -> Result<Credential, DeviceError> {
let url = http.origin().join(["auth", "device", "token"]);
let deadline = tokio::time::Instant::now() + Duration::from_secs(challenge.expires_in);
let mut interval = challenge.interval;
let start = tokio::time::Instant::now();
let deadline = start
.checked_add(Duration::from_secs(challenge.expires_in))
.unwrap_or_else(|| start + Duration::from_secs(86_400));
let mut interval = challenge.interval.max(1);
loop {
tokio::time::sleep(Duration::from_secs(interval)).await;
if tokio::time::Instant::now() >= deadline {
let current = tokio::time::Instant::now();
if current >= deadline {
return Err(DeviceError::Expired);
}
let wake = current
.checked_add(Duration::from_secs(interval))
.map_or(deadline, |next| deadline.min(next));
tokio::time::sleep_until(wake).await;
let body = serde_json::json!({
"grant_type": GRANT,
"device_code": challenge.device_code.expose_secret(),
Expand Down Expand Up @@ -150,3 +157,108 @@ pub fn now() -> u64 {
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs())
}

#[cfg(test)]
mod tests {
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};

use axum::http::StatusCode;
use axum::response::IntoResponse as _;
use axum::routing::post;
use axum::{Json, Router};
use serde_json::json;

use super::*;
use crate::origin::Origin;

async fn token_server(approve_on_poll: usize) -> (Http, Arc<AtomicUsize>) {
let polls = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&polls);
let app = Router::new().route(
"/auth/device/token",
post(move || {
let counter = Arc::clone(&counter);
async move {
let poll = counter.fetch_add(1, Ordering::SeqCst) + 1;
if poll >= approve_on_poll {
Json(json!({
"access_token": "pld_final_window",
"expires_in": 3600,
"scope": "reviews:read",
"organization_id": "0190f3a0-0000-7000-8000-000000000001",
}))
.into_response()
} else {
(
StatusCode::BAD_REQUEST,
Json(json!({ "error": "authorization_pending" })),
)
.into_response()
}
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = Origin::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(Http::new(origin).unwrap(), polls)
}

fn challenge(expires_in: u64, interval: u64) -> Challenge {
Challenge {
device_code: SecretString::from("dev-code"),
user_code: SecretString::from("ABCD-EFGH"),
verification_uri: "https://proofline.sh/device".to_owned(),
verification_uri_complete: None,
expires_in,
interval,
}
}

/// When remaining lifetime before `expires_in` is shorter than `interval`,
/// `finish` caps its final sleep at the deadline and still polls once
/// instead of expiring without checking the late approval.
#[tokio::test(start_paused = true)]
async fn finish_polls_at_deadline_instead_of_sleeping_past_expiry() {
let ticker = tokio::spawn(async {
for _ in 0..10_000_000 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
});

// 7s expiry with 5s interval: poll 1 at 5s is pending, poll 2 at 7s succeeds.
let (http, polls) = token_server(2).await;
let start = tokio::time::Instant::now();
let credential = finish(&http, &challenge(7, 5), None).await.unwrap();
let elapsed = start.elapsed();
assert_eq!(polls.load(Ordering::SeqCst), 2);
assert_eq!(credential.token.expose_secret(), "pld_final_window");
assert!(
elapsed >= Duration::from_secs(7) && elapsed < Duration::from_secs(8),
"{elapsed:?}"
);

// If still pending at the final 7s poll, it expires without a third poll.
let (http, polls) = token_server(usize::MAX).await;
let start = tokio::time::Instant::now();
let err = finish(&http, &challenge(7, 5), None).await.unwrap_err();
let elapsed = start.elapsed();
assert!(matches!(err, DeviceError::Expired), "{err}");
assert_eq!(polls.load(Ordering::SeqCst), 2);
assert!(
elapsed >= Duration::from_secs(7) && elapsed < Duration::from_secs(8),
"{elapsed:?}"
);

// Already-expired challenge stops immediately with zero polls.
let (http, polls) = token_server(1).await;
let err = finish(&http, &challenge(0, 5), None).await.unwrap_err();
assert!(matches!(err, DeviceError::Expired), "{err}");
assert_eq!(polls.load(Ordering::SeqCst), 0);

ticker.abort();
}
}