vcon-server 0.4.14

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
//! What must be refused.

use super::super::super::schema::{SCHEMA_VERSION, role_refusal, version_refusal};

#[test]
fn no_schema_is_refused_with_the_command_that_fixes_it() {
    let why = version_refusal(None).expect("refused");
    assert!(
        why.contains("no vCon schema") && why.contains("vcon-server migrate"),
        "says what is wrong and the command: {why}"
    );
}

#[test]
fn an_older_schema_is_refused_with_the_command_that_fixes_it() {
    let why = version_refusal(Some(SCHEMA_VERSION - 1)).expect("refused");
    assert!(
        why.contains("older") && why.contains("vcon-server migrate"),
        "older, and the command: {why}"
    );
}

#[test]
fn a_newer_schema_is_refused_as_newer_than_the_binary() {
    let why = version_refusal(Some(SCHEMA_VERSION + 1)).expect("refused");
    assert!(
        why.contains("newer than this binary"),
        "the design's words: {why}"
    );
    assert!(
        !why.contains("vcon-server migrate"),
        "migrate cannot fix a newer schema: {why}"
    );
}

#[test]
fn a_missing_owner_role_is_named() {
    let why = role_refusal("vcon_migrate", false, true, false).expect("refused");
    assert!(why.contains("vcon_owner"), "names the role: {why}");
}

#[test]
fn a_missing_application_role_is_named() {
    let why = role_refusal("vcon_migrate", true, false, true).expect("refused");
    assert!(why.contains("vcon_app"), "names the role: {why}");
}

#[test]
fn a_role_that_cannot_set_the_owner_is_named_with_the_grant() {
    let why = role_refusal("vcon_app", true, true, false).expect("refused");
    assert!(
        why.contains("\"vcon_app\"") && why.contains("GRANT vcon_owner"),
        "the role and the grant: {why}"
    );
}

#[cfg(feature = "backend-tests")]
mod on_a_server {
    use super::super::super::super::connect::Purpose;
    use super::super::super::super::schema::{
        COMMANDS_LOCK, MIGRATIONS, SCHEMA_VERSION, SERVERS_LOCK,
    };
    use super::super::super::live::{standby, value};
    use super::super::super::why;
    use super::super::live::{
        Db, REGISTRY_TABLES, TENANT_A, TENANT_B, TENANT_TABLES, count, in_scope,
        insert_registry_row, insert_tenant_row, no_scope,
    };

    fn is_no_tenant(result: &Result<(), String>) -> bool {
        result
            .as_ref()
            .err()
            .is_some_and(|e| e.contains("no tenant set"))
    }

    fn all_tables() -> Vec<&'static str> {
        TENANT_TABLES
            .iter()
            .chain(REGISTRY_TABLES)
            .copied()
            .collect()
    }

    #[tokio::test]
    async fn every_empty_table_refuses_a_select_with_no_tenant() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for table in all_tables() {
            let result = no_scope(&app, &format!("SELECT * FROM vcon.{table}")).await;
            if table == "tenant_lock" {
                // Since schema version 10 its read's rule is a CASE, which
                // the planner does not evaluate: with no row the read ends
                // with nothing, and with a row it is refused (v10.rs).
                assert_eq!(result, Ok(()), "{table}: no row, and no error");
                continue;
            }
            assert!(is_no_tenant(&result), "{table}: {result:?}");
        }
    }

    #[tokio::test]
    async fn every_table_refuses_an_insert_with_no_tenant() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for table in TENANT_TABLES {
            let result = no_scope(&app, &insert_tenant_row(table, TENANT_A)).await;
            assert!(is_no_tenant(&result), "{table}: {result:?}");
        }
        for table in REGISTRY_TABLES {
            let result = no_scope(&app, &insert_registry_row(table)).await;
            assert!(is_no_tenant(&result), "{table}: {result:?}");
        }
    }

    #[tokio::test]
    async fn every_table_refuses_an_update_or_delete_with_no_tenant() {
        let db = Db::migrated().await;
        let app = db.app().await;
        // The application role deletes no audit record and, since schema
        // version 11, no key of a tenant's log (schema_tests::v11); since
        // version 12, neither the id of the registry's key nor a key of
        // the registry's log (schema_tests::v12); since version 13 it
        // neither changes nor deletes the claim of the bucket prefix
        // (schema_tests::v13).
        let writable: Vec<&str> = all_tables()
            .into_iter()
            .filter(|t| {
                !matches!(
                    *t,
                    "audit"
                        | "audit_key"
                        | "admin_audit"
                        | "admin_audit_key"
                        | "registry_key"
                        | "storage_claim"
                )
            })
            .collect();
        for table in &writable {
            let column = match *table {
                "vcon" | "version" | "tombstone" | "key_use" | "parquet_file" | "purge_pending"
                | "manifest" | "tenant_lock" | "tenant_catalog" => "tenant",
                "tenant" => "name_mac",
                "master_key_use" => "master_key_id",
                "api_key" => "token_hash",
                "user_account" => "label_sealed",
                "membership" => "roles_sealed",
                "tenant_setting" => "value_sealed",
                "session" => "scopes_sealed",
                other => panic!("{other}"),
            };
            let result = no_scope(
                &app,
                &format!("UPDATE vcon.{table} SET {column} = {column}"),
            )
            .await;
            assert!(is_no_tenant(&result), "update {table}: {result:?}");
            let result = no_scope(&app, &format!("DELETE FROM vcon.{table}")).await;
            assert!(is_no_tenant(&result), "delete {table}: {result:?}");
        }
    }

    #[tokio::test]
    async fn every_table_with_rows_refuses_a_query_after_an_earlier_tenant() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for table in TENANT_TABLES {
            in_scope(&app, TENANT_A, &insert_tenant_row(table, TENANT_A))
                .await
                .expect("inserts");
        }
        for table in REGISTRY_TABLES {
            in_scope(&app, "registry", &insert_registry_row(table))
                .await
                .expect("inserts");
        }
        // The setting now exists on this connection, empty: the reused
        // connection case that a plain policy would read as no rows.
        for table in all_tables() {
            let result = no_scope(&app, &format!("SELECT * FROM vcon.{table}")).await;
            assert!(is_no_tenant(&result), "{table}: {result:?}");
        }
    }

    #[tokio::test]
    async fn the_version_table_is_refused_to_the_application_role() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for statement in [
            "SELECT * FROM vcon.schema_version",
            "INSERT INTO vcon.schema_version (version) VALUES (9)",
            "UPDATE vcon.schema_version SET version = 9",
            "DELETE FROM vcon.schema_version",
        ] {
            let result = no_scope(&app, statement).await;
            assert!(
                result
                    .as_ref()
                    .is_err_and(|e| e.contains("permission denied")),
                "{statement}: {result:?}"
            );
        }
    }

    #[tokio::test]
    async fn a_tenant_transaction_is_refused_the_registry() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for table in REGISTRY_TABLES {
            let result = in_scope(&app, TENANT_A, &format!("SELECT * FROM vcon.{table}")).await;
            let e = result.expect_err("refused");
            assert!(e.contains("is a tenant's"), "{table}: {e}");
        }
    }

    #[tokio::test]
    async fn the_registry_transaction_is_refused_a_tenants_rows() {
        let db = Db::migrated().await;
        let app = db.app().await;
        // Since schema version 10 the registry reads the lock rows, and
        // only reads them (v10.rs).
        for table in TENANT_TABLES
            .iter()
            .filter(|table| **table != "tenant_lock")
        {
            let result = in_scope(&app, "registry", &format!("SELECT * FROM vcon.{table}")).await;
            let e = result.expect_err("refused");
            assert!(e.contains("is the registry's"), "{table}: {e}");
        }
    }

    #[tokio::test]
    async fn a_row_for_another_tenant_is_refused() {
        let db = Db::migrated().await;
        let app = db.app().await;
        let e = in_scope(&app, TENANT_A, &insert_tenant_row("tombstone", TENANT_B))
            .await
            .expect_err("refused");
        assert!(
            e.contains("row-level security"),
            "the WITH CHECK refuses: {e}"
        );
    }

    #[tokio::test]
    async fn another_tenants_row_cannot_be_changed_or_removed() {
        let db = Db::migrated().await;
        let app = db.app().await;
        in_scope(&app, TENANT_A, &insert_tenant_row("key_use", TENANT_A))
            .await
            .expect("inserts");
        in_scope(&app, TENANT_B, "UPDATE vcon.key_use SET wraps = 99")
            .await
            .expect("no row, no error");
        in_scope(&app, TENANT_B, "DELETE FROM vcon.key_use")
            .await
            .expect("no row, no error");
        let rows = in_scope(&app, TENANT_A, "SELECT wraps FROM vcon.key_use")
            .await
            .expect("reads");
        let wraps = rows
            .iter()
            .find_map(|m| match m {
                tokio_postgres::SimpleQueryMessage::Row(r) => r.get(0).map(str::to_owned),
                _ => None,
            })
            .expect("the row");
        assert_eq!(wraps, "1", "tenant B changed nothing");
    }

    #[tokio::test]
    async fn a_malformed_tenant_setting_is_refused() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for scope in ["zz", "abcd", "00112233445566778899AABBCCDDEEFF"] {
            let e = in_scope(&app, scope, "SELECT * FROM vcon.vcon")
                .await
                .expect_err("refused");
            assert!(e.contains("not a tenant id"), "{scope}: {e}");
        }
    }

    #[tokio::test]
    async fn the_audit_log_cannot_be_deleted_changed_or_truncated() {
        let db = Db::migrated().await;
        let app = db.app().await;
        in_scope(&app, TENANT_A, &insert_tenant_row("audit", TENANT_A))
            .await
            .expect("inserts");
        for statement in [
            "DELETE FROM vcon.audit",
            "UPDATE vcon.audit SET action = 'changed'",
            "TRUNCATE vcon.audit",
        ] {
            let e = in_scope(&app, TENANT_A, statement)
                .await
                .expect_err("refused");
            assert!(e.contains("permission denied"), "{statement}: {e}");
        }
        for statement in [
            "DELETE FROM vcon.admin_audit",
            "UPDATE vcon.admin_audit SET action = 'changed'",
            "TRUNCATE vcon.admin_audit",
        ] {
            let e = in_scope(&app, "registry", statement)
                .await
                .expect_err("refused");
            assert!(e.contains("permission denied"), "{statement}: {e}");
        }
    }

    #[tokio::test]
    async fn the_application_role_cannot_change_the_schema() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for statement in [
            "CREATE TABLE vcon.evil (a int)",
            "DROP TABLE vcon.vcon",
            "ALTER TABLE vcon.vcon DISABLE ROW LEVEL SECURITY",
            "DROP POLICY tenant_rows ON vcon.vcon",
            "TRUNCATE vcon.version",
        ] {
            let result = no_scope(&app, statement).await;
            let e = result.expect_err("refused");
            assert!(
                e.contains("permission denied") || e.contains("must be owner"),
                "{statement}: {e}"
            );
        }
    }

    #[tokio::test]
    async fn a_serving_connection_to_a_database_with_no_schema_is_refused() {
        let db = Db::fresh().await;
        let why = why(db
            .connect("vcon_app", Purpose::Serve)
            .await
            .expect_err("refused"));
        assert!(
            why.contains("no vCon schema") && why.contains("vcon-server migrate"),
            "says so: {why}"
        );
    }

    #[tokio::test]
    async fn a_serving_connection_to_a_newer_schema_is_refused() {
        let db = Db::migrated().await;
        db.admin()
            .await
            .batch_execute(&format!(
                "SET ROLE vcon_owner; INSERT INTO vcon.schema_version (version) VALUES ({}); \
                 RESET ROLE",
                SCHEMA_VERSION + 1
            ))
            .await
            .expect("adds a version");
        let why = why(db
            .connect("vcon_app", Purpose::Serve)
            .await
            .expect_err("refused"));
        assert!(why.contains("newer than this binary"), "says so: {why}");
    }

    #[tokio::test]
    async fn a_serving_connection_as_a_member_of_the_owner_role_is_refused() {
        let db = Db::migrated().await;
        let why = why(db
            .connect("vcon_migrate", Purpose::Serve)
            .await
            .expect_err("refused"));
        assert!(
            why.contains("vcon_migrate") && why.contains("owns"),
            "names the role: {why}"
        );
    }

    #[tokio::test]
    async fn a_serving_connection_as_a_role_without_grants_is_refused() {
        let db = Db::migrated().await;
        let why = why(db
            .connect("vcon_stranger", Purpose::Serve)
            .await
            .expect_err("refused"));
        assert!(
            why.contains("vcon_stranger") && why.contains("vcon_app"),
            "names the role and the grant: {why}"
        );
    }

    #[tokio::test]
    async fn migrate_refuses_a_role_that_cannot_act_as_the_owner() {
        let db = Db::fresh().await;
        let why = why(db
            .connect("vcon_app", Purpose::Migrate)
            .await
            .expect_err("refused"));
        assert!(why.contains("GRANT vcon_owner"), "says so: {why}");
        assert_eq!(
            value(
                &db.admin().await,
                "SELECT to_regclass('vcon.schema_version') IS NULL"
            )
            .await,
            "t",
            "nothing was made"
        );
    }

    #[tokio::test]
    async fn migrate_refuses_while_a_server_holds_the_lock() {
        let db = Db::fresh().await;
        let holder = db.admin().await;
        holder
            .simple_query(&format!("SELECT pg_advisory_lock({SERVERS_LOCK})"))
            .await
            .expect("holds it");
        let e = db.migrate_with(MIGRATIONS).await.expect_err("refused");
        assert!(e.contains("another"), "says so: {e}");
        assert_eq!(
            value(&holder, "SELECT to_regclass('vcon.schema_version') IS NULL").await,
            "t",
            "and nothing was made"
        );
    }

    #[tokio::test]
    async fn migrate_refuses_while_a_command_holds_the_lock() {
        let db = Db::fresh().await;
        let holder = db.admin().await;
        holder
            .simple_query(&format!("SELECT pg_advisory_lock({COMMANDS_LOCK})"))
            .await
            .expect("holds it");
        let e = db.migrate_with(MIGRATIONS).await.expect_err("refused");
        assert!(e.contains("another"), "says so: {e}");
    }

    #[tokio::test]
    async fn migrate_refuses_while_a_lock_is_shared() {
        let db = Db::fresh().await;
        let holder = db.admin().await;
        holder
            .simple_query(&format!("SELECT pg_advisory_lock_shared({SERVERS_LOCK})"))
            .await
            .expect("holds it shared");
        let e = db.migrate_with(MIGRATIONS).await.expect_err("refused");
        assert!(
            e.contains("another"),
            "a shared holder is a server too: {e}"
        );
    }

    #[tokio::test]
    async fn a_migration_that_fails_leaves_nothing_behind() {
        let db = Db::fresh().await;
        let bad = "CREATE SCHEMA vcon; CREATE TABLE vcon.partial (a int); SELECT boom";
        let e = db.migrate_with(&[bad]).await.expect_err("refused");
        assert!(
            e.contains("boom") || e.contains("does not exist"),
            "the failure named: {e}"
        );
        assert_eq!(
            value(
                &db.admin().await,
                "SELECT to_regclass('vcon.partial') IS NULL"
            )
            .await,
            "t",
            "the transaction rolled back"
        );
    }

    #[tokio::test]
    async fn a_later_migration_that_fails_keeps_the_earlier_one() {
        let db = Db::fresh().await;
        let v2 = "CREATE TABLE vcon.extra (a int); SELECT boom";
        let e = db
            .migrate_with(&[MIGRATIONS[0], v2])
            .await
            .expect_err("refused");
        assert!(
            e.contains("boom") || e.contains("does not exist"),
            "named: {e}"
        );
        let admin = db.admin().await;
        assert_eq!(
            count(&admin, "SELECT count(*) FROM vcon.schema_version").await,
            1,
            "version 1 stayed committed"
        );
        assert_eq!(
            value(&admin, "SELECT to_regclass('vcon.extra') IS NULL").await,
            "t",
            "version 2 left nothing"
        );
    }

    #[tokio::test]
    async fn migrate_refuses_a_database_newer_than_the_binary() {
        let db = Db::migrated().await;
        db.admin()
            .await
            .batch_execute(&format!(
                "SET ROLE vcon_owner; INSERT INTO vcon.schema_version (version) VALUES ({}); \
                 RESET ROLE",
                SCHEMA_VERSION + 1
            ))
            .await
            .expect("adds a version");
        let e = db.migrate_with(MIGRATIONS).await.expect_err("refused");
        assert!(e.contains("newer than this binary"), "says so: {e}");
    }

    #[tokio::test]
    async fn migrate_refuses_a_schema_it_did_not_make() {
        let db = Db::fresh().await;
        db.admin()
            .await
            .batch_execute("SET ROLE vcon_owner; CREATE SCHEMA vcon; RESET ROLE")
            .await
            .expect("makes a schema");
        let e = db.migrate_with(MIGRATIONS).await.expect_err("refused");
        assert!(
            e.contains("vcon") && e.contains("did not make"),
            "says so: {e}"
        );
    }

    #[tokio::test]
    async fn migrate_refuses_a_standby() {
        let db = Db::fresh().await;
        // The standby answers as the primary would; only the port differs.
        let (_dir, mut settings) = db.settings("vcon_migrate");
        settings.port = standby();
        settings.dbname = "vcon".to_owned();
        let e = super::super::super::super::migrate(&settings)
            .await
            .expect_err("refused");
        assert!(e.0.contains("standby"), "says so: {}", e.0);
    }

    #[tokio::test]
    async fn no_message_holds_the_password_or_the_tenant_setting() {
        let db = Db::fresh().await;
        let password = super::super::super::live::password();
        let (_dir, settings) = db.settings("vcon_stranger");
        let e = super::super::super::super::migrate(&settings)
            .await
            .expect_err("refused");
        assert!(
            !e.0.contains(&password),
            "the refusal never holds the password: {}",
            e.0
        );
    }
}