grit-lib 0.5.21

Core library for the grit Git implementation
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
//! Integration tests for `grit_lib::remote::credentials`.
//!
//! These exercise the Git-compatible [`HelperCredentialProvider`] end-to-end
//! against real on-disk credential helper scripts (shell scripts that speak
//! Git's `key=value` credential protocol on stdin/stdout). A temp repo is
//! created with the system `git`, its `credential.helper` config is pointed at
//! a fake helper, and we assert:
//!
//! - `fill` returns the username/password the helper emits;
//! - `approve`/`reject` invoke the helper with `store`/`erase` (verified by a
//!   helper that records its action to a file);
//! - with **no** helper configured, `fill` returns the typed
//!   non-interactive error (it must not hang on a TTY/askpass).
//!
//! The tests skip gracefully if the system `git` binary is unavailable.

#![cfg(unix)]

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::sync::Once;

use grit_lib::config::ConfigSet;
use grit_lib::remote::credentials::{
    Credential, CredentialProvider, HelperCredentialProvider, NON_INTERACTIVE_MESSAGE,
};
use grit_lib::remote::github_auth::{github_token_credential, TOKEN_USERNAME};

/// Run `git` in `dir`; returns `None` if git is unavailable.
fn git(dir: &Path, args: &[&str]) -> Option<std::process::Output> {
    Command::new("git")
        .current_dir(dir)
        .args(args)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()
        .ok()
}

/// Initialize a repo in `dir`. Returns `false` if git is unavailable.
fn init_repo(dir: &Path) -> bool {
    matches!(git(dir, &["init", "-q"]), Some(out) if out.status.success())
}

/// Write an executable shell script and return its path.
fn write_script(path: &Path, body: &str) {
    fs::write(path, body).expect("write script");
    let mut perms = fs::metadata(path).expect("stat script").permissions();
    perms.set_mode(0o755);
    fs::set_permissions(path, perms).expect("chmod script");
}

static ISOLATE: Once = Once::new();

/// Detach config loading from the developer's real `~/.gitconfig` and
/// `/etc/gitconfig`. `ConfigSet::load` honors `GIT_CONFIG_GLOBAL` /
/// `GIT_CONFIG_SYSTEM` (pointing them at `/dev/null` yields no entries), so the
/// only `credential.helper` the provider sees is the one the test wrote into
/// the repo-local config. Every test wants the identical isolation, so setting
/// these process-wide once is race-free under parallel test execution.
fn isolate_global_config() {
    ISOLATE.call_once(|| {
        // SAFETY: set once, to a constant, before any test loads config.
        std::env::set_var("GIT_CONFIG_GLOBAL", "/dev/null");
        std::env::set_var("GIT_CONFIG_SYSTEM", "/dev/null");
    });
}

/// Load the repo-local config (no global/system) for the worktree at `dir`.
///
/// `ConfigSet::load` wants the `.git` directory, where `config` lives.
fn load_config(dir: &Path) -> ConfigSet {
    isolate_global_config();
    let git_dir = dir.join(".git");
    ConfigSet::load(
        &grit_lib::config::environment::Environment::capture_process(),
        Some(&git_dir),
        false,
    )
    .expect("load config")
}

fn sample_input() -> Credential {
    Credential {
        protocol: Some("https".into()),
        host: Some("example.com".into()),
        ..Default::default()
    }
}

#[test]
fn fill_returns_helper_username_and_password() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    // A helper that, on `get`, emits a fixed username/password (and echoes back
    // any input fields it received, like a real helper would not need to).
    let helper = dir.join("helper.sh");
    write_script(
        &helper,
        "#!/bin/sh\n\
         if [ \"$1\" = get ]; then\n\
           echo username=alice\n\
           echo password=secret\n\
         fi\n",
    );

    // Git's `!cmd` shell form runs the value through `sh -c`. Point the helper
    // at the absolute script path.
    let helper_value = format!("!{}", helper.display());
    let cfg = build_config(dir, &[("credential.helper", &helper_value)]);

    let provider = HelperCredentialProvider::new(cfg);
    let filled = provider.fill(&sample_input()).expect("fill should succeed");
    assert_eq!(filled.username.as_deref(), Some("alice"));
    assert_eq!(filled.password.as_deref(), Some("secret"));
    // The provider must preserve the original target fields.
    assert_eq!(filled.protocol.as_deref(), Some("https"));
    assert_eq!(filled.host.as_deref(), Some("example.com"));
}

#[test]
fn approve_and_reject_invoke_helper_with_store_and_erase() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    let record = dir.join("record.log");
    let helper = dir.join("recorder.sh");
    // Record the action ($1) so we can assert store/erase were dispatched.
    write_script(
        &helper,
        &format!(
            "#!/bin/sh\n\
             echo \"$1\" >> {record}\n\
             if [ \"$1\" = get ]; then\n\
               echo username=alice\n\
               echo password=secret\n\
             fi\n",
            record = record.display()
        ),
    );

    let helper_value = format!("!{}", helper.display());
    let cfg = build_config(dir, &[("credential.helper", &helper_value)]);
    let provider = HelperCredentialProvider::new(cfg);

    let cred = Credential {
        protocol: Some("https".into()),
        host: Some("example.com".into()),
        username: Some("alice".into()),
        password: Some("secret".into()),
        ..Default::default()
    };

    provider.approve(&cred).expect("approve");
    provider.reject(&cred).expect("reject");

    let log = fs::read_to_string(&record).expect("read record log");
    let actions: Vec<&str> = log.lines().collect();
    assert!(
        actions.contains(&"store"),
        "approve should invoke helper with `store`, got {actions:?}"
    );
    assert!(
        actions.contains(&"erase"),
        "reject should invoke helper with `erase`, got {actions:?}"
    );
}

#[test]
fn fill_without_helper_returns_typed_non_interactive_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    // No credential.helper configured.
    let cfg = load_config(dir);
    let provider = HelperCredentialProvider::new(cfg);

    let err = provider
        .fill(&sample_input())
        .expect_err("fill must fail (not hang) with no helper");
    // Must be the typed non-interactive message, not a TTY prompt/hang.
    assert!(
        err.to_string().contains(NON_INTERACTIVE_MESSAGE),
        "expected non-interactive error, got: {err}"
    );
}

#[test]
fn fill_returns_typed_error_when_helper_supplies_nothing() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    // A helper that returns no credentials at all (mimics e.g. an empty store).
    let helper = dir.join("empty.sh");
    write_script(&helper, "#!/bin/sh\nexit 0\n");
    let helper_value = format!("!{}", helper.display());
    let cfg = build_config(dir, &[("credential.helper", &helper_value)]);

    let provider = HelperCredentialProvider::new(cfg);
    let err = provider
        .fill(&sample_input())
        .expect_err("fill must fail when helper yields nothing");
    assert!(
        err.to_string().contains(NON_INTERACTIVE_MESSAGE),
        "expected non-interactive error, got: {err}"
    );
}

#[test]
fn fill_short_circuits_when_input_already_complete() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    // Helper that, if ever called, would FAIL the process — proving it is not
    // invoked when the input already has username+password.
    let helper = dir.join("explode.sh");
    write_script(&helper, "#!/bin/sh\nexit 17\n");
    let helper_value = format!("!{}", helper.display());
    let cfg = build_config(dir, &[("credential.helper", &helper_value)]);

    let provider = HelperCredentialProvider::new(cfg);
    let input = Credential {
        protocol: Some("https".into()),
        host: Some("example.com".into()),
        username: Some("bob".into()),
        password: Some("hunter2".into()),
        ..Default::default()
    };
    let filled = provider
        .fill(&input)
        .expect("complete input should not call helper");
    assert_eq!(filled.username.as_deref(), Some("bob"));
    assert_eq!(filled.password.as_deref(), Some("hunter2"));
}

#[test]
fn url_scoped_helper_applies_only_to_matching_target() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }

    let helper = dir.join("scoped.sh");
    write_script(
        &helper,
        "#!/bin/sh\n\
         if [ \"$1\" = get ]; then\n\
           echo username=scoped\n\
           echo password=pw\n\
         fi\n",
    );
    let helper_value = format!("!{}", helper.display());
    // Scope the helper to github.com only.
    let cfg = build_config(
        dir,
        &[("credential.https://github.com.helper", &helper_value)],
    );
    let provider = HelperCredentialProvider::new(cfg);

    // Matching target -> helper fires, credential completed.
    let github = Credential {
        protocol: Some("https".into()),
        host: Some("github.com".into()),
        ..Default::default()
    };
    let filled = provider.fill(&github).expect("matching scope fills");
    assert_eq!(filled.username.as_deref(), Some("scoped"));

    // Non-matching target -> helper does not apply -> typed non-interactive err.
    let other = Credential {
        protocol: Some("https".into()),
        host: Some("example.com".into()),
        ..Default::default()
    };
    let err = provider
        .fill(&other)
        .expect_err("non-matching scope yields no creds");
    assert!(err.to_string().contains(NON_INTERACTIVE_MESSAGE));
}

/// Append one `key=value` to the repo config with `git config --add`, so
/// multi-valued keys keep their load order.
fn git_config_add(dir: &Path, key: &str, value: &str) {
    let out = git(dir, &["config", "--local", "--add", key, value]).expect("git config");
    assert!(
        out.status.success(),
        "git config --add {key} failed: {out:?}"
    );
}

#[test]
fn helpers_for_lists_applicable_helpers_in_load_order_with_reset() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }
    let token = github_token_credential(None);

    git_config_add(dir, "credential.helper", "first");
    git_config_add(dir, "credential.https://github.com.helper", "github-only");
    git_config_add(dir, "credential.https://example.com.helper", "elsewhere");
    let provider = HelperCredentialProvider::new(load_config(dir));
    assert_eq!(provider.helpers_for(&token), ["first", "github-only"]);
    assert_eq!(
        provider.helpers_for(&sample_input()),
        ["first", "elsewhere"]
    );

    git_config_add(dir, "credential.https://github.com.helper", "");
    let provider = HelperCredentialProvider::new(load_config(dir));
    assert!(provider.helpers_for(&token).is_empty());
    assert_eq!(
        provider.helpers_for(&sample_input()),
        ["first", "elsewhere"]
    );

    // `--add` writes into the existing `[credential]` section, which precedes
    // the URL-scoped sections in the file, so the later reset still wins.
    git_config_add(dir, "credential.helper", "second");
    let provider = HelperCredentialProvider::new(load_config(dir));
    assert!(provider.helpers_for(&token).is_empty());
    assert_eq!(
        provider.helpers_for(&sample_input()),
        ["first", "second", "elsewhere"]
    );
}

#[test]
fn github_token_stored_by_grit_is_filled_and_erased_for_system_git() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let dir = tmp.path();
    if !init_repo(dir) {
        eprintln!("skipping: system git unavailable");
        return;
    }
    let store = dir.join("token-store");
    git_config_add(
        dir,
        "credential.helper",
        &format!("store --file={}", store.display()),
    );
    let provider = HelperCredentialProvider::new(load_config(dir));
    assert_eq!(
        provider.helpers_for(&github_token_credential(None)).len(),
        1
    );

    provider
        .approve(&github_token_credential(Some("gho_roundtrip")))
        .expect("store token");

    let git_fill = || {
        let mut child = Command::new("git")
            .current_dir(dir)
            .args(["credential", "fill"])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env_remove("GIT_ASKPASS")
            .env_remove("SSH_ASKPASS")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .spawn()
            .expect("spawn git credential fill");
        std::io::Write::write_all(
            child.stdin.as_mut().expect("stdin"),
            b"protocol=https\nhost=github.com\nusername=x-access-token\n\n",
        )
        .expect("write fill input");
        let out = child.wait_with_output().expect("git credential fill");
        Credential::parse_bytes(&out.stdout)
    };

    let filled = git_fill();
    assert_eq!(filled.username.as_deref(), Some(TOKEN_USERNAME));
    assert_eq!(filled.password.as_deref(), Some("gho_roundtrip"));

    provider
        .reject(&github_token_credential(None))
        .expect("erase token");
    assert!(
        !fs::read_to_string(&store)
            .unwrap_or_default()
            .contains("gho_roundtrip"),
        "erase must remove the stored token"
    );
    assert_eq!(git_fill().password, None);
}

#[test]
fn credential_wire_format_round_trips() {
    let input = "protocol=https\nhost=example.com\nusername=alice\npassword=secret\n";
    let cred = Credential::parse(input);
    assert_eq!(cred.username.as_deref(), Some("alice"));
    assert_eq!(cred.password.as_deref(), Some("secret"));
    assert_eq!(cred.serialize(), input);
}

/// Build a [`ConfigSet`] for `dir` with extra `key=value` config applied via
/// `git config --local` (so the entries land in the repo's real `.git/config`),
/// then load it. Keeps the test's config wiring identical to what an embedder
/// would see from a real repository.
fn build_config(dir: &Path, kvs: &[(&str, &str)]) -> ConfigSet {
    for (k, v) in kvs {
        let out = git(dir, &["config", "--local", k, v]).expect("git config");
        assert!(out.status.success(), "git config {k} failed: {out:?}");
    }
    load_config(dir)
}