mecha10-core 0.6.2

Mecha10 core runtime and foundational types
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
//! Authorization and Access Control
//!
//! Provides role-based access control (RBAC) for pub/sub topics.
//! Enables controlling which nodes can publish/subscribe to specific topics.
//!
//! # Architecture
//!
//! - Simple role-based permissions
//! - Wildcard pattern matching for topics
//! - Policies stored in Redis
//! - Optional enforcement (can be disabled for development)
//!
//! # Example
//!
//! ```rust
//! use mecha10::prelude::*;
//! use mecha10::auth::{AuthExt, Policy, Permission};
//!
//! # async fn example(ctx: &Context) -> Result<()> {
//! // Define a policy
//! let policy = Policy::new("camera_driver")
//!     .allow(Permission::Publish, "/sensors/camera/*")
//!     .allow(Permission::Subscribe, "/control/camera/*");
//!
//! ctx.register_policy(&policy).await?;
//!
//! // Assign role to node
//! ctx.assign_role("camera-1", "camera_driver").await?;
//!
//! // Check permission (automatically done in pub/sub)
//! let allowed = ctx.check_permission(
//!     "camera-1",
//!     Permission::Publish,
//!     "/sensors/camera/rgb"
//! ).await?;
//!
//! # Ok(())
//! # }
//! ```

use crate::context::Context;
use crate::enum_str_method;
use crate::error::{Mecha10Error, Result};
use serde::{Deserialize, Serialize};

/// Permission type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Permission {
    /// Permission to publish to a topic
    Publish,
    /// Permission to subscribe to a topic
    Subscribe,
}

enum_str_method!(
    #[allow(dead_code)]
    fn as_str(Permission) -> &str {
        Publish => "publish",
        Subscribe => "subscribe",
    }
);

/// Access control rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Permission type
    pub permission: Permission,

    /// Topic pattern (supports wildcards: /sensors/*)
    pub topic_pattern: String,
}

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

    /// Check if a topic matches this rule's pattern
    pub fn matches(&self, topic: &str) -> bool {
        matches_pattern(&self.topic_pattern, topic)
    }
}

/// Policy defining permissions for a role
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Policy {
    /// Role name
    pub role: String,

    /// Access control rules
    pub rules: Vec<Rule>,

    /// Policy description
    #[serde(default)]
    pub description: String,
}

impl Policy {
    /// Create a new policy for a role
    pub fn new(role: impl Into<String>) -> Self {
        Self {
            role: role.into(),
            rules: Vec::new(),
            description: String::new(),
        }
    }

    /// Set description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Add a permission rule
    pub fn allow(mut self, permission: Permission, topic_pattern: impl Into<String>) -> Self {
        self.rules.push(Rule::new(permission, topic_pattern));
        self
    }

    /// Add publish permission
    pub fn allow_publish(self, topic_pattern: impl Into<String>) -> Self {
        self.allow(Permission::Publish, topic_pattern)
    }

    /// Add subscribe permission
    pub fn allow_subscribe(self, topic_pattern: impl Into<String>) -> Self {
        self.allow(Permission::Subscribe, topic_pattern)
    }

    /// Check if this policy allows a specific action
    pub fn allows(&self, permission: Permission, topic: &str) -> bool {
        self.rules
            .iter()
            .any(|rule| rule.permission == permission && rule.matches(topic))
    }

    /// Get Redis key for this policy
    fn redis_key(&self) -> String {
        format!("mecha10:auth:policies:{}", self.role)
    }

    /// Get Redis key for policies list
    fn redis_list_key() -> String {
        "mecha10:auth:policies:list".to_string()
    }

    /// Get Redis key for node role assignment
    fn redis_role_key(node_id: &str) -> String {
        format!("mecha10:auth:roles:{}", node_id)
    }
}

/// Authorization extension trait for Context
pub trait AuthExt {
    /// Register a policy
    ///
    /// # Arguments
    ///
    /// * `policy` - Policy to register
    ///
    /// # Example
    ///
    /// ```rust
    /// use mecha10::prelude::*;
    /// use mecha10::auth::{AuthExt, Policy, Permission};
    ///
    /// # async fn example(ctx: &Context) -> Result<()> {
    /// let policy = Policy::new("camera_driver")
    ///     .allow_publish("/sensors/camera/*")
    ///     .allow_subscribe("/control/camera/*");
    ///
    /// ctx.register_policy(&policy).await?;
    /// # Ok(())
    /// # }
    /// ```
    fn register_policy(&self, policy: &Policy) -> impl std::future::Future<Output = Result<()>> + Send;

    /// Get a policy by role name
    ///
    /// # Arguments
    ///
    /// * `role` - Role name
    fn get_policy(&self, role: &str) -> impl std::future::Future<Output = Result<Option<Policy>>> + Send;

    /// List all registered policies
    fn list_policies(&self) -> impl std::future::Future<Output = Result<Vec<Policy>>> + Send;

    /// Assign a role to a node
    ///
    /// # Arguments
    ///
    /// * `node_id` - Node identifier
    /// * `role` - Role to assign
    fn assign_role(&self, node_id: &str, role: &str) -> impl std::future::Future<Output = Result<()>> + Send;

    /// Get the role assigned to a node
    ///
    /// # Arguments
    ///
    /// * `node_id` - Node identifier
    fn get_role(&self, node_id: &str) -> impl std::future::Future<Output = Result<Option<String>>> + Send;

    /// Check if a node has permission to perform an action on a topic
    ///
    /// # Arguments
    ///
    /// * `node_id` - Node identifier
    /// * `permission` - Permission type (Publish/Subscribe)
    /// * `topic` - Topic path
    ///
    /// # Returns
    ///
    /// `true` if permission is granted, `false` otherwise
    fn check_permission(
        &self,
        node_id: &str,
        permission: Permission,
        topic: &str,
    ) -> impl std::future::Future<Output = Result<bool>> + Send;

    /// Delete a policy
    ///
    /// # Arguments
    ///
    /// * `role` - Role name
    fn delete_policy(&self, role: &str) -> impl std::future::Future<Output = Result<()>> + Send;

    /// Remove role assignment from a node
    ///
    /// # Arguments
    ///
    /// * `node_id` - Node identifier
    fn unassign_role(&self, node_id: &str) -> impl std::future::Future<Output = Result<()>> + Send;
}

impl AuthExt for Context {
    async fn register_policy(&self, policy: &Policy) -> Result<()> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            // Serialize policy
            let policy_json = serde_json::to_string(&policy)
                .map_err(|e| Mecha10Error::Other(format!("Failed to serialize policy: {}", e)))?;

            // Store policy
            let key = policy.redis_key();
            conn.set::<_, _, ()>(&key, &policy_json)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to register policy: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            // Add to policies list
            let list_key = Policy::redis_list_key();
            conn.sadd::<_, _, ()>(&list_key, &policy.role)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to update policy list: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            Ok(())
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn get_policy(&self, role: &str) -> Result<Option<Policy>> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            let key = format!("mecha10:auth:policies:{}", role);
            let json: Option<String> = conn.get(&key).await.map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to get policy: {}", e),
                suggestion: "Check Redis connection".to_string(),
            })?;

            if let Some(json) = json {
                let policy = serde_json::from_str::<Policy>(&json)
                    .map_err(|e| Mecha10Error::Other(format!("Failed to parse policy: {}", e)))?;
                Ok(Some(policy))
            } else {
                Ok(None)
            }
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn list_policies(&self) -> Result<Vec<Policy>> {
        #[cfg(feature = "messaging")]
        {
            crate::redis_list_util::collect_from_redis_set(&Policy::redis_list_key(), |role| async move {
                self.get_policy(&role).await
            })
            .await
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn assign_role(&self, node_id: &str, role: &str) -> Result<()> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            let key = Policy::redis_role_key(node_id);
            conn.set::<_, _, ()>(&key, role)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to assign role: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            Ok(())
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn get_role(&self, node_id: &str) -> Result<Option<String>> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            let key = Policy::redis_role_key(node_id);
            let role: Option<String> = conn.get(&key).await.map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to get role: {}", e),
                suggestion: "Check Redis connection".to_string(),
            })?;

            Ok(role)
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn check_permission(&self, node_id: &str, permission: Permission, topic: &str) -> Result<bool> {
        // Get node's role
        let role = match self.get_role(node_id).await? {
            Some(role) => role,
            None => return Ok(false), // No role = no permissions
        };

        // Get policy for role
        let policy = match self.get_policy(&role).await? {
            Some(policy) => policy,
            None => return Ok(false), // No policy = no permissions
        };

        // Check if policy allows this action
        Ok(policy.allows(permission, topic))
    }

    async fn delete_policy(&self, role: &str) -> Result<()> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            // Delete policy
            let key = format!("mecha10:auth:policies:{}", role);
            conn.del::<_, ()>(&key)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to delete policy: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            // Remove from list
            let list_key = Policy::redis_list_key();
            conn.srem::<_, _, ()>(&list_key, role)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to update policy list: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            Ok(())
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }

    async fn unassign_role(&self, node_id: &str) -> Result<()> {
        #[cfg(feature = "messaging")]
        {
            use redis::AsyncCommands;

            let redis_url = Context::get_redis_url()?;
            let client = redis::Client::open(redis_url.as_str()).map_err(|e| Mecha10Error::MessagingError {
                message: format!("Failed to connect to Redis: {}", e),
                suggestion: "Ensure Redis is running".to_string(),
            })?;

            let mut conn =
                client
                    .get_multiplexed_async_connection()
                    .await
                    .map_err(|e| Mecha10Error::MessagingError {
                        message: format!("Failed to get Redis connection: {}", e),
                        suggestion: "Ensure Redis is running".to_string(),
                    })?;

            let key = Policy::redis_role_key(node_id);
            conn.del::<_, ()>(&key)
                .await
                .map_err(|e| Mecha10Error::MessagingError {
                    message: format!("Failed to unassign role: {}", e),
                    suggestion: "Check Redis connection".to_string(),
                })?;

            Ok(())
        }

        #[cfg(not(feature = "messaging"))]
        {
            Err(Mecha10Error::Other("Messaging feature not enabled".to_string()))
        }
    }
}

/// Check if a topic matches a pattern
///
/// Uses the same glob matching implementation as aggregated topics,
/// supporting full glob syntax including *, **, ?, [abc], {a,b}, etc.
///
/// # Examples
///
/// ```
/// # use mecha10_core::auth::matches_pattern;
/// assert!(matches_pattern("/sensors/*", "/sensors/camera"));
/// assert!(matches_pattern("/sensors/*/rgb", "/sensors/camera/rgb"));
/// assert!(!matches_pattern("/sensors/*", "/control/motor"));
///
/// // Advanced patterns
/// assert!(matches_pattern("/sensors/**", "/sensors/camera/left/rgb"));
/// assert!(matches_pattern("/sensors/camera?", "/sensors/camera1"));
/// assert!(matches_pattern("/sensors/{left,right}", "/sensors/left"));
/// ```
pub fn matches_pattern(pattern: &str, topic: &str) -> bool {
    // Use the centralized glob matching from aggregated module
    crate::aggregated::pattern::matches_pattern(topic, pattern)
}