use std::sync::Arc;
use bon::Builder;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt as _, Snafu};
use crate::{
core::{
EndpointUrl, Error,
client_auth::ClientAuthentication,
dpop::{AuthorizationServerDPoP, NoDPoP},
http::HttpClient,
platform::{Duration, sleep},
},
grant::{
core::{
OAuth2ExchangeGrant, TokenResponse,
form::{OAuth2FormRequest, with_dpop_nonce_retry},
},
refresh::RefreshGrant,
},
};
#[huskarl_macros::from_metadata(metadata = crate::core::server_metadata::AuthorizationServerMetadata)]
#[derive(Clone, Builder)]
#[builder(on(String, into))]
pub struct DeviceAuthorizationGrant {
client_id: String,
#[builder(with = |client: impl HttpClient + 'static| Arc::new(client) as Arc<dyn HttpClient>)]
http_client: Arc<dyn HttpClient>,
#[builder(with = |auth: impl ClientAuthentication + 'static| Arc::new(auth) as Arc<dyn ClientAuthentication>)]
client_auth: Arc<dyn ClientAuthentication>,
#[builder(
with = |dpop: impl AuthorizationServerDPoP + 'static| Arc::new(dpop) as Arc<dyn AuthorizationServerDPoP>,
default = Arc::new(NoDPoP),
)]
dpop: Arc<dyn AuthorizationServerDPoP>,
#[from_metadata(path = "issuer")]
issuer: Option<String>,
#[from_metadata(path = "token_endpoint")]
token_endpoint: EndpointUrl,
#[from_metadata(path = "mtls_endpoint_aliases?.token_endpoint?")]
mtls_token_endpoint: Option<EndpointUrl>,
#[builder(skip = crate::grant::core::resolve_mtls_alias(http_client.as_ref(), &token_endpoint, mtls_token_endpoint.as_ref()))]
effective_token_endpoint: EndpointUrl,
#[from_metadata(path = "token_endpoint_auth_methods_supported")]
token_endpoint_auth_methods_supported: Option<Vec<String>>,
#[from_metadata(path = "device_authorization_endpoint?")]
device_authorization_endpoint: EndpointUrl,
#[from_metadata(path = "mtls_endpoint_aliases?.device_authorization_endpoint?")]
mtls_device_authorization_endpoint: Option<EndpointUrl>,
#[builder(skip = crate::grant::core::resolve_mtls_alias(http_client.as_ref(), &device_authorization_endpoint, mtls_device_authorization_endpoint.as_ref()))]
effective_device_authorization_endpoint: EndpointUrl,
}
impl core::fmt::Debug for DeviceAuthorizationGrant {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("DeviceAuthorizationGrant")
.field("client_id", &self.client_id)
.field("issuer", &self.issuer)
.field("token_endpoint", &self.token_endpoint)
.field("mtls_token_endpoint", &self.mtls_token_endpoint)
.field(
"device_authorization_endpoint",
&self.device_authorization_endpoint,
)
.field(
"mtls_device_authorization_endpoint",
&self.mtls_device_authorization_endpoint,
)
.finish_non_exhaustive()
}
}
impl DeviceAuthorizationGrant {
pub async fn start(&self, start_input: StartInput) -> Result<StartOutput, Error> {
let payload = DeviceAuthorizationRequest {
scope: start_input.scopes.as_deref(),
resource: start_input.resource.as_deref(),
};
let device_auth_endpoint = &self.effective_device_authorization_endpoint;
let dpop_jkt = self.dpop().get_current_thumbprint();
let response: DeviceAuthorizationResponse = with_dpop_nonce_retry!({
let auth_params = self
.client_auth
.authentication_params(
&self.client_id,
self.issuer.as_deref(),
Some(&self.token_endpoint),
device_auth_endpoint,
self.token_endpoint_auth_methods_supported.as_deref(),
)
.await?;
OAuth2FormRequest::builder()
.form(&payload)
.auth_params(auth_params)
.uri(device_auth_endpoint.as_uri())
.dpop(self.dpop())
.maybe_dpop_jkt(dpop_jkt.as_deref())
.build()
.execute(self.http_client.as_ref())
.await
})?;
Ok(StartOutput::builder()
.expires_at(
crate::core::platform::SystemTime::now()
.checked_add(Duration::from_secs(response.expires_in.into()))
.unwrap_or_else(crate::core::platform::SystemTime::now),
)
.verification_uri(response.verification_uri)
.maybe_verification_uri_complete(response.verification_uri_complete)
.user_code(response.user_code)
.pending_state(PendingState {
device_code: response.device_code,
interval_secs: response.interval,
})
.build())
}
pub async fn poll_to_completion(
&self,
pending_state: &mut PendingState,
resource: Option<Vec<String>>,
) -> Result<TokenResponse, PollError> {
loop {
sleep(Duration::from_secs(pending_state.interval_secs.into())).await;
if let PollResult::Complete(token_response) =
self.poll(pending_state, resource.clone()).await?
{
return Ok(*token_response);
}
}
}
pub async fn poll(
&self,
pending_state: &mut PendingState,
resource: Option<Vec<String>>,
) -> Result<PollResult, PollError> {
let token_or_err = self
.exchange(super::grant::DeviceAuthorizationGrantParameters {
device_code: pending_state.device_code.clone(),
resource,
})
.await;
match token_or_err {
Ok(token) => Ok(PollResult::Complete(Box::new(token))),
Err(err) => match err.oauth_error_code() {
Some("slow_down") => {
pending_state.interval_secs = pending_state.interval_secs.saturating_add(5);
Ok(PollResult::Pending)
}
Some("authorization_pending") => Ok(PollResult::Pending),
Some("access_denied") => AccessDeniedSnafu.fail(),
Some("expired_token") => TokenExpiredSnafu.fail(),
_ => Err(err).context(ExchangeSnafu),
},
}
}
}
#[derive(Debug, Clone, Builder)]
pub struct DeviceAuthorizationGrantParameters {
pub device_code: String,
pub resource: Option<Vec<String>>,
}
#[derive(Debug, Serialize)]
pub struct DeviceAuthorizationGrantForm {
grant_type: &'static str,
device_code: String,
#[serde(skip_serializing_if = "Option::is_none")]
resource: Option<Vec<String>>,
}
impl OAuth2ExchangeGrant for DeviceAuthorizationGrant {
type Parameters = DeviceAuthorizationGrantParameters;
type Form<'a> = DeviceAuthorizationGrantForm;
fn client_id(&self) -> Option<&str> {
Some(&self.client_id)
}
fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
fn client_auth(&self) -> Option<&dyn ClientAuthentication> {
Some(self.client_auth.as_ref())
}
fn token_endpoint(&self) -> &EndpointUrl {
&self.token_endpoint
}
fn effective_token_endpoint(&self) -> &EndpointUrl {
&self.effective_token_endpoint
}
fn dpop(&self) -> &dyn AuthorizationServerDPoP {
self.dpop.as_ref()
}
fn http_client(&self) -> &dyn HttpClient {
self.http_client.as_ref()
}
fn allowed_auth_methods(&self) -> Option<&[String]> {
self.token_endpoint_auth_methods_supported.as_deref()
}
fn to_refresh_grant(&self) -> RefreshGrant {
RefreshGrant::builder()
.client_id(self.client_id.clone())
.maybe_issuer(self.issuer.clone())
.http_client(self.http_client.clone())
.client_auth(self.client_auth.clone())
.dpop(self.dpop.clone())
.token_endpoint(self.effective_token_endpoint.clone())
.maybe_token_endpoint_auth_methods_supported(
self.token_endpoint_auth_methods_supported.clone(),
)
.build()
}
fn build_form(&self, params: Self::Parameters) -> Self::Form<'_> {
DeviceAuthorizationGrantForm {
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
device_code: params.device_code,
resource: params.resource,
}
}
}
#[derive(Debug, Clone, Deserialize)]
struct DeviceAuthorizationResponse {
device_code: String,
user_code: String,
verification_uri: String,
verification_uri_complete: Option<String>,
expires_in: u32,
#[serde(default = "default_interval")]
interval: u32,
}
#[inline]
const fn default_interval() -> u32 {
5
}
#[derive(Debug, Serialize)]
struct DeviceAuthorizationRequest<'a> {
scope: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
resource: Option<&'a [String]>,
}
#[derive(Debug, Builder)]
#[builder(on(String, into))]
pub struct StartOutput {
pub user_code: String,
pub verification_uri: String,
pub verification_uri_complete: Option<String>,
pub expires_at: crate::core::platform::SystemTime,
pub pending_state: PendingState,
}
#[derive(Debug, Builder, Serialize, Deserialize)]
#[builder(on(String, into))]
pub struct PendingState {
pub device_code: String,
pub interval_secs: u32,
}
#[derive(Debug, Snafu)]
pub enum PollError {
AccessDenied,
TokenExpired,
Exchange {
source: Error,
},
}
#[derive(Debug)]
pub enum PollResult {
Pending,
Complete(Box<TokenResponse>),
}
#[derive(Debug, Clone, Builder)]
pub struct StartInput {
#[builder(required, with = |scopes: impl IntoIterator<Item = impl Into<String>>| crate::grant::core::mk_scopes(scopes))]
scopes: Option<String>,
resource: Option<Vec<String>>,
}
impl StartInput {
#[must_use]
pub fn scopes(scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self::builder().scopes(scopes).build()
}
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use http::{HeaderMap, Request, StatusCode};
use super::*;
use crate::core::{
Error,
client_auth::NoAuth,
http::{HttpClient, HttpResponse, Idempotency},
platform::MaybeSendBoxFuture,
};
struct FakeClient {
status: StatusCode,
body: &'static str,
}
impl HttpClient for FakeClient {
fn execute(
&self,
_request: Request<Bytes>,
_idempotency: Idempotency,
) -> MaybeSendBoxFuture<'_, Result<HttpResponse, Error>> {
let status = self.status;
let body = Bytes::from_static(self.body.as_bytes());
Box::pin(async move {
Ok(HttpResponse {
status,
headers: HeaderMap::new(),
body,
})
})
}
}
fn grant(status: StatusCode, body: &'static str) -> DeviceAuthorizationGrant {
DeviceAuthorizationGrant::builder()
.client_id("device-client")
.http_client(FakeClient { status, body })
.client_auth(NoAuth)
.token_endpoint("https://as.example/token".parse::<EndpointUrl>().unwrap())
.device_authorization_endpoint(
"https://as.example/device".parse::<EndpointUrl>().unwrap(),
)
.build()
}
fn pending() -> PendingState {
PendingState {
device_code: "dev-code".to_string(),
interval_secs: 5,
}
}
#[tokio::test]
async fn slow_down_bumps_interval_and_stays_pending() {
let g = grant(StatusCode::BAD_REQUEST, r#"{"error":"slow_down"}"#);
let mut state = pending();
let result = g.poll(&mut state, None).await.unwrap();
assert!(matches!(result, PollResult::Pending));
assert_eq!(state.interval_secs, 10, "slow_down adds 5s to the interval");
}
#[tokio::test]
async fn authorization_pending_stays_pending_without_bump() {
let g = grant(
StatusCode::BAD_REQUEST,
r#"{"error":"authorization_pending"}"#,
);
let mut state = pending();
let result = g.poll(&mut state, None).await.unwrap();
assert!(matches!(result, PollResult::Pending));
assert_eq!(
state.interval_secs, 5,
"authorization_pending leaves the interval unchanged"
);
}
#[tokio::test]
async fn access_denied_maps_to_error() {
let g = grant(StatusCode::BAD_REQUEST, r#"{"error":"access_denied"}"#);
assert!(matches!(
g.poll(&mut pending(), None).await,
Err(PollError::AccessDenied)
));
}
#[tokio::test]
async fn expired_token_maps_to_error() {
let g = grant(StatusCode::BAD_REQUEST, r#"{"error":"expired_token"}"#);
assert!(matches!(
g.poll(&mut pending(), None).await,
Err(PollError::TokenExpired)
));
}
#[tokio::test]
async fn other_oauth_error_propagates_as_exchange() {
let g = grant(StatusCode::BAD_REQUEST, r#"{"error":"invalid_client"}"#);
assert!(matches!(
g.poll(&mut pending(), None).await,
Err(PollError::Exchange { .. })
));
}
#[tokio::test]
async fn successful_token_completes_poll() {
let g = grant(
StatusCode::OK,
r#"{"access_token":"at-123","token_type":"bearer"}"#,
);
let result = g.poll(&mut pending(), None).await.unwrap();
assert!(matches!(result, PollResult::Complete(_)));
}
}