Skip to main content

git2db/
auth.rs

1//! Authentication and credential management
2//!
3//! Consolidated authentication patterns from the original codebase.
4
5use crate::callback_config::{AuthMode, CertificateConfig, RedirectPolicy};
6use git2::{Cred, CredentialType, RemoteCallbacks};
7use std::path::PathBuf;
8use tracing::{debug, info, warn};
9
10/// Authentication strategy for git operations
11#[derive(Debug, Clone)]
12pub enum AuthStrategy {
13    /// Use SSH key from agent
14    SshAgent { username: Option<String> },
15    /// Use specific SSH key file
16    SshKey {
17        username: String,
18        public_key: Option<PathBuf>,
19        private_key: PathBuf,
20        passphrase: Option<String>,
21    },
22    /// Use username/password
23    UserPass { username: String, password: String },
24    /// Use a personal access token.
25    ///
26    /// `host` optionally binds the token to an exact origin host (e.g.
27    /// `"github.com"`). When set, the credential callback only offers the
28    /// token when the request URL's host matches — a token configured for
29    /// host A is never sent to host B. `None` means unscoped; unscoped tokens
30    /// must not be attached to default/untrusted clone paths (see
31    /// [`crate::manager::GitManager::default_clone_options`]).
32    Token { token: String, host: Option<String> },
33    /// Use default credentials (for public repos)
34    Default,
35}
36
37impl AuthStrategy {
38    /// Whether this strategy consults **ambient** credential sources — the
39    /// running SSH agent (`ssh_key_from_agent`), the git credential helper,
40    /// or `~/.gitconfig` — rather than explicit material the caller provided.
41    ///
42    /// `Default` and `SshAgent` are ambient. `SshKey` (explicit file path),
43    /// `UserPass`, and `Token` are explicit and always honored, including
44    /// under [`crate::callback_config::AuthMode::ExplicitOnly`].
45    pub fn is_ambient(&self) -> bool {
46        matches!(self, AuthStrategy::Default | AuthStrategy::SshAgent { .. })
47    }
48}
49
50/// Git remote schemes accepted for authority-based credential scoping.
51///
52/// Anything else (`file`, `data`, an unrecognized custom scheme, ...) is
53/// rejected — [`extract_git_authority`] returns `None` and the caller fails
54/// closed rather than guessing an authority for a scheme it does not
55/// understand.
56const ALLOWED_SCHEMES: &[&str] = &["https", "http", "ssh", "git"];
57
58/// Extract the **canonical authority** from a git remote URL for host-scoping.
59///
60/// The authority is the `host[:port]` portion of the URL, canonicalized per
61/// the WHATWG URL Standard's host-parsing algorithm (via the `url` crate):
62/// - Domain names are IDNA-processed and ASCII case-folded.
63/// - IPv4 addresses (including non-canonical forms like octal/hex octets)
64///   are normalized to canonical dotted-decimal.
65/// - IPv6 literals are normalized and returned in bracketed form
66///   (`[2001:db8::cafe]`).
67/// - Default scheme ports are stripped (`:443`/`:80` for HTTPS/HTTP, `:22`
68///   for SSH, `:9418` for the git protocol); any other port is preserved.
69///
70/// **Security-critical / standards-based:** the URL is parsed structurally
71/// by [`url::Url::parse`] — the authority (scheme, userinfo, host, port) is
72/// separated from the path, query, and fragment by the same state machine
73/// browsers use, so an `@`, `/`, `?`, or `#` appearing in the path or query
74/// can never be misread as part of the authority. This closes the Sol P1
75/// path/query `@` confusion finding (#1429), which affected the previous
76/// hand-written parser.
77///
78/// `url::Url::parse` only applies IDNA/case canonicalization to the host
79/// automatically for its built-in "special" schemes (`http`/`https`); `ssh`
80/// and `git` are not "special" to the `url` crate, so their host is
81/// re-canonicalized explicitly via [`url::Host::parse`] — the same
82/// standards-based host algorithm, applied uniformly regardless of scheme.
83///
84/// **Backslash is rejected outright (fail closed), not parsed.** The WHATWG
85/// URL Standard treats `\` as equivalent to `/` within a "special" scheme
86/// (`http`/`https`), ending the authority early — but the pinned libgit2
87/// 1.9.x C parser treats `\` as an ordinary authority character and keeps
88/// splitting userinfo at the last `@`. The same input string is therefore
89/// assigned a *different* authority by this function than by the transport
90/// that actually opens the connection: `https://github.com\@evil.example/x`
91/// resolves to `github.com` here but libgit2 connects to `evil.example`.
92/// Any input containing `\` is a parser-differential attack surface, not a
93/// case this function can resolve by parsing more cleverly — it returns
94/// `None` unconditionally rather than risk agreeing with the wrong parser.
95/// See #1429 Kimi-K3 r3 P1.
96///
97/// Returns `None` for local paths (`file://`, bare paths), malformed URLs,
98/// URLs using a scheme outside [`ALLOWED_SCHEMES`], URLs containing a
99/// backslash, or URLs where the authority cannot be reliably determined.
100/// Callers must treat `None` as "authority unknown" and refuse the
101/// credential, not fall back to an unscoped release.
102///
103/// # Examples
104/// ```text
105/// https://github.com/user/repo.git        → "github.com"
106/// https://USER@github.com/user/repo.git   → "github.com"
107/// https://github.com:443/user/repo.git    → "github.com"   (default port stripped)
108/// https://github.com:8443/user/repo.git   → "github.com:8443"
109/// https://evil.example/repo@github.com    → "evil.example" (path @ ignored)
110/// ssh://git@github.com:22/user/repo.git   → "github.com"
111/// git@github.com:user/repo.git            → "github.com"   (scp-like)
112/// https://[2001:db8::cafe]/repo.git       → "[2001:db8::cafe]"
113/// https://github.com\@evil.example/x.git  → None            (backslash rejected)
114/// ```
115pub fn extract_git_authority(url: &str) -> Option<String> {
116    let trimmed = url.trim();
117    if trimmed.is_empty() {
118        return None;
119    }
120
121    // Fail closed on any backslash before doing any other parsing — see the
122    // doc comment above for the exact WHATWG-vs-libgit2 differential this
123    // closes. This must run before the scp-like/URL branch split and before
124    // `url::Url::parse`, since the differential exists regardless of which
125    // branch would otherwise handle the input.
126    if trimmed.contains('\\') {
127        return None;
128    }
129
130    if !trimmed.contains("://") {
131        return extract_scp_like_authority(trimmed);
132    }
133
134    let parsed = url::Url::parse(trimmed).ok()?;
135    let scheme = parsed.scheme();
136    if !ALLOWED_SCHEMES.contains(&scheme) {
137        return None;
138    }
139    // Reject cannot-be-a-base URLs (e.g. `mailto:`-shaped, no authority at
140    // all) up front — a scheme in ALLOWED_SCHEMES combined with `://` in the
141    // input always parses to a base URL, but guard explicitly rather than
142    // relying on that invariant.
143    if parsed.cannot_be_a_base() {
144        return None;
145    }
146    let raw_host = parsed.host_str()?;
147
148    // Re-run the raw host through the standards host-parsing algorithm
149    // unconditionally (IDNA + case-fold for domains, canonical IPv4, bracketed
150    // IPv6). `Url::parse` already did this for "special" schemes (http/https);
151    // for "non-special" git schemes (ssh/git) it left the host as an opaque,
152    // uncanonicalized string, so this step is required for those too.
153    let canonical_host = url::Host::parse(raw_host).ok()?;
154    let host_display = canonical_host.to_string();
155
156    match parsed.port() {
157        Some(port) if !is_default_port(scheme, port) => Some(format!("{host_display}:{port}")),
158        _ => Some(host_display),
159    }
160}
161
162/// Extract the canonical authority from git's scp-like remote syntax:
163/// `[user@]host:path` (no `scheme://`, e.g. `git@github.com:owner/repo.git`).
164/// This form has no port; a colon always introduces the path, never a port
165/// (`git@host:22/path` means path `22/path`, matching real git behavior).
166///
167/// The host is bounded by the **last** `@` before the first `:` — mirroring
168/// the WHATWG URL Standard's userinfo/host boundary (userinfo is everything
169/// up to the last `@`) — so an embedded `@` in a spoofed userinfo segment
170/// (`user@name@host:path`) cannot smuggle `name@host` in as the host.
171fn extract_scp_like_authority(input: &str) -> Option<String> {
172    let colon = input.find(':')?;
173    let before_colon = &input[..colon];
174    // A `/` before the first `:` means this isn't scp-like syntax at all
175    // (e.g. a bare local path containing a colon) — reject rather than guess.
176    if before_colon.contains('/') {
177        return None;
178    }
179    let at = before_colon.rfind('@')?;
180    let host = &before_colon[at + 1..];
181    if host.is_empty() {
182        return None;
183    }
184    let canonical_host = url::Host::parse(host).ok()?;
185    Some(canonical_host.to_string())
186}
187
188/// Whether a port is the default for the given scheme.
189fn is_default_port(scheme: &str, port: u16) -> bool {
190    match scheme {
191        "https" => port == 443,
192        "http" => port == 80,
193        "ssh" => port == 22,
194        "git" => port == 9418,
195        _ => false,
196    }
197}
198
199/// Credential manager for handling authentication.
200///
201/// Defaults to a **strict** security posture:
202/// - [`CertificateConfig::Strict`] — certificates are validated by libgit2
203///   against the system trust store; a cert that fails verification rejects
204///   the fetch. The previous always-`CertificateOk` behavior is gone.
205/// - [`AuthMode::ExplicitOnly`] — ambient credential discovery
206///   (`AuthStrategy::Default`, i.e. the git credential helper, `~/.gitconfig`,
207///   SSH agent fallback) is refused unless the caller explicitly opts in via
208///   [`AuthManager::with_auth_mode`]`(AllowAmbient)`.
209/// - [`RedirectPolicy::None`] — callers that build their own `git2::FetchOptions`
210///   from this manager's [`AuthManager::create_callbacks`] must also apply
211///   [`AuthManager::redirect_policy`] via [`RedirectPolicy::to_git2`] /
212///   `FetchOptions::follow_redirects`. libgit2's own default
213///   (`RemoteRedirect::Initial`) allows an off-site redirect on the initial
214///   request, and — per the pinned libgit2 1.9.x behavior — the credential
215///   callback still receives the *original* request URL after that redirect,
216///   not the effective peer. Combined with a host-scoped [`AuthStrategy::Token`],
217///   that would let a credential bound to host A be offered to a redirect
218///   target host B. See issue #1429 Sol P1.
219pub struct AuthManager {
220    strategies: Vec<AuthStrategy>,
221    certificate_mode: CertificateConfig,
222    auth_mode: AuthMode,
223    redirect_policy: RedirectPolicy,
224}
225
226impl AuthManager {
227    /// Create a new authentication manager with no strategies, strict
228    /// certificate validation, `ExplicitOnly` auth mode, and no off-site
229    /// redirects.
230    pub fn new() -> Self {
231        Self {
232            strategies: Vec::new(),
233            certificate_mode: CertificateConfig::Strict,
234            auth_mode: AuthMode::ExplicitOnly,
235            redirect_policy: RedirectPolicy::None,
236        }
237    }
238
239    /// Create authentication manager with strategies. Certificate validation
240    /// defaults to strict, auth mode to `ExplicitOnly`, and redirect policy to
241    /// no off-site redirects.
242    pub fn with_strategies(strategies: Vec<AuthStrategy>) -> Self {
243        Self {
244            strategies,
245            certificate_mode: CertificateConfig::Strict,
246            auth_mode: AuthMode::ExplicitOnly,
247            redirect_policy: RedirectPolicy::None,
248        }
249    }
250
251    /// Set the certificate validation mode.
252    pub fn with_certificate_mode(mut self, mode: CertificateConfig) -> Self {
253        self.certificate_mode = mode;
254        self
255    }
256
257    /// Set the authentication provenance mode.
258    pub fn with_auth_mode(mut self, mode: AuthMode) -> Self {
259        self.auth_mode = mode;
260        self
261    }
262
263    /// Set the off-site redirect policy. Defaults to [`RedirectPolicy::None`].
264    /// Callers driving a real `git2::FetchOptions` from this manager must
265    /// apply the result of [`AuthManager::redirect_policy`] via
266    /// `follow_redirects` — this struct only carries the *decision*; it does
267    /// not own a `FetchOptions` to enforce it against (see
268    /// [`crate::clone_options`] for the send-safe path that does).
269    pub fn with_redirect_policy(mut self, policy: RedirectPolicy) -> Self {
270        self.redirect_policy = policy;
271        self
272    }
273
274    /// Get the configured off-site redirect policy.
275    pub fn redirect_policy(&self) -> RedirectPolicy {
276        self.redirect_policy
277    }
278
279    /// Add an authentication strategy
280    pub fn add_strategy(&mut self, strategy: AuthStrategy) {
281        self.strategies.push(strategy);
282    }
283
284    /// Create remote callbacks with authentication and certificate handling.
285    ///
286    /// Security posture:
287    /// - Under `Strict` (default) the certificate callback returns
288    ///   `CertificatePassthrough`, deferring to libgit2's built-in verification.
289    ///   It never returns `CertificateOk` unconditionally, so an invalid or
290    ///   untrusted certificate fails the fetch.
291    /// - Under `ExplicitOnly` (default) `AuthStrategy::Default` is skipped, so
292    ///   ambient credential sources are not consulted.
293    pub fn create_callbacks(&self) -> RemoteCallbacks<'_> {
294        let mut callbacks = RemoteCallbacks::new();
295
296        let auth_mode = self.auth_mode;
297        callbacks.credentials(move |url, username_from_url, allowed_types| {
298            self.handle_credentials(auth_mode, url, username_from_url, allowed_types)
299        });
300
301        let cert_mode = self.certificate_mode.clone();
302        callbacks.certificate_check(move |cert, _host| Self::handle_certificate(&cert_mode, cert));
303
304        callbacks
305    }
306
307    /// Handle credential requests.
308    fn handle_credentials(
309        &self,
310        auth_mode: AuthMode,
311        url: &str,
312        username_from_url: Option<&str>,
313        allowed_types: CredentialType,
314    ) -> Result<Cred, git2::Error> {
315        info!("Attempting authentication for URL: {}", url);
316        info!("Username from URL: {:?}", username_from_url);
317        info!("Allowed credential types: {:?}", allowed_types);
318
319        // Try each strategy in order. Under ExplicitOnly, ambient strategies
320        // (AuthStrategy::Default → git credential helper / ~/.gitconfig;
321        // AuthStrategy::SshAgent → ssh-agent loaded keys) are refused so an
322        // untrusted fetch cannot silently pick up the operator's credentials.
323        for strategy in &self.strategies {
324            if matches!(auth_mode, AuthMode::ExplicitOnly) && strategy.is_ambient() {
325                debug!(
326                    "Refusing ambient strategy {:?} for {url} under ExplicitOnly auth mode",
327                    strategy
328                );
329                continue;
330            }
331            match self.try_strategy(strategy, url, username_from_url, allowed_types) {
332                Ok(cred) => {
333                    info!("Authentication successful with strategy: {:?}", strategy);
334                    return Ok(cred);
335                }
336                Err(e) => {
337                    debug!("Authentication failed with strategy {:?}: {}", strategy, e);
338                    continue;
339                }
340            }
341        }
342
343        warn!("All authentication strategies failed for {}", url);
344        if matches!(auth_mode, AuthMode::ExplicitOnly) {
345            Err(git2::Error::from_str(
346                "No suitable explicit authentication method (ambient discovery — credential \
347                 helper, ~/.gitconfig, SSH agent — refused under ExplicitOnly auth mode)",
348            ))
349        } else {
350            Err(git2::Error::from_str("No suitable authentication method"))
351        }
352    }
353
354    /// Certificate check shared between the sync and send-safe callback paths.
355    /// Delegates to [`crate::callback_config::CallbackConfig::certificate_decision`]
356    /// so the two paths cannot drift on the security boundary.
357    fn handle_certificate(
358        mode: &CertificateConfig,
359        cert: &git2::cert::Cert<'_>,
360    ) -> Result<git2::CertificateCheckStatus, git2::Error> {
361        let hostkey = cert.as_hostkey().and_then(|hk| {
362            hk.hostkey().map(|bytes| {
363                let host = std::str::from_utf8(bytes).unwrap_or("");
364                (host, bytes)
365            })
366        });
367        let status = crate::callback_config::CallbackConfig::certificate_decision(mode, hostkey)?;
368        if matches!(mode, CertificateConfig::AcceptAll) {
369            debug!(
370                "Accepting certificate unconditionally (AcceptAll mode): hostkey={:?}",
371                cert.as_hostkey().map(|h| h.hostkey())
372            );
373        }
374        Ok(status)
375    }
376
377    /// Try a specific authentication strategy
378    fn try_strategy(
379        &self,
380        strategy: &AuthStrategy,
381        url: &str,
382        username_from_url: Option<&str>,
383        allowed_types: CredentialType,
384    ) -> Result<Cred, git2::Error> {
385        match strategy {
386            AuthStrategy::SshAgent { username } => {
387                if allowed_types.contains(CredentialType::SSH_KEY) {
388                    let user = username.as_deref().or(username_from_url).unwrap_or("git");
389
390                    info!("Trying SSH key from agent for user: {}", user);
391                    Cred::ssh_key_from_agent(user)
392                } else {
393                    Err(git2::Error::from_str("SSH key not allowed"))
394                }
395            }
396
397            AuthStrategy::SshKey {
398                username,
399                public_key,
400                private_key,
401                passphrase,
402            } => {
403                if allowed_types.contains(CredentialType::SSH_KEY) {
404                    info!("Trying SSH key file: {:?}", private_key);
405                    Cred::ssh_key(
406                        username,
407                        public_key.as_deref(),
408                        private_key,
409                        passphrase.as_deref(),
410                    )
411                } else {
412                    Err(git2::Error::from_str("SSH key not allowed"))
413                }
414            }
415
416            AuthStrategy::UserPass { username, password } => {
417                if allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
418                    info!("Trying username/password authentication");
419                    Cred::userpass_plaintext(username, password)
420                } else {
421                    Err(git2::Error::from_str("Username/password not allowed"))
422                }
423            }
424
425            AuthStrategy::Token { token, host } => {
426                if !allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
427                    return Err(git2::Error::from_str("Token authentication not allowed"));
428                }
429                // Enforce authority scope: a token bound to an exact origin
430                // authority is only offered when the request URL's canonical
431                // authority matches. The authority is extracted path-safely
432                // (the path is separated before userinfo handling, so path/query
433                // `@` characters cannot spoof the authority). See #1429 Sol P1.
434                if let Some(bound) = host {
435                    match extract_git_authority(url) {
436                        Some(req_auth) if &req_auth == bound => {}
437                        Some(req_auth) => {
438                            debug!(
439                                "Refusing authority-scoped token for {url}: bound to \
440                                 {bound:?}, request authority is {req_auth:?}"
441                            );
442                            return Err(git2::Error::from_str(
443                                "Token is scoped to a different authority",
444                            ));
445                        }
446                        None => {
447                            debug!(
448                                "Refusing authority-scoped token for {url}: could not parse \
449                                 authority"
450                            );
451                            return Err(git2::Error::from_str(
452                                "Token is authority-scoped but request URL is unparseable",
453                            ));
454                        }
455                    }
456                }
457                info!("Trying token authentication");
458                // For GitHub and similar services, use token as password with empty username
459                Cred::userpass_plaintext("", token)
460            }
461
462            AuthStrategy::Default => {
463                if allowed_types.contains(CredentialType::DEFAULT) {
464                    info!("Trying default credentials");
465                    Cred::default()
466                } else {
467                    Err(git2::Error::from_str("Default credentials not allowed"))
468                }
469            }
470        }
471    }
472
473    /// Get the number of configured strategies (for testing)
474    pub fn strategy_count(&self) -> usize {
475        self.strategies.len()
476    }
477
478    /// Get the configured certificate validation mode.
479    pub fn certificate_mode(&self) -> CertificateConfig {
480        self.certificate_mode.clone()
481    }
482
483    /// Get the configured authentication provenance mode.
484    pub fn auth_mode(&self) -> AuthMode {
485        self.auth_mode
486    }
487
488    /// Get the strategies (for testing)
489    #[cfg(test)]
490    pub fn strategies(&self) -> &[AuthStrategy] {
491        &self.strategies
492    }
493}
494
495impl Default for AuthManager {
496    fn default() -> Self {
497        Self::new()
498    }
499}
500
501/// Builder for creating authentication strategies
502pub struct AuthBuilder {
503    strategies: Vec<AuthStrategy>,
504}
505
506impl AuthBuilder {
507    /// Create a new auth builder
508    pub fn new() -> Self {
509        Self {
510            strategies: Vec::new(),
511        }
512    }
513
514    /// Add SSH agent authentication
515    pub fn ssh_agent(mut self, username: Option<String>) -> Self {
516        self.strategies.push(AuthStrategy::SshAgent { username });
517        self
518    }
519
520    /// Add SSH key file authentication
521    pub fn ssh_key<U, P>(
522        mut self,
523        username: U,
524        public_key: Option<PathBuf>,
525        private_key: P,
526        passphrase: Option<String>,
527    ) -> Self
528    where
529        U: Into<String>,
530        P: Into<PathBuf>,
531    {
532        self.strategies.push(AuthStrategy::SshKey {
533            username: username.into(),
534            public_key,
535            private_key: private_key.into(),
536            passphrase,
537        });
538        self
539    }
540
541    /// Add username/password authentication
542    pub fn userpass<U, P>(mut self, username: U, password: P) -> Self
543    where
544        U: Into<String>,
545        P: Into<String>,
546    {
547        self.strategies.push(AuthStrategy::UserPass {
548            username: username.into(),
549            password: password.into(),
550        });
551        self
552    }
553
554    /// Add token authentication **without** an authority binding.
555    ///
556    /// **Warning:** an unscoped token is offered to ANY remote that challenges
557    /// for `USER_PASS_PLAINTEXT`. This is an explicit trusted-caller opt-in —
558    /// callers must understand the credential-exfiltration implications.
559    /// Prefer [`AuthBuilder::token_scoped`] which binds the token to an exact
560    /// origin authority.
561    pub fn token_unscoped<T>(mut self, token: T) -> Self
562    where
563        T: Into<String>,
564    {
565        self.strategies.push(AuthStrategy::Token {
566            token: token.into(),
567            host: None,
568        });
569        self
570    }
571
572    /// Add token authentication bound to an exact origin host. The token is
573    /// only offered when the request URL's host matches `host`.
574    pub fn token_scoped<T, H>(mut self, token: T, host: H) -> Self
575    where
576        T: Into<String>,
577        H: Into<String>,
578    {
579        self.strategies.push(AuthStrategy::Token {
580            token: token.into(),
581            host: Some(host.into()),
582        });
583        self
584    }
585
586    /// Add default credentials (fallback). Maps to libgit2's ambient credential
587    /// discovery (git credential helper, `~/.gitconfig`, SSH agent fallback).
588    /// Only honored when the `AuthManager` is built with
589    /// [`AuthMode::AllowAmbient`]; under the default `ExplicitOnly` mode this
590    /// strategy is refused at resolution time.
591    pub fn default_fallback(mut self) -> Self {
592        self.strategies.push(AuthStrategy::Default);
593        self
594    }
595
596    /// Build the authentication manager (strict certs, `ExplicitOnly` auth).
597    pub fn build(self) -> AuthManager {
598        AuthManager::with_strategies(self.strategies)
599    }
600}
601
602impl Default for AuthBuilder {
603    fn default() -> Self {
604        Self::new()
605    }
606}
607
608/// Helper function to create common authentication configurations.
609///
610/// Presets that include ambient discovery (`AuthStrategy::Default`) opt into
611/// [`AuthMode::AllowAmbient`] explicitly, since their purpose is operator-style
612/// access to first-party/trusted remotes. The strict certificate default is
613/// preserved in every preset.
614pub mod presets {
615    use super::*;
616
617    /// Standard SSH configuration (agent + ambient fallback). Opts into
618    /// `AllowAmbient` because the ambient fallback is the explicit intent.
619    pub fn ssh_standard() -> AuthManager {
620        AuthBuilder::new()
621            .ssh_agent(Some("git".to_owned()))
622            .default_fallback()
623            .build()
624            .with_auth_mode(AuthMode::AllowAmbient)
625    }
626
627    /// GitHub personal access token scoped to the canonical `github.com`
628    /// authority, with SSH-agent and ambient fallback.
629    pub fn github_token<T: Into<String>>(token: T) -> AuthManager {
630        AuthBuilder::new()
631            .token_scoped(token, "github.com")
632            .ssh_agent(Some("git".to_owned()))
633            .default_fallback()
634            .build()
635            .with_auth_mode(AuthMode::AllowAmbient)
636    }
637
638    /// SSH key file authentication with agent and ambient fallback.
639    pub fn ssh_key_file<U, P>(
640        username: U,
641        private_key: P,
642        passphrase: Option<String>,
643    ) -> AuthManager
644    where
645        U: Into<String>,
646        P: Into<PathBuf>,
647    {
648        AuthBuilder::new()
649            .ssh_key(username, None, private_key, passphrase)
650            .ssh_agent(Some("git".to_owned()))
651            .default_fallback()
652            .build()
653            .with_auth_mode(AuthMode::AllowAmbient)
654    }
655
656    /// Public repository access via ambient discovery only. Opts into
657    /// `AllowAmbient`.
658    pub fn public_only() -> AuthManager {
659        AuthBuilder::new()
660            .default_fallback()
661            .build()
662            .with_auth_mode(AuthMode::AllowAmbient)
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    #[test]
671    fn test_auth_builder() {
672        let auth = AuthBuilder::new()
673            .ssh_agent(Some("git".to_owned()))
674            .token_unscoped("ghp_test_token")
675            .default_fallback()
676            .build();
677
678        assert_eq!(auth.strategies.len(), 3);
679    }
680
681    #[test]
682    fn test_presets() {
683        let ssh_auth = presets::ssh_standard();
684        assert_eq!(ssh_auth.strategies.len(), 2);
685
686        let github_auth = presets::github_token("test_token");
687        assert_eq!(github_auth.strategies.len(), 3);
688
689        let public_auth = presets::public_only();
690        assert_eq!(public_auth.strategies.len(), 1);
691    }
692
693    #[test]
694    fn auth_manager_builder_chains_modes() {
695        let mgr = AuthManager::with_strategies(vec![AuthStrategy::Token {
696            token: "t".into(),
697            host: None,
698        }])
699        .with_certificate_mode(CertificateConfig::AcceptAll)
700        .with_auth_mode(AuthMode::AllowAmbient);
701        assert!(matches!(
702            mgr.certificate_mode(),
703            CertificateConfig::AcceptAll
704        ));
705        assert_eq!(mgr.auth_mode(), AuthMode::AllowAmbient);
706    }
707
708    /// The credentials callback under ExplicitOnly must refuse the Default
709    /// strategy even though it is present in the strategy list (ambient
710    /// discovery never consulted). Mirrors the callback_config unit test but
711    /// exercises the AuthManager (sync) path.
712    #[test]
713    fn auth_manager_explicit_only_refuses_default() {
714        let mgr = AuthManager::with_strategies(vec![AuthStrategy::Default]);
715        // allowed_types includes DEFAULT, so the only reason to fail is the
716        // ExplicitOnly refusal of the ambient Default strategy.
717        let res = mgr.handle_credentials(
718            AuthMode::ExplicitOnly,
719            "https://example.com/repo.git",
720            None,
721            CredentialType::DEFAULT,
722        );
723        assert!(res.is_err());
724    }
725
726    #[test]
727    fn extract_git_authority_parses_common_url_forms() {
728        assert_eq!(
729            extract_git_authority("https://github.com/user/repo.git"),
730            Some("github.com".to_owned())
731        );
732        assert_eq!(
733            extract_git_authority("https://user@github.com/user/repo.git"),
734            Some("github.com".to_owned())
735        );
736        assert_eq!(
737            extract_git_authority("ssh://git@github.com:22/user/repo.git"),
738            Some("github.com".to_owned()) // default SSH port stripped
739        );
740        assert_eq!(
741            extract_git_authority("git@github.com:user/repo.git"),
742            Some("github.com".to_owned())
743        );
744        assert_eq!(
745            extract_git_authority("https://huggingface.co/Qwen/Qwen3"),
746            Some("huggingface.co".to_owned())
747        );
748    }
749
750    #[test]
751    fn extract_git_authority_rejects_local_and_unparseable() {
752        assert_eq!(extract_git_authority("file:///path/to/repo"), None);
753        assert_eq!(extract_git_authority("/local/path"), None);
754        assert_eq!(extract_git_authority("not-a-url"), None);
755    }
756
757    #[test]
758    fn extract_git_authority_path_at_does_not_spoof() {
759        // The critical P1 fix: @ in the path must NOT be treated as userinfo.
760        assert_eq!(
761            extract_git_authority("https://evil.example/repo@github.com/owned.git"),
762            Some("evil.example".to_owned())
763        );
764        assert_eq!(
765            extract_git_authority("https://evil.example/repo?x=@github.com"),
766            Some("evil.example".to_owned())
767        );
768    }
769
770    #[test]
771    fn extract_git_authority_normalizes_case_and_ports() {
772        assert_eq!(
773            extract_git_authority("https://GitHub.COM/user/repo.git"),
774            Some("github.com".to_owned()) // case normalized
775        );
776        assert_eq!(
777            extract_git_authority("https://github.com:443/user/repo.git"),
778            Some("github.com".to_owned()) // default HTTPS port stripped
779        );
780        assert_eq!(
781            extract_git_authority("https://github.com:8443/user/repo.git"),
782            Some("github.com:8443".to_owned()) // non-default port preserved
783        );
784    }
785
786    #[test]
787    fn extract_git_authority_handles_ipv6() {
788        assert_eq!(
789            extract_git_authority("https://[2001:db8::1]/repo.git"),
790            Some("[2001:db8::1]".to_owned())
791        );
792        assert_eq!(
793            extract_git_authority("https://[2001:db8::1]:8443/repo.git"),
794            Some("[2001:db8::1]:8443".to_owned())
795        );
796    }
797
798    /// IPv6 authority is also canonicalized for the non-"special" `ssh`
799    /// scheme, where `url::Url::parse` does not canonicalize automatically —
800    /// proving the explicit `Host::parse` re-canonicalization step is load-bearing.
801    #[test]
802    fn extract_git_authority_handles_ipv6_over_ssh() {
803        assert_eq!(
804            extract_git_authority("ssh://git@[2001:DB8::1]:22/repo.git"),
805            Some("[2001:db8::1]".to_owned()) // default SSH port stripped, hex lowercased
806        );
807    }
808
809    /// IPv4 literals are canonicalized to dotted-decimal, including
810    /// non-canonical numeric forms (octal/hex octets) that could otherwise be
811    /// used to make two textually different authorities resolve to the same
812    /// address and evade a naive string comparison.
813    #[test]
814    fn extract_git_authority_canonicalizes_ipv4() {
815        assert_eq!(
816            extract_git_authority("https://192.168.1.1/repo.git"),
817            Some("192.168.1.1".to_owned())
818        );
819        // Octal-looking octet (leading zero) canonicalizes to the same
820        // decimal address per the WHATWG IPv4 parser.
821        assert_eq!(
822            extract_git_authority("https://192.168.1.001/repo.git"),
823            Some("192.168.1.1".to_owned())
824        );
825        assert_eq!(
826            extract_git_authority("git@192.168.1.1:owner/repo.git"),
827            Some("192.168.1.1".to_owned())
828        );
829    }
830
831    /// A port that is the ssh/git default but NOT the https/http default (or
832    /// vice versa) must be scoped per the URL's own scheme, never treated as
833    /// "default" merely because it matches a *different* scheme's default.
834    /// This specifically covers GitHub's real-world "SSH over port 443"
835    /// endpoint, which must not collide with the https:443 default.
836    #[test]
837    fn extract_git_authority_scopes_default_port_per_scheme() {
838        assert_eq!(
839            extract_git_authority("ssh://git@ssh.github.com:443/owner/repo.git"),
840            Some("ssh.github.com:443".to_owned()), // 443 is NOT the ssh default
841        );
842        assert_eq!(
843            extract_git_authority("ssh://git@github.com:22/owner/repo.git"),
844            Some("github.com".to_owned()), // 22 IS the ssh default
845        );
846        assert_eq!(
847            extract_git_authority("git://github.com:9418/owner/repo.git"),
848            Some("github.com".to_owned()), // 9418 is the git:// default
849        );
850        assert_eq!(
851            extract_git_authority("git://github.com:9419/owner/repo.git"),
852            Some("github.com:9419".to_owned()),
853        );
854    }
855
856    /// IDNA: two different Unicode case/normalization variants of the same
857    /// domain must canonicalize to the identical authority string (and to
858    /// ASCII punycode, not raw Unicode), so a lookalike-case Unicode domain
859    /// cannot bypass a string-equality host-scope check.
860    #[test]
861    fn extract_git_authority_normalizes_idna() {
862        let lower = extract_git_authority("https://münchen.example/repo.git");
863        let upper = extract_git_authority("https://MÜNCHEN.example/repo.git");
864        assert_eq!(lower, upper, "IDNA case folding must be applied uniformly");
865        assert!(
866            matches!(&lower, Some(host) if host.starts_with("xn--")),
867            "domain must be canonicalized to ASCII punycode, got {lower:?}",
868        );
869
870        // Same requirement over the non-"special" ssh scheme, where
871        // `url::Url::parse` alone would NOT apply IDNA — proving the explicit
872        // re-canonicalization step covers this scheme too.
873        let ssh_lower = extract_git_authority("ssh://git@münchen.example/repo.git");
874        let ssh_upper = extract_git_authority("ssh://git@MÜNCHEN.example/repo.git");
875        assert!(ssh_lower.is_some());
876        assert_eq!(ssh_lower, ssh_upper);
877        assert_eq!(
878            lower, ssh_lower,
879            "https and ssh must canonicalize identically"
880        );
881    }
882
883    /// Malformed authorities are rejected outright (`None`) rather than
884    /// silently truncated or misparsed into something that could
885    /// accidentally match a configured bound host.
886    #[test]
887    fn extract_git_authority_rejects_malformed() {
888        // Non-numeric port.
889        assert_eq!(
890            extract_git_authority("https://github.com:notaport/repo.git"),
891            None
892        );
893        // Unterminated IPv6 bracket.
894        assert_eq!(extract_git_authority("https://[2001:db8::1/repo.git"), None);
895        // Empty host: for a "non-special" git scheme (ssh/git) three slashes
896        // after the scheme yield a genuinely empty authority (unlike https,
897        // where WHATWG's "special authority ignore slashes" leniency would
898        // otherwise make the following path segment look like a host).
899        assert_eq!(extract_git_authority("ssh:///repo.git"), None);
900        assert_eq!(extract_git_authority("git:///repo.git"), None);
901        // Empty string / whitespace only.
902        assert_eq!(extract_git_authority(""), None);
903        assert_eq!(extract_git_authority("   "), None);
904    }
905
906    /// A scheme outside the git-relevant allowlist is rejected even though
907    /// `url::Url::parse` would happily parse it — an unrecognized scheme must
908    /// fail closed rather than be guessed to share an authority scope.
909    #[test]
910    fn extract_git_authority_rejects_disallowed_scheme() {
911        assert_eq!(extract_git_authority("ftp://github.com/repo.git"), None);
912        assert_eq!(
913            extract_git_authority("javascript://github.com/repo.git"),
914            None
915        );
916        assert_eq!(
917            extract_git_authority("mailto:git@github.com"),
918            None,
919            "cannot-be-a-base URLs must never resolve to an authority"
920        );
921    }
922
923    /// Fragment `#` must terminate the authority exactly like `/` and `?` —
924    /// an `@` after `#` must not be read as authority userinfo.
925    #[test]
926    fn extract_git_authority_fragment_at_does_not_spoof() {
927        assert_eq!(
928            extract_git_authority("https://evil.example/repo.git#@github.com"),
929            Some("evil.example".to_owned())
930        );
931    }
932
933    /// The classic human-misreading authority-confusion form: a full hostname
934    /// used as *userinfo* immediately before the real (attacker) host. Unlike
935    /// the path/query cases above, this is not a parser bug — the real
936    /// network authority genuinely is `evil.example`, and the parser must
937    /// report that faithfully so the caller's scope check refuses it.
938    #[test]
939    fn extract_git_authority_userinfo_lookalike_resolves_to_real_host() {
940        assert_eq!(
941            extract_git_authority("https://github.com@evil.example/repo.git"),
942            Some("evil.example".to_owned())
943        );
944    }
945
946    /// scp-like syntax: an embedded `@` within what looks like userinfo must
947    /// not smuggle a trailing `@host` segment in as the host — the host is
948    /// bounded by the LAST `@` before the first `:`, mirroring URL userinfo
949    /// semantics.
950    #[test]
951    fn extract_scp_like_authority_rejects_embedded_at_ambiguity() {
952        assert_eq!(
953            extract_git_authority("user@name@github.com:owner/repo.git"),
954            Some("github.com".to_owned())
955        );
956    }
957
958    /// scp-like syntax requires an explicit `user@`; a bare `host:path` with
959    /// no `@` and no `://` is not accepted (fails closed rather than
960    /// guessing this is scp-like syntax vs. an unrelated colon-bearing path).
961    #[test]
962    fn extract_scp_like_authority_requires_at_sign() {
963        assert_eq!(extract_git_authority("github.com:owner/repo.git"), None);
964    }
965
966    // ---- Backslash: WHATWG-vs-libgit2 authority differential (#1429 r3 P1) ----
967
968    /// The exact differential the r3 review causally proved against the real
969    /// pinned libgit2 stack: for a "special" scheme, WHATWG (`url::Url::parse`)
970    /// treats `\` as ending the authority early, resolving to `github.com` —
971    /// but libgit2's own C parser treats `\` as an ordinary authority
972    /// character and splits userinfo at the last `@`, resolving to
973    /// `evil.example`. Because the two parsers disagree on what the
974    /// authority even is, the function must refuse to answer at all.
975    #[test]
976    fn extract_git_authority_rejects_backslash_differential() {
977        assert_eq!(
978            extract_git_authority("https://github.com\\@evil.example/repo.git"),
979            None,
980            "a backslash-containing authority is a WHATWG/libgit2 parser \
981             differential and must fail closed, not resolve to either parser's answer",
982        );
983    }
984
985    /// Backslash is rejected regardless of scheme or position — this is not
986    /// specific to the `https` special-scheme case above.
987    #[test]
988    fn extract_git_authority_rejects_backslash_anywhere() {
989        assert_eq!(extract_git_authority("ssh://git@github.com\\evil/x"), None);
990        assert_eq!(
991            extract_git_authority("https://evil.example/\\@github.com"),
992            None
993        );
994        assert_eq!(
995            extract_git_authority("http://github.com\\.evil.example/x"),
996            None
997        );
998    }
999
1000    /// scp-like syntax is covered by the same top-level guard: a backslash
1001    /// anywhere in scp-like input is rejected before the `@`/`:` boundary
1002    /// logic ever runs.
1003    #[test]
1004    fn extract_git_authority_rejects_backslash_in_scp_like() {
1005        assert_eq!(
1006            extract_git_authority("git@github.com\\evil.example:owner/repo.git"),
1007            None
1008        );
1009    }
1010}