oxirs-fuseki 0.2.4

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
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
//! RDF-Native ReBAC Implementation
//!
//! This module implements ReBAC using RDF triples stored in a named graph,
//! enabling SPARQL-based policy queries and inference.
//!
//! ## RDF Schema
//!
//! Relationships are stored as RDF triples in the authorization graph:
//!
//! ```turtle
//! @prefix auth: <http://oxirs.org/auth#> .
//! @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
//!
//! # Named graph for authorization data
//! GRAPH <urn:oxirs:auth:relationships> {
//!
//!   # Subject-Relation-Object triples
//!   <user:alice> auth:owner <dataset:public> .
//!   <user:bob> auth:canRead <graph:http://example.org/g1> .
//!
//!   # Organization membership (for transitive permissions)
//!   <user:alice> auth:memberOf <organization:engineering> .
//!   <organization:engineering> auth:canAccess <dataset:internal> .
//!
//!   # Conditional relationships using reification
//!   _:r1 a auth:Relationship ;
//!        auth:subject <user:charlie> ;
//!        auth:relation auth:canRead ;
//!        auth:object <dataset:temporary> ;
//!        auth:notBefore "2025-01-01T00:00:00Z"^^xsd:dateTime ;
//!        auth:notAfter "2025-12-31T23:59:59Z"^^xsd:dateTime .
//! }
//! ```
//!
//! ## SPARQL Inference Rules
//!
//! Permission implication rules can be expressed as SPARQL CONSTRUCT queries:
//!
//! ```sparql
//! # Rule: owner implies canRead, canWrite, canDelete
//! CONSTRUCT {
//!   ?subject auth:canRead ?object .
//!   ?subject auth:canWrite ?object .
//!   ?subject auth:canDelete ?object .
//! }
//! WHERE {
//!   ?subject auth:owner ?object .
//! }
//! ```

use super::rebac::{
    CheckRequest, CheckResponse, RebacError, RebacEvaluator, RelationshipCondition,
    RelationshipTuple, Result,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, instrument, warn};

/// Authorization vocabulary namespace
const AUTH_NS: &str = "http://oxirs.org/auth#";

/// Named graph URI for storing authorization relationships
const AUTH_GRAPH: &str = "urn:oxirs:auth:relationships";

/// RDF-based ReBAC manager using SPARQL for policy queries
pub struct RdfRebacManager {
    /// Reference to RDF store (would be actual store in production)
    store: Arc<RwLock<MockRdfStore>>,
    /// Enable inference rules
    inference_enabled: bool,
}

impl RdfRebacManager {
    /// Create a new RDF-based ReBAC manager with mock store (for testing)
    pub fn new(store: Arc<RwLock<MockRdfStore>>) -> Self {
        Self {
            store,
            inference_enabled: true,
        }
    }

    /// Create a new RDF-based ReBAC manager with production OxiRS store
    pub fn with_store(store: crate::store::Store) -> RdfRebacManagerProduction {
        RdfRebacManagerProduction {
            store: Arc::new(OxiRdfStore::new(store)),
            inference_enabled: true,
        }
    }

    /// Enable or disable inference
    pub fn with_inference(mut self, enabled: bool) -> Self {
        self.inference_enabled = enabled;
        self
    }

    /// Generate SPARQL ASK query to check relationship
    fn generate_ask_query(request: &CheckRequest) -> String {
        let subject = Self::uri_escape(&request.subject);
        let relation = Self::relation_to_property(&request.relation);
        let object = Self::uri_escape(&request.object);

        format!(
            r#"
PREFIX auth: <{}>

ASK {{
  GRAPH <{}> {{
    <{}> {} <{}>
  }}
}}
"#,
            AUTH_NS, AUTH_GRAPH, subject, relation, object
        )
    }

    /// Generate SPARQL query to check with inference
    fn generate_ask_query_with_inference(request: &CheckRequest) -> String {
        let subject = Self::uri_escape(&request.subject);
        let relation = Self::relation_to_property(&request.relation);
        let object = Self::uri_escape(&request.object);

        // Include inference rules for permission implication
        format!(
            r#"
PREFIX auth: <{}>

ASK {{
  GRAPH <{}> {{
    {{
      # Direct relationship
      <{}> {} <{}>
    }}
    UNION
    {{
      # Implied by owner
      <{}> auth:owner <{}> .
      FILTER ({} IN (auth:canRead, auth:canWrite, auth:canDelete))
    }}
    UNION
    {{
      # Implied by canWrite (implies canRead)
      <{}> auth:canWrite <{}> .
      FILTER ({} = auth:canRead)
    }}
  }}
}}
"#,
            AUTH_NS,
            AUTH_GRAPH,
            subject,
            relation,
            object,
            subject,
            object,
            relation,
            subject,
            object,
            relation
        )
    }

    /// Generate SPARQL INSERT query to add relationship
    fn generate_insert_query(tuple: &RelationshipTuple) -> String {
        let subject = Self::uri_escape(&tuple.subject);
        let relation = Self::relation_to_property(&tuple.relation);
        let object = Self::uri_escape(&tuple.object);

        if tuple.condition.is_none() {
            // Simple triple insertion
            format!(
                r#"
PREFIX auth: <{}>

INSERT DATA {{
  GRAPH <{}> {{
    <{}> {} <{}>
  }}
}}
"#,
                AUTH_NS, AUTH_GRAPH, subject, relation, object
            )
        } else {
            // Reified relationship with condition
            Self::generate_reified_insert(tuple)
        }
    }

    /// Generate reified relationship insertion (for conditional relationships)
    fn generate_reified_insert(tuple: &RelationshipTuple) -> String {
        let subject = Self::uri_escape(&tuple.subject);
        let relation = Self::relation_to_property(&tuple.relation);
        let object = Self::uri_escape(&tuple.object);

        let mut triples = vec![
            format!("    [] a auth:Relationship ;"),
            format!("       auth:subject <{}> ;", subject),
            format!("       auth:relation {} ;", relation),
            format!("       auth:object <{}> ", object),
        ];

        if let Some(condition) = &tuple.condition {
            match condition {
                RelationshipCondition::TimeWindow {
                    not_before,
                    not_after,
                } => {
                    if let Some(nb) = not_before {
                        triples.push(format!(
                            "       ; auth:notBefore \"{}\"^^xsd:dateTime",
                            nb.to_rfc3339()
                        ));
                    }
                    if let Some(na) = not_after {
                        triples.push(format!(
                            "       ; auth:notAfter \"{}\"^^xsd:dateTime",
                            na.to_rfc3339()
                        ));
                    }
                }
                RelationshipCondition::IpAddress { allowed_ips } => {
                    for ip in allowed_ips {
                        triples.push(format!("       ; auth:allowedIp \"{}\"", ip));
                    }
                }
                RelationshipCondition::Attribute { key, value } => {
                    triples.push(format!(
                        "       ; auth:attribute [ auth:key \"{}\" ; auth:value \"{}\" ]",
                        key, value
                    ));
                }
            }
        }

        triples.push("    .".to_string());

        format!(
            r#"
PREFIX auth: <{}>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

INSERT DATA {{
  GRAPH <{}> {{
{}
  }}
}}
"#,
            AUTH_NS,
            AUTH_GRAPH,
            triples.join("\n")
        )
    }

    /// Generate SPARQL DELETE query to remove relationship
    fn generate_delete_query(tuple: &RelationshipTuple) -> String {
        let subject = Self::uri_escape(&tuple.subject);
        let relation = Self::relation_to_property(&tuple.relation);
        let object = Self::uri_escape(&tuple.object);

        format!(
            r#"
PREFIX auth: <{}>

DELETE WHERE {{
  GRAPH <{}> {{
    <{}> {} <{}>
  }}
}}
"#,
            AUTH_NS, AUTH_GRAPH, subject, relation, object
        )
    }

    /// Generate SPARQL query to list subject's relationships
    fn generate_list_subject_query(subject: &str) -> String {
        let subject_uri = Self::uri_escape(subject);

        format!(
            r#"
PREFIX auth: <{}>

SELECT ?relation ?object
WHERE {{
  GRAPH <{}> {{
    <{}> ?relation ?object .
    FILTER (STRSTARTS(STR(?relation), STR(auth:)))
  }}
}}
"#,
            AUTH_NS, AUTH_GRAPH, subject_uri
        )
    }

    /// Generate SPARQL query to list object's relationships
    fn generate_list_object_query(object: &str) -> String {
        let object_uri = Self::uri_escape(object);

        format!(
            r#"
PREFIX auth: <{}>

SELECT ?subject ?relation
WHERE {{
  GRAPH <{}> {{
    ?subject ?relation <{}> .
    FILTER (STRSTARTS(STR(?relation), STR(auth:)))
  }}
}}
"#,
            AUTH_NS, AUTH_GRAPH, object_uri
        )
    }

    /// Generate optimized batch SPARQL query using UNION
    /// This allows checking multiple relationships in a single query
    fn generate_batch_ask_query(requests: &[CheckRequest]) -> String {
        let union_clauses: Vec<String> = requests
            .iter()
            .enumerate()
            .map(|(idx, request)| {
                let subject = Self::uri_escape(&request.subject);
                let relation = Self::relation_to_property(&request.relation);
                let object = Self::uri_escape(&request.object);

                format!(
                    r#"    {{
      # Request {}
      BIND({} AS ?request_id)
      <{}> {} <{}>
    }}"#,
                    idx, idx, subject, relation, object
                )
            })
            .collect();

        format!(
            r#"
PREFIX auth: <{}>

SELECT ?request_id
WHERE {{
  GRAPH <{}> {{
{}
  }}
}}
"#,
            AUTH_NS,
            AUTH_GRAPH,
            union_clauses.join("\n    UNION\n")
        )
    }

    /// Convert relation string to RDF property URI
    fn relation_to_property(relation: &str) -> String {
        match relation {
            "can_read" => "auth:canRead".to_string(),
            "can_write" => "auth:canWrite".to_string(),
            "can_delete" => "auth:canDelete".to_string(),
            "owner" => "auth:owner".to_string(),
            "member" => "auth:memberOf".to_string(),
            "can_access" => "auth:canAccess".to_string(),
            "can_manage" => "auth:canManage".to_string(),
            other => format!("auth:{}", other.replace('_', "")),
        }
    }

    /// Escape URI for SPARQL
    fn uri_escape(s: &str) -> String {
        // Simple URI escaping (in production, use proper URI encoding)
        s.to_string()
    }
}

#[async_trait]
impl RebacEvaluator for RdfRebacManager {
    #[instrument(skip(self))]
    async fn check(&self, request: &CheckRequest) -> Result<CheckResponse> {
        debug!(
            "RDF ReBAC check: {} --{}-> {}",
            request.subject, request.relation, request.object
        );

        let query = if self.inference_enabled {
            Self::generate_ask_query_with_inference(request)
        } else {
            Self::generate_ask_query(request)
        };

        debug!("SPARQL ASK query:\n{}", query);

        // Execute SPARQL ASK query
        let store = self.store.read().await;
        let allowed = store.execute_ask(&query).await?;

        Ok(CheckResponse {
            allowed,
            reason: if allowed {
                Some("Relationship exists in RDF store".to_string())
            } else {
                Some("No matching relationship found".to_string())
            },
        })
    }

    #[instrument(skip(self))]
    async fn add_tuple(&self, tuple: RelationshipTuple) -> Result<()> {
        debug!(
            "Adding RDF tuple: {} --{}-> {}",
            tuple.subject, tuple.relation, tuple.object
        );

        let query = Self::generate_insert_query(&tuple);
        debug!("SPARQL INSERT query:\n{}", query);

        let mut store = self.store.write().await;
        store.execute_update(&query).await?;

        Ok(())
    }

    #[instrument(skip(self))]
    async fn remove_tuple(&self, tuple: &RelationshipTuple) -> Result<()> {
        debug!(
            "Removing RDF tuple: {} --{}-> {}",
            tuple.subject, tuple.relation, tuple.object
        );

        let query = Self::generate_delete_query(tuple);
        debug!("SPARQL DELETE query:\n{}", query);

        let mut store = self.store.write().await;
        store.execute_update(&query).await?;

        Ok(())
    }

    async fn list_subject_tuples(&self, subject: &str) -> Result<Vec<RelationshipTuple>> {
        let query = Self::generate_list_subject_query(subject);

        let store = self.store.read().await;
        let results = store.execute_select(&query).await?;

        let tuples = results
            .into_iter()
            .map(|(relation, object)| RelationshipTuple::new(subject.to_string(), relation, object))
            .collect();

        Ok(tuples)
    }

    async fn list_object_tuples(&self, object: &str) -> Result<Vec<RelationshipTuple>> {
        let query = Self::generate_list_object_query(object);

        let store = self.store.read().await;
        let results = store.execute_select(&query).await?;

        let tuples = results
            .into_iter()
            .map(|(subject, relation)| {
                RelationshipTuple::new(subject, relation, object.to_string())
            })
            .collect();

        Ok(tuples)
    }

    /// Optimized batch check using SPARQL UNION query
    /// This is significantly more efficient than individual queries
    async fn batch_check(&self, requests: &[CheckRequest]) -> Result<Vec<CheckResponse>> {
        if requests.is_empty() {
            return Ok(Vec::new());
        }

        // Generate optimized SPARQL query with UNION clauses
        let query = Self::generate_batch_ask_query(requests);

        debug!(
            "Executing batch ReBAC check with {} requests",
            requests.len()
        );

        let store = self.store.read().await;
        let batch_results = store.execute_batch_ask(&query, requests.len()).await?;

        // Convert boolean results to CheckResponse
        let responses = batch_results
            .into_iter()
            .zip(requests.iter())
            .map(|(allowed, request)| {
                if allowed {
                    CheckResponse::allow()
                } else {
                    CheckResponse::deny(format!(
                        "{} does not have {} on {}",
                        request.subject, request.relation, request.object
                    ))
                }
            })
            .collect();

        Ok(responses)
    }
}

/// Production RDF store using actual OxiRS Store
pub struct OxiRdfStore {
    /// Reference to OxiRS Store
    store: crate::store::Store,
}

impl OxiRdfStore {
    /// Create a new RDF store adapter
    pub fn new(store: crate::store::Store) -> Self {
        Self { store }
    }

    /// Execute SPARQL ASK query
    async fn execute_ask(&self, query: &str) -> Result<bool> {
        use crate::error::FusekiError;
        use oxirs_core::query::QueryResult as CoreQueryResult;

        let result = self
            .store
            .query(query)
            .map_err(|e| RebacError::Internal(format!("SPARQL ASK query failed: {}", e)))?;

        match result.inner {
            CoreQueryResult::Ask(boolean) => Ok(boolean),
            _ => Err(RebacError::Internal(
                "Expected ASK query result".to_string(),
            )),
        }
    }

    /// Execute SPARQL UPDATE query
    async fn execute_update(&self, query: &str) -> Result<()> {
        self.store
            .update(query)
            .map_err(|e| RebacError::Internal(format!("SPARQL UPDATE failed: {}", e)))?;
        Ok(())
    }

    /// Execute SPARQL SELECT query
    async fn execute_select(&self, query: &str) -> Result<Vec<(String, String)>> {
        use oxirs_core::query::QueryResult as CoreQueryResult;

        let result = self
            .store
            .query(query)
            .map_err(|e| RebacError::Internal(format!("SPARQL SELECT query failed: {}", e)))?;

        match result.inner {
            CoreQueryResult::Select { bindings, .. } => {
                let mut results = Vec::new();
                for binding in bindings {
                    // Extract first two variables from bindings
                    let mut values: Vec<String> =
                        binding.values().map(|term| term.to_string()).collect();
                    if values.len() >= 2 {
                        results.push((values.remove(0), values.remove(0)));
                    }
                }
                Ok(results)
            }
            _ => Err(RebacError::Internal(
                "Expected SELECT query result".to_string(),
            )),
        }
    }
}

/// Production RDF-based ReBAC manager using actual OxiRS Store
pub struct RdfRebacManagerProduction {
    /// Reference to production RDF store
    store: Arc<OxiRdfStore>,
    /// Enable inference rules
    inference_enabled: bool,
}

impl RdfRebacManagerProduction {
    /// Enable or disable inference
    pub fn with_inference(mut self, enabled: bool) -> Self {
        self.inference_enabled = enabled;
        self
    }
}

#[async_trait]
impl RebacEvaluator for RdfRebacManagerProduction {
    async fn check(&self, request: &CheckRequest) -> Result<CheckResponse> {
        let query = if self.inference_enabled {
            RdfRebacManager::generate_ask_query_with_inference(request)
        } else {
            RdfRebacManager::generate_ask_query(request)
        };

        let allowed = self.store.execute_ask(&query).await?;

        Ok(CheckResponse {
            allowed,
            reason: if allowed {
                Some("Relationship exists in RDF store".to_string())
            } else {
                Some("No matching relationship found".to_string())
            },
        })
    }

    async fn add_tuple(&self, tuple: RelationshipTuple) -> Result<()> {
        let query = RdfRebacManager::generate_insert_query(&tuple);
        self.store.execute_update(&query).await?;
        Ok(())
    }

    async fn remove_tuple(&self, tuple: &RelationshipTuple) -> Result<()> {
        let query = RdfRebacManager::generate_delete_query(tuple);
        self.store.execute_update(&query).await?;
        Ok(())
    }

    async fn list_subject_tuples(&self, subject: &str) -> Result<Vec<RelationshipTuple>> {
        let query = RdfRebacManager::generate_list_subject_query(subject);
        let results = self.store.execute_select(&query).await?;

        let tuples = results
            .into_iter()
            .map(|(relation, object)| RelationshipTuple::new(subject.to_string(), relation, object))
            .collect();

        Ok(tuples)
    }

    async fn list_object_tuples(&self, object: &str) -> Result<Vec<RelationshipTuple>> {
        let query = RdfRebacManager::generate_list_object_query(object);
        let results = self.store.execute_select(&query).await?;

        let tuples = results
            .into_iter()
            .map(|(subject, relation)| {
                RelationshipTuple::new(subject, relation, object.to_string())
            })
            .collect();

        Ok(tuples)
    }

    async fn batch_check(&self, requests: &[CheckRequest]) -> Result<Vec<CheckResponse>> {
        let mut responses = Vec::with_capacity(requests.len());

        for request in requests {
            let response = self.check(request).await?;
            responses.push(response);
        }

        Ok(responses)
    }
}

/// Mock RDF store for testing
/// In production, use OxiRdfStore
pub struct MockRdfStore {
    /// In-memory storage for testing
    triples: Vec<(String, String, String)>,
}

impl MockRdfStore {
    pub fn new() -> Self {
        Self {
            triples: Vec::new(),
        }
    }

    async fn execute_ask(&self, _query: &str) -> Result<bool> {
        // Mock implementation - in production, use OxiRdfStore
        Ok(false)
    }

    async fn execute_update(&mut self, _query: &str) -> Result<()> {
        // Mock implementation - in production, use OxiRdfStore
        Ok(())
    }

    async fn execute_select(&self, _query: &str) -> Result<Vec<(String, String)>> {
        // Mock implementation - in production, use OxiRdfStore
        Ok(vec![])
    }

    async fn execute_batch_ask(&self, _query: &str, count: usize) -> Result<Vec<bool>> {
        // Mock implementation - returns false for all requests
        // In production, use OxiRdfStore to execute the UNION query
        Ok(vec![false; count])
    }
}

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

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

    #[test]
    fn test_generate_ask_query() {
        let request = CheckRequest::new("user:alice", "can_read", "dataset:public");
        let query = RdfRebacManager::generate_ask_query(&request);

        assert!(query.contains("ASK"));
        assert!(query.contains("<user:alice>"));
        assert!(query.contains("auth:canRead"));
        assert!(query.contains("<dataset:public>"));
    }

    #[test]
    fn test_generate_insert_query() {
        let tuple = RelationshipTuple::new("user:alice", "owner", "dataset:public");
        let query = RdfRebacManager::generate_insert_query(&tuple);

        assert!(query.contains("INSERT DATA"));
        assert!(query.contains("<user:alice>"));
        assert!(query.contains("auth:owner"));
        assert!(query.contains("<dataset:public>"));
    }

    #[test]
    fn test_generate_delete_query() {
        let tuple = RelationshipTuple::new("user:alice", "can_read", "dataset:public");
        let query = RdfRebacManager::generate_delete_query(&tuple);

        assert!(query.contains("DELETE WHERE"));
        assert!(query.contains("<user:alice>"));
        assert!(query.contains("auth:canRead"));
        assert!(query.contains("<dataset:public>"));
    }

    #[test]
    fn test_relation_to_property() {
        assert_eq!(
            RdfRebacManager::relation_to_property("can_read"),
            "auth:canRead"
        );
        assert_eq!(RdfRebacManager::relation_to_property("owner"), "auth:owner");
        assert_eq!(
            RdfRebacManager::relation_to_property("member"),
            "auth:memberOf"
        );
    }

    #[test]
    fn test_generate_reified_insert_with_time_condition() {
        let condition = RelationshipCondition::TimeWindow {
            not_before: Some(
                DateTime::parse_from_rfc3339("2025-01-01T00:00:00Z")
                    .unwrap()
                    .into(),
            ),
            not_after: Some(
                DateTime::parse_from_rfc3339("2025-12-31T23:59:59Z")
                    .unwrap()
                    .into(),
            ),
        };

        let tuple = RelationshipTuple::with_condition(
            "user:alice",
            "can_read",
            "dataset:temporary",
            condition,
        );

        let query = RdfRebacManager::generate_reified_insert(&tuple);

        assert!(query.contains("auth:Relationship"));
        assert!(query.contains("auth:subject"));
        assert!(query.contains("auth:notBefore"));
        assert!(query.contains("auth:notAfter"));
        assert!(query.contains("xsd:dateTime"));
    }
}