kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Access control system with RBAC and ABAC
//!
//! This module provides:
//! - Role-Based Access Control (RBAC)
//! - Attribute-Based Access Control (ABAC)
//! - Permission management
//! - Access decision making

use chrono::{DateTime, Timelike, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use uuid::Uuid;

use crate::error::{CoreError, Result};

/// Permission represents a specific action that can be performed
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Permission {
    /// Resource type (e.g., "token", "order", "user")
    pub resource: String,
    /// Action (e.g., "create", "read", "update", "delete")
    pub action: String,
}

impl Permission {
    /// Create a new permission
    pub fn new(resource: impl Into<String>, action: impl Into<String>) -> Self {
        Self {
            resource: resource.into(),
            action: action.into(),
        }
    }

    /// Parse permission from string format "resource:action"
    pub fn from_string(s: &str) -> Result<Self> {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() != 2 {
            return Err(CoreError::Validation(
                "Permission must be in format 'resource:action'".to_string(),
            ));
        }

        Ok(Self {
            resource: parts[0].to_string(),
            action: parts[1].to_string(),
        })
    }

    /// Convert permission to string format
    pub fn to_string_format(&self) -> String {
        format!("{}:{}", self.resource, self.action)
    }

    /// Check if this permission matches a pattern (supports wildcards)
    pub fn matches(&self, pattern: &Permission) -> bool {
        let resource_match = pattern.resource == "*" || pattern.resource == self.resource;
        let action_match = pattern.action == "*" || pattern.action == self.action;

        resource_match && action_match
    }
}

/// Role in RBAC system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    /// Role ID
    pub id: Uuid,
    /// Role name
    pub name: String,
    /// Role description
    pub description: Option<String>,
    /// Permissions associated with this role
    pub permissions: HashSet<Permission>,
    /// Parent roles (for role inheritance)
    pub parent_roles: Vec<Uuid>,
    /// Created timestamp
    pub created_at: DateTime<Utc>,
}

impl Role {
    /// Create a new role
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4(),
            name: name.into(),
            description: None,
            permissions: HashSet::new(),
            parent_roles: Vec::new(),
            created_at: Utc::now(),
        }
    }

    /// Add a permission to the role
    pub fn add_permission(&mut self, permission: Permission) {
        self.permissions.insert(permission);
    }

    /// Remove a permission from the role
    pub fn remove_permission(&mut self, permission: &Permission) {
        self.permissions.remove(permission);
    }

    /// Check if role has a specific permission
    pub fn has_permission(&self, permission: &Permission) -> bool {
        self.permissions
            .iter()
            .any(|p| p == permission || permission.matches(p))
    }

    /// Add parent role for inheritance
    pub fn add_parent(&mut self, parent_id: Uuid) {
        if !self.parent_roles.contains(&parent_id) {
            self.parent_roles.push(parent_id);
        }
    }
}

/// User with assigned roles
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRoles {
    /// User ID
    pub user_id: Uuid,
    /// Assigned role IDs
    pub role_ids: Vec<Uuid>,
    /// Direct permissions (outside of roles)
    pub direct_permissions: HashSet<Permission>,
}

impl UserRoles {
    /// Create new user roles
    pub fn new(user_id: Uuid) -> Self {
        Self {
            user_id,
            role_ids: Vec::new(),
            direct_permissions: HashSet::new(),
        }
    }

    /// Assign a role to the user
    pub fn assign_role(&mut self, role_id: Uuid) {
        if !self.role_ids.contains(&role_id) {
            self.role_ids.push(role_id);
        }
    }

    /// Revoke a role from the user
    pub fn revoke_role(&mut self, role_id: &Uuid) {
        self.role_ids.retain(|id| id != role_id);
    }

    /// Add direct permission
    pub fn add_permission(&mut self, permission: Permission) {
        self.direct_permissions.insert(permission);
    }
}

/// Attribute for ABAC
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Attribute {
    /// Attribute key
    pub key: String,
    /// Attribute value
    pub value: String,
}

impl Attribute {
    /// Create a new attribute
    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            value: value.into(),
        }
    }
}

/// ABAC policy condition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PolicyCondition {
    /// Attribute equals value
    AttributeEquals {
        /// Attribute name to check.
        key: String,
        /// Expected attribute value.
        value: String,
    },
    /// Attribute contains value
    AttributeContains {
        /// Attribute name to check.
        key: String,
        /// Substring or element the attribute must contain.
        value: String,
    },
    /// Attribute greater than value (numeric)
    AttributeGreaterThan {
        /// Attribute name to check.
        key: String,
        /// Threshold value the attribute must exceed.
        value: String,
    },
    /// Time-based condition
    TimeWindow {
        /// Hour-of-day (0-23) when the window begins.
        start_hour: u8,
        /// Hour-of-day (0-23) when the window ends.
        end_hour: u8,
    },
    /// Combination of conditions (AND)
    And(Vec<PolicyCondition>),
    /// Combination of conditions (OR)
    Or(Vec<PolicyCondition>),
    /// Negation
    Not(Box<PolicyCondition>),
}

impl PolicyCondition {
    /// Evaluate condition against attributes
    pub fn evaluate(&self, attributes: &HashMap<String, String>) -> bool {
        match self {
            PolicyCondition::AttributeEquals { key, value } => {
                attributes.get(key).map(|v| v == value).unwrap_or(false)
            }
            PolicyCondition::AttributeContains { key, value } => attributes
                .get(key)
                .map(|v| v.contains(value))
                .unwrap_or(false),
            PolicyCondition::AttributeGreaterThan { key, value } => {
                if let Some(attr_value) = attributes.get(key) {
                    if let (Ok(av), Ok(cv)) = (attr_value.parse::<f64>(), value.parse::<f64>()) {
                        return av > cv;
                    }
                }
                false
            }
            PolicyCondition::TimeWindow {
                start_hour,
                end_hour,
            } => {
                let now = Utc::now().time();
                let current_hour = now.hour() as u8;
                current_hour >= *start_hour && current_hour < *end_hour
            }
            PolicyCondition::And(conditions) => conditions.iter().all(|c| c.evaluate(attributes)),
            PolicyCondition::Or(conditions) => conditions.iter().any(|c| c.evaluate(attributes)),
            PolicyCondition::Not(condition) => !condition.evaluate(attributes),
        }
    }
}

/// ABAC policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AbacPolicy {
    /// Policy ID
    pub id: Uuid,
    /// Policy name
    pub name: String,
    /// Resource this policy applies to
    pub resource: String,
    /// Action this policy allows
    pub action: String,
    /// Conditions that must be met
    pub conditions: Vec<PolicyCondition>,
    /// Policy priority (higher = evaluated first)
    pub priority: i32,
}

impl AbacPolicy {
    /// Create a new ABAC policy
    pub fn new(
        name: impl Into<String>,
        resource: impl Into<String>,
        action: impl Into<String>,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            name: name.into(),
            resource: resource.into(),
            action: action.into(),
            conditions: Vec::new(),
            priority: 0,
        }
    }

    /// Add a condition to the policy
    pub fn add_condition(&mut self, condition: PolicyCondition) {
        self.conditions.push(condition);
    }

    /// Evaluate if policy allows access
    pub fn allows(&self, permission: &Permission, attributes: &HashMap<String, String>) -> bool {
        // Check if permission matches
        if self.resource != permission.resource || self.action != permission.action {
            return false;
        }

        // Evaluate all conditions (AND logic)
        self.conditions.iter().all(|c| c.evaluate(attributes))
    }
}

/// Access control manager (combines RBAC and ABAC)
pub struct AccessControlManager {
    /// All roles in the system
    roles: HashMap<Uuid, Role>,
    /// User role assignments
    user_roles: HashMap<Uuid, UserRoles>,
    /// ABAC policies
    policies: Vec<AbacPolicy>,
}

impl AccessControlManager {
    /// Create a new access control manager
    pub fn new() -> Self {
        Self {
            roles: HashMap::new(),
            user_roles: HashMap::new(),
            policies: Vec::new(),
        }
    }

    /// Add a role to the system
    pub fn add_role(&mut self, role: Role) {
        self.roles.insert(role.id, role);
    }

    /// Get a role by ID
    pub fn get_role(&self, role_id: &Uuid) -> Option<&Role> {
        self.roles.get(role_id)
    }

    /// Assign a role to a user
    pub fn assign_role_to_user(&mut self, user_id: Uuid, role_id: Uuid) -> Result<()> {
        // Check if role exists
        if !self.roles.contains_key(&role_id) {
            return Err(CoreError::NotFound(format!("Role {} not found", role_id)));
        }

        let user_roles = self
            .user_roles
            .entry(user_id)
            .or_insert_with(|| UserRoles::new(user_id));
        user_roles.assign_role(role_id);

        Ok(())
    }

    /// Revoke a role from a user
    pub fn revoke_role_from_user(&mut self, user_id: Uuid, role_id: Uuid) {
        if let Some(user_roles) = self.user_roles.get_mut(&user_id) {
            user_roles.revoke_role(&role_id);
        }
    }

    /// Add a direct permission to a user
    pub fn add_permission_to_user(&mut self, user_id: Uuid, permission: Permission) {
        let user_roles = self
            .user_roles
            .entry(user_id)
            .or_insert_with(|| UserRoles::new(user_id));
        user_roles.add_permission(permission);
    }

    /// Get all permissions for a user (including inherited from roles)
    pub fn get_user_permissions(&self, user_id: &Uuid) -> HashSet<Permission> {
        let mut permissions = HashSet::new();

        if let Some(user_roles) = self.user_roles.get(user_id) {
            // Add direct permissions
            permissions.extend(user_roles.direct_permissions.clone());

            // Add permissions from roles (with inheritance)
            for role_id in &user_roles.role_ids {
                self.add_role_permissions(&mut permissions, role_id, &mut HashSet::new());
            }
        }

        permissions
    }

    /// Recursively add role permissions (handles inheritance)
    fn add_role_permissions(
        &self,
        permissions: &mut HashSet<Permission>,
        role_id: &Uuid,
        visited: &mut HashSet<Uuid>,
    ) {
        // Prevent infinite loops
        if visited.contains(role_id) {
            return;
        }
        visited.insert(*role_id);

        if let Some(role) = self.roles.get(role_id) {
            permissions.extend(role.permissions.clone());

            // Add parent role permissions
            for parent_id in &role.parent_roles {
                self.add_role_permissions(permissions, parent_id, visited);
            }
        }
    }

    /// Add an ABAC policy
    pub fn add_policy(&mut self, policy: AbacPolicy) {
        self.policies.push(policy);
        // Sort by priority (higher first)
        self.policies.sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    /// Check if user has permission (RBAC)
    pub fn has_permission(&self, user_id: &Uuid, permission: &Permission) -> bool {
        let user_permissions = self.get_user_permissions(user_id);
        user_permissions
            .iter()
            .any(|p| p == permission || permission.matches(p))
    }

    /// Check if access is allowed (RBAC + ABAC)
    pub fn is_access_allowed(
        &self,
        user_id: &Uuid,
        permission: &Permission,
        attributes: &HashMap<String, String>,
    ) -> bool {
        // First, check RBAC
        if self.has_permission(user_id, permission) {
            return true;
        }

        // Then, check ABAC policies
        for policy in &self.policies {
            if policy.allows(permission, attributes) {
                return true;
            }
        }

        false
    }

    /// Get all roles
    pub fn get_all_roles(&self) -> Vec<&Role> {
        self.roles.values().collect()
    }

    /// Get user's roles
    pub fn get_user_roles(&self, user_id: &Uuid) -> Vec<&Role> {
        if let Some(user_roles) = self.user_roles.get(user_id) {
            user_roles
                .role_ids
                .iter()
                .filter_map(|role_id| self.roles.get(role_id))
                .collect()
        } else {
            Vec::new()
        }
    }
}

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

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

    #[test]
    fn test_permission_creation() {
        let perm = Permission::new("token", "create");
        assert_eq!(perm.resource, "token");
        assert_eq!(perm.action, "create");
    }

    #[test]
    fn test_permission_from_string() {
        let perm = Permission::from_string("order:read").unwrap();
        assert_eq!(perm.resource, "order");
        assert_eq!(perm.action, "read");
    }

    #[test]
    fn test_permission_matches_wildcard() {
        let perm = Permission::new("token", "create");
        let wildcard = Permission::new("*", "create");

        assert!(perm.matches(&wildcard));
    }

    #[test]
    fn test_role_permissions() {
        let mut role = Role::new("admin");
        role.add_permission(Permission::new("token", "create"));
        role.add_permission(Permission::new("order", "read"));

        assert_eq!(role.permissions.len(), 2);
        assert!(role.has_permission(&Permission::new("token", "create")));
    }

    #[test]
    fn test_user_role_assignment() {
        let mut user_roles = UserRoles::new(Uuid::new_v4());
        let role_id = Uuid::new_v4();

        user_roles.assign_role(role_id);
        assert_eq!(user_roles.role_ids.len(), 1);

        user_roles.revoke_role(&role_id);
        assert_eq!(user_roles.role_ids.len(), 0);
    }

    #[test]
    fn test_attribute_condition() {
        let condition = PolicyCondition::AttributeEquals {
            key: "department".to_string(),
            value: "engineering".to_string(),
        };

        let mut attributes = HashMap::new();
        attributes.insert("department".to_string(), "engineering".to_string());

        assert!(condition.evaluate(&attributes));

        attributes.insert("department".to_string(), "sales".to_string());
        assert!(!condition.evaluate(&attributes));
    }

    #[test]
    fn test_time_window_condition() {
        let condition = PolicyCondition::TimeWindow {
            start_hour: 0,
            end_hour: 24,
        };

        let attributes = HashMap::new();
        assert!(condition.evaluate(&attributes));
    }

    #[test]
    fn test_and_condition() {
        let condition = PolicyCondition::And(vec![
            PolicyCondition::AttributeEquals {
                key: "role".to_string(),
                value: "admin".to_string(),
            },
            PolicyCondition::AttributeEquals {
                key: "department".to_string(),
                value: "it".to_string(),
            },
        ]);

        let mut attributes = HashMap::new();
        attributes.insert("role".to_string(), "admin".to_string());
        attributes.insert("department".to_string(), "it".to_string());

        assert!(condition.evaluate(&attributes));
    }

    #[test]
    fn test_abac_policy() {
        let mut policy = AbacPolicy::new("engineering_only", "token", "create");
        policy.add_condition(PolicyCondition::AttributeEquals {
            key: "department".to_string(),
            value: "engineering".to_string(),
        });

        let mut attributes = HashMap::new();
        attributes.insert("department".to_string(), "engineering".to_string());

        assert!(policy.allows(&Permission::new("token", "create"), &attributes));

        attributes.insert("department".to_string(), "sales".to_string());
        assert!(!policy.allows(&Permission::new("token", "create"), &attributes));
    }

    #[test]
    fn test_access_control_manager_rbac() {
        let mut manager = AccessControlManager::new();

        let mut role = Role::new("trader");
        role.add_permission(Permission::new("order", "create"));
        let role_id = role.id;

        manager.add_role(role);

        let user_id = Uuid::new_v4();
        manager.assign_role_to_user(user_id, role_id).unwrap();

        assert!(manager.has_permission(&user_id, &Permission::new("order", "create")));
        assert!(!manager.has_permission(&user_id, &Permission::new("order", "delete")));
    }

    #[test]
    fn test_access_control_manager_abac() {
        let mut manager = AccessControlManager::new();

        let mut policy = AbacPolicy::new("vip_only", "token", "mint");
        policy.add_condition(PolicyCondition::AttributeEquals {
            key: "tier".to_string(),
            value: "vip".to_string(),
        });

        manager.add_policy(policy);

        let user_id = Uuid::new_v4();
        let mut attributes = HashMap::new();
        attributes.insert("tier".to_string(), "vip".to_string());

        assert!(manager.is_access_allowed(
            &user_id,
            &Permission::new("token", "mint"),
            &attributes
        ));

        attributes.insert("tier".to_string(), "basic".to_string());
        assert!(!manager.is_access_allowed(
            &user_id,
            &Permission::new("token", "mint"),
            &attributes
        ));
    }

    #[test]
    fn test_role_inheritance() {
        let mut manager = AccessControlManager::new();

        // Create parent role
        let mut parent_role = Role::new("user");
        parent_role.add_permission(Permission::new("order", "read"));
        let parent_id = parent_role.id;
        manager.add_role(parent_role);

        // Create child role with inheritance
        let mut child_role = Role::new("admin");
        child_role.add_permission(Permission::new("order", "create"));
        child_role.add_parent(parent_id);
        let child_id = child_role.id;
        manager.add_role(child_role);

        let user_id = Uuid::new_v4();
        manager.assign_role_to_user(user_id, child_id).unwrap();

        // Should have both permissions
        assert!(manager.has_permission(&user_id, &Permission::new("order", "read")));
        assert!(manager.has_permission(&user_id, &Permission::new("order", "create")));
    }
}