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