Skip to main content

auth_framework/protocols/
uma.rs

1//! UMA 2.0 (User-Managed Access) implementation.
2//!
3//! Provides federated authorization where Resource Owners (RO) delegate access
4//! to their protected resources using OAuth 2.0 workflows.
5
6use crate::errors::{AuthError, Result};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::sync::Arc;
10use tokio::sync::RwLock;
11
12// ── UMA 2.0 Discovery Metadata ─────────────────────────────────────
13
14/// UMA 2.0 Authorization Server discovery metadata (`.well-known/uma2-configuration`).
15///
16/// Defined by UMA 2.0 Grant for OAuth 2.0 Authorization, Section 2.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct UmaDiscoveryMetadata {
19    /// The base URI of the UMA authorization server.
20    pub issuer: String,
21    /// Protection API Token (PAT) endpoint (OAuth 2.0 token endpoint).
22    pub token_endpoint: String,
23    /// Resource registration endpoint.
24    pub resource_registration_endpoint: String,
25    /// Permission endpoint (where resource servers register permission requests).
26    pub permission_endpoint: String,
27    /// RPT (Requesting Party Token) endpoint (same as token_endpoint).
28    pub rpt_endpoint: String,
29    /// Introspection endpoint for RPTs (RFC 7662).
30    pub introspection_endpoint: String,
31    /// Claims interaction endpoint for interactive claims gathering.
32    pub claims_interaction_endpoint: String,
33    /// Supported UMA grant types.
34    pub grant_types_supported: Vec<String>,
35    /// Supported token endpoint authentication methods.
36    pub token_endpoint_auth_methods_supported: Vec<String>,
37    /// Supported UMA profiles.
38    pub uma_profiles_supported: Vec<String>,
39}
40
41impl UmaDiscoveryMetadata {
42    /// Create discovery metadata for a given issuer base URL.
43    pub fn new(issuer: impl Into<String>) -> Self {
44        let base = issuer.into();
45        Self {
46            token_endpoint: format!("{base}/oauth/token"),
47            resource_registration_endpoint: format!("{base}/uma/resource_set"),
48            permission_endpoint: format!("{base}/uma/permission"),
49            rpt_endpoint: format!("{base}/oauth/token"),
50            introspection_endpoint: format!("{base}/oauth/introspect"),
51            claims_interaction_endpoint: format!("{base}/uma/claims"),
52            grant_types_supported: vec!["urn:ietf:params:oauth:grant-type:uma-ticket".to_string()],
53            token_endpoint_auth_methods_supported: vec![
54                "client_secret_basic".to_string(),
55                "client_secret_post".to_string(),
56            ],
57            uma_profiles_supported: vec![],
58            issuer: base,
59        }
60    }
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct UmaConfig {
65    pub enabled: bool,
66    pub pat_lifetime: u64, // Protection API Token lifetime in seconds
67    pub rpt_lifetime: u64, // Requesting Party Token lifetime in seconds
68    pub claims_interaction_endpoint: String,
69    /// Permission ticket lifetime in seconds (default: 300 = 5 minutes)
70    pub ticket_lifetime: u64,
71}
72
73impl Default for UmaConfig {
74    fn default() -> Self {
75        Self {
76            enabled: false,
77            pat_lifetime: 3600,
78            rpt_lifetime: 3600,
79            claims_interaction_endpoint: "/api/uma/claims".to_string(),
80            ticket_lifetime: 300,
81        }
82    }
83}
84
85/// Thread-safe UMA service
86pub struct UmaService {
87    config: UmaConfig,
88    resource_sets: Arc<RwLock<HashMap<String, UmaResourceSet>>>,
89    permission_tickets: Arc<RwLock<HashMap<String, PermissionTicket>>>,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct UmaResourceSet {
94    pub id: String,
95    pub name: String,
96    pub scopes: Vec<String>,
97    pub owner_id: String,
98    /// Optional policy: required claims for access (claim_name → expected_value)
99    pub required_claims: HashMap<String, String>,
100}
101
102/// A permission ticket issued when a resource server encounters an unauthorized request
103#[derive(Clone, Serialize, Deserialize)]
104struct PermissionTicket {
105    pub ticket: String,
106    pub resource_id: String,
107    pub requested_scopes: Vec<String>,
108    pub created_at: u64,
109}
110
111impl std::fmt::Debug for PermissionTicket {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        let mut d = f.debug_struct("PermissionTicket");
114        d.field("ticket", &crate::utils::redact::redacted(&self.ticket));
115        d.field("resource_id", &self.resource_id);
116        d.field("requested_scopes", &self.requested_scopes);
117        d.field("created_at", &self.created_at);
118        d.finish()
119    }
120}
121
122impl UmaService {
123    pub fn new(config: UmaConfig) -> Self {
124        Self {
125            config,
126            resource_sets: Arc::new(RwLock::new(HashMap::new())),
127            permission_tickets: Arc::new(RwLock::new(HashMap::new())),
128        }
129    }
130
131    /// Registers a resource set as part of the Resource Registration API (UMA §3.1).
132    pub async fn register_resource_set(&self, mut resource_set: UmaResourceSet) -> Result<String> {
133        if !self.config.enabled {
134            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
135        }
136
137        if resource_set.id.is_empty() {
138            resource_set.id = uuid::Uuid::new_v4().to_string();
139        }
140
141        let id = resource_set.id.clone();
142        self.resource_sets
143            .write()
144            .await
145            .insert(id.clone(), resource_set);
146        Ok(id)
147    }
148
149    /// Create a permission ticket when a resource server encounters an unauthorized request (UMA §3.2).
150    pub async fn create_permission_ticket(
151        &self,
152        resource_id: &str,
153        requested_scopes: Vec<String>,
154    ) -> Result<String> {
155        if !self.config.enabled {
156            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
157        }
158
159        // Verify the resource exists
160        let resources = self.resource_sets.read().await;
161        let resource = resources
162            .get(resource_id)
163            .ok_or_else(|| AuthError::validation("Resource set not found"))?;
164
165        // Verify requested scopes are valid for this resource
166        for scope in &requested_scopes {
167            if !resource.scopes.contains(scope) {
168                return Err(AuthError::validation(format!(
169                    "Scope '{}' is not valid for resource '{}'",
170                    scope, resource_id
171                )));
172            }
173        }
174
175        let ticket = format!("urn:uma:ticket:{}", uuid::Uuid::new_v4());
176        let now = std::time::SystemTime::now()
177            .duration_since(std::time::UNIX_EPOCH)
178            .unwrap_or_default()
179            .as_secs();
180
181        let permission = PermissionTicket {
182            ticket: ticket.clone(),
183            resource_id: resource_id.to_string(),
184            requested_scopes,
185            created_at: now,
186        };
187
188        self.permission_tickets
189            .write()
190            .await
191            .insert(ticket.clone(), permission);
192
193        Ok(ticket)
194    }
195
196    /// Request an RPT (Requesting Party Token) by presenting a permission ticket and claims (UMA §3.3).
197    pub async fn request_rpt(
198        &self,
199        ticket: &str,
200        claims: Option<HashMap<String, String>>,
201    ) -> Result<String> {
202        if !self.config.enabled {
203            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
204        }
205
206        if ticket.is_empty() {
207            return Err(AuthError::validation("Missing permission ticket"));
208        }
209
210        // Look up the permission ticket
211        let tickets = self.permission_tickets.read().await;
212        let permission = tickets
213            .get(ticket)
214            .ok_or_else(|| AuthError::validation("Permission ticket not found or expired"))?;
215
216        // Enforce ticket expiration
217        let now = std::time::SystemTime::now()
218            .duration_since(std::time::UNIX_EPOCH)
219            .unwrap_or_default()
220            .as_secs();
221        if now.saturating_sub(permission.created_at) > self.config.ticket_lifetime {
222            drop(tickets);
223            self.permission_tickets.write().await.remove(ticket);
224            return Err(AuthError::validation("Permission ticket has expired"));
225        };
226
227        // Look up the resource to evaluate policies
228        let resources = self.resource_sets.read().await;
229        let resource = resources.get(&permission.resource_id).ok_or_else(|| {
230            AuthError::internal("Resource for permission ticket no longer exists")
231        })?;
232
233        // Evaluate claims against resource policies
234        if !resource.required_claims.is_empty() {
235            let provided_claims = claims.as_ref().ok_or_else(|| {
236                AuthError::validation(format!(
237                    "UMA need_info: Redirect to {} with ticket {}",
238                    self.config.claims_interaction_endpoint, ticket
239                ))
240            })?;
241
242            for (required_claim, expected_value) in &resource.required_claims {
243                match provided_claims.get(required_claim) {
244                    Some(actual_value) if actual_value == expected_value => {}
245                    Some(_) => {
246                        return Err(AuthError::validation(format!(
247                            "Claim '{}' does not match required policy",
248                            required_claim
249                        )));
250                    }
251                    None => {
252                        return Err(AuthError::validation(format!(
253                            "UMA need_info: Missing required claim '{}'",
254                            required_claim
255                        )));
256                    }
257                }
258            }
259        }
260
261        // Claims satisfied — issue RPT
262        let rpt = format!("urn:uma:rpt:{}", uuid::Uuid::new_v4());
263
264        // Remove the consumed permission ticket
265        drop(tickets);
266        drop(resources);
267        self.permission_tickets.write().await.remove(ticket);
268
269        Ok(rpt)
270    }
271
272    /// List registered resource sets for an owner
273    pub async fn list_resource_sets(&self, owner_id: &str) -> Result<Vec<UmaResourceSet>> {
274        if !self.config.enabled {
275            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
276        }
277
278        let resources = self.resource_sets.read().await;
279        Ok(resources
280            .values()
281            .filter(|r| r.owner_id == owner_id)
282            .cloned()
283            .collect())
284    }
285
286    /// Delete a resource set
287    pub async fn delete_resource_set(&self, resource_id: &str, owner_id: &str) -> Result<()> {
288        if !self.config.enabled {
289            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
290        }
291
292        let mut resources = self.resource_sets.write().await;
293        if let Some(resource) = resources.get(resource_id) {
294            if resource.owner_id != owner_id {
295                return Err(AuthError::validation(
296                    "Only the resource owner can delete a resource set",
297                ));
298            }
299            resources.remove(resource_id);
300            Ok(())
301        } else {
302            Err(AuthError::validation("Resource set not found"))
303        }
304    }
305
306    /// Remove expired permission tickets from the in-memory store.
307    pub async fn cleanup_expired_tickets(&self) {
308        let now = std::time::SystemTime::now()
309            .duration_since(std::time::UNIX_EPOCH)
310            .unwrap_or_default()
311            .as_secs();
312        let lifetime = self.config.ticket_lifetime;
313        self.permission_tickets
314            .write()
315            .await
316            .retain(|_, t| now.saturating_sub(t.created_at) <= lifetime);
317    }
318
319    /// Get the UMA discovery metadata for this service.
320    pub fn discovery_metadata(&self, issuer: &str) -> UmaDiscoveryMetadata {
321        let mut meta = UmaDiscoveryMetadata::new(issuer);
322        meta.claims_interaction_endpoint = self.config.claims_interaction_endpoint.clone();
323        meta
324    }
325
326    /// Count of active permission tickets.
327    pub async fn ticket_count(&self) -> usize {
328        self.permission_tickets.read().await.len()
329    }
330
331    /// Count of registered resource sets.
332    pub async fn resource_count(&self) -> usize {
333        self.resource_sets.read().await.len()
334    }
335
336    /// Get a resource set by ID.
337    pub async fn get_resource_set(&self, resource_id: &str) -> Option<UmaResourceSet> {
338        self.resource_sets.read().await.get(resource_id).cloned()
339    }
340
341    /// Update a resource set (owner must match).
342    pub async fn update_resource_set(
343        &self,
344        resource_id: &str,
345        owner_id: &str,
346        name: Option<String>,
347        scopes: Option<Vec<String>>,
348        required_claims: Option<HashMap<String, String>>,
349    ) -> Result<()> {
350        if !self.config.enabled {
351            return Err(AuthError::config("UMA 2.0 protocol is currently disabled"));
352        }
353
354        let mut resources = self.resource_sets.write().await;
355        let resource = resources
356            .get_mut(resource_id)
357            .ok_or_else(|| AuthError::validation("Resource set not found"))?;
358
359        if resource.owner_id != owner_id {
360            return Err(AuthError::validation(
361                "Only the resource owner can update a resource set",
362            ));
363        }
364
365        if let Some(n) = name {
366            resource.name = n;
367        }
368        if let Some(s) = scopes {
369            resource.scopes = s;
370        }
371        if let Some(rc) = required_claims {
372            resource.required_claims = rc;
373        }
374        Ok(())
375    }
376}
377
378// ── Protection API Token (PAT) ──────────────────────────────────────
379
380/// A PAT (Protection API Token) record.
381///
382/// PATs are OAuth 2.0 access tokens with the `uma_protection` scope that
383/// resource servers use to access the UMA protection API.
384#[derive(Clone, Serialize, Deserialize)]
385pub struct Pat {
386    /// The PAT access token value.
387    pub access_token: String,
388    /// Client ID of the resource server that owns this PAT.
389    pub client_id: String,
390    /// When the PAT was issued (UNIX timestamp).
391    pub issued_at: u64,
392    /// When the PAT expires (UNIX timestamp).
393    pub expires_at: u64,
394}
395
396impl std::fmt::Debug for Pat {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        let mut d = f.debug_struct("Pat");
399        d.field(
400            "access_token",
401            &crate::utils::redact::redacted(&self.access_token),
402        );
403        d.field("client_id", &self.client_id);
404        d.field("issued_at", &self.issued_at);
405        d.field("expires_at", &self.expires_at);
406        d.finish()
407    }
408}
409
410impl Pat {
411    /// Check if PAT has expired.
412    pub fn is_expired(&self) -> bool {
413        let now = std::time::SystemTime::now()
414            .duration_since(std::time::UNIX_EPOCH)
415            .unwrap_or_default()
416            .as_secs();
417        now >= self.expires_at
418    }
419}
420
421/// In-memory PAT store for managing Protection API Tokens.
422pub struct PatStore {
423    tokens: Arc<RwLock<HashMap<String, Pat>>>,
424}
425
426impl PatStore {
427    /// Create a new empty PAT store.
428    pub fn new() -> Self {
429        Self {
430            tokens: Arc::new(RwLock::new(HashMap::new())),
431        }
432    }
433
434    /// Issue a new PAT for a resource server.
435    pub async fn issue(&self, client_id: &str, lifetime_secs: u64) -> Pat {
436        let now = std::time::SystemTime::now()
437            .duration_since(std::time::UNIX_EPOCH)
438            .unwrap_or_default()
439            .as_secs();
440        let pat = Pat {
441            access_token: format!("pat_{}", uuid::Uuid::new_v4()),
442            client_id: client_id.to_string(),
443            issued_at: now,
444            expires_at: now + lifetime_secs,
445        };
446        self.tokens
447            .write()
448            .await
449            .insert(pat.access_token.clone(), pat.clone());
450        pat
451    }
452
453    /// Validate a PAT and return its record if valid.
454    pub async fn validate(&self, token: &str) -> Result<Pat> {
455        let tokens = self.tokens.read().await;
456        let pat = tokens
457            .get(token)
458            .ok_or_else(|| AuthError::invalid_credential("PAT", "Invalid or unknown PAT"))?;
459        if pat.is_expired() {
460            return Err(AuthError::invalid_credential("PAT", "PAT has expired"));
461        }
462        Ok(pat.clone())
463    }
464
465    /// Revoke a PAT.
466    pub async fn revoke(&self, token: &str) -> bool {
467        self.tokens.write().await.remove(token).is_some()
468    }
469
470    /// Remove expired PATs.
471    pub async fn cleanup_expired(&self) {
472        self.tokens.write().await.retain(|_, p| !p.is_expired());
473    }
474
475    /// Count of stored PATs.
476    pub async fn count(&self) -> usize {
477        self.tokens.read().await.len()
478    }
479}
480
481impl Default for PatStore {
482    fn default() -> Self {
483        Self::new()
484    }
485}
486
487// ── RPT Introspection ───────────────────────────────────────────────
488
489/// Result of RPT (Requesting Party Token) introspection (RFC 7662 + UMA 2.0).
490#[derive(Debug, Clone, Serialize, Deserialize)]
491pub struct RptIntrospectionResponse {
492    /// Whether the RPT is currently active.
493    pub active: bool,
494    /// The permissions granted by this RPT.
495    #[serde(default)]
496    pub permissions: Vec<RptPermission>,
497    /// When the RPT expires (UNIX timestamp).
498    #[serde(default)]
499    pub exp: Option<u64>,
500    /// When the RPT was issued (UNIX timestamp).
501    #[serde(default)]
502    pub iat: Option<u64>,
503}
504
505/// A single permission within an RPT.
506#[derive(Debug, Clone, Serialize, Deserialize)]
507pub struct RptPermission {
508    /// The resource set ID this permission applies to.
509    pub resource_id: String,
510    /// The scopes granted.
511    pub scopes: Vec<String>,
512}
513
514/// In-memory RPT store with introspection support.
515pub struct RptStore {
516    tokens: Arc<RwLock<HashMap<String, RptIntrospectionResponse>>>,
517}
518
519impl RptStore {
520    /// Create a new RPT store.
521    pub fn new() -> Self {
522        Self {
523            tokens: Arc::new(RwLock::new(HashMap::new())),
524        }
525    }
526
527    /// Register an issued RPT with its permissions.
528    pub async fn register(
529        &self,
530        rpt: &str,
531        resource_id: &str,
532        scopes: Vec<String>,
533        lifetime_secs: u64,
534    ) {
535        let now = std::time::SystemTime::now()
536            .duration_since(std::time::UNIX_EPOCH)
537            .unwrap_or_default()
538            .as_secs();
539        let resp = RptIntrospectionResponse {
540            active: true,
541            permissions: vec![RptPermission {
542                resource_id: resource_id.to_string(),
543                scopes,
544            }],
545            exp: Some(now + lifetime_secs),
546            iat: Some(now),
547        };
548        self.tokens.write().await.insert(rpt.to_string(), resp);
549    }
550
551    /// Introspect an RPT (RFC 7662).
552    pub async fn introspect(&self, rpt: &str) -> RptIntrospectionResponse {
553        let tokens = self.tokens.read().await;
554        match tokens.get(rpt) {
555            Some(resp) => {
556                let now = std::time::SystemTime::now()
557                    .duration_since(std::time::UNIX_EPOCH)
558                    .unwrap_or_default()
559                    .as_secs();
560                let expired = resp.exp.is_some_and(|exp| now >= exp);
561                if expired {
562                    RptIntrospectionResponse {
563                        active: false,
564                        permissions: vec![],
565                        exp: resp.exp,
566                        iat: resp.iat,
567                    }
568                } else {
569                    resp.clone()
570                }
571            }
572            None => RptIntrospectionResponse {
573                active: false,
574                permissions: vec![],
575                exp: None,
576                iat: None,
577            },
578        }
579    }
580
581    /// Revoke an RPT.
582    pub async fn revoke(&self, rpt: &str) -> bool {
583        self.tokens.write().await.remove(rpt).is_some()
584    }
585
586    /// Remove expired RPTs.
587    pub async fn cleanup_expired(&self) {
588        let now = std::time::SystemTime::now()
589            .duration_since(std::time::UNIX_EPOCH)
590            .unwrap_or_default()
591            .as_secs();
592        self.tokens
593            .write()
594            .await
595            .retain(|_, r| r.exp.is_none_or(|exp| now < exp));
596    }
597
598    /// Number of stored RPTs.
599    pub async fn count(&self) -> usize {
600        self.tokens.read().await.len()
601    }
602}
603
604impl Default for RptStore {
605    fn default() -> Self {
606        Self::new()
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613
614    fn enabled_config() -> UmaConfig {
615        UmaConfig {
616            enabled: true,
617            ..UmaConfig::default()
618        }
619    }
620
621    fn sample_resource(owner: &str) -> UmaResourceSet {
622        UmaResourceSet {
623            id: String::new(),
624            name: "Photos".to_string(),
625            scopes: vec!["read".to_string(), "write".to_string()],
626            owner_id: owner.to_string(),
627            required_claims: HashMap::new(),
628        }
629    }
630
631    #[tokio::test]
632    async fn test_register_resource_set() {
633        let svc = UmaService::new(enabled_config());
634        let id = svc
635            .register_resource_set(sample_resource("alice"))
636            .await
637            .unwrap();
638        assert!(!id.is_empty());
639    }
640
641    #[tokio::test]
642    async fn test_list_resource_sets_filters_by_owner() {
643        let svc = UmaService::new(enabled_config());
644        svc.register_resource_set(sample_resource("alice"))
645            .await
646            .unwrap();
647        svc.register_resource_set(sample_resource("bob"))
648            .await
649            .unwrap();
650        let alice_rs = svc.list_resource_sets("alice").await.unwrap();
651        assert_eq!(alice_rs.len(), 1);
652        assert_eq!(alice_rs[0].owner_id, "alice");
653    }
654
655    #[tokio::test]
656    async fn test_delete_resource_set() {
657        let svc = UmaService::new(enabled_config());
658        let id = svc
659            .register_resource_set(sample_resource("alice"))
660            .await
661            .unwrap();
662        svc.delete_resource_set(&id, "alice").await.unwrap();
663        let resources = svc.list_resource_sets("alice").await.unwrap();
664        assert!(resources.is_empty());
665    }
666
667    #[tokio::test]
668    async fn test_delete_resource_wrong_owner_rejected() {
669        let svc = UmaService::new(enabled_config());
670        let id = svc
671            .register_resource_set(sample_resource("alice"))
672            .await
673            .unwrap();
674        let result = svc.delete_resource_set(&id, "eve").await;
675        assert!(result.is_err());
676    }
677
678    #[tokio::test]
679    async fn test_create_permission_ticket() {
680        let svc = UmaService::new(enabled_config());
681        let id = svc
682            .register_resource_set(sample_resource("alice"))
683            .await
684            .unwrap();
685        let ticket = svc
686            .create_permission_ticket(&id, vec!["read".to_string()])
687            .await
688            .unwrap();
689        assert!(!ticket.is_empty());
690    }
691
692    #[tokio::test]
693    async fn test_permission_ticket_invalid_scope_rejected() {
694        let svc = UmaService::new(enabled_config());
695        let id = svc
696            .register_resource_set(sample_resource("alice"))
697            .await
698            .unwrap();
699        let result = svc
700            .create_permission_ticket(&id, vec!["delete".to_string()])
701            .await;
702        assert!(result.is_err());
703    }
704
705    #[tokio::test]
706    async fn test_request_rpt_with_valid_ticket() {
707        let svc = UmaService::new(enabled_config());
708        let id = svc
709            .register_resource_set(sample_resource("alice"))
710            .await
711            .unwrap();
712        let ticket = svc
713            .create_permission_ticket(&id, vec!["read".to_string()])
714            .await
715            .unwrap();
716        let rpt = svc.request_rpt(&ticket, None).await.unwrap();
717        assert!(!rpt.is_empty());
718    }
719
720    #[tokio::test]
721    async fn test_request_rpt_invalid_ticket_rejected() {
722        let svc = UmaService::new(enabled_config());
723        let result = svc.request_rpt("bogus-ticket", None).await;
724        assert!(result.is_err());
725    }
726
727    #[tokio::test]
728    async fn test_disabled_service_rejects() {
729        let svc = UmaService::new(UmaConfig::default()); // enabled: false
730        let result = svc.register_resource_set(sample_resource("alice")).await;
731        assert!(result.is_err());
732    }
733
734    #[tokio::test]
735    async fn test_required_claims_enforced() {
736        let svc = UmaService::new(enabled_config());
737        let mut rs = sample_resource("alice");
738        rs.required_claims
739            .insert("country".to_string(), "US".to_string());
740        let id = svc.register_resource_set(rs).await.unwrap();
741        let ticket = svc
742            .create_permission_ticket(&id, vec!["read".to_string()])
743            .await
744            .unwrap();
745
746        // Without claims → should fail
747        let result = svc.request_rpt(&ticket, None).await;
748        assert!(result.is_err());
749
750        // Re-create ticket (old one consumed)
751        let ticket2 = svc
752            .create_permission_ticket(&id, vec!["read".to_string()])
753            .await
754            .unwrap();
755        // With correct claims → should succeed
756        let mut claims = HashMap::new();
757        claims.insert("country".to_string(), "US".to_string());
758        let rpt = svc.request_rpt(&ticket2, Some(claims)).await.unwrap();
759        assert!(!rpt.is_empty());
760    }
761
762    // ── UMA Discovery Metadata ──────────────────────────────────
763
764    #[test]
765    fn test_uma_discovery_metadata() {
766        let meta = UmaDiscoveryMetadata::new("https://auth.example.com");
767        assert_eq!(meta.issuer, "https://auth.example.com");
768        assert_eq!(meta.token_endpoint, "https://auth.example.com/oauth/token");
769        assert_eq!(
770            meta.resource_registration_endpoint,
771            "https://auth.example.com/uma/resource_set"
772        );
773        assert_eq!(
774            meta.permission_endpoint,
775            "https://auth.example.com/uma/permission"
776        );
777        assert_eq!(
778            meta.introspection_endpoint,
779            "https://auth.example.com/oauth/introspect"
780        );
781        assert!(
782            meta.grant_types_supported
783                .contains(&"urn:ietf:params:oauth:grant-type:uma-ticket".to_string())
784        );
785    }
786
787    #[test]
788    fn test_uma_discovery_serialization() {
789        let meta = UmaDiscoveryMetadata::new("https://auth.example.com");
790        let json = serde_json::to_value(&meta).unwrap();
791        assert_eq!(json["issuer"], "https://auth.example.com");
792        assert!(!json["grant_types_supported"].as_array().unwrap().is_empty());
793    }
794
795    #[tokio::test]
796    async fn test_uma_service_discovery() {
797        let svc = UmaService::new(enabled_config());
798        let meta = svc.discovery_metadata("https://auth.example.com");
799        assert_eq!(meta.claims_interaction_endpoint, "/api/uma/claims");
800    }
801
802    // ── Resource Set Updates ────────────────────────────────────
803
804    #[tokio::test]
805    async fn test_update_resource_set() {
806        let svc = UmaService::new(enabled_config());
807        let id = svc
808            .register_resource_set(sample_resource("alice"))
809            .await
810            .unwrap();
811        svc.update_resource_set(
812            &id,
813            "alice",
814            Some("Updated Photos".to_string()),
815            Some(vec![
816                "read".to_string(),
817                "write".to_string(),
818                "delete".to_string(),
819            ]),
820            None,
821        )
822        .await
823        .unwrap();
824        let rs = svc.get_resource_set(&id).await.unwrap();
825        assert_eq!(rs.name, "Updated Photos");
826        assert_eq!(rs.scopes.len(), 3);
827    }
828
829    #[tokio::test]
830    async fn test_update_resource_set_wrong_owner() {
831        let svc = UmaService::new(enabled_config());
832        let id = svc
833            .register_resource_set(sample_resource("alice"))
834            .await
835            .unwrap();
836        assert!(
837            svc.update_resource_set(&id, "eve", Some("Hacked".to_string()), None, None)
838                .await
839                .is_err()
840        );
841    }
842
843    #[tokio::test]
844    async fn test_resource_count() {
845        let svc = UmaService::new(enabled_config());
846        assert_eq!(svc.resource_count().await, 0);
847        svc.register_resource_set(sample_resource("alice"))
848            .await
849            .unwrap();
850        assert_eq!(svc.resource_count().await, 1);
851    }
852
853    // ── PAT Store ───────────────────────────────────────────────
854
855    #[tokio::test]
856    async fn test_pat_issue_and_validate() {
857        let store = PatStore::new();
858        let pat = store.issue("client1", 3600).await;
859        assert!(pat.access_token.starts_with("pat_"));
860        assert_eq!(pat.client_id, "client1");
861        assert!(!pat.is_expired());
862
863        let validated = store.validate(&pat.access_token).await.unwrap();
864        assert_eq!(validated.client_id, "client1");
865    }
866
867    #[tokio::test]
868    async fn test_pat_validate_unknown() {
869        let store = PatStore::new();
870        assert!(store.validate("bogus").await.is_err());
871    }
872
873    #[tokio::test]
874    async fn test_pat_revoke() {
875        let store = PatStore::new();
876        let pat = store.issue("client1", 3600).await;
877        assert!(store.revoke(&pat.access_token).await);
878        assert!(!store.revoke(&pat.access_token).await);
879        assert!(store.validate(&pat.access_token).await.is_err());
880    }
881
882    #[tokio::test]
883    async fn test_pat_count() {
884        let store = PatStore::new();
885        store.issue("c1", 3600).await;
886        store.issue("c2", 3600).await;
887        assert_eq!(store.count().await, 2);
888    }
889
890    // ── RPT Store & Introspection ───────────────────────────────
891
892    #[tokio::test]
893    async fn test_rpt_register_and_introspect() {
894        let store = RptStore::new();
895        store
896            .register("rpt-123", "resource-1", vec!["read".to_string()], 3600)
897            .await;
898        let resp = store.introspect("rpt-123").await;
899        assert!(resp.active);
900        assert_eq!(resp.permissions.len(), 1);
901        assert_eq!(resp.permissions[0].resource_id, "resource-1");
902        assert_eq!(resp.permissions[0].scopes, vec!["read"]);
903    }
904
905    #[tokio::test]
906    async fn test_rpt_introspect_unknown() {
907        let store = RptStore::new();
908        let resp = store.introspect("unknown").await;
909        assert!(!resp.active);
910        assert!(resp.permissions.is_empty());
911    }
912
913    #[tokio::test]
914    async fn test_rpt_revoke() {
915        let store = RptStore::new();
916        store
917            .register("rpt-456", "res-1", vec!["write".to_string()], 3600)
918            .await;
919        assert!(store.revoke("rpt-456").await);
920        let resp = store.introspect("rpt-456").await;
921        assert!(!resp.active);
922    }
923
924    #[tokio::test]
925    async fn test_rpt_count() {
926        let store = RptStore::new();
927        store
928            .register("rpt-1", "r1", vec!["read".to_string()], 3600)
929            .await;
930        store
931            .register("rpt-2", "r2", vec!["write".to_string()], 3600)
932            .await;
933        assert_eq!(store.count().await, 2);
934    }
935
936    #[tokio::test]
937    async fn test_rpt_introspection_serialization() {
938        let resp = RptIntrospectionResponse {
939            active: true,
940            permissions: vec![RptPermission {
941                resource_id: "res-1".to_string(),
942                scopes: vec!["read".to_string()],
943            }],
944            exp: Some(9999999999),
945            iat: Some(1000000000),
946        };
947        let json = serde_json::to_value(&resp).unwrap();
948        assert_eq!(json["active"], true);
949        assert_eq!(json["permissions"][0]["resource_id"], "res-1");
950    }
951}