mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
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
//! The seven profile commands.
//!
//! Six of them touch only the store on disk; only `conn test` reaches a server.
//! No command on this surface ever puts a secret on a channel: `list` and `show`
//! answer with the profile as it may be shown, and `add` and `edit` read the
//! secret from the standard input, never from a flag value, because a flag value
//! is visible in the process list of the whole machine.

use crate::cli::conn::{AddArgs, ConnCommand, TestArgs};
use crate::conn::options::ConnectionSettings;
use crate::conn::profile::{Profile, SecretRef, SecretVault};
use crate::conn::store::ProfileStore;
use crate::error::{Failure, Result};
use crate::output::Envelope;
use serde_json::{json, Value};

// `conn test` is the one command on this surface that opens a connection, so
// it lives apart from the six that only touch the store on disk.
mod reach;
// The three commands that alter a stored destination.
mod profiles;
// The one read of a secret this surface performs.
mod secret;

use secret::read_secret_from_standard_input;

/// Serves one profile command.
///
/// # Errors
///
/// Returns an absence failure when a named profile is unknown, a configuration
/// failure when the store cannot be written or a destination cannot be read, and
/// the mapped driver failure when `conn test` cannot reach the server.
pub async fn execute(
    command: &ConnCommand,
    config: &crate::config::Config,
    cli: &crate::cli::Cli,
    store: &mut ProfileStore,
    vault: &mut dyn SecretVault,
    settings: &ConnectionSettings,
) -> Result<Envelope> {
    // Which destination applies when none is named is the published setting
    // `conn.default`, read here and nowhere else on this surface.
    let marked = crate::dispatch::context::stored_default(config)?;
    let refuses_to_ask = crate::settings::no_input(&cli.globals);
    let settings_file =
        crate::config::paths::config_file(cli.globals.diagnostics.config_dir.as_deref())?;
    // Read here rather than reaching for it inside each of the four commands
    // that write, so the surface has one place where the question is asked and
    // a fifth writing command cannot be added without meeting it.
    let conditions = Conditions {
        refuses_to_ask,
        dry_run: cli.globals.safety.dry_run,
    };

    match command {
        ConnCommand::Add(args) => add(
            args,
            cli.globals.destination.database.as_deref(),
            store,
            vault,
            marked.as_deref(),
            &settings_file,
            conditions,
        ),
        ConnCommand::List => Ok(list(store, marked.as_deref())),
        ConnCommand::Show(args) => show(
            named(args.name.as_deref(), "conn show producao")?,
            store,
            marked.as_deref(),
        ),
        ConnCommand::Edit(args) => profiles::edit(
            named(args.name.as_deref(), "conn edit producao --host db.local")?,
            &args.fields,
            cli.globals.destination.database.as_deref(),
            store,
            vault,
            conditions,
        ),
        ConnCommand::Remove(args) => profiles::remove(
            named(args.name.as_deref(), "conn remove producao")?,
            store,
            vault,
            marked.as_deref(),
            &settings_file,
            conditions.dry_run,
        ),
        ConnCommand::Default(args) => profiles::set_default(
            named(args.name.as_deref(), "conn default producao")?,
            store,
            &settings_file,
            conditions.dry_run,
        ),
        ConnCommand::Test(args) => {
            // The connect ceiling is read here, beside every other setting this
            // surface obeys, and handed down. `test` opens by a route of its
            // own and so cannot pick it up from the shared one.
            let budget = crate::settings::connect_timeout(config, &cli.globals)?;
            reach::test(args, store, settings, marked.as_deref(), budget).await
        }
    }
}

/// What the invocation itself asked for, as opposed to what the command names.
///
/// Two questions that every writing command on this surface has to ask and that
/// belong to neither the arguments nor the store: whether a caller may be asked
/// for a secret, and whether this is a description rather than a change. They
/// travel together because they are decided together, once, where the surface is
/// entered.
#[derive(Debug, Clone, Copy)]
struct Conditions {
    /// Whether reading a secret from the input stream is refused outright.
    refuses_to_ask: bool,
    /// Whether this invocation describes what it would do and does none of it.
    dry_run: bool,
}

/// Demands the profile name the contract layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure naming what is missing and showing the form that
/// carries it.
fn named<'a>(given: Option<&'a str>, example: &str) -> Result<&'a str> {
    given.ok_or_else(|| {
        Failure::usage(
            "profile.name_missing",
            "this command needs the name of a profile to work on",
        )
        .with_hint(format!(
            "as in `{example}`; `conn list` shows the stored names"
        ))
    })
}

/// Creates a named destination.
///
/// The database arrives separately from the rest of the fields because it is
/// named by the global `--database` rather than by a flag of this command. The
/// manual publishes it that way, and giving this command a second flag of its
/// own for the same idea is what made the value vanish: the global took the
/// argument and the local field stayed empty.
fn add(
    args: &AddArgs,
    database: Option<&str>,
    store: &mut ProfileStore,
    vault: &mut dyn SecretVault,
    marked: Option<&str>,
    settings_file: &std::path::Path,
    conditions: Conditions,
) -> Result<Envelope> {
    let Conditions {
        refuses_to_ask,
        dry_run,
    } = conditions;
    let name = named(args.name.as_deref(), "conn add producao --host db.local")?;
    let reference = SecretRef::for_profile(name);
    let profile = Profile {
        host: args.host.clone(),
        port: args.port,
        socket: args.socket.clone(),
        user: args.user.clone(),
        database: database.map(str::to_owned),
        // Absent and `false` are the same on create: there is no stored value
        // to leave alone, so the third state the flag can carry has nothing to
        // mean here. It exists so the spelling matches `conn edit`.
        pin_database: args.pin_database.unwrap_or(false),
        auth_method: args.auth.clone(),
        secret: args.password_stdin.then(|| reference.clone()),
        client_cert: args.client_cert.clone(),
        client_key: args.client_key.clone(),
        ca: args.ca.clone(),
        require_tls: args.require_tls,
        session_setup: args.session_setup.clone(),
        read_only: args.read_only_profile.unwrap_or(false),
        ..Profile::named(name)
    };
    profile.ensure_reachable()?;
    profile.ensure_pin_names_a_database()?;

    // The secret is read from the input stream either way, because a caller who
    // piped one in has already spent it and a simulation that left it unread
    // would answer a question about a different invocation. It is kept only
    // when the destination is kept.
    if args.password_stdin {
        let secret = read_secret_from_standard_input(refuses_to_ask)?;
        if !dry_run {
            vault.store(&reference, &secret)?;
        }
    }

    let shown = profile.redacted();
    // Added to the store in hand whichever way this goes, so the name collision
    // is refused in a simulation exactly as it would be in the real thing. The
    // store dies with this process; `save` is what outlives it.
    store.add(profile)?;
    if !dry_run {
        store.save()?;
    }

    // The first destination on a fresh host becomes the one that applies when
    // none is named, so nothing else is needed before the first connection. It
    // is written to the registry, because that is where the default lives.
    let became_default = marked.is_none();
    if became_default && !dry_run {
        crate::config::store::store(settings_file, "conn.default", name)?;
    }

    Ok(Envelope::new(
        "conn add",
        json!({
            "created": true,
            "profile": shown,
            "is_default": became_default,
            "simulated": dry_run,
        }),
    ))
}

/// Lists every stored destination, none of them carrying a secret.
fn list(store: &ProfileStore, marked: Option<&str>) -> Envelope {
    let rows: Vec<Value> = store
        .list()
        .iter()
        .map(|profile| {
            let mut shown = profile.redacted();
            shown["is_default"] = json!(marked == Some(profile.name.as_str()));
            shown
        })
        .collect();
    Envelope::new("conn list", json!({ "rows": rows, "default": marked }))
}

/// Shows one destination with its secret redacted.
fn show(name: &str, store: &ProfileStore, marked: Option<&str>) -> Result<Envelope> {
    let profile = store.get(name)?;
    let mut shown = profile.redacted();
    shown["is_default"] = json!(marked == Some(name));
    Ok(Envelope::new("conn show", shown))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::conn::NameArgs;
    use secrecy::SecretString;
    use std::collections::HashMap;

    /// A vault that keeps secrets in memory, so the commands are provable
    /// without touching the real store.
    ///
    /// The commands that alter a destination live beside this file and are
    /// proved there, so this scratch vault is reachable from them too.
    #[derive(Default)]
    pub(super) struct MemoryVault {
        secrets: HashMap<String, String>,
    }

    impl SecretVault for MemoryVault {
        fn store(&mut self, reference: &SecretRef, secret: &SecretString) -> Result<()> {
            use secrecy::ExposeSecret;
            self.secrets.insert(
                reference.key().to_owned(),
                secret.expose_secret().to_owned(),
            );
            Ok(())
        }

        fn load(&self, reference: &SecretRef) -> Result<Option<SecretString>> {
            Ok(self
                .secrets
                .get(reference.key())
                .map(|secret| SecretString::from(secret.clone())))
        }

        fn forget(&mut self, reference: &SecretRef) -> Result<()> {
            self.secrets.remove(reference.key());
            Ok(())
        }
    }

    pub(super) fn store_in(directory: &std::path::Path) -> ProfileStore {
        ProfileStore::empty_at(directory.join("profiles.toml"))
    }

    fn add_args(name: &str) -> AddArgs {
        AddArgs {
            name: Some(name.to_owned()),
            host: Some("db.example".to_owned()),
            port: None,
            socket: None,
            user: Some("reader".to_owned()),
            password_stdin: false,
            pin_database: None,
            auth: None,
            client_cert: None,
            client_key: None,
            ca: None,
            require_tls: None,
            session_setup: Vec::new(),
            read_only_profile: None,
            check: false,
        }
    }

    /// The settings file of a scratch location, and the name it marks.
    ///
    /// The default now lives in the registry rather than in the store, so a
    /// test that wants to see it has to read it back from there.
    pub(super) fn settings_file_in(directory: &std::path::Path) -> std::path::PathBuf {
        crate::config::paths::config_file(Some(directory)).expect("a settings location")
    }

    fn marked_in(directory: &std::path::Path) -> Option<String> {
        let config = crate::config::Config::load(Some(directory)).expect("the location loads");
        crate::dispatch::context::stored_default(&config).expect("resolves")
    }

    /// A simulated create writes neither the store nor the registry.
    ///
    /// `--dry-run` is global, so the argument layer accepted it here from the
    /// first day and nothing on this surface ever read it. The destination was
    /// created, the default was marked, and the caller was told it was a
    /// simulation by nothing at all.
    #[test]
    fn a_simulated_create_leaves_the_store_and_the_registry_alone() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        let file = settings_file_in(directory.path());

        let envelope = add(
            &add_args("main"),
            Some("sales"),
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: true,
            },
        )
        .expect("the destination is admissible");

        assert_eq!(envelope.data["simulated"], true);
        assert_eq!(
            envelope.data["profile"]["host"], "db.example",
            "a simulation still describes what it would have written"
        );
        assert!(
            !directory.path().join("profiles.toml").exists(),
            "the simulation wrote the store it was only asked to describe"
        );
        assert_eq!(
            marked_in(directory.path()),
            None,
            "the simulation marked a default that was never created"
        );
    }

    /// A simulated create still refuses a destination naming no server.
    #[test]
    fn a_simulated_create_still_refuses_what_the_real_one_refuses() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        let file = settings_file_in(directory.path());

        let mut args = add_args("empty");
        args.host = None;
        add(
            &args,
            None,
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: true,
            },
        )
        .expect_err("a destination with no server is refused either way");
    }

    /// A simulated removal keeps the destination and its secret.
    #[test]
    fn a_simulated_removal_keeps_what_it_was_asked_to_describe() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        let file = settings_file_in(directory.path());
        add(
            &add_args("main"),
            None,
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: false,
            },
        )
        .expect("added");

        let envelope = profiles::remove("main", &mut store, &mut vault, Some("main"), &file, true)
            .expect("the destination exists");

        assert_eq!(envelope.data["simulated"], true);
        assert_eq!(envelope.data["name"], "main");
        // The store in hand really did lose it, and that is the point: the store
        // in hand dies with this process. What matters is the one on disk.
        let on_disk = ProfileStore::open(directory.path()).expect("the store opens");
        assert_eq!(
            on_disk.list().len(),
            1,
            "the simulation removed the destination it was only asked to describe"
        );
    }

    /// A created destination is stored, becomes the default and is answered for
    /// without a secret anywhere in the answer.
    #[test]
    fn adding_stores_the_destination_and_reveals_no_secret() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();

        let file = settings_file_in(directory.path());
        let envelope = add(
            &add_args("main"),
            Some("sales"),
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: false,
            },
        )
        .expect("added");
        assert_eq!(envelope.data["created"], true);
        assert_eq!(envelope.data["profile"]["host"], "db.example");
        assert_eq!(
            envelope.data["profile"]["database"], "sales",
            "the database named by the global reaches the stored destination"
        );
        assert!(envelope.data["profile"]["secret"].is_null());
        assert_eq!(
            marked_in(directory.path()).as_deref(),
            Some("main"),
            "the first destination is marked in the registry, not in the store"
        );
    }

    /// A destination naming no server is refused before anything is written.
    #[test]
    fn adding_a_destination_with_no_server_is_refused() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();

        let mut args = add_args("empty");
        args.host = None;
        let file = settings_file_in(directory.path());
        let failure = add(
            &args,
            None,
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: false,
            },
        )
        .expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_destination");
        assert!(store.list().is_empty(), "nothing may be stored on refusal");
    }

    /// The list answers under the published key and never carries a secret.
    #[test]
    fn the_list_uses_the_published_key_and_hides_secrets() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        vault
            .store(
                &SecretRef::for_profile("main"),
                &SecretString::from("hunter2"),
            )
            .expect("stored");
        store
            .add(Profile {
                host: Some("db.example".to_owned()),
                secret: Some(SecretRef::for_profile("main")),
                ..Profile::named("main")
            })
            .expect("added");

        let envelope = list(&store, Some("main"));
        let rows = envelope.data["rows"].as_array().expect("rows array");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["is_default"], true);
        assert_eq!(rows[0]["secret"], "***");
        let text = serde_json::to_string(&envelope).expect("serialises");
        assert!(!text.contains("hunter2"), "a secret leaked: {text}");
    }

    /// Showing an unknown destination is an absence, with a pointer to the list.
    #[test]
    fn showing_an_unknown_destination_is_an_absence() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let failure = show("ghost", &store_in(directory.path()), None).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Absence);
        assert!(failure.hint().is_some());
    }

    /// Every command in this family answers under the name the surface map
    /// publishes, so an answer is attributable to the call that made it.
    #[test]
    fn every_command_answers_under_its_published_name() {
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = store_in(directory.path());
        let mut vault = MemoryVault::default();
        let file = settings_file_in(directory.path());
        add(
            &add_args("main"),
            Some("sales"),
            &mut store,
            &mut vault,
            None,
            &file,
            Conditions {
                refuses_to_ask: false,
                dry_run: false,
            },
        )
        .expect("added");

        assert_eq!(list(&store, Some("main")).command, "conn list");
        assert_eq!(
            show("main", &store, Some("main")).expect("shown").command,
            "conn show"
        );
        assert_eq!(
            profiles::set_default("main", &store, &file, false)
                .expect("marked")
                .command,
            "conn default"
        );
        assert_eq!(
            profiles::remove("main", &mut store, &mut vault, Some("main"), &file, false)
                .expect("removed")
                .command,
            "conn remove"
        );
        // The two remaining names come from the same table the surface uses.
        assert_eq!(
            ConnCommand::Test(TestArgs { name: None }).published_name(),
            "conn test"
        );
        assert_eq!(
            ConnCommand::Show(NameArgs {
                name: Some("main".to_owned())
            })
            .published_name(),
            "conn show"
        );
    }
}