this repo has no description
1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::Value as JsonValue;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct RequestId(pub String);
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct TokenId(pub String);
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct DeviceId(pub String);
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct SessionId(pub String);
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct Code(pub String);
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct RefreshToken(pub String);
22
23impl RequestId {
24 pub fn generate() -> Self {
25 Self(format!(
26 "urn:ietf:params:oauth:request_uri:{}",
27 uuid::Uuid::new_v4()
28 ))
29 }
30}
31
32impl TokenId {
33 pub fn generate() -> Self {
34 Self(uuid::Uuid::new_v4().to_string())
35 }
36}
37
38impl DeviceId {
39 pub fn generate() -> Self {
40 Self(uuid::Uuid::new_v4().to_string())
41 }
42}
43
44impl SessionId {
45 pub fn generate() -> Self {
46 Self(uuid::Uuid::new_v4().to_string())
47 }
48}
49
50impl Code {
51 pub fn generate() -> Self {
52 use rand::Rng;
53 let bytes: [u8; 32] = rand::thread_rng().r#gen();
54 Self(base64::Engine::encode(
55 &base64::engine::general_purpose::URL_SAFE_NO_PAD,
56 bytes,
57 ))
58 }
59}
60
61impl RefreshToken {
62 pub fn generate() -> Self {
63 use rand::Rng;
64 let bytes: [u8; 32] = rand::thread_rng().r#gen();
65 Self(base64::Engine::encode(
66 &base64::engine::general_purpose::URL_SAFE_NO_PAD,
67 bytes,
68 ))
69 }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73#[serde(tag = "method")]
74pub enum ClientAuth {
75 #[serde(rename = "none")]
76 None,
77 #[serde(rename = "client_secret_basic")]
78 SecretBasic { client_secret: String },
79 #[serde(rename = "client_secret_post")]
80 SecretPost { client_secret: String },
81 #[serde(rename = "private_key_jwt")]
82 PrivateKeyJwt { client_assertion: String },
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuthorizationRequestParameters {
87 pub response_type: String,
88 pub client_id: String,
89 pub redirect_uri: String,
90 pub scope: Option<String>,
91 pub state: Option<String>,
92 pub code_challenge: String,
93 pub code_challenge_method: String,
94 pub response_mode: Option<String>,
95 pub login_hint: Option<String>,
96 pub dpop_jkt: Option<String>,
97 #[serde(flatten)]
98 pub extra: Option<JsonValue>,
99}
100
101#[derive(Debug, Clone)]
102pub struct RequestData {
103 pub client_id: String,
104 pub client_auth: Option<ClientAuth>,
105 pub parameters: AuthorizationRequestParameters,
106 pub expires_at: DateTime<Utc>,
107 pub did: Option<String>,
108 pub device_id: Option<String>,
109 pub code: Option<String>,
110 pub controller_did: Option<String>,
111}
112
113#[derive(Debug, Clone)]
114pub struct DeviceData {
115 pub session_id: String,
116 pub user_agent: Option<String>,
117 pub ip_address: String,
118 pub last_seen_at: DateTime<Utc>,
119}
120
121#[derive(Debug, Clone)]
122pub struct TokenData {
123 pub did: String,
124 pub token_id: String,
125 pub created_at: DateTime<Utc>,
126 pub updated_at: DateTime<Utc>,
127 pub expires_at: DateTime<Utc>,
128 pub client_id: String,
129 pub client_auth: ClientAuth,
130 pub device_id: Option<String>,
131 pub parameters: AuthorizationRequestParameters,
132 pub details: Option<JsonValue>,
133 pub code: Option<String>,
134 pub current_refresh_token: Option<String>,
135 pub scope: Option<String>,
136 pub controller_did: Option<String>,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct AuthorizedClientData {
141 pub scope: Option<String>,
142 pub remember: bool,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct OAuthClientMetadata {
147 pub client_id: String,
148 pub client_name: Option<String>,
149 pub client_uri: Option<String>,
150 pub logo_uri: Option<String>,
151 pub redirect_uris: Vec<String>,
152 pub grant_types: Option<Vec<String>>,
153 pub response_types: Option<Vec<String>>,
154 pub scope: Option<String>,
155 pub token_endpoint_auth_method: Option<String>,
156 pub dpop_bound_access_tokens: Option<bool>,
157 pub jwks: Option<JsonValue>,
158 pub jwks_uri: Option<String>,
159 pub application_type: Option<String>,
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct ProtectedResourceMetadata {
164 pub resource: String,
165 pub authorization_servers: Vec<String>,
166 pub bearer_methods_supported: Vec<String>,
167 pub scopes_supported: Vec<String>,
168 pub resource_documentation: Option<String>,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct AuthorizationServerMetadata {
173 pub issuer: String,
174 pub authorization_endpoint: String,
175 pub token_endpoint: String,
176 pub jwks_uri: String,
177 pub registration_endpoint: Option<String>,
178 pub scopes_supported: Option<Vec<String>>,
179 pub response_types_supported: Vec<String>,
180 pub response_modes_supported: Option<Vec<String>>,
181 pub grant_types_supported: Option<Vec<String>>,
182 pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
183 pub code_challenge_methods_supported: Option<Vec<String>>,
184 pub pushed_authorization_request_endpoint: Option<String>,
185 pub require_pushed_authorization_requests: Option<bool>,
186 pub dpop_signing_alg_values_supported: Option<Vec<String>>,
187 pub authorization_response_iss_parameter_supported: Option<bool>,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct ParResponse {
192 pub request_uri: String,
193 pub expires_in: u64,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct TokenResponse {
198 pub access_token: String,
199 pub token_type: String,
200 pub expires_in: u64,
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub refresh_token: Option<String>,
203 #[serde(skip_serializing_if = "Option::is_none")]
204 pub scope: Option<String>,
205 #[serde(skip_serializing_if = "Option::is_none")]
206 pub sub: Option<String>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct TokenRequest {
211 pub grant_type: String,
212 pub code: Option<String>,
213 pub redirect_uri: Option<String>,
214 pub code_verifier: Option<String>,
215 pub refresh_token: Option<String>,
216 pub client_id: Option<String>,
217 pub client_secret: Option<String>,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct DPoPClaims {
222 pub jti: String,
223 pub htm: String,
224 pub htu: String,
225 pub iat: i64,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 pub ath: Option<String>,
228 #[serde(skip_serializing_if = "Option::is_none")]
229 pub nonce: Option<String>,
230}
231
232#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct JwkPublicKey {
234 pub kty: String,
235 pub crv: Option<String>,
236 pub x: Option<String>,
237 pub y: Option<String>,
238 #[serde(rename = "use")]
239 pub key_use: Option<String>,
240 pub kid: Option<String>,
241 pub alg: Option<String>,
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct Jwks {
246 pub keys: Vec<JwkPublicKey>,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum AuthFlowState {
251 Pending,
252 Authenticated { did: String, device_id: Option<String> },
253 Authorized { did: String, device_id: Option<String>, code: String },
254 Expired,
255}
256
257impl AuthFlowState {
258 pub fn from_request_data(data: &RequestData) -> Self {
259 if data.expires_at < chrono::Utc::now() {
260 return AuthFlowState::Expired;
261 }
262 match (&data.did, &data.code) {
263 (Some(did), Some(code)) => AuthFlowState::Authorized {
264 did: did.clone(),
265 device_id: data.device_id.clone(),
266 code: code.clone(),
267 },
268 (Some(did), None) => AuthFlowState::Authenticated {
269 did: did.clone(),
270 device_id: data.device_id.clone(),
271 },
272 (None, _) => AuthFlowState::Pending,
273 }
274 }
275
276 pub fn is_pending(&self) -> bool {
277 matches!(self, AuthFlowState::Pending)
278 }
279
280 pub fn is_authenticated(&self) -> bool {
281 matches!(self, AuthFlowState::Authenticated { .. })
282 }
283
284 pub fn is_authorized(&self) -> bool {
285 matches!(self, AuthFlowState::Authorized { .. })
286 }
287
288 pub fn is_expired(&self) -> bool {
289 matches!(self, AuthFlowState::Expired)
290 }
291
292 pub fn can_authenticate(&self) -> bool {
293 matches!(self, AuthFlowState::Pending)
294 }
295
296 pub fn can_authorize(&self) -> bool {
297 matches!(self, AuthFlowState::Authenticated { .. })
298 }
299
300 pub fn can_exchange(&self) -> bool {
301 matches!(self, AuthFlowState::Authorized { .. })
302 }
303
304 pub fn did(&self) -> Option<&str> {
305 match self {
306 AuthFlowState::Authenticated { did, .. } | AuthFlowState::Authorized { did, .. } => {
307 Some(did)
308 }
309 _ => None,
310 }
311 }
312
313 pub fn code(&self) -> Option<&str> {
314 match self {
315 AuthFlowState::Authorized { code, .. } => Some(code),
316 _ => None,
317 }
318 }
319}
320
321impl std::fmt::Display for AuthFlowState {
322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 match self {
324 AuthFlowState::Pending => write!(f, "pending"),
325 AuthFlowState::Authenticated { did, .. } => write!(f, "authenticated ({})", did),
326 AuthFlowState::Authorized { did, code, .. } => {
327 write!(f, "authorized ({}, code={}...)", did, &code[..8.min(code.len())])
328 }
329 AuthFlowState::Expired => write!(f, "expired"),
330 }
331 }
332}
333
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub enum RefreshTokenState {
336 Valid,
337 Used { at: chrono::DateTime<chrono::Utc> },
338 InGracePeriod { rotated_at: chrono::DateTime<chrono::Utc> },
339 Expired,
340 Revoked,
341}
342
343impl RefreshTokenState {
344 pub fn is_valid(&self) -> bool {
345 matches!(self, RefreshTokenState::Valid)
346 }
347
348 pub fn is_usable(&self) -> bool {
349 matches!(
350 self,
351 RefreshTokenState::Valid | RefreshTokenState::InGracePeriod { .. }
352 )
353 }
354
355 pub fn is_used(&self) -> bool {
356 matches!(self, RefreshTokenState::Used { .. })
357 }
358
359 pub fn is_in_grace_period(&self) -> bool {
360 matches!(self, RefreshTokenState::InGracePeriod { .. })
361 }
362
363 pub fn is_expired(&self) -> bool {
364 matches!(self, RefreshTokenState::Expired)
365 }
366
367 pub fn is_revoked(&self) -> bool {
368 matches!(self, RefreshTokenState::Revoked)
369 }
370}
371
372impl std::fmt::Display for RefreshTokenState {
373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 match self {
375 RefreshTokenState::Valid => write!(f, "valid"),
376 RefreshTokenState::Used { at } => write!(f, "used ({})", at),
377 RefreshTokenState::InGracePeriod { rotated_at } => {
378 write!(f, "grace period (rotated {})", rotated_at)
379 }
380 RefreshTokenState::Expired => write!(f, "expired"),
381 RefreshTokenState::Revoked => write!(f, "revoked"),
382 }
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use chrono::{Duration, Utc};
390
391 fn make_request_data(
392 did: Option<String>,
393 code: Option<String>,
394 expires_in: Duration,
395 ) -> RequestData {
396 RequestData {
397 client_id: "test-client".into(),
398 client_auth: None,
399 parameters: AuthorizationRequestParameters {
400 response_type: "code".into(),
401 client_id: "test-client".into(),
402 redirect_uri: "https://example.com/callback".into(),
403 scope: Some("atproto".into()),
404 state: None,
405 code_challenge: "test".into(),
406 code_challenge_method: "S256".into(),
407 response_mode: None,
408 login_hint: None,
409 dpop_jkt: None,
410 extra: None,
411 },
412 expires_at: Utc::now() + expires_in,
413 did,
414 device_id: None,
415 code,
416 controller_did: None,
417 }
418 }
419
420 #[test]
421 fn test_auth_flow_state_pending() {
422 let data = make_request_data(None, None, Duration::minutes(5));
423 let state = AuthFlowState::from_request_data(&data);
424 assert!(state.is_pending());
425 assert!(!state.is_authenticated());
426 assert!(!state.is_authorized());
427 assert!(!state.is_expired());
428 assert!(state.can_authenticate());
429 assert!(!state.can_authorize());
430 assert!(!state.can_exchange());
431 assert!(state.did().is_none());
432 assert!(state.code().is_none());
433 }
434
435 #[test]
436 fn test_auth_flow_state_authenticated() {
437 let data = make_request_data(Some("did:plc:test".into()), None, Duration::minutes(5));
438 let state = AuthFlowState::from_request_data(&data);
439 assert!(!state.is_pending());
440 assert!(state.is_authenticated());
441 assert!(!state.is_authorized());
442 assert!(!state.is_expired());
443 assert!(!state.can_authenticate());
444 assert!(state.can_authorize());
445 assert!(!state.can_exchange());
446 assert_eq!(state.did(), Some("did:plc:test"));
447 assert!(state.code().is_none());
448 }
449
450 #[test]
451 fn test_auth_flow_state_authorized() {
452 let data = make_request_data(
453 Some("did:plc:test".into()),
454 Some("auth-code-123".into()),
455 Duration::minutes(5),
456 );
457 let state = AuthFlowState::from_request_data(&data);
458 assert!(!state.is_pending());
459 assert!(!state.is_authenticated());
460 assert!(state.is_authorized());
461 assert!(!state.is_expired());
462 assert!(!state.can_authenticate());
463 assert!(!state.can_authorize());
464 assert!(state.can_exchange());
465 assert_eq!(state.did(), Some("did:plc:test"));
466 assert_eq!(state.code(), Some("auth-code-123"));
467 }
468
469 #[test]
470 fn test_auth_flow_state_expired() {
471 let data = make_request_data(
472 Some("did:plc:test".into()),
473 Some("code".into()),
474 Duration::minutes(-1),
475 );
476 let state = AuthFlowState::from_request_data(&data);
477 assert!(state.is_expired());
478 assert!(!state.can_authenticate());
479 assert!(!state.can_authorize());
480 assert!(!state.can_exchange());
481 }
482
483 #[test]
484 fn test_refresh_token_state_valid() {
485 let state = RefreshTokenState::Valid;
486 assert!(state.is_valid());
487 assert!(state.is_usable());
488 assert!(!state.is_used());
489 assert!(!state.is_in_grace_period());
490 assert!(!state.is_expired());
491 assert!(!state.is_revoked());
492 }
493
494 #[test]
495 fn test_refresh_token_state_grace_period() {
496 let state = RefreshTokenState::InGracePeriod {
497 rotated_at: Utc::now(),
498 };
499 assert!(!state.is_valid());
500 assert!(state.is_usable());
501 assert!(!state.is_used());
502 assert!(state.is_in_grace_period());
503 }
504
505 #[test]
506 fn test_refresh_token_state_used() {
507 let state = RefreshTokenState::Used { at: Utc::now() };
508 assert!(!state.is_valid());
509 assert!(!state.is_usable());
510 assert!(state.is_used());
511 }
512
513 #[test]
514 fn test_refresh_token_state_expired() {
515 let state = RefreshTokenState::Expired;
516 assert!(!state.is_usable());
517 assert!(state.is_expired());
518 }
519
520 #[test]
521 fn test_refresh_token_state_revoked() {
522 let state = RefreshTokenState::Revoked;
523 assert!(!state.is_usable());
524 assert!(state.is_revoked());
525 }
526}