atproto_oauth_aip/workflow.rs
1//! # OAuth 2.0 Workflow Implementation for AT Protocol Identity Providers
2//!
3//! This module provides a complete OAuth 2.0 authorization code flow implementation
4//! specifically designed for AT Protocol Identity Providers (AIPs). It handles the
5//! three main phases of OAuth authentication: initialization, completion, and session exchange.
6//!
7//! ## Workflow Overview
8//!
9//! The OAuth workflow consists of three main functions that handle different phases:
10//!
11//! 1. **Initialization (`oauth_init`)**: Creates a Pushed Authorization Request (PAR)
12//! and returns the authorization URL for user consent
13//! 2. **Completion (`oauth_complete`)**: Exchanges the authorization code for access tokens
14//! 3. **Session Exchange (`session_exchange`)**: Converts OAuth tokens to AT Protocol sessions
15//!
16//! ## Security Features
17//!
18//! - **Pushed Authorization Requests (PAR)**: Enhanced security by storing authorization
19//! parameters server-side rather than in redirect URLs
20//! - **PKCE (Proof Key for Code Exchange)**: Protection against authorization code
21//! interception attacks
22//! - **DPoP (Demonstration of Proof-of-Possession)**: Cryptographic binding of tokens
23//! to specific keys for enhanced security
24//!
25//! ## Usage Example
26//!
27//! ```rust,no_run
28//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
29//! use atproto_oauth_aip::workflow::{oauth_init, oauth_complete, session_exchange, OAuthClient};
30//! use atproto_oauth::resources::{AuthorizationServer, OAuthProtectedResource};
31//! use atproto_oauth::workflow::{OAuthRequestState, OAuthRequest};
32//!
33//! let http_client = reqwest::Client::new();
34//!
35//! // 1. Initialize OAuth flow
36//! let oauth_client = OAuthClient {
37//! redirect_uri: "https://myapp.com/callback".to_string(),
38//! client_id: "my_client_id".to_string(),
39//! client_secret: "my_client_secret".to_string(),
40//! };
41//!
42//! # let authorization_server = AuthorizationServer {
43//! # issuer: "https://auth.example.com".to_string(),
44//! # authorization_endpoint: "https://auth.example.com/authorize".to_string(),
45//! # token_endpoint: "https://auth.example.com/token".to_string(),
46//! # pushed_authorization_request_endpoint: "https://auth.example.com/par".to_string(),
47//! # introspection_endpoint: "".to_string(),
48//! # scopes_supported: vec!["atproto".to_string(), "transition:generic".to_string()],
49//! # response_types_supported: vec!["code".to_string()],
50//! # grant_types_supported: vec!["authorization_code".to_string(), "refresh_token".to_string()],
51//! # token_endpoint_auth_methods_supported: vec!["none".to_string(), "private_key_jwt".to_string()],
52//! # token_endpoint_auth_signing_alg_values_supported: vec!["ES256".to_string()],
53//! # require_pushed_authorization_requests: true,
54//! # request_parameter_supported: false,
55//! # code_challenge_methods_supported: vec!["S256".to_string()],
56//! # authorization_response_iss_parameter_supported: true,
57//! # dpop_signing_alg_values_supported: vec!["ES256".to_string()],
58//! # client_id_metadata_document_supported: true,
59//! # };
60//!
61//! let oauth_request_state = OAuthRequestState {
62//! state: "random-state".to_string(),
63//! nonce: "random-nonce".to_string(),
64//! code_challenge: "code-challenge".to_string(),
65//! scope: "atproto transition:generic".to_string(),
66//! };
67//!
68//! let par_response = oauth_init(
69//! &http_client,
70//! &oauth_client,
71//! Some("user.bsky.social"),
72//! &authorization_server,
73//! &oauth_request_state
74//! ).await?;
75//!
76//! // User visits auth_url and grants consent, returns with authorization code
77//!
78//! // 2. Complete OAuth flow
79//! # let oauth_request = OAuthRequest {
80//! # oauth_state: "state".to_string(),
81//! # issuer: "https://auth.example.com".to_string(),
82//! # did: "did:plc:example".to_string(),
83//! # nonce: "nonce".to_string(),
84//! # signing_public_key: "public_key".to_string(),
85//! # pkce_verifier: "verifier".to_string(),
86//! # dpop_private_key: "private_key".to_string(),
87//! # created_at: chrono::Utc::now(),
88//! # expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
89//! # };
90//! let token_response = oauth_complete(
91//! &http_client,
92//! &oauth_client,
93//! &authorization_server,
94//! "received_auth_code",
95//! &oauth_request
96//! ).await?;
97//!
98//! // 3. Exchange for AT Protocol session
99//! # let protected_resource = OAuthProtectedResource {
100//! # resource: "https://pds.example.com".to_string(),
101//! # scopes_supported: vec!["atproto".to_string()],
102//! # bearer_methods_supported: vec!["header".to_string()],
103//! # authorization_servers: vec!["https://auth.example.com".to_string()],
104//! # };
105//! let session = session_exchange(
106//! &http_client,
107//! &protected_resource,
108//! &token_response.access_token
109//! ).await?;
110//! # Ok(())
111//! # }
112//! ```
113//!
114//! ## Error Handling
115//!
116//! All functions return `Result<T, OAuthWorkflowError>` with detailed error information
117//! for each phase of the OAuth flow including network failures, parsing errors,
118//! and protocol violations.
119
120use crate::errors::OAuthWorkflowError;
121use anyhow::Result;
122use atproto_oauth::{
123 resources::{AuthorizationServer, OAuthProtectedResource},
124 workflow::{OAuthRequest, OAuthRequestState, ParResponse, TokenResponse},
125};
126use serde::Deserialize;
127
128/// OAuth client configuration containing essential client credentials.
129pub struct OAuthClient {
130 /// The redirect URI where the authorization server will send the user after authorization.
131 pub redirect_uri: String,
132 /// The unique client identifier for this OAuth client.
133 pub client_id: String,
134
135 /// The client secret used for authenticating with the authorization server.
136 pub client_secret: String,
137}
138
139#[derive(Clone, Deserialize)]
140#[serde(untagged)]
141enum WrappedParResponse {
142 ParResponse(ParResponse),
143 Error {
144 error: String,
145 error_description: Option<String>,
146 },
147}
148
149/// Represents an authenticated AT Protocol session.
150///
151/// This structure contains all the information needed to make authenticated
152/// requests to AT Protocol services after a successful OAuth flow.
153#[derive(Clone, Deserialize)]
154pub struct ATProtocolSession {
155 /// The Decentralized Identifier (DID) of the authenticated user.
156 pub did: String,
157 /// The handle (username) of the authenticated user.
158 pub handle: String,
159 /// The OAuth access token for making authenticated requests.
160 pub access_token: String,
161 /// The type of token (typically "Bearer").
162 pub token_type: String,
163 /// The list of OAuth scopes granted to this session.
164 pub scopes: Vec<String>,
165 /// The Personal Data Server (PDS) endpoint URL for this user.
166 pub pds_endpoint: String,
167 /// The DPoP (Demonstration of Proof-of-Possession) key in JWK format.
168 pub dpop_key: String,
169 /// Unix timestamp indicating when this session expires.
170 pub expires_at: i64,
171}
172
173#[derive(Deserialize, Clone)]
174#[serde(untagged)]
175enum WrappedATProtocolSession {
176 ATProtocolSession(ATProtocolSession),
177 Error {
178 error: String,
179 error_description: Option<String>,
180 },
181}
182
183/// Initiates an OAuth authorization flow using Pushed Authorization Request (PAR).
184///
185/// This function starts the OAuth flow by sending a PAR request to the authorization
186/// server. PAR allows the client to push the authorization request parameters to the
187/// authorization server before redirecting the user, providing enhanced security.
188///
189/// # Arguments
190///
191/// * `http_client` - The HTTP client to use for making requests
192/// * `oauth_client` - OAuth client configuration with credentials
193/// * `handle` - Optional user handle to pre-fill in the login form
194/// * `authorization_server` - Authorization server metadata
195/// * `oauth_request_state` - OAuth request state including PKCE challenge and state
196///
197/// # Returns
198///
199/// Returns a `ParResponse` containing the request URI to redirect the user to,
200/// or an error if the PAR request fails.
201///
202/// # Example
203///
204/// ```no_run
205/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
206/// use atproto_oauth_aip::workflow::{oauth_init, OAuthClient};
207/// use atproto_oauth::workflow::OAuthRequestState;
208/// # let http_client = reqwest::Client::new();
209/// let oauth_client = OAuthClient {
210/// redirect_uri: "https://example.com/callback".to_string(),
211/// client_id: "client123".to_string(),
212/// client_secret: "secret456".to_string(),
213/// };
214/// # let authorization_server = todo!();
215/// let oauth_request_state = OAuthRequestState {
216/// state: "random-state".to_string(),
217/// nonce: "random-nonce".to_string(),
218/// code_challenge: "code-challenge".to_string(),
219/// scope: "atproto transition:generic".to_string(),
220/// };
221/// let par_response = oauth_init(
222/// &http_client,
223/// &oauth_client,
224/// Some("alice.bsky.social"),
225/// &authorization_server,
226/// &oauth_request_state,
227/// ).await?;
228/// # Ok(())
229/// # }
230/// ```
231pub async fn oauth_init(
232 http_client: &reqwest::Client,
233 oauth_client: &OAuthClient,
234 handle: Option<&str>,
235 authorization_server: &AuthorizationServer,
236 oauth_request_state: &OAuthRequestState,
237) -> Result<ParResponse> {
238 let par_url = authorization_server
239 .pushed_authorization_request_endpoint
240 .clone();
241
242 let scope = &oauth_request_state.scope;
243
244 let mut params = vec![
245 ("client_id", oauth_client.client_id.as_str()),
246 ("code_challenge_method", "S256"),
247 ("code_challenge", &oauth_request_state.code_challenge),
248 ("redirect_uri", oauth_client.redirect_uri.as_str()),
249 ("response_type", "code"),
250 ("scope", scope),
251 ("state", oauth_request_state.state.as_str()),
252 ];
253 if let Some(value) = handle {
254 params.push(("login_hint", value));
255 }
256
257 let response: WrappedParResponse = http_client
258 .post(par_url)
259 .form(¶ms)
260 .basic_auth(
261 oauth_client.client_id.as_str(),
262 Some(oauth_client.client_secret.as_str()),
263 )
264 .send()
265 .await
266 .map_err(OAuthWorkflowError::ParRequestFailed)?
267 .json()
268 .await
269 .map_err(OAuthWorkflowError::ParResponseParseFailed)?;
270
271 match response {
272 WrappedParResponse::ParResponse(value) => Ok(value),
273 WrappedParResponse::Error {
274 error,
275 error_description,
276 } => {
277 let error_message = if let Some(value) = error_description {
278 format!("{error}: {value}")
279 } else {
280 error.to_string()
281 };
282 Err(OAuthWorkflowError::ParResponseInvalid {
283 message: error_message,
284 }
285 .into())
286 }
287 }
288}
289
290/// Completes the OAuth authorization flow by exchanging the authorization code for tokens.
291///
292/// After the user has authorized the application and been redirected back with an
293/// authorization code, this function exchanges that code for access tokens using
294/// the token endpoint.
295///
296/// # Arguments
297///
298/// * `http_client` - The HTTP client to use for making requests
299/// * `oauth_client` - OAuth client configuration with credentials
300/// * `authorization_server` - Authorization server metadata
301/// * `callback_code` - The authorization code received in the callback
302/// * `oauth_request` - The original OAuth request containing the PKCE verifier
303///
304/// # Returns
305///
306/// Returns a `TokenResponse` containing the access token and other token information,
307/// or an error if the token exchange fails.
308///
309/// # Example
310///
311/// ```no_run
312/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
313/// use atproto_oauth_aip::workflow::oauth_complete;
314/// # let http_client = reqwest::Client::new();
315/// # let oauth_client = todo!();
316/// # let authorization_server = todo!();
317/// # let oauth_request = todo!();
318/// let token_response = oauth_complete(
319/// &http_client,
320/// &oauth_client,
321/// &authorization_server,
322/// "auth_code_from_callback",
323/// &oauth_request,
324/// ).await?;
325/// println!("Access token: {}", token_response.access_token);
326/// # Ok(())
327/// # }
328/// ```
329pub async fn oauth_complete(
330 http_client: &reqwest::Client,
331 oauth_client: &OAuthClient,
332 authorization_server: &AuthorizationServer,
333 callback_code: &str,
334 oauth_request: &OAuthRequest,
335) -> Result<TokenResponse> {
336 let params = [
337 ("client_id", oauth_client.client_id.as_str()),
338 ("redirect_uri", oauth_client.redirect_uri.as_str()),
339 ("grant_type", "authorization_code"),
340 ("code", callback_code),
341 ("code_verifier", &oauth_request.pkce_verifier),
342 ];
343
344 http_client
345 .post(&authorization_server.token_endpoint)
346 .basic_auth(
347 oauth_client.client_id.as_str(),
348 Some(oauth_client.client_secret.as_str()),
349 )
350 .form(¶ms)
351 .send()
352 .await
353 .map_err(OAuthWorkflowError::TokenRequestFailed)?
354 .json()
355 .await
356 .map_err(|e| OAuthWorkflowError::TokenResponseParseFailed(e).into())
357}
358
359/// Exchanges an OAuth access token for an AT Protocol session.
360///
361/// This function takes an OAuth access token and exchanges it for a full
362/// AT Protocol session, which includes additional information like the user's
363/// DID, handle, and PDS endpoint. This is specific to AT Protocol's OAuth
364/// implementation.
365///
366/// # Arguments
367///
368/// * `http_client` - The HTTP client to use for making requests
369/// * `protected_resource` - The protected resource metadata
370/// * `access_token` - The OAuth access token to exchange
371///
372/// # Returns
373///
374/// Returns an `ATProtocolSession` with full session information,
375/// or an error if the session exchange fails.
376///
377/// # Example
378///
379/// ```no_run
380/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
381/// use atproto_oauth_aip::workflow::session_exchange;
382/// # let http_client = reqwest::Client::new();
383/// # let protected_resource = todo!();
384/// # let access_token = "example_token";
385/// let session = session_exchange(
386/// &http_client,
387/// &protected_resource,
388/// access_token,
389/// ).await?;
390/// println!("Authenticated as {} ({})", session.handle, session.did);
391/// println!("PDS endpoint: {}", session.pds_endpoint);
392/// # Ok(())
393/// # }
394/// ```
395pub async fn session_exchange(
396 http_client: &reqwest::Client,
397 protected_resource: &OAuthProtectedResource,
398 access_token: &str,
399) -> Result<ATProtocolSession> {
400 let response = http_client
401 .get(format!(
402 "{}/api/atprotocol/session",
403 protected_resource.resource
404 ))
405 .bearer_auth(access_token)
406 .send()
407 .await
408 .map_err(OAuthWorkflowError::SessionRequestFailed)?
409 .json()
410 .await
411 .map_err(OAuthWorkflowError::SessionResponseParseFailed)?;
412
413 match response {
414 WrappedATProtocolSession::ATProtocolSession(value) => Ok(value),
415 WrappedATProtocolSession::Error {
416 error,
417 error_description,
418 } => {
419 let error_message = if let Some(value) = error_description {
420 format!("{error}: {value}")
421 } else {
422 error.to_string()
423 };
424 Err(OAuthWorkflowError::SessionResponseInvalid {
425 message: error_message,
426 }
427 .into())
428 }
429 }
430}