Skip to main content

git2db/
clone_options.rs

1//! Clone operation options
2//!
3//! This module provides a Send-safe way to configure git clone operations.
4//! Instead of holding non-Send callbacks directly, we use a configuration approach.
5//!
6//! # Example
7//!
8//! ```rust,ignore
9//! use git2db::clone_options::CloneOptions;
10//! use git2db::callback_config::{CallbackConfigBuilder, ProgressConfig};
11//! use git2db::auth::AuthStrategy;
12//!
13//! let options = CloneOptions::builder()
14//!     .callback_config(
15//!         CallbackConfigBuilder::new()
16//!             .auth(AuthStrategy::SshAgent { username: Some("git".to_owned()) })
17//!             .progress(ProgressConfig::Stdout)
18//!             .build()
19//!     )
20//!     .shallow(true)
21//!     .depth(1)
22//!     .branch("main")
23//!     .build();
24//! ```
25
26use crate::callback_config::{AuthMode, CallbackConfig};
27use git2::{build::CheckoutBuilder, FetchOptions, RemoteCallbacks};
28
29/// Trust posture for a clone/fetch operation.
30///
31/// `Untrusted` is the mode required for any repository whose remote or
32/// contents are not first-party-controlled — concretely, a PR head fetched by
33/// a merge gate. Selecting it clamps three independently-dangerous properties
34/// together (issue #1430), rather than requiring the caller to remember all
35/// three every time:
36///
37/// - [`SubmoduleMode`] is forced to [`SubmoduleMode::Disabled`] regardless of
38///   what the caller configured — `.gitmodules` is attacker-controlled
39///   content, and initializing a declared submodule means fetching from an
40///   arbitrary attacker-chosen remote URL.
41/// - [`FilterMode`] is forced to [`FilterMode::Passthrough`] regardless of
42///   what the caller configured — a `.gitattributes`-declared content filter
43///   (XET/LFS smudge) would resolve attacker-controlled pointer content
44///   against a real endpoint during checkout.
45/// - Auth is required to be [`AuthMode::ExplicitOnly`] (already the
46///   `CallbackConfig`/`AuthManager` default per B2/#1429) with no unscoped
47///   (`host: None`) [`crate::auth::AuthStrategy::Token`] present — see
48///   [`CloneOptions::validate_trust`].
49///
50/// This is deliberately the *only* notion of "untrusted" in `git2db` — it
51/// composes the ambient-vs-explicit auth split B2 already established rather
52/// than introducing a second, parallel trust concept.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum CloneTrust {
55    /// First-party, operator-controlled repository. The caller-selected
56    /// [`SubmoduleMode`], [`FilterMode`], and auth configuration are honored
57    /// as configured — this is the default, matching today's behavior.
58    #[default]
59    Trusted,
60    /// Arbitrary or attacker-influenced repository (PR heads, forge-facing
61    /// fetches, anything the merge gate builds). See [`CloneTrust`] docs for
62    /// exactly what this clamps.
63    Untrusted,
64}
65
66/// Controls whether `.gitmodules`-declared submodules are initialized and
67/// updated after a clone.
68///
69/// Replaces the previous plain `update_submodules: bool` field — folding
70/// submodule handling into a named mode makes the untrusted clamp in
71/// [`CloneTrust::Untrusted`] a single, unambiguous source of truth instead of
72/// a bool the caller could independently flip back on.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
74pub enum SubmoduleMode {
75    /// Never initialize or update submodules, even if the repository
76    /// declares them via `.gitmodules`. Secure default — matches the
77    /// pre-#1430 behavior, where submodule initialization was never wired
78    /// into [`crate::manager::GitManager::clone_repository`] at all.
79    #[default]
80    Disabled,
81    /// Initialize and update submodules after clone (equivalent to
82    /// `git clone --recurse-submodules`). Only appropriate for trusted,
83    /// first-party repositories, since a submodule's remote URL is taken
84    /// verbatim from the repository's own `.gitmodules` content.
85    Enabled,
86}
87
88/// Controls whether libgit2 content filters (XET/LFS smudge, and libgit2's
89/// own built-in `ident`/`crlf` filters) are applied during checkout.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum FilterMode {
92    /// Apply registered content filters normally during checkout — the
93    /// default, matching today's behavior.
94    #[default]
95    Enabled,
96    /// Disable all content filters during checkout
97    /// (`git2::build::CheckoutBuilder::disable_filters(true)`), so no
98    /// registered filter — XET/LFS smudge included — resolves checked-out
99    /// file content against an external endpoint. Required for untrusted
100    /// checkouts, where the `.gitattributes` filter declaration and the
101    /// pointer content it would smudge are both attacker-controlled.
102    Passthrough,
103}
104
105/// Send-safe options for cloning a repository
106#[derive(Default, Clone)]
107pub struct CloneOptions {
108    /// Send-safe callback configuration
109    pub callback_config: Option<CallbackConfig>,
110
111    /// Whether to perform a shallow clone
112    pub shallow: bool,
113
114    /// Depth for shallow clones
115    pub depth: Option<i32>,
116
117    /// Branch to checkout
118    pub branch: Option<String>,
119
120    /// Custom refspecs
121    pub refspecs: Vec<String>,
122
123    /// Trust posture for this clone. See [`CloneTrust`].
124    pub trust: CloneTrust,
125
126    /// Submodule handling, subject to the [`CloneTrust::Untrusted`] clamp —
127    /// see [`CloneOptions::effective_submodule_mode`].
128    pub submodule_mode: SubmoduleMode,
129
130    /// Content filter handling, subject to the [`CloneTrust::Untrusted`]
131    /// clamp — see [`CloneOptions::effective_filter_mode`].
132    pub filter_mode: FilterMode,
133
134    /// Network proxy URL
135    pub proxy_url: Option<String>,
136
137    /// Timeout in seconds for network operations
138    pub timeout_seconds: Option<u32>,
139}
140
141// Ensure CloneOptions is Send
142#[allow(dead_code)]
143const _: () = {
144    fn assert_send<T: Send>() {}
145    fn assert_clone_options_is_send() {
146        assert_send::<CloneOptions>();
147    }
148};
149
150impl CloneOptions {
151    /// Create a new CloneOptions builder
152    pub fn builder() -> CloneOptionsBuilder {
153        CloneOptionsBuilder::new()
154    }
155
156    /// Create options with callback configuration
157    pub fn with_callback_config(config: CallbackConfig) -> Self {
158        Self {
159            callback_config: Some(config),
160            ..Default::default()
161        }
162    }
163
164    /// The submodule mode actually in effect, after applying the
165    /// [`CloneTrust::Untrusted`] clamp. Under `Untrusted` this is always
166    /// [`SubmoduleMode::Disabled`], regardless of `self.submodule_mode` —
167    /// this is the single source of truth callers and tests should read,
168    /// rather than the raw field.
169    pub fn effective_submodule_mode(&self) -> SubmoduleMode {
170        match self.trust {
171            CloneTrust::Untrusted => SubmoduleMode::Disabled,
172            CloneTrust::Trusted => self.submodule_mode,
173        }
174    }
175
176    /// The filter mode actually in effect, after applying the
177    /// [`CloneTrust::Untrusted`] clamp. Under `Untrusted` this is always
178    /// [`FilterMode::Passthrough`], regardless of `self.filter_mode`.
179    pub fn effective_filter_mode(&self) -> FilterMode {
180        match self.trust {
181            CloneTrust::Untrusted => FilterMode::Passthrough,
182            CloneTrust::Trusted => self.filter_mode,
183        }
184    }
185
186    /// Validate that an [`CloneTrust::Untrusted`] clone cannot silently widen
187    /// its own credential surface — checked independently of the submodule/
188    /// filter clamps above, which cannot be bypassed by construction, but
189    /// auth is a `Vec<AuthStrategy>` the caller assembles separately.
190    ///
191    /// Refuses:
192    /// - [`AuthMode::AllowAmbient`] — untrusted fetches must stay
193    ///   [`AuthMode::ExplicitOnly`] (credential helper / `~/.gitconfig` / SSH
194    ///   agent must never be consulted for an attacker-influenced remote).
195    /// - An unscoped [`crate::auth::AuthStrategy::Token`] (`host: None`) —
196    ///   such a token is offered to *any* remote that challenges for it
197    ///   (see `auth.rs`), which for an untrusted, caller-selected remote is a
198    ///   credential-exfiltration vector. Untrusted clones must use either no
199    ///   token or one bound to an exact origin authority.
200    ///
201    /// `Trusted` options always validate successfully — this check exists
202    /// only to keep `Untrusted` honest.
203    pub fn validate_trust(&self) -> Result<(), crate::errors::Git2DBError> {
204        if self.trust != CloneTrust::Untrusted {
205            return Ok(());
206        }
207
208        let Some(config) = self.callback_config.as_ref() else {
209            return Ok(());
210        };
211
212        if config.auth_mode == AuthMode::AllowAmbient {
213            return Err(crate::errors::Git2DBError::configuration(
214                "CloneTrust::Untrusted requires AuthMode::ExplicitOnly; \
215                 AllowAmbient would permit ambient credential discovery \
216                 (credential helper, ~/.gitconfig, SSH agent) against an \
217                 untrusted remote",
218            ));
219        }
220
221        for strategy in &config.auth {
222            if let crate::auth::AuthStrategy::Token { host: None, .. } = strategy {
223                return Err(crate::errors::Git2DBError::configuration(
224                    "CloneTrust::Untrusted refuses an unscoped Token (host: \
225                     None): it would be offered to any remote, including an \
226                     untrusted caller-selected one — bind it to an exact \
227                     origin authority or omit it",
228                ));
229            }
230        }
231
232        Ok(())
233    }
234
235    /// Convert to legacy git2 options for use within spawn_blocking
236    /// This is called inside spawn_blocking where lifetime constraints are satisfied
237    pub(crate) fn to_git2_options(&self) -> LegacyCloneOptions<'_> {
238        let mut options = LegacyCloneOptions {
239            _shallow: self.shallow,
240            depth: self.depth,
241            branch: self.branch.clone(),
242            _refspecs: self.refspecs.clone(),
243            submodule_mode: self.effective_submodule_mode(),
244            filter_mode: self.effective_filter_mode(),
245            proxy_url: self.proxy_url.clone(),
246            _timeout_seconds: self.timeout_seconds,
247            ..Default::default()
248        };
249
250        // Create callbacks from config if present, and extract the redirect
251        // policy so it can be applied to FetchOptions.
252        if let Some(ref config) = self.callback_config {
253            options.callbacks = Some(config.create_callbacks());
254            options.redirect_policy = config.redirect_policy;
255        }
256
257        options
258    }
259}
260
261/// Internal legacy options structure for git2 interop
262/// Only used within spawn_blocking where non-Send is acceptable
263#[derive(Default)]
264pub(crate) struct LegacyCloneOptions<'cb> {
265    pub callbacks: Option<RemoteCallbacks<'cb>>,
266    pub _shallow: bool,
267    pub depth: Option<i32>,
268    pub branch: Option<String>,
269    pub _refspecs: Vec<String>,
270    /// Already resolved via [`CloneOptions::effective_submodule_mode`] — the
271    /// [`CloneTrust`] clamp has already been applied by the time this is set.
272    pub submodule_mode: SubmoduleMode,
273    /// Already resolved via [`CloneOptions::effective_filter_mode`].
274    pub filter_mode: FilterMode,
275    pub proxy_url: Option<String>,
276    pub _timeout_seconds: Option<u32>,
277    /// Off-site redirect policy (default: None — no off-site redirects).
278    pub redirect_policy: crate::callback_config::RedirectPolicy,
279}
280
281impl<'cb> LegacyCloneOptions<'cb> {
282    /// Create FetchOptions from these clone options
283    pub fn create_fetch_options(
284        &mut self,
285    ) -> Result<FetchOptions<'cb>, crate::errors::Git2DBError> {
286        let mut fetch_opts = FetchOptions::new();
287
288        // Apply callbacks if provided (move out of self)
289        if let Some(callbacks) = self.callbacks.take() {
290            fetch_opts.remote_callbacks(callbacks);
291        }
292
293        // Apply redirect policy: default is None (no off-site redirects) to
294        // prevent credential exfiltration via redirect when host-scoped
295        // credentials are present (Sol P1 #1429).
296        fetch_opts.follow_redirects(self.redirect_policy.to_git2());
297
298        // Apply proxy settings
299        if let Some(proxy_url) = &self.proxy_url {
300            let mut proxy_opts = git2::ProxyOptions::new();
301            proxy_opts.url(proxy_url);
302            fetch_opts.proxy_options(proxy_opts);
303        }
304
305        // Apply depth for shallow clones
306        if let Some(depth) = self.depth {
307            fetch_opts.depth(depth);
308        }
309
310        Ok(fetch_opts)
311    }
312
313    /// Create CheckoutBuilder for this clone.
314    ///
315    /// Under [`FilterMode::Passthrough`] this disables libgit2 content
316    /// filters entirely (`GIT_CHECKOUT_DISABLE_FILTERS`) so no
317    /// `.gitattributes`-registered filter — XET/LFS smudge included — runs
318    /// during checkout. See issue #1430.
319    pub fn create_checkout_builder(&self) -> CheckoutBuilder<'static> {
320        let mut builder = CheckoutBuilder::new();
321        if matches!(self.filter_mode, FilterMode::Passthrough) {
322            builder.disable_filters(true);
323        }
324        builder
325    }
326}
327
328/// Builder for CloneOptions with fluent interface
329pub struct CloneOptionsBuilder {
330    options: CloneOptions,
331}
332
333impl CloneOptionsBuilder {
334    /// Create a new builder with default options
335    pub fn new() -> Self {
336        Self {
337            options: CloneOptions::default(),
338        }
339    }
340
341    /// Set callback configuration
342    pub fn callback_config(mut self, config: CallbackConfig) -> Self {
343        self.options.callback_config = Some(config);
344        self
345    }
346
347    /// Enable shallow clone
348    pub fn shallow(mut self, shallow: bool) -> Self {
349        self.options.shallow = shallow;
350        self
351    }
352
353    /// Set clone depth
354    pub fn depth(mut self, depth: i32) -> Self {
355        self.options.depth = Some(depth);
356        self
357    }
358
359    /// Set branch to checkout
360    pub fn branch(mut self, branch: impl Into<String>) -> Self {
361        self.options.branch = Some(branch.into());
362        self
363    }
364
365    /// Add a refspec
366    pub fn refspec(mut self, refspec: impl Into<String>) -> Self {
367        self.options.refspecs.push(refspec.into());
368        self
369    }
370
371    /// Set the trust posture for this clone. See [`CloneTrust`] — selecting
372    /// [`CloneTrust::Untrusted`] clamps submodule and filter handling
373    /// regardless of what is configured below.
374    pub fn trust(mut self, trust: CloneTrust) -> Self {
375        self.options.trust = trust;
376        self
377    }
378
379    /// Set the submodule handling mode. Subject to the [`CloneTrust`] clamp
380    /// — see [`CloneOptions::effective_submodule_mode`].
381    pub fn submodule_mode(mut self, mode: SubmoduleMode) -> Self {
382        self.options.submodule_mode = mode;
383        self
384    }
385
386    /// Set the content filter handling mode. Subject to the [`CloneTrust`]
387    /// clamp — see [`CloneOptions::effective_filter_mode`].
388    pub fn filter_mode(mut self, mode: FilterMode) -> Self {
389        self.options.filter_mode = mode;
390        self
391    }
392
393    /// Set proxy URL
394    pub fn proxy_url(mut self, proxy_url: impl Into<String>) -> Self {
395        self.options.proxy_url = Some(proxy_url.into());
396        self
397    }
398
399    /// Set timeout in seconds
400    pub fn timeout(mut self, seconds: u32) -> Self {
401        self.options.timeout_seconds = Some(seconds);
402        self
403    }
404
405    /// Build the CloneOptions
406    pub fn build(self) -> CloneOptions {
407        self.options
408    }
409}
410
411impl Default for CloneOptionsBuilder {
412    fn default() -> Self {
413        Self::new()
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    #[test]
422    fn test_builder_pattern() {
423        let options = CloneOptions::builder()
424            .shallow(true)
425            .depth(5)
426            .branch("main")
427            .timeout(60)
428            .build();
429
430        assert!(options.shallow);
431        assert_eq!(options.depth, Some(5));
432        assert_eq!(options.branch, Some("main".to_owned()));
433        assert_eq!(options.timeout_seconds, Some(60));
434    }
435
436    #[test]
437    fn test_with_callback_config() {
438        use crate::callback_config::CallbackConfig;
439
440        let config = CallbackConfig::new();
441        let options = CloneOptions::with_callback_config(config);
442        assert!(options.callback_config.is_some());
443    }
444
445    #[test]
446    fn test_clone_options_is_send() {
447        fn assert_send<T: Send>() {}
448        assert_send::<CloneOptions>();
449    }
450
451    // ---- CloneTrust clamp ----
452
453    /// Defaults are `Trusted` + `SubmoduleMode::Disabled` +
454    /// `FilterMode::Enabled` — matches pre-#1430 behavior (submodules were
455    /// never wired up at all, filters ran normally).
456    #[test]
457    fn defaults_are_trusted_and_match_legacy_behavior() {
458        let options = CloneOptions::default();
459        assert_eq!(options.trust, CloneTrust::Trusted);
460        assert_eq!(options.effective_submodule_mode(), SubmoduleMode::Disabled);
461        assert_eq!(options.effective_filter_mode(), FilterMode::Enabled);
462    }
463
464    /// A `Trusted` clone honors whatever `SubmoduleMode`/`FilterMode` the
465    /// caller explicitly configured.
466    #[test]
467    fn trusted_honors_configured_modes() {
468        let options = CloneOptions::builder()
469            .trust(CloneTrust::Trusted)
470            .submodule_mode(SubmoduleMode::Enabled)
471            .filter_mode(FilterMode::Passthrough)
472            .build();
473        assert_eq!(options.effective_submodule_mode(), SubmoduleMode::Enabled);
474        assert_eq!(options.effective_filter_mode(), FilterMode::Passthrough);
475    }
476
477    /// `Untrusted` clamps submodule and filter mode to the safe values EVEN
478    /// WHEN the caller explicitly (mis)configured the opposite — this is the
479    /// property that makes `Untrusted` a single source of truth rather than
480    /// a bool that can be independently flipped back on.
481    #[test]
482    fn untrusted_clamps_submodule_and_filter_mode_despite_caller_override() {
483        let options = CloneOptions::builder()
484            .trust(CloneTrust::Untrusted)
485            .submodule_mode(SubmoduleMode::Enabled) // attempted override
486            .filter_mode(FilterMode::Enabled) // attempted override
487            .build();
488
489        assert_eq!(
490            options.effective_submodule_mode(),
491            SubmoduleMode::Disabled,
492            "Untrusted must clamp submodule_mode to Disabled regardless of the raw field"
493        );
494        assert_eq!(
495            options.effective_filter_mode(),
496            FilterMode::Passthrough,
497            "Untrusted must clamp filter_mode to Passthrough regardless of the raw field"
498        );
499    }
500
501    // ---- validate_trust() ----
502
503    #[test]
504    fn trusted_options_always_validate() {
505        use crate::auth::AuthStrategy;
506        use crate::callback_config::{AuthMode, CallbackConfigBuilder};
507
508        let options = CloneOptions::builder()
509            .trust(CloneTrust::Trusted)
510            .callback_config(
511                CallbackConfigBuilder::new()
512                    .auth(AuthStrategy::Token {
513                        token: "t".into(),
514                        host: None,
515                    })
516                    .auth_mode(AuthMode::AllowAmbient)
517                    .build(),
518            )
519            .build();
520        assert!(options.validate_trust().is_ok());
521    }
522
523    #[test]
524    fn untrusted_rejects_allow_ambient_auth_mode() {
525        use crate::callback_config::{AuthMode, CallbackConfigBuilder};
526
527        let options = CloneOptions::builder()
528            .trust(CloneTrust::Untrusted)
529            .callback_config(
530                CallbackConfigBuilder::new()
531                    .auth_mode(AuthMode::AllowAmbient)
532                    .build(),
533            )
534            .build();
535        assert!(
536            options.validate_trust().is_err(),
537            "Untrusted + AllowAmbient must be refused at validation time"
538        );
539    }
540
541    #[test]
542    fn untrusted_rejects_unscoped_token() {
543        use crate::auth::AuthStrategy;
544        use crate::callback_config::CallbackConfigBuilder;
545
546        let options = CloneOptions::builder()
547            .trust(CloneTrust::Untrusted)
548            .callback_config(
549                CallbackConfigBuilder::new()
550                    .auth(AuthStrategy::Token {
551                        token: "unscoped".into(),
552                        host: None,
553                    })
554                    .build(),
555            )
556            .build();
557        assert!(
558            options.validate_trust().is_err(),
559            "Untrusted + an unscoped Token (host: None) must be refused"
560        );
561    }
562
563    #[test]
564    fn untrusted_accepts_host_scoped_token() {
565        use crate::auth::AuthStrategy;
566        use crate::callback_config::CallbackConfigBuilder;
567
568        let options = CloneOptions::builder()
569            .trust(CloneTrust::Untrusted)
570            .callback_config(
571                CallbackConfigBuilder::new()
572                    .auth(AuthStrategy::Token {
573                        token: "scoped".into(),
574                        host: Some("github.com".into()),
575                    })
576                    .build(),
577            )
578            .build();
579        assert!(
580            options.validate_trust().is_ok(),
581            "Untrusted + a host-scoped Token must validate — this is the intended scoped-token path"
582        );
583    }
584
585    #[test]
586    fn untrusted_with_no_callback_config_validates() {
587        let options = CloneOptions::builder().trust(CloneTrust::Untrusted).build();
588        assert!(options.validate_trust().is_ok());
589    }
590
591    // FilterMode's effect on the actual checkout (disable_filters wiring) is
592    // proved end-to-end in manager.rs's ident-filter adversarial test — a
593    // git2::build::CheckoutBuilder has no getter to unit-test the flag in
594    // isolation, and a fake assertion here would prove nothing about the
595    // real libgit2 behavior.
596}