rivven-core 0.0.21

Core library for Rivven distributed event streaming platform
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
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
//! Cedar-based Authorization Engine for Rivven
//!
//! This module provides fine-grained, policy-as-code authorization using
//! [Cedar](https://www.cedarpolicy.com/), the policy language from AWS.
//!
//! ## Why Cedar?
//!
//! - **Formal verification**: Policies can be mathematically proven correct
//! - **Separation of concerns**: Policy changes without code changes
//! - **Audit trail**: Every decision is explainable
//! - **Attribute-based**: Context-aware decisions (time, IP, resource attributes)
//!
//! ## Rivven Entity Model
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │                     RIVVEN CEDAR SCHEMA                             │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │                                                                     │
//! │  namespace Rivven {                                                 │
//! │    entity User in [Group] {                                         │
//! │      email?: String,                                               │
//! │      roles: Set<String>,                                           │
//! │      service_account: Bool,                                        │
//! │    };                                                              │
//! │                                                                     │
//! │    entity Group in [Group];                                        │
//! │                                                                     │
//! │    entity Topic {                                                  │
//! │      owner?: User,                                                 │
//! │      partitions: Long,                                             │
//! │      replication_factor: Long,                                     │
//! │      retention_ms: Long,                                           │
//! │    };                                                              │
//! │                                                                     │
//! │    entity ConsumerGroup {                                          │
//! │      members: Set<User>,                                           │
//! │    };                                                              │
//! │                                                                     │
//! │    entity Cluster;                                                 │
//! │                                                                     │
//! │    action produce, consume, create, delete, alter, describe        │
//! │      appliesTo { principal: [User, Group], resource: [Topic] };    │
//! │                                                                     │
//! │    action join, leave, commit, fetch_offsets                       │
//! │      appliesTo { principal: [User, Group], resource: [ConsumerGroup] };│
//! │                                                                     │
//! │    action admin                                                     │
//! │      appliesTo { principal: [User, Group], resource: [Cluster] };  │
//! │  }                                                                  │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Example Policies
//!
//! ```cedar
//! // Allow users to produce to topics they own
//! permit(
//!   principal,
//!   action == Rivven::Action::"produce",
//!   resource
//! ) when {
//!   resource.owner == principal
//! };
//!
//! // Allow members of "producers" group to produce to any topic starting with "events-"
//! permit(
//!   principal in Rivven::Group::"producers",
//!   action == Rivven::Action::"produce",
//!   resource
//! ) when {
//!   resource.name.startsWith("events-")
//! };
//!
//! // Deny access from untrusted IPs
//! forbid(
//!   principal,
//!   action,
//!   resource
//! ) when {
//!   context.ip_address.isLoopback() == false &&
//!   context.ip_address.isInRange(ip("10.0.0.0/8")) == false
//! };
//! ```

#[cfg(feature = "cedar")]
mod cedar_impl {
    use cedar_policy::{
        Authorizer, Context, Decision, Entities, Entity, EntityId, EntityTypeName, EntityUid,
        Policy, PolicySet, Request, Schema, ValidationMode,
    };
    use parking_lot::RwLock;
    use serde::{Deserialize, Serialize};
    use std::collections::{HashMap, HashSet};
    use std::str::FromStr;
    use thiserror::Error;
    use tracing::{debug, info};

    // ============================================================================
    // Error Types
    // ============================================================================

    #[derive(Error, Debug)]
    pub enum CedarError {
        #[error("Policy parse error: {0}")]
        PolicyParse(String),

        #[error("Schema error: {0}")]
        Schema(String),

        #[error("Validation error: {0}")]
        Validation(String),

        #[error("Entity error: {0}")]
        Entity(String),

        #[error("Request error: {0}")]
        Request(String),

        #[error("Authorization denied: {principal} cannot {action} on {resource}")]
        Denied {
            principal: String,
            action: String,
            resource: String,
        },

        #[error("Internal error: {0}")]
        Internal(String),
    }

    pub type CedarResult<T> = Result<T, CedarError>;

    // ============================================================================
    // Helper: safe EntityUid construction
    // ============================================================================

    /// Create an `EntityUid` from type name and ID strings, mapping parse errors
    /// to `CedarError::Entity` instead of panicking. This eliminates all
    /// `.unwrap()` calls on user-supplied entity names (usernames, topic names,
    /// group names) that could crash the authorization engine on malformed input.
    fn make_entity_uid(type_name: &str, id: &str) -> CedarResult<EntityUid> {
        let tn = EntityTypeName::from_str(type_name).map_err(|e| {
            CedarError::Entity(format!("invalid entity type '{}': {}", type_name, e))
        })?;
        let eid = EntityId::from_str(id)
            .map_err(|e| CedarError::Entity(format!("invalid entity id '{}': {}", id, e)))?;
        Ok(EntityUid::from_type_name_and_id(tn, eid))
    }

    // ============================================================================
    // Rivven Actions
    // ============================================================================

    /// Actions that can be performed in Rivven
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum RivvenAction {
        // Topic actions
        Produce,
        Consume,
        Create,
        Delete,
        Alter,
        Describe,

        // Consumer group actions
        Join,
        Leave,
        Commit,
        FetchOffsets,

        // Cluster actions
        Admin,
        AlterConfigs,
        DescribeConfigs,
    }

    impl RivvenAction {
        pub fn as_str(&self) -> &'static str {
            match self {
                Self::Produce => "produce",
                Self::Consume => "consume",
                Self::Create => "create",
                Self::Delete => "delete",
                Self::Alter => "alter",
                Self::Describe => "describe",
                Self::Join => "join",
                Self::Leave => "leave",
                Self::Commit => "commit",
                Self::FetchOffsets => "fetch_offsets",
                Self::Admin => "admin",
                Self::AlterConfigs => "alter_configs",
                Self::DescribeConfigs => "describe_configs",
            }
        }

        fn to_entity_uid(self) -> CedarResult<EntityUid> {
            make_entity_uid("Rivven::Action", self.as_str())
        }
    }

    // ============================================================================
    // Resource Types
    // ============================================================================

    /// Types of resources in Rivven
    #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
    #[serde(tag = "type", content = "name")]
    pub enum RivvenResource {
        Topic(String),
        ConsumerGroup(String),
        Schema(String),
        Cluster,
    }

    impl RivvenResource {
        fn type_name(&self) -> &'static str {
            match self {
                Self::Topic(_) => "Rivven::Topic",
                Self::ConsumerGroup(_) => "Rivven::ConsumerGroup",
                Self::Schema(_) => "Rivven::Schema",
                Self::Cluster => "Rivven::Cluster",
            }
        }

        fn id(&self) -> &str {
            match self {
                Self::Topic(name) => name,
                Self::ConsumerGroup(name) => name,
                Self::Schema(name) => name,
                Self::Cluster => "default",
            }
        }

        fn to_entity_uid(&self) -> CedarResult<EntityUid> {
            make_entity_uid(self.type_name(), self.id())
        }
    }

    // ============================================================================
    // Authorization Context
    // ============================================================================

    /// Context for authorization decisions
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AuthzContext {
        /// Client IP address
        pub ip_address: Option<String>,

        /// Request timestamp (ISO 8601)
        pub timestamp: String,

        /// TLS client certificate subject (if mTLS)
        pub tls_subject: Option<String>,

        /// Additional context attributes
        #[serde(flatten)]
        pub extra: HashMap<String, serde_json::Value>,
    }

    impl Default for AuthzContext {
        fn default() -> Self {
            Self {
                ip_address: None,
                timestamp: chrono::Utc::now().to_rfc3339(),
                tls_subject: None,
                extra: HashMap::new(),
            }
        }
    }

    impl AuthzContext {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
            self.ip_address = Some(ip.into());
            self
        }

        pub fn with_tls_subject(mut self, subject: impl Into<String>) -> Self {
            self.tls_subject = Some(subject.into());
            self
        }

        pub fn with_attr(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
            self.extra.insert(key.into(), value);
            self
        }

        fn to_cedar_context(&self) -> CedarResult<Context> {
            // Cedar does not allow null values, so we must create a JSON object
            // with only the non-null values
            let mut context_map = serde_json::Map::new();

            // Add timestamp (always present)
            context_map.insert("timestamp".to_string(), serde_json::json!(self.timestamp));

            // Add optional fields only if they have values
            if let Some(ip) = &self.ip_address {
                context_map.insert("ip_address".to_string(), serde_json::json!(ip));
            }

            if let Some(tls) = &self.tls_subject {
                context_map.insert("tls_subject".to_string(), serde_json::json!(tls));
            }

            // Add extra context, filtering out null values
            for (key, value) in &self.extra {
                if !value.is_null() {
                    context_map.insert(key.clone(), value.clone());
                }
            }

            let json = serde_json::Value::Object(context_map);

            Context::from_json_value(json, None)
                .map_err(|e| CedarError::Request(format!("Invalid context: {}", e)))
        }
    }

    // ============================================================================
    // Authorization Decision
    // ============================================================================

    /// Result of an authorization check
    #[derive(Debug, Clone)]
    pub struct AuthzDecision {
        /// Whether access is allowed
        pub allowed: bool,

        /// Policies that permitted the action
        pub satisfied_policies: Vec<String>,

        /// Policies that denied the action
        pub denied_policies: Vec<String>,

        /// Errors during evaluation
        pub errors: Vec<String>,

        /// Diagnostics for debugging
        pub diagnostics: Option<String>,
    }

    impl AuthzDecision {
        pub fn allowed(satisfied: Vec<String>) -> Self {
            Self {
                allowed: true,
                satisfied_policies: satisfied,
                denied_policies: vec![],
                errors: vec![],
                diagnostics: None,
            }
        }

        pub fn denied(denied: Vec<String>) -> Self {
            Self {
                allowed: false,
                satisfied_policies: vec![],
                denied_policies: denied,
                errors: vec![],
                diagnostics: None,
            }
        }
    }

    // ============================================================================
    // Cedar Authorizer
    // ============================================================================

    /// Cedar-based authorization engine
    pub struct CedarAuthorizer {
        /// Cedar schema for validation
        schema: Option<Schema>,

        /// Policy set
        policies: RwLock<PolicySet>,

        /// Entity store
        entities: RwLock<Entities>,

        /// Whether to validate policies against schema
        validate_policies: bool,
    }

    impl CedarAuthorizer {
        /// Create a new authorizer with default schema
        pub fn new() -> CedarResult<Self> {
            let schema = Self::default_schema()?;

            Ok(Self {
                schema: Some(schema),
                policies: RwLock::new(PolicySet::new()),
                entities: RwLock::new(Entities::empty()),
                validate_policies: true,
            })
        }

        /// Create without schema validation (for testing)
        pub fn new_without_schema() -> Self {
            Self {
                schema: None,
                policies: RwLock::new(PolicySet::new()),
                entities: RwLock::new(Entities::empty()),
                validate_policies: false,
            }
        }

        /// Default Rivven Cedar schema
        fn default_schema() -> CedarResult<Schema> {
            let schema_src = r#"
{
  "Rivven": {
    "entityTypes": {
      "User": {
        "memberOfTypes": ["Group"],
        "shape": {
          "type": "Record",
          "attributes": {
            "email": { "type": "String", "required": false },
            "roles": { "type": "Set", "element": { "type": "String" } },
            "service_account": { "type": "Boolean" }
          }
        }
      },
      "Group": {
        "memberOfTypes": ["Group"]
      },
      "Topic": {
        "shape": {
          "type": "Record",
          "attributes": {
            "owner": { "type": "Entity", "name": "Rivven::User", "required": false },
            "partitions": { "type": "Long" },
            "replication_factor": { "type": "Long" },
            "retention_ms": { "type": "Long" },
            "name": { "type": "String" }
          }
        }
      },
      "ConsumerGroup": {
        "shape": {
          "type": "Record",
          "attributes": {
            "name": { "type": "String" }
          }
        }
      },
      "Schema": {
        "shape": {
          "type": "Record",
          "attributes": {
            "name": { "type": "String" },
            "version": { "type": "Long" }
          }
        }
      },
      "Cluster": {}
    },
    "actions": {
      "produce": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic"]
        }
      },
      "consume": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic"]
        }
      },
      "create": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic", "Schema"]
        }
      },
      "delete": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic", "ConsumerGroup", "Schema"]
        }
      },
      "alter": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic", "Schema"]
        }
      },
      "describe": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Topic", "ConsumerGroup", "Schema", "Cluster"]
        }
      },
      "join": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["ConsumerGroup"]
        }
      },
      "leave": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["ConsumerGroup"]
        }
      },
      "commit": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["ConsumerGroup"]
        }
      },
      "fetch_offsets": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["ConsumerGroup"]
        }
      },
      "admin": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Cluster"]
        }
      },
      "alter_configs": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Cluster"]
        }
      },
      "describe_configs": {
        "appliesTo": {
          "principalTypes": ["User", "Group"],
          "resourceTypes": ["Cluster"]
        }
      }
    }
  }
}
"#;

            Schema::from_json_str(schema_src)
                .map_err(|e| CedarError::Schema(format!("Invalid schema: {:?}", e)))
        }

        /// Add a policy from Cedar source
        pub fn add_policy(&self, id: &str, policy_src: &str) -> CedarResult<()> {
            let policy = Policy::parse(Some(cedar_policy::PolicyId::new(id)), policy_src)
                .map_err(|e| CedarError::PolicyParse(format!("{:?}", e)))?;

            // Validate against schema if enabled
            if self.validate_policies {
                if let Some(schema) = &self.schema {
                    let mut temp_set = PolicySet::new();
                    temp_set.add(policy.clone()).map_err(|e| {
                        CedarError::PolicyParse(format!("Duplicate policy ID: {:?}", e))
                    })?;

                    let validator = cedar_policy::Validator::new(schema.clone());
                    let result = validator.validate(&temp_set, ValidationMode::Strict);

                    if !result.validation_passed() {
                        let errors: Vec<String> = result
                            .validation_errors()
                            .map(|e| format!("{:?}", e))
                            .collect();
                        return Err(CedarError::Validation(errors.join("; ")));
                    }
                }
            }

            let mut policies = self.policies.write();
            policies
                .add(policy)
                .map_err(|e| CedarError::PolicyParse(format!("Failed to add policy: {:?}", e)))?;

            info!("Added Cedar policy: {}", id);
            Ok(())
        }

        /// Add multiple policies from Cedar source
        pub fn add_policies(&self, policies_src: &str) -> CedarResult<()> {
            let parsed = PolicySet::from_str(policies_src)
                .map_err(|e| CedarError::PolicyParse(format!("{:?}", e)))?;

            // Validate against schema if enabled
            if self.validate_policies {
                if let Some(schema) = &self.schema {
                    let validator = cedar_policy::Validator::new(schema.clone());
                    let result = validator.validate(&parsed, ValidationMode::Strict);

                    if !result.validation_passed() {
                        let errors: Vec<String> = result
                            .validation_errors()
                            .map(|e| format!("{:?}", e))
                            .collect();
                        return Err(CedarError::Validation(errors.join("; ")));
                    }
                }
            }

            let mut policies = self.policies.write();
            for policy in parsed.policies() {
                policies.add(policy.clone()).map_err(|e| {
                    CedarError::PolicyParse(format!("Failed to add policy: {:?}", e))
                })?;
            }

            Ok(())
        }

        /// Remove a policy by ID
        pub fn remove_policy(&self, id: &str) -> CedarResult<()> {
            // Cedar PolicySet doesn't support removal directly
            // We need to rebuild without the policy
            let mut policies = self.policies.write();
            let policy_id = cedar_policy::PolicyId::new(id);

            // Create a new PolicySet without the specified policy
            let new_policies = policies
                .policies()
                .filter(|p| p.id() != &policy_id)
                .cloned()
                .collect::<Vec<_>>();

            let mut new_set = PolicySet::new();
            for policy in new_policies {
                new_set.add(policy).ok();
            }

            *policies = new_set;
            info!("Removed Cedar policy: {}", id);
            Ok(())
        }

        /// Upsert a single entity incrementally without cloning all existing entities.
        /// Uses Cedar's `upsert_entities` API which re-computes TC but avoids O(n) clone.
        fn upsert_entity(&self, entity: Entity) -> CedarResult<()> {
            let mut guard = self.entities.write();
            let current = std::mem::replace(&mut *guard, Entities::empty());
            match current.upsert_entities([entity], None) {
                Ok(updated) => {
                    *guard = updated;
                    Ok(())
                }
                Err(e) => Err(CedarError::Entity(format!(
                    "Failed to upsert entity: {:?}",
                    e
                ))),
            }
        }

        /// Add a user entity
        pub fn add_user(
            &self,
            username: &str,
            email: Option<&str>,
            roles: &[&str],
            groups: &[&str],
            is_service_account: bool,
        ) -> CedarResult<()> {
            let uid = make_entity_uid("Rivven::User", username)?;

            // Build parent groups
            let parents: HashSet<EntityUid> = groups
                .iter()
                .map(|g| make_entity_uid("Rivven::Group", g))
                .collect::<CedarResult<_>>()?;

            // Build attributes
            let mut attrs = HashMap::new();
            if let Some(e) = email {
                attrs.insert(
                    "email".to_string(),
                    cedar_policy::RestrictedExpression::new_string(e.to_string()),
                );
            }

            let roles_set: Vec<_> = roles
                .iter()
                .map(|r| cedar_policy::RestrictedExpression::new_string(r.to_string()))
                .collect();
            attrs.insert(
                "roles".to_string(),
                cedar_policy::RestrictedExpression::new_set(roles_set),
            );

            attrs.insert(
                "service_account".to_string(),
                cedar_policy::RestrictedExpression::new_bool(is_service_account),
            );

            let entity = Entity::new(uid, attrs, parents)
                .map_err(|e| CedarError::Entity(format!("Invalid entity: {:?}", e)))?;

            self.upsert_entity(entity)?;

            debug!("Added user entity: {}", username);
            Ok(())
        }

        /// Add a group entity
        pub fn add_group(&self, name: &str, parent_groups: &[&str]) -> CedarResult<()> {
            let uid = make_entity_uid("Rivven::Group", name)?;

            let parents: HashSet<EntityUid> = parent_groups
                .iter()
                .map(|g| make_entity_uid("Rivven::Group", g))
                .collect::<CedarResult<_>>()?;

            let entity = Entity::new_no_attrs(uid, parents);

            self.upsert_entity(entity)?;

            debug!("Added group entity: {}", name);
            Ok(())
        }

        /// Add a topic entity
        pub fn add_topic(
            &self,
            name: &str,
            owner: Option<&str>,
            partitions: i64,
            replication_factor: i64,
            retention_ms: i64,
        ) -> CedarResult<()> {
            let uid = make_entity_uid("Rivven::Topic", name)?;

            let mut attrs = HashMap::new();
            attrs.insert(
                "name".to_string(),
                cedar_policy::RestrictedExpression::new_string(name.to_string()),
            );

            if let Some(o) = owner {
                let owner_uid = make_entity_uid("Rivven::User", o)?;
                attrs.insert(
                    "owner".to_string(),
                    cedar_policy::RestrictedExpression::new_entity_uid(owner_uid),
                );
            }

            attrs.insert(
                "partitions".to_string(),
                cedar_policy::RestrictedExpression::new_long(partitions),
            );
            attrs.insert(
                "replication_factor".to_string(),
                cedar_policy::RestrictedExpression::new_long(replication_factor),
            );
            attrs.insert(
                "retention_ms".to_string(),
                cedar_policy::RestrictedExpression::new_long(retention_ms),
            );

            let entity = Entity::new(uid, attrs, HashSet::new())
                .map_err(|e| CedarError::Entity(format!("Invalid entity: {:?}", e)))?;

            self.upsert_entity(entity)?;

            debug!("Added topic entity: {}", name);
            Ok(())
        }

        /// Add a consumer group entity
        pub fn add_consumer_group(&self, name: &str) -> CedarResult<()> {
            let uid = make_entity_uid("Rivven::ConsumerGroup", name)?;

            let mut attrs = HashMap::new();
            attrs.insert(
                "name".to_string(),
                cedar_policy::RestrictedExpression::new_string(name.to_string()),
            );

            let entity = Entity::new(uid, attrs, HashSet::new())
                .map_err(|e| CedarError::Entity(format!("Invalid entity: {:?}", e)))?;

            self.upsert_entity(entity)?;

            debug!("Added consumer group entity: {}", name);
            Ok(())
        }

        /// Add a schema entity
        pub fn add_schema(&self, name: &str, version: i64) -> CedarResult<()> {
            let uid = make_entity_uid("Rivven::Schema", name)?;

            let mut attrs = HashMap::new();
            attrs.insert(
                "name".to_string(),
                cedar_policy::RestrictedExpression::new_string(name.to_string()),
            );
            attrs.insert(
                "version".to_string(),
                cedar_policy::RestrictedExpression::new_long(version),
            );

            let entity = Entity::new(uid, attrs, HashSet::new())
                .map_err(|e| CedarError::Entity(format!("Invalid entity: {:?}", e)))?;

            self.upsert_entity(entity)?;

            debug!("Added schema entity: {} (version {})", name, version);
            Ok(())
        }

        /// Check if an action is authorized
        pub fn is_authorized(
            &self,
            principal: &str,
            action: RivvenAction,
            resource: &RivvenResource,
            context: &AuthzContext,
        ) -> CedarResult<AuthzDecision> {
            let principal_uid = make_entity_uid("Rivven::User", principal)?;

            let action_uid = action.to_entity_uid()?;
            let resource_uid = resource.to_entity_uid()?;
            let cedar_context = context.to_cedar_context()?;

            let request = Request::new(
                principal_uid.clone(),
                action_uid.clone(),
                resource_uid.clone(),
                cedar_context,
                None,
            )
            .map_err(|e| CedarError::Request(format!("Invalid request: {:?}", e)))?;

            let authorizer = Authorizer::new();
            let policies = self.policies.read();
            let entities = self.entities.read();

            let response = authorizer.is_authorized(&request, &policies, &entities);

            let decision = match response.decision() {
                Decision::Allow => {
                    let satisfied: Vec<String> = response
                        .diagnostics()
                        .reason()
                        .map(|id| id.to_string())
                        .collect();
                    AuthzDecision::allowed(satisfied)
                }
                Decision::Deny => {
                    let denied: Vec<String> = response
                        .diagnostics()
                        .reason()
                        .map(|id| id.to_string())
                        .collect();

                    let errors: Vec<String> = response
                        .diagnostics()
                        .errors()
                        .map(|e| format!("{:?}", e))
                        .collect();

                    AuthzDecision {
                        allowed: false,
                        satisfied_policies: vec![],
                        denied_policies: denied,
                        errors,
                        diagnostics: None,
                    }
                }
            };

            debug!(
                "Authorization: {} {} {} -> {}",
                principal,
                action.as_str(),
                resource.id(),
                if decision.allowed { "ALLOW" } else { "DENY" }
            );

            Ok(decision)
        }

        /// Check authorization and return error if denied
        pub fn authorize(
            &self,
            principal: &str,
            action: RivvenAction,
            resource: &RivvenResource,
            context: &AuthzContext,
        ) -> CedarResult<()> {
            let decision = self.is_authorized(principal, action, resource, context)?;

            if decision.allowed {
                Ok(())
            } else {
                Err(CedarError::Denied {
                    principal: principal.to_string(),
                    action: action.as_str().to_string(),
                    resource: format!("{:?}", resource),
                })
            }
        }

        /// Load default policies for common use cases
        pub fn load_default_policies(&self) -> CedarResult<()> {
            // Super admin has all permissions
            self.add_policy(
                "super-admin",
                r#"
permit(
  principal in Rivven::Group::"admins",
  action,
  resource
);
"#,
            )?;

            // All users can describe topics
            self.add_policy(
                "describe-topics",
                r#"
permit(
  principal,
  action == Rivven::Action::"describe",
  resource is Rivven::Topic
);
"#,
            )?;

            // All users can describe consumer groups
            self.add_policy(
                "describe-consumer-groups",
                r#"
permit(
  principal,
  action == Rivven::Action::"describe",
  resource is Rivven::ConsumerGroup
);
"#,
            )?;

            info!("Loaded default Cedar policies");
            Ok(())
        }
    }

    impl Default for CedarAuthorizer {
        /// logs error and returns a deny-all authorizer instead of panicking.
        ///
        /// On schema-parse failure, falls back to a schema-less authorizer with
        /// empty policies (deny-all). This avoids re-calling the same failing
        /// constructor and eliminates the panic path.
        fn default() -> Self {
            match Self::new() {
                Ok(authorizer) => authorizer,
                Err(e) => {
                    tracing::error!(
                        "Failed to create default Cedar authorizer: {}. Using deny-all fallback.",
                        e
                    );
                    // Use new_without_schema() — cannot fail, avoids re-calling new().
                    Self::new_without_schema()
                }
            }
        }
    }

    // ============================================================================
    // Tests
    // ============================================================================

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

        #[test]
        fn test_create_authorizer() {
            let authz = CedarAuthorizer::new().unwrap();
            assert!(authz.schema.is_some());
        }

        #[test]
        fn test_add_simple_policy() {
            let authz = CedarAuthorizer::new_without_schema();

            authz
                .add_policy(
                    "test-policy",
                    r#"
permit(
  principal == Rivven::User::"alice",
  action == Rivven::Action::"produce",
  resource == Rivven::Topic::"orders"
);
"#,
                )
                .unwrap();
        }

        #[test]
        fn test_add_user_and_authorize() {
            let authz = CedarAuthorizer::new_without_schema();

            // Add admin policy
            authz
                .add_policy(
                    "admin-all",
                    r#"
permit(
  principal in Rivven::Group::"admins",
  action,
  resource
);
"#,
                )
                .unwrap();

            // Add group and user
            authz.add_group("admins", &[]).unwrap();
            authz
                .add_user(
                    "alice",
                    Some("alice@example.com"),
                    &["admin"],
                    &["admins"],
                    false,
                )
                .unwrap();

            // Add topic
            authz
                .add_topic("orders", Some("alice"), 3, 2, 604800000)
                .unwrap();

            // Check authorization
            let ctx = AuthzContext::new().with_ip("127.0.0.1");
            let decision = authz
                .is_authorized(
                    "alice",
                    RivvenAction::Produce,
                    &RivvenResource::Topic("orders".to_string()),
                    &ctx,
                )
                .unwrap();

            assert!(decision.allowed);
        }

        #[test]
        fn test_deny_unauthorized() {
            let authz = CedarAuthorizer::new_without_schema();

            // Add a restrictive policy - only admins can produce
            authz
                .add_policy(
                    "only-admins-produce",
                    r#"
permit(
  principal in Rivven::Group::"admins",
  action == Rivven::Action::"produce",
  resource is Rivven::Topic
);
"#,
                )
                .unwrap();

            // Add a non-admin user
            authz
                .add_user("bob", Some("bob@example.com"), &["user"], &[], false)
                .unwrap();

            // Add topic
            authz.add_topic("orders", None, 3, 2, 604800000).unwrap();

            // Check authorization - should be denied
            let ctx = AuthzContext::new();
            let decision = authz
                .is_authorized(
                    "bob",
                    RivvenAction::Produce,
                    &RivvenResource::Topic("orders".to_string()),
                    &ctx,
                )
                .unwrap();

            assert!(!decision.allowed);
        }

        #[test]
        fn test_context_attributes() {
            let ctx = AuthzContext::new()
                .with_ip("192.168.1.100")
                .with_tls_subject("CN=client,O=Rivven")
                .with_attr("custom_field", serde_json::json!("custom_value"));

            assert_eq!(ctx.ip_address, Some("192.168.1.100".to_string()));
            assert_eq!(ctx.tls_subject, Some("CN=client,O=Rivven".to_string()));
            assert!(ctx.extra.contains_key("custom_field"));
        }
    }
}

#[cfg(feature = "cedar")]
pub use cedar_impl::*;

#[cfg(not(feature = "cedar"))]
mod no_cedar {
    //! Stub module when Cedar feature is disabled

    use std::collections::HashMap;
    use thiserror::Error;

    #[derive(Error, Debug)]
    pub enum CedarError {
        #[error("Cedar authorization not enabled. Build with 'cedar' feature.")]
        NotEnabled,
    }

    pub type CedarResult<T> = Result<T, CedarError>;

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum RivvenAction {
        Produce,
        Consume,
        Create,
        Delete,
        Alter,
        Describe,
        Join,
        Leave,
        Commit,
        FetchOffsets,
        Admin,
        AlterConfigs,
        DescribeConfigs,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub enum RivvenResource {
        Topic(String),
        ConsumerGroup(String),
        Schema(String),
        Cluster,
    }

    #[derive(Debug, Clone, Default)]
    pub struct AuthzContext {
        pub ip_address: Option<String>,
        pub timestamp: String,
        pub tls_subject: Option<String>,
        pub extra: HashMap<String, serde_json::Value>,
    }

    impl AuthzContext {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_ip(self, _ip: impl Into<String>) -> Self {
            self
        }

        pub fn with_tls_subject(self, _subject: impl Into<String>) -> Self {
            self
        }
    }

    pub struct CedarAuthorizer;

    impl CedarAuthorizer {
        pub fn new() -> CedarResult<Self> {
            Err(CedarError::NotEnabled)
        }

        pub fn authorize(
            &self,
            _principal: &str,
            _action: RivvenAction,
            _resource: &RivvenResource,
            _context: &AuthzContext,
        ) -> CedarResult<()> {
            Err(CedarError::NotEnabled)
        }
    }
}

#[cfg(not(feature = "cedar"))]
pub use no_cedar::*;