pimalaya-cli 0.3.2

CLI utils for Pimalaya
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! OS-aware credential-provider picker shared by the account wizards.
//!
//! A secret is read from a well-known credential CLI, from a custom
//! shell command, or stored raw in the configuration. Two flavours share
//! the same machinery:
//!
//! - a **password** is read from an OS keyring ([`KeyringProvider`]);
//! - an **OAuth 2.0 access token** is read from a token broker
//!   ([`TokenBroker`]) that refreshes it on every read.
//!
//! A known provider or broker yields an argv command (no shell), so the
//! config serializes it as a TOML array; only a custom command falls
//! back to a shell string. [`prompt_secret`] and [`prompt_token`] only
//! record the read command, leaving the value for the user to store
//! under the chosen entry beforehand. [`prompt_password`] asks for the
//! password once and [`prompt_store`] stores it after the caller tested
//! it, reading it back before answering the read command.
//!
//! Both lists are ordered by what the running system can actually do:
//! the entries whose CLI is found on the `PATH` lead, the rest follow
//! and say so. Nothing is hidden, since a provider missing today is one
//! package install away and the configuration written for it is correct
//! either way.

use core::fmt;
use std::{
    env,
    ffi::OsStr,
    io::{self, Write},
    path::Path,
    process::{Command, ExitStatus, Stdio},
};

use secrecy::{ExposeSecret, SecretSlice, SecretString};

use crate::prompt::{self, PromptResult};

/// Extensions Windows appends to a bare program name, tried after the
/// name itself. The `PATHEXT` list in practice, minus the entries no
/// credential CLI ships as.
#[cfg(windows)]
const WINDOWS_EXTENSIONS: [&str; 3] = [".exe", ".cmd", ".bat"];

/// A well-known credential-provider CLI a password can be read from.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KeyringProvider {
    /// `secret-tool`, over the Secret Service (GNOME Keyring).
    SecretTool,
    /// `kwallet-query`, over the KDE Wallet.
    KwalletQuery,
    /// `security`, over the macOS Keychain.
    Security,
    /// `pass`, the standard unix password manager.
    Pass,
}

impl KeyringProvider {
    /// The providers relevant on the running OS, the ones actually
    /// installed first and the rest in their wake, each group keeping
    /// the native-first order. Empty on platforms without a known
    /// stdin-friendly provider (Windows), where the picker goes straight
    /// to a custom command.
    pub fn available() -> Vec<Self> {
        let mut providers = Vec::new();

        if cfg!(target_os = "linux") {
            providers.push(Self::SecretTool);
            providers.push(Self::KwalletQuery);
        }

        if cfg!(target_os = "macos") {
            providers.push(Self::Security);
        }

        if cfg!(unix) {
            providers.push(Self::Pass);
        }

        // NOTE: a stable sort, so the native-first order above survives
        // inside the installed and the missing group alike.
        providers.sort_by_key(|provider| !provider.installed());

        providers
    }

    /// Whether this provider's CLI is found on the `PATH`, which is what
    /// leads the pick list: an installed provider is one a secret can be
    /// stored in today, while the rest are a package install away.
    ///
    /// The provider names its own program, being the first element of
    /// its read command, so no table of binary names is duplicated here.
    pub fn installed(self) -> bool {
        installed(&self.read_command(None, ""))
    }

    /// Display name of the provider, for the pick-list labels.
    pub fn name(self) -> &'static str {
        match self {
            Self::SecretTool => "secret-tool (GNOME Keyring / Secret Service)",
            Self::KwalletQuery => "kwallet-query (KDE Wallet)",
            Self::Security => "security (macOS Keychain)",
            Self::Pass => "pass (password store)",
        }
    }

    /// The argv (program + arguments, no shell) printing the secret at
    /// `key` on stdout — the value of the `*.command` config field.
    ///
    /// `key` is used **verbatim** as the entry identifier: `service` is
    /// an optional namespace a *self-owning* broker (which stores and
    /// reads its own value, e.g. an OAuth token manager) adds — a path
    /// prefix for `pass`/`kwallet`, a distinct attribute for
    /// `secret-tool`/`security`. Pass `None` to read a pre-existing entry
    /// exactly as named.
    pub fn read_command(self, service: Option<&str>, key: &str) -> Vec<String> {
        match self {
            Self::SecretTool => match service {
                Some(service) => {
                    argv(["secret-tool", "lookup", "service", service, "account", key])
                }
                None => secret_tool_lookup("account", key),
            },
            Self::KwalletQuery => {
                let entry = path(service, key);
                argv(["kwallet-query", "-r", &entry, "kdewallet"])
            }
            Self::Security => match service {
                Some(service) => argv([
                    "security",
                    "find-generic-password",
                    "-s",
                    service,
                    "-a",
                    key,
                    "-w",
                ]),
                None => argv(["security", "find-generic-password", "-a", key, "-w"]),
            },
            Self::Pass => {
                let entry = path(service, key);
                argv(["pass", "show", &entry])
            }
        }
    }

    /// The shell command line *persisting* a secret it receives on stdin
    /// — the write half of a store/read pair for a broker that owns the
    /// value (e.g. an OAuth token manager), as opposed to a pre-existing
    /// entry the user stores themselves. A shell line rather than an
    /// argv: the writes rely on shell features (`$(cat)` on macOS).
    pub fn write_command(self, service: Option<&str>, key: &str) -> String {
        match self {
            Self::SecretTool => match service {
                Some(service) => format!(
                    "secret-tool store --label {service}/{key} service {service} account {key}"
                ),
                None => format!("secret-tool store --label {key} account {key}"),
            },
            Self::KwalletQuery => format!("kwallet-query -w {} kdewallet", path(service, key)),
            // `security` takes the secret as an argument, not on stdin;
            // `$(cat)` bridges it, and `-U` overwrites an existing entry.
            // It also requires `-s`, so an entry without a namespace names
            // both the service and the account, the read by account alone
            // still finding it.
            Self::Security => {
                let service = service.unwrap_or(key);
                format!("security add-generic-password -U -s {service} -a {key} -w \"$(cat)\"")
            }
            Self::Pass => format!("pass insert -m -f {}", path(service, key)),
        }
    }

    /// Stores `secret` at `key`, the entry `read_command(None, key)` reads,
    /// writing it on the program's stdin and never on its arguments.
    pub fn store(self, key: &str, secret: &SecretString) -> io::Result<()> {
        let line = match self {
            Self::Security => Some(security_line(key, secret)?),
            _ => None,
        };

        let input = line.as_ref().unwrap_or(secret);
        let argv = self.store_command(key);

        let mut child = Command::new(&argv[0])
            .args(&argv[1..])
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()?;

        // NOTE: a broken pipe says less than the program's stderr.
        let written = match child.stdin.take() {
            Some(mut stdin) => stdin.write_all(input.expose_secret().as_bytes()),
            None => Ok(()),
        };

        let output = child.wait_with_output()?;

        if !output.status.success() {
            return Err(failure(&argv[0], &output.stderr, output.status));
        }

        written
    }

    /// The argv storing the entry at `key`, the secret going on its stdin.
    fn store_command(self, key: &str) -> Vec<String> {
        match self {
            Self::SecretTool => argv(["secret-tool", "store", "--label", key, "account", key]),
            Self::KwalletQuery => argv(["kwallet-query", "-w", key, "kdewallet"]),
            Self::Security => argv(["security", "-i"]),
            Self::Pass => argv(["pass", "insert", "-m", "-f", key]),
        }
    }

    /// Reads the entry at `key` back, failing unless it holds `secret`.
    fn read_back(self, key: &str, secret: &SecretString) -> io::Result<()> {
        let argv = self.read_command(None, key);

        let output = Command::new(&argv[0])
            .args(&argv[1..])
            .stdin(Stdio::null())
            .output()?;

        let stdout = SecretSlice::from(output.stdout);

        if !output.status.success() {
            return Err(failure(&argv[0], &output.stderr, output.status));
        }

        let stored = stdout.expose_secret();
        let stored = stored.strip_suffix(b"\n").unwrap_or(stored);

        if stored != secret.expose_secret().as_bytes() {
            return Err(io::Error::other("Entry read back does not match"));
        }

        Ok(())
    }
}

/// A well-known OAuth 2.0 token broker: an external CLI that owns the
/// account's refresh token and prints a *fresh* access token on stdout.
///
/// Himalaya (and the other Pimalaya tools) ship no OAuth flow of their
/// own; they call one of these on every connection. Reference
/// implementation ([`Ortie`](Self::Ortie)) first.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TokenBroker {
    /// `ortie`, the Pimalaya OAuth 2.0 token broker.
    Ortie,
    /// `pizauth`, an OAuth 2.0 token daemon.
    Pizauth,
    /// `oama`, the OAuth Anywhere Mail Agent.
    Oama,
}

impl TokenBroker {
    /// The known brokers, the ones actually installed first and the rest
    /// in their wake, each group keeping the reference-implementation
    /// order. Not OS-specific: all are cross-platform CLIs.
    pub fn available() -> Vec<Self> {
        let mut brokers = vec![Self::Ortie, Self::Pizauth, Self::Oama];

        // NOTE: a stable sort, as in `KeyringProvider::available`.
        brokers.sort_by_key(|broker| !broker.installed());

        brokers
    }

    /// Whether this broker's CLI is found on the `PATH`. Most users run
    /// one broker at most, so the one they have leads the list rather
    /// than sitting under two they never installed.
    pub fn installed(self) -> bool {
        installed(&self.read_command(""))
    }

    /// Display name of the broker, for the pick-list labels.
    pub fn name(self) -> &'static str {
        match self {
            Self::Ortie => "ortie (Pimalaya OAuth 2.0 token broker)",
            Self::Pizauth => "pizauth (OAuth 2.0 token daemon)",
            Self::Oama => "oama (OAuth Anywhere Mail Agent)",
        }
    }

    /// The argv (program + arguments, no shell) printing a fresh access
    /// token for `account` on stdout — the value of the `*.command`
    /// config field.
    ///
    /// `account` is the broker's own account handle: a name for `ortie`
    /// and `pizauth`, the email address for `oama`. It defaults to the
    /// Himalaya account name; the user adjusts it to match the broker's
    /// configuration.
    pub fn read_command(self, account: &str) -> Vec<String> {
        match self {
            Self::Ortie => argv(["ortie", "token", "show", "-a", account]),
            Self::Pizauth => argv(["pizauth", "show", account]),
            Self::Oama => argv(["oama", "access", account]),
        }
    }
}

/// Whether the program `argv` starts with is found on the `PATH`.
///
/// An empty `PATH`, or none at all, answers no for everything, which
/// leaves the pick list in its native order rather than pretending
/// nothing is installed in a way the labels would announce.
fn installed(argv: &[String]) -> bool {
    let Some(program) = argv.first() else {
        return false;
    };

    let Some(paths) = env::var_os("PATH") else {
        return false;
    };

    found_in(&paths, program)
}

/// Whether `program` sits in one of the directories `paths` lists.
///
/// Split from [`installed`] so the lookup is testable against a `PATH`
/// built for the test rather than the one the test runner inherited.
fn found_in(paths: &OsStr, program: &str) -> bool {
    env::split_paths(paths).any(|dir| found_at(&dir, program))
}

/// Whether `program` is a file in `dir`.
#[cfg(not(windows))]
fn found_at(dir: &Path, program: &str) -> bool {
    dir.join(program).is_file()
}

/// Whether `program` is a file in `dir`, under its bare name or under
/// one of the extensions Windows appends to it.
///
/// A bare name is not a filename there, and while the keyring providers
/// are all absent on Windows, the token brokers are not.
#[cfg(windows)]
fn found_at(dir: &Path, program: &str) -> bool {
    dir.join(program).is_file()
        || WINDOWS_EXTENSIONS
            .iter()
            .any(|extension| dir.join(format!("{program}{extension}")).is_file())
}

/// Collects `parts` into an owned argv vector.
fn argv<const N: usize>(parts: [&str; N]) -> Vec<String> {
    parts.iter().map(|part| part.to_string()).collect()
}

/// The argv looking up the `secret-tool` entry whose `attribute` is `key`.
///
/// `account` is the attribute a pre-existing entry is read by when none is
/// named; a KeePassXC entry keyed by its `Title` is read by `Title`.
fn secret_tool_lookup(attribute: &str, key: &str) -> Vec<String> {
    argv(["secret-tool", "lookup", attribute, key])
}

/// Renders a path-based entry: `key` alone, or `service/key` when a
/// namespace is given.
fn path(service: Option<&str>, key: &str) -> String {
    match service {
        Some(service) => format!("{service}/{key}"),
        None => key.to_owned(),
    }
}

/// The `security -i` line storing `secret` at `key`, its values quoted.
///
/// A line break would start another command, so one is refused.
fn security_line(key: &str, secret: &SecretString) -> io::Result<SecretString> {
    let secret = secret.expose_secret();

    if key.contains(['\n', '\r']) || secret.contains(['\n', '\r']) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Cannot store a key or a secret holding a line break",
        ));
    }

    // NOTE: sized up front, so no reallocation leaves a copy of the secret.
    let mut line = String::with_capacity(64 + 4 * key.len() + 2 * secret.len());

    line.push_str("add-generic-password -U -s ");
    push_quoted(&mut line, key);
    line.push_str(" -a ");
    push_quoted(&mut line, key);
    line.push_str(" -w ");
    push_quoted(&mut line, secret);
    line.push('\n');

    Ok(line.into())
}

/// Appends `value` to `line` double-quoted, `"` and `\` escaped.
fn push_quoted(line: &mut String, value: &str) {
    line.push('"');

    for c in value.chars() {
        if matches!(c, '"' | '\\') {
            line.push('\\');
        }

        line.push(c);
    }

    line.push('"');
}

/// The error of `program` exiting with `status`, from its stderr text.
fn failure(program: &str, stderr: &[u8], status: ExitStatus) -> io::Error {
    let stderr = String::from_utf8_lossy(stderr);
    let stderr = stderr.split_whitespace().collect::<Vec<_>>().join(" ");

    if stderr.is_empty() {
        return io::Error::other(format!("{program} failed, {status}"));
    }

    io::Error::other(stderr)
}

/// The `label` of a prompt as a noun in a sentence: `Password` reads
/// `password`, an initialism such as `API token` stays as written.
fn noun(label: &str) -> String {
    let mut chars = label.chars();

    match (chars.next(), chars.next()) {
        (Some(first), Some(second)) if second.is_lowercase() => first
            .to_lowercase()
            .chain(label[first.len_utf8()..].chars())
            .collect(),
        _ => label.to_string(),
    }
}

/// Whether the host of `endpoint` is neither `domain` nor a subdomain of it.
///
/// The userinfo before the host ends at the last `@`, as in a URL.
fn off_domain(endpoint: &str, domain: &str) -> bool {
    let rest = match endpoint.split_once("://") {
        Some((_, rest)) => rest,
        None => endpoint,
    };

    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..end];

    let authority = match authority.rsplit_once('@') {
        Some((_, authority)) => authority,
        None => authority,
    };

    let host = match authority.strip_prefix('[') {
        Some(ipv6) => ipv6.split(']').next().unwrap_or_default(),
        None => authority.split(':').next().unwrap_or_default(),
    };

    let host = host.trim_end_matches('.').to_lowercase();
    let domain = domain.trim_end_matches('.').to_lowercase();

    host != domain && !host.ends_with(&format!(".{domain}"))
}

/// A secret collected by the picker.
///
/// A known provider or broker yields an argv [`Command`](Self::Command)
/// (serialized as a TOML array); a user-typed command is a
/// [`Shell`](Self::Shell) line (serialized as a string), the fallback
/// form run through the platform shell.
pub enum SecretChoice {
    /// An argv command (program + arguments, no shell) whose stdout is
    /// the secret. The preferred form.
    Command(Vec<String>),
    /// A raw shell command line whose stdout is the secret — the
    /// fallback, run through the platform shell.
    Shell(String),
    /// The secret stored raw (plaintext) in the configuration.
    Raw(SecretString),
}

/// One entry in the secret pick list: a keyring provider, an OAuth
/// broker, a custom command, or a raw value.
///
/// A provider and a broker carry whether their CLI was found on the
/// `PATH`, which the label says out loud: an entry that cannot run today
/// is still offered, since installing it afterwards makes the very same
/// configuration work.
#[derive(Eq, PartialEq)]
enum Choice {
    Keyring {
        provider: KeyringProvider,
        installed: bool,
    },
    Broker {
        broker: TokenBroker,
        installed: bool,
    },
    Custom,
    Raw,
}

impl fmt::Display for Choice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Keyring {
                provider,
                installed,
            } => write!(f, "{}", label(provider.name(), *installed)),
            Self::Broker { broker, installed } => {
                write!(f, "{}", label(broker.name(), *installed))
            }
            Self::Custom => f.write_str("Custom shell command"),
            Self::Raw => f.write_str("Store raw in the configuration (plaintext, NOT recommended)"),
        }
    }
}

/// Appends the missing-CLI mention to a pick-list label, leaving an
/// installed entry named plainly.
fn label(name: &str, installed: bool) -> String {
    if installed {
        return name.to_owned();
    }

    format!("{name}, not found on PATH")
}

/// One entry in the store pick list of [`prompt_store`].
#[derive(Eq, PartialEq)]
enum Storage {
    Keyring(KeyringProvider),
    Custom,
    Raw,
}

impl fmt::Display for Storage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Keyring(provider) => write!(f, "Store it in {}", provider.name()),
            Self::Custom => f.write_str("Custom shell command printing it"),
            Self::Raw => f.write_str("Raw in the configuration (plaintext, NOT recommended)"),
        }
    }
}

/// Prompts for a password: a pick list of the OS keyring providers, then
/// a custom command, then a raw value. The providers whose CLI is found
/// on the `PATH` lead the list, the rest saying they are missing.
///
/// `key_default` seeds the entry prompt, and the chosen entry is used
/// verbatim: a pre-existing secret is read exactly as named.
pub fn prompt_secret(label: &str, key_default: &str) -> PromptResult<SecretChoice> {
    let mut choices = keyring_choices();
    choices.push(Choice::Custom);
    choices.push(Choice::Raw);

    prompt_choice(label, key_default, choices)
}

/// Prompts for an API token: a pick list combining the OS keyrings (for
/// a token the user generated on the provider and stored themselves) and,
/// when `oauth` is true, the OAuth 2.0 token brokers (which refresh and
/// print a fresh token on every read), then a custom command and a raw
/// value. Same aim as [`prompt_secret`] — a command that returns the
/// token — merging both acquisition paths behind one strategy prompt. The
/// brokers are hidden unless the service advertises OAuth; within each
/// family, the ones whose CLI is found on the `PATH` lead.
pub fn prompt_token(label: &str, key_default: &str, oauth: bool) -> PromptResult<SecretChoice> {
    let mut choices = keyring_choices();
    if oauth {
        choices.extend(
            TokenBroker::available()
                .into_iter()
                .map(|broker| Choice::Broker {
                    installed: broker.installed(),
                    broker,
                }),
        );
    }
    choices.push(Choice::Custom);
    choices.push(Choice::Raw);

    prompt_choice(label, key_default, choices)
}

/// Prompts once for a masked secret, after naming on stderr each of the
/// `endpoints` it goes to and whether one is off the address's `domain`.
pub fn prompt_password(
    label: &str,
    endpoints: &[&str],
    domain: Option<&str>,
) -> PromptResult<SecretString> {
    let noun = noun(label);

    for endpoint in endpoints {
        match domain {
            Some(domain) if off_domain(endpoint, domain) => {
                eprintln!("Your {noun} goes to {endpoint}, not on {domain}")
            }
            _ => eprintln!("Your {noun} goes to {endpoint}"),
        }
    }

    let password = prompt::secret(format!("{label}:"))?;

    Ok(password.into())
}

/// Prompts where to keep a tested secret: an installed keyring, storing it
/// at `key` and reading it back, a custom command, or the raw value.
pub fn prompt_store(label: &str, key: &str, secret: &SecretString) -> PromptResult<SecretChoice> {
    let mut providers: Vec<_> = KeyringProvider::available()
        .into_iter()
        .filter(|provider| provider.installed())
        .collect();

    loop {
        let mut choices: Vec<_> = providers.iter().copied().map(Storage::Keyring).collect();
        choices.push(Storage::Custom);
        choices.push(Storage::Raw);

        match prompt::item(format!("{label} storage:"), choices, None)? {
            Storage::Keyring(provider) => {
                let stored = provider
                    .store(key, secret)
                    .and_then(|()| provider.read_back(key, secret));

                match stored {
                    Ok(()) => return Ok(SecretChoice::Command(provider.read_command(None, key))),
                    Err(err) => {
                        eprintln!("Cannot store {label} in {}: {err}", provider.name());
                        providers.retain(|other| *other != provider);
                    }
                }
            }
            Storage::Custom => {
                let command = prompt::text(format!("{label} shell command:"), None::<String>)?;
                return Ok(SecretChoice::Shell(command));
            }
            Storage::Raw => return Ok(SecretChoice::Raw(secret.clone())),
        }
    }
}

/// The keyring providers as pick-list entries, in the order
/// [`KeyringProvider::available`] resolved and each labelled with
/// whether its CLI is there.
fn keyring_choices() -> Vec<Choice> {
    KeyringProvider::available()
        .into_iter()
        .map(|provider| Choice::Keyring {
            installed: provider.installed(),
            provider,
        })
        .collect()
}

/// Renders the pick list and resolves the selection into a
/// [`SecretChoice`].
///
/// `label` names the secret ("IMAP password", "API token") and
/// `key_default` seeds the entry/account prompt. A keyring entry is used
/// **verbatim** (no namespace), so a pre-existing secret is read exactly
/// as named; the value must already be stored under it, and a missing one
/// surfaces when the caller tests the account right after.
fn prompt_choice(
    label: &str,
    key_default: &str,
    choices: Vec<Choice>,
) -> PromptResult<SecretChoice> {
    match prompt::item(format!("{label} strategy:"), choices, None)? {
        Choice::Keyring {
            provider: KeyringProvider::SecretTool,
            ..
        } => {
            let attribute = prompt::text(
                format!("{label} keyring attribute:"),
                Some("account".to_owned()),
            )?;
            let key = prompt::text(
                format!("{label} keyring entry:"),
                Some(key_default.to_owned()),
            )?;

            // NOTE: a blank attribute cannot name anything, so it reads
            // by `account`.
            let attribute = match attribute.trim() {
                "" => "account",
                attribute => attribute,
            };

            Ok(SecretChoice::Command(secret_tool_lookup(attribute, &key)))
        }
        Choice::Keyring { provider, .. } => {
            let key = prompt::text(
                format!("{label} keyring entry:"),
                Some(key_default.to_owned()),
            )?;

            Ok(SecretChoice::Command(provider.read_command(None, &key)))
        }
        Choice::Broker { broker, .. } => {
            let account = prompt::text(format!("{label} account:"), Some(key_default.to_owned()))?;

            Ok(SecretChoice::Command(broker.read_command(&account)))
        }
        Choice::Custom => {
            let command = prompt::text(format!("{label} shell command:"), None::<String>)?;
            Ok(SecretChoice::Shell(command))
        }
        Choice::Raw => {
            let secret = prompt::password(format!("{label}:"), format!("Confirm {label}:"))?;
            Ok(SecretChoice::Raw(secret))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, path::PathBuf};

    use super::*;

    #[test]
    fn keyring_read_command_uses_the_entry_verbatim_without_a_namespace() {
        let entry = "pimalaya/posteo";
        assert_eq!(
            KeyringProvider::Pass.read_command(None, entry),
            ["pass", "show", "pimalaya/posteo"],
        );
        assert_eq!(
            KeyringProvider::SecretTool.read_command(None, entry),
            ["secret-tool", "lookup", "account", "pimalaya/posteo"],
        );
        assert_eq!(
            KeyringProvider::Security.read_command(None, entry),
            [
                "security",
                "find-generic-password",
                "-a",
                "pimalaya/posteo",
                "-w"
            ],
        );
        assert_eq!(
            KeyringProvider::KwalletQuery.read_command(None, entry),
            ["kwallet-query", "-r", "pimalaya/posteo", "kdewallet"],
        );
    }

    #[test]
    fn keyring_read_command_namespaces_the_entry_when_a_service_is_given() {
        let (service, account) = (Some("ortie"), "acme");
        assert_eq!(
            KeyringProvider::Pass.read_command(service, account),
            ["pass", "show", "ortie/acme"],
        );
        assert_eq!(
            KeyringProvider::SecretTool.read_command(service, account),
            [
                "secret-tool",
                "lookup",
                "service",
                "ortie",
                "account",
                "acme"
            ],
        );
        assert_eq!(
            KeyringProvider::Security.read_command(service, account),
            [
                "security",
                "find-generic-password",
                "-s",
                "ortie",
                "-a",
                "acme",
                "-w"
            ],
        );
    }

    #[test]
    fn keyring_write_command_names_a_security_service_without_a_namespace() {
        assert_eq!(
            KeyringProvider::Security.write_command(None, "acme"),
            "security add-generic-password -U -s acme -a acme -w \"$(cat)\"",
        );
        assert_eq!(
            KeyringProvider::Security.write_command(Some("ortie"), "acme"),
            "security add-generic-password -U -s ortie -a acme -w \"$(cat)\"",
        );
    }

    #[test]
    fn secret_tool_lookup_reads_the_named_attribute() {
        assert_eq!(
            secret_tool_lookup("Title", "disroot"),
            ["secret-tool", "lookup", "Title", "disroot"],
        );
        assert_eq!(
            KeyringProvider::SecretTool.read_command(None, "disroot"),
            secret_tool_lookup("account", "disroot"),
        );
    }

    #[test]
    fn broker_read_command_targets_the_account_per_broker() {
        assert_eq!(
            TokenBroker::Ortie.read_command("acme"),
            ["ortie", "token", "show", "-a", "acme"],
        );
        assert_eq!(
            TokenBroker::Pizauth.read_command("acme"),
            ["pizauth", "show", "acme"]
        );
        assert_eq!(
            TokenBroker::Oama.read_command("me@acme.test"),
            ["oama", "access", "me@acme.test"],
        );
    }

    #[test]
    fn available_lists_are_non_empty() {
        assert!(!TokenBroker::available().is_empty());
        if cfg!(unix) {
            assert!(!KeyringProvider::available().is_empty());
        }
    }

    /// Whatever this machine has installed, the two groups never
    /// interleave: once the list reaches an entry that is not there,
    /// nothing installed follows.
    #[test]
    fn available_lists_the_installed_entries_first() {
        let providers = KeyringProvider::available();
        if let Some(missing) = providers.iter().position(|p| !p.installed()) {
            assert!(providers[missing..].iter().all(|p| !p.installed()));
        }

        let brokers = TokenBroker::available();
        if let Some(missing) = brokers.iter().position(|b| !b.installed()) {
            assert!(brokers[missing..].iter().all(|b| !b.installed()));
        }
    }

    #[test]
    fn a_program_is_looked_up_in_every_path_entry() {
        let dir = env::temp_dir().join("pimalaya-cli-keyring-path");
        fs::create_dir_all(&dir).expect("create the PATH directory");
        let program = "pimalaya-cli-test-provider";
        fs::write(dir.join(program), "").expect("write the program");

        let paths =
            env::join_paths([PathBuf::from("/nonexistent"), dir.clone()]).expect("join the paths");

        assert!(found_in(&paths, program));
        assert!(!found_in(&paths, "pimalaya-cli-test-missing"));

        // A `PATH` that does not hold the directory does not find it,
        // which is what the labels report.
        let elsewhere = env::join_paths([PathBuf::from("/nonexistent")]).expect("join the paths");
        assert!(!found_in(&elsewhere, program));

        fs::remove_file(dir.join(program)).expect("remove the program");
    }

    #[test]
    fn an_entry_that_is_not_there_says_so() {
        assert_eq!(
            label("pass (password store)", true),
            "pass (password store)"
        );
        assert_eq!(
            label("pass (password store)", false),
            "pass (password store), not found on PATH",
        );
    }

    #[test]
    fn an_empty_command_is_not_installed() {
        assert!(!installed(&[]));
    }

    #[test]
    fn a_store_command_writes_the_entry_its_read_command_reads() {
        let key = "acme-imap";

        assert_eq!(
            KeyringProvider::SecretTool.store_command(key),
            [
                "secret-tool",
                "store",
                "--label",
                "acme-imap",
                "account",
                "acme-imap"
            ],
        );
        assert_eq!(
            KeyringProvider::KwalletQuery.store_command(key),
            ["kwallet-query", "-w", "acme-imap", "kdewallet"],
        );
        assert_eq!(
            KeyringProvider::Pass.store_command(key),
            ["pass", "insert", "-m", "-f", "acme-imap"],
        );

        // The keychain takes its command line, secret included, on stdin.
        assert_eq!(
            KeyringProvider::Security.store_command(key),
            ["security", "-i"]
        );
    }

    #[test]
    fn a_keychain_line_quotes_and_escapes_its_values() {
        let line = security_line("acme \"imap\"", &SecretString::from(r#"a"b\c d"#))
            .expect("build the line");

        assert_eq!(
            line.expose_secret(),
            "add-generic-password -U -s \"acme \\\"imap\\\"\" -a \"acme \\\"imap\\\"\" \
             -w \"a\\\"b\\\\c d\"\n",
        );
    }

    #[test]
    fn a_keychain_line_refuses_a_line_break() {
        let secret = SecretString::from("a\nadd-generic-password");
        let err = security_line("acme", &secret).expect_err("refuse the secret");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);

        let secret = SecretString::from("abc");
        let err = security_line("acme\r", &secret).expect_err("refuse the key");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn an_endpoint_is_on_its_domain_and_subdomains_only() {
        let domain = "example.org";

        assert!(!off_domain("imaps://imap.example.org:993", domain));
        assert!(!off_domain("https://example.org/jmap", domain));
        assert!(!off_domain("imaps://IMAP.Example.ORG:993", domain));
        assert!(!off_domain("smtp://mail.example.org.:587", "Example.org"));
        assert!(!off_domain("imap.example.org:143", domain));

        assert!(off_domain("imaps://imap.example.net:993", domain));
        assert!(off_domain("https://example.org.example.net/", domain));
        assert!(off_domain("https://notexample.org", domain));
        assert!(off_domain(
            "imaps://imap.example.org@example.net:993",
            domain
        ));
        assert!(off_domain("https://[2001:db8::1]:443/example.org", domain));
        assert!(off_domain("https://example.net?example.org", domain));
    }

    #[test]
    fn a_label_reads_as_a_noun_its_initialisms_kept() {
        assert_eq!(noun("Password"), "password");
        assert_eq!(noun("SMTP password"), "SMTP password");
        assert_eq!(noun("API token"), "API token");
        assert_eq!(noun("P"), "P");
    }
}