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