vcon-server 0.4.0

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
//! 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};
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),
    /// 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,
    },
    /// 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),
}

#[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,
    },
    /// 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 or audit.
        /// 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,
    },
    /// 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 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 {
    // 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::Mcp { config } => return mcp(&config),
        Command::Tenant(c) => tenant(c),
        Command::Key(c) => key(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::Remove {
            config,
            id,
            force,
            override_holds,
        } => (
            config,
            commands::Command::TenantRemove {
                id,
                force,
                override_holds,
            },
        ),
    }
}

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

fn fail(message: impl std::fmt::Display) -> ExitCode {
    eprintln!("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> {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .init();
    let config = config::load(config).map_err(|e| fail(format!("configuration: {e}")))?;
    runtime()?
        .block_on(serve::run(&config, stop_signal()))
        .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)
}

/// Completes on SIGINT or SIGTERM.
async fn stop_signal() {
    use tokio::signal::unix::{SignalKind, signal};
    let (Ok(mut interrupt), Ok(mut terminate)) = (
        signal(SignalKind::interrupt()),
        signal(SignalKind::terminate()),
    ) else {
        return;
    };
    tokio::select! {
        _ = interrupt.recv() => {}
        _ = terminate.recv() => {}
    }
}