cedarling 0.0.64

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

#[cfg(not(target_arch = "wasm32"))]
use super::super::BootstrapConfigLoadingError;
use super::super::log_config::StdOutMode;
use super::default_values::{
    default_enabled_feature_toggle, default_http_client_max_response_size_bytes,
    default_http_client_max_retries, default_http_client_retry_delay_secs, default_jti,
    default_jwks_refresh_min_interval, default_log_channel_capacity, default_log_max_retries,
    default_status_list_refresh_interval_max, default_token_cache_capacity,
    default_token_cache_max_ttl, default_true,
};
#[cfg(not(target_arch = "wasm32"))]
use super::default_values::{
    default_http_client_request_timeout, default_stdout_buffer_limit, default_stdout_timeout_millis,
};
use super::feature_types::{FeatureToggle, LoggerType};
use super::json_util::{
    deserialize_jwks_refresh_interval, deserialize_jwks_refresh_min_interval,
    deserialize_or_parse_string_as_json, deserialize_status_list_refresh_interval_max,
    parse_option_string,
};
use crate::JwtConfig;
use crate::LockTransport;
use crate::jwt_config::{TrustedIssuerLoaderTypeRaw, WorkersCount};
use crate::log::LogLevel;
use jsonwebtoken::Algorithm;
use serde::{Deserialize, Serialize};
#[cfg(not(target_arch = "wasm32"))]
use std::collections::HashMap;
use std::collections::HashSet;
#[cfg(not(target_arch = "wasm32"))]
use std::env;

use std::num::NonZeroUsize;

/// Struct that represent mapping mapping `Bootstrap properties` to be JSON and YAML compatible
/// from [link](https://github.com/JanssenProject/jans/wiki/Cedarling-Nativity-Plan#bootstrap-properties)
///
/// This structure is used to deserialize values from ENV VARS so json keys is same as keys in environment variables
//
//  All fields should be available to parse from string, because env vars always string.
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct BootstrapConfigRaw {
    ///  Human friendly identifier for the application
    #[serde(rename = "CEDARLING_APPLICATION_NAME")]
    pub application_name: String,

    /// Location of policy store JSON, used if policy store is not local, or retreived from Lock Master.
    #[serde(
        rename = "CEDARLING_POLICY_STORE_URI",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub policy_store_uri: Option<String>,

    /// How the Logs will be presented.
    #[serde(rename = "CEDARLING_LOG_TYPE", default)]
    pub log_type: LoggerType,

    /// Log level filter for logging. TRACE is lowest. FATAL is highest.
    #[serde(rename = "CEDARLING_LOG_LEVEL", default)]
    pub log_level: LogLevel,

    /// If `log_type` is set to [`LogType::Memory`], this is the TTL (time to live) of
    /// log entities in seconds.
    #[serde(rename = "CEDARLING_LOG_TTL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub log_ttl: Option<u64>,

    /// Maximum number of log entities that can be stored using [`LogType::Memory`].
    /// If value is 0, there is no limit. But if None, default value is applied.
    #[serde(rename = "CEDARLING_LOG_MAX_ITEMS", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub log_max_items: Option<usize>,

    /// Maximum size of a single log entity in bytes using [`LogType::Memory`].
    /// If value is 0, there is no limit. But if None, default value is applied.
    #[serde(rename = "CEDARLING_LOG_MAX_ITEM_SIZE", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub log_max_item_size: Option<usize>,

    /// Logging mode for stdout logger: "async" or "immediate (default)".
    /// Only applicable for native targets (not WASM).
    #[serde(rename = "CEDARLING_STDOUT_MODE", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub stdout_mode: StdOutMode,

    /// Flush timeout in milliseconds for async stdout logging.
    /// Only applicable for native targets (not WASM).
    #[cfg(not(target_arch = "wasm32"))]
    #[serde(
        rename = "CEDARLING_STDOUT_TIMEOUT_MILLIS",
        default = "default_stdout_timeout_millis"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub stdout_timeout_millis: u64,

    /// Buffer size limit in bytes for async stdout logging.
    /// Only applicable for native targets (not WASM).
    #[cfg(not(target_arch = "wasm32"))]
    #[serde(
        rename = "CEDARLING_STDOUT_BUFFER_LIMIT",
        default = "default_stdout_buffer_limit"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub stdout_buffer_limit: usize,

    /// Token claims that will be used for decision logging.
    /// Default is jti, but perhaps some other claim is needed.
    #[serde(
        rename = "CEDARLING_DECISION_LOG_DEFAULT_JWT_ID",
        default = "default_jti"
    )]
    pub decision_log_default_jwt_id: String,

    /// Path to a local file pointing containing a JWKS.
    #[serde(
        rename = "CEDARLING_LOCAL_JWKS",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub local_jwks: Option<String>,

    /// JSON object with policy store
    #[serde(rename = "CEDARLING_POLICY_STORE_LOCAL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub local_policy_store: Option<String>,

    /// Path to a Policy Store JSON file
    #[serde(
        rename = "CEDARLING_POLICY_STORE_LOCAL_FN",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub policy_store_local_fn: Option<String>,
    /// URL to a Policy Store CJAR file
    #[serde(
        rename = "CEDARLING_POLICY_STORE_CJAR_URL",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub policy_store_cjar_url: Option<String>,

    /// Maximum number of default entities allowed in a policy store.
    /// This prevents `DoS` attacks by limiting the number of entities that can be loaded.
    /// If value is 0, there is no limit. But if None, default value is applied.
    #[serde(rename = "CEDARLING_MAX_DEFAULT_ENTITIES", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub max_default_entities: Option<usize>,

    /// Maximum size of base64-encoded default entity strings in bytes.
    /// This prevents memory exhaustion attacks from extremely large base64 strings.
    /// If value is 0, there is no limit. But if None, default value is applied.
    #[serde(rename = "CEDARLING_MAX_BASE64_SIZE", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub max_base64_size: Option<usize>,

    /// Whether to check the signature of all JWT tokens.
    ///
    /// When enabled, this requires the `iss` (Issuer) claim to be present in
    /// all tokens and the issuer URL must use the `https` scheme.
    #[serde(
        rename = "CEDARLING_JWT_SIG_VALIDATION",
        default = "default_enabled_feature_toggle"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub jwt_sig_validation: FeatureToggle,

    /// Whether to check the status of the JWT. On startup.
    ///
    /// Cedarling will fetch and retreive the latest Status List JWT from the
    /// `.well-known/openid-configuration` via the `status_list_endpoint` claim and
    /// cache it. See the [`IETF Draft`] for more info.
    ///
    /// [`IETF Draft`]: https://datatracker.ietf.org/doc/draft-ietf-oauth-status-list/
    #[serde(
        rename = "CEDARLING_JWT_STATUS_VALIDATION",
        default = "default_enabled_feature_toggle"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub jwt_status_validation: FeatureToggle,

    /// When enabled, Cedar schema is required and all policies and entities are validated
    /// against it. When disabled, Cedarling runs without schema-based validation,
    /// allowing quick-start and prototyping without a schema.
    #[serde(
        rename = "CEDARLING_STRICT_SCHEMA_VALIDATION",
        default = "default_enabled_feature_toggle"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub strict_schema_validation: FeatureToggle,

    /// Cedarling will only accept tokens signed with these algorithms.
    #[serde(
        rename = "CEDARLING_JWT_SIGNATURE_ALGORITHMS_SUPPORTED",
        default = "JwtConfig::supported_algorithms"
    )]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub jwt_signature_algorithms_supported: HashSet<Algorithm>,

    /// If Enabled, the Cedarling will connect to the Lock Master for policies,
    /// and subscribe for SSE events.
    #[serde(rename = "CEDARLING_LOCK", default)]
    pub lock: FeatureToggle,

    /// URI where Cedarling can get JSON file with all required metadata about
    /// Lock Master, i.e. .well-known/lock-master-configuration.
    ///
    /// ***Required*** if `LOCK == enabled`.
    #[serde(rename = "CEDARLING_LOCK_SERVER_CONFIGURATION_URI", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub lock_server_configuration_uri: Option<String>,

    /// Controls whether Cedarling should listen for SSE config updates.
    #[serde(rename = "CEDARLING_LOCK_DYNAMIC_CONFIGURATION", default)]
    pub dynamic_configuration: FeatureToggle,

    /// SSA for DCR in a Lock Master deployment. The Cedarling will validate this
    /// SSA JWT prior to DCR.
    #[serde(
        rename = "CEDARLING_LOCK_SSA_JWT",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub lock_ssa_jwt: Option<String>,

    /// Pre-issued access token to use for Lock Server authentication, bypassing
    /// the SSA → DCR → `access_token` flow entirely.
    ///
    /// When this property is set, Cedarling will skip Dynamic Client Registration
    /// and use this access token directly to authenticate with Lock Server endpoints
    /// (log, health, telemetry). Primarily intended for testing and local development
    /// to simplify the bootstrap flow; may also be used in environments where the
    /// DCR flow is not available or access tokens are provisioned externally.
    ///
    /// If both `CEDARLING_LOCK_ACCESS_TOKEN_JWT` and `CEDARLING_LOCK_SSA_JWT` are
    /// set, `CEDARLING_LOCK_ACCESS_TOKEN_JWT` takes precedence and the SSA flow is
    /// skipped.
    ///
    /// Not available on WASM targets.
    #[cfg(not(target_arch = "wasm32"))]
    #[serde(
        rename = "CEDARLING_LOCK_ACCESS_TOKEN_JWT",
        default,
        deserialize_with = "parse_option_string"
    )]
    pub lock_access_token_jwt: Option<String>,

    /// How often to send log messages to Lock Master (0 to turn off trasmission).
    #[serde(rename = "CEDARLING_LOCK_LOG_INTERVAL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub audit_log_interval: u64,

    /// How often to send health messages to Lock Master (0 to turn off transmission).
    #[serde(rename = "CEDARLING_LOCK_HEALTH_INTERVAL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub audit_health_interval: u64,

    /// How often to send telemetry messages to Lock Master (0 to turn off transmission).
    #[serde(rename = "CEDARLING_LOCK_TELEMETRY_INTERVAL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub audit_telemetry_interval: u64,

    /// Controls whether Cedarling should listen for updates from the Lock Server.
    #[serde(rename = "CEDARLING_LOCK_LISTEN_SSE", default)]
    pub listen_sse: FeatureToggle,

    /// Allow interaction with a Lock server with invalid certificates. Used for testing.
    #[serde(rename = "CEDARLING_LOCK_ACCEPT_INVALID_CERTS", default)]
    pub accept_invalid_certs: FeatureToggle,

    /// Transport protocol for Lock Server communication ("grpc" or "rest").
    #[serde(
        rename = "CEDARLING_LOCK_TRANSPORT",
        deserialize_with = "deserialize_or_parse_string_as_json",
        default
    )]
    pub lock_transport: LockTransport,

    /// Channel capacity for buffering log entries before they are sent to the lock server.
    /// Higher values allow more logs to be buffered in memory when the lock server is slow,
    /// but also increase memory usage.
    /// Default value is 100.
    #[serde(
        rename = "CEDARLING_LOCK_LOG_CHANNEL_CAPACITY",
        deserialize_with = "deserialize_or_parse_string_as_json",
        default = "default_log_channel_capacity"
    )]
    pub lock_log_channel_capacity: NonZeroUsize,

    /// Maximum number of retry attempts for sending logs to the lock server.
    /// Uses exponential backoff strategy for retrying.
    /// Default value is 5.
    #[serde(
        rename = "CEDARLING_LOCK_LOG_MAX_RETRIES",
        deserialize_with = "deserialize_or_parse_string_as_json",
        default = "default_log_max_retries"
    )]
    pub lock_log_max_retries: u32,

    /// Maximum token cache TTL in seconds.
    ///
    /// Caps how long a validated token may stay in the cache. The effective
    /// TTL for an entry is `min(time-until-exp, max_ttl)` when both apply.
    ///
    /// - `> 0`: cap each entry's TTL at this value. Also used as the TTL for
    ///   tokens that do not carry an `exp` claim.
    /// - `0`: disables the token cache entirely.
    ///
    /// Default: `5` seconds — small enough to pick up revocation / status-list
    /// changes quickly, large enough to amortise repeated requests for the
    /// same token.
    #[serde(
        rename = "CEDARLING_TOKEN_CACHE_MAX_TTL",
        default = "default_token_cache_max_ttl"
    )]
    pub token_cache_max_ttl: usize,
    /// Maximum number of tokens the cache can store.
    /// Default value is 100.
    /// 0 means no limit.
    #[serde(
        rename = "CEDARLING_TOKEN_CACHE_CAPACITY",
        default = "default_token_cache_capacity"
    )]
    pub token_cache_capacity: usize,
    /// Enables eviction policy based on the earliest expiration time.
    ///
    /// When the cache reaches its capacity, the entry with the nearest
    /// expiration timestamp will be removed to make room for a new one.
    #[serde(
        rename = "CEDARLING_TOKEN_CACHE_EARLIEST_EXPIRATION_EVICTION",
        default = "default_true"
    )]
    pub token_cache_earliest_expiration_eviction: bool,

    // =========================================================================
    // Data Store Configuration
    // =========================================================================
    /// Maximum number of data entries in the data store (0 = unlimited).
    /// Default: 10,000
    #[serde(rename = "CEDARLING_DATA_STORE_MAX_ENTRIES", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_max_entries: Option<usize>,

    /// Maximum size per data entry in bytes (0 = unlimited).
    /// Default: 1MB (1,048,576 bytes)
    #[serde(rename = "CEDARLING_DATA_STORE_MAX_ENTRY_SIZE", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_max_entry_size: Option<usize>,

    /// Default TTL for data entries in seconds.
    /// If not set, entries do not expire.
    #[serde(rename = "CEDARLING_DATA_STORE_DEFAULT_TTL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_default_ttl: Option<u64>,

    /// Maximum allowed TTL for data entries in seconds.
    /// Default: 3600 (1 hour). Entries with TTL exceeding this value will be rejected.
    /// Note: `0` means a zero-second max TTL (immediate expiry), not unlimited.
    /// Omitting this property uses the default (1 hour).
    #[serde(rename = "CEDARLING_DATA_STORE_MAX_TTL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_max_ttl: Option<u64>,

    /// Enable metrics tracking (access counts, timestamps) for data entries.
    /// Default: true
    #[serde(rename = "CEDARLING_DATA_STORE_ENABLE_METRICS", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_enable_metrics: Option<bool>,

    /// Memory usage alert threshold as a percentage (0.0-100.0).
    /// When capacity usage exceeds this threshold, a warning is logged.
    /// Default: 80.0 (80%)
    #[serde(rename = "CEDARLING_DATA_STORE_MEMORY_ALERT_THRESHOLD", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub data_store_memory_alert_threshold: Option<f64>,
    /// Type of trusted issuer loader.
    /// If not set, synchronous loader is used.
    /// Can be `SYNC` or `ASYNC`.
    ///
    /// Sync loader means that trusted issuers will be loaded on initialization.
    /// Async loader means that trusted issuers will be loaded in background.
    #[serde(
        rename = "CEDARLING_TRUSTED_ISSUER_LOADER_TYPE",
        default,
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub trusted_issuer_loader_type: TrustedIssuerLoaderTypeRaw,
    /// Number of concurrent workers to use when loading trusted issuers.
    /// Applies to both SYNC (parallel loading during initialization) and ASYNC (parallel background loading) modes.
    /// Minimum possible value is 1. Zero will be used as 1.
    ///
    /// For WASM maximum value is 6, default is 2.
    /// For native maximum value is 1000, default is 10.
    #[serde(
        rename = "CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS",
        default,
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub trusted_issuer_loader_workers: WorkersCount,
    // =========================================================================
    // HTTP CLIENT CONFIGURATION
    // =========================================================================
    /// Per-request timeout in seconds.
    #[cfg(not(target_arch = "wasm32"))]
    #[serde(
        rename = "CEDARLING_HTTP_REQUEST_TIMEOUT",
        default = "default_http_client_request_timeout",
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub http_client_request_timeout: u64,
    /// Maximum number of retry attempts per request.
    #[serde(
        rename = "CEDARLING_HTTP_REQUEST_MAX_RETRIES",
        default = "default_http_client_max_retries",
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub http_client_request_max_retries: u32,

    /// Base delay between retries in seconds.
    #[serde(
        rename = "CEDARLING_HTTP_REQUEST_RETRY_DELAY",
        default = "default_http_client_retry_delay_secs",
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub http_client_request_retry_delay: u64,

    /// Maximum HTTP response body size, in bytes. Rejects oversized responses
    /// (JWKS, OIDC config, status list, policy store, Lock Server endpoints)
    /// before they're fully buffered into memory. `0` disables the cap.
    /// Default: 10 MB (`10485760`).
    #[serde(
        rename = "CEDARLING_HTTP_MAX_RESPONSE_SIZE_BYTES",
        default = "default_http_client_max_response_size_bytes",
        deserialize_with = "deserialize_or_parse_string_as_json"
    )]
    pub http_client_max_response_size_bytes: u64,

    /// Optional override for JWKS periodic refresh interval in seconds.
    /// When set, overrides the `Cache-Control: max-age` from the JWKS endpoint.
    /// If omitted, the server-driven interval or a 1-hour fallback is used.
    /// Values below 5 seconds are clamped to 5.
    #[serde(rename = "CEDARLING_JWKS_REFRESH_INTERVAL", default)]
    #[serde(deserialize_with = "deserialize_jwks_refresh_interval")]
    pub jwks_refresh_interval: Option<u64>,

    /// Minimum interval in seconds between on-demand JWKS re-fetches per issuer.
    /// Prevents abuse from invalid JWT floods triggering excessive re-fetches.
    /// Default: 30 seconds. Values below 5 seconds are clamped to 5.
    #[serde(
        rename = "CEDARLING_JWKS_REFRESH_MIN_INTERVAL",
        default = "default_jwks_refresh_min_interval"
    )]
    #[serde(deserialize_with = "deserialize_jwks_refresh_min_interval")]
    pub jwks_refresh_min_interval: u64,

    /// Upper bound on the Status List JWT refresh interval, in seconds.
    ///
    /// Caps how long Cedarling waits between Status List refreshes. When the Status
    /// List JWT carries a `ttl` claim, the effective refresh interval is
    /// `min(jwt_ttl, status_list_refresh_interval_max)`, so the issuer can request a
    /// *more frequent* refresh but never a less frequent one. When the JWT omits
    /// `ttl`, this value is used directly. A value of `0` or an unset variable is
    /// treated as "use the default" (300 seconds) so the status list cannot silently
    /// go stale forever. Non-zero values below `5` are clamped to `5`.
    ///
    /// Fail-closed behavior: if any background refresh fails — fetch error, 5xx
    /// response, or the status list body is invalid (JWT validation fails,
    /// deserialization fails, or bit-string parsing fails) — the cached status list
    /// is dropped and all tokens that reference it are rejected until the next
    /// successful refresh. This prevents a revoked token from being accepted based on
    /// stale data at the cost of temporarily denying valid tokens when the issuer's
    /// status endpoint is unreachable or returns a malformed payload.
    #[serde(
        rename = "CEDARLING_JWT_STATUS_LIST_REFRESH_INTERVAL_MAX",
        default = "default_status_list_refresh_interval_max"
    )]
    #[serde(deserialize_with = "deserialize_status_list_refresh_interval_max")]
    pub status_list_refresh_interval_max: u64,

    /// Base refresh interval, in seconds, for periodic background refresh of
    /// remote policy stores (`CjarUrl` / `LockServer`). `0` disables refresh and
    /// preserves the load-once-at-startup behavior. Non-zero values below the
    /// `MIN_REFRESH_INTERVAL_SECS` floor are clamped at service-init time (with
    /// a `WARN` log emitted) so the worker never busy-polls the upstream — see
    /// [`PolicyStoreConfig::effective_refresh_interval`]. A server
    /// `Cache-Control: max-age` / `Expires` hint can *shorten* the next
    /// interval but never extends it.
    #[serde(rename = "CEDARLING_POLICY_STORE_REFRESH_INTERVAL", default)]
    #[serde(deserialize_with = "deserialize_or_parse_string_as_json")]
    pub policy_store_refresh_interval_secs: u64,
}

impl Default for BootstrapConfigRaw {
    fn default() -> Self {
        serde_json::from_value(serde_json::json!({"CEDARLING_APPLICATION_NAME":""}))
            .expect("BootstrapConfigRaw should be deserialized from empty json object")
    }
}

impl BootstrapConfigRaw {
    /// Construct `BootstrapConfig` from environment variables and `BootstrapConfigRaw` config.
    /// Environment variables have bigger priority.
    //
    // Simple implementation that map input structure to JSON map
    // and map environment variables with prefix `CEDARLING_` to JSON map. And merge it.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn from_raw_config_and_env(
        raw: Option<BootstrapConfigRaw>,
    ) -> Result<Self, BootstrapConfigLoadingError> {
        let mut json_config_params = serde_json::json!(raw.unwrap_or_default())
            .as_object()
            .map(std::borrow::ToOwned::to_owned)
            .unwrap_or_default();

        for (k, v) in get_cedarling_env_vars() {
            // update map with values from env variables
            json_config_params.insert(k, v);
        }

        Ok(BootstrapConfigRaw::deserialize(json_config_params)?)
    }
}

/// Get environment variables related to `Cedarling`
#[cfg(not(target_arch = "wasm32"))]
fn get_cedarling_env_vars() -> HashMap<String, serde_json::Value> {
    env::vars()
        .filter_map(|(k, v)| {
            k.starts_with("CEDARLING_")
                .then_some((k, serde_json::json!(v)))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jwt_config::{MIN_JWKS_REFRESH_SECS, MIN_STATUS_LIST_REFRESH_SECS};
    use std::{
        env,
        sync::{LazyLock, Mutex},
    };
    use test_utils::assert_eq;

    static ENV_MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    fn with_env_vars<F>(vars: &[(&str, &str)], test: F)
    where
        F: FnOnce(),
    {
        // Ensure only one test modifies env vars at a time
        let _lock = ENV_MUTEX.lock().unwrap();

        // Create a fresh environment by clearing all CEDARLING_* vars
        let mut all_vars = Vec::new();
        for (key, value) in env::vars() {
            let key_clone = key.clone();
            all_vars.push((key, value));
            unsafe {
                env::remove_var(&key_clone);
            }
        }

        // Set new env vars
        for (key, value) in vars {
            unsafe {
                env::set_var(key, value);
            }
        }

        test();

        // Clean up
        for (key, _) in vars {
            unsafe {
                env::remove_var(key);
            }
        }

        // Restore original environment
        for (key, value) in all_vars {
            unsafe {
                env::set_var(&key, value);
            }
        }
    }

    /// Tests that the default configuration values are correctly set when no environment variables
    /// or raw config is provided.
    #[test]
    fn test_from_raw_config_and_env_defaults() {
        with_env_vars(&[], || {
            let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();
            assert_eq!(
                config.application_name, "",
                "Application name should be empty by default"
            );
            assert_eq!(
                config.policy_store_uri, None,
                "Policy store URI should be None by default"
            );
            assert_eq!(
                config.log_type,
                LoggerType::Off,
                "Logger should be off by default"
            );
            assert_eq!(
                config.log_level,
                LogLevel::WARN,
                "Default log level should be WARN"
            );
            assert_eq!(config.log_ttl, None, "Log TTL should be None by default");
            assert_eq!(
                config.decision_log_default_jwt_id, "jti",
                "Default JWT ID for decision logging should be 'jti'"
            );
            assert_eq!(
                config.lock_transport,
                LockTransport::Rest,
                "Default transport should be REST"
            );
        });
    }

    /// Tests that configuration values are correctly set when only a raw config is provided.
    #[test]
    fn test_from_raw_config_and_env() {
        with_env_vars(&[], || {
            let raw = BootstrapConfigRaw {
                application_name: "test-app".to_string(),
                log_type: LoggerType::Memory,
                log_level: LogLevel::DEBUG,
                ..Default::default()
            };

            let config = BootstrapConfigRaw::from_raw_config_and_env(Some(raw)).unwrap();

            assert_eq!(config.application_name, "test-app");
            assert_eq!(config.log_type, LoggerType::Memory);
            assert_eq!(config.log_level, LogLevel::DEBUG);
        });
    }

    /// Tests that configuration values are correctly set when only environment variables are provided.
    #[test]
    fn test_from_raw_config_and_env_with_env_vars() {
        with_env_vars(
            &[
                ("CEDARLING_APPLICATION_NAME", "env-app"),
                ("CEDARLING_LOG_TYPE", "memory"),
                ("CEDARLING_LOG_LEVEL", "DEBUG"),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(config.application_name, "env-app");
                assert_eq!(config.log_type, LoggerType::Memory);
                assert_eq!(config.log_level, LogLevel::DEBUG);
            },
        );
    }

    /// Tests that environment variables override raw config values when both are provided.
    #[test]
    fn test_from_raw_config_and_env_vars_override() {
        with_env_vars(
            &[
                ("CEDARLING_APPLICATION_NAME", "env-app"),
                ("CEDARLING_LOG_TYPE", "memory"),
            ],
            || {
                let raw = BootstrapConfigRaw {
                    application_name: "test-app".to_string(),
                    log_type: LoggerType::StdOut,
                    log_level: LogLevel::INFO,
                    ..Default::default()
                };

                let config = BootstrapConfigRaw::from_raw_config_and_env(Some(raw)).unwrap();

                // Env vars should override raw config
                assert_eq!(config.application_name, "env-app");
                assert_eq!(config.log_type, LoggerType::Memory);

                // Fields not set in env should use raw config values
                assert_eq!(config.log_level, LogLevel::INFO);
            },
        );
    }

    /// Tests that an error is returned when an invalid environment variable value is provided.
    #[test]
    fn test_from_raw_config_and_env_invalid_env_var() {
        with_env_vars(&[("CEDARLING_LOG_TYPE", "invalid")], || {
            let result = BootstrapConfigRaw::from_raw_config_and_env(None);
            assert!(result.is_err());
        });
    }

    /// Tests that empty string values in environment variables are handled correctly.
    #[test]
    fn test_from_raw_config_and_env_empty_strings() {
        with_env_vars(
            &[
                ("CEDARLING_APPLICATION_NAME", ""),
                ("CEDARLING_POLICY_STORE_URI", ""),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(config.application_name, "");
                assert_eq!(config.policy_store_uri, None);
            },
        );
    }

    /// Tests that environment variables for trusted issuer loader are parsed correctly.
    #[test]
    fn test_trusted_issuer_loader_env_vars() {
        with_env_vars(
            &[
                ("CEDARLING_TRUSTED_ISSUER_LOADER_TYPE", "ASYNC"),
                ("CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS", "5"),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(
                    config.trusted_issuer_loader_type,
                    TrustedIssuerLoaderTypeRaw::Async,
                    "Loader type should be Async from env var"
                );
                assert_eq!(
                    config.trusted_issuer_loader_workers, 5,
                    "Worker count should be 5 from env var"
                );
            },
        );
    }

    /// Tests JSON deserialization for trusted issuer loader fields.
    #[test]
    fn test_trusted_issuer_loader_json_deserialization() {
        // Valid JSON values
        let valid_cases = vec![
            (
                r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_TYPE": "SYNC", "CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS": 3}"#,
                TrustedIssuerLoaderTypeRaw::Sync,
                3,
            ),
            (
                r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_TYPE": "ASYNC", "CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS": 1}"#,
                TrustedIssuerLoaderTypeRaw::Async,
                1,
            ),
        ];

        for (json, expected_type, expected_workers) in valid_cases {
            let config: BootstrapConfigRaw = serde_json::from_str(json).unwrap();
            assert_eq!(
                config.trusted_issuer_loader_type, expected_type,
                "Loader type mismatch for JSON: {}",
                json
            );
            assert_eq!(
                config.trusted_issuer_loader_workers, expected_workers,
                "Worker count mismatch for JSON: {}",
                json
            );
        }

        // Invalid JSON values should produce errors
        let invalid_cases = vec![
            r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_TYPE": "INVALID"}"#,
            r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS": -1}"#,
            r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS": "not_a_number"}"#,
            r#"{"CEDARLING_APPLICATION_NAME": "", "CEDARLING_TRUSTED_ISSUER_LOADER_TYPE": 123}"#,
        ];

        for json in invalid_cases {
            let result: Result<BootstrapConfigRaw, _> = serde_json::from_str(json);
            result.expect_err(&format!("Should fail to parse invalid JSON: {json}"));
        }
    }

    /// Tests `CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS` to get clamped minimum value
    #[test]
    fn test_trusted_issuer_loader_claps_min() {
        with_env_vars(&[("CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS", "0")], || {
            let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

            assert_eq!(
                config.trusted_issuer_loader_workers,
                WorkersCount::MIN,
                "Default worker count should be {}",
                WorkersCount::MIN.get()
            );
        });
    }

    /// Tests `CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS` to get clamped max value
    #[test]
    fn test_trusted_issuer_loader_claps_max() {
        let max_val = (WorkersCount::MAX.get() + 100).to_string();

        with_env_vars(
            &[("CEDARLING_TRUSTED_ISSUER_LOADER_WORKERS", max_val.as_str())],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(
                    config.trusted_issuer_loader_workers,
                    WorkersCount::MAX,
                    "Default worker count should be {}",
                    WorkersCount::MAX.get()
                );
            },
        );
    }

    #[test]
    fn test_jwks_refresh_interval_from_env_var() {
        with_env_vars(
            &[
                ("CEDARLING_JWKS_REFRESH_INTERVAL", "30"),
                ("CEDARLING_JWKS_REFRESH_MIN_INTERVAL", "60"),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(
                    config.jwks_refresh_interval,
                    Some(30),
                    "JWKS refresh interval should match environment value"
                );
                assert_eq!(
                    config.jwks_refresh_min_interval, 60,
                    "JWKS refresh min interval should match environment value"
                );
            },
        );
    }

    #[test]
    fn test_jwks_refresh_interval_clamps_min() {
        with_env_vars(
            &[
                ("CEDARLING_JWKS_REFRESH_INTERVAL", "0"),
                ("CEDARLING_JWKS_REFRESH_MIN_INTERVAL", "0"),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(
                    config.jwks_refresh_interval,
                    Some(MIN_JWKS_REFRESH_SECS),
                    "JWKS refresh interval should be clamped to minimum"
                );
                assert_eq!(
                    config.jwks_refresh_min_interval, MIN_JWKS_REFRESH_SECS,
                    "JWKS refresh min interval should be clamped to minimum"
                );
            },
        );
    }

    #[test]
    fn test_jwks_refresh_interval_clamps_below_min() {
        with_env_vars(
            &[
                ("CEDARLING_JWKS_REFRESH_INTERVAL", "3"),
                ("CEDARLING_JWKS_REFRESH_MIN_INTERVAL", "3"),
            ],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();

                assert_eq!(
                    config.jwks_refresh_interval,
                    Some(MIN_JWKS_REFRESH_SECS),
                    "JWKS refresh interval should be clamped to minimum"
                );
                assert_eq!(
                    config.jwks_refresh_min_interval, MIN_JWKS_REFRESH_SECS,
                    "JWKS refresh min interval should be clamped to minimum"
                );
            },
        );
    }

    #[test]
    fn test_status_list_refresh_interval_max_default() {
        with_env_vars(&[], || {
            let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();
            assert_eq!(
                config.status_list_refresh_interval_max,
                JwtConfig::DEFAULT_STATUS_LIST_REFRESH_INTERVAL_MAX_SECS,
                "missing env var should resolve to the JwtConfig default"
            );
        });
    }

    #[test]
    fn test_status_list_refresh_interval_max_from_env() {
        with_env_vars(
            &[("CEDARLING_JWT_STATUS_LIST_REFRESH_INTERVAL_MAX", "120")],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();
                assert_eq!(
                    config.status_list_refresh_interval_max, 120,
                    "status list refresh max should match the value supplied via env var"
                );
            },
        );
    }

    #[test]
    fn test_status_list_refresh_interval_max_zero_uses_default() {
        with_env_vars(
            &[("CEDARLING_JWT_STATUS_LIST_REFRESH_INTERVAL_MAX", "0")],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();
                assert_eq!(
                    config.status_list_refresh_interval_max,
                    JwtConfig::DEFAULT_STATUS_LIST_REFRESH_INTERVAL_MAX_SECS,
                    "0 should be treated as 'use the default'"
                );
            },
        );
    }

    #[test]
    fn test_status_list_refresh_interval_max_clamps_below_min() {
        with_env_vars(
            &[("CEDARLING_JWT_STATUS_LIST_REFRESH_INTERVAL_MAX", "2")],
            || {
                let config = BootstrapConfigRaw::from_raw_config_and_env(None).unwrap();
                assert_eq!(
                    config.status_list_refresh_interval_max, MIN_STATUS_LIST_REFRESH_SECS,
                    "non-zero values below the minimum should be clamped"
                );
            },
        );
    }
}