role-system 1.1.1

A flexible and powerful role-based access control (RBAC) library for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Permission definitions and validation with enhanced three-part format support.

use crate::error::{Error, Result};
use std::collections::HashMap;
use std::sync::Arc;

/// A permission represents an action that can be performed on a resource type.
///
/// Permissions follow the format "action:resource" or "action:resource:instance"
/// Examples:
/// - "read:documents" - Read any document
/// - "read:documents:doc123" - Read specific document doc123
/// - "admin:users" - Admin access to users
/// - "admin:users:user456" - Admin access to specific user
///
/// Special permissions:
/// - "*:*" grants all permissions (super admin)
/// - "action:*" grants all actions on any resource
/// - "*:resource" grants any action on a specific resource
/// - "action:resource:*" grants action on any instance of resource
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub struct Permission {
    /// The action being performed (e.g., "read", "write", "delete").
    action: String,
    /// The resource type this permission applies to (e.g., "documents", "users").
    resource_type: String,
    /// Optional specific instance of the resource (e.g., "doc123", "user456").
    instance: Option<String>,
    /// Optional conditional validator function.
    #[cfg_attr(feature = "persistence", serde(skip))]
    condition: Option<PermissionCondition>,
}

/// A condition that must be met for a permission to be granted.
pub type PermissionCondition = Arc<dyn Fn(&HashMap<String, String>) -> bool + Send + Sync>;

impl Permission {
    /// Create a new permission for an action on a resource type.
    pub fn new(action: impl Into<String>, resource_type: impl Into<String>) -> Self {
        let action = action.into();
        let resource_type = resource_type.into();

        // Use specialized permission validation that allows wildcards
        Self::validate_permission_field(&action, "action").expect("Invalid action in permission");
        Self::validate_permission_field(&resource_type, "resource_type")
            .expect("Invalid resource_type in permission");

        Self {
            action,
            resource_type,
            instance: None,
            condition: None,
        }
    }

    /// Try to create a new permission, returning an error if validation fails.
    pub fn try_new(action: impl Into<String>, resource_type: impl Into<String>) -> Result<Self> {
        let action = action.into();
        let resource_type = resource_type.into();

        // Use specialized permission validation that allows wildcards
        Self::validate_permission_field(&action, "action")?;
        Self::validate_permission_field(&resource_type, "resource_type")?;

        Ok(Self {
            action,
            resource_type,
            instance: None,
            condition: None,
        })
    }

    /// Create a new permission for an action on a specific resource instance.
    pub fn with_instance(
        action: impl Into<String>,
        resource_type: impl Into<String>,
        instance: impl Into<String>,
    ) -> Self {
        let mut permission = Self::new(action, resource_type);
        let instance = instance.into();

        Self::validate_permission_field(&instance, "instance")
            .expect("Invalid instance in permission");

        permission.instance = Some(instance.to_owned());
        permission
    }

    /// Create a permission with a conditional validator.
    pub fn with_condition<F>(
        action: impl Into<String>,
        resource_type: impl Into<String>,
        condition: F,
    ) -> Self
    where
        F: Fn(&HashMap<String, String>) -> bool + Send + Sync + 'static,
    {
        let mut permission = Self::new(action, resource_type);
        permission.condition = Some(Arc::new(condition));
        permission
    }

    /// Create a permission with both instance and condition.
    pub fn with_instance_and_condition<F>(
        action: impl Into<String>,
        resource_type: impl Into<String>,
        instance: impl Into<String>,
        condition: F,
    ) -> Self
    where
        F: Fn(&HashMap<String, String>) -> bool + Send + Sync + 'static,
    {
        let mut permission = Self::with_instance(action, resource_type, instance);
        permission.condition = Some(Arc::new(condition));
        permission
    }

    /// Create a wildcard permission that grants access to all actions on a resource type.
    pub fn wildcard(resource_type: impl Into<String>) -> Self {
        Self::new("*", resource_type)
    }

    /// Create a super-admin permission that grants access to everything.
    pub fn super_admin() -> Self {
        Self::new("*", "*")
    }

    /// Create a permission with enhanced context awareness.
    ///
    /// # Example
    /// ```rust
    /// use role_system::permission::Permission;
    /// let perm = Permission::with_context("users", "read", Some("own_data"));
    /// ```
    pub fn with_context(
        resource_type: impl Into<String>,
        action: impl Into<String>,
        context: Option<impl Into<String>>,
    ) -> Self {
        let mut permission = Self::new(action, resource_type);
        if let Some(ctx) = context {
            permission.instance = Some(ctx.into());
        }
        permission
    }

    /// Create a permission with multiple scopes/actions.
    ///
    /// # Example
    /// ```rust
    /// use role_system::permission::Permission;
    /// let perms = Permission::with_scope("users", "read", vec!["profile", "preferences"]);
    /// ```
    pub fn with_scope(
        resource_type: impl Into<String>,
        action: impl Into<String>,
        scopes: Vec<impl Into<String>>,
    ) -> Vec<Self> {
        let resource_type = resource_type.into();
        let action = action.into();

        scopes
            .into_iter()
            .map(|scope| Self::with_instance(action.clone(), resource_type.clone(), scope.into()))
            .collect()
    }

    /// Create a conditional permission that depends on context.
    ///
    /// # Example
    /// ```rust
    /// use role_system::permission::Permission;
    /// let perm = Permission::conditional("users", "update")
    ///     .when(|context| context.get("user_id") == context.get("target_id"));
    /// ```
    pub fn conditional(
        resource_type: impl Into<String>,
        action: impl Into<String>,
    ) -> ConditionalPermissionBuilder {
        ConditionalPermissionBuilder::new(resource_type, action)
    }

    /// Get the action this permission grants.
    pub fn action(&self) -> &str {
        &self.action
    }

    /// Get the resource type this permission applies to.
    pub fn resource_type(&self) -> &str {
        &self.resource_type
    }

    /// Get the specific instance this permission applies to, if any.
    pub fn instance(&self) -> Option<&str> {
        self.instance.as_deref()
    }

    /// Check if this permission matches the given action and resource type.
    /// For backward compatibility, this doesn't consider instances.
    pub fn matches(&self, action: &str, resource_type: &str) -> bool {
        let action_match = self.action == "*" || self.action == action;
        let resource_match = self.resource_type == "*" || self.resource_type == resource_type;
        action_match && resource_match
    }

    /// Check if this permission matches the given action, resource type, and optional instance.
    pub fn matches_with_instance(
        &self,
        action: &str,
        resource_type: &str,
        instance: Option<&str>,
    ) -> bool {
        let action_match = self.action == "*" || self.action == action;
        let resource_match = self.resource_type == "*" || self.resource_type == resource_type;

        let instance_match = match (&self.instance, instance) {
            (None, _) => true, // Permission without instance matches any instance
            (Some(perm_inst), Some(req_inst)) => perm_inst == "*" || perm_inst == req_inst,
            (Some(_), None) => false, // Permission with instance doesn't match request without instance
        };

        action_match && resource_match && instance_match
    }

    /// Check if this permission implies another permission.
    /// A permission implies another if it grants equal or greater access.
    ///
    /// Examples:
    /// - "read:documents" implies "read:documents:doc123"
    /// - "admin:*" implies "admin:users"
    /// - "*:*" implies any permission
    /// - "read:documents:*" implies "read:documents:doc123"
    pub fn implies(&self, other: &Permission) -> bool {
        // Check action implication
        let action_implies = self.action == "*" || self.action == other.action;

        // Check resource implication
        let resource_implies =
            self.resource_type == "*" || self.resource_type == other.resource_type;

        // Check instance implication
        let instance_implies = match (&self.instance, &other.instance) {
            (None, _) => true,        // No instance restriction implies any instance
            (Some(_), None) => false, // Instance-specific doesn't imply general
            (Some(self_inst), Some(other_inst)) => self_inst == "*" || self_inst == other_inst,
        };

        action_implies && resource_implies && instance_implies
    }

    /// Check if this permission is granted given the context.
    pub fn is_granted(
        &self,
        action: &str,
        resource_type: &str,
        context: &HashMap<String, String>,
    ) -> bool {
        if !self.matches(action, resource_type) {
            return false;
        }

        // Check conditional validator if present
        if let Some(condition) = &self.condition {
            condition(context)
        } else {
            true
        }
    }

    /// Parse a permission from a string format like "action:resource_type" or "action:resource_type:instance".
    pub fn parse(permission_str: &str) -> Result<Self> {
        let parts: Vec<&str> = permission_str.split(':').collect();

        match parts.len() {
            2 => {
                let action = parts[0].trim();
                let resource_type = parts[1].trim();

                Self::validate_permission_field(action, "action")?;
                Self::validate_permission_field(resource_type, "resource_type")?;

                Ok(Self::new(action, resource_type))
            }
            3 => {
                let action = parts[0].trim();
                let resource_type = parts[1].trim();
                let instance = parts[2].trim();

                Self::validate_permission_field(action, "action")?;
                Self::validate_permission_field(resource_type, "resource_type")?;
                Self::validate_permission_field(instance, "instance")?;

                Ok(Self::with_instance(action, resource_type, instance))
            }
            _ => Err(Error::InvalidPermission(format!(
                "Permission must be in format 'action:resource_type' or 'action:resource_type:instance', got: '{permission_str}'"
            ))),
        }
    }

    /// Validate permission field allowing wildcards and other permission-specific characters.
    fn validate_permission_field(value: &str, field_name: &str) -> Result<()> {
        if value.trim().is_empty() {
            return Err(Error::ValidationError {
                field: field_name.to_string(),
                reason: "cannot be empty".to_string(),
                invalid_value: Some(value.to_string()),
            });
        }

        if value.len() > 255 {
            return Err(Error::ValidationError {
                field: field_name.to_string(),
                reason: "exceeds maximum length of 255 characters".to_string(),
                invalid_value: Some(format!("{}...", &value[..50])),
            });
        }

        // Allow wildcards and alphanumeric characters, hyphens, underscores
        // But reject dangerous control characters and certain symbols
        if value
            .chars()
            .any(|c| c.is_control() || "'\";{}[]\\<>".contains(c))
        {
            return Err(Error::ValidationError {
                field: field_name.to_string(),
                reason: "contains invalid characters".to_string(),
                invalid_value: Some(value.to_string()),
            });
        }

        // Still check for path traversal attempts
        if value.contains("..") || value.contains('\0') {
            return Err(Error::ValidationError {
                field: field_name.to_string(),
                reason: "contains path traversal sequences".to_string(),
                invalid_value: Some(value.to_string()),
            });
        }

        Ok(())
    }
}

/// Builder for creating conditional permissions with fluent API.
pub struct ConditionalPermissionBuilder {
    resource_type: String,
    action: String,
    conditions: Vec<PermissionCondition>,
}

impl ConditionalPermissionBuilder {
    /// Create a new conditional permission builder.
    pub fn new(resource_type: impl Into<String>, action: impl Into<String>) -> Self {
        Self {
            resource_type: resource_type.into(),
            action: action.into(),
            conditions: Vec::new(),
        }
    }

    /// Add a condition that must be true for the permission to be granted.
    pub fn when<F>(mut self, condition: F) -> Self
    where
        F: Fn(&HashMap<String, String>) -> bool + Send + Sync + 'static,
    {
        self.conditions.push(Arc::new(condition));
        self
    }

    /// Add an alternative condition (OR logic).
    pub fn or_when<F>(mut self, condition: F) -> Self
    where
        F: Fn(&HashMap<String, String>) -> bool + Send + Sync + 'static,
    {
        self.conditions.push(Arc::new(condition));
        self
    }

    /// Build the final permission with all conditions combined.
    pub fn build(self) -> Permission {
        let combined_condition = if self.conditions.is_empty() {
            None
        } else {
            Some(Arc::new(move |context: &HashMap<String, String>| {
                // OR logic: any condition can be true
                self.conditions.iter().any(|condition| condition(context))
            }) as PermissionCondition)
        };

        Permission {
            action: self.action,
            resource_type: self.resource_type,
            instance: None,
            condition: combined_condition,
        }
    }
}

impl std::fmt::Debug for Permission {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Permission")
            .field("action", &self.action)
            .field("resource_type", &self.resource_type)
            .field("instance", &self.instance)
            .field("has_condition", &self.condition.is_some())
            .finish()
    }
}

impl Clone for Permission {
    fn clone(&self) -> Self {
        Self {
            action: self.action.clone(),
            resource_type: self.resource_type.clone(),
            instance: self.instance.clone(),
            condition: self.condition.clone(), // Now we can clone Arc
        }
    }
}

impl PartialEq for Permission {
    fn eq(&self, other: &Self) -> bool {
        self.action == other.action
            && self.resource_type == other.resource_type
            && self.instance == other.instance
        // Note: We don't compare conditions as they're function pointers
    }
}

impl Eq for Permission {}

impl std::hash::Hash for Permission {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.action.hash(state);
        self.resource_type.hash(state);
        self.instance.hash(state);
        // Note: We don't hash conditions as they're function pointers
    }
}

impl std::fmt::Display for Permission {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.instance {
            Some(instance) => write!(f, "{}:{}:{}", self.action, self.resource_type, instance),
            None => write!(f, "{}:{}", self.action, self.resource_type),
        }
    }
}

impl std::str::FromStr for Permission {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

/// A collection of permissions with utility methods.
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub struct PermissionSet {
    permissions: Vec<Permission>,
}

impl std::fmt::Debug for PermissionSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PermissionSet")
            .field("permissions", &self.permissions)
            .field("count", &self.permissions.len())
            .finish()
    }
}

impl Clone for PermissionSet {
    fn clone(&self) -> Self {
        Self {
            permissions: self.permissions.clone(),
        }
    }
}

impl Default for PermissionSet {
    fn default() -> Self {
        Self::new()
    }
}

impl PermissionSet {
    /// Create a new empty permission set.
    pub fn new() -> Self {
        Self {
            permissions: Vec::new(),
        }
    }

    /// Add a permission to the set.
    pub fn add(&mut self, permission: Permission) {
        self.permissions.push(permission);
    }

    /// Remove a permission from the set.
    pub fn remove(&mut self, permission: &Permission) {
        self.permissions.retain(|p| p != permission);
    }

    /// Check if the set contains a specific permission.
    pub fn contains(&self, permission: &Permission) -> bool {
        self.permissions.contains(permission)
    }

    /// Check if any permission in the set grants the given action on the resource type.
    pub fn grants(
        &self,
        action: &str,
        resource_type: &str,
        context: &HashMap<String, String>,
    ) -> bool {
        self.permissions
            .iter()
            .any(|p| p.is_granted(action, resource_type, context))
    }

    /// Check if any permission in the set grants the given action on the resource type and instance.
    pub fn grants_with_instance(
        &self,
        action: &str,
        resource_type: &str,
        instance: Option<&str>,
        context: &HashMap<String, String>,
    ) -> bool {
        self.permissions.iter().any(|p| {
            p.matches_with_instance(action, resource_type, instance)
                && (p.condition.is_none() || p.condition.as_ref().unwrap()(context))
        })
    }

    /// Check if any permission in the set implies the given permission.
    pub fn implies(&self, permission: &Permission) -> bool {
        self.permissions.iter().any(|p| p.implies(permission))
    }

    /// Get all permissions in the set.
    pub fn permissions(&self) -> &[Permission] {
        &self.permissions
    }

    /// Get the number of permissions in the set.
    pub fn len(&self) -> usize {
        self.permissions.len()
    }

    /// Check if the permission set is empty.
    pub fn is_empty(&self) -> bool {
        self.permissions.is_empty()
    }

    /// Merge another permission set into this one.
    pub fn merge(&mut self, other: PermissionSet) {
        for permission in other.permissions {
            if !self.contains(&permission) {
                self.add(permission);
            }
        }
    }
}

impl From<Vec<Permission>> for PermissionSet {
    fn from(permissions: Vec<Permission>) -> Self {
        Self { permissions }
    }
}

impl From<Permission> for PermissionSet {
    fn from(permission: Permission) -> Self {
        Self {
            permissions: vec![permission],
        }
    }
}

impl IntoIterator for PermissionSet {
    type Item = Permission;
    type IntoIter = std::vec::IntoIter<Permission>;

    fn into_iter(self) -> Self::IntoIter {
        self.permissions.into_iter()
    }
}

impl<'a> IntoIterator for &'a PermissionSet {
    type Item = &'a Permission;
    type IntoIter = std::slice::Iter<'a, Permission>;

    fn into_iter(self) -> Self::IntoIter {
        self.permissions.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_permission_creation() {
        let permission = Permission::new("read", "documents");
        assert_eq!(permission.action(), "read");
        assert_eq!(permission.resource_type(), "documents");
        assert_eq!(permission.instance(), None);
    }

    #[test]
    fn test_permission_with_instance() {
        let permission = Permission::with_instance("read", "documents", "doc123");
        assert_eq!(permission.action(), "read");
        assert_eq!(permission.resource_type(), "documents");
        assert_eq!(permission.instance(), Some("doc123"));
    }

    #[test]
    fn test_permission_matching() {
        let permission = Permission::new("read", "documents");
        assert!(permission.matches("read", "documents"));
        assert!(!permission.matches("write", "documents"));
        assert!(!permission.matches("read", "users"));
    }

    #[test]
    fn test_permission_matching_with_instance() {
        let permission = Permission::with_instance("read", "documents", "doc123");

        // Should match exact instance
        assert!(permission.matches_with_instance("read", "documents", Some("doc123")));

        // Should not match different instance
        assert!(!permission.matches_with_instance("read", "documents", Some("doc456")));

        // Should not match when no instance provided
        assert!(!permission.matches_with_instance("read", "documents", None));

        // General permission should match any instance
        let general_permission = Permission::new("read", "documents");
        assert!(general_permission.matches_with_instance("read", "documents", Some("doc123")));
        assert!(general_permission.matches_with_instance("read", "documents", None));
    }

    #[test]
    fn test_permission_implication() {
        let general = Permission::new("read", "documents");
        let specific = Permission::with_instance("read", "documents", "doc123");

        // General should imply specific
        assert!(general.implies(&specific));

        // Specific should not imply general
        assert!(!specific.implies(&general));

        // Same permission should imply itself
        assert!(general.implies(&general));
        assert!(specific.implies(&specific));

        // Wildcard tests
        let wildcard_action = Permission::new("*", "documents");
        let wildcard_resource = Permission::new("read", "*");
        let super_admin = Permission::super_admin();

        assert!(wildcard_action.implies(&general));
        assert!(wildcard_resource.implies(&general));
        assert!(super_admin.implies(&general));
        assert!(super_admin.implies(&specific));
    }

    #[test]
    fn test_wildcard_permission() {
        let permission = Permission::wildcard("documents");
        assert!(permission.matches("read", "documents"));
        assert!(permission.matches("write", "documents"));
        assert!(!permission.matches("read", "users"));
    }

    #[test]
    fn test_super_admin_permission() {
        let permission = Permission::super_admin();
        assert!(permission.matches("read", "documents"));
        assert!(permission.matches("write", "users"));
        assert!(permission.matches("delete", "anything"));
    }

    #[test]
    fn test_permission_parsing() {
        // Two-part format
        let permission = Permission::parse("read:documents").unwrap();
        assert_eq!(permission.action(), "read");
        assert_eq!(permission.resource_type(), "documents");
        assert_eq!(permission.instance(), None);

        // Three-part format
        let permission = Permission::parse("read:documents:doc123").unwrap();
        assert_eq!(permission.action(), "read");
        assert_eq!(permission.resource_type(), "documents");
        assert_eq!(permission.instance(), Some("doc123"));

        // Error cases
        assert!(Permission::parse("invalid").is_err());
        assert!(Permission::parse("read:").is_err());
        assert!(Permission::parse(":documents").is_err());
        assert!(Permission::parse("read:documents:").is_err());
        assert!(Permission::parse("read:documents:instance:extra").is_err());
    }

    #[test]
    fn test_permission_display() {
        let permission = Permission::new("read", "documents");
        assert_eq!(permission.to_string(), "read:documents");

        let permission_with_instance = Permission::with_instance("read", "documents", "doc123");
        assert_eq!(
            permission_with_instance.to_string(),
            "read:documents:doc123"
        );
    }

    #[test]
    fn test_permission_set() {
        let mut set = PermissionSet::new();
        let perm1 = Permission::new("read", "documents");
        let perm2 = Permission::new("write", "documents");

        set.add(perm1.clone());
        set.add(perm2.clone());

        assert_eq!(set.len(), 2);
        assert!(set.contains(&perm1));
        assert!(set.contains(&perm2));

        let context = HashMap::new();
        assert!(set.grants("read", "documents", &context));
        assert!(set.grants("write", "documents", &context));
        assert!(!set.grants("delete", "documents", &context));
    }

    #[test]
    fn test_permission_set_with_instances() {
        let mut set = PermissionSet::new();
        let general_perm = Permission::new("read", "documents");
        let specific_perm = Permission::with_instance("write", "documents", "doc123");

        set.add(general_perm);
        set.add(specific_perm);

        let context = HashMap::new();

        // General permission should work for any instance
        assert!(set.grants_with_instance("read", "documents", Some("doc123"), &context));
        assert!(set.grants_with_instance("read", "documents", Some("doc456"), &context));
        assert!(set.grants_with_instance("read", "documents", None, &context));

        // Specific permission should only work for that instance
        assert!(set.grants_with_instance("write", "documents", Some("doc123"), &context));
        assert!(!set.grants_with_instance("write", "documents", Some("doc456"), &context));
        assert!(!set.grants_with_instance("write", "documents", None, &context));
    }

    #[test]
    fn test_permission_set_implication() {
        let mut set = PermissionSet::new();
        let general_perm = Permission::new("read", "documents");
        let admin_perm = Permission::new("admin", "*");

        set.add(general_perm);
        set.add(admin_perm);

        let specific_perm = Permission::with_instance("read", "documents", "doc123");
        let admin_users_perm = Permission::new("admin", "users");

        assert!(set.implies(&specific_perm));
        assert!(set.implies(&admin_users_perm));
    }
}