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
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
//! Where diagnostics go, how loud they are and how long they are kept.
//!
//! Diagnostics never touch the primary channel. The writer is fixed to the
//! auxiliary channel here, once, so no call site can choose otherwise and no
//! amount of extra detail can put a single byte in front of a caller parsing
//! the result.
//!
//! The level is decided by the marks on the command line and the stored
//! setting, and by nothing else. Reading it from the process environment would
//! put a setting of this product outside the configuration surface, where
//! `config list` cannot show it and `config doctor` cannot check it.

use crate::error::{Failure, Result};
use std::path::{Path, PathBuf};
use tracing::Level;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::rolling::{self, RollingFileAppender};
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;

/// The levels the product publishes, quietest first.
///
/// The order is the one the settings registry declares, and raising the detail
/// walks it one step at a time.
const LEVELS: [(&str, Level); 5] = [
    ("error", Level::ERROR),
    ("warn", Level::WARN),
    ("info", Level::INFO),
    ("debug", Level::DEBUG),
    ("trace", Level::TRACE),
];

/// How the diagnostic file turns over.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rotation {
    /// A new file each day.
    Daily,
    /// A new file each hour.
    Hourly,
    /// One file that never turns over.
    Never,
}

impl Rotation {
    /// Reads the stored word as a rotation.
    ///
    /// An unknown word yields nothing, so the caller decides whether that is a
    /// broken setting or simply nothing stored.
    #[must_use]
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "daily" => Some(Self::Daily),
            "hourly" => Some(Self::Hourly),
            "never" => Some(Self::Never),
            _ => None,
        }
    }

    /// The same choice, as the file writer expresses it.
    fn as_appender(self) -> rolling::Rotation {
        match self {
            Self::Daily => rolling::Rotation::DAILY,
            Self::Hourly => rolling::Rotation::HOURLY,
            Self::Never => rolling::Rotation::NEVER,
        }
    }
}

/// Everything that decides what the auxiliary channel does.
#[derive(Debug, Clone)]
pub struct Diagnostics {
    /// The loudest level that is reported; absent means the channel is silent.
    pub level: Option<Level>,
    /// Whether a copy is written to a file as well.
    pub to_file: bool,
    /// Where those files live.
    pub directory: PathBuf,
    /// How the file turns over.
    pub rotation: Rotation,
    /// How many turned-over files are kept.
    pub retention: usize,
    /// Whether the auxiliary channel carries decoration.
    pub colour: bool,
}

impl Diagnostics {
    /// The quietest sensible arrangement: the auxiliary channel and nothing else.
    #[must_use]
    pub fn to_channel_only(level: Option<Level>, colour: bool) -> Self {
        Self {
            level,
            to_file: false,
            directory: PathBuf::new(),
            rotation: Rotation::Daily,
            retention: 1,
            colour,
        }
    }
}

/// The level in force, from the marks and the stored setting.
///
/// Silencing wins outright, because a caller who asked for silence asked for
/// it whatever else is stored. Otherwise each repetition of the detail mark
/// walks one step up the published list, stopping at the loudest level rather
/// than wrapping around.
#[must_use]
pub fn level_for(quiet: bool, verbose: u8, stored: &str) -> Option<Level> {
    if quiet {
        return None;
    }
    let floor = LEVELS
        .iter()
        .position(|(name, _)| *name == stored.trim().to_ascii_lowercase())
        .unwrap_or(0);
    let index = floor.saturating_add(verbose as usize).min(LEVELS.len() - 1);
    LEVELS.get(index).map(|(_, level)| *level)
}

/// The published name of one level, for a diagnostic about diagnostics.
#[must_use]
pub fn name_of(level: Level) -> &'static str {
    LEVELS
        .iter()
        .find(|(_, candidate)| *candidate == level)
        .map_or("error", |(name, _)| *name)
}

/// Builds the file writer, creating the directory when it does not exist.
///
/// # Errors
///
/// Returns a configuration failure when the directory cannot be created or
/// written to, naming the path, so the caller can fix the destination rather
/// than guess at it.
pub fn build_appender(
    directory: &Path,
    rotation: Rotation,
    retention: usize,
) -> Result<RollingFileAppender> {
    std::fs::create_dir_all(directory).map_err(|error| unwritable(directory, &error))?;

    let mut builder = rolling::Builder::new()
        .rotation(rotation.as_appender())
        .filename_prefix(env!("CARGO_PKG_NAME"))
        .filename_suffix("log");
    // A retention of nothing would delete the file being written, so the
    // smallest meaningful policy is to keep the current one.
    builder = builder.max_log_files(retention.max(1));

    builder
        .build(directory)
        .map_err(|error| unwritable(directory, &error))
}

/// The failure a diagnostic destination that cannot be written produces.
fn unwritable(directory: &Path, cause: &impl std::fmt::Display) -> Failure {
    Failure::config(
        "log.destination_unwritable",
        format!(
            "the diagnostic directory `{}` cannot be written to",
            directory.display()
        ),
    )
    .with_detail("detail", directory.display().to_string())
    .with_hint("point `log.to_file` at a writable directory, or set it to false")
    .with_cause(cause.to_string())
}

/// What the auxiliary channel carries at one level.
///
/// Below the levels a caller asks for while diagnosing, the channel carries
/// this product's own events and nothing else. A level alone let every library
/// underneath write there too, and since the product itself publishes almost
/// nothing at the quiet levels, the whole content of the channel became raw
/// lines from the driver: a second, unshaped copy of the failure already
/// published, carrying the server's own phrasing that the published answer
/// deliberately does not repeat.
///
/// Asking for detail is asking for exactly that, so from the debugging levels
/// upwards everything underneath is admitted again.
///
/// The name matched is the compilation identity of this crate, which cargo
/// fixes when the product is built. It is not a setting: no caller can change
/// it and nothing reads it from the environment at run time.
fn scope_of(level: Level) -> tracing_subscriber::filter::Targets {
    let own =
        tracing_subscriber::filter::Targets::new().with_target(env!("CARGO_CRATE_NAME"), level);
    if level >= Level::DEBUG {
        own.with_default(level)
    } else {
        own
    }
}

/// A destination that has every secret removed from a line before it lands.
///
/// # Why the removal lives here and not at each call site
///
/// This product publishes almost nothing at the quiet levels, so asking for
/// detail is asking for the libraries underneath, and the driver writes the
/// statement it is about to send. A statement that sets a credential carries
/// one, and a destination text carries one wherever it is written. Neither line
/// belongs to this product, so no call site of this product could have removed
/// anything from them.
///
/// Wrapping the destination is the only place that sees every line whoever
/// wrote it. It was measured missing: the scrub existed, was proved, was
/// exported, and had no caller outside its own proofs, while the file it was
/// written to protect took the driver's lines exactly as they came.
#[derive(Debug, Clone)]
struct Scrubbing<M>(M);

impl<'writer, M: tracing_subscriber::fmt::MakeWriter<'writer>>
    tracing_subscriber::fmt::MakeWriter<'writer> for Scrubbing<M>
{
    type Writer = ScrubbingWriter<M::Writer>;

    fn make_writer(&'writer self) -> Self::Writer {
        ScrubbingWriter::new(self.0.make_writer())
    }

    fn make_writer_for(&'writer self, meta: &tracing::Metadata<'_>) -> Self::Writer {
        ScrubbingWriter::new(self.0.make_writer_for(meta))
    }
}

/// One event held whole, scrubbed, and only then written on.
///
/// Held whole because the scrub reads text and a write may arrive split at any
/// byte, including the middle of a character. Examining half a line would let
/// a secret through by the accident of where the split fell.
#[derive(Debug)]
struct ScrubbingWriter<W: std::io::Write> {
    inner: W,
    held: Vec<u8>,
}

impl<W: std::io::Write> ScrubbingWriter<W> {
    const fn new(inner: W) -> Self {
        Self {
            inner,
            held: Vec::new(),
        }
    }

    /// Scrubs what is held and writes it on.
    fn release(&mut self) -> std::io::Result<()> {
        if self.held.is_empty() {
            return Ok(());
        }
        let held = std::mem::take(&mut self.held);
        // Lossy on purpose. A byte that is not text cannot be examined by a
        // text pass, and writing it on unexamined is writing on exactly what
        // was never checked. The formatter above produces text, so this arm is
        // for a line that was already damaged before it arrived.
        let text = String::from_utf8_lossy(&held);
        self.inner.write_all(super::redact::scrub(&text).as_bytes())
    }
}

impl<W: std::io::Write> std::io::Write for ScrubbingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.held.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.release()?;
        self.inner.flush()
    }
}

impl<W: std::io::Write> Drop for ScrubbingWriter<W> {
    fn drop(&mut self) {
        // The formatter drops the writer once the event is written and never
        // flushes it, so this is where a line normally leaves. The outcome is
        // unread because a destination that cannot be written is already the
        // failure `install` reports, and losing a diagnostic must not become a
        // panic inside the machinery that reports failures.
        drop(self.release());
    }
}

/// Installs the auxiliary channel for this invocation.
///
/// Both destinations are wrapped in a scrubbing writer, so no line reaches a
/// screen or a file with a secret still in it, whichever library wrote it. The
/// wrapper is not named here because it is private: what a caller can rely on
/// is the property, and the type that carries it is this module's business.
///
/// The returned guard must be held until the process ends: dropping it flushes
/// whatever the file writer still holds, and dropping it early truncates the
/// last diagnostics of the run.
///
/// # Errors
///
/// Returns a configuration failure when a diagnostic file was asked for and
/// its destination cannot be written, and when an auxiliary channel was
/// already installed for this process, which is a defect rather than input.
pub fn install(settings: &Diagnostics) -> Result<Option<WorkerGuard>> {
    let Some(level) = settings.level else {
        return Ok(None);
    };

    let (writer, guard) = if settings.to_file {
        let appender = build_appender(&settings.directory, settings.rotation, settings.retention)?;
        let (writer, guard) = tracing_appender::non_blocking(appender);
        (Some(writer), Some(guard))
    } else {
        (None, None)
    };

    // The file layer carries no decoration: escape sequences in a file are
    // noise to every reader that opens it later.
    let file_layer = writer.map(|writer| {
        tracing_subscriber::fmt::layer()
            .with_ansi(false)
            .with_writer(Scrubbing(writer))
    });

    let channel_layer = tracing_subscriber::fmt::layer()
        .with_ansi(settings.colour)
        .with_writer(Scrubbing(std::io::stderr));

    tracing_subscriber::registry()
        .with(scope_of(level))
        .with(channel_layer)
        .with(file_layer)
        .try_init()
        .map_err(|error| {
            Failure::config(
                "log.already_installed",
                "the auxiliary channel was already installed for this process",
            )
            .with_cause(error.to_string())
        })?;

    Ok(guard)
}

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

    /// A destination that collects what was written, to read it back.
    #[derive(Debug, Clone, Default)]
    struct Collected(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl Collected {
        fn text(&self) -> String {
            String::from_utf8_lossy(&self.0.lock().expect("not poisoned")).into_owned()
        }
    }

    impl std::io::Write for Collected {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.lock().expect("not poisoned").extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// Nothing reaches a destination with a secret still in it.
    ///
    /// This is the proof the removal was missing. The scrub was written,
    /// proved and exported, and had no caller outside its own proofs, so the
    /// file it exists to protect took every line exactly as it came. Wrapping
    /// the destination is what put it on the path, and this asserts the wrap
    /// rather than the function, because the function was never the part that
    /// was wrong.
    #[test]
    fn no_secret_reaches_a_destination_through_this_channel() {
        use std::io::Write as _;

        let collected = Collected::default();
        let secrets = [
            "opening mysql://app:hunter2@db.internal:3306/shop",
            "sending CREATE USER 'app'@'%' IDENTIFIED BY 'hunter2'",
            "read password=hunter2 from the file",
        ];

        for line in secrets {
            let mut writer = ScrubbingWriter::new(collected.clone());
            writer.write_all(line.as_bytes()).expect("collected");
            drop(writer);
        }

        let written = collected.text();
        assert!(!written.contains("hunter2"), "written: {written}");
        assert!(written.contains("db.internal"), "the host is not a secret");
        assert!(written.contains("CREATE USER"), "the shape still reads");
    }

    /// A line may arrive split at any byte, including inside a character, so
    /// the removal reads the whole line and never a fragment of one.
    ///
    /// Examining halves would let a secret through by the accident of where
    /// the split fell, which is the kind of defect that never reproduces.
    #[test]
    fn a_line_split_across_writes_is_examined_whole() {
        use std::io::Write as _;

        let collected = Collected::default();
        let line = "opening mysql://app:hunter2@db.internal/shop";
        let mut writer = ScrubbingWriter::new(collected.clone());
        for chunk in line.as_bytes().chunks(3) {
            writer.write_all(chunk).expect("collected");
        }
        drop(writer);

        let written = collected.text();
        assert!(!written.contains("hunter2"), "written: {written}");
        assert!(written.contains("db.internal"));
    }

    /// A line carrying nothing sensitive arrives exactly as it was written.
    #[test]
    fn an_ordinary_line_passes_through_unchanged() {
        use std::io::Write as _;

        let collected = Collected::default();
        let line = "connected to db.internal:3306 in 12ms\n";
        let mut writer = ScrubbingWriter::new(collected.clone());
        writer.write_all(line.as_bytes()).expect("collected");
        drop(writer);

        assert_eq!(collected.text(), line);
    }

    /// Every destination this channel installs is wrapped, and nothing else.
    ///
    /// The proofs above show that the wrapper removes a secret. They cannot
    /// show that the wrapper is reached, because the channel installs once per
    /// process and the test binary has already installed one. That gap is
    /// exactly the gap that existed: a scrub that worked, was proved, and was
    /// never on the path.
    ///
    /// So this reads the source and counts. The needle is assembled from
    /// pieces rather than written whole, because this file is read by this
    /// test and a needle written whole would find itself.
    #[test]
    fn every_destination_this_channel_installs_is_wrapped() {
        let source = include_str!("tracing.rs");
        let wrapped = concat!("with_", "writer(Scrubbing(");
        let any_writer = concat!("with_", "writer(");

        let wrapped_count = source.matches(wrapped).count();
        let writer_count = source.matches(any_writer).count();

        assert_eq!(
            wrapped_count, 2,
            "the screen and the file are the two destinations, and both are wrapped"
        );
        assert_eq!(
            writer_count, wrapped_count,
            "a destination was installed without the wrapper, so lines reach it \
             with whatever they carried"
        );
    }

    #[test]
    fn silence_wins_over_everything_stored() {
        assert_eq!(level_for(true, 0, "trace"), None);
    }

    #[test]
    fn the_stored_setting_decides_when_no_mark_was_given() {
        assert_eq!(level_for(false, 0, "error"), Some(Level::ERROR));
        assert_eq!(level_for(false, 0, "info"), Some(Level::INFO));
    }

    #[test]
    fn each_repetition_of_the_mark_raises_the_detail_one_step() {
        assert_eq!(level_for(false, 1, "error"), Some(Level::WARN));
        assert_eq!(level_for(false, 2, "error"), Some(Level::INFO));
        assert_eq!(level_for(false, 3, "error"), Some(Level::DEBUG));
        assert_eq!(level_for(false, 4, "error"), Some(Level::TRACE));
    }

    #[test]
    fn raising_the_detail_stops_at_the_loudest_level() {
        assert_eq!(level_for(false, 200, "error"), Some(Level::TRACE));
    }

    #[test]
    fn an_unreadable_stored_level_falls_back_to_the_quietest() {
        assert_eq!(level_for(false, 0, "shout"), Some(Level::ERROR));
    }

    #[test]
    fn every_rotation_word_the_registry_publishes_is_read() {
        assert_eq!(Rotation::parse("daily"), Some(Rotation::Daily));
        assert_eq!(Rotation::parse("HOURLY"), Some(Rotation::Hourly));
        assert_eq!(Rotation::parse(" never "), Some(Rotation::Never));
        assert_eq!(Rotation::parse("weekly"), None);
    }

    #[test]
    fn a_diagnostic_file_is_created_where_it_was_asked_for() {
        let directory = tempfile::tempdir().expect("scratch directory");
        let target = directory.path().join("diagnostics");
        build_appender(&target, Rotation::Daily, 3).expect("writable");
        assert!(target.is_dir(), "the destination must exist afterwards");
    }

    /// FR-068. The set of diagnostic files never grows past the retention the
    /// caller configured: older turns are discarded when the writer opens.
    ///
    /// The turns are laid down by hand rather than waited for, because the
    /// only other way to produce a second daily file is to let a day pass.
    /// What is measured is the discarding, and that runs the same either way.
    #[test]
    fn the_set_of_files_never_passes_the_configured_retention() {
        /// How many turns of the diagnostic file are kept in this reading.
        const RETENTION: usize = 2;

        let directory = tempfile::tempdir().expect("scratch directory");
        let target = directory.path().join("diagnostics");
        std::fs::create_dir_all(&target).expect("creates");

        let prefix = env!("CARGO_PKG_NAME");
        for day in 1..=5 {
            std::fs::write(target.join(format!("{prefix}.2020-01-0{day}.log")), b"old")
                .expect("writes an earlier turn");
        }
        assert_eq!(
            kept(&target, prefix),
            5,
            "five turns are on disk to begin with"
        );

        let appender = build_appender(&target, Rotation::Daily, RETENTION).expect("writable");
        // The writer creates its own file only once something is written to it,
        // and that file counts against the same ceiling.
        std::io::Write::write_all(&mut { appender }, b"now\n").expect("writes");

        assert!(
            kept(&target, prefix) <= RETENTION,
            "the retention of {RETENTION} left {} files behind",
            kept(&target, prefix)
        );
    }

    /// How many diagnostic files of this product are in a directory.
    fn kept(directory: &std::path::Path, prefix: &str) -> usize {
        std::fs::read_dir(directory)
            .expect("a readable directory")
            .flatten()
            .filter(|entry| {
                entry
                    .file_name()
                    .to_str()
                    .is_some_and(|name| name.starts_with(prefix) && name.ends_with("log"))
            })
            .count()
    }

    #[test]
    fn a_destination_that_cannot_be_written_is_refused_by_configuration() {
        let directory = tempfile::tempdir().expect("scratch directory");
        let blocker = directory.path().join("not-a-directory");
        std::fs::write(&blocker, b"x").expect("writes");

        let failure = build_appender(&blocker.join("inside"), Rotation::Daily, 1)
            .expect_err("a file is not a directory");
        assert_eq!(failure.code(), "log.destination_unwritable");
        assert_eq!(failure.exit_number().code(), 4);
    }

    /// At the quiet levels the channel is the product's own, so a library
    /// underneath cannot write a second, unshaped copy of the failure the
    /// caller was already handed.
    #[test]
    fn a_library_underneath_is_kept_off_the_quiet_channel() {
        for level in [Level::ERROR, Level::WARN, Level::INFO] {
            let scope = scope_of(level);
            assert!(
                scope.would_enable(env!("CARGO_CRATE_NAME"), &level),
                "the product must still be heard at `{}`",
                name_of(level)
            );
            assert!(
                !scope.would_enable("mysql_async::conn::routines::prepare", &level),
                "the driver must not write to the channel at `{}`",
                name_of(level)
            );
        }
    }

    /// Asking for detail is asking for what is underneath as well, so the
    /// libraries come back the moment the caller is diagnosing.
    #[test]
    fn asking_for_detail_lets_the_libraries_back_in() {
        for level in [Level::DEBUG, Level::TRACE] {
            assert!(
                scope_of(level).would_enable("mysql_async::conn::routines::prepare", &Level::ERROR),
                "the driver must be heard again at `{}`",
                name_of(level)
            );
        }
    }

    #[test]
    fn a_silent_channel_installs_nothing_at_all() {
        let settings = Diagnostics::to_channel_only(None, false);
        assert!(install(&settings).expect("silence never fails").is_none());
    }

    #[test]
    fn every_level_has_a_published_name() {
        for (name, level) in LEVELS {
            assert_eq!(name_of(level), name);
        }
    }
}