rocketmq-auth 1.0.0

Unofficial Rust implementation of Apache RocketMQ
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
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Authorization metadata provider abstraction.
//!
//! This module provides the core trait for managing authorization metadata (ACLs)
//! in RocketMQ. Implementations can store metadata in various backends such as:
//! - Local files (YAML, JSON)
//! - Embedded databases (RocksDB, SQLite)
//! - Remote databases (MySQL, PostgreSQL)
//! - Distributed configuration services (etcd, Consul)

// Sub-modules
pub mod local;

use std::any::Any;

// Re-export commonly used types
pub use local::LocalAuthorizationMetadataProvider;

use crate::authentication::model::subject::Subject;
use crate::authorization::model::acl::Acl;
use crate::config::AuthConfig;
use crate::AuthServiceResult;

/// Authorization metadata provider trait.
///
/// This trait defines the interface for managing Access Control List (ACL) metadata
/// in RocketMQ's authorization system. It provides CRUD operations for ACLs and
/// supports querying and filtering metadata.
///
/// # Design Principles
///
/// - **Async-first**: All I/O operations are async to support scalable implementations
/// - **Flexible storage**: Implementations can use any backend (files, databases, remote services)
/// - **Query support**: Built-in filtering capabilities for listing ACLs
/// - **Error handling**: Comprehensive error reporting through `AuthServiceError`
///
/// # Thread Safety
///
/// Implementations must be `Send + Sync` to support concurrent access from multiple
/// RocketMQ components (broker, namesrv, proxy).
///
/// # Examples
///
/// ```rust,ignore
/// use rocketmq_auth::{AuthorizationMetadataProvider, AuthServiceResult};
/// use rocketmq_auth::Acl;
/// use rocketmq_auth::Subject;
/// use rocketmq_auth::AuthConfig;
///
/// struct MyMetadataProvider {
///     // Storage implementation
/// }
///
/// impl AuthorizationMetadataProvider for MyMetadataProvider {
///     fn initialize(
///         &mut self,
///         config: AuthConfig,
///         metadata_service: Option<Box<dyn Any + Send + Sync>>,
///     ) -> AuthServiceResult<()> {
///         // Initialize storage backend
///         Ok(())
///     }
///
///     async fn create_acl(&self, acl: Acl) -> AuthServiceResult<()> {
///         // Store ACL in backend
///         Ok(())
///     }
///
///     async fn get_acl<S: Subject>(&self, subject: &S) -> AuthServiceResult<Option<Acl>> {
///         // Retrieve ACL from backend
///         Ok(None)
///     }
///
///     // ... implement other methods
/// }
/// ```
#[allow(async_fn_in_trait)]
pub trait AuthorizationMetadataProvider: Send + Sync {
    /// Initialize the metadata provider with configuration.
    ///
    /// This method is called once during provider setup. Implementations should:
    /// - Initialize storage backend (open database, connect to remote service, etc.)
    /// - Load initial configuration and validate parameters
    /// - Set up caching layers if needed
    /// - Establish connection pools or prepare resources
    ///
    /// # Arguments
    ///
    /// * `config` - Authorization configuration containing provider-specific settings
    /// * `metadata_service` - Optional metadata service for advanced integration scenarios. Can be
    ///   downcast to implementation-specific types if needed.
    ///
    /// # Errors
    ///
    /// Returns `AuthFailureKind::InvalidConfiguration` if:
    /// - Configuration parameters are invalid
    /// - Storage backend cannot be initialized
    /// - Required resources are unavailable
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut provider = MyMetadataProvider::new();
    /// provider.initialize(auth_config, None)?;
    /// ```
    fn initialize(
        &mut self,
        config: AuthConfig,
        metadata_service: Option<Box<dyn Any + Send + Sync>>,
    ) -> AuthServiceResult<()>;

    /// Shutdown the metadata provider and release resources.
    ///
    /// This method should:
    /// - Close database connections
    /// - Flush pending writes
    /// - Release file handles
    /// - Cleanup temporary resources
    ///
    /// Implementations should be idempotent (safe to call multiple times).
    fn shutdown(&mut self);

    /// Create a new ACL for a subject.
    ///
    /// If an ACL already exists for the subject, implementations should return an error.
    /// Use `update_acl` to modify existing ACLs.
    ///
    /// # Arguments
    ///
    /// * `acl` - The ACL to create, containing subject information and policies
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::InvalidInput` if ACL already exists
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    /// - `AuthFailureKind::InvalidInput` if ACL data is malformed
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let acl = Acl::of("user:alice", SubjectType::User, policy);
    /// provider.create_acl(acl).await?;
    /// ```
    async fn create_acl(&self, acl: Acl) -> AuthServiceResult<()>;

    /// Delete an ACL for a subject.
    ///
    /// If the ACL does not exist, implementations should not return an error
    /// (idempotent operation).
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject whose ACL should be deleted
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let user = User::new("alice");
    /// provider.delete_acl(&user).await?;
    /// ```
    async fn delete_acl<S: Subject + Send + Sync>(&self, subject: &S) -> AuthServiceResult<()>;

    /// Update an existing ACL.
    ///
    /// This operation completely replaces the existing ACL. To perform partial updates,
    /// implementations should first retrieve the ACL, modify it, then call this method.
    ///
    /// # Arguments
    ///
    /// * `acl` - The updated ACL data
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::NotFound` if ACL doesn't exist
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    /// - `AuthFailureKind::InvalidInput` if ACL data is malformed
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut acl = provider.get_acl(&user).await?.unwrap();
    /// acl.add_policy(new_policy);
    /// provider.update_acl(acl).await?;
    /// ```
    async fn update_acl(&self, acl: Acl) -> AuthServiceResult<()>;

    /// Get the ACL for a specific subject.
    ///
    /// Returns `None` if no ACL exists for the subject.
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject to query
    ///
    /// # Returns
    ///
    /// - `Ok(Some(Acl))` if ACL exists
    /// - `Ok(None)` if no ACL found
    /// - `Err(...)` if operation fails
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let user = User::new("alice");
    /// if let Some(acl) = provider.get_acl(&user).await? {
    ///     println!("ACL found: {:?}", acl);
    /// }
    /// ```
    fn get_acl<S: Subject + Send + Sync>(
        &self,
        subject: &S,
    ) -> impl std::future::Future<Output = AuthServiceResult<Option<Acl>>> + Send;

    /// List ACLs with optional filtering.
    ///
    /// This method supports filtering by subject name pattern and resource pattern.
    /// Both filters are optional and use substring matching.
    ///
    /// # Arguments
    ///
    /// * `subject_filter` - Optional subject name filter (substring match)
    /// * `resource_filter` - Optional resource name filter (substring match)
    ///
    /// # Returns
    ///
    /// A vector of matching ACLs. Empty vector if no matches found.
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // List all ACLs
    /// let all_acls = provider.list_acl(None, None).await?;
    ///
    /// // Filter by subject
    /// let user_acls = provider.list_acl(Some("user:"), None).await?;
    ///
    /// // Filter by resource
    /// let topic_acls = provider.list_acl(None, Some("Topic:test")).await?;
    ///
    /// // Both filters
    /// let filtered = provider.list_acl(Some("user:alice"), Some("Topic:")).await?;
    /// ```
    async fn list_acl(
        &self,
        subject_filter: Option<&str>,
        resource_filter: Option<&str>,
    ) -> AuthServiceResult<Vec<Acl>>;
}

/// No-op authorization metadata provider for testing and disabled scenarios.
///
/// This provider accepts all operations but maintains no state. Useful for:
/// - Testing authorization logic without persistence
/// - Disabling authorization in development environments
/// - Placeholder implementations during development
#[derive(Debug, Default)]
pub struct NoopMetadataProvider;

impl NoopMetadataProvider {
    /// Create a new no-op metadata provider.
    pub fn new() -> Self {
        Self
    }
}

impl AuthorizationMetadataProvider for NoopMetadataProvider {
    fn initialize(
        &mut self,
        _config: AuthConfig,
        _metadata_service: Option<Box<dyn Any + Send + Sync>>,
    ) -> AuthServiceResult<()> {
        Ok(())
    }

    fn shutdown(&mut self) {
        // No resources to clean up
    }

    async fn create_acl(&self, _acl: Acl) -> AuthServiceResult<()> {
        Ok(())
    }

    async fn delete_acl<S: Subject + Send + Sync>(&self, _subject: &S) -> AuthServiceResult<()> {
        Ok(())
    }

    async fn update_acl(&self, _acl: Acl) -> AuthServiceResult<()> {
        Ok(())
    }

    async fn get_acl<S: Subject + Send + Sync>(&self, _subject: &S) -> AuthServiceResult<Option<Acl>> {
        Ok(None)
    }

    async fn list_acl(
        &self,
        _subject_filter: Option<&str>,
        _resource_filter: Option<&str>,
    ) -> AuthServiceResult<Vec<Acl>> {
        Ok(Vec::new())
    }
}

#[cfg(test)]
mod tests {
    use rocketmq_security_api::Action;

    use super::*;
    use crate::authentication::enums::subject_type::SubjectType;
    use crate::authentication::model::user::User;
    use crate::authorization::enums::decision::Decision;
    use crate::authorization::enums::policy_type::PolicyType;
    use crate::authorization::model::environment::Environment;
    use crate::authorization::model::policy::Policy;
    use crate::authorization::model::policy_entry::PolicyEntry;
    use crate::authorization::model::resource::Resource;

    #[tokio::test]
    async fn test_noop_provider_initialization() {
        let mut provider = NoopMetadataProvider::new();
        let config = AuthConfig::default();

        let result = provider.initialize(config, None);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_noop_provider_create_acl() {
        let provider = NoopMetadataProvider::new();

        let resource = Resource::of_topic("test-topic");
        let entry = PolicyEntry::of(
            resource,
            vec![Action::Pub],
            Environment::of("192.168.1.1"),
            Decision::Allow,
        );
        let policy = Policy::of_entries(PolicyType::Custom, vec![entry]);
        let acl = Acl::of("user:test", SubjectType::User, policy);

        let result = provider.create_acl(acl).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_noop_provider_get_acl_returns_none() {
        let provider = NoopMetadataProvider::new();
        let user = User::of("test");

        let result = provider.get_acl(&user).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_noop_provider_list_acl_returns_empty() {
        let provider = NoopMetadataProvider::new();

        let result = provider.list_acl(None, None).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_noop_provider_update_acl() {
        let provider = NoopMetadataProvider::new();

        let resource = Resource::of_topic("test-topic");
        let entry = PolicyEntry::of(
            resource,
            vec![Action::Pub],
            Environment::of("192.168.1.1"),
            Decision::Allow,
        );
        let policy = Policy::of_entries(PolicyType::Custom, vec![entry]);
        let acl = Acl::of("user:test", SubjectType::User, policy);

        let result = provider.update_acl(acl).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_noop_provider_delete_acl() {
        let provider = NoopMetadataProvider::new();
        let user = User::of("test");

        let result = provider.delete_acl(&user).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_noop_provider_shutdown() {
        let mut provider = NoopMetadataProvider::new();
        provider.shutdown();
        // Should not panic or cause issues
    }

    #[tokio::test]
    async fn test_noop_provider_list_with_filters() {
        let provider = NoopMetadataProvider::new();

        let result = provider.list_acl(Some("user:test"), Some("Topic:test")).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }
}