git2db/callback_config.rs
1//! Send-safe callback configuration for async git operations
2//!
3//! This module provides a bridge between git2's non-Send callbacks and async/Send requirements.
4//! Instead of holding closures directly, we capture the configuration needed to create them.
5
6use crate::auth::AuthStrategy;
7use git2::cert::Cert;
8use std::sync::Arc;
9
10/// Progress reporting configuration
11#[derive(Clone, Default)]
12pub enum ProgressConfig {
13 /// No progress reporting
14 #[default]
15 None,
16 /// Simple progress to stdout
17 Stdout,
18 /// Progress via channel (Send-safe)
19 Channel(Arc<dyn ProgressReporter>),
20}
21
22impl std::fmt::Debug for ProgressConfig {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 match self {
25 Self::None => write!(f, "None"),
26 Self::Stdout => write!(f, "Stdout"),
27 Self::Channel(_) => write!(f, "Channel(<custom>)"),
28 }
29 }
30}
31
32/// Trait for Send-safe progress reporting
33pub trait ProgressReporter: Send + Sync {
34 fn report(&self, stage: &str, current: usize, total: usize);
35}
36
37/// Certificate validation configuration.
38///
39/// Controls how the TLS/SSH host-key certificate check is handled during a
40/// network git operation. The default is [`CertificateConfig::Strict`], which
41/// defers to libgit2's built-in validation against the system trust store and
42/// **rejects on certificate failure**. This is the only acceptable mode for
43/// untrusted or forge-facing fetches (the merge gate's PR-head fetch, P2P
44/// distribution, etc.).
45///
46/// `AcceptAll` is an explicit, insecure opt-in reserved for tests/operator
47/// bootstrapping where the transport is otherwise authenticated. It must never
48/// be the default for a code path that fetches from an untrusted origin.
49#[derive(Debug, Clone, Default)]
50pub enum CertificateConfig {
51 /// Strict validation: defer to libgit2's built-in certificate verification
52 /// (system CA store for HTTPS, `known_hosts` for SSH) and reject on
53 /// failure. This is the secure default.
54 ///
55 /// Implemented by returning [`git2::CertificateCheckStatus::CertificatePassthrough`]
56 /// from the certificate callback, which signals "no application decision —
57 /// use libgit2's result". libgit2 then applies its strict default: an
58 /// untrusted CA, expired leaf, or hostname mismatch fails the fetch.
59 #[default]
60 Strict,
61 /// Accept every certificate without validation. **Insecure.**
62 ///
63 /// Explicit opt-in only. Appropriate for unit tests against a local
64 /// self-signed server, or operator bootstrapping over an already-trusted
65 /// transport. The untrusted/forge default must never select this mode.
66 AcceptAll,
67 /// Custom validation against a set of pinned host fingerprints.
68 Pinned(Vec<CertificatePinning>),
69}
70
71/// Authentication provenance mode — whether ambient credential sources may be
72/// consulted.
73///
74/// `ExplicitOnly` (the default) refuses ambient strategies —
75/// [`AuthStrategy::Default`] (git credential helper, `~/.gitconfig`) **and**
76/// [`AuthStrategy::SshAgent`] (the running SSH agent's loaded keys). This
77/// prevents an untrusted fetch from silently picking up the operator's personal
78/// credentials via `Cred::ssh_key_from_agent` or `Cred::default`. Explicit
79/// strategies (`SshKey` file, `UserPass`, `Token`) are always honored. Callers
80/// that intentionally want ambient discovery (e.g. a trusted first-party mirror
81/// clone driven by the operator's own identity) must explicitly opt in via
82/// [`AuthMode::AllowAmbient`].
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum AuthMode {
85 /// Only explicit authentication strategies are honored.
86 /// Ambient strategies ([`AuthStrategy::Default`], [`AuthStrategy::SshAgent`])
87 /// are rejected, so the credential helper, `~/.gitconfig`, and the SSH
88 /// agent are never consulted. Secure default for untrusted/forge-facing
89 /// fetches.
90 #[default]
91 ExplicitOnly,
92 /// Permit ambient credential discovery via [`AuthStrategy::Default`] and
93 /// [`AuthStrategy::SshAgent`]. Opt-in for trusted first-party mirrors
94 /// where operator identity is expected.
95 AllowAmbient,
96}
97
98/// Certificate pinning configuration
99#[derive(Debug, Clone)]
100pub struct CertificatePinning {
101 pub host: String,
102 pub fingerprint: Vec<u8>,
103}
104
105/// Off-site redirect policy for credential-bearing git operations.
106///
107/// libgit2's default (`Initial`) allows an off-site redirect on the initial
108/// request. Since the credential callback receives the *original* URL (not the
109/// redirect target) in the pinned libgit2 1.9.x, this means a token bound to
110/// host A can be offered to a redirect target host B (Sol P1 #1429). The
111/// secure default is [`RedirectPolicy::None`] — no off-site redirects.
112#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
113pub enum RedirectPolicy {
114 /// Do not follow any off-site redirects at any stage. **Secure default.**
115 /// Same-authority redirects (e.g. path changes on the same host) may still
116 /// be followed by the transport.
117 #[default]
118 None,
119 /// Follow off-site redirects on the initial request only (libgit2's
120 /// default). **Insecure with host-scoped credentials** — the credential
121 /// callback cannot verify the effective peer after redirect.
122 Initial,
123}
124
125impl RedirectPolicy {
126 /// Convert to the `git2` crate's redirect type.
127 pub fn to_git2(self) -> git2::RemoteRedirect {
128 match self {
129 RedirectPolicy::None => git2::RemoteRedirect::None,
130 RedirectPolicy::Initial => git2::RemoteRedirect::Initial,
131 }
132 }
133}
134
135/// Send-safe callback configuration
136///
137/// This type captures the *configuration* for callbacks rather than the callbacks themselves.
138/// It can be safely sent across threads and used to create the actual callbacks when needed.
139#[derive(Debug, Clone, Default)]
140pub struct CallbackConfig {
141 /// Authentication strategies to try
142 pub auth: Vec<AuthStrategy>,
143
144 /// Whether ambient credential sources (`AuthStrategy::Default`) may be
145 /// consulted. Defaults to [`AuthMode::ExplicitOnly`].
146 pub auth_mode: AuthMode,
147
148 /// Progress reporting configuration
149 pub progress: ProgressConfig,
150
151 /// Certificate validation configuration
152 pub certificates: CertificateConfig,
153
154 /// Off-site redirect policy. Defaults to [`RedirectPolicy::None`] (no
155 /// off-site redirects) to prevent credential exfiltration via redirect
156 /// when host-scoped credentials are present.
157 pub redirect_policy: RedirectPolicy,
158
159 /// Pack progress reporting
160 pub pack_progress: bool,
161
162 /// Push update reference callback enabled
163 pub push_update_reference: bool,
164}
165
166impl CallbackConfig {
167 /// Create a new callback configuration
168 pub fn new() -> Self {
169 Self::default()
170 }
171
172 /// Builder-style method to add authentication
173 pub fn with_auth(mut self, strategy: AuthStrategy) -> Self {
174 self.auth.push(strategy);
175 self
176 }
177
178 /// Builder-style method to set the authentication provenance mode.
179 pub fn with_auth_mode(mut self, mode: AuthMode) -> Self {
180 self.auth_mode = mode;
181 self
182 }
183
184 /// Builder-style method to set progress reporting
185 pub fn with_progress(mut self, progress: ProgressConfig) -> Self {
186 self.progress = progress;
187 self
188 }
189
190 /// Builder-style method to set certificate validation
191 pub fn with_certificates(mut self, certs: CertificateConfig) -> Self {
192 self.certificates = certs;
193 self
194 }
195
196 /// Extract the progress reporter (if using Channel config)
197 pub fn progress_reporter(&self) -> Option<Arc<dyn ProgressReporter>> {
198 match &self.progress {
199 ProgressConfig::Channel(reporter) => Some(Arc::clone(reporter)),
200 _ => None,
201 }
202 }
203
204 /// Create actual git2::RemoteCallbacks from this configuration
205 ///
206 /// This is called within spawn_blocking where non-Send is acceptable
207 pub fn create_callbacks(&self) -> git2::RemoteCallbacks<'_> {
208 let mut callbacks = git2::RemoteCallbacks::new();
209
210 // Set up authentication. Always install the credentials callback so
211 // that AuthMode is enforced even when no explicit strategy is provided:
212 // ExplicitOnly must refuse ambient discovery rather than silently fall
213 // through to libgit2's default credential helper.
214 let auth_strategies = self.auth.clone();
215 let auth_mode = self.auth_mode;
216 callbacks.credentials(move |url, username_from_url, allowed_types| {
217 Self::handle_auth(
218 &auth_strategies,
219 auth_mode,
220 url,
221 username_from_url,
222 allowed_types,
223 )
224 });
225
226 // Set up certificate checking. Strict (the default) defers to libgit2's
227 // built-in verification via CertificatePassthrough; it does NOT return
228 // CertificateOk, so a cert that fails system trust is rejected.
229 let cert_config = self.certificates.clone();
230 callbacks
231 .certificate_check(move |cert, _host| Self::handle_certificate(&cert_config, cert));
232
233 // Set up progress if configured
234 if !matches!(self.progress, ProgressConfig::None) {
235 let progress_config = self.progress.clone();
236 callbacks.transfer_progress(move |stats| {
237 Self::handle_progress(&progress_config, stats);
238 true
239 });
240 }
241
242 callbacks
243 }
244
245 fn handle_auth(
246 strategies: &[AuthStrategy],
247 auth_mode: AuthMode,
248 url: &str,
249 username_from_url: Option<&str>,
250 allowed_types: git2::CredentialType,
251 ) -> Result<git2::Cred, git2::Error> {
252 // Try each strategy in order. Under ExplicitOnly, ambient strategies
253 // (AuthStrategy::Default → git credential helper / ~/.gitconfig;
254 // AuthStrategy::SshAgent → ssh-agent loaded keys) are refused so an
255 // untrusted fetch cannot silently pick up the operator's credentials.
256 // Explicit strategies (SshKey file, UserPass, Token) are always honored.
257 for strategy in strategies {
258 if matches!(auth_mode, AuthMode::ExplicitOnly) && strategy.is_ambient() {
259 tracing::debug!(
260 "Refusing ambient strategy {:?} for {url} under ExplicitOnly auth mode",
261 strategy
262 );
263 continue;
264 }
265 match Self::try_auth_strategy(strategy, url, username_from_url, allowed_types) {
266 Ok(cred) => return Ok(cred),
267 Err(_) => continue,
268 }
269 }
270
271 if matches!(auth_mode, AuthMode::ExplicitOnly) {
272 Err(git2::Error::from_str(
273 "No suitable explicit authentication method (ambient discovery — credential \
274 helper, ~/.gitconfig, SSH agent — refused under ExplicitOnly auth mode)",
275 ))
276 } else {
277 Err(git2::Error::from_str("No suitable authentication method"))
278 }
279 }
280
281 fn try_auth_strategy(
282 strategy: &AuthStrategy,
283 url: &str,
284 username_from_url: Option<&str>,
285 allowed_types: git2::CredentialType,
286 ) -> Result<git2::Cred, git2::Error> {
287 use git2::{Cred, CredentialType};
288
289 match strategy {
290 AuthStrategy::SshAgent { username } => {
291 if allowed_types.contains(CredentialType::SSH_KEY) {
292 let user = username.as_deref().or(username_from_url).unwrap_or("git");
293 Cred::ssh_key_from_agent(user)
294 } else {
295 Err(git2::Error::from_str("SSH key not allowed"))
296 }
297 }
298 AuthStrategy::SshKey {
299 username,
300 public_key,
301 private_key,
302 passphrase,
303 } => {
304 if allowed_types.contains(CredentialType::SSH_KEY) {
305 Cred::ssh_key(
306 username,
307 public_key.as_deref(),
308 private_key,
309 passphrase.as_deref(),
310 )
311 } else {
312 Err(git2::Error::from_str("SSH key not allowed"))
313 }
314 }
315 AuthStrategy::UserPass { username, password } => {
316 if allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
317 Cred::userpass_plaintext(username, password)
318 } else {
319 Err(git2::Error::from_str("Username/password not allowed"))
320 }
321 }
322 AuthStrategy::Token { token, host } => {
323 if !allowed_types.contains(CredentialType::USER_PASS_PLAINTEXT) {
324 return Err(git2::Error::from_str("Token authentication not allowed"));
325 }
326 // Enforce authority scope (issue #1429 Sol P1): the authority
327 // is extracted path-safely and canonicalized, preventing
328 // path/query `@` spoofing, case confusion, port confusion,
329 // and IPv6 truncation.
330 if let Some(bound) = host {
331 match crate::auth::extract_git_authority(url) {
332 Some(req_auth) if req_auth == *bound => {}
333 Some(req_auth) => {
334 tracing::debug!(
335 "Refusing authority-scoped token for {url}: bound to \
336 {bound:?}, request authority is {req_auth:?}"
337 );
338 return Err(git2::Error::from_str(
339 "Token is scoped to a different authority",
340 ));
341 }
342 None => {
343 tracing::debug!(
344 "Refusing authority-scoped token for {url}: could not parse \
345 authority"
346 );
347 return Err(git2::Error::from_str(
348 "Token is authority-scoped but request URL is unparseable",
349 ));
350 }
351 }
352 }
353 Cred::userpass_plaintext("", token)
354 }
355 AuthStrategy::Default => {
356 if allowed_types.contains(CredentialType::DEFAULT) {
357 Cred::default()
358 } else {
359 Err(git2::Error::from_str("Default credentials not allowed"))
360 }
361 }
362 }
363 }
364
365 fn handle_certificate(
366 config: &CertificateConfig,
367 cert: &Cert<'_>,
368 ) -> Result<git2::CertificateCheckStatus, git2::Error> {
369 // Extract the hostkey material once; the decision itself is a pure
370 // function of (mode, hostkey) and is tested directly.
371 let hostkey = cert.as_hostkey().and_then(|hk| {
372 hk.hostkey().map(|bytes| {
373 let host = std::str::from_utf8(bytes).unwrap_or("");
374 (host, bytes)
375 })
376 });
377 Self::certificate_decision(config, hostkey)
378 }
379
380 /// Pure certificate decision, separated from FFI cert inspection so the
381 /// security boundary is unit-testable without a live TLS connection.
382 ///
383 /// - [`CertificateConfig::Strict`] returns `CertificatePassthrough`, which
384 /// tells libgit2 to apply its built-in verification and **reject on
385 /// failure**. It never returns `CertificateOk`.
386 /// - [`CertificateConfig::AcceptAll`] returns `CertificateOk` — the
387 /// explicit, insecure opt-in.
388 /// - [`CertificateConfig::Pinned`] returns `Ok` only when the resolved
389 /// hostkey matches a pin, otherwise rejects. Never falls back to
390 /// `AcceptAll`.
391 pub fn certificate_decision(
392 mode: &CertificateConfig,
393 hostkey: Option<(&str, &[u8])>,
394 ) -> Result<git2::CertificateCheckStatus, git2::Error> {
395 use git2::CertificateCheckStatus;
396 match mode {
397 CertificateConfig::Strict => Ok(CertificateCheckStatus::CertificatePassthrough),
398 CertificateConfig::AcceptAll => Ok(CertificateCheckStatus::CertificateOk),
399 CertificateConfig::Pinned(pins) => {
400 if let Some((host, key_bytes)) = hostkey {
401 for pin in pins {
402 if pin.host == host && pin.fingerprint.as_slice() == key_bytes {
403 return Ok(CertificateCheckStatus::CertificateOk);
404 }
405 }
406 }
407 Err(git2::Error::from_str(
408 "Certificate does not match any pinned fingerprint",
409 ))
410 }
411 }
412 }
413
414 fn handle_progress(config: &ProgressConfig, stats: git2::Progress<'_>) {
415 // Determine stage and progress based on git2::Progress stats
416 // Clone phases: fetch objects → index deltas → (checkout handled separately)
417 let (stage, current, total) = if stats.indexed_deltas() > 0 && stats.total_deltas() > 0 {
418 // Indexing deltas phase
419 ("indexing", stats.indexed_deltas(), stats.total_deltas())
420 } else if stats.indexed_objects() > 0
421 && stats.indexed_objects() > stats.received_objects() / 2
422 {
423 // Indexing objects phase (when most objects received)
424 ("indexing", stats.indexed_objects(), stats.total_objects())
425 } else {
426 // Fetching objects phase
427 ("fetch", stats.received_objects(), stats.total_objects())
428 };
429
430 match config {
431 ProgressConfig::None => {}
432 ProgressConfig::Stdout => {
433 tracing::info!("Progress [{stage}]: {current}/{total}");
434 }
435 ProgressConfig::Channel(reporter) => {
436 reporter.report(stage, current, total);
437 }
438 }
439 }
440}
441
442/// Builder for callback configuration
443pub struct CallbackConfigBuilder {
444 config: CallbackConfig,
445}
446
447impl Default for CallbackConfigBuilder {
448 fn default() -> Self {
449 Self::new()
450 }
451}
452
453impl CallbackConfigBuilder {
454 /// Create a new builder
455 pub fn new() -> Self {
456 Self {
457 config: CallbackConfig::new(),
458 }
459 }
460
461 /// Add an authentication strategy
462 pub fn auth(mut self, strategy: AuthStrategy) -> Self {
463 self.config.auth.push(strategy);
464 self
465 }
466
467 /// Add multiple authentication strategies
468 pub fn auth_strategies(mut self, strategies: Vec<AuthStrategy>) -> Self {
469 self.config.auth.extend(strategies);
470 self
471 }
472
473 /// Set the authentication provenance mode (default: [`AuthMode::ExplicitOnly`]).
474 pub fn auth_mode(mut self, mode: AuthMode) -> Self {
475 self.config.auth_mode = mode;
476 self
477 }
478
479 /// Set progress configuration
480 pub fn progress(mut self, progress: ProgressConfig) -> Self {
481 self.config.progress = progress;
482 self
483 }
484
485 /// Set certificate configuration
486 pub fn certificates(mut self, certs: CertificateConfig) -> Self {
487 self.config.certificates = certs;
488 self
489 }
490
491 /// Set the off-site redirect policy (default: [`RedirectPolicy::None`] —
492 /// no off-site redirects). See [`RedirectPolicy`] for why the default
493 /// matters when a host-scoped credential is configured.
494 pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
495 self.config.redirect_policy = policy;
496 self
497 }
498
499 /// Enable pack progress
500 pub fn pack_progress(mut self, enabled: bool) -> Self {
501 self.config.pack_progress = enabled;
502 self
503 }
504
505 /// Build the configuration
506 pub fn build(self) -> CallbackConfig {
507 self.config
508 }
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use std::path::PathBuf;
515
516 #[test]
517 fn test_callback_config_is_send() {
518 fn assert_send<T: Send>() {}
519 assert_send::<CallbackConfig>();
520 }
521
522 #[test]
523 fn test_builder_pattern() {
524 let config = CallbackConfigBuilder::new()
525 .auth(AuthStrategy::SshAgent {
526 username: Some("git".to_owned()),
527 })
528 .progress(ProgressConfig::Stdout)
529 .certificates(CertificateConfig::AcceptAll)
530 .build();
531
532 assert_eq!(config.auth.len(), 1);
533 assert!(matches!(config.progress, ProgressConfig::Stdout));
534 assert!(matches!(config.certificates, CertificateConfig::AcceptAll));
535 }
536
537 // ---- AuthMode enforcement (private handle_auth seam) ----
538
539 fn user_pass_allowed() -> git2::CredentialType {
540 git2::CredentialType::USER_PASS_PLAINTEXT
541 }
542
543 fn default_allowed() -> git2::CredentialType {
544 git2::CredentialType::DEFAULT
545 }
546
547 fn ssh_allowed() -> git2::CredentialType {
548 git2::CredentialType::SSH_KEY
549 }
550
551 /// Under ExplicitOnly, a sole `AuthStrategy::Default` is refused — ambient
552 /// credential sources (credential helper, ~/.gitconfig, SSH agent fallback)
553 /// are not consulted.
554 #[test]
555 fn explicit_only_refuses_ambient_default() {
556 let auth = vec![AuthStrategy::Default];
557 let res = CallbackConfig::handle_auth(
558 &auth,
559 AuthMode::ExplicitOnly,
560 "https://github.com/example/repo.git",
561 None,
562 default_allowed(),
563 );
564 assert!(
565 res.is_err(),
566 "ExplicitOnly must refuse AuthStrategy::Default so ambient credentials are not \
567 consulted",
568 );
569 }
570
571 /// Under ExplicitOnly, `AuthStrategy::SshAgent` is ALSO refused — it
572 /// consults the running SSH agent (`Cred::ssh_key_from_agent`), an ambient
573 /// source. An untrusted fetch must not silently use the operator's loaded
574 /// SSH keys.
575 #[test]
576 fn explicit_only_refuses_ambient_ssh_agent() {
577 let auth = vec![AuthStrategy::SshAgent {
578 username: Some("git".to_owned()),
579 }];
580 let res = CallbackConfig::handle_auth(
581 &auth,
582 AuthMode::ExplicitOnly,
583 "https://github.com/example/repo.git",
584 None,
585 ssh_allowed(),
586 );
587 assert!(
588 res.is_err(),
589 "ExplicitOnly must refuse AuthStrategy::SshAgent (ssh-agent is ambient)",
590 );
591 }
592
593 /// Under AllowAmbient, `AuthStrategy::SshAgent` is honored — the explicit
594 /// opt-in path for trusted first-party mirrors.
595 #[test]
596 fn allow_ambient_permits_ssh_agent() {
597 let auth = vec![AuthStrategy::SshAgent {
598 username: Some("git".to_owned()),
599 }];
600 let res = CallbackConfig::handle_auth(
601 &auth,
602 AuthMode::AllowAmbient,
603 "https://github.com/example/repo.git",
604 None,
605 ssh_allowed(),
606 );
607 assert!(
608 res.is_ok(),
609 "AllowAmbient must permit AuthStrategy::SshAgent"
610 );
611 }
612
613 /// `is_ambient()` classifies exactly the environment-backed strategies.
614 #[test]
615 fn is_ambient_classification() {
616 assert!(AuthStrategy::Default.is_ambient());
617 assert!(AuthStrategy::SshAgent { username: None }.is_ambient());
618 // Explicit strategies are never ambient.
619 assert!(!AuthStrategy::Token {
620 token: "t".into(),
621 host: None
622 }
623 .is_ambient());
624 assert!(!AuthStrategy::UserPass {
625 username: "u".into(),
626 password: "p".into(),
627 }
628 .is_ambient());
629 assert!(!AuthStrategy::SshKey {
630 username: "u".into(),
631 public_key: None,
632 private_key: PathBuf::from("/k"),
633 passphrase: None,
634 }
635 .is_ambient());
636 }
637
638 /// Under AllowAmbient, `AuthStrategy::Default` is honored when the server
639 /// permits DEFAULT credentials — the explicit opt-in path.
640 #[test]
641 fn allow_ambient_permits_default() {
642 let auth = vec![AuthStrategy::Default];
643 let res = CallbackConfig::handle_auth(
644 &auth,
645 AuthMode::AllowAmbient,
646 "https://github.com/example/repo.git",
647 None,
648 default_allowed(),
649 );
650 assert!(
651 res.is_ok(),
652 "AllowAmbient must permit AuthStrategy::Default"
653 );
654 }
655
656 /// Under ExplicitOnly, an explicit Token strategy succeeds and a trailing
657 /// `Default` fallback is skipped rather than poisoning resolution or
658 /// silently consulting ambient sources.
659 #[test]
660 fn explicit_only_skips_default_uses_explicit_token() {
661 let auth = vec![
662 AuthStrategy::Token {
663 token: "ghp_explicit".to_owned(),
664 host: None,
665 },
666 AuthStrategy::Default,
667 ];
668 let res = CallbackConfig::handle_auth(
669 &auth,
670 AuthMode::ExplicitOnly,
671 "https://github.com/example/repo.git",
672 None,
673 user_pass_allowed(),
674 );
675 assert!(
676 res.is_ok(),
677 "explicit Token must succeed under ExplicitOnly"
678 );
679 }
680
681 /// Under ExplicitOnly with only ambient strategies, resolution fails even
682 /// when DEFAULT is allowed by the server.
683 #[test]
684 fn explicit_only_no_strategies_fails_closed() {
685 let auth: Vec<AuthStrategy> = vec![AuthStrategy::Default];
686 let res = CallbackConfig::handle_auth(
687 &auth,
688 AuthMode::ExplicitOnly,
689 "https://github.com/example/repo.git",
690 None,
691 default_allowed(),
692 );
693 assert!(
694 res.is_err(),
695 "ExplicitOnly with only ambient strategies must fail closed",
696 );
697 }
698
699 // ---- Host-scoped Token: a token for host A is never offered to host B ----
700
701 /// A token bound to `github.com` must NOT be offered when the request URL
702 /// points at a different host (`evil.example`). This is the host-A/host-B
703 /// negative test required by the #1429 Sol P1 fix.
704 #[test]
705 fn host_scoped_token_refused_for_different_host() {
706 let auth = vec![AuthStrategy::Token {
707 token: "trusted-forge-token".to_owned(),
708 host: Some("github.com".to_owned()),
709 }];
710 // Host B: the caller-selected remote is NOT github.com.
711 let res = CallbackConfig::handle_auth(
712 &auth,
713 AuthMode::ExplicitOnly,
714 "https://evil.example/untrusted/repo.git",
715 None,
716 user_pass_allowed(),
717 );
718 assert!(
719 res.is_err(),
720 "A host-scoped token bound to github.com must not be offered to evil.example",
721 );
722 }
723
724 /// The same host-scoped token IS offered when the request URL's host
725 /// matches the bound origin — the positive control for the negative test.
726 #[test]
727 fn host_scoped_token_offered_for_matching_host() {
728 let auth = vec![AuthStrategy::Token {
729 token: "trusted-forge-token".to_owned(),
730 host: Some("github.com".to_owned()),
731 }];
732 let res = CallbackConfig::handle_auth(
733 &auth,
734 AuthMode::ExplicitOnly,
735 "https://github.com/user/repo.git",
736 None,
737 user_pass_allowed(),
738 );
739 assert!(
740 res.is_ok(),
741 "A host-scoped token must be offered to its bound host",
742 );
743 }
744
745 /// An unscoped token (host: None) is offered to any host — this is the
746 /// behavior the caller explicitly constructs; it is not attached to the
747 /// default clone path (see manager.rs).
748 #[test]
749 fn unscoped_token_offered_to_any_host() {
750 let auth = vec![AuthStrategy::Token {
751 token: "explicit-unscoped".to_owned(),
752 host: None,
753 }];
754 let res = CallbackConfig::handle_auth(
755 &auth,
756 AuthMode::ExplicitOnly,
757 "https://anyhost.example/repo.git",
758 None,
759 user_pass_allowed(),
760 );
761 assert!(res.is_ok(), "An unscoped explicit Token is always honored");
762 }
763}