cedarling 0.0.42

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
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
// 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.

//! Cedar Value Mapping
//!
//! Provides bidirectional conversion between JSON values and Cedar values,
//! with support for all Cedar data types including extension types.

use crate::context_data_api::error::ValueMappingError;

use super::CedarType;
use cedar_policy::{EntityId, EntityTypeName, EntityUid, RestrictedExpression};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::net::IpAddr;
use std::str::FromStr;

/// Represents a parsed Cedar entity reference.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct EntityReference {
    /// The entity type (e.g., "User", "`Namespace::Type`")
    pub entity_type: String,
    /// The entity identifier
    pub entity_id: String,
}

/// Represents a detected extension type with its parsed value.
#[derive(Debug, Clone, PartialEq)]
pub enum ExtensionValue {
    /// An IP address (IPv4 or IPv6) or CIDR range
    IpAddr(String),
    /// A fixed-precision decimal number (up to 4 decimal places)
    Decimal(String),
    /// An instant of time with millisecond precision (RFC 3339 / ISO 8601)
    DateTime(String),
    /// A duration of time with millisecond precision
    Duration(String),
}

/// Mapper for bidirectional JSON ↔ Cedar value conversion.
///
/// Provides methods to convert between `serde_json::Value` and Cedar's
/// `RestrictedExpression`, with support for all Cedar data types including
/// extension types (IP addresses, decimals).
#[derive(Debug, Clone)]
pub struct CedarValueMapper {
    /// Whether to auto-detect extension types from string patterns
    auto_detect_extensions: bool,
    /// Maximum allowed value size in bytes (0 = no limit)
    max_value_size: usize,
}

impl Default for CedarValueMapper {
    fn default() -> Self {
        Self::new()
    }
}

impl CedarValueMapper {
    /// Create a new mapper with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            auto_detect_extensions: true,
            max_value_size: 0,
        }
    }

    /// Create a mapper with auto-detection of extension types disabled.
    #[must_use]
    pub fn new_without_auto_detect() -> Self {
        Self {
            auto_detect_extensions: false,
            max_value_size: 0,
        }
    }

    /// Set the maximum allowed value size in bytes.
    ///
    /// A value of 0 means no limit.
    #[must_use]
    pub fn with_max_size(mut self, max_size: usize) -> Self {
        self.max_value_size = max_size;
        self
    }

    /// Convert a JSON value to a Cedar `RestrictedExpression`.
    ///
    /// Supports all Cedar primitive types, collections, and extension types.
    /// Null values are not supported and will return an error.
    pub fn json_to_cedar(
        &self,
        value: &Value,
    ) -> Result<Option<RestrictedExpression>, ValueMappingError> {
        // Check size limit
        if self.max_value_size > 0 {
            let size = Self::estimate_value_size(value);
            if size > self.max_value_size {
                return Err(ValueMappingError::ValueTooLarge {
                    size,
                    limit: self.max_value_size,
                });
            }
        }

        self.convert_value(value)
    }

    /// Convert a JSON value to Cedar, returning the inferred Cedar type.
    ///
    /// This is useful when you need both the expression and type information.
    pub fn json_to_cedar_with_type(
        &self,
        value: &Value,
    ) -> Result<Option<(RestrictedExpression, CedarType)>, ValueMappingError> {
        let cedar_type = CedarType::from_value(value);
        let expr = self.json_to_cedar(value)?;
        Ok(expr.map(|e| (e, cedar_type)))
    }

    /// Convert a Cedar expression back to JSON format.
    ///
    /// This is useful for serializing Cedar values for storage or transmission.
    /// Entity references are converted to `{"type": "...", "id": "..."}` format.
    /// Extension types are converted to `{"__extn": {"fn": "...", "arg": "..."}}` format.
    ///
    /// # Note
    ///
    /// This method works with the JSON representation of Cedar values,
    /// not the evaluated result. For evaluated results, use `eval_result_to_json`.
    pub fn cedar_to_json(expr_json: &Value) -> Result<Value, ValueMappingError> {
        // Cedar's JSON format uses special markers for extension types and entities
        // This method normalizes those to a consistent format
        Self::normalize_cedar_json(expr_json)
    }

    /// Access a nested value using dot notation.
    pub fn get_nested<'a>(value: &'a Value, path: &str) -> Result<&'a Value, ValueMappingError> {
        if path.is_empty() {
            return Ok(value);
        }

        let mut current = value;
        for component in path.split('.') {
            if component.is_empty() {
                return Err(ValueMappingError::InvalidPath {
                    path: path.to_string(),
                });
            }

            current = match current {
                Value::Object(obj) => {
                    obj.get(component)
                        .ok_or_else(|| ValueMappingError::PathNotFound {
                            path: path.to_string(),
                        })?
                },
                Value::Array(arr) => {
                    // Support numeric indexing for arrays
                    let index: usize =
                        component
                            .parse()
                            .map_err(|_| ValueMappingError::PathNotFound {
                                path: path.to_string(),
                            })?;
                    arr.get(index)
                        .ok_or_else(|| ValueMappingError::PathNotFound {
                            path: path.to_string(),
                        })?
                },
                _ => {
                    return Err(ValueMappingError::PathNotFound {
                        path: path.to_string(),
                    });
                },
            };
        }

        Ok(current)
    }

    /// Set a value at a nested path, creating intermediate objects as needed.
    pub fn set_nested(
        value: &mut Value,
        path: &str,
        new_value: Value,
    ) -> Result<(), ValueMappingError> {
        if path.is_empty() {
            *value = new_value;
            return Ok(());
        }

        let components: Vec<&str> = path.split('.').collect();
        let mut current = value;

        for (i, component) in components.iter().enumerate() {
            if component.is_empty() {
                return Err(ValueMappingError::InvalidPath {
                    path: path.to_string(),
                });
            }

            let is_last = i == components.len() - 1;

            if is_last {
                // Set the value
                let Value::Object(obj) = current else {
                    return Err(ValueMappingError::TypeMismatch {
                        expected: "object".to_string(),
                        actual: Self::value_type_name(current).to_string(),
                    });
                };
                obj.insert((*component).to_string(), new_value);
                return Ok(());
            }

            // Navigate or create intermediate objects
            let Value::Object(obj) = current else {
                return Err(ValueMappingError::TypeMismatch {
                    expected: "object".to_string(),
                    actual: Self::value_type_name(current).to_string(),
                });
            };
            current = obj
                .entry((*component).to_string())
                .or_insert_with(|| Value::Object(Map::new()));
        }

        Ok(())
    }

    /// Detect if a string value represents a Cedar extension type.
    ///
    /// Detects the following extension types:
    /// - `ipaddr`: IP addresses (IPv4/IPv6) and CIDR ranges (e.g., "192.168.1.1", "10.0.0.0/8")
    /// - `decimal`: Fixed-precision decimals (e.g., "3.14", "-12.345")
    /// - `datetime`: ISO 8601 / RFC 3339 timestamps (e.g., "2024-10-15T11:35:00Z")
    /// - `duration`: Duration strings (e.g., "2h30m", "1d12h", "500ms")
    ///
    /// See: <https://docs.cedarpolicy.com/policies/syntax-datatypes.html#datatype-extension>
    #[must_use]
    pub fn detect_extension(value: &str) -> Option<ExtensionValue> {
        // Check for plain IP address (IPv4 or IPv6)
        if IpAddr::from_str(value).is_ok() {
            return Some(ExtensionValue::IpAddr(value.to_string()));
        }

        // Check for CIDR notation (e.g., "192.168.1.0/24", "fe80::/10")
        if let Some((ip_part, prefix_part)) = value.split_once('/')
            && let Ok(ip) = IpAddr::from_str(ip_part)
            && let Ok(prefix_len) = prefix_part.parse::<u8>()
        {
            // Validate prefix length: 0-32 for IPv4, 0-128 for IPv6
            let max_prefix = if ip.is_ipv4() { 32 } else { 128 };
            if prefix_len <= max_prefix {
                return Some(ExtensionValue::IpAddr(value.to_string()));
            }
        }

        // Check for datetime (ISO 8601 / RFC 3339 format)
        // Examples: "2024-10-15", "2024-10-15T11:35:00Z", "2024-10-15T11:35:00.000+0100"
        if Self::is_datetime_format(value) {
            return Some(ExtensionValue::DateTime(value.to_string()));
        }

        // Check for duration format (e.g., "2h30m", "-1d12h", "500ms")
        if Self::is_duration_format(value) {
            return Some(ExtensionValue::Duration(value.to_string()));
        }

        // Check for decimal (must contain decimal point and be parseable as f64)
        // Must have exactly one decimal point, not end with it, and reject exponent notation
        if value.contains('.')
            && !value.contains('e')
            && !value.contains('E')
            && !value.ends_with('.')
            && value.chars().filter(|&c| c == '.').count() == 1
        {
            // Parse as f64 to validate numeric format, but ensure it's fixed-point
            if value.parse::<f64>().is_ok() {
                // Additional check: ensure there's at least one digit before and after the decimal point
                if let Some(dot_pos) = value.find('.') {
                    let before_dot = &value[..dot_pos];
                    let after_dot = &value[dot_pos + 1..];
                    // Require at least one ASCII digit in before_dot (optionally preceded by a single '+' or '-')
                    let before_has_digit = before_dot.chars().any(|c| c.is_ascii_digit());
                    let before_valid =
                        if before_dot.is_empty() || before_dot == "+" || before_dot == "-" {
                            false // Must have at least one digit, not just sign or empty
                        } else {
                            // Must have at least one digit, and all chars are digits or a single leading sign
                            let has_leading_sign =
                                before_dot.starts_with('+') || before_dot.starts_with('-');
                            let sign_count = before_dot
                                .chars()
                                .filter(|c| *c == '+' || *c == '-')
                                .count();
                            before_has_digit
                                && before_dot
                                    .chars()
                                    .all(|c| c.is_ascii_digit() || c == '+' || c == '-')
                                && (!has_leading_sign || sign_count == 1)
                        };
                    // Require at least one ASCII digit in after_dot, and all chars are digits
                    let after_ok = !after_dot.is_empty()
                        && after_dot.chars().all(|c| c.is_ascii_digit())
                        && after_dot.chars().any(|c| c.is_ascii_digit());
                    // Both sides must have digits
                    if before_valid && after_ok {
                        return Some(ExtensionValue::Decimal(value.to_string()));
                    }
                }
            }
        }

        None
    }

    /// Check if a string looks like an ISO 8601 / RFC 3339 datetime.
    ///
    /// Uses real parsing to validate semantic correctness, not just byte patterns.
    /// Supported formats:
    /// - "2024-10-15" (date only)
    /// - "2024-10-15T11:35:00Z" (UTC)
    /// - "2024-10-15T11:35:00.000Z" (UTC with milliseconds)
    /// - "2024-10-15T11:35:00+0100" (with timezone offset)
    /// - "2024-10-15T11:35:00.000+0100" (with timezone and milliseconds)
    fn is_datetime_format(value: &str) -> bool {
        use chrono::{DateTime, NaiveDate};

        // Try RFC 3339 parsing first (handles full datetime with timezone)
        if DateTime::parse_from_rfc3339(value).is_ok() {
            return true;
        }

        // Try ISO 8601 format with offset without colon (e.g., "+0100")
        if DateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%z").is_ok() {
            return true;
        }

        // Try ISO 8601 format with offset and fractional seconds
        if DateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f%z").is_ok() {
            return true;
        }

        // Try date-only format (YYYY-MM-DD)
        if NaiveDate::parse_from_str(value, "%Y-%m-%d").is_ok() {
            return true;
        }

        false
    }

    /// Check if a string looks like a Cedar duration format.
    ///
    /// Enforces unit ordering: d > h > m > s > ms (descending rank order).
    /// Supported formats:
    /// - "2h30m" (hours and minutes)
    /// - "-1d12h" (negative, days and hours)
    /// - "1h30m45s" (hours, minutes, seconds)
    /// - "500ms" (milliseconds only)
    /// - "1d" (days only)
    fn is_duration_format(value: &str) -> bool {
        use crate::context_data_api::entry::UnitRank;

        if value.is_empty() {
            return false;
        }

        let bytes = value.as_bytes();
        let mut i = 0;

        if bytes[i] == b'-' {
            i += 1;
            if i == bytes.len() {
                return false;
            }
        }

        let mut last_rank = UnitRank::Start;

        while i < bytes.len() {
            let start = i;
            while i < bytes.len() && bytes[i].is_ascii_digit() {
                i += 1;
            }
            if start == i {
                return false;
            }

            let (current_rank, consumed) = match bytes.get(i) {
                Some(b'd') if last_rank < UnitRank::Days => (UnitRank::Days, 1),
                Some(b'h') if last_rank < UnitRank::Hours => (UnitRank::Hours, 1),
                Some(b's') if last_rank < UnitRank::Seconds => (UnitRank::Seconds, 1),
                Some(b'm') => {
                    if i + 1 < bytes.len() && bytes[i + 1] == b's' {
                        if last_rank < UnitRank::Millis {
                            (UnitRank::Millis, 2)
                        } else {
                            return false;
                        }
                    } else if last_rank < UnitRank::Minutes {
                        (UnitRank::Minutes, 1)
                    } else {
                        return false;
                    }
                },
                _ => return false,
            };

            last_rank = current_rank;
            i += consumed;
        }

        true
    }

    /// Check if a value represents a Cedar entity reference.
    #[must_use]
    pub fn is_entity_reference(value: &Value) -> bool {
        if let Value::Object(obj) = value {
            obj.len() == 2
                && obj.get("type").is_some_and(serde_json::Value::is_string)
                && obj.get("id").is_some_and(serde_json::Value::is_string)
        } else {
            false
        }
    }

    /// Parse an entity reference from JSON.
    pub(super) fn parse_entity_reference(
        value: &Value,
    ) -> Result<EntityReference, ValueMappingError> {
        if let Value::Object(obj) = value {
            let entity_type = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
                ValueMappingError::InvalidEntityReference {
                    reason: "missing or invalid 'type' field".to_string(),
                }
            })?;

            let entity_id = obj.get("id").and_then(|v| v.as_str()).ok_or_else(|| {
                ValueMappingError::InvalidEntityReference {
                    reason: "missing or invalid 'id' field".to_string(),
                }
            })?;

            Ok(EntityReference {
                entity_type: entity_type.to_string(),
                entity_id: entity_id.to_string(),
            })
        } else {
            Err(ValueMappingError::InvalidEntityReference {
                reason: "expected object with 'type' and 'id' fields".to_string(),
            })
        }
    }

    /// Get the JSON type name of a value.
    #[must_use]
    pub fn value_type_name(value: &Value) -> &'static str {
        match value {
            Value::Null => "null",
            Value::Bool(_) => "bool",
            Value::Number(_) => "number",
            Value::String(_) => "string",
            Value::Array(_) => "array",
            Value::Object(_) => "object",
        }
    }

    // Internal conversion method
    fn convert_value(
        &self,
        value: &Value,
    ) -> Result<Option<RestrictedExpression>, ValueMappingError> {
        let expr = match value {
            Value::Null => return Err(ValueMappingError::NullNotSupported),
            Value::Bool(b) => RestrictedExpression::new_bool(*b),
            Value::Number(n) => Self::convert_number(n)?,
            Value::String(s) => self.convert_string(s),
            Value::Array(arr) => self.convert_array(arr)?,
            Value::Object(obj) => return self.convert_object(value, obj),
        };

        Ok(Some(expr))
    }

    /// Convert a JSON number to a Cedar expression.
    fn convert_number(n: &serde_json::Number) -> Result<RestrictedExpression, ValueMappingError> {
        if let Some(i) = n.as_i64() {
            Ok(RestrictedExpression::new_long(i))
        } else if let Some(f) = n.as_f64() {
            // Convert floating point to decimal extension
            // Format to 4 decimal places to avoid scientific notation and ensure Cedar compatibility
            let decimal_str = format!("{f:.4}");
            Ok(RestrictedExpression::new_decimal(decimal_str))
        } else {
            Err(ValueMappingError::NumberNotRepresentable {
                value: n.to_string(),
            })
        }
    }

    /// Convert a JSON string to a Cedar expression.
    fn convert_string(&self, s: &str) -> RestrictedExpression {
        if self.auto_detect_extensions {
            match Self::detect_extension(s) {
                Some(ExtensionValue::IpAddr(ip)) => RestrictedExpression::new_ip(ip),
                Some(ExtensionValue::Decimal(d)) => RestrictedExpression::new_decimal(d),
                Some(ExtensionValue::DateTime(dt)) => RestrictedExpression::new_datetime(dt),
                Some(ExtensionValue::Duration(dur)) => RestrictedExpression::new_duration(dur),
                None => RestrictedExpression::new_string(s.to_string()),
            }
        } else {
            RestrictedExpression::new_string(s.to_string())
        }
    }

    /// Convert a JSON array to a Cedar set expression.
    fn convert_array(&self, arr: &[Value]) -> Result<RestrictedExpression, ValueMappingError> {
        let mut exprs = Vec::with_capacity(arr.len());

        for item in arr {
            match self.convert_value(item)? {
                Some(expr) => exprs.push(expr),
                None => {
                    return Err(ValueMappingError::NullNotSupported);
                },
            }
        }

        Ok(RestrictedExpression::new_set(exprs))
    }

    /// Convert a JSON object to a Cedar expression (entity, extension, or record).
    fn convert_object(
        &self,
        value: &Value,
        obj: &serde_json::Map<String, Value>,
    ) -> Result<Option<RestrictedExpression>, ValueMappingError> {
        // Check for entity reference
        if Self::is_entity_reference(value) {
            return Self::convert_entity_reference(value);
        }

        // Check for extension type markers (__extn)
        if let Some(extn) = obj.get("__extn") {
            return Self::convert_extension_marker(extn);
        }

        // Regular record
        let mut fields = HashMap::with_capacity(obj.len());

        for (key, val) in obj {
            let expr = self.convert_value(val)?;
            fields.insert(
                key.clone(),
                expr.expect("convert_value should always return Some"),
            );
        }

        Ok(Some(RestrictedExpression::new_record(fields)?))
    }

    /// Convert an entity reference to a Cedar entity UID expression.
    fn convert_entity_reference(
        value: &Value,
    ) -> Result<Option<RestrictedExpression>, ValueMappingError> {
        let entity_ref = Self::parse_entity_reference(value)?;

        let entity_type = EntityTypeName::from_str(&entity_ref.entity_type).map_err(|e| {
            ValueMappingError::InvalidEntityReference {
                reason: format!("invalid entity type '{}': {}", entity_ref.entity_type, e),
            }
        })?;

        let entity_id = EntityId::from_str(&entity_ref.entity_id).map_err(|e| {
            ValueMappingError::InvalidEntityReference {
                reason: format!("invalid entity id '{}': {}", entity_ref.entity_id, e),
            }
        })?;

        let uid = EntityUid::from_type_name_and_id(entity_type, entity_id);
        Ok(Some(RestrictedExpression::new_entity_uid(uid)))
    }

    /// Convert an extension marker (__extn) to a Cedar extension expression.
    fn convert_extension_marker(
        extn: &Value,
    ) -> Result<Option<RestrictedExpression>, ValueMappingError> {
        let extn_obj =
            extn.as_object()
                .ok_or_else(|| ValueMappingError::InvalidExtensionFormat {
                    extension_type: "__extn".to_string(),
                    value: extn.to_string(),
                })?;

        let fn_name = extn_obj.get("fn").and_then(|v| v.as_str()).ok_or_else(|| {
            ValueMappingError::InvalidExtensionFormat {
                extension_type: "__extn".to_string(),
                value: format!(
                    "missing or invalid 'fn' field in {}",
                    serde_json::to_string(extn_obj).unwrap_or_default()
                ),
            }
        })?;

        let arg = extn_obj
            .get("arg")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ValueMappingError::InvalidExtensionFormat {
                extension_type: fn_name.to_string(),
                value: format!(
                    "missing or invalid 'arg' field in {}",
                    serde_json::to_string(extn_obj).unwrap_or_default()
                ),
            })?;

        match fn_name {
            "decimal" => Ok(Some(RestrictedExpression::new_decimal(arg))),
            "ip" | "ipaddr" => Ok(Some(RestrictedExpression::new_ip(arg))),
            "datetime" => Ok(Some(RestrictedExpression::new_datetime(arg))),
            "duration" => Ok(Some(RestrictedExpression::new_duration(arg))),
            _ => Err(ValueMappingError::InvalidExtensionFormat {
                extension_type: fn_name.to_string(),
                value: arg.to_string(),
            }),
        }
    }

    /// Estimates the JSON-serialized size of a value in bytes.
    ///
    /// This provides a rough estimate for size limiting without actual serialization.
    fn estimate_value_size(value: &Value) -> usize {
        match value {
            // "null" = 4 chars
            Value::Null => 4,
            // "true" or "false" = 4-5 chars, use max
            Value::Bool(_) => 5,
            // Number as string representation
            Value::Number(n) => n.to_string().len(),
            // String content + 2 for surrounding quotes
            Value::String(s) => s.len() + 2,
            // 2 for brackets [] + elements with commas
            Value::Array(arr) => {
                2 + arr
                    .iter()
                    .map(|v| Self::estimate_value_size(v) + 1) // +1 for comma separator
                    .sum::<usize>()
            },
            // 2 for braces {} + key-value pairs
            Value::Object(obj) => {
                2 + obj
                    .iter()
                    .map(|(k, v)| k.len() + 3 + Self::estimate_value_size(v) + 1) // +3 for quotes and colon, +1 for comma
                    .sum::<usize>()
            },
        }
    }

    // Normalize Cedar JSON format to standard JSON
    fn normalize_cedar_json(value: &Value) -> Result<Value, ValueMappingError> {
        match value {
            Value::Object(obj) => {
                // Check for __entity marker (Cedar format for entity references)
                if let Some(entity) = obj.get("__entity")
                    && let Some(entity_obj) = entity.as_object()
                {
                    return Ok(serde_json::json!({
                        "type": entity_obj.get("type"),
                        "id": entity_obj.get("id")
                    }));
                }

                // Check for __extn marker (extension types)
                // Preserve the entire wrapper so json_to_cedar can consume it
                if obj.contains_key("__extn") {
                    return Ok(Value::Object(obj.clone()));
                }

                // Regular object - recursively process
                let mut normalized = Map::new();
                for (key, val) in obj {
                    normalized.insert(key.clone(), Self::normalize_cedar_json(val)?);
                }
                Ok(Value::Object(normalized))
            },
            Value::Array(arr) => {
                let normalized: Result<Vec<_>, _> =
                    arr.iter().map(Self::normalize_cedar_json).collect();
                Ok(Value::Array(normalized?))
            },
            // Primitives pass through unchanged
            _ => Ok(value.clone()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use test_utils::assert_eq;

    #[test]
    fn test_json_to_cedar_primitives() {
        let mapper = CedarValueMapper::new();

        // Boolean
        let result = mapper.json_to_cedar(&json!(true));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());

        // Long
        let result = mapper.json_to_cedar(&json!(42));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());

        // String
        let result = mapper.json_to_cedar(&json!("hello"));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_json_to_cedar_null_error() {
        let mapper = CedarValueMapper::new();
        let result = mapper.json_to_cedar(&json!(null));
        assert!(
            matches!(result, Err(ValueMappingError::NullNotSupported)),
            "expected Err(ValueMappingError::NullNotSupported), got: {result:?}"
        );
    }

    #[test]
    fn test_json_to_cedar_collections() {
        let mapper = CedarValueMapper::new();

        // Set (array)
        let result = mapper.json_to_cedar(&json!([1, 2, 3]));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());

        // Record (object)
        let result = mapper.json_to_cedar(&json!({"name": "Alice", "age": 30}));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_extension_detection_ipaddr() {
        // IPv4
        assert!(matches!(
            CedarValueMapper::detect_extension("192.168.1.1"),
            Some(ExtensionValue::IpAddr(_))
        ));

        // IPv6
        assert!(matches!(
            CedarValueMapper::detect_extension("::1"),
            Some(ExtensionValue::IpAddr(_))
        ));

        // IPv4 CIDR notation
        assert!(matches!(
            CedarValueMapper::detect_extension("10.0.0.0/8"),
            Some(ExtensionValue::IpAddr(_))
        ));
        assert!(matches!(
            CedarValueMapper::detect_extension("192.168.1.0/24"),
            Some(ExtensionValue::IpAddr(_))
        ));

        // IPv6 CIDR notation
        assert!(matches!(
            CedarValueMapper::detect_extension("fe80::/10"),
            Some(ExtensionValue::IpAddr(_))
        ));
        assert!(matches!(
            CedarValueMapper::detect_extension("2001:db8::/32"),
            Some(ExtensionValue::IpAddr(_))
        ));

        // Invalid CIDR prefix (too large for IPv4)
        assert!(CedarValueMapper::detect_extension("192.168.1.0/33").is_none());

        // Not an IP
        assert!(CedarValueMapper::detect_extension("hello").is_none());
    }

    #[test]
    fn test_extension_detection_decimal() {
        assert!(matches!(
            CedarValueMapper::detect_extension("3.14"),
            Some(ExtensionValue::Decimal(_))
        ));

        // Integer is not decimal
        assert!(
            CedarValueMapper::detect_extension("42").is_none(),
            "integer should not be detected as decimal"
        );

        // Multiple dots is not decimal (would be detected as IP first if valid)
        assert!(
            CedarValueMapper::detect_extension("1.2.3.4.5").is_none(),
            "multiple dots should not be detected as decimal"
        );

        // Negative cases: should reject invalid decimal formats
        assert!(
            CedarValueMapper::detect_extension(".5").is_none(),
            "decimal without digits before dot should be rejected"
        );
        assert!(
            CedarValueMapper::detect_extension("-.5").is_none(),
            "decimal with only sign before dot should be rejected"
        );
        assert!(
            CedarValueMapper::detect_extension("5.").is_none(),
            "decimal with trailing dot should be rejected"
        );
        assert!(
            CedarValueMapper::detect_extension("1e5").is_none(),
            "scientific notation should be rejected"
        );
        assert!(
            CedarValueMapper::detect_extension("1.2e-3").is_none(),
            "scientific notation with decimal should be rejected"
        );
    }

    #[test]
    fn test_extension_detection_datetime() {
        // Date only
        assert!(matches!(
            CedarValueMapper::detect_extension("2024-10-15"),
            Some(ExtensionValue::DateTime(_))
        ));

        // UTC datetime
        assert!(matches!(
            CedarValueMapper::detect_extension("2024-10-15T11:35:00Z"),
            Some(ExtensionValue::DateTime(_))
        ));

        // UTC with milliseconds
        assert!(matches!(
            CedarValueMapper::detect_extension("2024-10-15T11:35:00.000Z"),
            Some(ExtensionValue::DateTime(_))
        ));

        // With timezone offset (RFC3339 requires colon in timezone)
        assert!(matches!(
            CedarValueMapper::detect_extension("2024-10-15T11:35:00+01:00"),
            Some(ExtensionValue::DateTime(_))
        ));

        // Invalid datetime
        assert!(!matches!(
            CedarValueMapper::detect_extension("not-a-date"),
            Some(ExtensionValue::DateTime(_))
        ));
    }

    #[test]
    fn test_extension_detection_duration() {
        // Hours and minutes
        assert!(matches!(
            CedarValueMapper::detect_extension("2h30m"),
            Some(ExtensionValue::Duration(_))
        ));

        // Negative duration
        assert!(matches!(
            CedarValueMapper::detect_extension("-1d12h"),
            Some(ExtensionValue::Duration(_))
        ));

        // Hours, minutes, seconds
        assert!(matches!(
            CedarValueMapper::detect_extension("1h30m45s"),
            Some(ExtensionValue::Duration(_))
        ));

        // Milliseconds only
        assert!(matches!(
            CedarValueMapper::detect_extension("500ms"),
            Some(ExtensionValue::Duration(_))
        ));

        // Days only
        assert!(matches!(
            CedarValueMapper::detect_extension("1d"),
            Some(ExtensionValue::Duration(_))
        ));

        // Invalid duration
        assert!(!matches!(
            CedarValueMapper::detect_extension("not-a-duration"),
            Some(ExtensionValue::Duration(_))
        ));
    }

    #[test]
    fn test_json_to_cedar_with_auto_detect() {
        let mapper = CedarValueMapper::new();

        // IP address should be detected
        let result = mapper.json_to_cedar(&json!("192.168.1.1"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_json_to_cedar_without_auto_detect() {
        let mapper = CedarValueMapper::new_without_auto_detect();

        // IP address should be treated as string
        let result = mapper.json_to_cedar(&json!("192.168.1.1"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_is_entity_reference() {
        assert!(CedarValueMapper::is_entity_reference(&json!({
            "type": "User",
            "id": "123"
        })));

        // Missing type
        assert!(!CedarValueMapper::is_entity_reference(&json!({
            "id": "123"
        })));

        // Extra field
        assert!(!CedarValueMapper::is_entity_reference(&json!({
            "type": "User",
            "id": "123",
            "extra": true
        })));

        // Wrong types
        assert!(!CedarValueMapper::is_entity_reference(&json!({
            "type": 123,
            "id": "123"
        })));
    }

    #[test]
    fn test_parse_entity_reference() {
        let value = json!({"type": "User", "id": "alice"});
        let result = CedarValueMapper::parse_entity_reference(&value);
        assert!(result.is_ok());
        let entity_ref = result.expect("should parse");
        assert_eq!(entity_ref.entity_type, "User");
        assert_eq!(entity_ref.entity_id, "alice");
    }

    #[test]
    fn test_dot_notation_access() {
        let data = json!({
            "user": {
                "profile": {
                    "name": "Alice",
                    "age": 30
                }
            }
        });

        // Valid paths
        let name = CedarValueMapper::get_nested(&data, "user.profile.name");
        assert!(name.is_ok());
        assert_eq!(name.unwrap(), &json!("Alice"));

        let age = CedarValueMapper::get_nested(&data, "user.profile.age");
        assert!(age.is_ok());
        assert_eq!(age.unwrap(), &json!(30));

        // Invalid path
        let missing = CedarValueMapper::get_nested(&data, "user.missing.field");
        assert!(matches!(
            missing,
            Err(ValueMappingError::PathNotFound { .. })
        ));
    }

    #[test]
    fn test_dot_notation_array_access() {
        let data = json!({
            "items": ["a", "b", "c"]
        });

        let item = CedarValueMapper::get_nested(&data, "items.1");
        assert!(item.is_ok());
        assert_eq!(item.unwrap(), &json!("b"));
    }

    #[test]
    fn test_set_nested() {
        let mut data = json!({});

        CedarValueMapper::set_nested(&mut data, "user.profile.name", json!("Alice"))
            .expect("should set nested value");

        assert_eq!(data, json!({"user": {"profile": {"name": "Alice"}}}));
    }

    #[test]
    fn test_value_size_limit() {
        let mapper = CedarValueMapper::new().with_max_size(10);

        // Small value should pass
        let result = mapper.json_to_cedar(&json!("hi"));
        assert!(result.is_ok());

        // Large value should fail
        let result = mapper.json_to_cedar(&json!("this is a very long string"));
        assert!(matches!(
            result,
            Err(ValueMappingError::ValueTooLarge { .. })
        ));
    }

    #[test]
    fn test_explicit_extension_marker() {
        let mapper = CedarValueMapper::new();

        // Decimal with explicit marker
        let decimal = json!({"__extn": {"fn": "decimal", "arg": "3.14159"}});
        let result = mapper.json_to_cedar(&decimal);
        assert!(result.is_ok(), "decimal extension should parse");

        // IP with explicit marker
        let ip = json!({"__extn": {"fn": "ip", "arg": "10.0.0.1"}});
        let result = mapper.json_to_cedar(&ip);
        assert!(result.is_ok(), "ip extension should parse");

        // IP CIDR with explicit marker
        let ip_cidr = json!({"__extn": {"fn": "ip", "arg": "192.168.0.0/16"}});
        let result = mapper.json_to_cedar(&ip_cidr);
        assert!(result.is_ok(), "ip CIDR extension should parse");

        // Datetime with explicit marker
        let datetime = json!({"__extn": {"fn": "datetime", "arg": "2024-10-15T11:35:00Z"}});
        let result = mapper.json_to_cedar(&datetime);
        assert!(result.is_ok(), "datetime extension should parse");

        // Duration with explicit marker
        let duration = json!({"__extn": {"fn": "duration", "arg": "2h30m"}});
        let result = mapper.json_to_cedar(&duration);
        assert!(result.is_ok(), "duration extension should parse");
    }

    #[test]
    fn test_json_to_cedar_with_type() {
        let mapper = CedarValueMapper::new();

        let result = mapper.json_to_cedar_with_type(&json!("hello"));
        assert!(result.is_ok());
        let (_, cedar_type) = result.expect("should convert").expect("should have value");
        assert_eq!(cedar_type, CedarType::String);

        let result = mapper.json_to_cedar_with_type(&json!(42));
        assert!(result.is_ok());
        let (_, cedar_type) = result.expect("should convert").expect("should have value");
        assert_eq!(cedar_type, CedarType::Long);

        let result = mapper.json_to_cedar_with_type(&json!({"a": 1}));
        assert!(result.is_ok());
        let (_, cedar_type) = result.expect("should convert").expect("should have value");
        assert_eq!(cedar_type, CedarType::Record);
    }

    #[test]
    fn test_nested_structures() {
        let mapper = CedarValueMapper::new();

        let complex = json!({
            "user": {
                "name": "Alice",
                "roles": ["admin", "user"],
                "profile": {
                    "age": 30,
                    "verified": true
                }
            },
            "metadata": {
                "version": 1
            }
        });

        let result = mapper.json_to_cedar(&complex);
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }
}