helios-persistence 0.1.47

Polyglot persistence layer for Helios FHIR Server
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
//! Tests for tenant data isolation.
//!
//! This module tests that data is properly isolated between tenants
//! and that all operations respect tenant boundaries.

use serde_json::json;

use helios_persistence::core::{ResourceStorage, SearchProvider};
use helios_persistence::tenant::{TenantContext, TenantId, TenantPermissions};
use helios_persistence::types::{Pagination, SearchQuery};

#[cfg(feature = "sqlite")]
use helios_persistence::backends::sqlite::SqliteBackend;

// ============================================================================
// Helper Functions
// ============================================================================

#[cfg(feature = "sqlite")]
fn create_sqlite_backend() -> SqliteBackend {
    let backend = SqliteBackend::in_memory().expect("Failed to create SQLite backend");
    backend.init_schema().expect("Failed to initialize schema");
    backend
}

fn create_tenant(id: &str) -> TenantContext {
    TenantContext::new(TenantId::new(id), TenantPermissions::full_access())
}

fn create_patient_json(name: &str) -> serde_json::Value {
    json!({
        "resourceType": "Patient",
        "name": [{"family": name}]
    })
}

// ============================================================================
// CRUD Isolation Tests
// ============================================================================

/// Test that created resources are only visible to their tenant.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_create_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create patient in tenant A
    let patient = create_patient_json("TenantA Patient");
    let created = backend.create(&tenant_a, "Patient", patient).await.unwrap();

    // Tenant A can read it
    let read_a = backend
        .read(&tenant_a, "Patient", created.id())
        .await
        .unwrap();
    assert!(read_a.is_some());

    // Tenant B cannot read it
    let read_b = backend
        .read(&tenant_b, "Patient", created.id())
        .await
        .unwrap();
    assert!(read_b.is_none());
}

/// Test that exists respects tenant isolation.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_exists_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    let patient = create_patient_json("Test");
    let created = backend.create(&tenant_a, "Patient", patient).await.unwrap();

    assert!(backend.exists(&tenant_a, "Patient", created.id()).await.unwrap());
    assert!(!backend.exists(&tenant_b, "Patient", created.id()).await.unwrap());
}

/// Test that read_batch only returns resources from the correct tenant.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_read_batch_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create patients in tenant A
    let p1 = backend
        .create(&tenant_a, "Patient", create_patient_json("A1"))
        .await
        .unwrap();
    let p2 = backend
        .create(&tenant_a, "Patient", create_patient_json("A2"))
        .await
        .unwrap();

    // Create patient in tenant B with known ID
    backend
        .create_or_update(&tenant_b, "Patient", "b-patient", create_patient_json("B1"))
        .await
        .unwrap();

    // Batch read from tenant A including B's patient ID
    let ids = vec![p1.id(), p2.id(), "b-patient"];
    let batch_a = backend
        .read_batch(&tenant_a, "Patient", &ids)
        .await
        .unwrap();

    // Should only get tenant A's patients
    assert_eq!(batch_a.len(), 2);
    for resource in &batch_a {
        assert_eq!(resource.tenant_id().as_str(), "tenant-a");
    }
}

/// Test that count only counts resources in the tenant.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_count_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create 5 patients in tenant A
    for i in 0..5 {
        backend
            .create(&tenant_a, "Patient", create_patient_json(&format!("A{}", i)))
            .await
            .unwrap();
    }

    // Create 3 patients in tenant B
    for i in 0..3 {
        backend
            .create(&tenant_b, "Patient", create_patient_json(&format!("B{}", i)))
            .await
            .unwrap();
    }

    let count_a = backend.count(&tenant_a, Some("Patient")).await.unwrap();
    let count_b = backend.count(&tenant_b, Some("Patient")).await.unwrap();

    assert_eq!(count_a, 5);
    assert_eq!(count_b, 3);
}

// ============================================================================
// Search Isolation Tests
// ============================================================================

/// Test that search only returns resources from the tenant.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_search_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create patients with same name in both tenants
    for i in 0..3 {
        backend
            .create(&tenant_a, "Patient", create_patient_json("Smith"))
            .await
            .unwrap();
    }

    for i in 0..2 {
        backend
            .create(&tenant_b, "Patient", create_patient_json("Smith"))
            .await
            .unwrap();
    }

    // Search in each tenant
    let query = SearchQuery::new("Patient");

    let result_a = backend
        .search(&tenant_a, &query, Pagination::new(100))
        .await
        .unwrap();
    let result_b = backend
        .search(&tenant_b, &query, Pagination::new(100))
        .await
        .unwrap();

    // Each tenant should only see their own
    assert_eq!(result_a.resources.len(), 3);
    for resource in &result_a.resources {
        assert_eq!(resource.tenant_id().as_str(), "tenant-a");
    }

    assert_eq!(result_b.resources.len(), 2);
    for resource in &result_b.resources {
        assert_eq!(resource.tenant_id().as_str(), "tenant-b");
    }
}

// ============================================================================
// Update and Delete Isolation Tests
// ============================================================================

/// Test that update cannot modify another tenant's resource.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_update_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create in tenant A
    let patient = create_patient_json("Original");
    let created = backend.create(&tenant_a, "Patient", patient).await.unwrap();

    // Create a fake resource with same ID but tenant B's context
    let fake_resource = helios_persistence::types::StoredResource::new(
        "Patient",
        created.id(),
        TenantId::new("tenant-b"),
        json!({"resourceType": "Patient"}),
    );

    // Try to update from tenant B
    let result = backend
        .update(&tenant_b, &fake_resource, json!({"resourceType": "Patient", "name": [{"family": "Hacked"}]}))
        .await;

    // Should fail
    assert!(result.is_err());

    // Original should be unchanged
    let original = backend
        .read(&tenant_a, "Patient", created.id())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(original.content()["name"][0]["family"], "Original");
}

/// Test that delete cannot remove another tenant's resource.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_delete_isolation() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create in tenant A
    let patient = create_patient_json("TenantA");
    let created = backend.create(&tenant_a, "Patient", patient).await.unwrap();

    // Try to delete from tenant B
    let result = backend.delete(&tenant_b, "Patient", created.id()).await;

    // Should fail (NotFound because B can't see A's resource)
    assert!(result.is_err());

    // Resource should still exist in tenant A
    assert!(backend.exists(&tenant_a, "Patient", created.id()).await.unwrap());
}

// ============================================================================
// Same ID in Different Tenants Tests
// ============================================================================

/// Test that same ID can exist in different tenants.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_same_id_different_tenants() {
    let backend = create_sqlite_backend();

    let tenant_a = create_tenant("tenant-a");
    let tenant_b = create_tenant("tenant-b");

    // Create patient with same ID in both tenants
    let patient_a = json!({
        "resourceType": "Patient",
        "name": [{"family": "TenantA Patient"}]
    });
    let patient_b = json!({
        "resourceType": "Patient",
        "name": [{"family": "TenantB Patient"}]
    });

    backend
        .create_or_update(&tenant_a, "Patient", "shared-id", patient_a)
        .await
        .unwrap();
    backend
        .create_or_update(&tenant_b, "Patient", "shared-id", patient_b)
        .await
        .unwrap();

    // Read from each tenant
    let read_a = backend
        .read(&tenant_a, "Patient", "shared-id")
        .await
        .unwrap()
        .unwrap();
    let read_b = backend
        .read(&tenant_b, "Patient", "shared-id")
        .await
        .unwrap()
        .unwrap();

    // Should be different resources
    assert_eq!(read_a.content()["name"][0]["family"], "TenantA Patient");
    assert_eq!(read_b.content()["name"][0]["family"], "TenantB Patient");
    assert_ne!(read_a.tenant_id(), read_b.tenant_id());
}

// ============================================================================
// System Tenant Tests
// ============================================================================

/// Test that system tenant resources can be accessed by other tenants.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_system_tenant_access() {
    let backend = create_sqlite_backend();

    let system = TenantContext::system();
    let tenant_a = create_tenant("tenant-a");

    // Create shared resource in system tenant
    let value_set = json!({
        "resourceType": "ValueSet",
        "name": "SharedValueSet"
    });
    let created = backend
        .create(&system, "ValueSet", value_set)
        .await
        .unwrap();

    // System tenant can read it
    let read_system = backend
        .read(&system, "ValueSet", created.id())
        .await
        .unwrap();
    assert!(read_system.is_some());

    // Regular tenants with system access permission should be able to access
    // (depends on permissions configuration)
}

/// Test that regular tenants cannot modify system resources.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_cannot_modify_system_resources() {
    let backend = create_sqlite_backend();

    let system = TenantContext::system();
    let tenant_a = create_tenant("tenant-a");

    // Create in system tenant
    let value_set = json!({
        "resourceType": "ValueSet",
        "name": "SystemValueSet"
    });
    let created = backend
        .create(&system, "ValueSet", value_set)
        .await
        .unwrap();

    // Regular tenant should not be able to delete it
    let result = backend.delete(&tenant_a, "ValueSet", created.id()).await;

    // Should fail
    assert!(result.is_err());
}

// ============================================================================
// Hierarchical Tenant Tests
// ============================================================================

/// Test parent tenant accessing child tenant resources (if permitted).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_hierarchical_tenant_access() {
    let backend = create_sqlite_backend();

    let parent = TenantContext::new(
        TenantId::new("parent"),
        TenantPermissions::builder()
            .can_access_child_tenants(true)
            .build(),
    );
    let child = create_tenant("parent/child");

    // Create in child tenant
    let patient = create_patient_json("ChildPatient");
    let created = backend.create(&child, "Patient", patient).await.unwrap();

    // Parent with child access permission might be able to read
    // (behavior depends on implementation)
    let read_parent = backend
        .read(&parent, "Patient", created.id())
        .await;

    // This test documents expected hierarchical access behavior
}