Skip to main content

grit_protocol/
lib.rs

1//! Git smart protocol handlers for HTTP transport.
2//!
3//! Runs upload-pack and receive-pack in-process via [`grit_lib::remote::serve`], with
4//! no subprocess or external `grit` binary. Every push runs the [`PushGuard`], which
5//! keeps pushes off the target branch of a repository with snapshot checkouts.
6
7pub mod receive_pack;
8pub mod session;
9pub mod upload_pack;
10
11use std::io::{Read, Write};
12use std::path::{Path, PathBuf};
13
14use grit_lib::config::git_path::path_for_error_message;
15use grit_lib::config::ConfigSet;
16
17pub use grit_lib::config::environment::RepositoryOptions;
18use grit_lib::objects::odb::Odb;
19use grit_lib::remote::serve::{
20    self, ProtocolVersion, ReceiveHook, ReceiveHookContext, ReceiveOutcome, ReceivePolicy,
21    RefCommand, RefUpdateRefusal, RefUpdateResult, ServeOptions, UploadOutcome,
22};
23use grit_lib::remote::snapshot_checkout::TargetGuard;
24use grit_lib::repo::Repository;
25
26pub use session::{ReceiveRpcResult, ServeSession};
27
28/// Errors from smart-protocol handlers.
29#[derive(Debug, thiserror::Error)]
30pub enum Error {
31    /// The path does not look like a git repository.
32    #[error("not a git repository: {0}")]
33    NotARepository(String),
34    /// Serving the wire protocol failed.
35    #[error(transparent)]
36    Serve(#[from] serve::ServeError),
37    /// Opening or reading repository state failed.
38    #[error(transparent)]
39    Repository(Box<grit_lib::error::Error>),
40    /// Buffered I/O failed while collecting the response.
41    #[error(transparent)]
42    Io(#[from] std::io::Error),
43}
44
45impl Error {
46    /// The I/O error from reading the client's request stream, for a failed
47    /// [`receive_pack::stateless_rpc_from_reader`] exchange.
48    ///
49    /// Servers use this to answer a request body that could not be read (truncated,
50    /// badly encoded, or rejected by the server's own decoding limits) with a client
51    /// error rather than a server error. During receive-pack that is the only source of
52    /// stream errors: the response is collected in memory, and repository failures are
53    /// reported as other [`serve::ServeError`] variants or inside the status report.
54    /// Upload-pack can also return stream errors while reading repository data. When the
55    /// inner error is [`grit_lib::remote::serve::RequestBodyLimitExceeded`], smart HTTP
56    /// maps the failure to 413; other upload-pack stream errors are usually server faults.
57    ///
58    /// # Returns
59    ///
60    /// `Some` with the request read error, or `None` for every other failure.
61    #[must_use]
62    pub fn request_stream_error(&self) -> Option<&std::io::Error> {
63        match self {
64            Self::Serve(serve::ServeError::Io(e)) => Some(e),
65            _ => None,
66        }
67    }
68}
69
70impl From<grit_lib::error::Error> for Error {
71    fn from(value: grit_lib::error::Error) -> Self {
72        match value {
73            grit_lib::error::Error::Remote(grit_lib::remote::RemoteError::Serve(serve)) => {
74                Self::Serve(serve)
75            }
76            grit_lib::error::Error::Io(io) => Self::Serve(serve::ServeError::Io(io)),
77            other => Self::Repository(Box::new(other)),
78        }
79    }
80}
81
82/// Result alias for protocol handlers.
83pub type Result<T> = std::result::Result<T, Error>;
84
85/// Server features beyond plain fetch and push, for the `_with` handlers.
86#[derive(Debug, Clone, Default)]
87pub struct Extensions {
88    /// Bundles offered through the protocol v2 `bundle-uri` command.
89    pub bundle_list: Option<grit_lib::remote::bundle_uri::BundleList>,
90    /// Resumable push endpoint advertised by receive-pack as `pushBundle=<value>`.
91    pub push_bundle: Option<String>,
92}
93
94/// The in-process checks every push these handlers serve gets.
95///
96/// A repository with snapshot checkouts refuses pushes that create, update or
97/// delete its target branch ([`TargetGuard`]), and tells the pusher how its
98/// work reaches the target instead. A repository without checkouts keeps
99/// Git's rules.
100#[derive(Debug, Clone, Default)]
101pub struct PushGuard {
102    target: Option<TargetGuard>,
103}
104
105impl PushGuard {
106    /// The guard for pushes to `repo`.
107    ///
108    /// # Parameters
109    ///
110    /// - `repo`: the repository receiving the push.
111    #[must_use]
112    pub fn for_repository(repo: &Repository) -> Self {
113        Self {
114            target: TargetGuard::for_repository(repo),
115        }
116    }
117
118    /// The branch pushes are kept off, when there is one.
119    #[must_use]
120    pub fn target(&self) -> Option<&str> {
121        self.target.as_ref().map(TargetGuard::target)
122    }
123}
124
125impl ReceiveHook for PushGuard {
126    fn update(&self, command: &RefCommand, odb: &Odb) -> std::result::Result<(), RefUpdateRefusal> {
127        self.target
128            .as_ref()
129            .map_or(Ok(()), |guard| guard.update(command, odb))
130    }
131
132    fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
133        let guard = self.target.as_ref()?;
134        updates
135            .iter()
136            .any(|u| u.error.is_some() && guard.guards(&u.refname))
137            .then(|| target_push_advice(guard.target()))
138    }
139}
140
141struct GuardedHook {
142    guard: PushGuard,
143    extra: Option<std::sync::Arc<dyn ReceiveHook + Send + Sync>>,
144}
145
146impl ReceiveHook for GuardedHook {
147    fn pre_receive_ctx(
148        &self,
149        commands: &[RefCommand],
150        odb: &Odb,
151        ctx: &ReceiveHookContext<'_>,
152    ) -> std::result::Result<(), RefUpdateRefusal> {
153        self.guard.pre_receive_ctx(commands, odb, ctx)?;
154        if let Some(h) = self.extra.as_deref() {
155            h.pre_receive_ctx(commands, odb, ctx)?;
156        }
157        Ok(())
158    }
159
160    fn update_ctx(
161        &self,
162        command: &RefCommand,
163        odb: &Odb,
164        ctx: &ReceiveHookContext<'_>,
165    ) -> std::result::Result<(), RefUpdateRefusal> {
166        self.guard.update_ctx(command, odb, ctx)?;
167        if let Some(h) = self.extra.as_deref() {
168            h.update_ctx(command, odb, ctx)?;
169        }
170        Ok(())
171    }
172
173    fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
174        match (
175            self.guard.message(updates),
176            self.extra.as_deref().and_then(|h| h.message(updates)),
177        ) {
178            (None, None) => None,
179            (Some(a), None) => Some(a),
180            (None, Some(b)) => Some(b),
181            (Some(a), Some(b)) => Some(format!("{a}{b}")),
182        }
183    }
184
185    fn post_receive(
186        &self,
187        commands: &[&RefCommand],
188        odb: &Odb,
189        ctx: &ReceiveHookContext<'_>,
190    ) -> std::result::Result<(), RefUpdateRefusal> {
191        if let Some(h) = self.extra.as_deref() {
192            h.post_receive(commands, odb, ctx)?;
193        }
194        Ok(())
195    }
196
197    fn post_update(
198        &self,
199        commands: &[&RefCommand],
200        odb: &Odb,
201    ) -> std::result::Result<(), RefUpdateRefusal> {
202        if let Some(h) = self.extra.as_deref() {
203            h.post_update(commands, odb)?;
204        }
205        Ok(())
206    }
207}
208
209/// What a pusher of the target branch `target` is told to do instead.
210fn target_push_advice(target: &str) -> String {
211    format!(
212        "{target} is the server's target branch: pushes can't change it.\n\
213         Push your work to another branch:\n\
214         \x20 grit switch -c <branch>\n\
215         \x20 grit push origin <branch>\n\
216         then merge it into {target} from a snapshot checkout of this repository:\n\
217         \x20 grit integrate <branch>\n\
218         (In a snapshot checkout, `grit checkin` sends your branches and `grit integrate` merges them.)\n"
219    )
220}
221
222/// Build [`RepositoryOptions`] from the current process environment
223/// ([`RepositoryOptions::from_process`]).
224///
225/// Captures `HOME`, `GIT_CONFIG_*`, and the other variables [`ConfigSet::load`]
226/// uses for global and system config. Call once at server startup and pass the
227/// same options into every handler so receive policy and hide-ref rules match
228/// a `grit receive-pack` / `grit upload-pack` subprocess.
229#[must_use]
230pub fn repository_options_from_process() -> RepositoryOptions {
231    RepositoryOptions::from_process()
232}
233
234/// Map an explicit smart-HTTP protocol version header to a wire version.
235#[must_use]
236pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
237    match version {
238        Some(2) => ProtocolVersion::V2,
239        Some(1) => ProtocolVersion::V1,
240        _ => ProtocolVersion::V0,
241    }
242}
243
244/// Validate that a path looks like a git repository (bare or non-bare).
245///
246/// # Errors
247///
248/// Returns [`Error::NotARepository`] when neither `HEAD` nor `.git/HEAD` exists.
249pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
250    if path.join("HEAD").is_file() {
251        return Ok(path.to_path_buf());
252    }
253    let dot_git = path.join(".git");
254    if dot_git.join("HEAD").is_file() {
255        return Ok(path.to_path_buf());
256    }
257    Err(Error::NotARepository(path_for_error_message(path)))
258}
259
260pub(crate) fn run_upload_pack(
261    repo_path: &Path,
262    protocol_version: Option<u8>,
263    stateless_rpc: bool,
264    advertise_refs: bool,
265    input: &[u8],
266    repository_options: &RepositoryOptions,
267    extensions: &Extensions,
268) -> Result<Vec<u8>> {
269    let mut output = Vec::new();
270    run_upload_pack_to(
271        repo_path,
272        protocol_version,
273        stateless_rpc,
274        advertise_refs,
275        &mut &*input,
276        repository_options,
277        extensions,
278        &mut output,
279    )?;
280    Ok(output)
281}
282
283#[allow(clippy::too_many_arguments)]
284pub(crate) fn run_upload_pack_to(
285    repo_path: &Path,
286    protocol_version: Option<u8>,
287    stateless_rpc: bool,
288    advertise_refs: bool,
289    input: &mut dyn Read,
290    repository_options: &RepositoryOptions,
291    extensions: &Extensions,
292    output: &mut dyn std::io::Write,
293) -> Result<()> {
294    run_upload_pack_with_session(
295        repo_path,
296        protocol_version,
297        stateless_rpc,
298        advertise_refs,
299        input,
300        repository_options,
301        extensions,
302        output,
303        &ServeSession::none(),
304    )
305    .map(|_| ())
306}
307
308#[allow(clippy::too_many_arguments)]
309pub(crate) fn run_upload_pack_with_session(
310    repo_path: &Path,
311    protocol_version: Option<u8>,
312    stateless_rpc: bool,
313    advertise_refs: bool,
314    input: &mut dyn Read,
315    repository_options: &RepositoryOptions,
316    extensions: &Extensions,
317    output: &mut dyn std::io::Write,
318    session: &ServeSession,
319) -> Result<UploadOutcome> {
320    let without_fetcher = repository_options
321        .clone()
322        .with_promisor_fetcher(None)
323        .for_serving();
324    let repo = Repository::open(repo_path, &without_fetcher)?;
325    let config = ConfigSet::load(
326        repo.environment(),
327        Some(repo.git_dir()),
328        &grit_lib::config::LoadConfigOptions::standard(repo.environment(), Some(repo.git_dir())),
329    )
330    .unwrap_or_default();
331    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
332    let mut opts = ServeOptions {
333        protocol: protocol_version_from_header(protocol_version),
334        stateless_rpc,
335        advertise_refs,
336        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
337        hidden_refs,
338        bundle_list: extensions.bundle_list.clone(),
339        push_bundle: None,
340        lazy_fetch: ServeOptions::lazy_fetch_from_environment(repo.environment()),
341        ..ServeOptions::default()
342    };
343    // The promisor fetcher in `repository_options` is used only when this request may
344    // fetch missing promised objects; otherwise the served repository fetches nothing.
345    opts.attach_promisor_fetcher(&repo, repository_options.promisor_fetcher.clone());
346    serve::UploadPack::new(&repo, &mut opts)
347        .with_cancel(session.cancel())
348        .run(input, output)
349        .map_err(Error::from)
350}
351
352pub(crate) fn run_receive_pack(
353    repo_path: &Path,
354    stateless_rpc: bool,
355    advertise_refs: bool,
356    input: &mut dyn Read,
357    repository_options: &RepositoryOptions,
358    extensions: &Extensions,
359) -> Result<Vec<u8>> {
360    let mut output = Vec::new();
361    run_receive_pack_to(
362        repo_path,
363        stateless_rpc,
364        advertise_refs,
365        input,
366        repository_options,
367        extensions,
368        &mut output,
369    )?;
370    Ok(output)
371}
372
373pub(crate) fn run_receive_pack_to(
374    repo_path: &Path,
375    stateless_rpc: bool,
376    advertise_refs: bool,
377    input: &mut dyn Read,
378    repository_options: &RepositoryOptions,
379    extensions: &Extensions,
380    output: &mut dyn Write,
381) -> Result<()> {
382    run_receive_pack_with_session(
383        repo_path,
384        stateless_rpc,
385        advertise_refs,
386        input,
387        repository_options,
388        extensions,
389        output,
390        &ServeSession::none(),
391    )
392    .map(|_| ())
393}
394
395#[allow(clippy::too_many_arguments)]
396pub(crate) fn run_receive_pack_with_session(
397    repo_path: &Path,
398    stateless_rpc: bool,
399    advertise_refs: bool,
400    input: &mut dyn Read,
401    repository_options: &RepositoryOptions,
402    extensions: &Extensions,
403    output: &mut dyn Write,
404    session: &ServeSession,
405) -> Result<ReceiveOutcome> {
406    let options = repository_options
407        .clone()
408        .with_promisor_fetcher(None)
409        .for_serving();
410    let repo = Repository::open(repo_path, &options)?;
411    let config = ConfigSet::load(
412        repo.environment(),
413        Some(repo.git_dir()),
414        &grit_lib::config::LoadConfigOptions::standard(repo.environment(), Some(repo.git_dir())),
415    )
416    .unwrap_or_default();
417    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
418    let opts = ServeOptions {
419        protocol: ProtocolVersion::V0,
420        stateless_rpc,
421        advertise_refs,
422        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
423        hidden_refs,
424        bundle_list: None,
425        push_bundle: extensions.push_bundle.clone(),
426        ..ServeOptions::default()
427    };
428    let policy = ReceivePolicy::from_config(&config);
429    let guard = PushGuard::for_repository(&repo);
430    let hook = GuardedHook {
431        guard,
432        extra: session.receive_hook.clone(),
433    };
434    serve::ReceivePack::new(&repo, &opts, &policy)
435        .with_hook(&hook)
436        .with_cancel(session.cancel())
437        .run(input, output)
438        .map_err(Error::from)
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use grit_lib::remote::serve::ProtocolVersion;
445
446    #[test]
447    fn pushes_of_the_target_are_told_what_to_do_instead() {
448        let result = |refname: &str, error: Option<RefUpdateRefusal>| RefUpdateResult {
449            refname: refname.to_owned(),
450            old: None,
451            new: None,
452            error,
453        };
454        let refused = Some(RefUpdateRefusal::TargetBranch {
455            target: "main".to_owned(),
456        });
457        assert_eq!(
458            PushGuard::default().message(&[result("refs/heads/main", refused.clone())]),
459            None,
460            "a repository without checkouts has no guard"
461        );
462        let guard = PushGuard {
463            target: Some(TargetGuard::new("main")),
464        };
465        assert_eq!(guard.target(), Some("main"));
466        assert_eq!(guard.message(&[result("refs/heads/main", None)]), None);
467        assert_eq!(
468            guard.message(&[result(
469                "refs/heads/topic",
470                Some(RefUpdateRefusal::StaleInfo)
471            )]),
472            None
473        );
474        let advice = guard
475            .message(&[
476                result("refs/heads/topic", None),
477                result("refs/heads/main", refused),
478            ])
479            .unwrap_or_default();
480        assert!(
481            advice.starts_with("main is the server's target branch"),
482            "{advice}"
483        );
484        assert!(advice.contains("grit integrate <branch>"), "{advice}");
485        // Refused for Git's own reasons (a checked-out branch), it still explains.
486        assert!(guard
487            .message(&[result(
488                "refs/heads/main",
489                Some(RefUpdateRefusal::CurrentBranch)
490            )])
491            .is_some());
492    }
493
494    #[test]
495    fn protocol_header_maps_versions() {
496        assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
497        assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
498    }
499}