cedarling 0.0.8

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

//! # Auth Engine
//! Part of Cedarling that main purpose is:
//! - evaluate if authorization is granted for *user*
//! - evaluate if authorization is granted for *client* / *workload *

use crate::TrustedIssuerLoadingInfo;
use crate::bootstrap_config::AuthorizationConfig;
use crate::common::default_entities::DefaultEntities;
use crate::common::policy_store::{PolicyStoreWithID, TrustedIssuer};
use crate::context_data_api::DataStore;
use crate::entity_builder::{BuiltEntitiesUnsigned, EntityBuilder};
use crate::jwt;
use crate::log::interface::LogWriter;
use crate::log::{
    AuthorizationLogInfo, AuthorizeInfo, BaseLogEntry, Decision, DecisionLogEntry, Diagnostics,
    DiagnosticsSummary, LogEntry, LogLevel, LogTokensInfo, Logger, PushedDataInfo, gen_uuid7,
};
use build_ctx::{build_context, build_multi_issuer_context};
use cedar_policy::{Entities, Entity, EntityUid};
use chrono::Utc;
use metrics::MetricsCollector;
use request::{AuthorizeMultiIssuerRequest, RequestUnsigned};
use serde_json::json;
use smol_str::SmolStr;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use std::sync::Arc;
use uuid7::Uuid;

mod authorize_result;
mod build_ctx;
mod error_metrics;
mod errors;
pub(crate) mod metrics;

pub(crate) mod request;

pub use authorize_result::{AuthorizeResult, MultiIssuerAuthorizeResult};
pub use errors::*;

/// Configuration to Authz to initialize service without errors
pub(crate) struct AuthzConfig {
    pub log_service: Logger,
    pub policy_store: PolicyStoreWithID,
    pub jwt_service: Arc<jwt::JwtService>,
    pub entity_builder: Arc<EntityBuilder>,
    pub authorization: AuthorizationConfig,
    /// Data store for pushed data that gets injected into context
    pub data_store: Arc<DataStore>,
    /// Shared metrics collector for telemetry
    pub metrics: Arc<MetricsCollector>,
}

/// Authorization Service
/// The primary service of the Cedarling application responsible for evaluating authorization requests.
/// It leverages other services as needed to complete its evaluations.
pub(super) struct Authz {
    config: AuthzConfig,
    authorizer: cedar_policy::Authorizer,
}

impl Authz {
    /// Create a new Authorization Service
    pub(crate) fn new(config: AuthzConfig) -> Self {
        config.log_service.log_any(
            LogEntry::new(BaseLogEntry::new_system_opt_request_id(
                LogLevel::INFO,
                None,
            ))
            .set_cedar_version()
            .set_message("Cedarling Authz initialized successfully".to_string()),
        );

        Self {
            config,
            authorizer: cedar_policy::Authorizer::new(),
        }
    }

    pub(crate) fn trusted_issuers(&self) -> Option<&HashMap<String, TrustedIssuer>> {
        self.config.policy_store.trusted_issuers.as_ref()
    }

    /// Clone the [`Arc`] wrapping the current [`jwt::JwtService`] for reuse across a refresh.
    pub(crate) fn clone_jwt_service(&self) -> Arc<jwt::JwtService> {
        Arc::clone(&self.config.jwt_service)
    }

    /// Get pushed data and build `PushedDataInfo` for logging.
    fn get_pushed_data(&self) -> (HashMap<String, serde_json::Value>, Option<PushedDataInfo>) {
        let pushed_data = self.config.data_store.get_all();
        let pushed_data_info = if pushed_data.is_empty() {
            None
        } else {
            // Use iterator chain - compiler optimizes this well
            Some(PushedDataInfo {
                keys: pushed_data
                    .keys()
                    .map(|k| SmolStr::from(k.as_str()))
                    .collect(),
            })
        };
        (pushed_data, pushed_data_info)
    }

    /// Evaluate Multi-Issuer Authorization Request
    ///
    /// This implementation processes multiple JWT tokens from different issuers.
    /// It validates the request format and JWT tokens, builds entities, and performs authorization evaluation.
    ///
    /// Unlike traditional authorization which uses workload/user principals, multi-issuer authorization
    /// evaluates policies based solely on the context (tokens) without requiring a principal.
    // This function orchestrates the full multi-issuer authorization flow. The complexity
    // is inherent to handling multiple token sources and splitting it would reduce readability.
    #[allow(clippy::too_many_lines)]
    pub(super) fn authorize_multi_issuer(
        &self,
        request: &AuthorizeMultiIssuerRequest,
    ) -> Result<MultiIssuerAuthorizeResult, AuthorizeError> {
        let start_time = Utc::now();
        let request_id = gen_uuid7();

        // Validate the request structure
        request.validate().inspect_err(|e| {
            self.config.metrics.record_error(e);
            self.config.metrics.record_authz_error();
        })?;

        let schema = &self.config.policy_store.schema;

        let validated_tokens = self
            .config
            .jwt_service
            .validate_multi_issuer_tokens(&request.tokens)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        let entities_data = self
            .config
            .entity_builder
            .build_multi_issuer_entities(
                &validated_tokens,
                &request.resource,
                self.config.log_service.as_ref(),
            )
            .map_err(|e| {
                self.config.metrics.record_error(&e);
                self.config.metrics.record_authz_error();
                AuthorizeError::MultiIssuerEntity(e)
            })?;

        let action = cedar_policy::EntityUid::from_str(request.action.as_str())
            .map_err(AuthorizeError::from)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        // Capture pushed data info for logging before context is built
        let (pushed_data, pushed_data_info) = self.get_pushed_data();

        let schema_ref = schema.as_ref().map(|s| &s.schema);

        let context = build_multi_issuer_context(
            request.context.clone().unwrap_or(json!({})),
            &entities_data.tokens,
            schema_ref,
            &action,
            pushed_data,
        )
        .inspect_err(|e| {
            self.config.metrics.record_error(e);
            self.config.metrics.record_authz_error();
        })?;

        let resource_uid = entities_data.resource.uid();

        let entities = entities_data
            .entities(schema_ref)
            .map_err(AuthorizeError::ValidateEntities)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        // Multi-issuer authorization does not use a principal
        // Authorization is based solely on the context (tokens)
        let authz_result = self
            .execute_authorize(ExecuteAuthorizeParameters {
                entities: &entities,
                principal: None,
                action: action.clone(),
                resource: resource_uid.clone(),
                context,
            })
            .map_err(AuthorizeError::RequestValidation)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        let authz_info = AuthorizeInfo {
            principal: "None (multi-issuer)".to_string(),
            diagnostics: Diagnostics::new(
                authz_result.diagnostics(),
                &self.config.policy_store.policies,
            ),
            decision: authz_result.decision().into(),
        };

        // measure time how long request executes, before the result clone so the
        // clone cost is excluded from the latency measurement
        let decision_time_micro_sec = calculate_elapsed_time(start_time);

        let result = MultiIssuerAuthorizeResult::new(authz_result.clone(), request_id);

        // FROM THIS POINT WE ONLY MAKE LOGS

        // Log policy evaluation errors if any exist
        self.log_policy_evaluation_errors(
            &authz_info.diagnostics,
            "multi-issuer (no principal)",
            request_id,
        );

        let tokens_logging_info = LogTokensInfo::new(
            &validated_tokens,
            self.config
                .authorization
                .decision_log_default_jwt_id
                .as_str(),
        );

        let multi_diagnostics = std::slice::from_ref(&authz_info.diagnostics);

        // Decision log
        // we log decision log before debug log, to avoid cloning diagnostic info
        self.log_decision(
            request_id,
            &DecisionLogMetadata {
                action: request.action.clone(),
                resource: resource_uid.to_string(),
                decision_diagnostics: multi_diagnostics,
                decision_time: decision_time_micro_sec,
                principal: DecisionLogEntry::principal(
                    false, // No person principal for multi-issuer
                    false, // No workload principal for multi-issuer
                ),
                tokens_logging_info,
                decision: result.decision,
                pushed_data: pushed_data_info,
            },
        );

        // DEBUG LOG
        // Log all result information about multi-issuer authorization
        let debug_log_fn = BaseLogEntry::new_system(LogLevel::DEBUG, request_id).with_fn(|base| {
            // usually debug log is disabled, so we build entities_json only when needed
            // error should newer happen here, because entities were built successfully before
            let entities_json: serde_json::Value = {
                // getting entities as json
                serialize_entities(&entities)
            };

            LogEntry::new(base)
                .set_auth_info(AuthorizationLogInfo {
                    action: request.action.clone(),
                    context: request.context.clone().unwrap_or(json!({})),
                    resource: resource_uid.to_string(),
                    entities: entities_json,
                    authorize_info: vec![authz_info.clone()],
                    authorized: result.decision,
                })
                .set_message("Result of multi-issuer authorize.".to_string())
        });
        self.config.log_service.log_fn(debug_log_fn);

        // Record metrics
        let decision = Decision::from(result.decision);
        let policy_decisions = multi_diagnostics
            .iter()
            .flat_map(|d| d.reason.iter())
            .map(|policy| (policy.id.as_str(), decision));

        self.config.metrics.record_evaluation(
            decision_time_micro_sec,
            decision,
            false,
            policy_decisions,
        );

        Ok(result)
    }

    /// Evaluate Authorization Request with unsigned data.
    // This function handles unsigned authorization flow with entity building,
    // authorization checks, and logging. The complexity is inherent to the workflow.
    #[allow(clippy::too_many_lines)]
    pub(super) fn authorize_unsigned(
        &self,
        request: &RequestUnsigned,
    ) -> Result<AuthorizeResult, AuthorizeError> {
        let start_time = Utc::now();
        // We use uuid v7 because it is generated based on the time and sortable.
        // and we need sortable ids to use it in the sparkv database.
        // Sparkv store data in BTree. So we need have correct order of ids.
        //
        // Request ID should be passed to each log entry for tracing in logs and to get log entities from memory logger
        let request_id = gen_uuid7();

        let schema = &self.config.policy_store.schema;
        let schema_ref = schema.as_ref().map(|s| &s.schema);
        // Parse action UID.
        let action = cedar_policy::EntityUid::from_str(request.action.as_str())
            .map_err(AuthorizeError::from)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        let BuiltEntitiesUnsigned {
            principal,
            resource,
            built_entities,
        } = self
            .config
            .entity_builder
            .build_entities_unsigned(request)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;
        let principal_uid = principal.as_ref().map(cedar_policy::Entity::uid);
        let resource_uid = resource.uid();

        // Capture pushed data info for logging before context is built
        let (pushed_data, pushed_data_info) = self.get_pushed_data();

        let context = build_context(
            &self.config,
            request.context.clone(),
            &built_entities,
            &action,
            pushed_data,
        )
        .inspect_err(|e| {
            self.config.metrics.record_error(e);
            self.config.metrics.record_authz_error();
        })?;

        let entities = Entities::from_entities(principal.into_iter().chain([resource]), schema_ref)
            .map_err(|e| AuthorizeError::ValidateEntities(Box::new(e)))
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        let response = self
            .execute_authorize(ExecuteAuthorizeParameters {
                entities: &entities,
                principal: principal_uid.clone(),
                action: action.clone(),
                resource: resource_uid.clone(),
                context,
            })
            .map_err(AuthorizeError::RequestValidation)
            .inspect_err(|e| {
                self.config.metrics.record_error(e);
                self.config.metrics.record_authz_error();
            })?;

        // measure time how long request executes, before the result clone so the
        // clone cost is excluded from the latency measurement
        let decision_time_micro_sec = calculate_elapsed_time(start_time);

        let result = AuthorizeResult::new(response.clone(), request_id);

        // FROM THIS POINT WE ONLY MAKE LOGS

        let principal_label = principal_uid
            .as_ref()
            .map_or_else(|| "None".to_string(), ToString::to_string);

        let authz_info = AuthorizeInfo {
            principal: principal_label,
            diagnostics: Diagnostics::new(
                response.diagnostics(),
                &self.config.policy_store.policies,
            ),
            decision: response.decision().into(),
        };

        let debug_authorize_info = vec![authz_info.clone()];
        let diagnostics = std::slice::from_ref(&authz_info.diagnostics);

        // Log policy evaluation errors if any exist
        self.log_policy_evaluation_errors(
            &authz_info.diagnostics,
            &authz_info.principal,
            request_id,
        );

        let logged_principals = principal_uid.as_slice();

        // Decision log
        // we log decision log before debug log, to avoid cloning diagnostic info
        self.log_decision(
            request_id,
            &DecisionLogMetadata {
                action: request.action.clone(),
                resource: resource_uid.to_string(),
                decision: result.decision,
                tokens_logging_info: LogTokensInfo::empty(),
                decision_time: decision_time_micro_sec,
                decision_diagnostics: diagnostics,
                principal: DecisionLogEntry::all_principals(logged_principals),
                pushed_data: pushed_data_info,
            },
        );

        // DEBUG LOG
        // Log all result information about both authorize checks.
        // Where principal is `"Jans::Workload"` and where principal is `"Jans::User"`.
        self.log_debug(
            request_id,
            &DebugLogMetadata {
                action: request.action.clone(),
                resource: resource_uid.to_string(),
                context: &request.context,
                entities: &entities,
                debug_authz_info: debug_authorize_info,
                decision: result.decision,
            },
        );

        if !result.decision {
            self.log_failed_diagnostics(diagnostics, request_id);
        }

        // Record metrics
        let decision = Decision::from(result.decision);
        let policy_decisions = diagnostics
            .iter()
            .flat_map(|d| d.reason.iter())
            .map(|policy| (policy.id.as_str(), decision));

        self.config.metrics.record_evaluation(
            decision_time_micro_sec,
            decision,
            true,
            policy_decisions,
        );

        Ok(result)
    }

    /// Execute cedar policy `is_authorized` method to check
    /// if allowed make request with given parameters
    fn execute_authorize(
        &self,
        parameters: ExecuteAuthorizeParameters,
    ) -> Result<cedar_policy::Response, Box<cedar_policy::RequestValidationError>> {
        let has_principal = parameters.principal.is_some();

        let request_builder_base = cedar_policy::Request::builder()
            .action(parameters.action)
            .resource(parameters.resource)
            .context(parameters.context);

        let request = if let Some(schema) = &self.config.policy_store.schema {
            let request_builder = request_builder_base.schema(&schema.schema);
            match parameters.principal {
                Some(principal) => request_builder.principal(principal).build()?,
                None => request_builder.build()?,
            }
        } else {
            match parameters.principal {
                Some(principal) => request_builder_base.principal(principal).build(),
                None => request_builder_base.build(),
            }
        };
        if has_principal {
            Ok(self.authorizer.is_authorized(
                &request,
                self.config.policy_store.policies.get_set(),
                parameters.entities,
            ))
        } else {
            Ok(self.is_authorized_partial(&request, parameters.entities))
        }
    }

    /// Run a partial Cedar authorization and convert the result to a concrete [`cedar_policy::Response`].
    ///
    /// When the partial evaluation already yields a concrete decision the original diagnostics are
    /// preserved via [`cedar_policy::PartialResponse::concretize`].  When residuals remain (no
    /// concrete decision), a fail-closed Deny is synthesized: the nontrivial-residual policy IDs
    /// become the `reason` set and evaluation errors are extracted through `concretize()` — the
    /// only public API in cedar-policy 4.9 that surfaces `AuthorizationError` objects from a
    /// `PartialResponse`.
    fn is_authorized_partial(
        &self,
        request: &cedar_policy::Request,
        entities: &cedar_policy::Entities,
    ) -> cedar_policy::Response {
        let partial = self.authorizer.is_authorized_partial(
            request,
            self.config.policy_store.policies.get_set(),
            entities,
        );

        // `decision()` is preferred over `concretize()`: it returns `Some` iff the partial
        // response already has a concrete decision, letting us preserve the original
        // diagnostics; only residual-dependent requests fall through to a synthesized Deny.
        if partial.decision().is_some() {
            partial.concretize()
        } else {
            let residual_ids: HashSet<cedar_policy::PolicyId> = partial
                .nontrivial_residuals()
                .map(|p| p.id().clone())
                .collect();
            let errors: Vec<cedar_policy::AuthorizationError> = partial
                .concretize()
                .diagnostics()
                .errors()
                .cloned()
                .collect();
            cedar_policy::Response::new(cedar_policy::Decision::Deny, residual_ids, errors)
        }
    }

    /// Log policy evaluation errors for diagnostics
    fn log_policy_evaluation_errors(
        &self,
        diagnostics: &Diagnostics,
        principal_name: &str,
        request_id: Uuid,
    ) {
        if !diagnostics.errors.is_empty() {
            let log_entry = LogEntry::new(BaseLogEntry::new_decision(request_id))
                .set_message(format!("Policy evaluation errors for {principal_name}"))
                .set_error(format!("{:?}", diagnostics.errors));
            self.config.log_service.log_any(log_entry);
        }
    }

    /// Logs a summary of all diagnostics errors when authorization is denied.
    ///
    /// This provides a consolidated view of all policy evaluation errors across all principals,
    /// complementing the per-principal error logs. Only logs when there are actual errors
    /// to avoid noise.
    fn log_failed_diagnostics(&self, diagnostics: &[Diagnostics], request_id: Uuid) {
        let all_errors: Vec<_> = diagnostics.iter().flat_map(|d| &d.errors).collect();

        if all_errors.is_empty() {
            return;
        }

        let serialized_errors = serde_json::to_string(&all_errors)
            .unwrap_or_else(|_| "failed to serialize diagnostics errors".to_string());

        let log_entry = LogEntry::new(BaseLogEntry::new_decision(request_id))
            .set_message(
                "Authorization denied: summary of all policy evaluation errors".to_string(),
            )
            .set_error(serialized_errors);

        self.config.log_service.log_any(log_entry);
    }

    /// Logs a decision log entry.
    fn log_decision(&self, request_id: Uuid, metadata: &DecisionLogMetadata) {
        let entry = BaseLogEntry::new_decision(request_id).with_fn(|base| DecisionLogEntry {
            base,
            policystore_id: self.config.policy_store.id.as_str().into(),
            policystore_version: self.config.policy_store.get_store_version().into(),
            principal: metadata.principal.clone(),
            lock_client_id: None,
            action: metadata.action.clone(),
            resource: metadata.resource.clone(),
            decision: metadata.decision.into(),
            tokens: metadata.tokens_logging_info.clone(),
            decision_time_micro_sec: metadata.decision_time,
            diagnostics: DiagnosticsSummary::from_diagnostics(metadata.decision_diagnostics),
            pushed_data: metadata.pushed_data.clone(),
        });
        self.config.log_service.log_fn(entry);
    }

    /// Logs a debug log entry.
    fn log_debug(&self, request_id: Uuid, metadata: &DebugLogMetadata) {
        let debug_log_fn = BaseLogEntry::new_system(LogLevel::DEBUG, request_id).with_fn(|base| {
            // usually debug log is disabled, so we build entities_json only when needed
            // error should newer happen here, because entities were built successfully before
            let entities_json: serde_json::Value = {
                // getting entities as json
                serialize_entities(metadata.entities)
            };

            LogEntry::new(base)
                .set_auth_info(AuthorizationLogInfo {
                    action: metadata.action.clone(),
                    context: metadata.context.clone(),
                    resource: metadata.resource.clone(),
                    entities: entities_json,
                    authorize_info: metadata.debug_authz_info.clone(),
                    authorized: metadata.decision,
                })
                .set_message("Result of authorize.".to_string())
        });
        self.config.log_service.log_fn(debug_log_fn);
    }

    /// Returns metadata for policies matching the given unsigned request parameters.
    ///
    /// Builds entity type names from `EntityData` principals/resources and parses
    /// action strings, then delegates to `PoliciesContainer::get_matching_policies`.
    pub(super) fn get_matching_policies_unsigned(
        &self,
        principal: Option<&crate::EntityData>,
        actions: &[String],
        resources: &[crate::EntityData],
    ) -> Result<Vec<crate::PolicyMetadata>, AuthorizeError> {
        let principal_types = match principal {
            Some(p) => entity_data_to_type_names(std::slice::from_ref(p))?,
            None => HashSet::new(),
        };
        let action_uids = parse_action_uids(actions)?;
        let resource_types = entity_data_to_type_names(resources)?;

        Ok(self.config.policy_store.policies.get_matching_policies(
            &principal_types,
            &action_uids,
            &resource_types,
        ))
    }

    /// Returns metadata for policies matching the given multi-issuer request parameters.
    ///
    /// Validates tokens and extracts principal entity types from them, then
    /// delegates to `PoliciesContainer::get_matching_policies`.
    pub(super) fn get_matching_policies_multi_issuer(
        &self,
        tokens: &[crate::TokenInput],
        actions: &[String],
        resources: &[crate::EntityData],
    ) -> Result<Vec<crate::PolicyMetadata>, AuthorizeError> {
        let validated_tokens = self
            .config
            .jwt_service
            .validate_multi_issuer_tokens(tokens)?;

        let principal_types: HashSet<cedar_policy::EntityTypeName> = validated_tokens
            .keys()
            .map(|mapping| {
                cedar_policy::EntityTypeName::from_str(mapping)
                    .map_err(|e| AuthorizeError::IdentifierParsing(e.into()))
            })
            .collect::<Result<_, _>>()?;

        let action_uids = parse_action_uids(actions)?;
        let resource_types = entity_data_to_type_names(resources)?;

        Ok(self.config.policy_store.policies.get_matching_policies(
            &principal_types,
            &action_uids,
            &resource_types,
        ))
    }
}

/// Parse entity type names from `EntityData` slices.
fn entity_data_to_type_names(
    entities: &[crate::EntityData],
) -> Result<HashSet<cedar_policy::EntityTypeName>, AuthorizeError> {
    entities
        .iter()
        .map(|e| {
            cedar_policy::EntityTypeName::from_str(&e.cedar_mapping.entity_type)
                .map_err(|e| AuthorizeError::IdentifierParsing(e.into()))
        })
        .collect()
}

/// Parse action strings into `EntityUid` set.
fn parse_action_uids(actions: &[String]) -> Result<HashSet<EntityUid>, AuthorizeError> {
    actions
        .iter()
        .map(|a| EntityUid::from_str(a).map_err(Into::into))
        .collect()
}

impl TrustedIssuerLoadingInfo for Authz {
    fn is_trusted_issuer_loaded_by_name(&self, issuer_id: &str) -> bool {
        self.config
            .jwt_service
            .is_trusted_issuer_loaded_by_name(issuer_id)
    }

    fn is_trusted_issuer_loaded_by_iss(&self, iss_claim: &str) -> bool {
        self.config
            .jwt_service
            .is_trusted_issuer_loaded_by_iss(iss_claim)
    }

    fn total_issuers(&self) -> usize {
        self.config.jwt_service.total_issuers()
    }

    fn loaded_trusted_issuers_count(&self) -> usize {
        self.config.jwt_service.loaded_trusted_issuers_count()
    }

    fn loaded_trusted_issuer_ids(&self) -> HashSet<String> {
        self.config.jwt_service.loaded_trusted_issuer_ids()
    }

    fn failed_trusted_issuer_ids(&self) -> HashSet<String> {
        self.config.jwt_service.failed_trusted_issuer_ids()
    }
}

fn calculate_elapsed_time(start_time: chrono::DateTime<Utc>) -> i64 {
    let since_start = Utc::now().signed_duration_since(start_time);
    since_start.num_microseconds().unwrap_or(
        //overflow (exceeding 2^63 microseconds in either direction)
        i64::MAX,
    )
}

fn serialize_entities(entities: &Entities) -> serde_json::Value {
    entities.to_json_value().unwrap_or(serde_json::Value::Null)
}

/// Helper struct to hold named parameters for [`Authz::log_decision`] method.
struct DecisionLogMetadata<'a> {
    action: String,
    resource: String,
    principal: Vec<smol_str::SmolStr>,
    tokens_logging_info: LogTokensInfo,
    decision_diagnostics: &'a [Diagnostics],
    decision_time: i64,
    decision: bool,
    pushed_data: Option<PushedDataInfo>,
}

/// Helper struct to hold named parameters for [`Authz::log_debug`] method.
struct DebugLogMetadata<'a> {
    action: String,
    resource: String,
    context: &'a serde_json::Value,
    entities: &'a Entities,
    debug_authz_info: Vec<AuthorizeInfo>,
    decision: bool,
}

/// Helper struct to hold named parameters for [`Authz::execute_authorize`] method.
struct ExecuteAuthorizeParameters<'a> {
    entities: &'a Entities,
    principal: Option<EntityUid>,
    action: EntityUid,
    resource: EntityUid,
    context: cedar_policy::Context,
}

/// Structure to hold entites created from tokens
#[derive(Debug)]
pub(super) struct AuthorizeEntitiesData {
    pub issuers: HashSet<Entity>,
    pub tokens: HashMap<String, Entity>,
    pub resource: Entity,
    pub default_entities: DefaultEntities,
}

impl AuthorizeEntitiesData {
    /// Create iterator to get all entities
    ///
    /// This method merges request entities with default entities, where default entities
    /// (from the policy store) take precedence over request-supplied entities in case of
    /// UID conflicts. This ensures that policy-store entities — which represent
    /// change-controlled, trusted shared state — cannot be overwritten by attacker-controlled
    /// request data.
    fn into_iter(self) -> impl Iterator<Item = Entity> {
        let capacity = 1usize // resource
            .saturating_add(self.issuers.len())
            .saturating_add(self.tokens.len())
            .saturating_add(self.default_entities.inner.len());
        let mut merged_entities: HashMap<EntityUid, Entity> = HashMap::with_capacity(capacity);

        // Add request entities first (these may be overwritten by default entities)
        merged_entities.insert(self.resource.uid(), self.resource);
        merged_entities.extend(self.issuers.into_iter().map(|e| (e.uid(), e)));
        merged_entities.extend(self.tokens.into_values().map(|e| (e.uid(), e)));

        // Add default entities last (these take precedence over request entities if UID conflicts exist)
        merged_entities.extend(
            Arc::try_unwrap(self.default_entities.inner)
                .unwrap_or_else(|arc| (*arc).clone())
                .into_values()
                .map(|e| (e.uid(), e)),
        );

        merged_entities.into_values()
    }

    /// Collect all entities to [`cedar_policy::Entities`]
    pub(crate) fn entities(
        self,
        schema: Option<&cedar_policy::Schema>,
    ) -> Result<cedar_policy::Entities, Box<cedar_policy::entities_errors::EntitiesError>> {
        Entities::from_entities(self.into_iter(), schema).map_err(Box::new)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::Arc;

    fn to_entity(json: serde_json::Value) -> Entity {
        Entity::from_json_value(json, None).expect("entity from json")
    }

    fn default_entities(jsons: &[serde_json::Value]) -> DefaultEntities {
        let inner: HashMap<EntityUid, Entity> = jsons
            .iter()
            .map(|j| {
                let entity = to_entity(j.clone());
                (entity.uid().clone(), entity)
            })
            .collect();
        DefaultEntities {
            inner: Arc::new(inner),
        }
    }

    #[test]
    fn default_takes_precedence_over_resource_on_uid_collision() {
        let data = AuthorizeEntitiesData {
            issuers: HashSet::new(),
            tokens: HashMap::new(),
            resource: to_entity(
                json!({"uid": {"type": "Jans::Org", "id": "org1"}, "attrs": {"name": "evil", "is_admin": false}, "parents": []}),
            ),
            default_entities: default_entities(&[
                json!({"uid": {"type": "Jans::Org", "id": "org1"}, "attrs": {"name": "trusted", "is_admin": true}, "parents": []}),
            ]),
        };

        let ents = data.entities(None).expect("entities");
        let uid: EntityUid = "Jans::Org::\"org1\"".parse().unwrap();
        let entity = ents.get(&uid).expect("org1 entity");
        let json = entity.to_json_value().expect("to_json");
        assert_eq!(
            json.pointer("/attrs/name").and_then(|v| v.as_str()),
            Some("trusted"),
            "default org name should override request value"
        );
        assert_eq!(
            json.pointer("/attrs/is_admin")
                .and_then(serde_json::Value::as_bool),
            Some(true),
            "default is_admin should override request false"
        );
    }

    #[test]
    fn default_takes_precedence_over_issuer_on_uid_collision() {
        let mut issuers = HashSet::new();
        issuers.insert(to_entity(json!({"uid": {"type": "Jans::Issuer", "id": "iss1"}, "attrs": {"trusted": false}, "parents": []})));
        let data = AuthorizeEntitiesData {
            issuers,
            tokens: HashMap::new(),
            resource: to_entity(
                json!({"uid": {"type": "Jans::Resource", "id": "res1"}, "attrs": {}, "parents": []}),
            ),
            default_entities: default_entities(&[
                json!({"uid": {"type": "Jans::Issuer", "id": "iss1"}, "attrs": {"trusted": true}, "parents": []}),
            ]),
        };

        let ents = data.entities(None).expect("entities");
        let uid: EntityUid = "Jans::Issuer::\"iss1\"".parse().unwrap();
        let json = ents
            .get(&uid)
            .expect("issuer entity")
            .to_json_value()
            .expect("to_json");
        assert_eq!(
            json.pointer("/attrs/trusted")
                .and_then(serde_json::Value::as_bool),
            Some(true),
            "default issuer trusted=true should override request false"
        );
    }

    #[test]
    fn default_takes_precedence_over_token_on_uid_collision() {
        let mut tokens = HashMap::new();
        tokens.insert(
            "tok1".to_string(),
            to_entity(json!({"uid": {"type": "Jans::access_token", "id": "tok1"}, "attrs": {"scope": "evil"}, "parents": []})),
        );
        let data = AuthorizeEntitiesData {
            issuers: HashSet::new(),
            tokens,
            resource: to_entity(
                json!({"uid": {"type": "Jans::Resource", "id": "res1"}, "attrs": {}, "parents": []}),
            ),
            default_entities: default_entities(&[
                json!({"uid": {"type": "Jans::access_token", "id": "tok1"}, "attrs": {"scope": "read"}, "parents": []}),
            ]),
        };

        let ents = data.entities(None).expect("entities");
        let uid: EntityUid = "Jans::access_token::\"tok1\"".parse().unwrap();
        let json = ents
            .get(&uid)
            .expect("token entity")
            .to_json_value()
            .expect("to_json");
        assert_eq!(
            json.pointer("/attrs/scope").and_then(|v| v.as_str()),
            Some("read"),
            "default token scope should override request value"
        );
    }

    #[test]
    fn unique_uids_all_present() {
        let data = AuthorizeEntitiesData {
            issuers: HashSet::new(),
            tokens: HashMap::new(),
            resource: to_entity(
                json!({"uid": {"type": "Jans::Resource", "id": "res1"}, "attrs": {}, "parents": []}),
            ),
            default_entities: default_entities(&[
                json!({"uid": {"type": "Jans::Org", "id": "org1"}, "attrs": {}, "parents": []}),
            ]),
        };

        let ents = data.entities(None).expect("entities");
        assert!(
            ents.get(&"Jans::Resource::\"res1\"".parse().unwrap())
                .is_some(),
            "resource entity should be present when no UID collision"
        );
        assert!(
            ents.get(&"Jans::Org::\"org1\"".parse().unwrap()).is_some(),
            "default entity should be present when no UID collision"
        );
        assert_eq!(
            ents.iter().count(),
            2,
            "both entities should be present with unique UIDs"
        );
    }

    #[test]
    fn empty_defaults_produces_only_request_entities() {
        let data = AuthorizeEntitiesData {
            issuers: HashSet::new(),
            tokens: HashMap::new(),
            resource: to_entity(
                json!({"uid": {"type": "Jans::Resource", "id": "res1"}, "attrs": {}, "parents": []}),
            ),
            default_entities: DefaultEntities::default(),
        };

        let ents = data.entities(None).expect("entities");
        assert!(
            ents.get(&"Jans::Resource::\"res1\"".parse().unwrap())
                .is_some(),
            "resource entity should be present with empty defaults"
        );
        assert_eq!(
            ents.iter().count(),
            1,
            "only resource entity expected with empty defaults"
        );
    }

    #[test]
    fn defaults_win_when_both_resource_and_issuer_collide() {
        let mut issuers = HashSet::new();
        issuers.insert(to_entity(json!({"uid": {"type": "Jans::Group", "id": "admin"}, "attrs": {"role": "user"}, "parents": []})));
        let data = AuthorizeEntitiesData {
            issuers,
            tokens: HashMap::new(),
            resource: to_entity(
                json!({"uid": {"type": "Jans::Org", "id": "org1"}, "attrs": {"name": "evil"}, "parents": []}),
            ),
            default_entities: default_entities(&[
                json!({"uid": {"type": "Jans::Org", "id": "org1"}, "attrs": {"name": "trusted"}, "parents": []}),
                json!({"uid": {"type": "Jans::Group", "id": "admin"}, "attrs": {"role": "admin"}, "parents": []}),
            ]),
        };

        let ents = data.entities(None).expect("entities");

        let org_uid: EntityUid = "Jans::Org::\"org1\"".parse().unwrap();
        let org_json = ents
            .get(&org_uid)
            .expect("org entity")
            .to_json_value()
            .expect("to_json");
        assert_eq!(
            org_json.pointer("/attrs/name").and_then(|v| v.as_str()),
            Some("trusted"),
            "default org name should override request value in multi-collision test"
        );

        let group_uid: EntityUid = "Jans::Group::\"admin\"".parse().unwrap();
        let group_json = ents
            .get(&group_uid)
            .expect("group entity")
            .to_json_value()
            .expect("to_json");
        assert_eq!(
            group_json.pointer("/attrs/role").and_then(|v| v.as_str()),
            Some("admin"),
            "default group role should override request value in multi-collision test"
        );
    }
}