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 upload_pack;
9
10use std::io::Read;
11use std::path::{Path, PathBuf};
12
13use grit_lib::config::git_path::path_for_error_message;
14use grit_lib::config::ConfigSet;
15
16pub use grit_lib::config::environment::RepositoryOptions;
17use grit_lib::objects::odb::Odb;
18use grit_lib::remote::serve::{
19    self, ProtocolVersion, ReceiveHook, ReceivePolicy, RefCommand, RefUpdateRefusal,
20    RefUpdateResult, ServeOptions,
21};
22use grit_lib::remote::snapshot_checkout::TargetGuard;
23use grit_lib::repo::Repository;
24
25/// Errors from smart-protocol handlers.
26#[derive(Debug, thiserror::Error)]
27pub enum Error {
28    /// The path does not look like a git repository.
29    #[error("not a git repository: {0}")]
30    NotARepository(String),
31    /// Serving the wire protocol failed.
32    #[error(transparent)]
33    Serve(#[from] serve::ServeError),
34    /// Opening or reading repository state failed.
35    #[error(transparent)]
36    Repository(#[from] grit_lib::error::Error),
37    /// Buffered I/O failed while collecting the response.
38    #[error(transparent)]
39    Io(#[from] std::io::Error),
40}
41
42impl Error {
43    /// The I/O error from reading the client's request stream, for a failed
44    /// [`receive_pack::stateless_rpc_from_reader`] exchange.
45    ///
46    /// Servers use this to answer a request body that could not be read (truncated,
47    /// badly encoded, or rejected by the server's own decoding limits) with a client
48    /// error rather than a server error. During receive-pack that is the only source of
49    /// stream errors: the response is collected in memory, and repository failures are
50    /// reported as other [`serve::ServeError`] variants or inside the status report.
51    /// Upload-pack can
52    /// also return stream errors while reading repository data, so do not use this to
53    /// classify upload-pack failures.
54    ///
55    /// # Returns
56    ///
57    /// `Some` with the request read error, or `None` for every other failure.
58    #[must_use]
59    pub fn request_stream_error(&self) -> Option<&std::io::Error> {
60        match self {
61            Self::Serve(serve::ServeError::Io(e)) => Some(e),
62            _ => None,
63        }
64    }
65}
66
67/// Result alias for protocol handlers.
68pub type Result<T> = std::result::Result<T, Error>;
69
70/// Server features beyond plain fetch and push, for the `_with` handlers.
71#[derive(Debug, Clone, Default)]
72pub struct Extensions {
73    /// Bundles offered through the protocol v2 `bundle-uri` command.
74    pub bundle_list: Option<grit_lib::remote::bundle_uri::BundleList>,
75    /// Resumable push endpoint advertised by receive-pack as `pushBundle=<value>`.
76    pub push_bundle: Option<String>,
77}
78
79/// The in-process checks every push these handlers serve gets.
80///
81/// A repository with snapshot checkouts refuses pushes that create, update or
82/// delete its target branch ([`TargetGuard`]), and tells the pusher how its
83/// work reaches the target instead. A repository without checkouts keeps
84/// Git's rules.
85#[derive(Debug, Clone, Default)]
86pub struct PushGuard {
87    target: Option<TargetGuard>,
88}
89
90impl PushGuard {
91    /// The guard for pushes to `repo`.
92    ///
93    /// # Parameters
94    ///
95    /// - `repo`: the repository receiving the push.
96    #[must_use]
97    pub fn for_repository(repo: &Repository) -> Self {
98        Self {
99            target: TargetGuard::for_repository(repo),
100        }
101    }
102
103    /// The branch pushes are kept off, when there is one.
104    #[must_use]
105    pub fn target(&self) -> Option<&str> {
106        self.target.as_ref().map(TargetGuard::target)
107    }
108}
109
110impl ReceiveHook for PushGuard {
111    fn update(&self, command: &RefCommand, odb: &Odb) -> std::result::Result<(), RefUpdateRefusal> {
112        self.target
113            .as_ref()
114            .map_or(Ok(()), |guard| guard.update(command, odb))
115    }
116
117    fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
118        let guard = self.target.as_ref()?;
119        updates
120            .iter()
121            .any(|u| u.error.is_some() && guard.guards(&u.refname))
122            .then(|| target_push_advice(guard.target()))
123    }
124}
125
126/// What a pusher of the target branch `target` is told to do instead.
127fn target_push_advice(target: &str) -> String {
128    format!(
129        "{target} is the server's target branch: pushes can't change it.\n\
130         Push your work to another branch:\n\
131         \x20 grit switch -c <branch>\n\
132         \x20 grit push origin <branch>\n\
133         then merge it into {target} from a snapshot checkout of this repository:\n\
134         \x20 grit integrate <branch>\n\
135         (In a snapshot checkout, `grit checkin` sends your branches and `grit integrate` merges them.)\n"
136    )
137}
138
139/// Build [`RepositoryOptions`] from the current process environment
140/// ([`RepositoryOptions::from_process`]).
141///
142/// Captures `HOME`, `GIT_CONFIG_*`, and the other variables [`ConfigSet::load`]
143/// uses for global and system config. Call once at server startup and pass the
144/// same options into every handler so receive policy and hide-ref rules match
145/// a `grit receive-pack` / `grit upload-pack` subprocess.
146#[must_use]
147pub fn repository_options_from_process() -> RepositoryOptions {
148    RepositoryOptions::from_process()
149}
150
151/// Map an explicit smart-HTTP protocol version header to a wire version.
152#[must_use]
153pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
154    match version {
155        Some(2) => ProtocolVersion::V2,
156        Some(1) => ProtocolVersion::V1,
157        _ => ProtocolVersion::V0,
158    }
159}
160
161/// Validate that a path looks like a git repository (bare or non-bare).
162///
163/// # Errors
164///
165/// Returns [`Error::NotARepository`] when neither `HEAD` nor `.git/HEAD` exists.
166pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
167    if path.join("HEAD").is_file() {
168        return Ok(path.to_path_buf());
169    }
170    let dot_git = path.join(".git");
171    if dot_git.join("HEAD").is_file() {
172        return Ok(path.to_path_buf());
173    }
174    Err(Error::NotARepository(path_for_error_message(path)))
175}
176
177pub(crate) fn run_upload_pack(
178    repo_path: &Path,
179    protocol_version: Option<u8>,
180    stateless_rpc: bool,
181    advertise_refs: bool,
182    input: &[u8],
183    repository_options: &RepositoryOptions,
184    extensions: &Extensions,
185) -> Result<Vec<u8>> {
186    let mut output = Vec::new();
187    run_upload_pack_to(
188        repo_path,
189        protocol_version,
190        stateless_rpc,
191        advertise_refs,
192        input,
193        repository_options,
194        extensions,
195        &mut output,
196    )?;
197    Ok(output)
198}
199
200#[allow(clippy::too_many_arguments)]
201pub(crate) fn run_upload_pack_to(
202    repo_path: &Path,
203    protocol_version: Option<u8>,
204    stateless_rpc: bool,
205    advertise_refs: bool,
206    input: &[u8],
207    repository_options: &RepositoryOptions,
208    extensions: &Extensions,
209    output: &mut dyn std::io::Write,
210) -> Result<()> {
211    let without_fetcher = repository_options
212        .clone()
213        .with_promisor_fetcher(None)
214        .for_serving();
215    let repo = Repository::open(repo_path, &without_fetcher)?;
216    let config =
217        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
218    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
219    let mut opts = ServeOptions {
220        protocol: protocol_version_from_header(protocol_version),
221        stateless_rpc,
222        advertise_refs,
223        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
224        hidden_refs,
225        bundle_list: extensions.bundle_list.clone(),
226        push_bundle: None,
227        lazy_fetch: ServeOptions::lazy_fetch_from_environment(repo.environment()),
228        ..ServeOptions::default()
229    };
230    // The promisor fetcher in `repository_options` is used only when this request may
231    // fetch missing promised objects; otherwise the served repository fetches nothing.
232    opts.attach_promisor_fetcher(&repo, &config, repository_options.promisor_fetcher.clone());
233    let _summary = serve::upload_pack(&repo, &mut &*input, output, &mut opts)?;
234    Ok(())
235}
236
237pub(crate) fn run_receive_pack(
238    repo_path: &Path,
239    stateless_rpc: bool,
240    advertise_refs: bool,
241    input: &mut dyn Read,
242    repository_options: &RepositoryOptions,
243    extensions: &Extensions,
244) -> Result<Vec<u8>> {
245    let options = repository_options
246        .clone()
247        .with_promisor_fetcher(None)
248        .for_serving();
249    let repo = Repository::open(repo_path, &options)?;
250    let config =
251        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
252    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
253    let opts = ServeOptions {
254        protocol: ProtocolVersion::V0,
255        stateless_rpc,
256        advertise_refs,
257        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
258        hidden_refs,
259        bundle_list: None,
260        push_bundle: extensions.push_bundle.clone(),
261        ..ServeOptions::default()
262    };
263    let policy = ReceivePolicy::from_config(&config);
264    let guard = PushGuard::for_repository(&repo);
265    let mut output = Vec::new();
266    serve::receive_pack_with_hook(&repo, input, &mut output, &opts, &policy, &guard)?;
267    Ok(output)
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use grit_lib::remote::serve::ProtocolVersion;
274
275    #[test]
276    fn pushes_of_the_target_are_told_what_to_do_instead() {
277        let result = |refname: &str, error: Option<RefUpdateRefusal>| RefUpdateResult {
278            refname: refname.to_owned(),
279            old: None,
280            new: None,
281            error,
282        };
283        let refused = Some(RefUpdateRefusal::TargetBranch {
284            target: "main".to_owned(),
285        });
286        assert_eq!(
287            PushGuard::default().message(&[result("refs/heads/main", refused.clone())]),
288            None,
289            "a repository without checkouts has no guard"
290        );
291        let guard = PushGuard {
292            target: Some(TargetGuard::new("main")),
293        };
294        assert_eq!(guard.target(), Some("main"));
295        assert_eq!(guard.message(&[result("refs/heads/main", None)]), None);
296        assert_eq!(
297            guard.message(&[result(
298                "refs/heads/topic",
299                Some(RefUpdateRefusal::StaleInfo)
300            )]),
301            None
302        );
303        let advice = guard
304            .message(&[
305                result("refs/heads/topic", None),
306                result("refs/heads/main", refused),
307            ])
308            .unwrap_or_default();
309        assert!(
310            advice.starts_with("main is the server's target branch"),
311            "{advice}"
312        );
313        assert!(advice.contains("grit integrate <branch>"), "{advice}");
314        // Refused for Git's own reasons (a checked-out branch), it still explains.
315        assert!(guard
316            .message(&[result(
317                "refs/heads/main",
318                Some(RefUpdateRefusal::CurrentBranch)
319            )])
320            .is_some());
321    }
322
323    #[test]
324    fn protocol_header_maps_versions() {
325        assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
326        assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
327    }
328}