nizaam-core 1.0.1

Domain-agnostic Rust infrastructure core for building secure, observable, reliable, and extensible Nizaam engines.
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
//! Security middleware for Nizaam Core.
//!
//! This module connects the provider-neutral authentication and authorization
//! boundaries to the generic middleware system.
//!
//! The middleware:
//!
//! 1. obtains opaque authentication material through a caller-supplied
//!    credential extractor;
//! 2. authenticates that material into a trusted `PrincipalIdentity`;
//! 3. establishes a request-scoped `SecurityContext` on the existing
//!    `EngineContext`;
//! 4. identifies the requested capability from the existing Core request
//!    descriptor;
//! 5. performs generic Core authorization;
//! 6. continues only when authentication and authorization succeed.
//!
//! Provider-specific credential formats and engine/domain-specific
//! authorization remain outside this module.

use crate::{contracts::UniversalRequest, runtime::EngineContext};

use super::{
    authentication::{AuthenticationError, AuthenticationRequest, Authenticator},
    authorization::{AuthorizationDecision, AuthorizationError, AuthorizationRequest, Authorizer},
    context::SecurityContext,
};

use crate::middleware::stages::{
    Middleware, MiddlewareError, MiddlewareRejection, MiddlewareResult,
};

/// Extracts opaque authentication material from an incoming request.
///
/// The extractor is intentionally separate from `Authenticator`.
///
/// The extractor is responsible only for obtaining authentication material.
/// The authenticator is responsible for interpreting and validating that
/// material.
///
/// This separation keeps transport-specific credential extraction outside
/// Core security policy.
pub trait CredentialExtractor: Send + Sync {
    /// Returns authentication material for the supplied request.
    ///
    /// `None` means that no authentication material was available.
    fn extract(&self, context: &EngineContext, request: &UniversalRequest) -> Option<Vec<u8>>;
}

/// Security middleware that performs authentication and generic authorization.
///
/// The middleware is provider-neutral:
///
/// ```text
/// UniversalRequest
///        ↓
/// CredentialExtractor
///        ↓
/// opaque credentials
///        ↓
/// Authenticator
///        ↓
/// PrincipalIdentity
///        ↓
/// SecurityContext
///        ↓
/// AuthorizationRequest
///        ↓
/// Authorizer
///        ↓
/// Continue / Reject / Fail
/// ```
///
/// The middleware does not perform capability resolution or dispatch.
pub struct SecurityMiddleware<A, Z, C> {
    authenticator: A,
    authorizer: Z,
    credential_extractor: C,
}

impl<A, Z, C> SecurityMiddleware<A, Z, C>
where
    A: Authenticator,
    Z: Authorizer,
    C: CredentialExtractor,
{
    /// Creates security middleware from its authentication, authorization,
    /// and credential-extraction components.
    pub fn new(authenticator: A, authorizer: Z, credential_extractor: C) -> Self {
        Self {
            authenticator,
            authorizer,
            credential_extractor,
        }
    }

    /// Returns a reference to the configured authenticator.
    pub fn authenticator(&self) -> &A {
        &self.authenticator
    }

    /// Returns a reference to the configured authorizer.
    pub fn authorizer(&self) -> &Z {
        &self.authorizer
    }

    /// Returns a reference to the configured credential extractor.
    pub fn credential_extractor(&self) -> &C {
        &self.credential_extractor
    }
}

impl<A, Z, C> std::fmt::Debug for SecurityMiddleware<A, Z, C>
where
    A: Authenticator,
    Z: Authorizer,
    C: CredentialExtractor,
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SecurityMiddleware")
            .finish_non_exhaustive()
    }
}

impl<A, Z, C> Middleware for SecurityMiddleware<A, Z, C>
where
    A: Authenticator,
    Z: Authorizer,
    C: CredentialExtractor,
{
    fn on_request(
        &self,
        context: &mut EngineContext,
        request: &mut UniversalRequest,
    ) -> MiddlewareResult {
        /*
         * Authentication material is deliberately extracted by a separate
         * provider-neutral component. Core does not interpret transport
         * headers, JWTs, API keys, certificates, or any other credential
         * format here.
         */
        let credentials = match self.credential_extractor.extract(context, request) {
            Some(credentials) if !credentials.is_empty() => credentials,

            None => {
                return MiddlewareResult::Reject(MiddlewareRejection::new(
                    "authentication credentials are required",
                ));
            }

            Some(_) => {
                return MiddlewareResult::Reject(MiddlewareRejection::new(
                    "authentication credentials are required",
                ));
            }
        };

        /*
         * The authentication input is borrowed only for the duration of the
         * authentication operation. It is never placed into SecurityContext.
         */
        let authentication_request = AuthenticationRequest::new(&credentials);

        let principal = match self.authenticator.authenticate(&authentication_request) {
            Ok(principal) => principal,

            Err(AuthenticationError::MissingCredentials) => {
                return MiddlewareResult::Reject(MiddlewareRejection::new(
                    "authentication credentials are required",
                ));
            }

            Err(AuthenticationError::InvalidCredentials) => {
                return MiddlewareResult::Reject(MiddlewareRejection::new(
                    "authentication credentials are invalid",
                ));
            }

            Err(AuthenticationError::Failed) => {
                return MiddlewareResult::Fail(MiddlewareError::new("authentication failed"));
            }
        };

        /*
         * Preserve an already-established trusted calling-service identity
         * when the current request context contains one.
         *
         * We intentionally do not infer calling-service identity from the
         * request payload or arbitrary transport metadata.
         */
        let calling_service = context
            .security()
            .and_then(SecurityContext::calling_service)
            .cloned();

        let security_context = SecurityContext::new(principal, calling_service);

        /*
         * EngineContext::with_security already provides the existing Core
         * context replacement mechanism. We replace the current request's
         * context with the enriched context rather than creating a second
         * competing request context.
         */
        *context = context.clone().with_security(security_context);

        /*
         * Capability identification uses the Core contract descriptor.
         * No engine-specific payload interpretation occurs here.
         */
        let capability_id = &request.event.envelope.metadata.descriptor.capability_id;

        let security = context
            .security()
            .expect("security context must be established after authentication");

        let authorization_request = AuthorizationRequest::new(
            security.principal(),
            security.calling_service(),
            capability_id,
        );

        match self.authorizer.authorize(&authorization_request) {
            Ok(AuthorizationDecision::Allow) => MiddlewareResult::Continue,

            Ok(AuthorizationDecision::Deny) => {
                MiddlewareResult::Reject(MiddlewareRejection::new("authorization denied"))
            }

            Err(AuthorizationError::Failed) => {
                MiddlewareResult::Fail(MiddlewareError::new("authorization failed"))
            }
        }
    }
}

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

    use crate::{
        contracts::{
            UniversalRequest,
            descriptor::{
                ContractDescriptor, EncodedPayload, Interaction, PayloadDescriptor, Version,
            },
            envelope::MessageEnvelope,
            metadata::{ContractMetadata, Participants},
        },
        identity::{CapabilityId, ContractId, CorrelationId, EngineId, MessageId, OperationId},
        middleware::stages::{Middleware, MiddlewareError, MiddlewareRejection, MiddlewareResult},
        operation::{Operation, OperationContext},
        runtime::EngineContext,
        security::{PrincipalId, PrincipalIdentity, PrincipalType},
    };

    fn context() -> EngineContext {
        EngineContext::new(OperationContext::new(Operation::new(
            OperationId::new("security-middleware-operation").unwrap(),
            CorrelationId::new("security-middleware-correlation").unwrap(),
        )))
    }

    fn request_with_capability(capability: &str) -> UniversalRequest {
        let descriptor = ContractDescriptor::new(
            ContractId::new("security.middleware.contract").unwrap(),
            CapabilityId::new(capability).unwrap(),
            Version::new(1, 0, 0),
            Interaction::Request,
            PayloadDescriptor::new("application/octet-stream", Version::new(1, 0, 0)).unwrap(),
        );

        let metadata = ContractMetadata::new(
            descriptor.clone(),
            Participants::new(
                EngineId::new("security-middleware-sender").unwrap(),
                EngineId::new("security-middleware-receiver").unwrap(),
            ),
        );

        let operation_context = OperationContext::new(Operation::new(
            OperationId::new("security-middleware-operation").unwrap(),
            CorrelationId::new("security-middleware-correlation").unwrap(),
        ));

        UniversalRequest::new(MessageEnvelope::new(
            MessageId::new("security-middleware-request").unwrap(),
            operation_context,
            metadata,
            EncodedPayload::new(descriptor.payload, b"opaque domain payload"),
        ))
    }

    fn user_identity() -> PrincipalIdentity {
        PrincipalIdentity::new(PrincipalType::User, PrincipalId::new("user-123").unwrap())
    }

    fn service_identity() -> PrincipalIdentity {
        PrincipalIdentity::new(
            PrincipalType::Service,
            PrincipalId::new("gateway-1").unwrap(),
        )
    }

    #[derive(Clone, Copy, Debug)]
    struct StaticCredentials {
        credentials: Option<&'static [u8]>,
    }

    impl CredentialExtractor for StaticCredentials {
        fn extract(
            &self,
            _context: &EngineContext,
            _request: &UniversalRequest,
        ) -> Option<Vec<u8>> {
            self.credentials.map(ToOwned::to_owned)
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct UserAuthenticator;

    impl Authenticator for UserAuthenticator {
        fn authenticate(
            &self,
            request: &AuthenticationRequest<'_>,
        ) -> Result<PrincipalIdentity, AuthenticationError> {
            match request.credentials() {
                b"user-token" => Ok(user_identity()),

                b"" => Err(AuthenticationError::MissingCredentials),

                _ => Err(AuthenticationError::InvalidCredentials),
            }
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct AllowAllAuthorizer;

    impl Authorizer for AllowAllAuthorizer {
        fn authorize(
            &self,
            _request: &AuthorizationRequest<'_>,
        ) -> Result<AuthorizationDecision, AuthorizationError> {
            Ok(AuthorizationDecision::Allow)
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct DenyAllAuthorizer;

    impl Authorizer for DenyAllAuthorizer {
        fn authorize(
            &self,
            _request: &AuthorizationRequest<'_>,
        ) -> Result<AuthorizationDecision, AuthorizationError> {
            Ok(AuthorizationDecision::Deny)
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct FailingAuthenticator;

    impl Authenticator for FailingAuthenticator {
        fn authenticate(
            &self,
            _request: &AuthenticationRequest<'_>,
        ) -> Result<PrincipalIdentity, AuthenticationError> {
            Err(AuthenticationError::Failed)
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct FailingAuthorizer;

    impl Authorizer for FailingAuthorizer {
        fn authorize(
            &self,
            _request: &AuthorizationRequest<'_>,
        ) -> Result<AuthorizationDecision, AuthorizationError> {
            Err(AuthorizationError::Failed)
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct ServiceAuthenticator;

    impl Authenticator for ServiceAuthenticator {
        fn authenticate(
            &self,
            request: &AuthenticationRequest<'_>,
        ) -> Result<PrincipalIdentity, AuthenticationError> {
            if request.credentials() == b"service-token" {
                Ok(service_identity())
            } else {
                Err(AuthenticationError::InvalidCredentials)
            }
        }
    }

    #[test]
    fn security_middleware_authenticates_and_continues() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(result, MiddlewareResult::Continue);

        assert_eq!(
            context
                .security()
                .expect("security context must be established after authentication")
                .principal(),
            &user_identity()
        );
    }

    #[test]
    fn authentication_establishes_security_context_on_same_engine_context() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let original_operation = context.operation().operation.id.clone();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(result, MiddlewareResult::Continue);

        assert_eq!(context.operation().operation.id, original_operation);

        assert_eq!(
            context
                .security()
                .expect("security context must be established after authentication")
                .principal(),
            &user_identity()
        );
    }

    #[test]
    fn calling_service_identity_is_preserved() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let calling_service = service_identity();

        let security_context = SecurityContext::new(user_identity(), Some(calling_service.clone()));

        let mut context = context().with_security(security_context);

        let mut request = request_with_capability("quran.read");

        /*
         * Authentication replaces the principal while preserving the already
         * trusted calling service from the current Core context.
         */
        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(result, MiddlewareResult::Continue);

        assert_eq!(
            context
                .security()
                .expect("security context must be established after authentication")
                .calling_service(),
            Some(&calling_service)
        );

        assert_eq!(
            context
                .security()
                .expect("security context must be established after authentication")
                .principal(),
            &user_identity()
        );
    }

    #[test]
    fn missing_credentials_are_rejected() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials { credentials: None },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Reject(MiddlewareRejection::new(
                "authentication credentials are required",
            ),)
        );
    }

    #[test]
    fn invalid_credentials_are_rejected() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"invalid-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Reject(MiddlewareRejection::new(
                "authentication credentials are invalid",
            ),)
        );
    }

    #[test]
    fn empty_credentials_are_rejected() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b""),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Reject(MiddlewareRejection::new(
                "authentication credentials are required",
            ),)
        );
    }

    #[test]
    fn authentication_failure_is_middleware_failure() {
        let middleware = SecurityMiddleware::new(
            FailingAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Fail(MiddlewareError::new("authentication failed",),)
        );
    }

    #[test]
    fn authorization_allow_continues_processing() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        assert_eq!(
            middleware.on_request(&mut context, &mut request,),
            MiddlewareResult::Continue
        );
    }

    #[test]
    fn authorization_deny_rejects_processing() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            DenyAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Reject(MiddlewareRejection::new("authorization denied",),)
        );
    }

    #[test]
    fn authorization_failure_is_middleware_failure() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            FailingAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(
            result,
            MiddlewareResult::Fail(MiddlewareError::new("authorization failed",),)
        );
    }

    #[test]
    fn authorization_receives_capability_identifier_without_payload_interpretation() {
        #[derive(Clone, Copy, Debug)]
        struct CapabilityCheckingAuthorizer;

        impl Authorizer for CapabilityCheckingAuthorizer {
            fn authorize(
                &self,
                request: &AuthorizationRequest<'_>,
            ) -> Result<AuthorizationDecision, AuthorizationError> {
                assert_eq!(request.capability().as_str(), "quran.read");

                Ok(AuthorizationDecision::Allow)
            }
        }

        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            CapabilityCheckingAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        assert_eq!(
            middleware.on_request(&mut context, &mut request,),
            MiddlewareResult::Continue
        );
    }

    #[test]
    fn service_principal_can_be_authenticated() {
        let middleware = SecurityMiddleware::new(
            ServiceAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"service-token"),
            },
        );

        let mut context = context();

        let mut request = request_with_capability("quran.read");

        let result = middleware.on_request(&mut context, &mut request);

        assert_eq!(result, MiddlewareResult::Continue);

        assert_eq!(
            context
                .security()
                .expect("security context must be established after authentication")
                .principal()
                .principal_type(),
            PrincipalType::Service
        );
    }

    #[test]
    fn security_middleware_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}

        assert_send_sync::<
            SecurityMiddleware<UserAuthenticator, AllowAllAuthorizer, StaticCredentials>,
        >();
    }

    #[test]
    fn security_middleware_debug_does_not_require_debug_components() {
        let middleware = SecurityMiddleware::new(
            UserAuthenticator,
            AllowAllAuthorizer,
            StaticCredentials {
                credentials: Some(b"user-token"),
            },
        );

        let debug = format!("{middleware:?}");

        assert!(debug.contains("SecurityMiddleware"));
    }
}