udb 0.4.21

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
use super::*;

const KEY: &[u8] = b"test-hash-secret";

#[test]
fn password_policy_enforces_complexity() {
    let policy = PasswordPolicy::default();
    assert!(policy.validate("CorrectHorse1!").is_ok());
    assert!(policy.validate("Ab1!").is_err(), "too short");
    assert!(policy.validate("correcthorse1!").is_err(), "no uppercase");
    assert!(policy.validate("CORRECTHORSE1!").is_err(), "no lowercase");
    assert!(policy.validate("CorrectHorse!!").is_err(), "no digit");
    assert!(policy.validate("CorrectHorse12").is_err(), "no symbol");
}

// ── Live-Postgres test harness ───────────────────────────────────────────────
// In-memory stores are forbidden — they pass while the real Postgres path is
// broken. The store-level tests below run against a live Postgres (gated by
// `UDB_LIVE_AUTH_TESTS=1` / `UDB_LIVE_AUTH_PG_DSN`) and reset the native auth
// schema first so each test starts clean. They are `#[ignore]`d so the default
// `cargo test` does not require a database; run them as the final check with:
//   UDB_LIVE_AUTH_TESTS=1 cargo test --lib runtime::authn -- --ignored --nocapture

fn live_pg_dsn() -> Option<String> {
    std::env::var("UDB_LIVE_AUTH_PG_DSN")
        .or_else(|_| std::env::var("UDB_INTEGRATION_PG_DSN"))
        .ok()
        .or_else(|| {
            std::env::var("UDB_LIVE_AUTH_TESTS")
                .ok()
                .filter(|v| matches!(v.as_str(), "1" | "true" | "yes"))
                .map(|_| "postgres://udb:udb@localhost:55432/udb".to_string())
        })
}

/// Connect to the live auth Postgres and re-create the native auth schema from
/// the proto-generated DDL, or return `None` when no live DB is configured.
async fn live_auth_pool() -> Option<sqlx::PgPool> {
    let dsn = live_pg_dsn()?;
    let pool = sqlx::postgres::PgPoolOptions::new()
        .max_connections(2)
        .acquire_timeout(std::time::Duration::from_secs(10))
        .connect(&dsn)
        .await
        .unwrap_or_else(|err| panic!("connect live auth postgres at {dsn}: {err}"));
    cleanup_live_auth_db(&pool).await;
    for stmt in crate::runtime::native_catalog::native_service_catalog_ddl() {
        sqlx::raw_sql(&stmt)
            .execute(&pool)
            .await
            .unwrap_or_else(|err| panic!("native auth DDL failed: {err}\nSQL:\n{stmt}"));
    }
    Some(pool)
}

async fn cleanup_live_auth_db(pool: &sqlx::PgPool) {
    // Drop EVERY native `udb_*` schema present, not just udb_authn/udb_authz:
    // `native_service_catalog_ddl()` creates all native schemas (udb_system,
    // udb_tenant, udb_control, …), so a DB carrying any of them from a prior run
    // makes the test's `CREATE SCHEMA` fail with "already exists". Enumerating the
    // live schemas makes this self-isolating on any DB (mirrors the non-auth
    // `cleanup_native_service_db` helper).
    let schemas: Vec<String> = sqlx::query_scalar(
        "SELECT nspname FROM pg_namespace WHERE nspname LIKE 'udb\\_%' ESCAPE '\\'",
    )
    .fetch_all(pool)
    .await
    .expect("list native udb_* schemas");
    for schema in schemas {
        let stmt = format!(
            "DROP SCHEMA IF EXISTS \"{}\" CASCADE",
            schema.replace('"', "\"\"")
        );
        sqlx::query(&stmt)
            .execute(pool)
            .await
            .unwrap_or_else(|err| panic!("drop native schema {schema}: {err}"));
    }
    // Migration-tracking tables live in `public`; drop them so a re-migrate is clean.
    let public_tables: Vec<String> =
        sqlx::query_scalar("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
            .fetch_all(pool)
            .await
            .expect("list public tables");
    for table in public_tables {
        let stmt = format!(
            "DROP TABLE IF EXISTS public.\"{}\" CASCADE",
            table.replace('"', "\"\"")
        );
        sqlx::query(&stmt)
            .execute(pool)
            .await
            .unwrap_or_else(|err| panic!("drop public table {table}: {err}"));
    }
    sqlx::query("DROP EXTENSION IF EXISTS pg_partman CASCADE")
        .execute(pool)
        .await
        .expect("drop pg_partman extension");
    sqlx::query("DROP SCHEMA IF EXISTS partman CASCADE")
        .execute(pool)
        .await
        .expect("drop partman schema");
}

fn test_now_unix() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0)
}

async fn seed_live_user(pool: &sqlx::PgPool, label: &str) -> String {
    let user_id = uuid::Uuid::new_v4().to_string();
    let suffix = uuid::Uuid::new_v4().simple().to_string();
    let now = test_now_unix();
    PostgresUserStore::new(pool.clone(), "")
        .put_user(UserRecord {
            user_id: user_id.clone(),
            username: format!("{label}_{suffix}"),
            email: format!("{label}_{suffix}@example.com"),
            password_hash: hash_secret("password", KEY),
            account_kind: AccountKind::Person,
            status: AccountStatus::Active,
            tenant_id: "acme".into(),
            full_name: label.to_string(),
            created_at_unix: now,
            updated_at_unix: now,
            profile_attributes_json: "{}".into(),
            ..Default::default()
        })
        .await
        .expect("seed live auth user");
    user_id
}

#[test]
fn hash_secret_is_deterministic_and_keyed() {
    let a = hash_secret("session-abc", KEY);
    let b = hash_secret("session-abc", KEY);
    assert_eq!(a, b, "same secret + key → same hash");
    assert!(a.starts_with("hmac-sha256:"));
    // Different key → different hash (a leaked DB without the key can't match).
    assert_ne!(a, hash_secret("session-abc", b"other-key"));
    // Different secret → different hash.
    assert_ne!(a, hash_secret("session-xyz", KEY));
    // The raw secret never appears in the stored form.
    assert!(!a.contains("session-abc"));
}

#[test]
fn password_hash_runtime_and_proto_contract_agree_on_argon2id() {
    let hashed = hash_password("CorrectHorse1!", KEY);
    assert!(hashed.starts_with("$argon2"));
    assert!(!password_hash_needs_upgrade(&hashed));
    assert!(password_hash_needs_upgrade(&hash_secret(
        "password:legacy",
        KEY
    )));

    let proto = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("proto/udb/core/authn/entity/v1/user.proto"),
    )
    .expect("read user proto");
    assert!(proto.contains("Argon2id PHC hash"));
    assert!(proto.contains("hashing_algorithm: \"argon2id\""));
    assert!(!proto.to_ascii_lowercase().contains("bcrypt"));
}

#[test]
fn session_hash_runtime_and_proto_contract_agree_on_hmac_sha256_storage_only() {
    let hashed = hash_secret("sess_raw", KEY);
    assert!(hashed.starts_with("hmac-sha256:"));
    assert!(!hashed.contains("sess_raw"));

    let proto = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("proto/udb/core/authn/entity/v1/session.proto"),
    )
    .expect("read session proto");
    assert!(proto.contains("hashing_algorithm: \"hmac-sha256\""));
    assert!(proto.contains("output_view: OUTPUT_VIEW_STORAGE_ONLY"));
    assert!(proto.contains("Keyed HMAC digest of the session token"));
    assert!(!proto.to_ascii_lowercase().contains("bcrypt"));
}

#[tokio::test]
#[ignore = "requires Postgres; run with UDB_LIVE_AUTH_TESTS=1 ... -- --ignored"]
async fn session_lifecycle_create_validate_expire_revoke() {
    let Some(pool) = live_auth_pool().await else {
        eprintln!("skipped: set UDB_LIVE_AUTH_TESTS=1 or UDB_LIVE_AUTH_PG_DSN");
        return;
    };
    let user_id = seed_live_user(&pool, "session_lifecycle").await;
    let store = PostgresSessionStore::new(pool, "");
    let raw = "sess-raw-123";
    let rec = SessionRecord {
        session_id_hash: hash_secret(raw, KEY),
        principal_id: "user_1".into(),
        user_id,
        tenant_id: "acme".into(),
        created_at_unix: test_now_unix(),
        updated_at_unix: test_now_unix(),
        expires_at_unix: 2000,
        ..Default::default()
    };
    store.put(&rec).await.unwrap();

    // Active before expiry.
    assert!(
        validate_session(&store, raw, KEY, 1500, 0)
            .await
            .unwrap()
            .is_some()
    );
    // Wrong raw id → no match (hash differs).
    assert!(
        validate_session(&store, "wrong", KEY, 1500, 0)
            .await
            .unwrap()
            .is_none()
    );
    // Expired at/after expires_at.
    assert!(
        validate_session(&store, raw, KEY, 2000, 0)
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        validate_session(&store, raw, KEY, 2500, 0)
            .await
            .unwrap()
            .is_none()
    );

    // Revoke → inactive even before expiry.
    assert!(store.revoke(&hash_secret(raw, KEY), 1200).await.unwrap());
    assert!(
        validate_session(&store, raw, KEY, 1500, 0)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
#[ignore = "requires Postgres; run with UDB_LIVE_AUTH_TESTS=1 ... -- --ignored"]
async fn refresh_session_extends_active_but_not_expired() {
    let Some(pool) = live_auth_pool().await else {
        eprintln!("skipped: set UDB_LIVE_AUTH_TESTS=1 or UDB_LIVE_AUTH_PG_DSN");
        return;
    };
    let user_id = seed_live_user(&pool, "refresh_session").await;
    let store = PostgresSessionStore::new(pool, "");
    let raw = "s1";
    let record = SessionRecord {
        session_id_hash: hash_secret(raw, KEY),
        principal_id: "u".into(),
        user_id,
        created_at_unix: test_now_unix(),
        updated_at_unix: test_now_unix(),
        expires_at_unix: 2000,
        ..Default::default()
    };
    store.put(&record).await.unwrap();
    // Active at 1500: refresh with ttl 1000 → new expiry 2500.
    let r = refresh_session(&store, raw, KEY, 1500, 1000)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(r.expires_at_unix, 2500);
    assert_eq!(r.updated_at_unix, 1500);
    assert!(
        validate_session(&store, raw, KEY, 2400, 0)
            .await
            .unwrap()
            .is_some()
    );
    // Once expired, it cannot be refreshed back to life.
    assert!(
        refresh_session(&store, raw, KEY, 3000, 1000)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
#[ignore = "requires Postgres; run with UDB_LIVE_AUTH_TESTS=1 ... -- --ignored"]
async fn revoke_all_for_principal_revokes_only_that_principal() {
    let Some(pool) = live_auth_pool().await else {
        eprintln!("skipped: set UDB_LIVE_AUTH_TESTS=1 or UDB_LIVE_AUTH_PG_DSN");
        return;
    };
    let user_1_id = seed_live_user(&pool, "revoke_user_1").await;
    let user_2_id = seed_live_user(&pool, "revoke_user_2").await;
    let store = PostgresSessionStore::new(pool, "");
    for (raw, principal) in [("a", "user_1"), ("b", "user_1"), ("c", "user_2")] {
        let user_id = if principal == "user_1" {
            user_1_id.clone()
        } else {
            user_2_id.clone()
        };
        let record = SessionRecord {
            session_id_hash: hash_secret(raw, KEY),
            principal_id: principal.into(),
            user_id,
            created_at_unix: test_now_unix(),
            updated_at_unix: test_now_unix(),
            expires_at_unix: 9999,
            ..Default::default()
        };
        store.put(&record).await.unwrap();
    }
    let revoked = store.revoke_all_for_principal("user_1", 500).await.unwrap();
    assert_eq!(revoked, 2);
    assert!(
        validate_session(&store, "a", KEY, 100, 0)
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        validate_session(&store, "b", KEY, 100, 0)
            .await
            .unwrap()
            .is_none()
    );
    // user_2's session is untouched.
    assert!(
        validate_session(&store, "c", KEY, 100, 0)
            .await
            .unwrap()
            .is_some()
    );
}

#[tokio::test]
#[ignore = "requires Postgres; run with UDB_LIVE_AUTH_TESTS=1 ... -- --ignored"]
async fn api_key_validate_hash_lookup_expiry_revocation() {
    let Some(pool) = live_auth_pool().await else {
        eprintln!("skipped: set UDB_LIVE_AUTH_TESTS=1 or UDB_LIVE_AUTH_PG_DSN");
        return;
    };
    let store = PostgresApiKeyStore::new(pool, "");
    let raw = "udbk_abc123.secretpart";
    store
        .put(ApiKeyRecord {
            key_prefix: api_key_prefix(raw),
            key_hash: hash_secret(raw, KEY),
            principal_id: "svc-1".into(),
            tenant_id: "acme".into(),
            scopes: vec!["udb:read".into()],
            expires_at_unix: 2000,
            ..Default::default()
        })
        .await
        .unwrap();

    assert_eq!(api_key_prefix(raw), "udbk_abc123");
    // Valid before expiry.
    assert!(
        validate_api_key(&store, raw, KEY, 1000)
            .await
            .unwrap()
            .is_some()
    );
    // Tampered secret with the same prefix → hash mismatch → reject.
    assert!(
        validate_api_key(&store, "udbk_abc123.WRONG", KEY, 1000)
            .await
            .unwrap()
            .is_none()
    );
    // Expired.
    assert!(
        validate_api_key(&store, raw, KEY, 2000)
            .await
            .unwrap()
            .is_none()
    );
    // Revoked.
    assert!(store.revoke("udbk_abc123", 500).await.unwrap());
    assert!(
        validate_api_key(&store, raw, KEY, 1000)
            .await
            .unwrap()
            .is_none()
    );
}

#[tokio::test]
#[ignore = "requires Postgres; run with UDB_LIVE_AUTH_TESTS=1 ... -- --ignored"]
async fn rotate_api_key_issues_new_and_revokes_old() {
    let Some(pool) = live_auth_pool().await else {
        eprintln!("skipped: set UDB_LIVE_AUTH_TESTS=1 or UDB_LIVE_AUTH_PG_DSN");
        return;
    };
    let store = PostgresApiKeyStore::new(pool, "");
    let old = "udbk_old.s1";
    store
        .put(ApiKeyRecord {
            key_prefix: api_key_prefix(old),
            key_hash: hash_secret(old, KEY),
            principal_id: "svc".into(),
            scopes: vec!["udb:read".into()],
            expires_at_unix: 9999,
            ..Default::default()
        })
        .await
        .unwrap();
    assert!(
        validate_api_key(&store, old, KEY, 100)
            .await
            .unwrap()
            .is_some()
    );

    let new = "udbk_new.s2";
    let template = ApiKeyRecord {
        principal_id: "svc".into(),
        scopes: vec!["udb:read".into()],
        expires_at_unix: 9999,
        ..Default::default()
    };
    let new_rec = rotate_api_key(&store, &api_key_prefix(old), new, KEY, 500, template)
        .await
        .unwrap();
    assert_eq!(new_rec.key_prefix, "udbk_new");

    // Old key no longer valid; new key valid.
    assert!(
        validate_api_key(&store, old, KEY, 600)
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        validate_api_key(&store, new, KEY, 600)
            .await
            .unwrap()
            .is_some()
    );
}

#[test]
fn auth_catalog_ddl_is_idempotent_and_covers_all_tables() {
    let ddl = auth_catalog_ddl("udb_system");
    let joined = ddl.join("\n");
    for fragment in [
        "CREATE TABLE IF NOT EXISTS \"udb_authn\".\"users\"",
        "CREATE TABLE IF NOT EXISTS \"udb_authn\".\"sessions\"",
        "CREATE TABLE IF NOT EXISTS \"udb_authn\".\"otps\"",
        "CREATE TABLE IF NOT EXISTS \"udb_authn\".\"api_keys\"",
    ] {
        assert!(
            joined.contains(fragment),
            "missing generated DDL fragment {fragment}"
        );
    }
    assert!(
        joined.contains("UDB:proto_manifest_checksum"),
        "native authn DDL must carry proto manifest metadata"
    );
}

#[test]
fn authn_config_defaults_and_sessions_usable_gate() {
    let cfg = AuthnConfig::default();
    assert!(!cfg.session_enabled);
    assert_eq!(cfg.session_backend, "postgres");
    assert_eq!(cfg.session_ttl_secs, 86_400);
    assert_eq!(cfg.session_idle_ttl_secs, 3_600);
    // Sessions require BOTH enabled and a hash secret (no raw-id storage).
    assert!(!cfg.sessions_usable());
    let ok = AuthnConfig {
        session_enabled: true,
        session_hash_secret: "secret".into(),
        ..AuthnConfig::default()
    };
    assert!(ok.sessions_usable());
    // Enabled but no secret → not usable.
    let no_secret = AuthnConfig {
        session_enabled: true,
        ..AuthnConfig::default()
    };
    assert!(!no_secret.sessions_usable());
}

#[test]
fn external_jwt_provider_maps_configured_claims() {
    let provider = ExternalJwtProvider::new(ExternalProviderConfig {
        provider_id: "auth0".into(),
        tenant_claim: "org_id".into(),
        roles_claim: "https://udb/roles".into(),
        ..ExternalProviderConfig::default()
    });
    let claims = r#"{
            "sub": "u1",
            "org_id": "acme",
            "project_id": "billing",
            "https://udb/roles": ["admin", "writer"],
            "scopes": "udb:read udb:write"
        }"#;
    let p = provider.map_identity("", claims).unwrap();
    assert_eq!(p.provider_id, "auth0");
    assert_eq!(p.subject, "u1");
    assert_eq!(p.principal_id, "auth0:u1");
    assert_eq!(p.tenant_id, "acme");
    assert_eq!(p.project_id, "billing");
    assert_eq!(p.roles, vec!["admin", "writer"]);
    // Space-separated scope string is split into a list.
    assert_eq!(p.scopes, vec!["udb:read", "udb:write"]);
    assert_eq!(p.auth_method, "external");
}

#[tokio::test]
async fn external_roles_alone_do_not_bypass_udb_policy() {
    use crate::runtime::authz::{AuthzPolicy, AuthzQuery, AuthzSnapshot, Effect, ResourceRef};
    use std::collections::BTreeMap;

    let provider = ExternalJwtProvider::new(ExternalProviderConfig::default());
    let principal = provider
        .map_identity("", r#"{"sub":"u1","tenant_id":"acme","roles":["admin"]}"#)
        .unwrap();
    let res = ResourceRef::message("acme.Invoice");
    let attrs = BTreeMap::new();
    let q = AuthzQuery {
        principal: &principal,
        resource: &res,
        action: "data.delete",
        purpose: "x",
        attributes: &attrs,
    };

    // No UDB policy → an externally-asserted "admin" role grants nothing.
    let empty = AuthzSnapshot {
        version: "v".into(),
        ..Default::default()
    };
    assert!(
        !empty.casbin_authorize(&q).await.allowed,
        "external roles must not bypass UDB authorization"
    );

    // Only a UDB-owned policy granting that role allows the action.
    let snap = AuthzSnapshot {
        version: "v".into(),
        policies: vec![AuthzPolicy {
            id: "p".into(),
            role: "admin".into(),
            action: "*".into(),
            effect: Effect::Allow,
            ..Default::default()
        }],
        ..Default::default()
    };
    assert!(snap.casbin_authorize(&q).await.allowed);
}