corteq 0.1.0

Enterprise-grade multi-tenant SaaS framework for Rust with security-first design
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
//! Critical security tests for tenant isolation
//!
//! These tests simulate adversarial scenarios and edge cases to ensure
//! the framework is resilient against various attack vectors:
//! - SQL injection attempts
//! - Malformed tenant IDs
//! - Token replay and manipulation
//! - Concurrent transaction isolation
//! - Cache poisoning
//! - Privilege escalation attempts
//!
//! Note: Tests that insert/delete data use #[serial] to avoid race conditions.

use corteq::{JwtService, MemoryTenantCache, TenantCache, TenantContext, TenantDatabase};
use serial_test::serial;
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;

/// Test tenant IDs from migration
const ACME_TENANT_ID: &str = "11111111-1111-1111-1111-111111111111";
const TEST_TENANT_ID: &str = "22222222-2222-2222-2222-222222222222";

/// Get database URL from environment or use default
/// Security tests require a non-superuser role to properly test RLS enforcement
fn get_database_url() -> String {
    std::env::var("RLS_DATABASE_URL")
        .or_else(|_| std::env::var("DATABASE_URL"))
        .unwrap_or_else(|_| {
            "postgres://corteq_app:corteq_app_pass@172.24.0.3:5432/corteq_test".to_string()
        })
}

/// Create a database connection pool for testing
async fn create_test_pool() -> PgPool {
    PgPool::connect(&get_database_url())
        .await
        .expect("Failed to connect to test database")
}

/// Create a tenant context for testing
fn create_tenant_context(tenant_id: Uuid) -> TenantContext {
    TenantContext::new(tenant_id, "test-tenant".to_string(), "test-key".to_string())
}

#[tokio::test]
async fn test_security_sql_injection_in_tenant_context() {
    let pool = create_test_pool().await;

    // Attempt SQL injection via tenant_id string representation
    // This should fail safely without allowing injection
    let malicious_tenant_id = "11111111-1111-1111-1111-111111111111' OR '1'='1";

    // The UUID parsing should fail, preventing injection
    let result = Uuid::parse_str(malicious_tenant_id);
    assert!(result.is_err(), "Malformed UUID should not parse");

    // Even if we bypass Uuid parsing, the database parameter binding should protect us
    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let tenant_ctx = create_tenant_context(acme_tenant_id);

    let mut db = TenantDatabase::begin(&pool, &tenant_ctx)
        .await
        .expect("Failed to begin transaction");

    // Test that parameterized queries prevent SQL injection
    // Try to inject SQL via the bound parameter
    let injection_attempt = "' OR '1'='1' --";
    let result =
        sqlx::query_as::<_, (Uuid, String)>("SELECT id, title FROM documents WHERE title = $1")
            .bind(injection_attempt)
            .fetch_all(db.connection())
            .await;

    // Should return no results - the injection string is treated as literal text
    assert!(result.is_ok());
    assert_eq!(
        result.unwrap().len(),
        0,
        "Parameterized query should treat injection attempt as literal string"
    );

    // Verify we can still query legitimate data
    let valid_docs: Vec<(Uuid, String)> =
        sqlx::query_as("SELECT id, title FROM documents WHERE deleted_at IS NULL")
            .fetch_all(db.connection())
            .await
            .expect("Valid query should work");

    assert_eq!(valid_docs.len(), 2, "Should see 2 Acme documents");

    db.rollback().await.expect("Failed to rollback");
}

#[tokio::test]
async fn test_security_malformed_tenant_id_uuid() {
    let pool = create_test_pool().await;

    // Various malformed UUID attempts
    let malformed_ids = vec![
        "not-a-uuid",
        "00000000-0000-0000-0000-000000000000", // nil UUID
        "ffffffff-ffff-ffff-ffff-ffffffffffff", // max UUID (probably doesn't exist)
        "",
        "12345",
        "../../../etc/passwd",
    ];

    for malformed in malformed_ids {
        let parse_result = Uuid::parse_str(malformed);

        if let Ok(uuid) = parse_result {
            // If it happens to parse as valid UUID, ensure it doesn't leak data
            let tenant_ctx = create_tenant_context(uuid);

            let mut db = TenantDatabase::begin(&pool, &tenant_ctx)
                .await
                .expect("Failed to begin transaction");

            let docs: Vec<(Uuid,)> =
                sqlx::query_as("SELECT id FROM documents WHERE deleted_at IS NULL")
                    .fetch_all(db.connection())
                    .await
                    .expect("Query should succeed");

            // Should return 0 documents for non-existent tenant
            assert_eq!(
                docs.len(),
                0,
                "Non-existent tenant should see no documents: {malformed}"
            );

            db.rollback().await.expect("Failed to rollback");
        } else {
            // Most malformed IDs should fail to parse
            assert!(
                parse_result.is_err(),
                "Malformed UUID should not parse: {malformed}"
            );
        }
    }
}

#[tokio::test]
#[serial]
async fn test_security_tenant_context_isolation_between_transactions() {
    let pool = create_test_pool().await;
    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let test_tenant_id = Uuid::parse_str(TEST_TENANT_ID).unwrap();

    // Transaction 1: Acme Corp
    let acme_ctx = create_tenant_context(acme_tenant_id);
    let mut acme_db = TenantDatabase::begin(&pool, &acme_ctx)
        .await
        .expect("Failed to begin Acme transaction");

    let acme_docs: Vec<(Uuid,)> =
        sqlx::query_as("SELECT id FROM documents WHERE deleted_at IS NULL")
            .fetch_all(acme_db.connection())
            .await
            .expect("Failed to query Acme documents");

    assert_eq!(acme_docs.len(), 2, "Acme should see 2 documents");

    // Transaction 2: Test Tenant (concurrent with Transaction 1)
    let test_ctx = create_tenant_context(test_tenant_id);
    let mut test_db = TenantDatabase::begin(&pool, &test_ctx)
        .await
        .expect("Failed to begin Test transaction");

    let test_docs: Vec<(Uuid,)> =
        sqlx::query_as("SELECT id FROM documents WHERE deleted_at IS NULL")
            .fetch_all(test_db.connection())
            .await
            .expect("Failed to query Test documents");

    assert_eq!(test_docs.len(), 2, "Test should see 2 documents");

    // Verify no overlap
    let acme_ids: Vec<Uuid> = acme_docs.into_iter().map(|d| d.0).collect();
    let test_ids: Vec<Uuid> = test_docs.into_iter().map(|d| d.0).collect();

    assert!(
        !acme_ids.iter().any(|id| test_ids.contains(id)),
        "Concurrent transactions should not see each other's data"
    );

    // Both transactions should commit successfully without interference
    acme_db.commit().await.expect("Acme commit failed");
    test_db.commit().await.expect("Test commit failed");
}

#[tokio::test]
async fn test_security_jwt_token_manipulation() {
    let jwt_service = JwtService::new(b"test-secret-key");

    let tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let user_id = Uuid::new_v4();

    // Create valid claims
    let valid_claims = corteq::auth::Claims {
        sub: user_id,
        tenant_id,
        roles: vec!["user".to_string()],
        exp: (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp(),
        iat: chrono::Utc::now().timestamp(),
    };

    let valid_token = jwt_service
        .encode(&valid_claims)
        .expect("Failed to encode token");

    // Test 1: Malformed token
    let malformed_tokens = vec![
        "not.a.token",
        "invalid",
        "",
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.invalid.signature",
    ];

    for malformed in malformed_tokens {
        let result = jwt_service.decode(malformed);
        assert!(
            result.is_err(),
            "Malformed token should not decode: {malformed}"
        );
    }

    // Test 2: Token with wrong signature (signed with different key)
    let wrong_key_service = JwtService::new(b"different-secret-key");
    let wrong_key_token = wrong_key_service
        .encode(&valid_claims)
        .expect("Failed to encode with wrong key");

    let result = jwt_service.decode(&wrong_key_token);
    assert!(
        result.is_err(),
        "Token signed with wrong key should not validate"
    );

    // Test 3: Expired token
    let expired_claims = corteq::auth::Claims {
        sub: user_id,
        tenant_id,
        roles: vec!["user".to_string()],
        exp: (chrono::Utc::now() - chrono::Duration::hours(1)).timestamp(), // Expired 1 hour ago
        iat: (chrono::Utc::now() - chrono::Duration::hours(2)).timestamp(),
    };

    let expired_token = jwt_service
        .encode(&expired_claims)
        .expect("Failed to encode expired token");

    let result = jwt_service.decode(&expired_token);
    assert!(result.is_err(), "Expired token should not validate");

    // Test 4: Valid token should work
    let result = jwt_service.decode(&valid_token);
    assert!(result.is_ok(), "Valid token should decode successfully");
}

#[tokio::test]
async fn test_security_cache_poisoning_attempt() {
    let cache: Arc<dyn TenantCache> = Arc::new(MemoryTenantCache::default());

    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let test_tenant_id = Uuid::parse_str(TEST_TENANT_ID).unwrap();

    // Create contexts
    let acme_ctx = TenantContext::new(
        acme_tenant_id,
        "acme-corp".to_string(),
        "acme-key".to_string(),
    );

    let test_ctx = TenantContext::new(
        test_tenant_id,
        "test-tenant".to_string(),
        "test-key".to_string(),
    );

    // Cache Acme context
    cache.set(acme_tenant_id, acme_ctx.clone()).await;

    // Try to retrieve with different tenant_id - should return None
    let result = cache.get(&test_tenant_id).await;
    assert!(
        result.is_none(),
        "Cache should not return wrong tenant context"
    );

    // Verify correct tenant_id returns correct context
    let result = cache.get(&acme_tenant_id).await;
    assert!(result.is_some());
    let cached = result.unwrap();
    assert_eq!(cached.tenant_id, acme_tenant_id);
    assert_eq!(cached.tenant_slug, "acme-corp");

    // Cache Test context
    cache.set(test_tenant_id, test_ctx.clone()).await;

    // Verify both contexts are isolated
    let acme_cached = cache.get(&acme_tenant_id).await.unwrap();
    let test_cached = cache.get(&test_tenant_id).await.unwrap();

    assert_ne!(acme_cached.tenant_id, test_cached.tenant_id);
    assert_ne!(acme_cached.tenant_slug, test_cached.tenant_slug);
    assert_ne!(acme_cached.encryption_key_id, test_cached.encryption_key_id);
}

#[tokio::test]
#[serial]
async fn test_security_concurrent_writes_no_cross_contamination() {
    let pool = create_test_pool().await;
    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let test_tenant_id = Uuid::parse_str(TEST_TENANT_ID).unwrap();

    let doc_id_1 = Uuid::new_v4();
    let doc_id_2 = Uuid::new_v4();
    let user_id = Uuid::new_v4();

    // Spawn concurrent transactions
    let pool_clone = pool.clone();
    let handle1 = tokio::spawn(async move {
        let acme_ctx = create_tenant_context(acme_tenant_id);
        let mut db = TenantDatabase::begin(&pool_clone, &acme_ctx)
            .await
            .expect("Failed to begin Acme transaction");

        sqlx::query(
            "INSERT INTO documents (id, tenant_id, title, content, created_by)
             VALUES ($1, $2, $3, $4, $5)",
        )
        .bind(doc_id_1)
        .bind(acme_tenant_id)
        .bind("Acme Concurrent Doc")
        .bind("Content from concurrent write")
        .bind(user_id)
        .execute(db.connection())
        .await
        .expect("Failed to insert Acme document");

        db.commit()
            .await
            .expect("Failed to commit Acme transaction");
    });

    let pool_clone = pool.clone();
    let handle2 = tokio::spawn(async move {
        let test_ctx = create_tenant_context(test_tenant_id);
        let mut db = TenantDatabase::begin(&pool_clone, &test_ctx)
            .await
            .expect("Failed to begin Test transaction");

        sqlx::query(
            "INSERT INTO documents (id, tenant_id, title, content, created_by)
             VALUES ($1, $2, $3, $4, $5)",
        )
        .bind(doc_id_2)
        .bind(test_tenant_id)
        .bind("Test Concurrent Doc")
        .bind("Content from concurrent write")
        .bind(user_id)
        .execute(db.connection())
        .await
        .expect("Failed to insert Test document");

        db.commit()
            .await
            .expect("Failed to commit Test transaction");
    });

    // Wait for both to complete
    handle1.await.expect("Handle 1 panicked");
    handle2.await.expect("Handle 2 panicked");

    // Verify each tenant can only see their own document
    let acme_ctx = create_tenant_context(acme_tenant_id);
    let mut acme_db = TenantDatabase::begin(&pool, &acme_ctx)
        .await
        .expect("Failed to begin Acme verification");

    let acme_doc: Option<(String,)> = sqlx::query_as("SELECT title FROM documents WHERE id = $1")
        .bind(doc_id_1)
        .fetch_optional(acme_db.connection())
        .await
        .expect("Failed to query Acme document");

    assert!(acme_doc.is_some());
    assert_eq!(acme_doc.unwrap().0, "Acme Concurrent Doc");

    // Acme should NOT see Test document
    let wrong_doc: Option<(String,)> = sqlx::query_as("SELECT title FROM documents WHERE id = $1")
        .bind(doc_id_2)
        .fetch_optional(acme_db.connection())
        .await
        .expect("Query should succeed");

    assert!(wrong_doc.is_none(), "Acme should not see Test document");

    acme_db
        .commit()
        .await
        .expect("Failed to commit verification");

    // Cleanup - delete from each tenant separately due to RLS
    let acme_ctx = create_tenant_context(acme_tenant_id);
    let mut acme_cleanup = TenantDatabase::begin(&pool, &acme_ctx).await.unwrap();
    sqlx::query("DELETE FROM documents WHERE id = $1")
        .bind(doc_id_1)
        .execute(acme_cleanup.connection())
        .await
        .ok();
    acme_cleanup.commit().await.ok();

    let test_ctx = create_tenant_context(test_tenant_id);
    let mut test_cleanup = TenantDatabase::begin(&pool, &test_ctx).await.unwrap();
    sqlx::query("DELETE FROM documents WHERE id = $1")
        .bind(doc_id_2)
        .execute(test_cleanup.connection())
        .await
        .ok();
    test_cleanup.commit().await.ok();
}

#[tokio::test]
async fn test_security_zero_uuid_tenant_id() {
    let pool = create_test_pool().await;

    // UUID with all zeros (nil UUID)
    let zero_uuid = Uuid::nil();
    let tenant_ctx = create_tenant_context(zero_uuid);

    let mut db = TenantDatabase::begin(&pool, &tenant_ctx)
        .await
        .expect("Failed to begin transaction");

    let docs: Vec<(Uuid,)> = sqlx::query_as("SELECT id FROM documents WHERE deleted_at IS NULL")
        .fetch_all(db.connection())
        .await
        .expect("Query should succeed");

    // Should return 0 documents for non-existent tenant
    assert_eq!(docs.len(), 0, "Nil UUID tenant should see no documents");

    db.rollback().await.expect("Failed to rollback");
}

#[tokio::test]
#[serial]
async fn test_security_transaction_rollback_does_not_leak_data() {
    let pool = create_test_pool().await;
    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();
    let new_doc_id = Uuid::new_v4();
    let user_id = Uuid::new_v4();

    // Start transaction and insert document
    let tenant_ctx = create_tenant_context(acme_tenant_id);
    let mut db = TenantDatabase::begin(&pool, &tenant_ctx)
        .await
        .expect("Failed to begin transaction");

    sqlx::query(
        "INSERT INTO documents (id, tenant_id, title, content, created_by)
         VALUES ($1, $2, $3, $4, $5)",
    )
    .bind(new_doc_id)
    .bind(acme_tenant_id)
    .bind("Rollback Test Document")
    .bind("This should not persist")
    .bind(user_id)
    .execute(db.connection())
    .await
    .expect("Insert should succeed");

    // Verify document is visible within transaction
    let doc: Option<(String,)> = sqlx::query_as("SELECT title FROM documents WHERE id = $1")
        .bind(new_doc_id)
        .fetch_optional(db.connection())
        .await
        .expect("Query should succeed");

    assert!(doc.is_some(), "Document should be visible in transaction");

    // Rollback the transaction
    db.rollback().await.expect("Failed to rollback");

    // Verify document does NOT exist after rollback
    let mut verify_db = TenantDatabase::begin(&pool, &tenant_ctx)
        .await
        .expect("Failed to begin verification transaction");

    let doc_after_rollback: Option<(String,)> =
        sqlx::query_as("SELECT title FROM documents WHERE id = $1")
            .bind(new_doc_id)
            .fetch_optional(verify_db.connection())
            .await
            .expect("Query should succeed");

    assert!(
        doc_after_rollback.is_none(),
        "Document should not exist after rollback"
    );

    verify_db
        .commit()
        .await
        .expect("Failed to commit verification");
}

#[tokio::test]
async fn test_security_empty_tenant_context_denies_access() {
    let pool = create_test_pool().await;

    // Query without TenantDatabase wrapper (no tenant context set)
    let docs: Vec<(Uuid,)> = sqlx::query_as("SELECT id FROM documents WHERE deleted_at IS NULL")
        .fetch_all(&pool)
        .await
        .expect("Query should succeed");

    assert_eq!(
        docs.len(),
        0,
        "No documents should be visible without tenant context (default deny)"
    );
}

#[tokio::test]
async fn test_security_session_variable_isolation() {
    let pool = create_test_pool().await;
    let acme_tenant_id = Uuid::parse_str(ACME_TENANT_ID).unwrap();

    // Set tenant context
    let tenant_ctx = create_tenant_context(acme_tenant_id);
    let mut db = TenantDatabase::begin(&pool, &tenant_ctx)
        .await
        .expect("Failed to begin transaction");

    // Verify the session variable is set correctly
    let current_tenant: Option<(String,)> =
        sqlx::query_as("SELECT current_setting('app.current_tenant_id', true)")
            .fetch_optional(db.connection())
            .await
            .expect("Query should succeed");

    assert!(current_tenant.is_some());
    assert_eq!(current_tenant.unwrap().0, acme_tenant_id.to_string());

    db.commit().await.expect("Failed to commit");

    // After transaction ends, session variable should not leak to new connections
    // Use COALESCE to handle NULL values from current_setting
    let leaked_tenant: Option<(String,)> = sqlx::query_as(
        "SELECT COALESCE(current_setting('app.current_tenant_id', true), '') AS tenant_id",
    )
    .fetch_optional(&pool)
    .await
    .expect("Query should succeed");

    // Should be empty string (transaction-scoped variable)
    assert!(leaked_tenant.is_some());
    let tenant_value = leaked_tenant.unwrap().0;
    assert!(
        tenant_value.is_empty(),
        "Tenant context should not leak across transactions, got: {tenant_value}"
    );
}