oxirs 0.2.4

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
//! ReBAC Manager - Core relationship management for authorization
//!
//! This module provides the core functionality for managing ReBAC (Relationship-Based Access Control)
//! relationships using RDF as the underlying storage format.

use crate::cli::error::{CliError, CliErrorKind, CliResult};
use oxirs_core::model::{
    BlankNode, GraphName, Literal, NamedNode, Object, Predicate, Quad, Subject,
};
use oxirs_core::RdfStore;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use tracing::{debug, info};

/// Authorization namespace for ReBAC relationships
pub const AUTH_NAMESPACE: &str = "http://oxirs.org/auth#";

/// Default graph URI for ReBAC relationships
pub const DEFAULT_GRAPH: &str = "urn:oxirs:auth:relationships";

/// ReBAC relationship tuple (subject, relation, object)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RelationshipTuple {
    /// Subject (e.g., "user:alice")
    pub subject: String,
    /// Relation (e.g., "owner", "can_read", "can_write")
    pub relation: String,
    /// Object (e.g., "dataset:public", "graph:`http://example.org/g1`")
    pub object: String,
    /// Optional condition (e.g., temporal constraints, context)
    pub condition: Option<String>,
}

impl RelationshipTuple {
    /// Create a new relationship tuple
    pub fn new(
        subject: impl Into<String>,
        relation: impl Into<String>,
        object: impl Into<String>,
    ) -> Self {
        Self {
            subject: subject.into(),
            relation: relation.into(),
            object: object.into(),
            condition: None,
        }
    }

    /// Create a new conditional relationship tuple
    pub fn with_condition(
        subject: impl Into<String>,
        relation: impl Into<String>,
        object: impl Into<String>,
        condition: impl Into<String>,
    ) -> Self {
        Self {
            subject: subject.into(),
            relation: relation.into(),
            object: object.into(),
            condition: Some(condition.into()),
        }
    }

    /// Convert to RDF quad
    pub fn to_quad(&self, namespace: &str, graph_uri: &str) -> CliResult<Quad> {
        let subject = self.parse_subject(&self.subject)?;
        let predicate_node = NamedNode::new(format!("{}{}", namespace, self.relation))
            .map_err(|e| CliError::validation_error(format!("Invalid relation: {}", e)))?;
        let predicate = Predicate::NamedNode(predicate_node);
        let object = self.parse_object(&self.object)?;
        let graph_node = NamedNode::new(graph_uri)
            .map_err(|e| CliError::validation_error(format!("Invalid graph URI: {}", e)))?;
        let graph = GraphName::NamedNode(graph_node);

        Ok(Quad::new(subject, predicate, object, graph))
    }

    /// Parse subject string to RDF Subject
    fn parse_subject(&self, s: &str) -> CliResult<Subject> {
        if s.starts_with("_:") {
            Ok(Subject::BlankNode(
                BlankNode::new(s.trim_start_matches("_:")).map_err(|e| {
                    CliError::validation_error(format!("Invalid blank node: {}", e))
                })?,
            ))
        } else if s.contains(':') {
            Ok(Subject::NamedNode(NamedNode::new(s).map_err(|e| {
                CliError::validation_error(format!("Invalid subject: {}", e))
            })?))
        } else {
            // Assume user/dataset/graph prefix
            Ok(Subject::NamedNode(
                NamedNode::new(format!("urn:oxirs:auth:{}", s))
                    .map_err(|e| CliError::validation_error(format!("Invalid subject: {}", e)))?,
            ))
        }
    }

    /// Parse object string to RDF Object
    fn parse_object(&self, s: &str) -> CliResult<Object> {
        if s.starts_with("_:") {
            Ok(Object::BlankNode(
                BlankNode::new(s.trim_start_matches("_:")).map_err(|e| {
                    CliError::validation_error(format!("Invalid blank node: {}", e))
                })?,
            ))
        } else if s.starts_with('"') {
            // Literal value
            Ok(Object::Literal(Literal::new_simple_literal(
                s.trim_matches('"'),
            )))
        } else if s.contains(':') {
            Ok(Object::NamedNode(NamedNode::new(s).map_err(|e| {
                CliError::validation_error(format!("Invalid object: {}", e))
            })?))
        } else {
            // Assume resource prefix
            Ok(Object::NamedNode(
                NamedNode::new(format!("urn:oxirs:auth:{}", s))
                    .map_err(|e| CliError::validation_error(format!("Invalid object: {}", e)))?,
            ))
        }
    }

    /// Create from RDF quad
    pub fn from_quad(quad: &Quad, namespace: &str) -> Option<Self> {
        let subject = match quad.subject() {
            Subject::NamedNode(n) => n.as_str().to_string(),
            Subject::BlankNode(b) => format!("_:{}", b.as_str()),
            _ => return None,
        };

        // Extract predicate string from Predicate enum
        use oxirs_core::model::Predicate;
        let predicate_str = match quad.predicate() {
            Predicate::NamedNode(n) => n.as_str(),
            Predicate::Variable(v) => v.as_str(),
        };

        let relation = if let Some(stripped) = predicate_str.strip_prefix(namespace) {
            stripped.to_string()
        } else {
            predicate_str.to_string()
        };

        let object = match quad.object() {
            Object::NamedNode(n) => n.as_str().to_string(),
            Object::BlankNode(b) => format!("_:{}", b.as_str()),
            Object::Literal(l) => format!("\"{}\"", l.value()),
            Object::Variable(v) => v.as_str().to_string(),
            Object::QuotedTriple(_) => return None, // Skip quoted triples for now
        };

        Some(Self {
            subject,
            relation,
            object,
            condition: None,
        })
    }
}

/// Backend storage type for ReBAC
#[derive(Debug, Clone, Copy)]
pub enum StorageBackend {
    /// In-memory storage (fast, non-persistent)
    InMemory,
    /// RDF-native storage using oxirs-tdb (persistent)
    RdfNative,
}

/// ReBAC Manager for managing authorization relationships
pub struct RebacManager {
    /// RDF store for relationship storage
    store: RdfStore,
    /// Authorization namespace
    namespace: String,
    /// Default graph URI
    graph_uri: String,
    /// Backend type
    backend: StorageBackend,
}

impl RebacManager {
    /// Create a new in-memory ReBAC manager
    pub fn new_in_memory() -> CliResult<Self> {
        let store = RdfStore::new().map_err(|e| {
            CliError::new(CliErrorKind::Other(format!(
                "Failed to create store: {}",
                e
            )))
        })?;
        Ok(Self {
            store,
            namespace: AUTH_NAMESPACE.to_string(),
            graph_uri: DEFAULT_GRAPH.to_string(),
            backend: StorageBackend::InMemory,
        })
    }

    /// Create a new persistent ReBAC manager with RDF-native storage
    pub fn new_persistent(path: &Path) -> CliResult<Self> {
        let store = RdfStore::open(path).map_err(|e| {
            CliError::new(CliErrorKind::Other(format!("Failed to open store: {}", e)))
        })?;
        Ok(Self {
            store,
            namespace: AUTH_NAMESPACE.to_string(),
            graph_uri: DEFAULT_GRAPH.to_string(),
            backend: StorageBackend::RdfNative,
        })
    }

    /// Set custom namespace
    pub fn with_namespace(mut self, namespace: String) -> Self {
        self.namespace = namespace;
        self
    }

    /// Set custom graph URI
    pub fn with_graph(mut self, graph_uri: String) -> Self {
        self.graph_uri = graph_uri;
        self
    }

    /// Get backend type
    pub fn backend(&self) -> StorageBackend {
        self.backend
    }

    /// Add a relationship tuple
    pub fn add_relationship(&mut self, tuple: &RelationshipTuple) -> CliResult<()> {
        let quad = tuple.to_quad(&self.namespace, &self.graph_uri)?;
        self.store.insert_quad(quad).map_err(|e| {
            CliError::new(CliErrorKind::Other(format!(
                "Failed to insert relationship: {}",
                e
            )))
        })?;
        debug!("Added relationship: {:?}", tuple);
        Ok(())
    }

    /// Add multiple relationships in batch
    pub fn add_relationships(&mut self, tuples: &[RelationshipTuple]) -> CliResult<usize> {
        let mut count = 0;
        for tuple in tuples {
            self.add_relationship(tuple)?;
            count += 1;
        }
        info!("Added {} relationships", count);
        Ok(count)
    }

    /// Remove a relationship tuple
    pub fn remove_relationship(&mut self, tuple: &RelationshipTuple) -> CliResult<bool> {
        let quad = tuple.to_quad(&self.namespace, &self.graph_uri)?;
        let removed = self.store.remove_quad(&quad).map_err(|e| {
            CliError::new(CliErrorKind::Other(format!(
                "Failed to remove relationship: {}",
                e
            )))
        })?;
        if removed {
            debug!("Removed relationship: {:?}", tuple);
        }
        Ok(removed)
    }

    /// Check if a relationship exists
    pub fn has_relationship(&self, tuple: &RelationshipTuple) -> CliResult<bool> {
        let quad = tuple.to_quad(&self.namespace, &self.graph_uri)?;
        Ok(self.store.contains_quad(&quad).unwrap_or(false))
    }

    /// Query relationships with optional filters
    pub fn query_relationships(
        &self,
        subject: Option<&str>,
        relation: Option<&str>,
        object: Option<&str>,
    ) -> CliResult<Vec<RelationshipTuple>> {
        // Query all quads in the ReBAC graph only
        let graph_node = NamedNode::new(&self.graph_uri)
            .map_err(|e| CliError::validation_error(format!("Invalid graph URI: {}", e)))?;
        let target_graph = GraphName::NamedNode(graph_node);

        let quads = self
            .store
            .query_quads(None, None, None, Some(&target_graph))
            .map_err(|e| {
                CliError::new(CliErrorKind::Other(format!("Failed to query quads: {}", e)))
            })?;

        let mut results = Vec::new();
        for quad in quads {
            if let Some(tuple) = RelationshipTuple::from_quad(&quad, &self.namespace) {
                // Apply filters
                if let Some(s) = subject {
                    if !tuple.subject.contains(s) {
                        continue;
                    }
                }
                if let Some(r) = relation {
                    if !tuple.relation.contains(r) {
                        continue;
                    }
                }
                if let Some(o) = object {
                    if !tuple.object.contains(o) {
                        continue;
                    }
                }
                results.push(tuple);
            }
        }

        Ok(results)
    }

    /// Get all relationships
    pub fn get_all_relationships(&self) -> CliResult<Vec<RelationshipTuple>> {
        self.query_relationships(None, None, None)
    }

    /// Get statistics about stored relationships
    pub fn get_statistics(&self) -> CliResult<RebacStatistics> {
        let all_tuples = self.get_all_relationships()?;

        let mut stats = RebacStatistics {
            total_relationships: all_tuples.len(),
            ..Default::default()
        };

        // Count by relation type
        for tuple in &all_tuples {
            *stats.by_relation.entry(tuple.relation.clone()).or_insert(0) += 1;
            *stats.by_subject.entry(tuple.subject.clone()).or_insert(0) += 1;
            *stats.by_object.entry(tuple.object.clone()).or_insert(0) += 1;

            if tuple.condition.is_some() {
                stats.conditional_relationships += 1;
            }
        }

        Ok(stats)
    }

    /// Check for duplicate relationships
    pub fn find_duplicates(&self) -> CliResult<Vec<RelationshipTuple>> {
        let all_tuples = self.get_all_relationships()?;
        let mut seen = HashSet::new();
        let mut duplicates = Vec::new();

        for tuple in all_tuples {
            let key = (
                tuple.subject.clone(),
                tuple.relation.clone(),
                tuple.object.clone(),
            );
            if !seen.insert(key) {
                duplicates.push(tuple);
            }
        }

        Ok(duplicates)
    }

    /// Check for orphaned relationships (subjects or objects that don't exist as entities)
    pub fn find_orphans(&self) -> CliResult<Vec<RelationshipTuple>> {
        let all_tuples = self.get_all_relationships()?;

        // Collect all subjects and objects
        let mut entities = HashSet::new();
        for tuple in &all_tuples {
            entities.insert(tuple.subject.clone());
            entities.insert(tuple.object.clone());
        }

        // Find orphans (relationships pointing to non-existent entities)
        let mut orphans = Vec::new();
        for tuple in all_tuples {
            // Check if object exists as a subject somewhere
            let object_exists = entities.contains(&tuple.object);
            if !object_exists
                && !tuple.object.starts_with("dataset:")
                && !tuple.object.starts_with("graph:")
            {
                orphans.push(tuple);
            }
        }

        Ok(orphans)
    }

    /// Clear all relationships
    pub fn clear_all(&mut self) -> CliResult<usize> {
        let all_tuples = self.get_all_relationships()?;
        let count = all_tuples.len();

        for tuple in all_tuples {
            self.remove_relationship(&tuple)?;
        }

        info!("Cleared {} relationships", count);
        Ok(count)
    }

    /// Export relationships to Turtle format
    pub fn export_turtle(&self) -> CliResult<String> {
        let tuples = self.get_all_relationships()?;
        let mut turtle = String::new();

        // Prefixes
        turtle.push_str("@prefix auth: <http://oxirs.org/auth#> .\n");
        turtle.push_str("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n");

        // Named graph
        turtle.push_str(&format!("<{}> {{\n", self.graph_uri));

        // Relationships
        for tuple in tuples {
            turtle.push_str(&format!(
                "  <{}> auth:{} <{}> .\n",
                tuple.subject, tuple.relation, tuple.object
            ));
        }

        turtle.push_str("}\n");

        Ok(turtle)
    }

    /// Export relationships to JSON format
    pub fn export_json(&self) -> CliResult<String> {
        let tuples = self.get_all_relationships()?;
        serde_json::to_string_pretty(&tuples).map_err(|e| {
            CliError::serialization_error(format!("Failed to serialize to JSON: {}", e))
        })
    }

    /// Import relationships from Turtle format
    pub fn import_turtle(&mut self, turtle: &str) -> CliResult<usize> {
        // Simple parsing for demo purposes
        // In production, use a proper Turtle parser
        let mut count = 0;
        for line in turtle.lines() {
            let line = line.trim();
            if line.is_empty()
                || line.starts_with('@')
                || line.starts_with('{')
                || line.starts_with('}')
            {
                continue;
            }

            // Parse triple: <subject> predicate <object> .
            if let Some(parts) = self.parse_turtle_triple(line) {
                let tuple = RelationshipTuple::new(parts.0, parts.1, parts.2);
                self.add_relationship(&tuple)?;
                count += 1;
            }
        }

        Ok(count)
    }

    /// Simple Turtle triple parser (for demo purposes)
    fn parse_turtle_triple(&self, line: &str) -> Option<(String, String, String)> {
        let line = line.trim_end_matches(" .").trim();
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() < 3 {
            return None;
        }

        let subject = parts[0].trim_matches('<').trim_matches('>').to_string();
        let predicate = parts[1].strip_prefix("auth:")?.to_string();
        let object = parts[2].trim_matches('<').trim_matches('>').to_string();

        Some((subject, predicate, object))
    }

    /// Import relationships from JSON format
    pub fn import_json(&mut self, json: &str) -> CliResult<usize> {
        let tuples: Vec<RelationshipTuple> = serde_json::from_str(json)
            .map_err(|e| CliError::serialization_error(format!("Failed to parse JSON: {}", e)))?;

        self.add_relationships(&tuples)
    }

    /// Verify data integrity
    pub fn verify_integrity(&self) -> CliResult<IntegrityReport> {
        let duplicates = self.find_duplicates()?;
        let orphans = self.find_orphans()?;
        let total = self.get_all_relationships()?.len();

        Ok(IntegrityReport {
            total_relationships: total,
            duplicates: duplicates.len(),
            orphans: orphans.len(),
            is_valid: duplicates.is_empty() && orphans.is_empty(),
        })
    }
}

/// Statistics about ReBAC relationships
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct RebacStatistics {
    pub total_relationships: usize,
    pub conditional_relationships: usize,
    pub by_relation: HashMap<String, usize>,
    pub by_subject: HashMap<String, usize>,
    pub by_object: HashMap<String, usize>,
}

/// Integrity verification report
#[derive(Debug, Serialize, Deserialize)]
pub struct IntegrityReport {
    pub total_relationships: usize,
    pub duplicates: usize,
    pub orphans: usize,
    pub is_valid: bool,
}

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

    #[test]
    fn test_relationship_tuple_creation() {
        let tuple = RelationshipTuple::new("user:alice", "owner", "dataset:public");
        assert_eq!(tuple.subject, "user:alice");
        assert_eq!(tuple.relation, "owner");
        assert_eq!(tuple.object, "dataset:public");
        assert!(tuple.condition.is_none());
    }

    #[test]
    fn test_relationship_tuple_with_condition() {
        let tuple =
            RelationshipTuple::with_condition("user:bob", "can_read", "dataset:secret", "time>9am");
        assert_eq!(tuple.subject, "user:bob");
        assert_eq!(tuple.condition, Some("time>9am".to_string()));
    }

    #[test]
    fn test_rebac_manager_creation() {
        let manager = RebacManager::new_in_memory();
        assert!(manager.is_ok());
    }

    #[test]
    fn test_add_and_query_relationships() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        let tuple1 = RelationshipTuple::new("user:alice", "owner", "dataset:public");
        let tuple2 = RelationshipTuple::new("user:bob", "can_read", "dataset:public");

        assert!(manager.add_relationship(&tuple1).is_ok());
        assert!(manager.add_relationship(&tuple2).is_ok());

        let all = manager.get_all_relationships().unwrap();
        assert_eq!(all.len(), 2);

        // Query by subject
        let alice_rels = manager
            .query_relationships(Some("alice"), None, None)
            .unwrap();
        assert_eq!(alice_rels.len(), 1);
        assert_eq!(alice_rels[0].subject, "user:alice");
    }

    #[test]
    fn test_remove_relationship() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        let tuple = RelationshipTuple::new("user:alice", "owner", "dataset:public");
        manager.add_relationship(&tuple).unwrap();

        assert!(manager.has_relationship(&tuple).unwrap());

        let removed = manager.remove_relationship(&tuple).unwrap();
        assert!(removed);
        assert!(!manager.has_relationship(&tuple).unwrap());
    }

    #[test]
    fn test_statistics() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        manager
            .add_relationship(&RelationshipTuple::new(
                "user:alice",
                "owner",
                "dataset:public",
            ))
            .unwrap();
        manager
            .add_relationship(&RelationshipTuple::new(
                "user:bob",
                "can_read",
                "dataset:public",
            ))
            .unwrap();
        manager
            .add_relationship(&RelationshipTuple::new(
                "user:charlie",
                "can_read",
                "dataset:internal",
            ))
            .unwrap();

        let stats = manager.get_statistics().unwrap();
        assert_eq!(stats.total_relationships, 3);
        assert_eq!(stats.by_relation.get("owner"), Some(&1));
        assert_eq!(stats.by_relation.get("can_read"), Some(&2));
    }

    #[test]
    fn test_find_duplicates() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        let tuple = RelationshipTuple::new("user:alice", "owner", "dataset:public");
        manager.add_relationship(&tuple).unwrap();
        manager.add_relationship(&tuple).unwrap(); // Attempt duplicate (RDF stores auto-deduplicate)

        // RDF stores automatically de-duplicate quads, so no duplicates should exist
        let duplicates = manager.find_duplicates().unwrap();
        assert_eq!(duplicates.len(), 0);

        // Verify that only one relationship exists
        let all = manager.get_all_relationships().unwrap();
        assert_eq!(all.len(), 1);
    }

    #[test]
    fn test_export_import_turtle() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        manager
            .add_relationship(&RelationshipTuple::new(
                "user:alice",
                "owner",
                "dataset:public",
            ))
            .unwrap();
        manager
            .add_relationship(&RelationshipTuple::new(
                "user:bob",
                "can_read",
                "dataset:public",
            ))
            .unwrap();

        let turtle = manager.export_turtle().unwrap();
        assert!(turtle.contains("user:alice"));
        assert!(turtle.contains("auth:owner"));

        let mut new_manager = RebacManager::new_in_memory().unwrap();
        let count = new_manager.import_turtle(&turtle).unwrap();
        assert_eq!(count, 2);

        let all = new_manager.get_all_relationships().unwrap();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_export_import_json() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        manager
            .add_relationship(&RelationshipTuple::new(
                "user:alice",
                "owner",
                "dataset:public",
            ))
            .unwrap();

        let json = manager.export_json().unwrap();
        assert!(json.contains("user:alice"));

        let mut new_manager = RebacManager::new_in_memory().unwrap();
        let count = new_manager.import_json(&json).unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_verify_integrity() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        manager
            .add_relationship(&RelationshipTuple::new(
                "user:alice",
                "owner",
                "dataset:public",
            ))
            .unwrap();
        manager
            .add_relationship(&RelationshipTuple::new(
                "user:bob",
                "can_read",
                "dataset:public",
            ))
            .unwrap();

        let report = manager.verify_integrity().unwrap();
        assert_eq!(report.total_relationships, 2);
        assert!(report.is_valid);
    }

    #[test]
    fn test_clear_all() {
        let mut manager = RebacManager::new_in_memory().unwrap();

        manager
            .add_relationship(&RelationshipTuple::new(
                "user:alice",
                "owner",
                "dataset:public",
            ))
            .unwrap();
        manager
            .add_relationship(&RelationshipTuple::new(
                "user:bob",
                "can_read",
                "dataset:public",
            ))
            .unwrap();

        let count = manager.clear_all().unwrap();
        assert_eq!(count, 2);

        let all = manager.get_all_relationships().unwrap();
        assert_eq!(all.len(), 0);
    }

    #[test]
    fn test_persistent_storage() {
        use std::time::{SystemTime, UNIX_EPOCH};

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let temp_dir = env::temp_dir().join(format!("rebac_test_{}", timestamp));
        std::fs::create_dir_all(&temp_dir).unwrap();

        {
            let mut manager = RebacManager::new_persistent(&temp_dir).unwrap();
            manager
                .add_relationship(&RelationshipTuple::new(
                    "user:alice",
                    "owner",
                    "dataset:public",
                ))
                .unwrap();
        }

        // Reopen and verify persistence
        {
            let manager = RebacManager::new_persistent(&temp_dir).unwrap();
            let all = manager.get_all_relationships().unwrap();
            assert_eq!(all.len(), 1);
        }

        // Cleanup
        std::fs::remove_dir_all(&temp_dir).unwrap();
    }
}