tensor_vault 0.4.0

AES-256-GCM encrypted secret storage with graph-based access control
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Graph-based access control using topological path verification.

#[cfg(test)]
use std::collections::HashMap;
use std::collections::{HashSet, VecDeque};

use graph_engine::{Direction, GraphEngine, PropertyValue};

use crate::attenuation::AttenuationPolicy;
use crate::signing::EdgeSigner;
use crate::Permission;

/// Access controller using graph topology for authorization.
pub struct AccessController;

// ========== Node-based Graph API Helpers ==========
// These functions provide a string-key interface on top of the node-based graph API.

/// Ensure the entity_key index exists.
fn ensure_entity_key_index(graph: &GraphEngine) {
    // Create index if it doesn't exist (idempotent operation)
    let _ = graph.create_node_property_index("entity_key");
}

/// Get or create a graph node for an entity key (test helper).
#[cfg(test)]
fn get_or_create_entity_node(graph: &GraphEngine, entity_key: &str) -> u64 {
    ensure_entity_key_index(graph);

    if let Ok(nodes) =
        graph.find_nodes_by_property("entity_key", &PropertyValue::String(entity_key.to_string()))
    {
        if let Some(node) = nodes.first() {
            return node.id;
        }
    }

    let mut props = HashMap::new();
    props.insert(
        "entity_key".to_string(),
        PropertyValue::String(entity_key.to_string()),
    );
    graph.create_node("AccessEntity", props).unwrap_or(0)
}

/// Find node by entity key without creating.
fn find_entity_node(graph: &GraphEngine, entity_key: &str) -> Option<u64> {
    ensure_entity_key_index(graph);
    graph
        .find_nodes_by_property("entity_key", &PropertyValue::String(entity_key.to_string()))
        .ok()
        .and_then(|nodes| nodes.first().map(|n| n.id))
}

/// Get the entity key for a node ID.
fn get_entity_key(graph: &GraphEngine, node_id: u64) -> Option<String> {
    graph.get_node(node_id).ok().and_then(|node| {
        if let Some(PropertyValue::String(key)) = node.properties.get("entity_key") {
            Some(key.clone())
        } else {
            None
        }
    })
}

/// Edge info returned from graph traversal.
struct EdgeInfo {
    target_key: String,
    source_key: String,
    edge_type: String,
    signature: Option<Vec<u8>>,
    sig_timestamp: Option<i64>,
    /// Bottleneck capacity (1=Read, 2=Write, 3=Admin), if set.
    capacity: Option<i64>,
}

/// Get outgoing edges for an entity, returning (target_key, edge_type).
fn get_outgoing_edges(graph: &GraphEngine, entity_key: &str) -> Vec<(String, String)> {
    get_outgoing_edges_full(graph, entity_key)
        .into_iter()
        .map(|e| (e.target_key, e.edge_type))
        .collect()
}

/// Get outgoing edges with full info including signature properties.
fn get_outgoing_edges_full(graph: &GraphEngine, entity_key: &str) -> Vec<EdgeInfo> {
    let Some(node_id) = find_entity_node(graph, entity_key) else {
        return Vec::new();
    };

    let mut result = Vec::new();
    if let Ok(edges) = graph.edges_of(node_id, Direction::Outgoing) {
        for edge in edges {
            let target_id = if edge.from == node_id {
                edge.to
            } else {
                edge.from
            };
            if let Some(target_key) = get_entity_key(graph, target_id) {
                let signature = match edge.properties.get("vault_sig") {
                    Some(PropertyValue::Bytes(b)) => Some(b.clone()),
                    _ => None,
                };
                let sig_timestamp = match edge.properties.get("vault_sig_ts") {
                    Some(PropertyValue::Int(ts)) => Some(*ts),
                    _ => None,
                };
                let capacity = match edge.properties.get("vault_capacity") {
                    Some(PropertyValue::Int(c)) => Some(*c),
                    _ => None,
                };
                result.push(EdgeInfo {
                    target_key,
                    source_key: entity_key.to_string(),
                    edge_type: edge.edge_type.clone(),
                    signature,
                    sig_timestamp,
                    capacity,
                });
            }
        }
    }
    result
}

/// Get incoming edges for an entity, returning (source_key, edge_type).
fn get_incoming_edges(graph: &GraphEngine, entity_key: &str) -> Vec<(String, String)> {
    let Some(node_id) = find_entity_node(graph, entity_key) else {
        return Vec::new();
    };

    let mut result = Vec::new();
    if let Ok(edges) = graph.edges_of(node_id, Direction::Incoming) {
        for edge in edges {
            let source_id = if edge.to == node_id {
                edge.from
            } else {
                edge.to
            };
            if let Some(source_key) = get_entity_key(graph, source_id) {
                result.push((source_key, edge.edge_type.clone()));
            }
        }
    }
    result
}

/// Add an edge between two entity keys (test helper).
#[cfg(test)]
fn add_edge(graph: &GraphEngine, from_key: &str, to_key: &str, edge_type: &str) -> u64 {
    let from_node = get_or_create_entity_node(graph, from_key);
    let to_node = get_or_create_entity_node(graph, to_key);
    graph
        .create_edge(from_node, to_node, edge_type, HashMap::new(), true)
        .unwrap_or(0)
}

/// Edge type prefix for vault access grants.
const VAULT_ACCESS_PREFIX: &str = "VAULT_ACCESS";

/// Allowlisted edge types that can be traversed during access control checks.
/// Only these edge types can grant transitive access permissions.
/// - VAULT_ACCESS_* edges grant explicit vault permissions
/// - MEMBER edges allow group membership traversal
const ALLOWED_TRAVERSAL_EDGES: &[&str] = &[
    "VAULT_ACCESS",
    "VAULT_ACCESS_READ",
    "VAULT_ACCESS_WRITE",
    "VAULT_ACCESS_ADMIN",
    "MEMBER",
];

/// Hard limit on BFS traversal depth to prevent DoS via long MEMBER chains.
const MAX_BFS_DEPTH: usize = 32;

/// Check if an edge type is allowed for access control traversal.
fn is_allowed_edge_type(edge_type: &str) -> bool {
    ALLOWED_TRAVERSAL_EDGES
        .iter()
        .any(|&allowed| edge_type.starts_with(allowed))
}

impl AccessController {
    /// Check if a path exists from source to target in the graph.
    ///
    /// Uses BFS following only outgoing edges from each node.
    /// Only traverses edges in the allowlist (VAULT_ACCESS_*, MEMBER).
    /// Returns true if path exists, false otherwise.
    pub fn check_path(graph: &GraphEngine, source: &str, target: &str) -> bool {
        if source == target {
            return true;
        }

        // BFS traversal - only follow outgoing edges with allowed types
        let mut visited = HashSet::new();
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();

        queue.push_back((source.to_string(), 0));
        visited.insert(source.to_string());

        while let Some((current, depth)) = queue.pop_front() {
            if depth >= MAX_BFS_DEPTH {
                continue;
            }

            for (to, edge_type) in get_outgoing_edges(graph, &current) {
                // Only traverse allowed edge types
                if !is_allowed_edge_type(&edge_type) {
                    continue;
                }

                if to == target {
                    return true;
                }

                if !visited.contains(&to) {
                    visited.insert(to.clone());
                    queue.push_back((to, depth + 1));
                }
            }
        }

        false
    }

    /// Get all entities that have direct access to a target via VAULT_ACCESS edges.
    pub fn get_direct_accessors(graph: &GraphEngine, target: &str) -> Vec<String> {
        let mut accessors = Vec::new();

        for (from, edge_type) in get_incoming_edges(graph, target) {
            if edge_type.starts_with(VAULT_ACCESS_PREFIX) {
                accessors.push(from);
            }
        }

        accessors
    }

    /// Get the highest permission level for a requester on a target.
    ///
    /// Returns None if no access path exists.
    ///
    /// SECURITY: MEMBER edges allow graph traversal but do NOT grant permission
    /// to the target. Only VAULT_ACCESS_* edges grant actual permissions.
    /// This prevents privilege escalation via group membership.
    pub fn get_permission_level(
        graph: &GraphEngine,
        source: &str,
        target: &str,
    ) -> Option<Permission> {
        if source == target {
            return Some(Permission::Admin);
        }

        // BFS traversal tracking the best permission found along each path
        let mut visited = HashSet::new();
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        let mut best_permission: Option<Permission> = None;

        queue.push_back((source.to_string(), 0));
        visited.insert(source.to_string());

        while let Some((current, depth)) = queue.pop_front() {
            if depth >= MAX_BFS_DEPTH {
                continue;
            }

            for (to, edge_type) in get_outgoing_edges(graph, &current) {
                // Only traverse allowed edge types
                if !is_allowed_edge_type(&edge_type) {
                    continue;
                }

                // SECURITY FIX: Only VAULT_ACCESS_* edges can grant permission
                // MEMBER edges allow traversal but do NOT grant permission to target
                if edge_type.starts_with(VAULT_ACCESS_PREFIX) {
                    if to == target {
                        // Found target via VAULT_ACCESS edge - extract permission
                        if let Some(perm) = Permission::from_edge_type(&edge_type) {
                            best_permission = Some(match best_permission {
                                None => perm,
                                Some(existing) => Self::max_permission(existing, perm),
                            });
                        }
                    }
                    // Don't continue traversal past VAULT_ACCESS edges
                    // (they point to secrets, not to groups)
                } else {
                    // MEMBER edge - allow traversal but no permission granted
                    if !visited.contains(&to) {
                        visited.insert(to.clone());
                        queue.push_back((to, depth + 1));
                    }
                }
            }
        }

        best_permission
    }

    /// Get the highest permission level with edge signature verification
    /// and distance-based attenuation.
    ///
    /// Like `get_permission_level`, but:
    /// - Verifies HMAC signatures on VAULT_ACCESS edges (tampered = skipped)
    /// - Unsigned (legacy) edges are accepted
    /// - Applies distance-based attenuation via `AttenuationPolicy`
    /// - BFS depth is bounded by the policy's `horizon`
    pub fn get_permission_level_verified(
        graph: &GraphEngine,
        source: &str,
        target: &str,
        signer: &EdgeSigner,
        policy: &AttenuationPolicy,
    ) -> Option<Permission> {
        if source == target {
            return Some(Permission::Admin);
        }

        let mut visited = HashSet::new();
        // (entity_key, depth) -- depth counts MEMBER hops traversed
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        let mut best_permission: Option<Permission> = None;

        queue.push_back((source.to_string(), 0));
        visited.insert(source.to_string());

        while let Some((current, depth)) = queue.pop_front() {
            // BFS depth bounded by attenuation horizon
            if depth >= policy.horizon {
                continue;
            }

            for edge in get_outgoing_edges_full(graph, &current) {
                if !is_allowed_edge_type(&edge.edge_type) {
                    continue;
                }

                if edge.edge_type.starts_with(VAULT_ACCESS_PREFIX) {
                    if edge.target_key == target {
                        // Verify signature if present; skip tampered edges
                        if let (Some(sig), Some(ts)) = (&edge.signature, edge.sig_timestamp) {
                            if !signer.verify_edge(
                                &edge.source_key,
                                &edge.target_key,
                                &edge.edge_type,
                                ts,
                                sig,
                            ) {
                                continue;
                            }
                        }
                        // The VAULT_ACCESS hop itself counts as +1
                        let total_hops = depth + 1;
                        if let Some(perm) = Permission::from_edge_type(&edge.edge_type) {
                            if let Some(attenuated) = policy.attenuate(perm, total_hops) {
                                // Apply bottleneck: capacity limits the effective permission
                                let effective = match edge.capacity.and_then(Permission::from_level)
                                {
                                    Some(cap) => Self::min_permission(attenuated, cap),
                                    None => attenuated,
                                };
                                best_permission = Some(match best_permission {
                                    None => effective,
                                    Some(existing) => Self::max_permission(existing, effective),
                                });
                            }
                        }
                    }
                } else if !visited.contains(&edge.target_key) {
                    visited.insert(edge.target_key.clone());
                    queue.push_back((edge.target_key, depth + 1));
                }
            }
        }

        best_permission
    }

    /// Check if a path exists with at least the required permission level.
    pub fn check_path_with_permission(
        graph: &GraphEngine,
        source: &str,
        target: &str,
        required: Permission,
    ) -> bool {
        match Self::get_permission_level(graph, source, target) {
            Some(perm) => perm.allows(required),
            None => false,
        }
    }

    /// Check permission with signature verification and attenuation.
    pub fn check_path_with_permission_verified(
        graph: &GraphEngine,
        source: &str,
        target: &str,
        required: Permission,
        signer: &EdgeSigner,
        policy: &AttenuationPolicy,
    ) -> bool {
        match Self::get_permission_level_verified(graph, source, target, signer, policy) {
            Some(perm) => perm.allows(required),
            None => false,
        }
    }

    fn max_permission(a: Permission, b: Permission) -> Permission {
        match (a, b) {
            (Permission::Admin, _) | (_, Permission::Admin) => Permission::Admin,
            (Permission::Write, _) | (_, Permission::Write) => Permission::Write,
            (Permission::Read, Permission::Read) => Permission::Read,
        }
    }

    fn min_permission(a: Permission, b: Permission) -> Permission {
        match (a, b) {
            (Permission::Read, _) | (_, Permission::Read) => Permission::Read,
            (Permission::Write, _) | (_, Permission::Write) => Permission::Write,
            (Permission::Admin, Permission::Admin) => Permission::Admin,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;

    #[test]
    fn test_node_creation_and_lookup() {
        let graph = GraphEngine::new();

        // Create a node
        let node_id = get_or_create_entity_node(&graph, "test:entity");
        assert!(node_id > 0, "Node should be created with positive ID");

        // Verify we can find it again
        let found = find_entity_node(&graph, "test:entity");
        assert_eq!(found, Some(node_id), "Should find the same node");

        // Verify the property is set correctly
        let node = graph.get_node(node_id).expect("Should get node");
        let key = node.properties.get("entity_key");
        assert_eq!(
            key,
            Some(&PropertyValue::String("test:entity".to_string())),
            "Node should have correct entity_key property"
        );
    }

    #[test]
    fn test_edge_creation_and_lookup() {
        let graph = GraphEngine::new();

        // Create edge
        let edge_id = add_edge(&graph, "from:a", "to:b", "TEST_EDGE");
        assert!(edge_id > 0, "Edge should be created");

        // Verify outgoing edges
        let outgoing = get_outgoing_edges(&graph, "from:a");
        assert_eq!(outgoing.len(), 1, "Should have 1 outgoing edge");
        assert_eq!(outgoing[0].0, "to:b", "Target should be to:b");
        assert_eq!(outgoing[0].1, "TEST_EDGE", "Edge type should be TEST_EDGE");
    }

    #[test]
    fn test_same_node() {
        let graph = GraphEngine::new();

        assert!(AccessController::check_path(
            &graph,
            "user:alice",
            "user:alice"
        ));
    }

    #[test]
    fn test_direct_path() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:api_key", "VAULT_ACCESS");

        assert!(AccessController::check_path(
            &graph,
            "user:alice",
            "secret:api_key"
        ));
        assert!(!AccessController::check_path(
            &graph,
            "user:bob",
            "secret:api_key"
        ));
    }

    #[test]
    fn test_transitive_path() {
        let graph = GraphEngine::new();

        // alice -> team -> secret
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:api_key", "VAULT_ACCESS");

        assert!(AccessController::check_path(
            &graph,
            "user:alice",
            "secret:api_key"
        ));
    }

    #[test]
    fn test_no_path() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:one", "VAULT_ACCESS");
        add_edge(&graph, "user:bob", "secret:two", "VAULT_ACCESS");

        assert!(!AccessController::check_path(
            &graph,
            "user:alice",
            "secret:two"
        ));
    }

    #[test]
    fn test_cycle_handling() {
        let graph = GraphEngine::new();

        // Create a cycle: a -> b -> c -> a using allowed MEMBER edges
        add_edge(&graph, "node:a", "node:b", "MEMBER");
        add_edge(&graph, "node:b", "node:c", "MEMBER");
        add_edge(&graph, "node:c", "node:a", "MEMBER");

        // Should not hang, should find path
        assert!(AccessController::check_path(&graph, "node:a", "node:c"));

        // d is not connected
        assert!(!AccessController::check_path(&graph, "node:a", "node:d"));
    }

    #[test]
    fn test_long_path() {
        let graph = GraphEngine::new();

        // Create a long chain: node:0 -> node:1 -> ... -> node:10 using allowed MEMBER edges
        for i in 0..10 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }

        // Forward direction works
        assert!(AccessController::check_path(&graph, "node:0", "node:10"));
        // Reverse direction should NOT work (directional access)
        assert!(!AccessController::check_path(&graph, "node:10", "node:0"));
    }

    #[test]
    fn test_disallowed_edge_type_blocked() {
        let graph = GraphEngine::new();

        // Create path using disallowed edge type
        add_edge(&graph, "node:a", "node:b", "RANDOM_EDGE");

        // Path should NOT be found because RANDOM_EDGE is not allowlisted
        assert!(!AccessController::check_path(&graph, "node:a", "node:b"));
    }

    #[test]
    fn test_directional_path() {
        let graph = GraphEngine::new();

        add_edge(&graph, "node:a", "node:b", "MEMBER");

        // Only forward direction works (a -> b)
        assert!(AccessController::check_path(&graph, "node:a", "node:b"));
        // Reverse does NOT work
        assert!(!AccessController::check_path(&graph, "node:b", "node:a"));
    }

    #[test]
    fn test_get_direct_accessors() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS");
        add_edge(&graph, "user:bob", "secret:key", "VAULT_ACCESS");
        add_edge(&graph, "user:carol", "secret:key", "OTHER_EDGE");

        let accessors = AccessController::get_direct_accessors(&graph, "secret:key");

        assert_eq!(accessors.len(), 2);
        assert!(accessors.contains(&"user:alice".to_string()));
        assert!(accessors.contains(&"user:bob".to_string()));
        assert!(!accessors.contains(&"user:carol".to_string()));
    }

    #[test]
    fn test_empty_graph() {
        let graph = GraphEngine::new();

        assert!(!AccessController::check_path(
            &graph,
            "user:alice",
            "secret:key"
        ));
    }

    #[test]
    fn test_concurrent_access_check() {
        use std::thread;

        let graph = Arc::new(GraphEngine::new());

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS");

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let graph = Arc::clone(&graph);
                thread::spawn(move || {
                    for _ in 0..100 {
                        let result =
                            AccessController::check_path(&graph, "user:alice", "secret:key");
                        assert!(result);
                    }
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }
    }

    // === Permission Level Tests ===

    #[test]
    fn test_permission_level_direct_read() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_READ");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Read));
    }

    #[test]
    fn test_permission_level_direct_write() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_WRITE");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Write));
    }

    #[test]
    fn test_permission_level_direct_admin() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_ADMIN");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Admin));
    }

    #[test]
    fn test_permission_level_backward_compat() {
        let graph = GraphEngine::new();

        // Old-style VAULT_ACCESS edge should be treated as Admin
        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Admin));
    }

    #[test]
    fn test_permission_level_transitive_minimum() {
        let graph = GraphEngine::new();

        // alice -> team (MEMBER) -> secret (VAULT_ACCESS_READ)
        // The path gives Alice only Read permission via the chain
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:key", "VAULT_ACCESS_READ");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Read));
    }

    #[test]
    fn test_permission_level_best_of_multiple_paths() {
        let graph = GraphEngine::new();

        // Alice has two paths:
        // Path 1: alice -> secret (VAULT_ACCESS_READ)
        // Path 2: alice -> team -> secret (VAULT_ACCESS_ADMIN)
        // Should get Admin (best of both)
        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_READ");
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:key", "VAULT_ACCESS_ADMIN");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Admin));
    }

    #[test]
    fn test_permission_level_no_path() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:bob", "secret:key", "VAULT_ACCESS_READ");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, None);
    }

    #[test]
    fn test_check_path_with_permission_read_ok() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_READ");

        assert!(AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Read
        ));
    }

    #[test]
    fn test_check_path_with_permission_read_denied_write() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_READ");

        // Read permission doesn't allow Write
        assert!(!AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Write
        ));
    }

    #[test]
    fn test_check_path_with_permission_write_allows_read() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_WRITE");

        // Write permission allows Read
        assert!(AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Read
        ));
    }

    #[test]
    fn test_check_path_with_permission_admin_allows_all() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_ADMIN");

        assert!(AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Read
        ));
        assert!(AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Write
        ));
        assert!(AccessController::check_path_with_permission(
            &graph,
            "user:alice",
            "secret:key",
            Permission::Admin
        ));
    }

    #[test]
    fn test_get_direct_accessors_with_permission_levels() {
        let graph = GraphEngine::new();

        add_edge(&graph, "user:alice", "secret:key", "VAULT_ACCESS_READ");
        add_edge(&graph, "user:bob", "secret:key", "VAULT_ACCESS_WRITE");
        add_edge(&graph, "user:carol", "secret:key", "VAULT_ACCESS_ADMIN");

        let accessors = AccessController::get_direct_accessors(&graph, "secret:key");

        assert_eq!(accessors.len(), 3);
        assert!(accessors.contains(&"user:alice".to_string()));
        assert!(accessors.contains(&"user:bob".to_string()));
        assert!(accessors.contains(&"user:carol".to_string()));
    }

    // === Security Tests for MEMBER Edge Permission ===

    #[test]
    fn test_member_edge_direct_to_secret_no_permission() {
        let graph = GraphEngine::new();

        // SECURITY: MEMBER edge directly to secret should NOT grant permission
        add_edge(&graph, "user:alice", "secret:key", "MEMBER");

        // Should return None - no VAULT_ACCESS_* edge to secret
        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, None);
    }

    #[test]
    fn test_member_chain_without_vault_access_no_permission() {
        let graph = GraphEngine::new();

        // alice -> team (MEMBER) -> secret (MEMBER)
        // SECURITY: This should NOT grant any permission
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:key", "MEMBER");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, None);
    }

    #[test]
    fn test_member_traversal_to_vault_access_grants_permission() {
        let graph = GraphEngine::new();

        // alice -> team (MEMBER) -> secret (VAULT_ACCESS_WRITE)
        // Should grant Write permission via the chain
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:key", "VAULT_ACCESS_WRITE");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Write));
    }

    #[test]
    fn test_member_with_mixed_access_paths() {
        let graph = GraphEngine::new();

        // alice -> team1 (MEMBER) -> secret (MEMBER) - no permission
        // alice -> team2 (MEMBER) -> secret (VAULT_ACCESS_READ) - Read permission
        // Should get Read from the valid path
        add_edge(&graph, "user:alice", "team:team1", "MEMBER");
        add_edge(&graph, "team:team1", "secret:key", "MEMBER");
        add_edge(&graph, "user:alice", "team:team2", "MEMBER");
        add_edge(&graph, "team:team2", "secret:key", "VAULT_ACCESS_READ");

        let perm = AccessController::get_permission_level(&graph, "user:alice", "secret:key");
        assert_eq!(perm, Some(Permission::Read));
    }

    #[test]
    fn test_check_path_still_works_with_member() {
        let graph = GraphEngine::new();

        // check_path (for path existence) should still work with MEMBER edges
        add_edge(&graph, "user:alice", "team:devs", "MEMBER");
        add_edge(&graph, "team:devs", "secret:key", "MEMBER");

        // Path exists (MEMBER edges connect the nodes)
        assert!(AccessController::check_path(
            &graph,
            "user:alice",
            "secret:key"
        ));
        // But no permission is granted
        assert_eq!(
            AccessController::get_permission_level(&graph, "user:alice", "secret:key"),
            None
        );
    }

    // === BFS Depth Limit Tests ===

    #[test]
    fn test_check_path_depth_limit_exceeded() {
        let graph = GraphEngine::new();

        // Chain of 35 MEMBER edges: node:0 -> node:1 -> ... -> node:35
        for i in 0..35 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }

        // 35 hops exceeds MAX_BFS_DEPTH (32), path should not be found
        assert!(!AccessController::check_path(&graph, "node:0", "node:35"));
    }

    #[test]
    fn test_check_path_within_depth_limit() {
        let graph = GraphEngine::new();

        // Chain of 30 MEMBER edges: node:0 -> node:1 -> ... -> node:30
        for i in 0..30 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }

        // 30 hops is within MAX_BFS_DEPTH (32), path should be found
        assert!(AccessController::check_path(&graph, "node:0", "node:30"));
    }

    #[test]
    fn test_get_permission_level_depth_limit_exceeded() {
        let graph = GraphEngine::new();

        // Chain of 35 MEMBER edges then a VAULT_ACCESS_WRITE edge
        for i in 0..35 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }
        add_edge(&graph, "node:35", "secret:key", "VAULT_ACCESS_WRITE");

        // 35 MEMBER hops exceeds MAX_BFS_DEPTH (32), should return None
        assert_eq!(
            AccessController::get_permission_level(&graph, "node:0", "secret:key"),
            None
        );
    }

    #[test]
    fn test_get_permission_level_within_depth_limit() {
        let graph = GraphEngine::new();

        // Chain of 30 MEMBER edges then a VAULT_ACCESS_WRITE edge
        for i in 0..30 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }
        add_edge(&graph, "node:30", "secret:key", "VAULT_ACCESS_WRITE");

        // 30 MEMBER hops is within MAX_BFS_DEPTH (32), should find permission
        assert_eq!(
            AccessController::get_permission_level(&graph, "node:0", "secret:key"),
            Some(Permission::Write)
        );
    }

    #[test]
    fn test_check_path_at_exact_boundary() {
        let graph = GraphEngine::new();

        // Chain of exactly 31 MEMBER edges: node:0 -> ... -> node:31
        // At depth 31, node:31 is enqueued with depth=31 which is < 32, so it
        // will be processed and its edges explored. A target at node:32 requires
        // the edge from node:31 (depth=31) to be explored, which succeeds.
        for i in 0..32 {
            add_edge(
                &graph,
                &format!("node:{i}"),
                &format!("node:{}", i + 1),
                "MEMBER",
            );
        }

        // 31 hops (depth 31) should still find node:32 as a neighbor
        assert!(AccessController::check_path(&graph, "node:0", "node:32"));

        // But 33 hops should fail: node:32 is enqueued at depth=32 and skipped
        add_edge(&graph, "node:32", "node:33", "MEMBER");
        assert!(!AccessController::check_path(&graph, "node:0", "node:33"));
    }
}