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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Turning stored settings and command line marks into what each family needs.
//!
//! This is the single place where a key name becomes a value used by the work.
//! Keeping it here means no command reads the configuration on its own, and no
//! ceiling is ever written as a bare number inside the code.

use crate::cli::globals::{Compress, GlobalFlags, RowCountMode as FlagRowCountMode};
use crate::config::keys::Value;
use crate::config::Config;
use crate::error::{Failure, Result};
use std::time::Duration;

/// The failure for a key this code demands a value from and the registry has
/// none for.
///
/// Nothing a caller typed can cause this. Either the registry carries no
/// built-in for a key the work cannot run without, or the work read the key as
/// the wrong shape. Both are defects in this build, so the message says so
/// rather than blaming whoever ran the command.
fn no_usable_value(key: &str) -> Failure {
    Failure::config(
        "config.key_without_a_usable_value",
        format!("`{key}` carries no value this build can use"),
    )
    .with_detail("detail", key)
    .with_hint("this is a defect in the setting registry, not in the invocation")
}

/// Reads one key as a truth value.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and when the registry carries no truth value for the key.
pub fn boolean(config: &Config, key: &str) -> Result<bool> {
    match config.resolve(key)?.value {
        Some(Value::Boolean(value)) => Ok(value),
        _ => Err(no_usable_value(key)),
    }
}

/// Reads one key as a whole number.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and when the registry carries no number for the key.
pub fn integer(config: &Config, key: &str) -> Result<u64> {
    match config.resolve(key)?.value {
        Some(Value::Integer(value)) => Ok(value),
        _ => Err(no_usable_value(key)),
    }
}

/// Reads one key as a count that fits the machine's address size.
///
/// A number too large for this machine is clamped rather than refused: the key
/// asked for "at least this much", and the largest this machine can address is
/// the honest answer to that.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and when the registry carries no number for the key.
pub fn count(config: &Config, key: &str) -> Result<usize> {
    Ok(usize::try_from(integer(config, key)?).unwrap_or(usize::MAX))
}

/// Reads one key as a word of a closed list or as free text.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and when the registry carries no word for the key.
pub fn word(config: &Config, key: &str) -> Result<String> {
    match config.resolve(key)?.value {
        Some(Value::Enumeration(value)) => Ok(value.to_owned()),
        Some(Value::Text(value)) => Ok(value),
        _ => Err(no_usable_value(key)),
    }
}

/// Reads one key as a span of seconds.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and when the registry carries no number for the key.
pub fn seconds(config: &Config, key: &str) -> Result<Duration> {
    Ok(Duration::from_secs(integer(config, key)?))
}

/// The lowest protocol version the encrypted channel may negotiate.
///
/// This reader loads the settings itself, unlike every other one here, and the
/// reason is ordering rather than convenience. The floor is imposed by which
/// cipher suites the crypto provider offers, so it has to be known before the
/// provider is installed, which happens before the settings any command reads
/// have been resolved. Everything else on this page is read after that point
/// and takes an already-loaded `Config`.
///
/// A settings location that cannot be read answers with the published default
/// rather than a failure: refusing the whole invocation over the protocol floor
/// would be a larger consequence than the caller asked for, and the work loads
/// the same file again a moment later and reports the fault there with its own
/// cause.
#[must_use]
pub fn protocol_floor(
    config_dir: Option<&std::path::Path>,
) -> crate::conn::provider::ProtocolFloor {
    use crate::conn::provider::ProtocolFloor;

    Config::load(config_dir)
        .ok()
        .and_then(|config| word(&config, "tls.min_version").ok())
        .map_or(ProtocolFloor::default(), |value| {
            ProtocolFloor::from_word(&value)
        })
}

/// Reads one key that is deliberately absent until somebody stores it.
///
/// A key the server or the host decides carries no built-in, so demanding one
/// would turn "nobody has decided yet" into a failure. This is the only reader
/// that treats absence as an answer.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn optional_count(config: &Config, key: &str) -> Result<Option<usize>> {
    Ok(match config.resolve(key)?.value {
        Some(Value::Integer(value)) => usize::try_from(value).ok(),
        _ => None,
    })
}

/// Reads one word key that is deliberately absent until somebody stores it.
///
/// The companion of [`optional_count`], for the keys the host decides: the
/// language of messages is the host's until a caller says otherwise, and
/// inventing one here would override that silently.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn optional_word(config: &Config, key: &str) -> Result<Option<String>> {
    Ok(match config.resolve(key)?.value {
        Some(Value::Enumeration(value)) => Some(value.to_owned()),
        Some(Value::Text(value)) => Some(value),
        _ => None,
    })
}

/// How many simultaneous units of work this invocation admits.
///
/// The count follows the machine's cores, bounded by the stored ceiling and by
/// the one ceiling this product declares, so a large machine never turns into
/// an unbounded fan-out against a single server. That ceiling is not written
/// here: `runtime::gate` states it once, and this reads it.
///
/// Two numbers arrive here and they are deliberately not treated alike. A
/// number nobody typed — the host's own core count, or a ceiling left in the
/// settings — is a reading, and the honest answer to a reading above the
/// declared ceiling is the ceiling, so it is clamped. A number typed on the
/// command line is a request, and answering `1` where `0` was asked hides the
/// mistake instead of reporting it, so it is refused (FR-067).
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain,
/// and a usage failure when the number asked for on the command line is
/// outside the domain this product admits.
pub fn concurrency(config: &Config, flags: &GlobalFlags) -> Result<usize> {
    use crate::runtime::gate;

    // The ceiling the ceiling is held under. It was a number in `gate` and
    // nothing else, so an operator whose server could take more simultaneous
    // work had no way to say so, and the clamp below silently returned less
    // than was asked for. Settled before either branch reads it, because both
    // of them are held under it.
    gate::declare_ceiling(count(config, "limits.max_concurrency_ceiling")?);

    if let Some(asked) = flags.limits.max_concurrency {
        return gate::admissible(asked);
    }

    // This key is one the host decides, so the registry deliberately carries no
    // built-in for it and the machine's own core count stands in, already held
    // under the declared ceiling by the gate that publishes it.
    Ok(optional_count(config, "limits.max_concurrency")?
        .map_or_else(gate::permits_for_host, |stored| {
            stored.clamp(1, gate::ceiling())
        }))
}

/// Which change count the caller asked for.
///
/// The mark on the command line wins over the stored key, which wins over the
/// published default of counting the rows the server actually altered.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn row_count_matched(config: &Config, flags: &GlobalFlags) -> Result<bool> {
    if let Some(mode) = flags.output.row_count {
        return Ok(matches!(mode, FlagRowCountMode::Matched));
    }
    Ok(word(config, "sql.row_count_mode")? == "matched")
}

/// Whether the channel to the server carries compressed traffic.
///
/// The mark on the command line wins over the stored key, as every setting
/// does. `auto` leaves the decision to the negotiation, so only an explicit
/// `always` turns compression on from this side.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn compress(config: &Config, flags: &GlobalFlags) -> Result<bool> {
    Ok(match flags.limits.compress {
        Some(Compress::Always) => true,
        Some(Compress::Never | Compress::Auto) => false,
        None => word(config, "conn.compression")? == "always",
    })
}

/// Whether this invocation refuses to ask anything and fails instead.
///
/// This answers one question only: did the caller say it will not be asked.
/// Whether a given read would actually wait is a different question, answered
/// where the read happens, by [`refuse_a_read_that_would_wait`].
///
/// Keeping them apart is not tidiness. This once also reported the absence of
/// a terminal, and the sole consumer then required a terminal anyway, so that
/// half could never change an outcome: `(mark || !terminal) && terminal` is
/// just `mark && terminal`. It was documented as meaningful, it was not, and
/// it made the mark itself look inert under any harness with no terminal
/// attached.
#[must_use]
pub fn no_input(flags: &GlobalFlags) -> bool {
    flags.safety.no_input
}

/// Refuses a read that would sit there until a person types.
///
/// The companion of [`no_input`], for the two places that really do block: a
/// secret read from the standard input and a statement read from it. Both are
/// harmless when something was piped in, because reading what a caller sent is
/// not a question. Both wait forever on a terminal with nobody at it, which is
/// exactly what this invocation said it would not do.
///
/// So the refusal needs BOTH conditions: the invocation refuses to ask, and the
/// read would actually wait. Refusing on the first alone would break every
/// piped invocation, which is the ordinary way an agent runs this tool.
///
/// # Errors
///
/// Returns a validation failure when this invocation refuses to ask and the
/// read would wait for a person.
pub fn refuse_a_read_that_would_wait(refuses_to_ask: bool, what: &str) -> Result<()> {
    use std::io::IsTerminal as _;

    if refuses_to_ask && std::io::stdin().is_terminal() {
        return Err(Failure::validation(
            "input.refused",
            format!("reading {what} would wait for somebody to type, and this invocation refuses to ask"),
        )
        .with_detail("detail", "stdin")
        .with_hint("pipe the value in, or drop --no-input"));
    }
    Ok(())
}

/// The time budget for one operation.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn operation_timeout(config: &Config, flags: &GlobalFlags) -> Result<Duration> {
    match flags.limits.timeout {
        Some(secs) => Ok(Duration::from_secs(secs)),
        None => seconds(config, "limits.query_timeout_secs"),
    }
}

/// The time budget for opening a connection.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn connect_timeout(config: &Config, flags: &GlobalFlags) -> Result<Duration> {
    match flags.limits.connect_timeout {
        Some(secs) => Ok(Duration::from_secs(secs)),
        None => seconds(config, "limits.connect_timeout_secs"),
    }
}

/// How many times reaching the server is retried, and how long the waits are.
///
/// The mark on the command line wins over the stored key. Zero extra attempts
/// is a legal answer and means the first failure is the final one.
///
/// Two bounds are carried, not one. The ceiling bounds a single wait and the
/// deadline bounds the whole series, and a caller waiting on the policy cares
/// about the second: attempts under a ceiling still add up to a stall that
/// nothing in the count declared.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn retry_policy(config: &Config, flags: &GlobalFlags) -> Result<crate::runtime::Backoff> {
    // The ceiling on a single wait comes from `limits.retry_wait_ceiling_ms`.
    // Without one, a policy with many attempts turns a short operation into one
    // that looks like it has hung.
    //
    // It was a count of doublings written here, applied as a shift over the base
    // wait. That made the ceiling real and unreachable at the same time: the two
    // keys around it were published while the number that bounded them both was
    // not, which is exactly what the heading of this module says never happens.
    // Published as the ceiling itself rather than as the count of doublings,
    // because the ceiling is what anybody actually wants to move.
    let attempts = match flags.limits.retries {
        Some(asked) => asked,
        None => u32::try_from(integer(config, "limits.retries")?).unwrap_or_default(),
    };
    let base = Duration::from_millis(integer(config, "limits.retry_base_ms")?);
    Ok(crate::runtime::Backoff::new(
        attempts,
        base,
        Duration::from_millis(integer(config, "limits.retry_wait_ceiling_ms")?),
        Duration::from_millis(integer(config, "limits.retry_deadline_ms")?),
    ))
}

/// Where a secret this host records is allowed to come to rest.
///
/// # Errors
///
/// Returns a configuration failure when the stored word is outside the key's
/// domain, and when the registry carries no word for the key.
pub fn secret_storage(config: &Config) -> Result<crate::config::vault::SecretStorage> {
    crate::config::vault::SecretStorage::parse(&word(config, "secret.storage_mode")?)
}

/// Everything the encrypted channel obeys, read as one.
///
/// The four keys behind it are always read together, and a channel built from
/// three of them and a literal for the fourth would be exactly the defect this
/// module exists to prevent.
///
/// # Why one of them needs the command line too
///
/// Every other setting here answers what to do. Trusting an unknown authority
/// answers something else: it removes the only thing that tells the server
/// apart from whoever answered instead of it, and the channel stays encrypted
/// either way, so nothing about the result would look wrong.
///
/// A stored key is therefore not enough to reach that level. The key still says
/// which level to check at, and the invocation has to say that the caller knows
/// what that level leaves open. Requiring both is what stops a file written for
/// a laboratory server months ago from following the caller to a real one.
///
/// The level that only accepts a name mismatch is not covered, and the
/// difference is not a matter of degree: there the certificate is still signed
/// by an authority the caller trusts, and an impostor still needs one.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain,
/// and when the stored level trusts an unknown authority without the
/// invocation saying so.
pub fn encryption(config: &Config, flags: &GlobalFlags) -> Result<crate::conn::tls::Encryption> {
    use crate::conn::tls::{Encryption, RootStore, Verification};

    let verification = Verification::parse(&word(config, "tls.verify")?)?;
    if verification.accept_unknown_authority && !flags.safety.accept_unverified_tls {
        return Err(Failure::config(
            "config.unverified_tls_unacknowledged",
            "`tls.verify` is set to trust an unknown authority, which is the \
             check that tells the server apart from an impostor",
        )
        .with_detail("detail", "tls.verify")
        .with_hint(
            "pass `--accept-unverified-tls` to take that risk for this \
             invocation, or set `tls.verify` to full or to ca",
        ));
    }

    Ok(Encryption {
        demanded: boolean(config, "conn.require_tls")?,
        verification,
        root_store: RootStore::parse(&word(config, "tls.root_store")?)?,
    })
}

/// Everything that shapes a value on its way out, read as one.
///
/// The shape of a byte value is a setting the type map must not decide for
/// itself, and the ceiling on raw content is the one already published for the
/// whole answer: a single value larger than the answer's own volume ceiling
/// could never be emitted anyway, so inventing a second number for it would be
/// a ceiling nobody could find.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain,
/// and when the shape is a word this build does not know.
pub fn conversion(config: &Config) -> Result<crate::types::Conversion> {
    use crate::types::binary::{Content, Policy};
    use crate::types::Conversion;

    let content = match word(config, "output.binary")?.as_str() {
        "summary" => Content::Described,
        "full" => Content::Raw {
            max_bytes: count(config, "output.max_bytes")?,
        },
        other => {
            return Err(Failure::config(
                "config.unknown_binary_shape",
                format!("`{other}` is not a shape a byte value can take"),
            )
            .with_detail("detail", other)
            .with_hint("set output.binary to summary or to full"))
        }
    };

    Ok(Conversion {
        binary: Policy { content },
    })
}

/// The adjustments every session gets before the ones its destination declares.
///
/// The key holds one text because that is what a settings file can carry, and a
/// host that needs more than one adjustment separates them with a semicolon,
/// which is what separates statements everywhere else. Nothing stored means no
/// adjustment, never an empty statement the server would refuse.
///
/// # Errors
///
/// Returns a configuration failure when the stored value is outside its domain.
pub fn session_setup(config: &Config) -> Result<Vec<String>> {
    Ok(optional_word(config, "conn.session_setup")?
        .into_iter()
        .flat_map(|stored| {
            stored
                .split(';')
                .map(str::trim)
                .filter(|adjustment| !adjustment.is_empty())
                .map(ToOwned::to_owned)
                .collect::<Vec<_>>()
        })
        .collect())
}

/// Whether this invocation refuses every change before opening a connection.
///
/// The mark on the command line only tightens: a caller may ask for refusal
/// even where the stored key allows change, and never the other way round.
///
/// # Errors
///
/// Returns a config failure when the stored value is outside the key's domain.
pub fn read_only(config: &Config, flags: &GlobalFlags) -> Result<bool> {
    Ok(flags.safety.read_only || boolean(config, "sql.read_only")?)
}

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

    fn flags_from(args: &[&str]) -> GlobalFlags {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .chain(["meta", "version"])
            .map(ToOwned::to_owned)
            .collect();
        crate::cli::Cli::try_parse_from(command_line)
            .expect("the sample invocation parses")
            .globals
    }

    fn empty_config() -> Config {
        let scratch = tempfile::tempdir().expect("scratch directory");
        Config::load(Some(scratch.path())).expect("an empty location still loads")
    }

    /// Nothing stored means the registry's own built-in is what the work
    /// reads, and no literal written beside the reader can override it.
    #[test]
    fn a_missing_key_falls_back_to_the_published_default() {
        let config = empty_config();
        assert_eq!(integer(&config, "limits.retries").expect("resolves"), 2);
        assert!(!boolean(&config, "sql.read_only").expect("resolves"));
    }

    #[test]
    fn a_mark_on_the_command_line_beats_the_stored_value() {
        let config = empty_config();
        let flags = flags_from(&["--timeout", "5"]);
        assert_eq!(
            operation_timeout(&config, &flags).expect("resolves"),
            Duration::from_secs(5)
        );
    }

    /// The mark only tightens. The published default lets change through, so
    /// the defence is the confirmation, the required restriction and the
    /// ceiling on affected rows, each of which refuses on its own merits.
    #[test]
    fn the_refusal_mark_only_ever_tightens() {
        let config = empty_config();
        let asked = flags_from(&["--read-only"]);
        assert!(read_only(&config, &asked).expect("resolves"));

        let silent = flags_from(&[]);
        assert!(
            !read_only(&config, &silent).expect("resolves"),
            "nothing but the mark or the key may refuse every change"
        );
    }

    /// Asking for no repeats must mean no repeats, and not fall back to the
    /// stored value: a caller who wrote zero meant zero.
    #[test]
    fn asking_for_no_repeats_is_honoured() {
        let config = empty_config();
        assert_eq!(
            retry_policy(&config, &flags_from(&["--retries", "0"]))
                .expect("resolves")
                .extra_attempts,
            0
        );
        assert_eq!(
            retry_policy(&config, &flags_from(&["--retries", "4"]))
                .expect("resolves")
                .extra_attempts,
            4
        );
    }

    /// The wait grows and then stops, so many attempts never turn a short
    /// operation into one that looks like it has hung.
    #[test]
    fn the_wait_between_attempts_grows_and_then_stops() {
        let policy = retry_policy(&empty_config(), &flags_from(&[])).expect("resolves");
        assert_eq!(policy.wait_before(1), Duration::from_millis(200));
        assert_eq!(policy.wait_before(2), Duration::from_millis(400));
        assert_eq!(policy.wait_before(50), policy.ceiling);
        assert!(policy.ceiling <= Duration::from_secs(10));
    }

    /// The configured level alone never reaches the trust of an unknown
    /// authority, because that level is the one an impostor needs.
    ///
    /// Every other setting here answers what to do, and this one answers
    /// whether the server on the other end is the server. A file written for a
    /// laboratory months ago is exactly how that answer follows somebody to a
    /// real destination, so the invocation has to say it too.
    #[test]
    fn trusting_an_unknown_authority_is_refused_unless_the_invocation_says_so() {
        let config = empty_config()
            .with_flag("tls.verify", "none")
            .expect("a legal level");

        let failure =
            encryption(&config, &flags_from(&[])).expect_err("the level alone is not enough");
        assert_eq!(failure.code(), "config.unverified_tls_unacknowledged");
        assert!(
            failure.hint().is_some_and(|hint| hint.contains("full")),
            "the way back to a checked channel is named"
        );

        let acknowledged = encryption(&config, &flags_from(&["--accept-unverified-tls"]))
            .expect("the caller said so");
        assert!(
            acknowledged.verification.accept_unknown_authority,
            "the level asked for is the level given"
        );
    }

    /// Accepting a name mismatch is not the same risk and is not covered.
    ///
    /// There the certificate is still signed by an authority the caller trusts,
    /// so an impostor still needs one; demanding the same word for both would
    /// teach callers to type it out of habit.
    #[test]
    fn accepting_a_name_mismatch_needs_no_acknowledgement() {
        let config = empty_config()
            .with_flag("tls.verify", "ca")
            .expect("a legal level");

        let resolved = encryption(&config, &flags_from(&[])).expect("the chain is still checked");
        assert!(resolved.verification.accept_address_mismatch);
        assert!(!resolved.verification.accept_unknown_authority);
    }

    /// The channel's published defaults come from the registry alone, so no
    /// literal beside a reader can weaken a destination on its own.
    #[test]
    fn the_channel_takes_its_published_defaults() {
        use crate::conn::provider::ProtocolFloor;
        use crate::conn::tls::RootStore;

        let resolved = encryption(&empty_config(), &flags_from(&[])).expect("resolves");
        assert!(
            resolved.demanded,
            "an encrypted channel is demanded by default"
        );
        assert!(resolved.verification.is_strict(), "both checks stay on");
        assert_eq!(resolved.root_store, RootStore::System);

        // The floor is read on its own, before the provider is installed, so it
        // is checked here rather than on the channel it never travels with.
        let scratch = tempfile::tempdir().expect("scratch directory");
        assert_eq!(
            protocol_floor(Some(scratch.path())),
            ProtocolFloor::Twelve,
            "nothing below 1.2 is offered and 1.3 is not demanded by default"
        );
    }

    /// Both words of the floor have to mean different providers, or the setting
    /// is one the product stores and never acts on.
    #[test]
    fn asking_for_the_newer_protocol_raises_the_floor() {
        use crate::conn::provider::ProtocolFloor;

        let scratch = tempfile::tempdir().expect("scratch directory");
        let file =
            crate::config::paths::config_file(Some(scratch.path())).expect("a settings location");
        crate::config::store::store(&file, "tls.min_version", "1.3").expect("legal");

        assert_eq!(
            protocol_floor(Some(scratch.path())),
            ProtocolFloor::Thirteen
        );
    }

    /// The refusal needs both conditions, or every piped invocation breaks.
    ///
    /// Under a test harness there is no terminal, so no read would wait and
    /// nothing is refused whatever the mark says. That is the point: refusing
    /// on the mark alone would break the ordinary way an agent runs this tool.
    #[test]
    fn a_read_is_refused_only_when_it_would_really_wait() {
        use std::io::IsTerminal as _;

        let on_a_terminal = std::io::stdin().is_terminal();

        // Refusing to ask is necessary.
        assert!(
            refuse_a_read_that_would_wait(false, "a secret").is_ok(),
            "an invocation that never said it refuses must still be able to read"
        );

        // And on its own it is not sufficient: the read has to be one that
        // would wait, which is what having a terminal means.
        let refused = refuse_a_read_that_would_wait(true, "a secret");
        assert_eq!(
            refused.is_err(),
            on_a_terminal,
            "the refusal must follow whether a person could be waiting"
        );

        if let Err(failure) = refused {
            assert_eq!(failure.code(), "input.refused");
            assert_eq!(failure.exit_number().code(), 3);
            assert!(failure.hint().is_some());
        }
    }

    /// Nothing stored means no adjustment, never an empty statement the server
    /// would refuse.
    #[test]
    fn a_session_gets_no_adjustment_until_one_is_stored() {
        assert!(session_setup(&empty_config()).expect("resolves").is_empty());
    }

    /// A byte value leaves as a description until somebody asks for the content,
    /// and that choice comes from the registry rather than from a word written
    /// beside the type map.
    #[test]
    fn a_byte_value_is_described_until_the_content_is_asked_for() {
        use crate::types::binary::Content;

        let described = conversion(&empty_config()).expect("resolves");
        assert_eq!(described.binary.content, Content::Described);
    }

    /// Both words have to mean different things, or the setting is one the
    /// product stores and never acts on.
    #[test]
    fn asking_for_the_content_changes_what_a_byte_value_becomes() {
        use crate::types::binary::Content;

        let scratch = tempfile::tempdir().expect("scratch directory");
        let file =
            crate::config::paths::config_file(Some(scratch.path())).expect("a settings location");
        crate::config::store::store(&file, "output.binary", "full").expect("legal");
        let config = Config::load(Some(scratch.path())).expect("the location loads");

        assert!(matches!(
            conversion(&config).expect("resolves").binary.content,
            Content::Raw { .. }
        ));
    }

    /// FR-067. A ceiling of zero on the command line is refused rather than
    /// quietly rewritten as one, and the refusal is a usage failure.
    #[test]
    fn a_ceiling_of_zero_on_the_command_line_is_refused() {
        let failure = concurrency(&empty_config(), &flags_from(&["--max-concurrency", "0"]))
            .expect_err("zero admits no work");
        assert_eq!(failure.code(), "concurrency.none_admitted");
        assert_eq!(failure.exit_number().code(), 2);
    }

    /// FR-067. There is one declared ceiling, the gate publishes it, and a
    /// number above it typed on the command line is refused against that one.
    #[test]
    fn a_ceiling_above_the_declared_one_is_refused_against_the_only_ceiling() {
        let above = (crate::runtime::gate::MAX_PERMITS + 1).to_string();
        let failure = concurrency(&empty_config(), &flags_from(&["--max-concurrency", &above]))
            .expect_err("above the ceiling");
        assert_eq!(failure.code(), "concurrency.above_ceiling");
        assert_eq!(failure.exit_number().code(), 2);

        assert_eq!(
            concurrency(
                &empty_config(),
                &flags_from(&[
                    "--max-concurrency",
                    &crate::runtime::gate::MAX_PERMITS.to_string()
                ])
            )
            .expect("the ceiling itself is legal"),
            crate::runtime::gate::MAX_PERMITS
        );
    }

    /// FR-067. Nothing asked for means the host's own count, which is a
    /// reading and is therefore held under the ceiling rather than refused.
    #[test]
    fn the_host_count_stands_in_when_nothing_was_asked_for() {
        let resolved = concurrency(&empty_config(), &flags_from(&[])).expect("resolves");
        assert!(resolved >= 1);
        assert!(resolved <= crate::runtime::gate::MAX_PERMITS);
    }

    #[test]
    fn the_change_count_defaults_to_the_rows_the_server_altered() {
        let config = empty_config();
        assert!(!row_count_matched(&config, &flags_from(&[])).expect("resolves"));
        assert!(
            row_count_matched(&config, &flags_from(&["--row-count", "matched"])).expect("resolves")
        );
    }
}