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
//! The encrypted channel, and the refusal when this build carries none.
//!
//! Every mature crypto provider for the encryption stack needs a C toolchain,
//! which would stop the product installing on a host without one. Encryption is
//! therefore an opt-in build, and this module has two halves: the one that
//! builds the encrypted channel, compiled only when the build carries it, and
//! the one that refuses clearly, compiled always.
//!
//! The refusal half is compiled unconditionally on purpose. A build without
//! encryption must still be able to *say* that it has none; a module that
//! vanished with the feature would leave the caller with a missing-symbol
//! failure instead of a configuration failure carrying a hint.

use super::profile::Profile;
use crate::error::{Failure, Result};

/// The two certificate checks, kept apart.
///
/// Trusting an unknown authority and accepting a certificate issued for another
/// address are different risks with different reasons to take them, so they are
/// two settings and never one.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Verification {
    /// Accept a certificate no trusted authority signed.
    pub accept_unknown_authority: bool,
    /// Accept a certificate issued for an address other than the one dialled.
    pub accept_address_mismatch: bool,
}

impl Verification {
    /// Whether both checks are in force.
    #[must_use]
    pub const fn is_strict(self) -> bool {
        !self.accept_unknown_authority && !self.accept_address_mismatch
    }

    /// Reads the one word a caller chooses a level by.
    ///
    /// A caller picking a level wants one word for it, so the two checks behind
    /// it move together and predictably. Relaxing the address check alone is
    /// what `ca` means: the authority is still trusted, the name on the
    /// certificate is not the one dialled.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is not one this build
    /// knows, which can only happen if the registry and this list drift apart.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "full" => Ok(Self {
                accept_unknown_authority: false,
                accept_address_mismatch: false,
            }),
            "ca" => Ok(Self {
                accept_unknown_authority: false,
                accept_address_mismatch: true,
            }),
            "none" => Ok(Self {
                accept_unknown_authority: true,
                accept_address_mismatch: true,
            }),
            other => Err(Failure::config(
                "config.unknown_tls_verify",
                format!("`{other}` is not a level this build checks a certificate at"),
            )
            .with_detail("detail", other)
            .with_hint("set tls.verify to full, to ca or to none")),
        }
    }
}

/// Where the authorities trusted for this channel come from.
///
/// The encryption stack this build carries reads no store the host owns: the
/// authorities it knows without being told are the ones compiled into the
/// binary. So the three sources differ by what is added to that set and by
/// whether that set is used at all, rather than by which of two stores is read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RootStore {
    /// The authorities this build knows, plus any the destination names.
    #[default]
    System,
    /// Only the authorities this build knows; a destination's own is ignored.
    Bundled,
    /// Only the authority the destination names; nothing else is trusted.
    File,
}

impl RootStore {
    /// Reads the one word a caller names a trust source by.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the word is not one this build
    /// knows.
    pub fn parse(word: &str) -> Result<Self> {
        match word {
            "system" => Ok(Self::System),
            "bundled" => Ok(Self::Bundled),
            "file" => Ok(Self::File),
            other => Err(Failure::config(
                "config.unknown_root_store",
                format!("`{other}` is not a source of trusted authorities"),
            )
            .with_detail("detail", other)
            .with_hint("set tls.root_store to system, to bundled or to file")),
        }
    }

    /// Whether the authorities compiled into this build are trusted.
    #[must_use]
    pub const fn trusts_the_built_in_authorities(self) -> bool {
        matches!(self, Self::System | Self::Bundled)
    }

    /// Whether the authority the destination names is added to the trusted set.
    #[must_use]
    pub const fn trusts_the_named_authority(self) -> bool {
        matches!(self, Self::System | Self::File)
    }
}

/// Everything the settings layer decides about the encrypted channel.
///
/// Grouped rather than passed one by one, because these four are always read
/// together and a new one must not silently change every call site's shape.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Encryption {
    /// Whether an encrypted channel is demanded even where the profile is silent.
    pub demanded: bool,
    /// How thoroughly the server's certificate is checked.
    pub verification: Verification,
    /// Where the trusted authorities come from.
    pub root_store: RootStore,
}

/// Whether this profile asks for an encrypted channel at all.
///
/// This is the one place the precedence lives, and it has two steps.
///
/// Naming an authority, a client certificate or a client key asks for
/// encryption whatever else was said. A caller who supplied a certificate did
/// not mean clear text, so that wins even over a destination that states it
/// needs no encryption.
///
/// Otherwise the destination has the last word when it states one, and the
/// stored key is only the default for a destination that says nothing. Reading
/// the two as `stored || destination`, as this once did, made the stored demand
/// unbeatable: with the published default of `true`, a caller writing
/// `require_tls=false` was ignored in silence, which inverts the precedence the
/// product publishes.
#[must_use]
pub fn wants_encryption(profile: &Profile, encryption: &Encryption) -> bool {
    if profile.ca.is_some() || profile.client_cert.is_some() || profile.client_key.is_some() {
        return true;
    }
    profile.require_tls.unwrap_or(encryption.demanded)
}

/// The failure a build without encryption answers with.
///
/// This is the whole reason the module is compiled unconditionally: the caller
/// gets a configuration failure with a concrete next step, not a build error.
#[must_use]
pub fn unavailable() -> Failure {
    Failure::config(
        "tls.not_available",
        "this build carries no network encryption",
    )
    .with_hint(
        "install a build with the encryption feature enabled, or drop the encryption request",
    )
}

/// Refuses a certificate half-pair before any connection is attempted.
///
/// A certificate without its key, or a key without its certificate, can never
/// authenticate this client, and failing here says so plainly.
fn ensure_identity_is_complete(profile: &Profile) -> Result<()> {
    match (&profile.client_cert, &profile.client_key) {
        (Some(_), None) => Err(Failure::config(
            "tls.key_missing",
            "a client certificate was named without its key",
        )
        .with_hint("name the matching key with --client-key")),
        (None, Some(_)) => Err(Failure::config(
            "tls.certificate_missing",
            "a client key was named without its certificate",
        )
        .with_hint("name the matching certificate with --client-cert")),
        _ => Ok(()),
    }
}

/// Builds the encrypted channel this profile asks for.
///
/// Answers `None` when nothing asks for encryption, so a destination that never
/// mentions it and a build whose stored demand is off are opened in the plain
/// way without further ceremony.
///
/// # The protocol floor is not here
///
/// The driver's option set carries no field for a protocol version, so the
/// floor cannot be handed over at this point. It is imposed instead by which
/// cipher suites the crypto provider offers, which is decided before any
/// channel is built. See [`crate::conn::provider::ProtocolFloor`]. Carrying a
/// second copy of it here would be one setting with two readers, which is the
/// duplication this layer exists to avoid.
///
/// # Errors
///
/// Returns a configuration failure when a certificate is named without its key,
/// when the trust source is `file` and the destination names no authority, and,
/// on a build without encryption, whenever any encryption is asked for.
#[cfg(feature = "tls")]
pub fn channel(profile: &Profile, encryption: &Encryption) -> Result<Option<mysql_async::SslOpts>> {
    use mysql_async::{ClientIdentity, SslOpts};

    if !wants_encryption(profile, encryption) {
        return Ok(None);
    }
    ensure_identity_is_complete(profile)?;
    ensure_the_named_authority_exists(profile, encryption.root_store)?;

    let mut options = SslOpts::default()
        .with_danger_accept_invalid_certs(encryption.verification.accept_unknown_authority)
        .with_danger_skip_domain_validation(encryption.verification.accept_address_mismatch)
        // Turning the built-in set off is what makes `file` mean "this authority
        // and no other". Leaving it on is what the other two sources mean.
        .with_disable_built_in_roots(!encryption.root_store.trusts_the_built_in_authorities());

    if let Some(authority) = &profile.ca {
        if encryption.root_store.trusts_the_named_authority() {
            options = options.with_root_certs(vec![authority.clone().into()]);
        }
    }

    if let (Some(certificate), Some(key)) = (&profile.client_cert, &profile.client_key) {
        options = options.with_client_identity(Some(ClientIdentity::new(
            certificate.clone().into(),
            key.clone().into(),
        )));
    }

    Ok(Some(options))
}

/// Refuses a trust source that would leave nothing trusted at all.
///
/// Asking for `file` while naming no authority disables the built-in set and
/// puts nothing in its place, so every certificate would be rejected. Saying so
/// here is better than a handshake failure that names no cause.
///
/// Compiled only where a channel can be built at all: a build without
/// encryption refuses on the capability long before a trust source matters.
#[cfg(feature = "tls")]
fn ensure_the_named_authority_exists(profile: &Profile, root_store: RootStore) -> Result<()> {
    if root_store == RootStore::File && profile.ca.is_none() {
        return Err(Failure::config(
            "tls.no_authority_named",
            "the trust source is the named authority and this destination names none",
        )
        .with_hint("name an authority with --ca, or set tls.root_store to system"));
    }
    Ok(())
}

/// Refuses every encryption request, because this build carries none.
///
/// The signature matches the encrypted build exactly, so the caller has one
/// code path and the difference between builds shows up as a failure rather
/// than as a shape change.
///
/// # Errors
///
/// Returns a configuration failure whenever the profile asks for encryption.
#[cfg(not(feature = "tls"))]
pub fn channel(profile: &Profile, encryption: &Encryption) -> Result<Option<mysql_async::SslOpts>> {
    if wants_encryption(profile, encryption) {
        return Err(unavailable());
    }
    ensure_identity_is_complete(profile)?;
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn encrypted() -> Profile {
        Profile {
            host: Some("db.example".to_owned()),
            require_tls: Some(true),
            ..Profile::named("secure")
        }
    }

    /// A destination that never mentions encryption asks for none, on either
    /// build, and is opened without ceremony.
    #[test]
    fn a_plain_destination_asks_for_no_encryption() {
        let profile = Profile {
            host: Some("db.example".to_owned()),
            ..Profile::named("plain")
        };
        assert!(!wants_encryption(&profile, &Encryption::default()));
        assert!(channel(&profile, &Encryption::default())
            .expect("no encryption asked for")
            .is_none());
    }

    /// Naming an authority asks for encryption just as plainly as demanding it,
    /// so a caller who set a path is never quietly connected in clear text.
    #[test]
    fn naming_a_certificate_asks_for_encryption() {
        let by_authority = Profile {
            ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
            ..Profile::named("implicit")
        };
        assert!(wants_encryption(&by_authority, &Encryption::default()));
    }

    /// The stored demand is what a profile stating nothing falls back to, which
    /// is what makes `conn.require_tls` a default rather than a recorded value.
    #[test]
    fn a_silent_destination_takes_the_stored_demand() {
        let profile = Profile {
            host: Some("db.example".to_owned()),
            ..Profile::named("silent")
        };
        let demanded = Encryption {
            demanded: true,
            ..Encryption::default()
        };
        assert!(!wants_encryption(&profile, &Encryption::default()));
        assert!(wants_encryption(&profile, &demanded));
    }

    /// A destination that states it needs no encryption must beat the stored
    /// demand, or the published precedence is inverted and the caller is
    /// ignored in silence.
    #[test]
    fn a_destination_that_states_no_encryption_beats_the_stored_demand() {
        let demanded = Encryption {
            demanded: true,
            ..Encryption::default()
        };
        let refuses = Profile {
            require_tls: Some(false),
            ..Profile::named("plain")
        };
        assert!(
            !wants_encryption(&refuses, &demanded),
            "the destination has the last word over the stored default"
        );

        // And the three states really are three: saying nothing is not the same
        // answer as saying no.
        let silent = Profile {
            require_tls: None,
            ..Profile::named("silent")
        };
        assert!(wants_encryption(&silent, &demanded));
    }

    /// Supplying a certificate wins over everything, including a destination
    /// that states it needs no encryption: nobody hands over a key meaning
    /// clear text.
    #[test]
    fn naming_a_certificate_wins_even_over_a_stated_refusal() {
        let contradictory = Profile {
            require_tls: Some(false),
            ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
            ..Profile::named("contradictory")
        };
        assert!(wants_encryption(&contradictory, &Encryption::default()));
    }

    /// The three levels are one word each and move both checks together, so a
    /// caller never has to know which of the two a word relaxes.
    #[test]
    fn each_level_names_exactly_which_checks_it_relaxes() {
        assert!(Verification::parse("full").expect("known").is_strict());

        let authority_kept = Verification::parse("ca").expect("known");
        assert!(!authority_kept.accept_unknown_authority);
        assert!(authority_kept.accept_address_mismatch);

        let nothing = Verification::parse("none").expect("known");
        assert!(nothing.accept_unknown_authority);
        assert!(nothing.accept_address_mismatch);

        assert_eq!(
            Verification::parse("sometimes")
                .expect_err("must refuse")
                .code(),
            "config.unknown_tls_verify"
        );
    }

    /// The three trust sources differ in what they add and in whether the set
    /// this build carries is used at all.
    #[test]
    fn each_trust_source_names_a_different_set_of_authorities() {
        let system = RootStore::parse("system").expect("known");
        assert!(system.trusts_the_built_in_authorities());
        assert!(system.trusts_the_named_authority());

        let bundled = RootStore::parse("bundled").expect("known");
        assert!(bundled.trusts_the_built_in_authorities());
        assert!(!bundled.trusts_the_named_authority());

        let file = RootStore::parse("file").expect("known");
        assert!(!file.trusts_the_built_in_authorities());
        assert!(file.trusts_the_named_authority());

        assert_eq!(
            RootStore::parse("elsewhere")
                .expect_err("must refuse")
                .code(),
            "config.unknown_root_store"
        );
    }

    /// Trusting only a named authority while naming none would trust nothing at
    /// all, so it is refused here rather than at the handshake.
    #[test]
    fn trusting_only_a_named_authority_needs_one_to_be_named() {
        let encryption = Encryption {
            demanded: true,
            root_store: RootStore::File,
            ..Encryption::default()
        };
        let failure = channel(&encrypted(), &encryption).expect_err("must refuse");
        // Without encryption the build refuses earlier, on the capability.
        assert!(matches!(
            failure.code(),
            "tls.no_authority_named" | "tls.not_available"
        ));
    }

    /// The two checks are separate settings, because they are separate risks.
    #[test]
    fn the_two_checks_are_independent() {
        let authority_only = Verification {
            accept_unknown_authority: true,
            accept_address_mismatch: false,
        };
        assert!(!authority_only.is_strict());
        assert!(Verification::default().is_strict());
    }

    /// A certificate without its key is refused on either build, before any
    /// connection is attempted.
    #[test]
    fn a_half_pair_is_refused() {
        let profile = Profile {
            host: Some("db.example".to_owned()),
            client_cert: Some(PathBuf::from("/etc/ssl/client.pem")),
            ..Profile::named("halfpair")
        };
        let failure = channel(&profile, &Encryption::default()).expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Config);
        // Without encryption the build refuses earlier, on the capability; with
        // it, on the missing key. Either way the caller is told what to fix.
        assert!(matches!(
            failure.code(),
            "tls.key_missing" | "tls.not_available"
        ));
    }

    /// A build without encryption refuses the request with a hint, rather than
    /// connecting in clear text or failing to build at all.
    #[cfg(not(feature = "tls"))]
    #[test]
    fn a_build_without_encryption_refuses_and_says_why() {
        let failure = channel(&encrypted(), &Encryption::default()).expect_err("must refuse");
        assert_eq!(failure.code(), "tls.not_available");
        assert!(failure.hint().is_some());
        assert!(!failure.is_retryable());
    }

    /// A build with encryption honours the request and both checks.
    #[cfg(feature = "tls")]
    #[test]
    fn a_build_with_encryption_honours_the_request() {
        let options = channel(&encrypted(), &Encryption::default())
            .expect("encryption available")
            .expect("channel built");
        assert!(options.root_certs().is_empty());
        assert!(!options.skip_domain_validation());
        assert!(!options.accept_invalid_certs());
        assert!(
            !options.disable_built_in_roots(),
            "the ordinary source keeps the authorities this build carries"
        );
    }

    /// Each trust source has to reach the driver differently, or the setting is
    /// a word the product records and never acts on.
    #[cfg(feature = "tls")]
    #[test]
    fn each_trust_source_reaches_the_driver_differently() {
        let with_authority = Profile {
            ca: Some(PathBuf::from("/etc/ssl/ca.pem")),
            ..encrypted()
        };

        let built = |store| {
            channel(
                &with_authority,
                &Encryption {
                    demanded: true,
                    root_store: store,
                    ..Encryption::default()
                },
            )
            .expect("encryption available")
            .expect("channel built")
        };

        let system = built(RootStore::System);
        assert!(!system.disable_built_in_roots());
        assert_eq!(system.root_certs().len(), 1);

        let bundled = built(RootStore::Bundled);
        assert!(!bundled.disable_built_in_roots());
        assert!(
            bundled.root_certs().is_empty(),
            "only what this build carries is trusted"
        );

        let file = built(RootStore::File);
        assert!(file.disable_built_in_roots());
        assert_eq!(file.root_certs().len(), 1);
    }

    /// Each level has to reach the driver's two checks, or the word is one the
    /// product records and never acts on.
    #[cfg(feature = "tls")]
    #[test]
    fn each_level_reaches_the_drivers_two_checks() {
        let built = |word| {
            channel(
                &encrypted(),
                &Encryption {
                    demanded: true,
                    verification: Verification::parse(word).expect("known"),
                    ..Encryption::default()
                },
            )
            .expect("encryption available")
            .expect("channel built")
        };

        let full = built("full");
        assert!(!full.accept_invalid_certs());
        assert!(!full.skip_domain_validation());

        let authority_only = built("ca");
        assert!(!authority_only.accept_invalid_certs());
        assert!(authority_only.skip_domain_validation());

        let nothing = built("none");
        assert!(nothing.accept_invalid_certs());
        assert!(nothing.skip_domain_validation());
    }
}