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
//! A destination written as one text.
//!
//! A profile is the durable way to name a server; this is the throw-away one.
//! The text is parsed into the same [`Profile`] shape, so everything past this
//! point treats a text destination and a stored one identically.
//!
//! # Why redaction lives here
//!
//! A destination text carries the secret inline, and a destination text is
//! exactly what a diagnostic message wants to quote. A secret written to a log
//! is permanent and escapes credential rotation, so [`redact`] exists and every
//! message about a destination goes through it.

use super::profile::Profile;
use crate::error::{Failure, Result};
use secrecy::SecretString;
use std::path::PathBuf;

/// The schemes a destination text may carry.
const ACCEPTED_SCHEMES: [&str; 2] = ["mariadb", "mysql"];

/// What a redacted secret is replaced by.
const REDACTED: &str = "***";

/// A destination parsed out of one text.
///
/// The secret is held apart from the profile, because the profile is written,
/// shown and logged while the secret is none of those things.
#[derive(Debug)]
pub struct Dsn {
    /// The destination, without any secret in it.
    pub profile: Profile,
    /// The secret the text carried, if it carried one.
    pub secret: Option<SecretString>,
}

impl Dsn {
    /// Parses a destination text into a throw-away profile.
    ///
    /// The accepted form is `scheme://user:secret@host:port/database?key=value`,
    /// where every part after the scheme is optional.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the scheme is missing or unknown,
    /// when the port is not a number, or when a parameter is not one this
    /// product understands. An unknown parameter is refused rather than ignored,
    /// because ignoring it would silently drop a setting the caller asked for.
    pub fn parse(text: &str) -> Result<Self> {
        let rest = split_scheme(text)?;
        let (authority, path_and_query) = split_once_or_all(rest, '/');
        let (credential, endpoint) = split_credential(authority);
        let (user, secret) = split_user_and_secret(credential);
        let (host, port) = split_host_and_port(endpoint, text)?;
        let (database, query) = split_once_or_all(path_and_query, '?');

        let mut profile = Profile {
            host,
            port,
            user: user.map(decode),
            database: (!database.is_empty()).then(|| decode(database)),
            ..Profile::named("dsn")
        };
        apply_parameters(&mut profile, query, text)?;
        profile.ensure_reachable()?;

        Ok(Self {
            profile,
            secret: secret.map(|value| SecretString::from(decode(value))),
        })
    }
}

/// Removes the scheme and refuses a text that carries none this product knows.
fn split_scheme(text: &str) -> Result<&str> {
    let Some((scheme, rest)) = text.split_once("://") else {
        return Err(malformed(text, "the text carries no scheme"));
    };
    if !ACCEPTED_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) {
        return Err(malformed(
            text,
            format!("`{scheme}` is not a scheme this product speaks"),
        ));
    }
    Ok(rest)
}

/// Splits the credential from the endpoint, on the last separator.
///
/// The last one is used, because a secret may itself contain the separator
/// while a host never does.
fn split_credential(authority: &str) -> (&str, &str) {
    authority
        .rsplit_once('@')
        .map_or(("", authority), |(credential, endpoint)| {
            (credential, endpoint)
        })
}

/// Splits the user from the secret it carries.
fn split_user_and_secret(credential: &str) -> (Option<&str>, Option<&str>) {
    if credential.is_empty() {
        return (None, None);
    }
    credential.split_once(':').map_or_else(
        || (Some(credential), None),
        |(user, secret)| (Some(user), Some(secret)),
    )
}

/// Splits the endpoint into a host and a port.
///
/// The port stays absent when the text omits it, so the configured default
/// applies rather than a number written into this file.
fn split_host_and_port(endpoint: &str, text: &str) -> Result<(Option<String>, Option<u16>)> {
    if endpoint.is_empty() {
        return Ok((None, None));
    }
    let Some((host, port)) = endpoint.rsplit_once(':') else {
        return Ok((Some(decode(endpoint)), None));
    };
    let parsed = port
        .parse::<u16>()
        .map_err(|_| malformed(text, format!("`{port}` is not a port number")))?;
    Ok((Some(decode(host)), Some(parsed)))
}

/// Applies the parameters the text carries, refusing any this product does not
/// understand.
fn apply_parameters(profile: &mut Profile, query: &str, text: &str) -> Result<()> {
    for pair in query.split('&').filter(|pair| !pair.is_empty()) {
        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
        let value = decode(value);
        match key.to_ascii_lowercase().as_str() {
            "socket" => profile.socket = Some(PathBuf::from(value)),
            "database" | "db" => profile.database = Some(value),
            "ca" => profile.ca = Some(PathBuf::from(value)),
            "client_cert" => profile.client_cert = Some(PathBuf::from(value)),
            "client_key" => profile.client_key = Some(PathBuf::from(value)),
            "require_tls" => profile.require_tls = Some(is_affirmative(&value)),
            "read_only" => profile.read_only = is_affirmative(&value),
            "auth" => profile.auth_method = Some(value),
            unknown => {
                return Err(malformed(
                    text,
                    format!("`{unknown}` is not a parameter this product understands"),
                ))
            }
        }
    }
    Ok(())
}

/// Whether a parameter value means yes.
fn is_affirmative(value: &str) -> bool {
    matches!(
        value.to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on" | ""
    )
}

/// Splits on the first occurrence, or returns everything on the left.
fn split_once_or_all(text: &str, separator: char) -> (&str, &str) {
    text.split_once(separator)
        .map_or((text, ""), |(left, right)| (left, right))
}

/// Decodes the percent escapes a destination text may carry.
///
/// A secret routinely contains characters that would otherwise end the
/// credential or start the path, so refusing to decode would make many real
/// secrets unusable.
fn decode(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut bytes = text.bytes().collect::<Vec<_>>().into_iter().peekable();
    let mut raw: Vec<u8> = Vec::with_capacity(text.len());
    while let Some(byte) = bytes.next() {
        if byte == b'%' {
            let high = bytes.peek().copied().and_then(hex_value);
            if let Some(high) = high {
                bytes.next();
                let low = bytes.peek().copied().and_then(hex_value);
                if let Some(low) = low {
                    bytes.next();
                    raw.push(high * 16 + low);
                    continue;
                }
                raw.push(b'%');
                raw.push(b'0' + high);
                continue;
            }
        }
        raw.push(byte);
    }
    out.push_str(&String::from_utf8_lossy(&raw));
    out
}

/// The numeric value of one hexadecimal digit.
const fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// The failure a text this product cannot read produces.
///
/// The text is redacted before it enters the message, because the message ends
/// up on the auxiliary channel and, from there, in somebody's log file.
fn malformed(text: &str, detail: impl Into<String>) -> Failure {
    let shown = redact(text);
    Failure::config(
        "dsn.malformed",
        format!("the destination `{shown}` cannot be read"),
    )
    .with_detail("detail", shown)
    .with_hint("write it as scheme://user:secret@host:port/database")
    .with_cause(detail.into())
}

/// Replaces the secret inside a destination text with a fixed mark.
///
/// Used everywhere a destination appears in a message. A secret written to a
/// durable log outlives the process, survives credential rotation in the sense
/// that it keeps working until somebody notices, and cannot be recalled.
/// # Why the credential is found before the path is
///
/// The obvious reading cuts the authority at the first `/` and then looks for
/// the `@` inside it. That is right until a secret carries a `/` of its own,
/// and then the cut lands in the middle of the secret: what is left holds no
/// `@`, the parse gives up, and giving up here returned the text unchanged —
/// the whole destination, secret and all, into a durable log. A reader with a
/// slash in the password was the one case the mark existed for and the one case
/// it did not cover.
///
/// So the `@` is found first, on the whole remainder, and the path is cut out
/// of what follows it. A secret may hold slashes; the endpoint that follows the
/// `@` may not, because a host with a slash is not a host.
///
/// # Why an unreadable text is hidden rather than returned
///
/// Every early exit below hides instead of passing the text through. A text
/// with no `://` or no `@` carries no secret in the form this function knows,
/// but the cost of the two mistakes is not the same: showing a marked text that
/// held nothing is noise, and showing a secret is a secret out. When the shape
/// is not the one this function reads, it says so and shows nothing.
#[must_use]
pub fn redact(dsn: &str) -> String {
    let Some((scheme, rest)) = dsn.split_once("://") else {
        return dsn.to_owned();
    };

    // The last `@` of the remainder opens the endpoint, so anything before it
    // is credential however many separators it happens to contain.
    let Some((credential, after_credential)) = rest.rsplit_once('@') else {
        return dsn.to_owned();
    };

    let (endpoint, tail) = split_once_or_all(after_credential, '/');
    let separator = if after_credential.len() > endpoint.len() {
        "/"
    } else {
        ""
    };

    let user = credential
        .split_once(':')
        .map_or(credential, |(user, _)| user);
    let masked = if credential.contains(':') {
        format!("{user}:{REDACTED}")
    } else {
        user.to_owned()
    };

    format!("{scheme}://{masked}@{endpoint}{separator}{tail}")
}

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

    /// The whole accepted form parses into the parts it names.
    #[test]
    fn a_full_destination_parses_into_its_parts() {
        let dsn = Dsn::parse("mariadb://reader:hunter2@db.example:3307/sales").expect("parses");
        assert_eq!(dsn.profile.host.as_deref(), Some("db.example"));
        assert_eq!(dsn.profile.port, Some(3307));
        assert_eq!(dsn.profile.user.as_deref(), Some("reader"));
        assert_eq!(dsn.profile.database.as_deref(), Some("sales"));
        assert_eq!(
            dsn.secret.as_ref().map(ExposeSecret::expose_secret),
            Some("hunter2")
        );
    }

    /// An omitted port stays absent, so the configured default applies rather
    /// than a number written into this file.
    #[test]
    fn an_omitted_port_stays_absent() {
        let dsn = Dsn::parse("mysql://reader@db.example/sales").expect("parses");
        assert_eq!(dsn.profile.port, None);
        assert!(dsn.secret.is_none());
    }

    /// Percent escapes are decoded, so a secret containing a separator works.
    #[test]
    fn escaped_characters_survive_the_parse() {
        let dsn = Dsn::parse("mariadb://reader:a%40b%3Ac@db.example/sales").expect("parses");
        assert_eq!(
            dsn.secret.as_ref().map(ExposeSecret::expose_secret),
            Some("a@b:c")
        );
    }

    /// Parameters this product understands are applied.
    #[test]
    fn known_parameters_are_applied() {
        let dsn = Dsn::parse("mariadb://reader@db.example/sales?require_tls=true&read_only=1")
            .expect("parses");
        assert_eq!(dsn.profile.require_tls, Some(true));
        assert!(dsn.profile.read_only);
    }

    /// An unknown parameter is refused, because ignoring it would silently drop
    /// a setting the caller asked for.
    #[test]
    fn an_unknown_parameter_is_refused() {
        let failure =
            Dsn::parse("mariadb://reader@db.example/sales?charset=utf8").expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Config);
        assert_eq!(failure.code(), "dsn.malformed");
    }

    /// A text with no scheme, an unknown scheme or a bad port is refused.
    #[test]
    fn a_text_this_product_cannot_read_is_refused() {
        for text in [
            "db.example/sales",
            "postgres://reader@db.example/sales",
            "mariadb://reader@db.example:notaport/sales",
        ] {
            let failure = Dsn::parse(text).expect_err("must refuse");
            assert_eq!(failure.code(), "dsn.malformed", "accepted `{text}`");
        }
    }

    /// A destination naming no server at all is refused before any connection.
    #[test]
    fn a_destination_naming_no_server_is_refused() {
        let failure = Dsn::parse("mariadb://reader@/sales").expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_destination");
    }

    /// The secret never survives into the message of a failure about the text.
    #[test]
    fn a_failure_message_never_carries_the_secret() {
        let failure =
            Dsn::parse("mariadb://reader:hunter2@db.example:x/sales").expect_err("must refuse");
        assert!(
            !failure.message().contains("hunter2"),
            "the secret leaked: {}",
            failure.message()
        );
        assert!(failure.message().contains(REDACTED));
    }

    /// Redaction hides the secret and keeps everything a reader needs.
    #[test]
    fn redaction_hides_the_secret_and_keeps_the_rest() {
        let redacted = redact("mariadb://reader:hunter2@db.example:3307/sales");
        assert_eq!(redacted, "mariadb://reader:***@db.example:3307/sales");
    }

    /// A separator inside the secret does not hand the secret to the reader.
    ///
    /// This is the case the mark was for and the case it used to miss. Cutting
    /// the authority at the first `/` landed inside the secret, the piece left
    /// over held no `@`, and the give-up path returned the destination
    /// unchanged — the secret written out whole, into a log that outlives the
    /// process. The secret is asserted absent rather than the output asserted
    /// equal, because absent is the property that matters.
    #[test]
    fn a_secret_carrying_a_separator_is_still_hidden() {
        let redacted = redact("mariadb://reader:pa/ss@db.example:3307/sales");
        assert!(
            !redacted.contains("pa/ss"),
            "the secret reached the reader: {redacted}"
        );
        assert!(
            redacted.contains(REDACTED),
            "nothing was marked: {redacted}"
        );
        assert!(
            redacted.contains("db.example:3307") && redacted.contains("sales"),
            "the parts a reader needs were lost: {redacted}"
        );
    }

    /// Several separators, and one in the endpoint's own path, still hide it.
    #[test]
    fn many_separators_do_not_uncover_the_secret() {
        let redacted = redact("mariadb://reader:a/b/c@db.example/sales/main");
        assert!(
            !redacted.contains("a/b/c"),
            "the secret reached the reader: {redacted}"
        );
        assert_eq!(redacted, "mariadb://reader:***@db.example/sales/main");
    }

    /// A text with no secret is left as it is, rather than gaining a mark that
    /// would suggest a secret exists.
    #[test]
    fn a_text_without_a_secret_is_left_alone() {
        let text = "mariadb://reader@db.example/sales";
        assert_eq!(redact(text), text);
        assert_eq!(redact("not a destination"), "not a destination");
    }

    /// Redaction never lets the secret through, whatever the text around it.
    #[test]
    fn redaction_holds_for_every_shape_of_text() {
        for text in [
            "mariadb://u:s3cr3t@h",
            "mariadb://u:s3cr3t@h/db",
            "mariadb://u:s3cr3t@h:3306/db?require_tls=1",
            "mysql://u:s3cr3t@h:3306/",
        ] {
            let redacted = redact(text);
            assert!(
                !redacted.contains("s3cr3t"),
                "the secret leaked from `{text}`"
            );
            assert!(redacted.contains(REDACTED), "no mark left in `{redacted}`");
        }
    }
}