trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
//! Tests for `tm secrets` against an in-process trusty-secrets server (#7521).
//!
//! No test touches the OS Keychain, the real clipboard, or `~/.trusty-tools`:
//! the server serves a socket in a `TempDir` over two `MemoryBackend`s,
//! `keychain` and `spare` (the `copy` destination), its index and machine
//! config sit in the same `TempDir`, the machine config selects `keychain`
//! on every OS, every value source is a fixed string, and the client's spawn
//! program is a path that does not exist, so no real `trusty-secrets` runs.
//! Every run captures stdout, the error's `Display` and `Debug`, and TRACE
//! tracing, and [`Outcome::assert_no_value`] checks all four.

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use clap::Parser;
use tempfile::TempDir;
use tokio::sync::oneshot;
use trusty_secrets::server::{BackendFactory, OnDemandSecrets, ServerSettings, serve};
use trusty_secrets::store::{MemoryBackend, SecretBackend};
use trusty_secrets::{BackendId, SecretKey, SecretsError, VaultName};

use super::*;
use crate::cli::{Cli, Command};

/// A value longer than 8 characters: only [`HEAD`] may ever be printed.
const VALUE: &str = "sk-live-TAIL-7521-c0ffee";
/// The first 8 characters of [`VALUE`].
const HEAD: &str = "sk-live-";
/// Everything after [`HEAD`]; no output may carry it.
const TAIL: &str = "TAIL-7521-c0ffee";
/// A value of exactly 8 characters: no character of it may be printed.
const SHORT: &str = "Q7xZ-9wK";
/// The project vault of the fixture's `git@github.com:Acme/Web.git`.
const PROJECT_VAULT: &str = "trusty/acme/web";
/// The owner vault of the same remote.
const OWNER_VAULT: &str = "trusty/acme";
/// The harness machine config: selects the memory `keychain` on every OS.
const PINNED_MACHINE_CONFIG: &str = "secrets:\n  default_backend: keychain\n";

/// A value source that returns one fixed text.
struct Fixed(&'static str);

impl ValueSource for Fixed {
    fn read(&self) -> anyhow::Result<String> {
        Ok(self.0.to_owned())
    }
}

/// A served socket over two memory backends, in a temp dir.
struct Harness {
    tmp: TempDir,
    repo: PathBuf,
    keychain: Arc<MemoryBackend>,
    /// #7521: the second backend, `spare`, for `copy`.
    spare: Arc<MemoryBackend>,
    client: OnDemandSecrets,
    _shutdown: oneshot::Sender<()>,
}

fn git(dir: &Path, args: &[&str]) {
    let status = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .status()
        .expect("git runs");
    assert!(status.success(), "git {args:?} failed");
}

/// A client whose spawn fallback can never start a real server.
fn client_at(tmp: &Path, socket: &Path) -> OnDemandSecrets {
    OnDemandSecrets::at(socket).with_program(tmp.join("no-such-trusty-secrets"))
}

/// A `keychain` double whose `set` sleeps before storing.
///
/// Why: #7524 P2-M1 — stands in for a vendor CLI write that outlasts the
/// client's old 30 s wait; this crate builds trusty-secrets without
/// `cli-backends`, so it has no `op` backend to slow down.
#[derive(Debug)]
struct SlowSet {
    inner: Arc<MemoryBackend>,
    delay: Duration,
}

impl SecretBackend for SlowSet {
    fn id(&self) -> BackendId {
        self.inner.id()
    }
    fn capabilities(&self) -> trusty_secrets::store::Capabilities {
        self.inner.capabilities()
    }
    fn get(
        &self,
        vault: &VaultName,
        key: &SecretKey,
    ) -> Result<Option<trusty_secrets::SecretValue>, SecretsError> {
        self.inner.get(vault, key)
    }
    fn set(
        &self,
        vault: &VaultName,
        key: &SecretKey,
        value: &trusty_secrets::SecretValue,
    ) -> Result<(), SecretsError> {
        std::thread::sleep(self.delay);
        self.inner.set(vault, key, value)
    }
    fn delete(&self, vault: &VaultName, key: &SecretKey) -> Result<bool, SecretsError> {
        self.inner.delete(vault, key)
    }
}

async fn harness() -> Harness {
    harness_slowed(Duration::ZERO).await
}

/// [`harness`], with every `keychain` write taking `set_delay` first.
async fn harness_slowed(set_delay: Duration) -> Harness {
    let tmp = TempDir::new().expect("tempdir");
    let repo = tmp.path().join("repo");
    std::fs::create_dir(&repo).expect("mkdir repo");
    git(&repo, &["init", "-q"]);
    git(
        &repo,
        &["remote", "add", "origin", "git@github.com:Acme/Web.git"],
    );
    let settings = ServerSettings::new(
        tmp.path().join("run").join("s.sock"),
        tmp.path().join("index"),
        tmp.path().join("machine.yaml"),
        Duration::from_secs(60),
    );
    // #7521: with no machine config the server picks the build's default
    // backend — `keychain` on macOS, `file` elsewhere (#9326) — and this
    // factory serves no `file`. Pin `keychain`, the memory backend, so every
    // OS selects it.
    std::fs::write(&settings.machine_config, PINNED_MACHINE_CONFIG).expect("write machine.yaml");
    let pinned = trusty_secrets::store::config::load_machine_at(&settings.machine_config)
        .expect("load machine.yaml")
        .and_then(|m| m.default_backend);
    assert_eq!(
        pinned,
        Some(BackendId::keychain()),
        "the harness must pin the memory `keychain` backend on every OS"
    );
    let keychain = Arc::new(MemoryBackend::new());
    let spare = Arc::new(MemoryBackend::new());
    let (kc, sp) = (Arc::clone(&keychain), Arc::clone(&spare));
    let backends: BackendFactory = Arc::new(move |id: &BackendId| {
        let backend: Arc<dyn SecretBackend> = match id.as_str() {
            BackendId::KEYCHAIN if !set_delay.is_zero() => Arc::new(SlowSet {
                inner: Arc::clone(&kc),
                delay: set_delay,
            }),
            BackendId::KEYCHAIN => Arc::clone(&kc) as Arc<dyn SecretBackend>,
            "spare" => Arc::clone(&sp) as Arc<dyn SecretBackend>,
            _ => {
                return Err(SecretsError::UnknownBackend {
                    backend: id.to_string(),
                });
            }
        };
        Ok(backend)
    });
    let (tx, rx) = oneshot::channel::<()>();
    let socket = settings.socket.clone();
    tokio::spawn(serve(settings, backends, async move {
        let _ = rx.await;
    }));
    let started = Instant::now();
    while !trusty_common::uds::socket_is_serving(&socket, Duration::from_millis(200)).await {
        assert!(
            started.elapsed() < Duration::from_secs(20),
            "socket never served"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    let client = client_at(tmp.path(), &socket);
    Harness {
        tmp,
        repo,
        keychain,
        spare,
        client,
        _shutdown: tx,
    }
}

/// Collects every tracing line written while a verb runs.
#[derive(Clone, Default)]
struct LogSink(Arc<Mutex<Vec<u8>>>);

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

/// What one verb produced: stdout, the error (`{:#}` and `{:?}`), and logs.
struct Outcome {
    out: String,
    err: Option<String>,
    logs: String,
}

impl Outcome {
    /// No text carries [`TAIL`] or any of [`SHORT`].
    fn assert_no_value(&self) {
        let err = self.err.as_deref().unwrap_or("");
        for (what, text) in [("stdout", &*self.out), ("error", err), ("logs", &self.logs)] {
            assert!(!text.contains(TAIL), "{what} carries the value: {text}");
            assert!(
                !text.contains(&SHORT[..4]),
                "{what} carries the short value: {text}"
            );
        }
    }

    fn err(&self) -> &str {
        self.err.as_deref().expect("the verb failed")
    }
}

/// Parse `tm secrets <args>` and run it in `project` against `client`.
async fn run_in(
    client: &OnDemandSecrets,
    project: &Path,
    clipboard: &'static str,
    stdin: &'static str,
    args: &[&str],
) -> Outcome {
    run_ci(client, project, clipboard, stdin, false, args).await
}

/// [`run_in`], as a CI run (`CI=true`) when `ci` is set.
async fn run_ci(
    client: &OnDemandSecrets,
    project: &Path,
    clipboard: &'static str,
    stdin: &'static str,
    ci: bool,
    args: &[&str],
) -> Outcome {
    let argv = ["tm", "secrets"].into_iter().chain(args.iter().copied());
    let Some(Command::Secrets { action }) = Cli::try_parse_from(argv).expect("parse").command
    else {
        panic!("not a secrets command");
    };
    let sink = LogSink::default();
    let writer = sink.clone();
    let subscriber = tracing_subscriber::fmt()
        .with_max_level(tracing::Level::TRACE)
        .with_ansi(false)
        .with_writer(move || writer.clone())
        .finish();
    let _guard = tracing::subscriber::set_default(subscriber);
    let ctx = Ctx {
        client,
        project,
        clipboard: &Fixed(clipboard),
        stdin: &Fixed(stdin),
        ci,
    };
    let mut out = Vec::new();
    let result = dispatch(&ctx, action, &mut out).await;
    out.flush().expect("flush");
    let logs = String::from_utf8_lossy(&sink.0.lock().expect("log sink")).into_owned();
    let outcome = Outcome {
        out: String::from_utf8(out).expect("utf-8 stdout"),
        err: result.err().map(|e| format!("{e:#}\n{e:?}")),
        logs,
    };
    outcome.assert_no_value();
    outcome
}

async fn run(h: &Harness, clipboard: &'static str, args: &[&str]) -> Outcome {
    run_in(&h.client, &h.repo, clipboard, "", args).await
}

/// Write `key` to the owner scope over the socket; the CLI never does.
async fn seed_owner(h: &Harness, key: &str, value: &str) {
    let ctx = Ctx {
        client: &h.client,
        project: &h.repo,
        clipboard: &Fixed(""),
        stdin: &Fixed(""),
        ci: false,
    };
    let params = serde_json::json!({ "vault": OWNER_VAULT, "key": key, "value": value });
    let _: serde_json::Value = ctx
        .call(trusty_secrets::api::methods::method::SET, params)
        .await
        .expect("owner-scope set");
}

/// Write `text` to `name` in the harness dir; the path as UTF-8.
fn env_file(h: &Harness, name: &str, text: &str) -> String {
    let path = h.tmp.path().join(name);
    std::fs::write(&path, text).expect("write env file");
    path.to_str().expect("utf-8 path").to_owned()
}

fn stored(backend: &MemoryBackend, vault: &str, key: &str) -> Option<String> {
    let vault = VaultName::new(vault).expect("vault");
    let key = SecretKey::new(key).expect("key");
    backend
        .get(&vault, &key)
        .expect("memory get")
        .map(|v| v.expose().to_owned())
}

#[test]
fn cli_parses_every_secrets_verb() {
    for args in [
        vec!["set", "K"],
        vec!["set", "K", "grp", "--value", "-"],
        vec!["list"],
        vec!["remove", "K"],
        vec!["remove", "K", "grp"],
        vec!["import", ".env"],
        vec!["import", ".env", "grp"],
        vec!["copy", "--from", "keychain", "--to", "spare"],
        vec!["copy", "--from", "keychain", "--to", "spare", "A", "grp.B"],
        vec!["doctor"],
    ] {
        let argv = ["tm", "secrets"].into_iter().chain(args.iter().copied());
        let cli = Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{args:?}: {e}"));
        assert!(
            matches!(cli.command, Some(Command::Secrets { .. })),
            "{args:?}"
        );
    }
    // `set` needs a key.
    assert!(Cli::try_parse_from(["tm", "secrets", "set"]).is_err());
    // #7521: the owner scope is the console's (DOC-74 §15.3).
    for args in [
        vec!["set", "K", "--owner"],
        vec!["remove", "K", "--owner"],
        vec!["import", ".env", "--owner"],
        // `copy` needs both backends.
        vec!["copy", "--from", "keychain"],
        vec!["remove"],
        vec!["import"],
    ] {
        let argv = ["tm", "secrets"].into_iter().chain(args.iter().copied());
        assert!(Cli::try_parse_from(argv).is_err(), "{args:?} parsed");
    }
}

#[test]
fn parsed_set_arguments_never_show_in_debug() {
    let key = format!("API_KEY:{VALUE}");
    let argv = ["tm", "secrets", "set", &key, VALUE, "--value", VALUE, VALUE];
    let cli = Cli::try_parse_from(argv).expect("parse");
    let debug = format!("{cli:?}");
    assert!(debug.contains("Secrets"), "{debug}");
    assert!(!debug.contains(TAIL), "Debug shows the value: {debug}");
}

#[tokio::test]
async fn set_reads_the_clipboard_and_confirms_head_and_length_only() {
    let h = harness().await;
    let first = run(&h, " sk-live-TAIL-7521-c0ffee\n", &["set", "API_KEY"]).await;
    assert_eq!(first.err, None);
    assert_eq!(
        first.out,
        format!("(new) secret set API_KEY: {HEAD}… [24 chars]\n")
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "API_KEY").as_deref(),
        Some(VALUE)
    );

    let second = run(&h, "sk-live-TAIL-7521-c0ffee-v2", &["set", "API_KEY"]).await;
    assert_eq!(
        second.out,
        format!("(updated) secret set API_KEY: {HEAD}… [27 chars]\n")
    );
}

/// Why: #7524 P2-M1 — `tm secrets set` waited 30 s, so a backend write
/// that took longer was reported as "did not cross the socket" and then
/// committed. A write taking 31 s now reports its real outcome. Red while
/// the trusty-secrets client waited 30 s.
/// Test: itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn set_slower_than_the_old_client_wait_reports_the_real_outcome() {
    let h = harness_slowed(Duration::from_secs(31)).await;
    let started = Instant::now();
    let outcome = run(&h, VALUE, &["set", "API_KEY"]).await;
    assert_eq!(outcome.err, None, "tm gave up before the server answered");
    assert!(started.elapsed() >= Duration::from_secs(31));
    assert_eq!(
        outcome.out,
        format!("(new) secret set API_KEY: {HEAD}… [24 chars]\n")
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "API_KEY").as_deref(),
        Some(VALUE)
    );
}

#[tokio::test]
async fn set_with_a_short_value_shows_only_its_length() {
    let h = harness().await;
    let outcome = run(&h, SHORT, &["set", "PIN"]).await;
    assert_eq!(outcome.out, "(new) secret set PIN: [8 chars]\n");
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "PIN").as_deref(),
        Some(SHORT)
    );
}

#[tokio::test]
async fn set_with_an_empty_clipboard_is_an_error_and_stores_nothing() {
    let h = harness().await;
    let outcome = run(&h, " \n\t", &["set", "API_KEY"]).await;
    assert!(
        outcome.err().contains("the clipboard is empty"),
        "{}",
        outcome.err()
    );
    assert_eq!(outcome.out, "");
    let piped = run(&h, VALUE, &["set", "API_KEY", "--value", "-"]).await;
    assert!(piped.err().contains("stdin is empty"), "{}", piped.err());
    assert!(h.keychain.is_empty());
}

#[tokio::test]
async fn set_refuses_a_value_on_the_command_line_without_echoing_it() {
    let h = harness().await;
    let in_key = format!("API_KEY:{VALUE}");
    for args in [
        vec!["set", "API_KEY", "grp", VALUE],
        vec!["set", "API_KEY", "--value", VALUE],
        vec!["set", in_key.as_str()],
        vec!["set", "API_KEY", VALUE],
    ] {
        let outcome = run(&h, VALUE, &args).await;
        assert!(outcome.err.is_some(), "{args:?} was accepted");
        assert_eq!(outcome.out, "", "{args:?}");
    }
    assert!(h.keychain.is_empty());
}

#[tokio::test]
async fn set_with_a_group_namespaces_the_key() {
    let h = harness().await;
    let outcome = run_in(
        &h.client,
        &h.repo,
        "",
        VALUE,
        &["set", "API_KEY", "stripe", "--value", "-"],
    )
    .await;
    assert_eq!(
        outcome.out,
        format!("(new) secret set stripe.API_KEY: {HEAD}… [24 chars]\n")
    );
    let again = run(&h, VALUE, &["set", "API_KEY", "stripe"]).await;
    assert!(
        again
            .out
            .starts_with("(updated) secret set stripe.API_KEY: "),
        "{}",
        again.out
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "stripe.API_KEY").as_deref(),
        Some(VALUE)
    );
    assert_eq!(stored(&h.keychain, PROJECT_VAULT, "API_KEY"), None);
    let dotted = run(&h, VALUE, &["set", "API_KEY", "a.b"]).await;
    assert!(
        dotted.err().contains("a group is 1 to 16"),
        "{}",
        dotted.err()
    );
}

#[tokio::test]
async fn list_prints_key_names_only() {
    let h = harness().await;
    run(&h, VALUE, &["set", "A_KEY"]).await;
    seed_owner(&h, "B_KEY", SHORT).await;
    let outcome = run(&h, "", &["list"]).await;
    assert_eq!(
        outcome.out,
        "trusty/acme/web (Project):\n  A_KEY\ntrusty/acme (Owner):\n  B_KEY\n"
    );
    assert!(!outcome.out.contains(HEAD) && !outcome.out.contains("chars"));
}

/// #7521: `remove` deletes from the project scope only, and a key it does
/// not hold exits 1 naming the key.
#[tokio::test]
async fn remove_deletes_a_project_key_and_fails_by_name_on_a_missing_one() {
    let h = harness().await;
    run(&h, VALUE, &["set", "API_KEY", "grp"]).await;
    seed_owner(&h, "B_KEY", SHORT).await;
    let removed = run(&h, "", &["remove", "API_KEY", "grp"]).await;
    assert_eq!(removed.err, None);
    assert_eq!(removed.out, "removed grp.API_KEY from trusty/acme/web\n");
    assert_eq!(stored(&h.keychain, PROJECT_VAULT, "grp.API_KEY"), None);

    let missing = run(&h, "", &["remove", "API_KEY", "grp"]).await;
    assert!(
        missing
            .err()
            .contains("grp.API_KEY is not in trusty/acme/web"),
        "{}",
        missing.err()
    );
    assert_eq!(missing.out, "");
    // An owner-scope key is out of reach: missing from the project scope.
    let owner = run(&h, "", &["remove", "B_KEY"]).await;
    assert!(
        owner.err().contains("B_KEY is not in trusty/acme/web"),
        "{}",
        owner.err()
    );
    assert_eq!(
        stored(&h.keychain, OWNER_VAULT, "B_KEY").as_deref(),
        Some(SHORT)
    );
}

/// #7521: `import` stores each entry in the project scope, names skipped
/// references, and prints no value and no mask.
#[tokio::test]
async fn import_loads_a_dotenv_file_and_prints_names_only() {
    let h = harness().await;
    let text = format!("# keys\nAPI_KEY={VALUE}\nexport PIN='{SHORT}'\nREF=secret://OTHER\n");
    let path = env_file(&h, "app.env", &text);
    let outcome = run(&h, "", &["import", &path]).await;
    assert_eq!(outcome.err, None);
    assert_eq!(
        outcome.out,
        "imported API_KEY (new)\nimported PIN (new)\nskipped REF (a secret:// reference)\n\
         trusty/acme/web: 2 imported, 1 skipped, 0 failed\n"
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "API_KEY").as_deref(),
        Some(VALUE)
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "PIN").as_deref(),
        Some(SHORT)
    );
    assert_eq!(stored(&h.keychain, PROJECT_VAULT, "REF"), None);
    assert_eq!(h.keychain.len(), 2, "nothing outside the project scope");
    assert!(std::path::Path::new(&path).exists(), "the file stays");

    let grouped = run(&h, "", &["import", &path, "app"]).await;
    assert!(
        grouped.out.starts_with("imported app.API_KEY (new)\n"),
        "{}",
        grouped.out
    );
    let again = run(&h, "", &["import", &path]).await;
    assert!(
        again.out.starts_with("imported API_KEY (updated)\n"),
        "{}",
        again.out
    );
}

/// #7521: a refused key fails the run by name; the other keys still land.
#[tokio::test]
async fn import_fails_by_name_on_a_refused_key_and_imports_the_rest() {
    let h = harness().await;
    let path = env_file(&h, "app.env", &format!("EMPTY=\nAPI_KEY={VALUE}\n"));
    let outcome = run(&h, "", &["import", &path]).await;
    assert!(
        outcome.out.starts_with("failed EMPTY: tm secrets: "),
        "{}",
        outcome.out
    );
    assert!(
        outcome.out.ends_with(
            "imported API_KEY (new)\ntrusty/acme/web: 1 imported, 0 skipped, 1 failed\n"
        ),
        "{}",
        outcome.out
    );
    assert!(
        outcome.err().contains("1 key(s) failed: EMPTY"),
        "{}",
        outcome.err()
    );
    assert_eq!(
        stored(&h.keychain, PROJECT_VAULT, "API_KEY").as_deref(),
        Some(VALUE)
    );
}

/// #7521: a syntax error names the line number, never the line, and stores
/// nothing — not even the lines before it.
#[tokio::test]
async fn import_syntax_error_names_the_line_not_its_text() {
    let h = harness().await;
    let path = env_file(
        &h,
        "bad.env",
        &format!("GOOD={SHORT}\nLEAKY_NAME={VALUE}'x\n"),
    );
    let outcome = run(&h, "", &["import", &path]).await;
    let err = outcome.err();
    assert!(err.contains(".env line 2: "), "{err}");
    assert!(
        !err.contains("LEAKY_NAME"),
        "the error quotes the line: {err}"
    );
    assert!(!err.contains(HEAD), "the error quotes the line: {err}");
    assert_eq!(outcome.out, "");
    assert!(
        h.keychain.is_empty(),
        "a file that does not parse stores nothing"
    );

    let absent = h.tmp.path().join("absent.env");
    let absent = run(&h, "", &["import", absent.to_str().expect("utf-8")]).await;
    assert!(absent.err().contains("cannot read"), "{}", absent.err());
}

/// #7521: a bad group is refused before the file is read or a key is sent.
#[tokio::test]
async fn import_with_an_invalid_group_stores_nothing() {
    let h = harness().await;
    let path = env_file(&h, "app.env", &format!("API_KEY={VALUE}\n"));
    let outcome = run(&h, "", &["import", &path, "a.b"]).await;
    assert!(
        outcome.err().contains("a group is 1 to 16"),
        "{}",
        outcome.err()
    );
    assert_eq!(outcome.out, "");
    assert!(h.keychain.is_empty());
}

/// #7521: `copy` moves the named keys, or every project key, to the other
/// backend; the owner scope is not copied and no value is printed.
#[tokio::test]
async fn copy_moves_project_keys_between_backends_without_printing_them() {
    let h = harness().await;
    run(&h, VALUE, &["set", "API_KEY"]).await;
    run(&h, SHORT, &["set", "PIN"]).await;
    seed_owner(&h, "B_KEY", SHORT).await;

    let named = run(
        &h,
        "",
        &["copy", "--from", "keychain", "--to", "spare", "API_KEY"],
    )
    .await;
    assert_eq!(named.err, None);
    assert_eq!(
        named.out,
        "copied API_KEY\nkeychain -> spare: 1 copied, 0 not copied\n"
    );
    assert_eq!(stored(&h.spare, PROJECT_VAULT, "PIN"), None);

    let all = run(&h, "", &["copy", "--from", "keychain", "--to", "spare"]).await;
    assert_eq!(all.err, None);
    assert!(all.out.contains("copied API_KEY\n"), "{}", all.out);
    assert!(all.out.contains("copied PIN\n"), "{}", all.out);
    assert!(
        all.out
            .ends_with("keychain -> spare: 2 copied, 0 not copied\n"),
        "{}",
        all.out
    );
    assert_eq!(
        stored(&h.spare, PROJECT_VAULT, "API_KEY").as_deref(),
        Some(VALUE)
    );
    assert_eq!(
        stored(&h.spare, PROJECT_VAULT, "PIN").as_deref(),
        Some(SHORT)
    );
    assert_eq!(stored(&h.spare, OWNER_VAULT, "B_KEY"), None);
}

/// #7521: a key the source lacks is named and exits 1; a same-backend or
/// unknown-backend copy is refused.
#[tokio::test]
async fn copy_fails_by_name_on_a_missing_key() {
    let h = harness().await;
    run(&h, VALUE, &["set", "API_KEY"]).await;
    let args = [
        "copy", "--from", "keychain", "--to", "spare", "API_KEY", "NOPE",
    ];
    let outcome = run(&h, "", &args).await;
    assert_eq!(
        outcome.out,
        "copied API_KEY\nnot copied NOPE\nkeychain -> spare: 1 copied, 1 not copied\n"
    );
    assert!(
        outcome
            .err()
            .contains("1 key(s) not copied (absent from keychain, or refused by spare): NOPE"),
        "{}",
        outcome.err()
    );
    assert_eq!(stored(&h.spare, PROJECT_VAULT, "NOPE"), None);

    let same = run(&h, "", &["copy", "--from", "spare", "--to", "spare"]).await;
    assert!(same.err().contains("are the same"), "{}", same.err());
    let unknown = run(&h, "", &["copy", "--from", "keychain", "--to", "vault"]).await;
    assert!(
        unknown.err().contains("not available in this build"),
        "{}",
        unknown.err()
    );
}

#[tokio::test]
async fn doctor_reports_socket_and_backends_without_values() {
    let h = harness().await;
    run(&h, VALUE, &["set", "API_KEY"]).await;
    let outcome = run(&h, "", &["doctor"]).await;
    assert_eq!(outcome.err, None);
    let socket = h.client.socket().display().to_string();
    assert!(
        outcome.out.contains(&format!("socket {socket}: reachable")),
        "{}",
        outcome.out
    );
    assert!(
        outcome.out.contains("selected backend: keychain"),
        "{}",
        outcome.out
    );
    assert!(
        outcome
            .out
            .contains("backend keychain: available [READ, WRITE"),
        "{}",
        outcome.out
    );
    assert!(!outcome.out.contains(HEAD));

    // Outside a checkout: the project is reported, the socket still answers,
    // and the machine default's report exits non-zero (#7519 d4 Q4).
    let outside = h.tmp.path().join("plain");
    std::fs::create_dir(&outside).expect("mkdir");
    let bare = run_in(&h.client, &outside, "", "", &["doctor"]).await;
    assert!(bare.err().contains(PROJECT_NOT_JUDGED), "{}", bare.err());
    assert!(
        bare.out
            .starts_with("project: tm secrets: secrets.doctor: "),
        "{}",
        bare.out
    );
    assert!(bare.out.contains(": reachable"), "{}", bare.out);
}

/// The error a doctor run ends with when the server refused the project.
const PROJECT_NOT_JUDGED: &str = "the project was refused, so the report above is the machine \
     default's";

/// #7521: a remote off github.com is a project refusal like any other
/// (#9328's `remote_host_unsupported`), so doctor still reports the backends.
/// #7519 d4 Q4 (owner ruling): it keeps the `project:` line and the
/// machine default's report, and exits non-zero. Red while it exited 0.
#[tokio::test]
async fn doctor_reports_backends_when_the_remote_is_off_github() {
    let h = harness().await;
    let gitlab = h.tmp.path().join("gitlab");
    std::fs::create_dir(&gitlab).expect("mkdir gitlab");
    git(&gitlab, &["init", "-q"]);
    git(
        &gitlab,
        &["remote", "add", "origin", "https://gitlab.com/acme/app.git"],
    );
    let outcome = run_in(&h.client, &gitlab, "", "", &["doctor"]).await;
    assert!(
        outcome.err().contains(PROJECT_NOT_JUDGED),
        "{}",
        outcome.err()
    );
    assert!(
        outcome
            .out
            .starts_with("project: tm secrets: secrets.doctor: "),
        "{}",
        outcome.out
    );
    assert!(outcome.out.contains("github.com"), "{}", outcome.out);
    let socket = h.client.socket().display().to_string();
    assert!(
        outcome.out.contains(&format!("socket {socket}: reachable")),
        "{}",
        outcome.out
    );
    assert!(
        outcome
            .out
            .contains("backend keychain: available [READ, WRITE"),
        "{}",
        outcome.out
    );
    outcome.assert_no_value();
}

/// #7521: a server that refuses `secrets.doctor` answered, so the socket is
/// reachable; the refusal is the error.
#[tokio::test]
async fn doctor_reports_a_refusing_server_as_reachable() {
    let h = harness().await;
    std::fs::write(
        h.tmp.path().join("machine.yaml"),
        "secrets:\n  default_backend:\n    - not-a-backend-id\n",
    )
    .expect("write machine.yaml");
    let outcome = run(&h, "", &["doctor"]).await;
    let socket = h.client.socket().display().to_string();
    assert_eq!(outcome.out, format!("socket {socket}: reachable\n"));
    assert!(
        outcome.err().contains("config section is invalid"),
        "{}",
        outcome.err()
    );
}

/// #7521: a configured backend this build cannot open fails doctor after
/// the table.
#[tokio::test]
async fn doctor_fails_when_the_selected_backend_is_unavailable() {
    let h = harness().await;
    std::fs::write(
        h.tmp.path().join("machine.yaml"),
        "secrets:\n  default_backend: onepassword\n",
    )
    .expect("write machine.yaml");
    let outcome = run(&h, "", &["doctor"]).await;
    assert!(
        outcome.out.contains("selected backend: onepassword\n"),
        "{}",
        outcome.out
    );
    assert!(
        outcome.out.contains("backend keychain: available ["),
        "{}",
        outcome.out
    );
    // #7519 P4: the row names why; this build links no CLI backend.
    assert!(
        outcome
            .out
            .contains("backend onepassword: unavailable (not_compiled): "),
        "{}",
        outcome.out
    );
    assert!(
        outcome
            .err()
            .contains("the selected backend `onepassword` is unavailable"),
        "{}",
        outcome.err()
    );
}

/// #7519 P4: the table names each unavailable row's reason and fix, the
/// selected backend's posture, and 1Password headless readiness; an
/// available 1Password row with no token never reads as plain "available".
#[tokio::test]
async fn doctor_renders_reasons_posture_and_headless_readiness() {
    let h = harness().await;
    let outcome = run(&h, "", &["doctor"]).await;
    assert_eq!(outcome.err, None, "{}", outcome.out);
    for line in [
        "posture: keychain\n",
        "backend file: unavailable (not_compiled): ",
        "backend keeper: unavailable (not_compiled): ",
        "headless: 1Password service-account token at server start: no\n",
    ] {
        assert!(outcome.out.contains(line), "{line:?} in\n{}", outcome.out);
    }

    let report = |token: bool| -> trusty_secrets::server::DoctorResponse {
        serde_json::from_value(serde_json::json!({
            "socket": "/s", "index_root": "/i", "machine_config": "/m",
            "account_config": "/home/u/.trusty-tools/trusty-common/config.yaml",
            "project_root": null, "project_config": null,
            "selected_backend": "onepassword", "posture": "other",
            "backends": [
                {"id": "file", "available": true, "capabilities": ["READ"]},
                {"id": "onepassword", "available": true, "capabilities": ["READ", "WRITE"]},
                {"id": "keeper", "available": false, "capabilities": [],
                 "reason": "cli_not_installed", "detail": "`keeper` is not installed"},
            ],
            "headless": {"onepassword_token": token},
            "tools": [
                {"id": "bitwarden", "program": "bw", "installed": true, "path": "/usr/bin/bw"},
                {"id": "vault", "program": "vault", "installed": false},
            ],
        }))
        .expect("decode")
    };
    let mut out = Vec::new();
    doctor::render(&report(false), &mut out).expect("render");
    let text = String::from_utf8(out).expect("utf-8");
    assert!(text.contains("account machine config: /home/u/"), "{text}");
    assert!(
        text.contains("backend onepassword: available [READ, WRITE]; no service-account token"),
        "{text}"
    );
    assert!(
        text.contains("backend keeper: unavailable (cli_not_installed): `keeper` is not installed"),
        "{text}"
    );
    let mut out = Vec::new();
    doctor::render(&report(true), &mut out).expect("render");
    let text = String::from_utf8(out).expect("utf-8");
    assert!(
        text.contains("backend onepassword: available [READ, WRITE]\n"),
        "{text}"
    );
    assert!(text.contains("token at server start: yes\n"), "{text}");
    // #7519 P4: DOC-74 §7's tools, installed or not.
    assert!(
        text.ends_with(
            "tool bitwarden (bw): installed at /usr/bin/bw; no trusty-secrets backend\n\
             tools not installed: vault\n"
        ),
        "{text}"
    );
}

/// A doctor report selecting `selected`, with 1Password available and the
/// token's presence at server start `token`; `None` omits `headless`, as a
/// server older than #7519 P4 does.
fn ci_report(selected: &str, token: Option<bool>) -> trusty_secrets::server::DoctorResponse {
    let mut report = serde_json::json!({
        "socket": "/s", "index_root": "/i", "machine_config": "/m",
        "project_root": null, "project_config": null, "selected_backend": selected,
        "backends": [
            {"id": "keychain", "available": true, "capabilities": ["READ", "WRITE"]},
            {"id": "onepassword", "available": true, "capabilities": ["READ", "WRITE"]},
        ],
    });
    if let Some(token) = token {
        report["headless"] = serde_json::json!({"onepassword_token": token});
    }
    serde_json::from_value(report).expect("decode")
}

/// #7519 d4 Q2 (owner ruling): under `CI=true`, doctor exits non-zero when
/// the selected 1Password has no service-account token at server start.
/// Without CI, or with a token, or with another backend selected, it passes
/// as before. Red while CI was not read.
#[tokio::test]
async fn doctor_under_ci_fails_when_onepassword_has_no_headless_credential() {
    use doctor::{Judged, is_ci, verdict};
    let err = verdict(
        &ci_report("onepassword", Some(false)),
        Judged::Project,
        true,
    )
    .expect_err("CI with no token must fail");
    assert!(
        err.to_string().contains("OP_SERVICE_ACCOUNT_TOKEN"),
        "{err}"
    );
    for (selected, token, ci) in [
        ("onepassword", false, false),
        ("onepassword", true, true),
        ("keychain", false, true),
    ] {
        verdict(&ci_report(selected, Some(token)), Judged::Project, ci)
            .unwrap_or_else(|e| panic!("{selected} token={token} ci={ci}: {e}"));
    }
    // #7519 P4 critic: a server too old to report readiness fails closed.
    let old = ci_report("onepassword", None);
    assert_eq!(old.headless, None);
    verdict(&old, Judged::Project, true).expect_err("CI with no readiness reported must fail");
    for (value, ci) in [
        (Some("true"), true),
        (Some("TRUE"), true),
        (Some("1"), true),
        (Some("false"), false),
        (Some(""), false),
        (None, false),
    ] {
        assert_eq!(is_ci(value), ci, "{value:?}");
    }
    // A CI run on the Keychain still passes end to end.
    let h = harness().await;
    let outcome = run_ci(&h.client, &h.repo, "", "", true, &["doctor"]).await;
    assert_eq!(outcome.err, None, "{}", outcome.out);
}

#[tokio::test]
async fn every_verb_fails_without_a_value_when_the_socket_is_unreachable() {
    let h = harness().await;
    let dead = client_at(h.tmp.path(), &h.tmp.path().join("dead").join("s.sock"));
    let env = env_file(&h, "app.env", &format!("API_KEY={VALUE}\nPIN={SHORT}\n"));
    for args in [
        vec!["set", "API_KEY"],
        vec!["set", "PIN", "--value", "-"],
        vec!["list"],
        vec!["remove", "API_KEY"],
        vec!["import", env.as_str()],
        vec!["copy", "--from", "keychain", "--to", "spare"],
        vec!["doctor"],
    ] {
        let outcome = run_in(&dead, &h.repo, VALUE, SHORT, &args).await;
        assert!(
            outcome.err().contains("cannot start trusty-secrets"),
            "{args:?}: {}",
            outcome.err()
        );
    }
    let doctor = run_in(&dead, &h.repo, "", "", &["doctor"]).await;
    assert!(doctor.out.ends_with(": unreachable\n"), "{}", doctor.out);
    assert!(h.keychain.is_empty() && h.spare.is_empty());
}