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
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
// 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 manager implementation.
//!
//! This module provides the `AuthorizationMetadataManager`, which coordinates
//! authorization and authentication metadata providers to manage ACL (Access Control List)
//! operations in RocketMQ's authorization system.
//!
//! # Architecture
//!
//! The manager acts as a facade that:
//! - Validates subjects exist before ACL operations (via `AuthenticationMetadataProvider`)
//! - Performs ACL validation and initialization
//! - Delegates storage operations to `AuthorizationMetadataProvider`
//! - Provides a unified, type-safe API for ACL management
//!
//! # Design Principles
//!
//! 1. **Two-Provider Coordination**: Authentication provider validates subject existence,
//!    authorization provider handles ACL persistence
//! 2. **Validation-First**: All ACL mutations are validated before storage
//! 3. **Async-First**: All I/O operations are async
//! 4. **Error Transparency**: Errors from underlying providers are propagated clearly
//!
//! # Thread Safety
//!
//! The manager can be safely shared across threads. Provider instances must implement
//! `Send + Sync`.

use std::sync::Arc;

use tracing::debug;

use crate::authentication::enums::subject_type::SubjectType;
use crate::authentication::model::subject::Subject;
use crate::authentication::provider::AuthenticationMetadataProvider;
use crate::authorization::enums::policy_type::PolicyType;
use crate::authorization::metadata_provider::local::LocalAuthorizationMetadataProvider;
use crate::authorization::model::acl::Acl;
use crate::authorization::model::policy::Policy;
use crate::authorization::model::policy_entry::PolicyEntry;
use crate::authorization::model::resource::Resource;
use crate::config::AuthConfig;
use crate::AuthFailureKind;
use crate::AuthServiceError;
use crate::AuthServiceResult;
use crate::ProviderRegistry;

/// Authorization metadata manager.
///
/// This struct manages ACL (Access Control List) operations by coordinating
/// two metadata providers:
/// - `AuthorizationMetadataProvider`: Persists ACL data
/// - `AuthenticationMetadataProvider`: Validates USER subject existence
///
/// # Examples
///
/// ```rust,ignore
/// use rocketmq_auth::AuthorizationMetadataManager;
/// use rocketmq_auth::AuthConfig;
///
/// // Create manager with configuration
/// let config = AuthConfig::default();
/// let manager = AuthorizationMetadataManager::new(config)?;
///
/// // Create ACL for a user
/// let acl = Acl::of("user:alice", SubjectType::User, policy);
/// manager.create_acl(acl).await?;
///
/// // Retrieve ACL
/// let user = User::of("alice");
/// if let Some(acl) = manager.get_acl(&user).await? {
///     println!("ACL found: {:?}", acl);
/// }
///
/// // Shutdown
/// manager.shutdown().await;
/// ```
pub struct AuthorizationMetadataManager {
    /// Authorization metadata provider for ACL persistence
    authorization_provider: Arc<crate::AclMetadataHandle>,

    /// Authentication metadata provider for USER subject validation
    authentication_provider: Option<Arc<dyn crate::UserMetadataRead>>,
    owned_registry: Option<ProviderRegistry>,
}

impl AuthorizationMetadataManager {
    /// Create a new manager with the given providers.
    ///
    /// # Arguments
    ///
    /// * `authorization_provider` - Provider for ACL storage operations
    /// * `authentication_provider` - Optional provider for subject validation
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let auth_provider = Arc::new(LocalAuthorizationMetadataProvider::new(...));
    /// let manager = AuthorizationMetadataManager::with_providers(
    ///     auth_provider,
    ///     None
    /// );
    /// ```
    pub fn with_providers(
        authorization_provider: Arc<LocalAuthorizationMetadataProvider>,
        authentication_provider: Option<Arc<dyn AuthenticationMetadataProvider>>,
    ) -> Self {
        Self {
            authorization_provider: crate::AclMetadataHandle::legacy(authorization_provider),
            authentication_provider: authentication_provider.map(|port| {
                Arc::new(crate::provider_ports::LegacyUserReader(port)) as Arc<dyn crate::UserMetadataRead>
            }),
            owned_registry: None,
        }
    }

    pub fn with_registry(registry: &ProviderRegistry) -> Self {
        Self {
            authorization_provider: registry.authorization_metadata_provider(),
            authentication_provider: Some(registry.authentication_metadata_provider()),
            owned_registry: None,
        }
    }

    /// Create a manager from configuration.
    ///
    /// This will instantiate providers based on the configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Authorization configuration
    ///
    /// # Errors
    ///
    /// Returns `AuthFailureKind::InvalidConfiguration` if provider initialization fails
    pub fn new(config: AuthConfig) -> AuthServiceResult<Self> {
        let registry = ProviderRegistry::local(&config).map_err(|error| {
            AuthServiceError::with_source(
                crate::AuthOperation::Initialize,
                crate::AuthFailureKind::InvalidConfiguration,
                error,
            )
        })?;
        let mut manager = Self::with_registry(&registry);
        manager.owned_registry = Some(registry);
        Ok(manager)
    }

    /// Shutdown the manager and release resources.
    ///
    /// Managers created from configuration close their providers. Managers
    /// borrowing a registry leave provider finalization to its runtime owner.
    pub async fn shutdown(&mut self) {
        if let Err(error) = self
            .shutdown_until(rocketmq_runtime::ShutdownDeadline::after(
                std::time::Duration::from_secs(5),
            ))
            .await
        {
            tracing::warn!(?error, "authorization metadata manager shutdown incomplete");
        }
    }

    pub async fn shutdown_until(&self, deadline: rocketmq_runtime::ShutdownDeadline) -> AuthServiceResult<()> {
        match &self.owned_registry {
            Some(registry) => registry.shutdown_until(deadline).await,
            None => Ok(()),
        }
    }

    /// Create a new ACL.
    ///
    /// This method:
    /// 1. Validates the ACL structure
    /// 2. Initializes default policy types
    /// 3. Verifies the subject exists (if authentication provider is available)
    /// 4. Checks if ACL already exists
    /// 5. Creates or updates the ACL
    ///
    /// # Arguments
    ///
    /// * `acl` - The ACL to create
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::NotFound` if subject doesn't exist
    /// - `AuthFailureKind::InvalidInput` if ACL validation fails
    /// - `AuthFailureKind::InvalidInput` if ACL already exists (and merge fails)
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let acl = Acl::of("user:alice", SubjectType::User, policy);
    /// manager.create_acl(acl).await?;
    /// ```
    pub async fn create_acl(&self, mut acl: Acl) -> AuthServiceResult<()> {
        // 1. Validate ACL
        self.validate_acl(&acl)?;

        // 2. Initialize default policy types
        Self::init_acl(&mut acl);

        // 3. Verify subject exists (for USER type)
        self.verify_subject_exists(&acl).await?;

        // 4. Check if ACL already exists and merge if needed
        let subject_key = acl.subject_key();
        let subject_type = acl.subject_type();

        match self
            .authorization_provider
            .get_acl(&UserSubjectWrapper {
                key: subject_key.to_string(),
                subject_type,
            })
            .await?
        {
            None => {
                // No existing ACL, create new one
                debug!("Creating new ACL for subject: {}", subject_key);
                self.authorization_provider.create_acl(acl).await
            }
            Some(mut old_acl) => {
                // ACL exists, update policies
                debug!("ACL already exists for subject {}, updating policies", subject_key);
                old_acl.update_policies(acl.policies().clone());
                self.authorization_provider.update_acl(old_acl).await
            }
        }
    }

    /// Update an existing ACL.
    ///
    /// This method:
    /// 1. Validates the ACL structure
    /// 2. Initializes default policy types
    /// 3. Verifies the subject exists
    /// 4. Creates the ACL if it doesn't exist, or merges with existing ACL
    ///
    /// # Arguments
    ///
    /// * `acl` - The ACL with updated policies
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::NotFound` if subject doesn't exist
    /// - `AuthFailureKind::InvalidInput` if ACL validation fails
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut acl = manager.get_acl(&user).await?.unwrap();
    /// acl.add_policy(new_policy);
    /// manager.update_acl(acl).await?;
    /// ```
    pub async fn update_acl(&self, mut acl: Acl) -> AuthServiceResult<()> {
        // 1. Validate ACL
        self.validate_acl(&acl)?;

        // 2. Initialize default policy types
        Self::init_acl(&mut acl);

        // 3. Verify subject exists
        self.verify_subject_exists(&acl).await?;

        // 4. Get existing ACL and merge or create
        let subject_key = acl.subject_key();
        let subject_type = acl.subject_type();

        match self
            .authorization_provider
            .get_acl(&UserSubjectWrapper {
                key: subject_key.to_string(),
                subject_type,
            })
            .await?
        {
            None => {
                // No existing ACL, create new one
                debug!("No existing ACL for subject {}, creating new", subject_key);
                self.authorization_provider.create_acl(acl).await
            }
            Some(mut old_acl) => {
                // Merge policies
                debug!("Updating existing ACL for subject: {}", subject_key);
                old_acl.update_policies(acl.policies().clone());
                self.authorization_provider.update_acl(old_acl).await
            }
        }
    }

    /// Delete an ACL for a subject.
    ///
    /// This is a convenience method that calls `delete_acl_with_filter` with no filters.
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject whose ACL should be deleted
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::NotFound` if subject doesn't exist
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    pub async fn delete_acl<S: Subject + Send + Sync>(&self, subject: &S) -> AuthServiceResult<()> {
        self.delete_acl_with_filter(subject, None, None).await
    }

    /// Delete an ACL or specific policy entries.
    ///
    /// This method provides fine-grained deletion:
    /// - If `resource` is specified: deletes specific policy entry for that resource
    /// - If only `policy_type` is specified: deletes entire policy of that type
    /// - If neither specified: deletes entire ACL
    ///
    /// # Arguments
    ///
    /// * `subject` - The subject whose ACL to modify
    /// * `policy_type` - Optional policy type filter (defaults to CUSTOM if resource specified)
    /// * `resource` - Optional resource to delete from the policy
    ///
    /// # Errors
    ///
    /// - `AuthFailureKind::NotFound` if subject doesn't exist
    /// - `AuthFailureKind::InvalidInput` if ACL doesn't exist
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Delete entire ACL
    /// manager.delete_acl_with_filter(&user, None, None).await?;
    ///
    /// // Delete a specific policy type
    /// manager.delete_acl_with_filter(&user, Some(PolicyType::CUSTOM), None).await?;
    ///
    /// // Delete specific resource from policy
    /// let resource = Resource::of_topic("test-topic");
    /// manager.delete_acl_with_filter(&user, Some(PolicyType::CUSTOM), Some(&resource)).await?;
    /// ```
    pub async fn delete_acl_with_filter<S: Subject + Send + Sync>(
        &self,
        subject: &S,
        policy_type: Option<PolicyType>,
        resource: Option<&Resource>,
    ) -> AuthServiceResult<()> {
        // 1. Verify subject exists
        self.verify_subject_by_ref(subject).await?;

        // 2. Default policy type to CUSTOM if not specified
        let policy_type = policy_type.unwrap_or(PolicyType::Custom);

        // 3. Get existing ACL
        let mut acl = self.authorization_provider.get_acl(subject).await?.ok_or_else(|| {
            AuthServiceError::invalid_context(format!(
                "The ACL for subject '{}' does not exist",
                subject.subject_key()
            ))
        })?;

        // 4. Delete policy entry or entire ACL
        if let Some(resource) = resource {
            // Delete specific resource from policy
            debug!(
                "Deleting resource {:?} from {:?} policy for subject {}",
                resource,
                policy_type,
                subject.subject_key()
            );
            acl.delete_policy(policy_type, resource);

            if acl.policies().is_empty() {
                // No policies left, delete entire ACL
                self.authorization_provider.delete_acl(subject).await
            } else {
                // Update ACL with remaining policies
                self.authorization_provider.update_acl(acl).await
            }
        } else {
            // Delete entire ACL
            debug!("Deleting entire ACL for subject: {}", subject.subject_key());
            self.authorization_provider.delete_acl(subject).await
        }
    }

    /// Get the ACL for a 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::NotFound` if subject doesn't exist
    /// - `AuthFailureKind::Unavailable` if
    ///   storage operation fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let user = User::of("alice");
    /// if let Some(acl) = manager.get_acl(&user).await? {
    ///     println!("Found ACL with {} policies", acl.policies().len());
    /// }
    /// ```
    pub async fn get_acl<S: Subject + Send + Sync>(&self, subject: &S) -> AuthServiceResult<Option<Acl>> {
        // 1. Verify subject exists
        self.verify_subject_by_ref(subject).await?;

        // 2. Get ACL from provider
        self.authorization_provider.get_acl(subject).await
    }

    /// List ACLs with optional filtering.
    ///
    /// # 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 = manager.list_acl(None, None).await?;
    ///
    /// // Filter by subject
    /// let user_acls = manager.list_acl(Some("user:"), None).await?;
    ///
    /// // Filter by resource
    /// let topic_acls = manager.list_acl(None, Some("Topic:test")).await?;
    /// ```
    pub async fn list_acl(
        &self,
        subject_filter: Option<&str>,
        resource_filter: Option<&str>,
    ) -> AuthServiceResult<Vec<Acl>> {
        self.authorization_provider
            .list_acl(subject_filter, resource_filter)
            .await
    }

    // ========== Private Helper Methods ==========

    /// Initialize ACL defaults.
    ///
    /// Rust policies always carry an explicit `PolicyType`; no mutation is needed here.
    fn init_acl(_acl: &mut Acl) {}

    /// Validate ACL structure.
    ///
    /// Checks:
    /// - Subject type is not None/Unknown
    /// - Policies list is not empty
    /// - Each policy is valid
    fn validate_acl(&self, acl: &Acl) -> AuthServiceResult<()> {
        // Validate subject type (currently only User is valid)
        // SubjectType doesn't have Unknown variant, so validation is simplified

        // Validate policies exist
        if acl.policies().is_empty() {
            return Err(AuthServiceError::invalid_context(
                "The policies list is empty".to_string(),
            ));
        }

        // Validate each policy
        for policy in acl.policies() {
            self.validate_policy(policy)?;
        }

        Ok(())
    }

    /// Validate policy structure.
    ///
    /// Checks:
    /// - Policy entries list is not empty
    /// - Each entry is valid
    fn validate_policy(&self, policy: &Policy) -> AuthServiceResult<()> {
        // Validate entries exist
        if policy.entries().is_empty() {
            return Err(AuthServiceError::invalid_context(
                "Policy entries list is empty".to_string(),
            ));
        }

        // Validate each entry
        for entry in policy.entries() {
            self.validate_policy_entry(entry)?;
        }

        Ok(())
    }

    /// Validate policy entry structure.
    ///
    /// Checks:
    /// - Resources list is not empty
    /// - Actions list is not empty
    fn validate_policy_entry(&self, entry: &PolicyEntry) -> AuthServiceResult<()> {
        // PolicyEntry has a single resource (not a list)
        // Validate actions list is not empty
        if entry.actions().is_empty() {
            return Err(AuthServiceError::invalid_context(
                "PolicyEntry actions list is empty".to_string(),
            ));
        }

        Ok(())
    }

    /// Verify that the subject exists in the authentication system.
    ///
    /// For USER subjects, checks with authentication provider (when available).
    /// For other subject types, assumes existence.
    async fn verify_subject_exists(&self, acl: &Acl) -> AuthServiceResult<()> {
        if acl.subject_type() == SubjectType::User {
            self.verify_user_subject_key(acl.subject_key()).await?;
        }
        Ok(())
    }

    /// Verify that a subject exists by reference.
    ///
    /// Similar to verify_subject_exists but works with Subject trait references.
    async fn verify_subject_by_ref<S: Subject + Send + Sync>(&self, subject: &S) -> AuthServiceResult<()> {
        if subject.subject_type() == SubjectType::User {
            self.verify_user_subject_key(subject.subject_key()).await?;
        }
        Ok(())
    }

    async fn verify_user_subject_key(&self, subject_key: &str) -> AuthServiceResult<()> {
        let provider = self.authentication_provider.as_ref().ok_or_else(|| {
            AuthServiceError::not_initialized("The authenticationMetadataProvider is not configured.")
        })?;
        let username = subject_key
            .split_once(':')
            .map(|(_, username)| username)
            .unwrap_or(subject_key)
            .trim();
        if username.is_empty() {
            return Err(AuthServiceError::subject_not_found(subject_key));
        }

        match provider.lookup_user(username).await {
            Ok(_) => Ok(()),
            Err(error) if error.kind() == AuthFailureKind::NotFound => Err(AuthServiceError::subject_not_found(
                format!("The subject of {subject_key} is not exist."),
            )),
            Err(error) => Err(AuthServiceError::storage_read_failed(error)),
        }
    }
}

/// Wrapper struct to implement Subject trait for get_acl operations.
///
/// This is needed because we need to pass subject information to the provider's
/// get_acl method which expects a type implementing the Subject trait.
struct UserSubjectWrapper {
    key: String,
    subject_type: SubjectType,
}

impl Subject for UserSubjectWrapper {
    fn subject_key(&self) -> &str {
        &self.key
    }

    fn subject_type(&self) -> SubjectType {
        self.subject_type
    }
}