girt 0.10.1

An incremental, idiomatic Rust implementation of Git
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
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! Explicit credential helper and askpass lifecycle.

use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use super::CredentialStore;
use crate::Config;
use crate::config::boolean;

/// A credential scope supplied by the application after URL parsing.
///
/// Components must not contain CR, LF, or NUL. A path is sent only when `use_http_path` is true.
#[derive(Clone)]
#[non_exhaustive]
pub struct CredentialContext {
    /// URL scheme, such as `https`.
    pub protocol: Vec<u8>,
    /// Host and optional port.
    pub host: Vec<u8>,
    /// Repository path without a leading slash.
    pub path: Option<Vec<u8>>,
    /// Whether helpers may distinguish repositories on the same HTTP host.
    pub use_http_path: bool,
}

impl CredentialContext {
    /// Creates a context without a path; HTTP path matching is disabled.
    pub fn new(protocol: Vec<u8>, host: Vec<u8>) -> Self {
        Self {
            protocol,
            host,
            path: None,
            use_http_path: false,
        }
    }

    /// Sets [`Self::protocol`].
    #[must_use]
    pub fn with_protocol(mut self, protocol: Vec<u8>) -> Self {
        self.protocol = protocol;
        self
    }

    /// Sets [`Self::host`].
    #[must_use]
    pub fn with_host(mut self, host: Vec<u8>) -> Self {
        self.host = host;
        self
    }

    /// Sets [`Self::path`].
    #[must_use]
    pub fn with_path(mut self, path: Option<Vec<u8>>) -> Self {
        self.path = path;
        self
    }

    /// Sets [`Self::use_http_path`].
    #[must_use]
    pub fn with_use_http_path(mut self, use_http_path: bool) -> Self {
        self.use_http_path = use_http_path;
        self
    }
}

impl std::fmt::Debug for CredentialContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CredentialContext").finish_non_exhaustive()
    }
}

/// Secret-bearing helper response. Debug deliberately omits all values.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct Credential {
    /// Username returned by a helper or prompt.
    pub username: Option<Vec<u8>>,
    /// Password or token returned by a helper or prompt.
    pub password: Option<Vec<u8>>,
}

impl Credential {
    /// Creates an empty credential with no username or password.
    pub fn new() -> Self {
        Self {
            username: None,
            password: None,
        }
    }

    /// Sets [`Self::username`].
    #[must_use]
    pub fn with_username(mut self, username: Option<Vec<u8>>) -> Self {
        self.username = username;
        self
    }

    /// Sets [`Self::password`].
    #[must_use]
    pub fn with_password(mut self, password: Option<Vec<u8>>) -> Self {
        self.password = password;
        self
    }
}

impl std::fmt::Debug for Credential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Credential").finish_non_exhaustive()
    }
}

impl Credential {
    /// Both fields are needed for ordinary username/password authentication.
    pub fn complete(&self) -> bool {
        self.username.is_some() && self.password.is_some()
    }
}

/// An application-approved executable and arguments. No shell interpretation is performed.
#[derive(Clone)]
#[non_exhaustive]
pub struct CredentialProgram {
    /// Executable path or name resolved through the caller's approved PATH.
    pub executable: PathBuf,
    /// Literal arguments, before the helper action or askpass prompt.
    pub arguments: Vec<std::ffi::OsString>,
    /// Whether to inherit the caller process environment. Prefer false for narrow trust.
    pub inherit_environment: bool,
    /// Environment entries supplied by the application after optional clearing.
    pub environment: Vec<(std::ffi::OsString, std::ffi::OsString)>,
}

impl CredentialProgram {
    /// Creates a program with no arguments or environment entries and no environment inheritance.
    pub fn new(executable: PathBuf) -> Self {
        Self {
            executable,
            arguments: Vec::new(),
            inherit_environment: false,
            environment: Vec::new(),
        }
    }

    /// Sets [`Self::executable`].
    #[must_use]
    pub fn with_executable(mut self, executable: PathBuf) -> Self {
        self.executable = executable;
        self
    }

    /// Sets [`Self::arguments`].
    #[must_use]
    pub fn with_arguments(mut self, arguments: Vec<std::ffi::OsString>) -> Self {
        self.arguments = arguments;
        self
    }

    /// Sets [`Self::inherit_environment`].
    #[must_use]
    pub fn with_inherit_environment(mut self, inherit_environment: bool) -> Self {
        self.inherit_environment = inherit_environment;
        self
    }

    /// Sets [`Self::environment`].
    #[must_use]
    pub fn with_environment(
        mut self,
        environment: Vec<(std::ffi::OsString, std::ffi::OsString)>,
    ) -> Self {
        self.environment = environment;
        self
    }
}

impl std::fmt::Debug for CredentialProgram {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CredentialProgram").finish_non_exhaustive()
    }
}

/// A configured helper that the application explicitly mapped to a trusted implementation.
#[derive(Clone)]
#[non_exhaustive]
pub struct CredentialHelper {
    /// Exact configuration value; used only to match the selected helper order.
    pub configured_name: Vec<u8>,
    /// What answers the helper's `get`, `store` and `erase` requests.
    pub backend: CredentialBackend,
}

impl CredentialHelper {
    /// Creates a helper from its configured name and explicitly approved backend.
    pub fn new(configured_name: Vec<u8>, backend: CredentialBackend) -> Self {
        Self {
            configured_name,
            backend,
        }
    }

    /// Sets [`Self::configured_name`].
    #[must_use]
    pub fn with_configured_name(mut self, configured_name: Vec<u8>) -> Self {
        self.configured_name = configured_name;
        self
    }

    /// Sets [`Self::backend`].
    #[must_use]
    pub fn with_backend(mut self, backend: CredentialBackend) -> Self {
        self.backend = backend;
        self
    }
}

/// How a credential helper runs.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CredentialBackend {
    /// An approved external process speaking Git's credential helper protocol.
    Program(CredentialProgram),
    /// girt's native implementation of Git's `store` helper; no process is started.
    Store(CredentialStore),
}

impl std::fmt::Debug for CredentialHelper {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CredentialHelper").finish_non_exhaustive()
    }
}

/// Value-free error with a stage for recovery decisions.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CredentialError {
    /// A context or protocol response is invalid.
    #[error("invalid credential {0}")]
    Protocol(&'static str),
    /// A configured helper has not been explicitly approved by the application.
    #[error("credential helper requires application approval")]
    UnapprovedHelper,
    /// Process creation or pipe I/O failed.
    #[error("credential {stage} I/O failed")]
    Io {
        /// Operation that failed.
        stage: &'static str,
        /// Underlying OS error.
        #[source]
        source: std::io::Error,
    },
    /// Program exited unsuccessfully.
    #[error("credential {0} exited unsuccessfully")]
    Exit(&'static str),
    /// Caller cancelled the lifecycle.
    #[error("credential operation cancelled")]
    Cancelled,
    /// Deadline expired.
    #[error("credential operation timed out")]
    Deadline,
}

/// Ordered helper session. The application owns the allowlist, prompting, and any saved secret.
///
/// Select the helpers from config, map each name to a trusted program, then call `fill`. Keep the
/// returned session through authentication so `approve` or `reject` can notify the same helpers.
/// All methods are blocking; call them on an application worker when used from an async runtime.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::Config;
/// use girt::remote::{CredentialContext, CredentialSession, Prompt};
///
/// let config = Config::parse(b"")?;
/// let context = CredentialContext::new(b"https".to_vec(), b"example.invalid".to_vec())
///     .with_path(Some(b"repo".to_vec()))
///     .with_use_http_path(false);
/// let cancel = AtomicBool::new(false);
/// let mut prompt = |field| {
///     Some(match field {
///         Prompt::Username => b"sample-user".to_vec(),
///         Prompt::Password => b"synthetic-secret".to_vec(),
///         _ => return None,
///     })
/// };
/// let session = CredentialSession::fill(&config, context, &[], Some(&mut prompt), &cancel, None)?;
/// assert!(session.credential().complete());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct CredentialSession {
    context: CredentialContext,
    helpers: Vec<CredentialBackend>,
    credential: Credential,
    helper_failures: Vec<(usize, CredentialError)>,
}

impl std::fmt::Debug for CredentialSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CredentialSession").finish_non_exhaustive()
    }
}

impl CredentialSession {
    /// Query configured helpers in order, then prompt for any missing field if allowed.
    ///
    /// An empty `credential.helper` resets earlier helpers. The application supplies `programs`
    /// for every remaining helper; shell snippets and helpers that internally invoke Git require
    /// explicit application handling. Prompt is called with `Username` or `Password`, and can
    /// return `None` to cancel. No process is started when `cancel` is already set.
    ///
    /// # Errors
    ///
    /// Returns [`CredentialError`] for malformed context/configuration/helper responses, unapproved
    /// helpers, process or store I/O, cancellation or deadline expiry. A prompt returning `None`
    /// reports cancellation. Nonzero helper exits are retained in [`Self::helper_failures`] while
    /// later helpers are tried; success does not guarantee complete credentials when no prompt is
    /// supplied.
    pub fn fill(
        config: &Config,
        mut context: CredentialContext,
        programs: &[CredentialHelper],
        mut prompt: Option<&mut dyn FnMut(Prompt) -> Option<Vec<u8>>>,
        cancel: &AtomicBool,
        deadline: Option<Instant>,
    ) -> Result<Self, CredentialError> {
        validate_context(&context)?;
        let mut names = Vec::new();
        let mut username = None;
        for entry in config.entries() {
            if !entry.section.eq_ignore_ascii_case(b"credential")
                || !scope_matches(entry.subsection.as_deref(), &context)
            {
                continue;
            }
            if entry.name.eq_ignore_ascii_case(b"username") {
                username = Some(
                    entry
                        .value
                        .clone()
                        .ok_or(CredentialError::Protocol("username configuration"))?,
                );
            } else if entry.name.eq_ignore_ascii_case(b"usehttppath") {
                context.use_http_path = boolean(entry.value.as_deref())
                    .ok_or(CredentialError::Protocol("path configuration"))?;
            } else if entry.name.eq_ignore_ascii_case(b"helper") {
                let name = entry
                    .value
                    .as_deref()
                    .ok_or(CredentialError::Protocol("helper configuration"))?;
                if name.is_empty() {
                    names.clear();
                } else {
                    names.push(name);
                }
            }
        }
        let mut helpers = Vec::new();
        for name in names {
            let selected = programs
                .iter()
                .find(|program| program.configured_name == name)
                .ok_or(CredentialError::UnapprovedHelper)?;
            helpers.push(selected.backend.clone());
        }
        let mut credential = Credential {
            username,
            password: None,
        };
        let mut helper_failures = Vec::new();
        for (position, helper) in helpers.iter().enumerate() {
            let program = match helper {
                CredentialBackend::Program(program) => program,
                CredentialBackend::Store(store) => {
                    check(cancel, deadline)?;
                    store.get(&context, &mut credential)?;
                    if credential.complete() {
                        break;
                    }
                    continue;
                }
            };
            let input = encode(&context, &credential)?;
            let output = match run(program, Some("get"), &input, cancel, deadline) {
                Ok(output) => output,
                Err(error @ CredentialError::Exit(_)) => {
                    helper_failures.push((position, error));
                    continue;
                }
                Err(error) => return Err(error),
            };
            merge(&mut credential, &output)?;
            if credential.complete() {
                break;
            }
        }
        if !credential.complete()
            && let Some(prompt) = prompt.as_mut()
        {
            if credential.username.is_none() {
                check(cancel, deadline)?;
                credential.username =
                    Some(prompt(Prompt::Username).ok_or(CredentialError::Cancelled)?);
            }
            if credential.password.is_none() {
                check(cancel, deadline)?;
                credential.password =
                    Some(prompt(Prompt::Password).ok_or(CredentialError::Cancelled)?);
            }
        }
        check(cancel, deadline)?;
        Ok(Self {
            context,
            helpers,
            credential,
            helper_failures,
        })
    }

    /// Nonzero helper exits and their zero-based configured positions. Later helpers still ran.
    pub fn helper_failures(&self) -> &[(usize, CredentialError)] {
        &self.helper_failures
    }

    /// Secret result for one authentication attempt.
    pub fn credential(&self) -> &Credential {
        &self.credential
    }

    /// Scope used for this lookup. Transports must compare it with the final destination before
    /// attaching the credential to a request.
    pub fn context(&self) -> &CredentialContext {
        &self.context
    }

    /// Notify all selected helpers after successful authentication.
    ///
    /// # Errors
    ///
    /// Returns [`CredentialError`] for invalid protocol bytes, helper/store I/O, unsuccessful
    /// helper exit, cancellation or deadline expiry. Earlier helpers may already have stored
    /// credentials; notifications are sequential and are not rolled back.
    pub fn approve(
        &self,
        cancel: &AtomicBool,
        deadline: Option<Instant>,
    ) -> Result<(), CredentialError> {
        self.notify("store", cancel, deadline)
    }

    /// Notify all selected helpers after rejected authentication.
    ///
    /// # Errors
    ///
    /// Returns [`CredentialError`] for invalid protocol bytes, helper/store I/O, unsuccessful
    /// helper exit, cancellation or deadline expiry. Earlier helpers may already have erased
    /// credentials; notifications are sequential and are not rolled back.
    pub fn reject(
        &self,
        cancel: &AtomicBool,
        deadline: Option<Instant>,
    ) -> Result<(), CredentialError> {
        self.notify("erase", cancel, deadline)
    }

    fn notify(
        &self,
        action: &'static str,
        cancel: &AtomicBool,
        deadline: Option<Instant>,
    ) -> Result<(), CredentialError> {
        let input = encode(&self.context, &self.credential)?;
        for helper in &self.helpers {
            match helper {
                CredentialBackend::Program(program) => {
                    run(program, Some(action), &input, cancel, deadline)?;
                }
                CredentialBackend::Store(store) => {
                    check(cancel, deadline)?;
                    if action == "store" {
                        store.store(&self.context, &self.credential)?;
                    } else {
                        store.erase(&self.context, &self.credential)?;
                    }
                }
            }
        }
        Ok(())
    }
}

/// A field requested by the application-owned prompt callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Prompt {
    /// The account name for the endpoint.
    Username,
    /// The secret for the endpoint and previously chosen username.
    Password,
}

/// Run an explicitly approved askpass executable for one prompt; `None` means user cancellation.
///
/// # Errors
///
/// Returns [`CredentialError::Protocol`] for NUL, CR or LF in the question, or process/protocol,
/// exit, cancellation or deadline errors while running the approved executable. An empty answer
/// is successful user cancellation (`Ok(None)`); the executable may already have run on failure.
pub fn askpass(
    program: &CredentialProgram,
    question: &str,
    cancel: &AtomicBool,
    deadline: Option<Instant>,
) -> Result<Option<Vec<u8>>, CredentialError> {
    if question.contains(['\0', '\r', '\n']) {
        return Err(CredentialError::Protocol("askpass question"));
    }
    let output = run_askpass(program, question, cancel, deadline)?;
    let answer = output.strip_suffix(b"\n").unwrap_or(&output);
    let answer = answer.strip_suffix(b"\r").unwrap_or(answer);
    if answer.is_empty() {
        Ok(None)
    } else {
        Ok(Some(answer.to_vec()))
    }
}

fn validate_context(context: &CredentialContext) -> Result<(), CredentialError> {
    for value in [
        &context.protocol[..],
        &context.host[..],
        context.path.as_deref().unwrap_or_default(),
    ] {
        if value.contains(&0) || value.contains(&b'\n') || value.contains(&b'\r') {
            return Err(CredentialError::Protocol("context"));
        }
    }
    if context.protocol.is_empty() || context.host.is_empty() {
        return Err(CredentialError::Protocol("context"));
    }
    Ok(())
}

fn scope_matches(scope: Option<&[u8]>, context: &CredentialContext) -> bool {
    let Some(scope) = scope else {
        return true;
    };
    let Some((protocol, location)) = scope
        .windows(3)
        .position(|part| part == b"://")
        .map(|at| (&scope[..at], &scope[at + 3..]))
    else {
        return false;
    };
    if !protocol.eq_ignore_ascii_case(&context.protocol) {
        return false;
    }
    let slash = location
        .iter()
        .position(|byte| *byte == b'/')
        .unwrap_or(location.len());
    if !location[..slash].eq_ignore_ascii_case(&context.host) {
        return false;
    }
    if slash == location.len() {
        return true;
    }
    let scoped_path = &location[slash + 1..];
    let Some(path) = &context.path else {
        return false;
    };
    path == scoped_path
        || path
            .strip_prefix(scoped_path)
            .is_some_and(|rest| rest.starts_with(b"/"))
}

fn encode(
    context: &CredentialContext,
    credential: &Credential,
) -> Result<Vec<u8>, CredentialError> {
    let mut result = Vec::new();
    for (key, value) in [
        (b"protocol".as_slice(), Some(context.protocol.as_slice())),
        (b"host".as_slice(), Some(context.host.as_slice())),
        (
            b"path".as_slice(),
            context.path.as_deref().filter(|_| context.use_http_path),
        ),
        (b"username".as_slice(), credential.username.as_deref()),
        (b"password".as_slice(), credential.password.as_deref()),
    ] {
        if let Some(value) = value {
            if value.contains(&0) || value.contains(&b'\n') || value.contains(&b'\r') {
                return Err(CredentialError::Protocol("field"));
            }
            result.extend_from_slice(key);
            result.push(b'=');
            result.extend_from_slice(value);
            result.push(b'\n');
        }
    }
    result.push(b'\n');
    Ok(result)
}

fn merge(credential: &mut Credential, output: &[u8]) -> Result<(), CredentialError> {
    for line in output.split(|byte| *byte == b'\n') {
        let line = line.strip_suffix(b"\r").unwrap_or(line);
        if line.is_empty() {
            break;
        }
        let equal = line
            .iter()
            .position(|byte| *byte == b'=')
            .ok_or(CredentialError::Protocol("helper response"))?;
        let (key, remainder) = line.split_at(equal);
        let value = &remainder[1..];
        if value.contains(&0) {
            return Err(CredentialError::Protocol("helper response"));
        }
        match key {
            b"username" => credential.username = Some(value.to_vec()),
            b"password" => credential.password = Some(value.to_vec()),
            b"quit" if value == b"true" => return Err(CredentialError::Cancelled),
            _ => {}
        }
    }
    Ok(())
}

fn run_askpass(
    program: &CredentialProgram,
    question: &str,
    cancel: &AtomicBool,
    deadline: Option<Instant>,
) -> Result<Vec<u8>, CredentialError> {
    process(program, None, Some(question), &[], cancel, deadline)
}

fn run(
    program: &CredentialProgram,
    action: Option<&'static str>,
    input: &[u8],
    cancel: &AtomicBool,
    deadline: Option<Instant>,
) -> Result<Vec<u8>, CredentialError> {
    process(program, action, None, input, cancel, deadline)
}

fn check(cancel: &AtomicBool, deadline: Option<Instant>) -> Result<(), CredentialError> {
    if cancel.load(Ordering::Relaxed) {
        Err(CredentialError::Cancelled)
    } else if deadline.is_some_and(|end| Instant::now() >= end) {
        Err(CredentialError::Deadline)
    } else {
        Ok(())
    }
}

fn process(
    program: &CredentialProgram,
    action: Option<&'static str>,
    question: Option<&str>,
    input: &[u8],
    cancel: &AtomicBool,
    deadline: Option<Instant>,
) -> Result<Vec<u8>, CredentialError> {
    check(cancel, deadline)?;
    let mut command = Command::new(&program.executable);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    if !program.inherit_environment {
        command.env_clear();
    }
    command.envs(program.environment.iter().cloned());
    command
        .args(&program.arguments)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null());
    if let Some(action) = action {
        command.arg(action);
    }
    if let Some(question) = question {
        command.arg(question);
    }
    let mut child = command.spawn().map_err(|source| CredentialError::Io {
        stage: "spawn",
        source,
    })?;
    let mut stdin = child.stdin.take().expect("piped stdin");
    let stdout = child.stdout.take().expect("piped stdout");
    let input = input.to_vec();
    let writer = std::thread::spawn(move || stdin.write_all(&input));
    let (sender, receiver) = mpsc::channel();
    let reader = std::thread::spawn(move || {
        let mut output = Vec::new();
        let result = stdout.take(65_537).read_to_end(&mut output);
        let _ = sender.send(output.len() > 65_536);
        (result, output)
    });
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Err(source) => {
                terminate(&mut child);
                let _ = child.wait();
                let _ = writer.join();
                let _ = reader.join();
                return Err(CredentialError::Io {
                    stage: "wait",
                    source,
                });
            }
            Ok(None) => {}
        }
        if let Err(error) = check(cancel, deadline) {
            terminate(&mut child);
            let _ = child.wait();
            let _ = writer.join();
            let _ = reader.join();
            return Err(error);
        }
        if receiver.try_recv() == Ok(true) {
            // A bounded reader has stopped while the child may still be writing.
            if let Ok(Some(status)) = child.try_wait() {
                break status;
            }
            terminate(&mut child);
            let _ = child.wait();
            let _ = writer.join();
            let _ = reader.join();
            return Err(CredentialError::Protocol("response limit"));
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    #[cfg(unix)]
    terminate(&mut child);
    let written = writer
        .join()
        .map_err(|_| CredentialError::Protocol("stdin worker"))?;
    let (read, output) = reader
        .join()
        .map_err(|_| CredentialError::Protocol("stdout worker"))?;
    if !status.success() {
        return Err(CredentialError::Exit(action.unwrap_or("askpass")));
    }
    // A successful helper may answer without consuming every input field. Its closed stdin then
    // yields BrokenPipe even though the response is valid and the process exited successfully.
    if let Err(source) = written
        && source.kind() != std::io::ErrorKind::BrokenPipe
    {
        return Err(CredentialError::Io {
            stage: "stdin",
            source,
        });
    }
    read.map_err(|source| CredentialError::Io {
        stage: "stdout",
        source,
    })?;
    if output.len() > 65_536 {
        return Err(CredentialError::Protocol("response limit"));
    }
    Ok(output)
}

fn terminate(child: &mut std::process::Child) {
    #[cfg(unix)]
    {
        use rustix::process::{Pid, Signal, kill_process_group};
        if let Some(pid) = Pid::from_raw(child.id() as i32) {
            let _ = kill_process_group(pid, Signal::KILL);
        }
    }
    let _ = child.kill();
}

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

    #[cfg(unix)]
    fn helper(script: &str) -> (tempfile::TempDir, CredentialHelper) {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("helper.sh");
        std::fs::write(&path, script).unwrap();
        let helper = CredentialHelper {
            configured_name: b"synthetic".to_vec(),
            backend: CredentialBackend::Program(CredentialProgram {
                executable: PathBuf::from("sh"),
                arguments: vec![path.into_os_string()],
                inherit_environment: false,
                environment: Vec::new(),
            }),
        };
        (directory, helper)
    }

    #[cfg(unix)]
    fn process(helper: &CredentialHelper) -> &CredentialProgram {
        match &helper.backend {
            CredentialBackend::Program(program) => program,
            CredentialBackend::Store(_) => unreachable!("test helpers are programs"),
        }
    }

    #[cfg(unix)]
    fn context(use_http_path: bool) -> CredentialContext {
        CredentialContext {
            protocol: b"https".to_vec(),
            host: b"example.invalid".to_vec(),
            path: Some(b"one/repo".to_vec()),
            use_http_path,
        }
    }

    #[cfg(unix)]
    #[test]
    fn helper_lookup_scope_and_notifications() {
        let directory = tempfile::tempdir().unwrap();
        let record = directory.path().join("record");
        let script = format!(
            "case \"$1\" in\nget) cat > /dev/null; printf 'username=sample\\npassword=synthetic-secret\\n\\n' ;;\nstore|erase) printf '%s\\n' \"$1\" >> '{}'; cat >> '{}' ;;\nesac\n",
            record.display(),
            record.display()
        );
        let (_helper_dir, helper) = helper(&script);
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let cancel = AtomicBool::new(false);
        let session =
            CredentialSession::fill(&config, context(true), &[helper], None, &cancel, None)
                .unwrap();
        assert_eq!(
            session.credential().username.as_deref(),
            Some(b"sample".as_slice())
        );
        assert_eq!(
            session.credential().password.as_deref(),
            Some(b"synthetic-secret".as_slice())
        );
        session.approve(&cancel, None).unwrap();
        session.reject(&cancel, None).unwrap();
        let recorded = std::fs::read(record).unwrap();
        assert!(
            recorded
                .windows(b"path=one/repo".len())
                .any(|part| part == b"path=one/repo")
        );
        assert!(
            recorded
                .windows(b"store".len())
                .any(|part| part == b"store")
        );
        assert!(
            recorded
                .windows(b"erase".len())
                .any(|part| part == b"erase")
        );
        assert!(!format!("{session:?}").contains("synthetic-secret"));
    }

    #[cfg(unix)]
    #[test]
    fn helper_reset_and_prompt() {
        let (_directory, helper) = helper("cat > /dev/null; printf 'username=helper\\n\\n'");
        let config =
            Config::parse(b"[credential]\nhelper = unapproved\nhelper =\nhelper = synthetic\n")
                .unwrap();
        let cancel = AtomicBool::new(false);
        let mut prompt = |field| {
            assert_eq!(field, Prompt::Password);
            Some(b"prompted-secret".to_vec())
        };
        let session = CredentialSession::fill(
            &config,
            context(false),
            &[helper],
            Some(&mut prompt),
            &cancel,
            None,
        )
        .unwrap();
        assert_eq!(
            session.credential().password.as_deref(),
            Some(b"prompted-secret".as_slice())
        );
    }

    #[cfg(unix)]
    #[test]
    fn cancellation_kills_waiting_helper() {
        let (_directory, helper) = helper("cat > /dev/null; sleep 30");
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let cancel = AtomicBool::new(false);
        let started = Instant::now();
        let result = CredentialSession::fill(
            &config,
            context(false),
            &[helper],
            None,
            &cancel,
            Some(started + Duration::from_millis(100)),
        );
        assert!(matches!(result, Err(CredentialError::Deadline)));
        assert!(started.elapsed() < Duration::from_secs(3));
    }

    #[cfg(unix)]
    #[test]
    fn askpass_returns_answer_and_empty_cancels() {
        let (_directory, program) = helper("printf 'synthetic-secret\\n'");
        let cancel = AtomicBool::new(false);
        assert_eq!(
            askpass(process(&program), "Password:", &cancel, None).unwrap(),
            Some(b"synthetic-secret".to_vec())
        );
        let (_directory, empty) = helper("printf '\\n'");
        assert_eq!(
            askpass(process(&empty), "Password:", &cancel, None).unwrap(),
            None
        );
    }

    #[cfg(windows)]
    #[test]
    fn native_windows_askpass_process() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("askpass.cmd");
        std::fs::write(&path, b"@echo off\r\necho synthetic-secret\r\n").unwrap();
        let program = CredentialProgram {
            executable: PathBuf::from("cmd.exe"),
            arguments: vec!["/D".into(), "/C".into(), path.into_os_string()],
            inherit_environment: false,
            environment: Vec::new(),
        };
        let cancel = AtomicBool::new(false);
        assert_eq!(
            askpass(&program, "Password:", &cancel, None).unwrap(),
            Some(b"synthetic-secret".to_vec())
        );
    }
    #[cfg(unix)]
    #[test]
    fn scoped_helper_does_not_run_for_another_repository() {
        let config =
            Config::parse(b"[credential \"https://example.invalid/one\"]\nhelper = synthetic\n")
                .unwrap();
        let cancel = AtomicBool::new(false);
        let other = CredentialContext {
            path: Some(b"other/repo".to_vec()),
            ..context(true)
        };
        let session = CredentialSession::fill(&config, other, &[], None, &cancel, None).unwrap();
        assert!(!session.credential().complete());
    }

    #[cfg(unix)]
    #[test]
    fn helper_exit_and_protocol_failure_are_redacted() {
        let (_directory, helper) = helper("printf 'password=synthetic-secret\\n'; exit 7");
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let cancel = AtomicBool::new(false);
        let session =
            CredentialSession::fill(&config, context(false), &[helper], None, &cancel, None)
                .unwrap();
        assert!(matches!(
            session.helper_failures(),
            [(0, CredentialError::Exit("get"))]
        ));
        assert!(!session.credential().complete());
        assert!(!format!("{session:?}").contains("synthetic-secret"));
    }

    #[cfg(unix)]
    #[test]
    fn configured_username_and_path_policy_reach_helper() {
        let (_directory, helper) = helper(
            r#"input=$(cat); case "$input" in *'path=one/repo'*) printf 'password=synthetic-secret\n';; esac"#,
        );
        let config = Config::parse(
            b"[credential]\nhelper = synthetic\nusername = configured\nuseHttpPath = true\n",
        )
        .unwrap();
        let cancel = AtomicBool::new(false);
        let session =
            CredentialSession::fill(&config, context(false), &[helper], None, &cancel, None)
                .unwrap();
        assert_eq!(
            session.credential().username.as_deref(),
            Some(b"configured".as_slice())
        );
        assert_eq!(
            session.credential().password.as_deref(),
            Some(b"synthetic-secret".as_slice())
        );
    }
    #[cfg(unix)]
    #[test]
    fn failed_helper_allows_later_helper() {
        let (_first_dir, mut first) = helper("exit 7");
        first.configured_name = b"first".to_vec();
        let (_second_dir, mut second) =
            helper("printf 'username=sample\\npassword=synthetic-secret\\n\\n'");
        second.configured_name = b"second".to_vec();
        let config = Config::parse(b"[credential]\nhelper = first\nhelper = second\n").unwrap();
        let cancel = AtomicBool::new(false);
        let session = CredentialSession::fill(
            &config,
            context(false),
            &[first, second],
            None,
            &cancel,
            None,
        )
        .unwrap();
        assert!(session.credential().complete());
        assert!(matches!(
            session.helper_failures(),
            [(0, CredentialError::Exit("get"))]
        ));
    }

    #[cfg(unix)]
    #[test]
    fn successful_helper_may_close_stdin_before_reading() {
        let (_directory, helper) = helper("printf 'username=sample\\npassword=secret\\n\\n'");
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let mut context = context(false);
        context.host = vec![b'h'; 1024 * 1024];
        let cancel = AtomicBool::new(false);
        let session =
            CredentialSession::fill(&config, context, &[helper], None, &cancel, None).unwrap();
        assert!(session.credential().complete());
    }

    #[cfg(unix)]
    #[test]
    fn helper_quit_cancels_without_prompt() {
        let (_directory, helper) = helper("printf 'quit=true\\n\\n'");
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let cancel = AtomicBool::new(false);
        let result =
            CredentialSession::fill(&config, context(false), &[helper], None, &cancel, None);
        assert!(matches!(result, Err(CredentialError::Cancelled)));
    }
    #[test]
    fn configured_program_debug_hides_sensitive_values() {
        let helper = CredentialHelper {
            configured_name: b"synthetic-secret".to_vec(),
            backend: CredentialBackend::Program(CredentialProgram {
                executable: PathBuf::from("synthetic-secret"),
                arguments: vec!["synthetic-secret".into()],
                inherit_environment: false,
                environment: vec![("TOKEN".into(), "synthetic-secret".into())],
            }),
        };
        assert!(!format!("{helper:?}").contains("synthetic-secret"));
        assert!(!format!("{:?}", helper.backend).contains("synthetic-secret"));
    }
    #[cfg(windows)]
    #[test]
    fn native_windows_helper_lifecycle() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("helper.cmd");
        std::fs::write(
            &path,
            b"@echo off\r\nmore > nul\r\nif \"%1\"==\"get\" (\r\n  echo username=sample\r\n  echo password=synthetic-secret\r\n)\r\n",
        ).unwrap();
        let helper = CredentialHelper {
            configured_name: b"synthetic".to_vec(),
            backend: CredentialBackend::Program(CredentialProgram {
                executable: PathBuf::from("cmd.exe"),
                arguments: vec!["/D".into(), "/C".into(), path.into_os_string()],
                inherit_environment: false,
                environment: Vec::new(),
            }),
        };
        let config = Config::parse(b"[credential]\nhelper = synthetic\n").unwrap();
        let cancel = AtomicBool::new(false);
        let context = CredentialContext {
            protocol: b"https".to_vec(),
            host: b"example.invalid".to_vec(),
            path: None,
            use_http_path: false,
        };
        let session =
            CredentialSession::fill(&config, context, &[helper], None, &cancel, None).unwrap();
        assert!(session.credential().complete());
        session.approve(&cancel, None).unwrap();
        session.reject(&cancel, None).unwrap();
    }
}