vcon-server 0.4.18

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
//! Schema version 15: the registry records its tenant creates under way,
//! in the table `pending_tenant`, so recovery keeps the space of a create
//! that has not yet added its tenant's row (store/pending.rs); each tenant
//! its pack files under way, in `pending_file`; and the registry the
//! leases of the work one server does for all, in `lease`. Each live
//! test of the migration starts from a database at version 14.

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

/// The position of this version's migration.
const THIS: usize = 14;

/// This version's migration, or a panic that says there is none.
fn text() -> &'static str {
    assert!(
        MIGRATIONS.len() > THIS,
        "there are {} migrations",
        MIGRATIONS.len()
    );
    MIGRATIONS[THIS]
}

/// The migration's statements as one line, every run of white space one
/// space.
fn one_line() -> String {
    text()
        .lines()
        .filter(|line| !line.trim_start().starts_with("--"))
        .collect::<Vec<_>>()
        .join(" ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

/// The migration's comment as one line, without the comment marks.
fn comment() -> String {
    text()
        .lines()
        .filter_map(|line| line.trim_start().strip_prefix("--"))
        .flat_map(str::split_whitespace)
        .collect::<Vec<_>>()
        .join(" ")
}

// What must work.

#[test]
fn version_15_makes_the_pending_tenant_table_once() {
    assert_eq!(
        text().matches("CREATE TABLE vcon.pending_tenant (").count(),
        1,
        "the fifteenth makes pending_tenant once"
    );
}

#[test]
fn the_binary_s_version_is_at_least_15() {
    assert!(
        usize::try_from(SCHEMA_VERSION).expect("positive") > THIS,
        "this binary's version: {SCHEMA_VERSION}"
    );
}

#[test]
fn a_pending_tenant_row_is_an_id_and_the_time_its_create_began() {
    assert!(
        one_line().contains(
            "CREATE TABLE vcon.pending_tenant ( id bytea PRIMARY KEY, started_at bigint NOT NULL );"
        ),
        "the columns and the key: {}",
        one_line()
    );
}

#[test]
fn the_pending_tenant_table_has_the_policy_of_the_registry_s_rows() {
    let line = one_line();
    for statement in [
        "ALTER TABLE vcon.pending_tenant ENABLE ROW LEVEL SECURITY;",
        "ALTER TABLE vcon.pending_tenant FORCE ROW LEVEL SECURITY;",
        "CREATE POLICY registry_rows ON vcon.pending_tenant USING (vcon.in_registry() = (id IS \
         NOT NULL)) WITH CHECK (vcon.in_registry());",
        "GRANT SELECT, INSERT, DELETE ON vcon.pending_tenant TO vcon_app;",
    ] {
        assert!(line.contains(statement), "{statement}: {line}");
    }
}

#[test]
fn the_migration_says_why_the_pending_tenant_table_starts_empty() {
    assert!(
        comment().contains(
            "The table starts empty: migrate holds the database's lock, which a serving server \
             holds too, so no create is under way while it runs."
        ),
        "the reason, in the migration's comment: {}",
        comment()
    );
}

// What must be refused.

#[test]
fn a_version_14_database_is_refused_with_the_command_that_upgrades_it() {
    let refusal = version_refusal(Some(14)).expect("refused");
    assert!(refusal.contains("vcon-server migrate"), "{refusal}");
}

#[test]
fn the_application_role_is_granted_no_update_on_pending_tenant() {
    assert!(
        !one_line().contains("UPDATE ON vcon.pending_tenant") && !one_line().contains("TRUNCATE"),
        "a create begins once: {}",
        one_line()
    );
}

// The pack files under way: a tenant's rows, as vcon.pending_write's are.

#[test]
fn version_15_makes_the_pending_file_table_once() {
    assert_eq!(
        text().matches("CREATE TABLE vcon.pending_file (").count(),
        1,
        "the fifteenth makes pending_file once"
    );
}

#[test]
fn a_pending_file_row_is_a_tenant_s_file_and_the_time_its_writing_began() {
    assert!(
        one_line().contains(
            "CREATE TABLE vcon.pending_file ( tenant bytea NOT NULL, file_id bytea NOT NULL, \
             started_at bigint NOT NULL, PRIMARY KEY (tenant, file_id) );"
        ),
        "{}",
        one_line()
    );
}

#[test]
fn the_pending_file_table_has_the_policy_of_a_tenant_s_rows() {
    for statement in [
        "ALTER TABLE vcon.pending_file ENABLE ROW LEVEL SECURITY;",
        "ALTER TABLE vcon.pending_file FORCE ROW LEVEL SECURITY;",
        "CREATE POLICY tenant_rows ON vcon.pending_file USING (tenant = vcon.tenant()) \
         WITH CHECK (tenant = vcon.tenant());",
        "GRANT SELECT, INSERT, DELETE ON vcon.pending_file TO vcon_app;",
    ] {
        assert!(one_line().contains(statement), "{statement}");
    }
}

#[test]
fn the_migration_says_why_pack_files_under_way_are_recorded() {
    let comment = comment();
    assert!(
        comment.contains("vcon.pending_file") && comment.contains("before it puts the file"),
        "the reason, in the migration's comment: {comment}"
    );
}

// The leases of the work one server does for every server (lease.rs).

#[test]
fn version_15_makes_the_lease_table_once() {
    assert_eq!(
        text().matches("CREATE TABLE vcon.lease (").count(),
        1,
        "the fifteenth makes lease once"
    );
}

#[test]
fn a_lease_row_is_a_job_its_holder_and_two_times_of_the_database() {
    assert!(
        one_line().contains(
            "CREATE TABLE vcon.lease ( name text PRIMARY KEY, holder text NOT NULL, taken_at \
             timestamptz NOT NULL, expires_at timestamptz NOT NULL );"
        ),
        "{}",
        one_line()
    );
}

#[test]
fn the_lease_table_has_the_policy_of_the_registry_s_rows() {
    for statement in [
        "ALTER TABLE vcon.lease ENABLE ROW LEVEL SECURITY;",
        "ALTER TABLE vcon.lease FORCE ROW LEVEL SECURITY;",
        "CREATE POLICY registry_rows ON vcon.lease USING (vcon.in_registry() = (name IS NOT \
         NULL)) WITH CHECK (vcon.in_registry());",
        "GRANT SELECT, INSERT, UPDATE, DELETE ON vcon.lease TO vcon_app;",
    ] {
        assert!(one_line().contains(statement), "{statement}");
    }
}

#[test]
fn the_migration_says_a_lease_s_times_are_the_database_s() {
    let comment = comment();
    assert!(
        comment.contains("vcon.lease")
            && comment.contains("by the database's clock")
            && comment.contains("no server's own clock"),
        "the reason, in the migration's comment: {comment}"
    );
}

#[test]
fn the_application_role_is_granted_no_update_on_pending_file() {
    assert!(
        !one_line().contains("UPDATE ON vcon.pending_file"),
        "a file's writing begins once: {}",
        one_line()
    );
}

/// Live, against the servers of scripts/pg-test-server.sh.
#[cfg(feature = "backend-tests")]
mod on_a_server {
    use super::super::super::super::schema::{MIGRATIONS, Migrated};
    use super::super::live::{Db, TENANT_A, TENANT_B, in_scope, no_scope};
    use super::super::v8::on_a_server::{one, owner, refused};
    use super::THIS;

    /// The creating rows the registry reads: each id and its time.
    const ROWS: &str = "SELECT coalesce(string_agg(encode(id, 'hex') || ':' || started_at, ',' \
                        ORDER BY id), '') FROM vcon.pending_tenant";

    fn pending(id: &str, at: i64) -> String {
        format!("INSERT INTO vcon.pending_tenant (id, started_at) VALUES ('\\x{id}', {at})")
    }

    async fn run(client: &tokio_postgres::Client, scope: &str, sql: &str) {
        in_scope(client, scope, sql)
            .await
            .unwrap_or_else(|e| panic!("{sql}: {e}"));
    }

    #[tokio::test]
    async fn a_version_14_database_is_brought_to_version_15() {
        let db = Db::fresh().await;
        db.migrate_with(&MIGRATIONS[..THIS])
            .await
            .expect("version 14");
        assert_eq!(
            db.migrate_with(&MIGRATIONS[..=THIS])
                .await
                .expect("version 15"),
            Migrated { from: 14, to: 15 },
            "the fifteenth migration alone"
        );
        assert_eq!(one(&db.app().await, "registry", ROWS).await, "", "empty");
    }

    #[test]
    fn a_server_of_this_binary_refuses_a_database_at_version_14() {
        let db = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime")
            .block_on(async {
                let db = Db::fresh().await;
                db.migrate_with(&MIGRATIONS[..THIS])
                    .await
                    .expect("version 14");
                db
            });
        let (_dir, settings) = db.settings("vcon_app");
        let crate::config::StorageError(why) =
            super::super::super::super::catalog::Database::connect(&settings).expect_err("refused");
        assert!(
            why.contains(&format!(
                "version 14, older than this binary's {}",
                super::super::super::super::schema::SCHEMA_VERSION
            )) && why.contains("vcon-server migrate"),
            "the versions and the command: {why}"
        );
    }

    #[tokio::test]
    async fn the_application_role_adds_reads_and_deletes_creating_rows() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &pending("01", 7)).await;
        run(&app, "registry", &pending("02", -7)).await;
        assert_eq!(one(&app, "registry", ROWS).await, "01:7,02:-7", "both rows");
        run(
            &app,
            "registry",
            "DELETE FROM vcon.pending_tenant WHERE id = '\\x01'",
        )
        .await;
        assert_eq!(one(&app, "registry", ROWS).await, "02:-7", "one is left");
    }

    #[tokio::test]
    async fn the_application_role_cannot_change_a_creating_row() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &pending("01", 7)).await;
        for sql in [
            "UPDATE vcon.pending_tenant SET started_at = 8",
            "TRUNCATE vcon.pending_tenant",
        ] {
            assert_eq!(
                refused(&app, "registry", sql).await,
                "permission denied for table pending_tenant",
                "{sql}"
            );
        }
    }

    #[tokio::test]
    async fn a_delete_with_no_scope_is_refused_and_keeps_the_rows() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &pending("01", 7)).await;
        assert_eq!(
            no_scope(&app, "DELETE FROM vcon.pending_tenant").await,
            Err("no tenant set for this transaction".to_owned()),
            "a statement outside the registry's transactions"
        );
        assert_eq!(one(&app, "registry", ROWS).await, "01:7", "the row is kept");
    }

    #[tokio::test]
    async fn a_tenant_s_transaction_reads_and_adds_no_creating_row() {
        let db = Db::migrated().await;
        run(&owner(&db).await, "registry", &pending("01", 7)).await;
        let app = db.app().await;
        for sql in [
            "SELECT count(*) FROM vcon.pending_tenant".to_owned(),
            pending("02", 1),
            "DELETE FROM vcon.pending_tenant".to_owned(),
        ] {
            assert_eq!(
                refused(&app, TENANT_A, &sql).await,
                "this transaction is a tenant's, not the registry's",
                "{sql}"
            );
        }
        assert_eq!(
            one(&app, "registry", ROWS).await,
            "01:7",
            "the registry's row is kept"
        );
    }

    /// The pending file rows a tenant reads: each file and its time.
    const FILES: &str = "SELECT coalesce(string_agg(encode(file_id, 'hex') || ':' || started_at, \
                         ',' ORDER BY file_id), '') FROM vcon.pending_file";

    fn pending_file(tenant: &str, file: &str, at: i64) -> String {
        format!(
            "INSERT INTO vcon.pending_file (tenant, file_id, started_at) \
             VALUES ('\\x{tenant}', '\\x{file}', {at})"
        )
    }

    #[tokio::test]
    async fn the_application_role_adds_reads_and_deletes_pending_file_rows() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, TENANT_A, &pending_file(TENANT_A, "01", 7)).await;
        run(&app, TENANT_A, &pending_file(TENANT_A, "02", -7)).await;
        assert_eq!(one(&app, TENANT_A, FILES).await, "01:7,02:-7", "both rows");
        run(
            &app,
            TENANT_A,
            "DELETE FROM vcon.pending_file WHERE file_id = '\\x01'",
        )
        .await;
        assert_eq!(one(&app, TENANT_A, FILES).await, "02:-7", "one is left");
    }

    #[tokio::test]
    async fn the_application_role_cannot_change_a_pending_file_row() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, TENANT_A, &pending_file(TENANT_A, "01", 7)).await;
        for sql in [
            "UPDATE vcon.pending_file SET started_at = 8",
            "TRUNCATE vcon.pending_file",
        ] {
            assert_eq!(
                refused(&app, TENANT_A, sql).await,
                "permission denied for table pending_file",
                "{sql}"
            );
        }
    }

    #[tokio::test]
    async fn a_tenant_neither_reads_nor_deletes_another_tenant_s_pending_files() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, TENANT_A, &pending_file(TENANT_A, "01", 7)).await;
        assert_eq!(one(&app, TENANT_B, FILES).await, "", "B reads none of A's");
        run(&app, TENANT_B, "DELETE FROM vcon.pending_file").await;
        assert_eq!(one(&app, TENANT_A, FILES).await, "01:7", "A's row is kept");
        let why = refused(&app, TENANT_B, &pending_file(TENANT_A, "02", 7)).await;
        assert!(
            why.contains("row-level security"),
            "B cannot add a row of A's: {why}"
        );
    }

    #[tokio::test]
    async fn a_pending_file_statement_with_no_tenant_is_refused() {
        let db = Db::migrated().await;
        let app = db.app().await;
        for sql in [
            "SELECT * FROM vcon.pending_file".to_owned(),
            "DELETE FROM vcon.pending_file".to_owned(),
            pending_file(TENANT_A, "01", 7),
        ] {
            let why = no_scope(&app, &sql).await.expect_err("refused");
            assert!(
                why.contains("no tenant set for this transaction"),
                "{sql}: {why}"
            );
        }
    }

    /// The lease rows the registry reads: each job and its holder.
    const LEASES: &str = "SELECT coalesce(string_agg(name || ':' || holder, ',' ORDER BY name), \
                          '') FROM vcon.lease";

    fn lease(name: &str, holder: &str) -> String {
        format!(
            "INSERT INTO vcon.lease (name, holder, taken_at, expires_at) \
             VALUES ('{name}', '{holder}', now(), now() + interval '1 minute')"
        )
    }

    #[tokio::test]
    async fn the_application_role_takes_renews_and_gives_up_lease_rows() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &lease("sweep", "a")).await;
        run(&app, "registry", &lease("pack", "b")).await;
        assert_eq!(
            one(&app, "registry", LEASES).await,
            "pack:b,sweep:a",
            "both"
        );
        run(
            &app,
            "registry",
            "UPDATE vcon.lease SET holder = 'c' WHERE name = 'sweep'",
        )
        .await;
        run(
            &app,
            "registry",
            "DELETE FROM vcon.lease WHERE name = 'pack'",
        )
        .await;
        assert_eq!(
            one(&app, "registry", LEASES).await,
            "sweep:c",
            "one, renamed"
        );
    }

    #[tokio::test]
    async fn the_application_role_cannot_empty_the_lease_table_at_once() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &lease("sweep", "a")).await;
        assert_eq!(
            refused(&app, "registry", "TRUNCATE vcon.lease").await,
            "permission denied for table lease",
            "no TRUNCATE"
        );
        assert_eq!(one(&app, "registry", LEASES).await, "sweep:a", "kept");
    }

    #[tokio::test]
    async fn a_tenant_s_transaction_reads_and_writes_no_lease_row() {
        let db = Db::migrated().await;
        run(&owner(&db).await, "registry", &lease("sweep", "a")).await;
        let app = db.app().await;
        for sql in [
            LEASES.to_owned(),
            lease("pack", "b"),
            "UPDATE vcon.lease SET holder = 'c'".to_owned(),
            "DELETE FROM vcon.lease".to_owned(),
        ] {
            assert_eq!(
                refused(&app, TENANT_A, &sql).await,
                "this transaction is a tenant's, not the registry's",
                "{sql}"
            );
        }
        assert_eq!(one(&app, "registry", LEASES).await, "sweep:a", "kept");
    }

    #[tokio::test]
    async fn a_lease_statement_with_no_scope_is_refused() {
        let db = Db::migrated().await;
        let app = db.app().await;
        run(&app, "registry", &lease("sweep", "a")).await;
        for sql in [
            "UPDATE vcon.lease SET holder = 'c'".to_owned(),
            "DELETE FROM vcon.lease".to_owned(),
            lease("pack", "b"),
        ] {
            let why = no_scope(&app, &sql).await.expect_err("refused");
            assert!(
                why.contains("no tenant set for this transaction"),
                "{sql}: {why}"
            );
        }
        assert_eq!(one(&app, "registry", LEASES).await, "sweep:a", "kept");
    }

    #[tokio::test]
    async fn the_registry_s_transaction_reads_and_adds_no_pending_file_row() {
        let db = Db::migrated().await;
        run(
            &owner(&db).await,
            TENANT_A,
            &pending_file(TENANT_A, "01", 7),
        )
        .await;
        let app = db.app().await;
        for sql in [
            FILES.to_owned(),
            pending_file(TENANT_A, "02", 1),
            "DELETE FROM vcon.pending_file".to_owned(),
        ] {
            assert_eq!(
                refused(&app, "registry", &sql).await,
                "this transaction is the registry's, not a tenant's",
                "{sql}"
            );
        }
        assert_eq!(
            one(&app, TENANT_A, FILES).await,
            "01:7",
            "the tenant's row is kept"
        );
    }
}