core-policy 0.11.1

Pure RBAC/ABAC policy engine core (zero crypto/network dependencies)
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
//! Policy definitions and validation logic
//!
//! This module provides the core domain types for RBAC/ABAC authorization:
//! - `Action`: What operations can be performed
//! - `Resource`: What can be accessed
//! - `PolicyRule`: Individual authorization rule
//! - `Policy`: Collection of rules with versioning
//!
//! ## Security Constraints
//!
//! The following limits are enforced to prevent resource exhaustion:
//! - `MAX_RULES_PER_POLICY` (1024): Maximum rules per policy
//! - `MAX_POLICY_NAME_LENGTH` (128): Maximum policy name length
//! - `MAX_RESOURCE_PATTERN_LENGTH` (256): Maximum pattern length

use crate::context_expr::ContextExpr;
use crate::error::{PolicyError, Result};
use crate::path::PathPattern;
use crate::{MAX_POLICY_NAME_LENGTH, MAX_RULES_PER_POLICY};
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

/// Action that can be performed on a resource
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Action {
    /// Read access
    Read,
    /// Write access
    Write,
    /// Execute access
    Execute,
    /// Delete access
    Delete,
    /// All actions
    All,
    /// Custom action
    Custom(String),
}

impl Action {
    /// Check if this action matches another action (considering wildcards)
    #[must_use]
    pub fn matches(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::All, _) | (_, Self::All) => true,
            (a, b) => a == b,
        }
    }
}

/// Resource that can be accessed
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Resource {
    /// File system path
    File(String),
    /// USB device
    Usb(String),
    /// Network tunnel
    Tunnel(String),
    /// All resources
    All,
    /// Custom resource
    Custom {
        /// Resource type identifier
        resource_type: String,
        /// Resource path
        path: String,
    },
}

impl Resource {
    /// Check if this resource matches another resource (considering wildcards)
    #[must_use]
    pub fn matches(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::All, _) | (_, Self::All) => true,
            (Self::File(pattern), Self::File(path)) => {
                // Use unchecked since patterns in existing resources are assumed valid
                PathPattern::new_unchecked(pattern).matches(path)
            }
            (Self::Usb(pattern), Self::Usb(device)) => {
                PathPattern::new_unchecked(pattern).matches(device)
            }
            (Self::Tunnel(pattern), Self::Tunnel(name)) => {
                PathPattern::new_unchecked(pattern).matches(name)
            }
            (
                Self::Custom {
                    resource_type: t1,
                    path: p1,
                },
                Self::Custom {
                    resource_type: t2,
                    path: p2,
                },
            ) => t1 == t2 && PathPattern::new_unchecked(p1).matches(p2),
            _ => false,
        }
    }
}

/// A single policy rule with optional ABAC (Attribute-Based Access Control) features
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyRule {
    /// Peer ID that this rule applies to
    pub peer_id: String,
    /// Action allowed by this rule
    pub action: Action,
    /// Resource this rule applies to
    pub resource: Resource,

    // ===== ABAC Features =====
    /// Optional expiration timestamp (Unix seconds)
    /// If set, the rule is only valid before this time
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,

    /// Optional context attributes for conditional access (legacy - simple key-value matching)
    /// Examples: {"location": "office", "security_level": "high"}
    ///
    /// Uses BTreeMap for deterministic serialization (cryptographic safety)
    ///
    /// **Note:** This is the legacy ABAC mechanism. For complex boolean logic,
    /// use `context_expr` instead.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, String>,

    /// Optional context expression for advanced ABAC (boolean logic)
    ///
    /// This provides more powerful conditional logic than simple attribute matching:
    /// - Boolean operators: AND, OR, NOT
    /// - Comparison operators: ==, !=, <, <=, >, >=
    /// - Attribute existence checks: HAS
    ///
    /// Examples:
    /// - `role == "admin" AND department == "IT"`
    /// - `(role == "admin" OR role == "moderator") AND active == "true"`
    /// - `NOT (status == "banned")`
    ///
    /// When both `attributes` and `context_expr` are present, **both** must match.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_expr: Option<ContextExpr>,
}

impl PolicyRule {
    /// Create a new policy rule with basic RBAC
    #[must_use]
    pub fn new(peer_id: String, action: Action, resource: Resource) -> Self {
        Self {
            peer_id,
            action,
            resource,
            expires_at: None,
            attributes: BTreeMap::new(),
            context_expr: None,
        }
    }

    /// Create a new policy rule with expiration (ABAC)
    #[must_use]
    pub fn with_expiration(
        peer_id: String,
        action: Action,
        resource: Resource,
        expires_at: u64,
    ) -> Self {
        Self {
            peer_id,
            action,
            resource,
            expires_at: Some(expires_at),
            attributes: BTreeMap::new(),
            context_expr: None,
        }
    }

    /// Create a new policy rule with attributes (ABAC)
    #[must_use]
    pub const fn with_attributes(
        peer_id: String,
        action: Action,
        resource: Resource,
        attributes: BTreeMap<String, String>,
    ) -> Self {
        Self {
            peer_id,
            action,
            resource,
            expires_at: None,
            attributes,
            context_expr: None,
        }
    }

    /// Add an expiration time to this rule
    #[must_use]
    pub const fn expires_at(mut self, timestamp: u64) -> Self {
        self.expires_at = Some(timestamp);
        self
    }

    /// Add an attribute to this rule
    #[must_use]
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Add a context expression to this rule (advanced ABAC)
    ///
    /// # Example
    ///
    /// ```
    /// use core_policy::{PolicyRule, Action, Resource, ContextExpr};
    ///
    /// let rule = PolicyRule::new("alice".into(), Action::Read, Resource::All)
    ///     .with_context_expr(ContextExpr::parse("role == \"admin\"").unwrap());
    /// ```
    #[must_use]
    pub fn with_context_expr(mut self, expr: ContextExpr) -> Self {
        self.context_expr = Some(expr);
        self
    }

    /// Check if this rule has expired
    #[must_use]
    pub fn is_expired(&self, current_time: u64) -> bool {
        self.expires_at.is_some_and(|exp| current_time >= exp)
    }

    /// Check if this rule's attributes match the given context
    ///
    /// This method evaluates both legacy attribute matching and the new context expression:
    /// 1. If `attributes` is non-empty, all attributes must match (legacy behavior)
    /// 2. If `context_expr` is present, it must evaluate to true
    /// 3. Both conditions must be satisfied if both are present
    ///
    /// Returns true if all context constraints match.
    #[must_use]
    pub fn matches_context(&self, context: &BTreeMap<String, String>) -> bool {
        // Legacy attribute matching (simple key-value equality)
        let attributes_match = if self.attributes.is_empty() {
            true // No constraints = always matches
        } else {
            // All rule attributes must be present in context and match
            self.attributes
                .iter()
                .all(|(key, value)| context.get(key) == Some(value))
        };

        // New context expression evaluation (boolean logic)
        let expr_match = match &self.context_expr {
            None => true, // No expression = always matches
            Some(expr) => {
                // Evaluate expression with depth 0 (start of recursion)
                // If evaluation fails (e.g., too deep), treat as non-match for security
                expr.evaluate(context, 0).unwrap_or(false)
            }
        };

        // Both must match
        attributes_match && expr_match
    }

    /// Check if this rule allows a specific action on a resource for a peer
    /// Basic RBAC check (no time or context validation)
    #[must_use]
    pub fn allows(&self, peer_id: &str, action: &Action, resource: &Resource) -> bool {
        self.peer_id == peer_id && self.action.matches(action) && self.resource.matches(resource)
    }

    /// Check if this rule allows a specific action on a resource for a peer
    /// Includes time-based and attribute-based checks
    #[must_use]
    pub fn allows_with_context(
        &self,
        peer_id: &str,
        action: &Action,
        resource: &Resource,
        current_time: u64,
        context: &BTreeMap<String, String>,
    ) -> bool {
        // Basic RBAC check
        if !self.allows(peer_id, action, resource) {
            return false;
        }

        // Time-based check (if rule has expiration)
        if self.is_expired(current_time) {
            return false;
        }

        // Attribute-based check (if rule has attributes)
        if !self.matches_context(context) {
            return false;
        }

        true
    }
}

/// A policy containing multiple rules
///
/// # Security
///
/// Fields are private to enforce validation through deserialization.
/// Use `Policy::new()` or deserialize from TOML/JSON to create instances.
/// The `#[serde(try_from)]` attribute ensures all deserialized policies
/// are validated against T20 limits (max rules, max name length, etc.).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "PolicyRaw")]
pub struct Policy {
    /// Policy name/identifier
    name: String,

    // ===== Version Control =====
    /// Policy version (monotonic counter, starts at 1)
    version: u64,

    /// Unix timestamp when this policy was issued
    issued_at: u64,

    /// Unix timestamp when this policy expires
    valid_until: u64,

    /// List of policy rules
    rules: Vec<PolicyRule>,

    /// Metadata (uses BTreeMap for deterministic serialization)
    metadata: BTreeMap<String, String>,
}

fn default_version() -> u64 {
    1
}

/// Raw policy structure for deserialization (internal use only)
///
/// This struct is used as an intermediate representation during deserialization.
/// After parsing, it is converted to `Policy` via `TryFrom<PolicyRaw>`, which
/// performs validation to enforce T20 limits.
///
/// This pattern ensures that **all** deserialized policies are validated,
/// preventing DoS attacks through maliciously crafted policy files.
#[derive(Debug, Clone, Deserialize)]
struct PolicyRaw {
    name: String,
    #[serde(default = "default_version")]
    version: u64,
    #[serde(default)]
    issued_at: u64,
    #[serde(default)]
    valid_until: u64,
    rules: Vec<PolicyRule>,
    #[serde(default)]
    metadata: BTreeMap<String, String>,
}

/// Convert PolicyRaw to Policy with validation
///
/// This is called automatically during deserialization due to the
/// `#[serde(try_from = "PolicyRaw")]` attribute on `Policy`.
///
/// # Errors
///
/// Returns `PolicyError` if validation fails:
/// - `TooManyRules`: More than `MAX_RULES_PER_POLICY` rules
/// - `NameTooLong`: Policy name exceeds `MAX_POLICY_NAME_LENGTH`
/// - `InvalidRule`: Other validation failures (empty name, no rules, etc.)
impl TryFrom<PolicyRaw> for Policy {
    type Error = PolicyError;

    fn try_from(raw: PolicyRaw) -> Result<Self> {
        // T20 mitigation: Enforce maximum name length
        if raw.name.len() > MAX_POLICY_NAME_LENGTH {
            return Err(PolicyError::NameTooLong {
                max: MAX_POLICY_NAME_LENGTH,
                length: raw.name.len(),
            });
        }

        // T20 mitigation: Enforce maximum rules
        if raw.rules.len() > MAX_RULES_PER_POLICY {
            return Err(PolicyError::TooManyRules {
                max: MAX_RULES_PER_POLICY,
                attempted: raw.rules.len(),
            });
        }

        // Create policy instance
        let policy = Policy {
            name: raw.name,
            version: raw.version,
            issued_at: raw.issued_at,
            valid_until: raw.valid_until,
            rules: raw.rules,
            metadata: raw.metadata,
        };

        // Run additional validation
        policy.validate()?;

        Ok(policy)
    }
}

impl Policy {
    // ===== Accessors =====

    /// Get the policy name
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the policy version
    #[must_use]
    pub const fn version(&self) -> u64 {
        self.version
    }

    /// Get the issuance timestamp
    #[must_use]
    pub const fn issued_at(&self) -> u64 {
        self.issued_at
    }

    /// Get the expiration timestamp
    #[must_use]
    pub const fn valid_until(&self) -> u64 {
        self.valid_until
    }

    /// Get a reference to the policy rules
    #[must_use]
    pub fn rules(&self) -> &[PolicyRule] {
        &self.rules
    }

    /// Get a reference to the metadata
    #[must_use]
    pub fn metadata(&self) -> &BTreeMap<String, String> {
        &self.metadata
    }

    // ===== Constructors =====

    /// Create a new empty policy with version 1
    ///
    /// # Arguments
    ///
    /// * `name` - Policy identifier
    /// * `valid_duration_secs` - How long this policy is valid (in seconds)
    /// * `current_time` - Current Unix timestamp (injected for purity/determinism)
    ///
    /// # Errors
    ///
    /// Returns `PolicyError::NameTooLong` if name exceeds `MAX_POLICY_NAME_LENGTH`
    pub fn new(
        name: impl Into<String>,
        valid_duration_secs: u64,
        current_time: u64,
    ) -> Result<Self> {
        let name = name.into();

        // T20 mitigation: Enforce maximum name length
        if name.len() > MAX_POLICY_NAME_LENGTH {
            return Err(PolicyError::NameTooLong {
                max: MAX_POLICY_NAME_LENGTH,
                length: name.len(),
            });
        }

        Ok(Self {
            name,
            version: 1,
            issued_at: current_time,
            valid_until: current_time + valid_duration_secs,
            rules: Vec::new(),
            metadata: BTreeMap::new(),
        })
    }

    /// Create a policy without timestamps (for testing/legacy)
    ///
    /// # Errors
    ///
    /// Returns `PolicyError::NameTooLong` if name exceeds `MAX_POLICY_NAME_LENGTH`
    pub fn new_unversioned(name: impl Into<String>) -> Result<Self> {
        let name = name.into();

        // T20 mitigation: Enforce maximum name length
        if name.len() > MAX_POLICY_NAME_LENGTH {
            return Err(PolicyError::NameTooLong {
                max: MAX_POLICY_NAME_LENGTH,
                length: name.len(),
            });
        }

        Ok(Self {
            name,
            version: 1,
            issued_at: 0,
            valid_until: 2_000_000_000, // Year 2033 (reasonable far future)
            rules: Vec::new(),
            metadata: BTreeMap::new(),
        })
    }

    /// Add a rule to this policy
    ///
    /// # Errors
    ///
    /// Returns `PolicyError::TooManyRules` if adding this rule would exceed `MAX_RULES_PER_POLICY`
    pub fn add_rule(mut self, rule: PolicyRule) -> Result<Self> {
        // T20 mitigation: Enforce maximum rules
        if self.rules.len() >= MAX_RULES_PER_POLICY {
            return Err(PolicyError::TooManyRules {
                max: MAX_RULES_PER_POLICY,
                attempted: self.rules.len() + 1,
            });
        }

        self.rules.push(rule);
        Ok(self)
    }

    /// Add metadata to this policy
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Check if a peer is allowed to perform an action on a resource
    ///
    /// This method delegates to `PolicyAuthorizer` (SRP - Single Responsibility Principle).
    /// The Policy struct focuses on construction and management, while authorization
    /// logic is handled by the dedicated `PolicyAuthorizer`.
    #[must_use]
    pub fn is_allowed(&self, peer_id: &str, action: &Action, resource: &Resource) -> bool {
        crate::authorizer::PolicyAuthorizer::new(&self.rules).is_allowed(peer_id, action, resource)
    }

    /// Validate policy (check for conflicts, invalid rules, etc.)
    ///
    /// # Errors
    ///
    /// Returns `PolicyError::InvalidRule` if:
    /// - Policy name is empty
    /// - Policy has no rules
    /// - Any rule has an empty peer ID
    pub fn validate(&self) -> Result<()> {
        if self.name.is_empty() {
            return Err(PolicyError::InvalidRule(
                "Policy name cannot be empty".to_string(),
            ));
        }

        if self.rules.is_empty() {
            return Err(PolicyError::InvalidRule(
                "Policy must have at least one rule".to_string(),
            ));
        }

        for rule in &self.rules {
            if rule.peer_id.is_empty() {
                return Err(PolicyError::InvalidRule(
                    "Peer ID cannot be empty".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Load policy from TOML string
    ///
    /// Requires the `toml` feature.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - TOML parsing fails
    /// - Validation fails (see `validate()`)
    #[cfg(feature = "toml")]
    pub fn from_toml(toml_str: &str) -> Result<Self> {
        let policy: Self = toml::from_str(toml_str)?;
        policy.validate()?;
        Ok(policy)
    }

    /// Serialize policy to TOML string
    ///
    /// Requires the `toml` feature.
    ///
    /// # Errors
    ///
    /// Returns `PolicyError::SerializationError` if TOML serialization fails
    #[cfg(feature = "toml")]
    pub fn to_toml(&self) -> Result<String> {
        toml::to_string(self).map_err(|e| PolicyError::SerializationError(e.to_string()))
    }
}