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
// 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.

//! ACL-based authorization handler implementation.
//!
//! This module implements Access Control List (ACL) authorization as part of the
//! authorization chain. It evaluates incoming requests against stored ACL policies
//! and makes allow/deny decisions based on:
//! - Resource matching (topic, group, cluster)
//! - Action matching (PUB, SUB, CREATE, etc.)
//! - Environment matching (source IP, etc.)
//! - Policy priority (CUSTOM > DEFAULT, DENY > ALLOW, LITERAL > PREFIXED)

use std::cmp::Ordering;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use rocketmq_security_api::AuthorizationDecision;
use rocketmq_security_api::AuthorizationDenial;
use rocketmq_security_api::ResourcePattern;
use rocketmq_security_api::ResourceType;

use super::handler::AuthorizationHandler;
use crate::authorization::context::default_authorization_context::DefaultAuthorizationContext;
use crate::authorization::enums::decision::Decision;
use crate::authorization::enums::policy_type::PolicyType;
#[cfg(test)]
use crate::authorization::metadata_provider::AuthorizationMetadataProvider;
use crate::authorization::model::acl::Acl;
use crate::authorization::model::environment::Environment;
use crate::authorization::model::policy::Policy;
use crate::authorization::model::policy_entry::PolicyEntry;
use crate::AclMetadataRead;
use crate::AuthServiceError;
use crate::AuthServiceResult;
use crate::SubjectKey;

/// ACL Authorization Handler.
///
/// This handler performs ACL-based authorization by:
/// 1. Loading the subject's ACL from the metadata provider
/// 2. Matching policy entries against the request context
/// 3. Evaluating the decision (ALLOW/DENY) based on priority
///
/// # Priority Rules
///
/// Policies are evaluated in this priority order:
/// 1. **Resource Type**: Specific types (Topic, Group) > ANY
/// 2. **Resource Pattern**: LITERAL > PREFIXED > ANY
/// 3. **Resource Name Length**: Longer prefixes > shorter (for PREFIXED pattern)
/// 4. **Decision**: DENY > ALLOW (deny takes precedence)
pub struct AclAuthorizationHandler<P: AclMetadataRead + ?Sized> {
    /// Provider for fetching ACL metadata
    metadata_provider: Arc<P>,
}

impl<P: AclMetadataRead + ?Sized> AclAuthorizationHandler<P> {
    /// Create a new ACL authorization handler.
    ///
    /// # Arguments
    ///
    /// * `metadata_provider` - Provider for retrieving ACL data
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use rocketmq_auth::AclAuthorizationHandler;
    /// use rocketmq_auth::LocalAuthorizationMetadataProvider;
    /// use std::sync::Arc;
    ///
    /// let provider = Arc::new(LocalAuthorizationMetadataProvider::new());
    /// let handler = AclAuthorizationHandler::new(provider);
    /// ```
    pub fn new(metadata_provider: Arc<P>) -> Self {
        Self { metadata_provider }
    }

    /// Match policy entries from an ACL against the authorization context.
    ///
    /// This method:
    /// 1. Tries CUSTOM policies first
    /// 2. Falls back to DEFAULT policies if no CUSTOM match
    /// 3. Sorts matched entries by priority
    /// 4. Returns the highest-priority entry
    async fn match_policy_entries(&self, context: &DefaultAuthorizationContext, acl: &Acl) -> Option<PolicyEntry> {
        let mut matched_entries = Vec::new();

        // Step 1: Try CUSTOM policies first. ACLs normally contain one policy
        // per type, but admin or provider inputs may contain duplicates; all
        // matching entries must be considered before DENY/ALLOW priority sorting.
        for policy in acl
            .policies()
            .iter()
            .filter(|policy| policy.policy_type() == PolicyType::Custom)
        {
            if let Some(mut entries) = self.match_policy_entries_from_policy(context, policy) {
                matched_entries.append(&mut entries);
            }
        }

        // Step 2: If no CUSTOM matches, try DEFAULT policies
        if matched_entries.is_empty() {
            for policy in acl
                .policies()
                .iter()
                .filter(|policy| policy.policy_type() == PolicyType::Default)
            {
                if let Some(mut entries) = self.match_policy_entries_from_policy(context, policy) {
                    matched_entries.append(&mut entries);
                }
            }
        }

        // Step 3: No matches found
        if matched_entries.is_empty() {
            return None;
        }

        // Step 4: Sort by priority and return the first (highest priority)
        matched_entries.sort_by(|a, b| self.compare_policy_entries(a, b));

        // Return first element (highest priority)
        matched_entries.into_iter().next()
    }

    /// Match policy entries from a specific policy against the context.
    ///
    /// Filters entries that match:
    /// - Resource (type, name, pattern)
    /// - Actions (must include at least one requested action)
    /// - Environment (source IP, etc.)
    ///
    /// # Java Mapping
    ///
    /// Maps to `matchPolicyEntries(DefaultAuthorizationContext, List<PolicyEntry>)`
    fn match_policy_entries_from_policy(
        &self,
        context: &DefaultAuthorizationContext,
        policy: &Policy,
    ) -> Option<Vec<PolicyEntry>> {
        let entries = policy.entries();
        if entries.is_empty() {
            return None;
        }

        let resource_binding = context.resource();
        let resource = resource_binding.as_ref()?;
        let actions = context.actions();
        let source_ip_binding = context.source_ip();
        let source_ip = source_ip_binding.unwrap_or("");
        let environment = Environment::of(source_ip).unwrap_or_default();

        let matched: Vec<PolicyEntry> = entries
            .iter()
            .filter(|entry| entry.is_match_resource(resource))
            .filter(|entry| entry.is_match_action(actions))
            .filter(|entry| entry.is_match_environment(&environment))
            .cloned()
            .collect();

        if matched.is_empty() {
            None
        } else {
            Some(matched)
        }
    }

    /// Compare two policy entries for priority sorting.
    ///
    /// Priority rules (in order):
    /// 1. Resource Type: Specific (Topic, Group, Cluster) > ANY
    /// 2. Resource Pattern: LITERAL > PREFIXED > ANY
    /// 3. For PREFIXED: Longer prefix > Shorter prefix
    /// 4. Decision: DENY > ALLOW
    ///
    /// Returns:
    /// - `Ordering::Less` if o1 has higher priority
    /// - `Ordering::Greater` if o2 has higher priority
    /// - `Ordering::Equal` if same priority
    fn compare_policy_entries(&self, o1: &PolicyEntry, o2: &PolicyEntry) -> Ordering {
        let r1 = o1.resource();
        let r2 = o2.resource();

        // Step 1: Compare resource types
        if r1.resource_type != r2.resource_type {
            // ANY has lowest priority
            if r1.resource_type == ResourceType::Any {
                return Ordering::Greater; // o1 has lower priority
            }
            if r2.resource_type == ResourceType::Any {
                return Ordering::Less; // o1 has higher priority
            }
        }

        // Step 2: Compare resource patterns
        if r1.resource_pattern != r2.resource_pattern {
            return match (r1.resource_pattern, r2.resource_pattern) {
                (ResourcePattern::Literal, _) => Ordering::Less, // LITERAL has highest priority
                (_, ResourcePattern::Literal) => Ordering::Greater,
                (ResourcePattern::Prefixed, ResourcePattern::Any) => Ordering::Less,
                (ResourcePattern::Any, ResourcePattern::Prefixed) => Ordering::Greater,
                _ => Ordering::Equal,
            };
        }

        // Step 3: For PREFIXED pattern, compare prefix lengths (longer = higher priority)
        if r1.resource_pattern == ResourcePattern::Prefixed {
            if let (Some(name1), Some(name2)) = (&r1.resource_name, &r2.resource_name) {
                let cmp = name2.len().cmp(&name1.len()); // Reverse: longer name has higher priority
                if cmp != Ordering::Equal {
                    return cmp;
                }
            }
        }

        // Step 4: Compare decisions (DENY > ALLOW)
        let d1 = o1.decision();
        let d2 = o2.decision();
        if d1 != d2 {
            return if d1 == Decision::Deny {
                Ordering::Less // o1 (DENY) has higher priority
            } else {
                Ordering::Greater // o2 (DENY) has higher priority
            };
        }

        Ordering::Equal
    }
}

impl<P: AclMetadataRead + ?Sized + 'static> AuthorizationHandler for AclAuthorizationHandler<P> {
    fn handle<'a>(
        &'a self,
        context: &'a DefaultAuthorizationContext,
    ) -> Pin<Box<dyn Future<Output = AuthServiceResult<AuthorizationDecision>> + Send + 'a>> {
        Box::pin(async move {
            // Step 1: Extract subject from context
            let subject_binding = context.subject();
            let subject_wrapper = subject_binding
                .as_ref()
                .ok_or_else(|| AuthServiceError::invalid_context("subject is missing".to_owned()))?;

            let subject = SubjectKey::new(subject_wrapper.subject_type(), subject_wrapper.subject_key());

            // Step 2: Fetch ACL from metadata provider
            let acl = self.metadata_provider.lookup_acl(&subject).await?;
            let Some(acl) = acl else {
                return Ok(AuthorizationDecision::Deny(AuthorizationDenial::SubjectUnknown));
            };

            // Step 3: Match policy entries
            let Some(matched_entry) = self.match_policy_entries(context, &acl).await else {
                return Ok(AuthorizationDecision::Deny(AuthorizationDenial::PolicyNotApplicable));
            };

            // Step 4: Check decision
            if matched_entry.decision() == Decision::Deny {
                return Ok(AuthorizationDecision::Deny(AuthorizationDenial::PermissionDenied));
            }

            // Step 5: Authorization granted
            Ok(AuthorizationDecision::Allow)
        })
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use rocketmq_security_api::Action;
    use rocketmq_security_api::ResourcePattern;
    use rocketmq_security_api::ResourceType;

    use super::*;
    use crate::authentication::enums::subject_type::SubjectType;
    use crate::authentication::model::user::User;
    use crate::authorization::context::default_authorization_context::DefaultAuthorizationContext;
    use crate::authorization::metadata_provider::local::LocalAuthorizationMetadataProvider;
    use crate::authorization::model::policy::Policy;
    use crate::authorization::model::resource::Resource;
    use crate::config::AuthConfig;

    #[tokio::test]
    async fn test_acl_authorization_handler_allow() {
        // Create a local metadata provider
        let mut provider = LocalAuthorizationMetadataProvider::new();
        provider.initialize(AuthConfig::default(), None).unwrap();
        let provider = Arc::new(provider);

        // Create ACL for user "alice" with ALLOW on topic "test-topic"
        let user = User::of("alice");
        let resource = Resource::of_topic("test-topic");
        let policy = Policy::of(vec![resource.clone()], vec![Action::Pub], None, Decision::Allow);
        let acl = Acl::of_subject_and_policy(&user, policy);

        // Store ACL
        provider.create_acl(acl).await.unwrap();

        // Create handler
        let handler = AclAuthorizationHandler::new(provider);

        // Create authorization context
        let context = DefaultAuthorizationContext::of("alice", SubjectType::User, resource, Action::Pub, "127.0.0.1");

        // Test authorization - should succeed
        let result = handler.handle(&context).await;
        assert_eq!(result.unwrap(), AuthorizationDecision::Allow);
    }

    #[tokio::test]
    async fn test_acl_authorization_handler_deny() {
        let mut provider = LocalAuthorizationMetadataProvider::new();
        provider.initialize(AuthConfig::default(), None).unwrap();
        let provider = Arc::new(provider);

        // Create ACL with DENY decision
        let user = User::of("bob");
        let resource = Resource::of_topic("forbidden-topic");
        let policy = Policy::of(vec![resource.clone()], vec![Action::Pub], None, Decision::Deny);
        let acl = Acl::of_subject_and_policy(&user, policy);

        provider.create_acl(acl).await.unwrap();

        let handler = AclAuthorizationHandler::new(provider);

        let context = DefaultAuthorizationContext::of("bob", SubjectType::User, resource, Action::Pub, "192.168.1.1");

        // An explicit policy denial is a normal decision, not an error.
        let result = handler.handle(&context).await;
        assert_eq!(
            result.unwrap(),
            AuthorizationDecision::Deny(AuthorizationDenial::PermissionDenied)
        );
    }

    #[tokio::test]
    async fn test_acl_authorization_handler_no_acl() {
        let mut provider = LocalAuthorizationMetadataProvider::new();
        provider.initialize(AuthConfig::default(), None).unwrap();
        let provider = Arc::new(provider);
        let handler = AclAuthorizationHandler::new(provider);

        let resource = Resource::of_topic("test-topic");
        let context = DefaultAuthorizationContext::of("charlie", SubjectType::User, resource, Action::Pub, "10.0.0.1");

        // A missing ACL is a closed, typed denial.
        let result = handler.handle(&context).await;
        assert_eq!(
            result.unwrap(),
            AuthorizationDecision::Deny(AuthorizationDenial::SubjectUnknown)
        );
    }

    #[tokio::test]
    async fn test_acl_authorization_handler_no_matching_policy() {
        let mut provider = LocalAuthorizationMetadataProvider::new();
        provider.initialize(AuthConfig::default(), None).unwrap();
        let provider = Arc::new(provider);

        // Create ACL for topic "topic-a" but request accesses "topic-b"
        let user = User::of("dave");
        let allowed_resource = Resource::of_topic("topic-a");
        let policy = Policy::of(vec![allowed_resource], vec![Action::Pub], None, Decision::Allow);
        let acl = Acl::of_subject_and_policy(&user, policy);

        provider.create_acl(acl).await.unwrap();

        let handler = AclAuthorizationHandler::new(provider);

        let requested_resource = Resource::of_topic("topic-b");
        let context =
            DefaultAuthorizationContext::of("dave", SubjectType::User, requested_resource, Action::Pub, "172.16.0.1");

        // The subject is known, but no policy applies to this request.
        let result = handler.handle(&context).await;
        assert_eq!(
            result.unwrap(),
            AuthorizationDecision::Deny(AuthorizationDenial::PolicyNotApplicable)
        );
    }

    #[test]
    fn test_compare_policy_entries_resource_type() {
        let provider = Arc::new(LocalAuthorizationMetadataProvider::new());
        let handler = AclAuthorizationHandler::new(provider);

        let topic_entry = PolicyEntry::of(
            Resource::of(ResourceType::Topic, Some("t1".to_string()), ResourcePattern::Literal),
            vec![Action::Pub],
            None,
            Decision::Allow,
        );

        let any_entry = PolicyEntry::of(
            Resource::of(ResourceType::Any, None, ResourcePattern::Any),
            vec![Action::Pub],
            None,
            Decision::Allow,
        );

        // Topic should have higher priority than ANY
        assert_eq!(handler.compare_policy_entries(&topic_entry, &any_entry), Ordering::Less);
        assert_eq!(
            handler.compare_policy_entries(&any_entry, &topic_entry),
            Ordering::Greater
        );
    }

    #[test]
    fn test_compare_policy_entries_resource_pattern() {
        let provider = Arc::new(LocalAuthorizationMetadataProvider::new());
        let handler = AclAuthorizationHandler::new(provider);

        let literal = PolicyEntry::of(
            Resource::of(ResourceType::Topic, Some("test".to_string()), ResourcePattern::Literal),
            vec![Action::Pub],
            None,
            Decision::Allow,
        );

        let prefixed = PolicyEntry::of(
            Resource::of(ResourceType::Topic, Some("test".to_string()), ResourcePattern::Prefixed),
            vec![Action::Pub],
            None,
            Decision::Allow,
        );

        // LITERAL > PREFIXED
        assert_eq!(handler.compare_policy_entries(&literal, &prefixed), Ordering::Less);
    }

    #[test]
    fn test_compare_policy_entries_decision() {
        let provider = Arc::new(LocalAuthorizationMetadataProvider::new());
        let handler = AclAuthorizationHandler::new(provider);

        let deny = PolicyEntry::of(
            Resource::of(ResourceType::Topic, Some("t1".to_string()), ResourcePattern::Literal),
            vec![Action::Pub],
            None,
            Decision::Deny,
        );

        let allow = PolicyEntry::of(
            Resource::of(ResourceType::Topic, Some("t1".to_string()), ResourcePattern::Literal),
            vec![Action::Pub],
            None,
            Decision::Allow,
        );

        // DENY > ALLOW
        assert_eq!(handler.compare_policy_entries(&deny, &allow), Ordering::Less);
    }
}