vcon-server 0.4.12

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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! The vcon-server command: parses the command line and runs the
//! subcommand from the vcon_server library.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};
use vcon_server::commands::{self, Log, Owner, Place};
use vcon_server::tenants::KeyLife;
use vcon_server::{config, envelope, serve};

/// A vCon server: stores IETF vCons, encrypted at rest.
#[derive(Parser)]
#[command(name = "vcon-server", version)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Starts the server.
    Serve {
        /// The configuration file.
        #[arg(long)]
        config: PathBuf,
    },
    /// Makes, lists, changes and removes tenants.
    #[command(subcommand)]
    Tenant(TenantCommand),
    /// Makes, lists and revokes keys.
    #[command(subcommand)]
    Key(KeyCommand),
    /// Makes, lists and deactivates users. Runs on the host only.
    #[command(subcommand)]
    User(UserCommand),
    /// Grants and revokes a user's roles in a tenant or as an operator. Runs on
    /// the host only.
    #[command(subcommand)]
    Membership(MembershipCommand),
    /// Reads the audit logs.
    #[command(subcommand)]
    Audit(AuditCommand),
    /// Rotates keys. Runs only while no server does.
    #[command(subcommand)]
    Rekey(RekeyCommand),
    /// Speaks MCP on stdin and stdout for an AI agent, forwarding each
    /// request to a running server with the one key its client file names.
    Mcp {
        /// The client file: the server's URL, the key file and the CA.
        #[arg(long)]
        config: PathBuf,
    },
    /// Shows a running server's vCons in the terminal, read over its HTTP
    /// API with the one key its client file names. In every build but one
    /// made without the default features.
    Tui {
        /// The client file: the server's URL, the key file and the CA.
        #[arg(long)]
        config: PathBuf,
    },
    /// Opens every stored version and reports damage, leftover files,
    /// versions past due and work waiting for key rotation; exits 1 when
    /// anything needs attention. Runs only while no server does.
    Check {
        #[command(flatten)]
        config: ConfigArg,
    },
    /// Writes a consistent copy of the data directory to a new directory
    /// while the server runs: each catalog with SQLite's online backup, and
    /// every object file a copied catalog names. Restore it as a data
    /// directory, under the same master key.
    Backup {
        #[command(flatten)]
        config: ConfigArg,
        /// The directory to write; it must not exist.
        dir: PathBuf,
    },
    /// Writes a copy of a tenant's data in another format, beside a running
    /// server.
    #[command(subcommand)]
    Export(ExportCommand),
    /// Moves the data to the storage the configuration names.
    #[command(subcommand)]
    Storage(StorageCommand),
    /// Makes or brings up to date the schema of the PostgreSQL catalog the
    /// configuration names, as a role that may act as vcon_owner. Runs only
    /// while no server does; a server never migrates at start.
    Migrate {
        #[command(flatten)]
        config: ConfigArg,
    },
}

#[derive(Subcommand)]
enum StorageCommand {
    /// Moves every tenant's sealed objects from the data directory to the
    /// bucket the configuration's [storage] table names: each is written,
    /// read back and compared before its file is removed. Runs only while
    /// no server does; run it again to finish a run that stopped.
    MoveObjects {
        #[command(flatten)]
        config: ConfigArg,
    },
}

#[derive(Subcommand)]
enum ExportCommand {
    /// Writes a tenant's kept versions as Parquet files, one directory per
    /// store date, and a manifest naming them: each version's sealed body
    /// byte for byte, and the clear columns of the tenant's metadata level.
    Parquet {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        #[arg(long)]
        tenant: String,
        /// A directory, or s3://bucket/prefix.
        #[arg(long)]
        to: String,
        /// Only versions stored at or after this RFC 3339 time.
        #[arg(long)]
        since: Option<String>,
        /// Only versions stored before this RFC 3339 time.
        #[arg(long)]
        until: Option<String>,
    },
}

#[derive(Subcommand)]
enum RekeyCommand {
    /// Rotates a tenant's key: every data key is rewrapped and the tenant's
    /// catalog re-encrypted under a new tenant key. A run that stops is
    /// finished by running it again.
    Tenant {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
    },
    /// Rotates the master key: every tenant key is rewrapped under the new
    /// one, in a copy of server.sqlite that replaces it only once complete.
    Master {
        #[command(flatten)]
        config: ConfigArg,
        /// The file holding the new 32-byte master key.
        #[arg(long)]
        new_master: PathBuf,
    },
}

/// The configuration file every command reads.
#[derive(Args)]
struct ConfigArg {
    /// The configuration file.
    #[arg(long)]
    config: PathBuf,
}

#[derive(Subcommand)]
enum TenantCommand {
    /// Makes a tenant and prints its id. Runs only while no server does.
    Create {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's name: 1 to 128 characters.
        name: String,
        /// Its retention period, such as 7y, 18m or 90d; the server
        /// default if left out.
        #[arg(long)]
        retention: Option<String>,
    },
    /// Lists the tenants.
    List {
        #[command(flatten)]
        config: ConfigArg,
    },
    /// Sets a tenant's retention period.
    SetRetention {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
        /// A period such as 7y, 18m or 90d, or `default` for the server's.
        retention: String,
    },
    /// Sets which clear columns a tenant's Parquet files carry.
    SetMetadata {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
        /// none (the default), counts, or full, which holds personal data.
        metadata: String,
    },
    /// Sets the roles a membership in a tenant may be given: its role cap.
    SetRoleCap {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
        /// A role the cap allows: reader, producer, records, legal, auditor
        /// or tenant-admin. Repeat it for each role.
        #[arg(long = "role", required_unless_present = "all", conflicts_with = "all")]
        roles: Vec<String>,
        /// Removes the cap, so every tenant role is allowed.
        #[arg(long)]
        all: bool,
    },
    /// Prints a tenant's role cap.
    RoleCap {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
    },
    /// Removes a tenant. Runs only while no server does.
    Remove {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant's id.
        id: String,
        /// Remove its vCons too.
        #[arg(long)]
        force: bool,
        /// Remove its vCons even under a legal hold.
        #[arg(long, requires = "force")]
        override_holds: bool,
    },
}

#[derive(Subcommand)]
enum KeyCommand {
    /// Makes a key and prints its id and token, shown this once.
    Create {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant the key belongs to.
        #[arg(
            long,
            required_unless_present = "operator",
            conflicts_with = "operator"
        )]
        tenant: Option<String>,
        /// A scope the tenant key holds: write, read, delete, legal, audit or
        /// tenant_admin. Repeat it for each scope.
        #[arg(long = "scope", requires = "tenant", conflicts_with = "operator")]
        scopes: Vec<String>,
        /// Makes an operator key, holding the admin scope.
        #[arg(long)]
        operator: bool,
        /// Who holds the key.
        #[arg(long)]
        label: String,
        /// The days until the key expires, from 1 to 365. Without this and
        /// without --no-expiry the key expires in 90 days.
        #[arg(long, value_name = "DAYS", conflicts_with = "no_expiry")]
        expires_days: Option<u32>,
        /// Makes a key that never expires. Refused when the configuration
        /// sets keys.no_expiry to false.
        #[arg(long)]
        no_expiry: bool,
    },
    /// Lists keys, never their tokens.
    List {
        #[command(flatten)]
        config: ConfigArg,
        /// Only this tenant's keys.
        #[arg(long)]
        tenant: Option<String>,
    },
    /// Revokes a key from its next request on.
    Revoke {
        #[command(flatten)]
        config: ConfigArg,
        /// The key's id.
        id: String,
    },
}

#[derive(Subcommand)]
enum UserCommand {
    /// Makes a user, a person who signs in, and prints its id.
    Add {
        #[command(flatten)]
        config: ConfigArg,
        /// What the user is shown as.
        label: String,
        /// The issuer of the identity provider that knows the user. With
        /// neither this nor --subject, the user is a local account.
        #[arg(long, requires = "subject")]
        issuer: Option<String>,
        /// The subject the identity provider gives the user.
        #[arg(long, requires = "issuer")]
        subject: Option<String>,
    },
    /// Lists users, each with its memberships.
    List {
        #[command(flatten)]
        config: ConfigArg,
    },
    /// Deactivates a user and removes its memberships.
    Deactivate {
        #[command(flatten)]
        config: ConfigArg,
        /// The user's id.
        id: String,
    },
}

#[derive(Args)]
struct PlaceArgs {
    /// The tenant the membership is in.
    #[arg(
        long,
        required_unless_present = "operator",
        conflicts_with = "operator"
    )]
    tenant: Option<String>,
    /// The operator membership, which holds the operator role.
    #[arg(long)]
    operator: bool,
}

#[derive(Subcommand)]
enum MembershipCommand {
    /// Gives a user roles in a tenant, or the operator role, and prints
    /// the roles the membership then holds.
    Grant {
        #[command(flatten)]
        config: ConfigArg,
        /// The user's id.
        user: String,
        #[command(flatten)]
        place: PlaceArgs,
        /// A role in the tenant: reader, producer, records, legal, auditor
        /// or tenant-admin. Repeat it for each role.
        #[arg(
            long = "role",
            required_unless_present = "operator",
            conflicts_with = "operator"
        )]
        roles: Vec<String>,
    },
    /// Takes roles from a user's membership and prints the roles it still
    /// holds. With no --role, the membership is removed.
    Revoke {
        #[command(flatten)]
        config: ConfigArg,
        /// The user's id.
        user: String,
        #[command(flatten)]
        place: PlaceArgs,
        /// A role to take. Repeat it for each role.
        #[arg(long = "role", conflicts_with = "operator")]
        roles: Vec<String>,
    },
}

impl PlaceArgs {
    fn place(self, roles: Vec<String>) -> Place {
        match self.tenant {
            Some(id) => Place::Tenant { id, roles },
            None => Place::Operator,
        }
    }
}

fn user(command: UserCommand) -> (ConfigArg, commands::Command) {
    match command {
        UserCommand::Add {
            config,
            label,
            issuer,
            subject,
        } => (
            config,
            commands::Command::UserAdd {
                label,
                identity: issuer.zip(subject),
            },
        ),
        UserCommand::List { config } => (config, commands::Command::UserList),
        UserCommand::Deactivate { config, id } => {
            (config, commands::Command::UserDeactivate { id })
        }
    }
}

fn membership(command: MembershipCommand) -> (ConfigArg, commands::Command) {
    match command {
        MembershipCommand::Grant {
            config,
            user,
            place,
            roles,
        } => (
            config,
            commands::Command::MembershipGrant {
                user,
                place: place.place(roles),
            },
        ),
        MembershipCommand::Revoke {
            config,
            user,
            place,
            roles,
        } => (
            config,
            commands::Command::MembershipRevoke {
                user,
                place: place.place(roles),
            },
        ),
    }
}

#[derive(Subcommand)]
enum AuditCommand {
    /// Writes an audit log as JSON lines, oldest first.
    Export {
        #[command(flatten)]
        config: ConfigArg,
        /// The tenant whose log to write.
        #[arg(long, required_unless_present = "admin", conflicts_with = "admin")]
        tenant: Option<String>,
        /// Write the admin log.
        #[arg(long)]
        admin: bool,
        /// Only the records after this sequence number.
        #[arg(long)]
        since: Option<i64>,
    },
}

fn main() -> ExitCode {
    let code = run();
    vcon_server::stderr::drain(vcon_server::stderr::EXIT_DRAIN);
    code
}

fn run() -> ExitCode {
    // Parsing touches no secret, and `--help` must work anywhere.
    let cli = Cli::parse();
    // Then, before any key, token or body is read: no core dumps, and all
    // memory locked, so none can reach a dump or swap.
    if let Err(e) = envelope::disable_core_dumps() {
        return fail(format!("core dumps cannot be turned off: {e}"));
    }
    if let Err(e) = envelope::lock_all_memory() {
        return fail(format!(
            "memory cannot be locked: {e}; allow it, for example LimitMEMLOCK=infinity"
        ));
    }
    let (config, command) = match cli.command {
        Command::Serve { config } => return serve(&config),
        Command::Migrate { config } => return migrate(&config.config),
        Command::Mcp { config } => return mcp(&config),
        Command::Tui { config } => return tui(&config),
        Command::Tenant(c) => tenant(c),
        Command::Key(c) => key(c),
        Command::User(c) => user(c),
        Command::Membership(c) => membership(c),
        Command::Rekey(RekeyCommand::Tenant { config, id }) => {
            (config, commands::Command::RekeyTenant { id })
        }
        Command::Rekey(RekeyCommand::Master { config, new_master }) => {
            (config, commands::Command::RekeyMaster { new_master })
        }
        Command::Check { config } => (config, commands::Command::Check),
        Command::Storage(StorageCommand::MoveObjects { config }) => {
            (config, commands::Command::StorageMoveObjects)
        }
        Command::Backup { config, dir } => (config, commands::Command::Backup { to: dir }),
        Command::Export(ExportCommand::Parquet {
            config,
            tenant,
            to,
            since,
            until,
        }) => (
            config,
            commands::Command::ExportParquet {
                tenant,
                to,
                since,
                until,
            },
        ),
        Command::Audit(AuditCommand::Export {
            config,
            tenant,
            admin: _,
            since,
        }) => (
            config,
            commands::Command::AuditExport {
                log: tenant.map_or(Log::Admin, Log::Tenant),
                since,
            },
        ),
    };
    let config = match config::load(&config.config) {
        Ok(config) => config,
        Err(e) => return fail(format!("configuration: {e}")),
    };
    match commands::run(&config, &command, &mut std::io::stdout().lock()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => fail(e),
    }
}

fn tenant(command: TenantCommand) -> (ConfigArg, commands::Command) {
    match command {
        TenantCommand::Create {
            config,
            name,
            retention,
        } => (config, commands::Command::TenantCreate { name, retention }),
        TenantCommand::List { config } => (config, commands::Command::TenantList),
        TenantCommand::SetRetention {
            config,
            id,
            retention,
        } => (
            config,
            commands::Command::TenantSetRetention { id, retention },
        ),
        TenantCommand::SetMetadata {
            config,
            id,
            metadata,
        } => (
            config,
            commands::Command::TenantSetMetadata { id, metadata },
        ),
        TenantCommand::SetRoleCap {
            config,
            id,
            roles,
            all,
        } => (
            config,
            commands::Command::TenantSetRoleCap {
                id,
                roles: (!all).then_some(roles),
            },
        ),
        TenantCommand::RoleCap { config, id } => (config, commands::Command::TenantRoleCap { id }),
        TenantCommand::Remove {
            config,
            id,
            force,
            override_holds,
        } => (
            config,
            commands::Command::TenantRemove {
                id,
                force,
                override_holds,
            },
        ),
    }
}

/// The life `key create` asks for: `--no-expiry`, else `--expires-days`,
/// else the default. The days are checked where the key is made.
fn key_life(expires_days: Option<u32>, no_expiry: bool) -> KeyLife {
    match (no_expiry, expires_days) {
        (true, _) => KeyLife::Never,
        (false, Some(days)) => KeyLife::Days(days),
        (false, None) => KeyLife::Default,
    }
}

fn key(command: KeyCommand) -> (ConfigArg, commands::Command) {
    match command {
        KeyCommand::Create {
            config,
            tenant,
            scopes,
            operator: _,
            label,
            expires_days,
            no_expiry,
        } => {
            let owner = match tenant {
                Some(id) => Owner::Tenant { id, scopes },
                None => Owner::Operator,
            };
            let life = key_life(expires_days, no_expiry);
            (config, commands::Command::KeyCreate { owner, label, life })
        }
        KeyCommand::List { config, tenant } => (config, commands::Command::KeyList { tenant }),
        KeyCommand::Revoke { config, id } => (config, commands::Command::KeyRevoke { id }),
    }
}

/// `vcon-server migrate`: reads the configuration and applies the
/// migrations, needing no data directory or master key.
fn migrate(config: &Path) -> ExitCode {
    let config = match config::load(config) {
        Ok(config) => config,
        Err(e) => return fail(format!("configuration: {e}")),
    };
    match commands::migrate(&config, &mut std::io::stdout().lock()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => fail(e),
    }
}

fn fail(message: impl std::fmt::Display) -> ExitCode {
    vcon_server::stderr::line(&format!("vcon-server: {message}"));
    ExitCode::FAILURE
}

fn serve(config: &Path) -> ExitCode {
    match run_serve(config) {
        Ok(()) => ExitCode::SUCCESS,
        Err(failed) => failed,
    }
}

/// `vcon-server serve` until it stops, or the exit for why it stopped.
fn run_serve(config: &Path) -> Result<(), ExitCode> {
    // A log line goes on stderr's queue and is never written by the
    // request that logged it; a line that cannot be written is dropped
    // (crate::stderr says why). The builder's fallback for a failed write,
    // `eprintln!`, would panic in the request that logged it.
    tracing_subscriber::fmt()
        .with_writer(vcon_server::stderr::stderr)
        .log_internal_errors(false)
        .init();
    let config = config::load(config).map_err(|e| fail(format!("configuration: {e}")))?;
    runtime()?.block_on(async {
        // Taken before the server starts, so a signal that arrives at any
        // moment from here on is an orderly stop.
        let stop =
            stop_signal().map_err(|e| fail(format!("the stop signals cannot be taken: {e}")))?;
        serve::run(&config, stop).await.map_err(fail)
    })
}

/// The async runtime `serve` and `mcp` run on, or the exit for a runtime
/// that cannot start.
fn runtime() -> Result<tokio::runtime::Runtime, ExitCode> {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|e| fail(format!("the runtime cannot start: {e}")))
}

fn mcp(config: &Path) -> ExitCode {
    match run_mcp(config) {
        Ok(()) => ExitCode::SUCCESS,
        Err(failed) => failed,
    }
}

/// `vcon-server mcp` until stdin ends, or the exit for why it stopped.
fn run_mcp(config: &Path) -> Result<(), ExitCode> {
    let config = vcon_server::mcp::stdio::client_config(config)
        .map_err(|e| fail(format!("client file: {e}")))?;
    runtime()?
        .block_on(vcon_server::mcp::stdio::stdio(&config))
        .map_err(fail)
}

/// `vcon-server tui` until the user quits.
#[cfg(feature = "tui")]
fn tui(config: &Path) -> ExitCode {
    let config = match vcon_server::mcp::stdio::client_config(config) {
        Ok(config) => config,
        Err(e) => return fail(format!("client file: {e}")),
    };
    match vcon_server::tui::run(&config) {
        Ok(()) => ExitCode::SUCCESS,
        Err(why) => fail(why),
    }
}

/// `vcon-server tui` in a build without the terminal UI: says how to get
/// one, and fails.
#[cfg(not(feature = "tui"))]
fn tui(_config: &Path) -> ExitCode {
    fail("this build has no terminal UI: build vcon-server with the cargo feature tui")
}

/// Takes SIGINT and SIGTERM from this call on, and gives a future that
/// completes when either has arrived, including one that arrived before
/// the future was first polled. Called inside the runtime.
///
/// # Errors
///
/// The system's error when a signal cannot be taken. No test reaches it:
/// the system refuses only a signal that may not be caught, and these two
/// may.
fn stop_signal() -> std::io::Result<impl Future<Output = ()>> {
    use tokio::signal::unix::{SignalKind, signal};
    let mut interrupt = signal(SignalKind::interrupt())?;
    let mut terminate = signal(SignalKind::terminate())?;
    Ok(async move {
        tokio::select! {
            _ = interrupt.recv() => {}
            _ = terminate.recv() => {}
        }
    })
}