grit-protocol 0.5.29

Git smart protocol handlers for the grit implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Git smart protocol handlers for HTTP transport.
//!
//! Runs upload-pack and receive-pack in-process via [`grit_lib::remote::serve`], with
//! no subprocess or external `grit` binary. Every push runs the [`PushGuard`], which
//! keeps pushes off the target branch of a repository with snapshot checkouts.

pub mod receive_pack;
pub mod session;
pub mod upload_pack;

use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use grit_lib::config::git_path::path_for_error_message;
use grit_lib::config::ConfigSet;

pub use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::Odb;
use grit_lib::remote::serve::{
    self, ProtocolVersion, ReceiveHook, ReceiveHookContext, ReceiveOutcome, ReceivePolicy,
    RefCommand, RefUpdateRefusal, RefUpdateResult, ServeOptions, UploadOutcome,
};
use grit_lib::remote::snapshot_checkout::TargetGuard;
use grit_lib::repo::Repository;

pub use session::{ReceiveRpcResult, ServeSession};

/// Errors from smart-protocol handlers.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The path does not look like a git repository.
    #[error("not a git repository: {0}")]
    NotARepository(String),
    /// Serving the wire protocol failed.
    #[error(transparent)]
    Serve(#[from] serve::ServeError),
    /// Opening or reading repository state failed.
    #[error(transparent)]
    Repository(#[from] grit_lib::error::Error),
    /// Buffered I/O failed while collecting the response.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl Error {
    /// The I/O error from reading the client's request stream, for a failed
    /// [`receive_pack::stateless_rpc_from_reader`] exchange.
    ///
    /// Servers use this to answer a request body that could not be read (truncated,
    /// badly encoded, or rejected by the server's own decoding limits) with a client
    /// error rather than a server error. During receive-pack that is the only source of
    /// stream errors: the response is collected in memory, and repository failures are
    /// reported as other [`serve::ServeError`] variants or inside the status report.
    /// Upload-pack can also return stream errors while reading repository data. When the
    /// inner error is [`grit_lib::remote::serve::RequestBodyLimitExceeded`], smart HTTP
    /// maps the failure to 413; other upload-pack stream errors are usually server faults.
    ///
    /// # Returns
    ///
    /// `Some` with the request read error, or `None` for every other failure.
    #[must_use]
    pub fn request_stream_error(&self) -> Option<&std::io::Error> {
        match self {
            Self::Serve(serve::ServeError::Io(e)) => Some(e),
            _ => None,
        }
    }
}

/// Result alias for protocol handlers.
pub type Result<T> = std::result::Result<T, Error>;

/// Server features beyond plain fetch and push, for the `_with` handlers.
#[derive(Debug, Clone, Default)]
pub struct Extensions {
    /// Bundles offered through the protocol v2 `bundle-uri` command.
    pub bundle_list: Option<grit_lib::remote::bundle_uri::BundleList>,
    /// Resumable push endpoint advertised by receive-pack as `pushBundle=<value>`.
    pub push_bundle: Option<String>,
}

/// The in-process checks every push these handlers serve gets.
///
/// A repository with snapshot checkouts refuses pushes that create, update or
/// delete its target branch ([`TargetGuard`]), and tells the pusher how its
/// work reaches the target instead. A repository without checkouts keeps
/// Git's rules.
#[derive(Debug, Clone, Default)]
pub struct PushGuard {
    target: Option<TargetGuard>,
}

impl PushGuard {
    /// The guard for pushes to `repo`.
    ///
    /// # Parameters
    ///
    /// - `repo`: the repository receiving the push.
    #[must_use]
    pub fn for_repository(repo: &Repository) -> Self {
        Self {
            target: TargetGuard::for_repository(repo),
        }
    }

    /// The branch pushes are kept off, when there is one.
    #[must_use]
    pub fn target(&self) -> Option<&str> {
        self.target.as_ref().map(TargetGuard::target)
    }
}

impl ReceiveHook for PushGuard {
    fn update(&self, command: &RefCommand, odb: &Odb) -> std::result::Result<(), RefUpdateRefusal> {
        self.target
            .as_ref()
            .map_or(Ok(()), |guard| guard.update(command, odb))
    }

    fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
        let guard = self.target.as_ref()?;
        updates
            .iter()
            .any(|u| u.error.is_some() && guard.guards(&u.refname))
            .then(|| target_push_advice(guard.target()))
    }
}

struct GuardedHook {
    guard: PushGuard,
    extra: Option<std::sync::Arc<dyn ReceiveHook + Send + Sync>>,
}

impl ReceiveHook for GuardedHook {
    fn pre_receive_ctx(
        &self,
        commands: &[RefCommand],
        odb: &Odb,
        ctx: &ReceiveHookContext<'_>,
    ) -> std::result::Result<(), RefUpdateRefusal> {
        self.guard.pre_receive_ctx(commands, odb, ctx)?;
        if let Some(h) = self.extra.as_deref() {
            h.pre_receive_ctx(commands, odb, ctx)?;
        }
        Ok(())
    }

    fn update_ctx(
        &self,
        command: &RefCommand,
        odb: &Odb,
        ctx: &ReceiveHookContext<'_>,
    ) -> std::result::Result<(), RefUpdateRefusal> {
        self.guard.update_ctx(command, odb, ctx)?;
        if let Some(h) = self.extra.as_deref() {
            h.update_ctx(command, odb, ctx)?;
        }
        Ok(())
    }

    fn message(&self, updates: &[RefUpdateResult]) -> Option<String> {
        match (
            self.guard.message(updates),
            self.extra.as_deref().and_then(|h| h.message(updates)),
        ) {
            (None, None) => None,
            (Some(a), None) => Some(a),
            (None, Some(b)) => Some(b),
            (Some(a), Some(b)) => Some(format!("{a}{b}")),
        }
    }

    fn post_receive(
        &self,
        commands: &[&RefCommand],
        odb: &Odb,
        ctx: &ReceiveHookContext<'_>,
    ) -> std::result::Result<(), RefUpdateRefusal> {
        if let Some(h) = self.extra.as_deref() {
            h.post_receive(commands, odb, ctx)?;
        }
        Ok(())
    }

    fn post_update(
        &self,
        commands: &[&RefCommand],
        odb: &Odb,
    ) -> std::result::Result<(), RefUpdateRefusal> {
        if let Some(h) = self.extra.as_deref() {
            h.post_update(commands, odb)?;
        }
        Ok(())
    }
}

/// What a pusher of the target branch `target` is told to do instead.
fn target_push_advice(target: &str) -> String {
    format!(
        "{target} is the server's target branch: pushes can't change it.\n\
         Push your work to another branch:\n\
         \x20 grit switch -c <branch>\n\
         \x20 grit push origin <branch>\n\
         then merge it into {target} from a snapshot checkout of this repository:\n\
         \x20 grit integrate <branch>\n\
         (In a snapshot checkout, `grit checkin` sends your branches and `grit integrate` merges them.)\n"
    )
}

/// Build [`RepositoryOptions`] from the current process environment
/// ([`RepositoryOptions::from_process`]).
///
/// Captures `HOME`, `GIT_CONFIG_*`, and the other variables [`ConfigSet::load`]
/// uses for global and system config. Call once at server startup and pass the
/// same options into every handler so receive policy and hide-ref rules match
/// a `grit receive-pack` / `grit upload-pack` subprocess.
#[must_use]
pub fn repository_options_from_process() -> RepositoryOptions {
    RepositoryOptions::from_process()
}

/// Map an explicit smart-HTTP protocol version header to a wire version.
#[must_use]
pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
    match version {
        Some(2) => ProtocolVersion::V2,
        Some(1) => ProtocolVersion::V1,
        _ => ProtocolVersion::V0,
    }
}

/// Validate that a path looks like a git repository (bare or non-bare).
///
/// # Errors
///
/// Returns [`Error::NotARepository`] when neither `HEAD` nor `.git/HEAD` exists.
pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
    if path.join("HEAD").is_file() {
        return Ok(path.to_path_buf());
    }
    let dot_git = path.join(".git");
    if dot_git.join("HEAD").is_file() {
        return Ok(path.to_path_buf());
    }
    Err(Error::NotARepository(path_for_error_message(path)))
}

pub(crate) fn run_upload_pack(
    repo_path: &Path,
    protocol_version: Option<u8>,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &[u8],
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
) -> Result<Vec<u8>> {
    let mut output = Vec::new();
    run_upload_pack_to(
        repo_path,
        protocol_version,
        stateless_rpc,
        advertise_refs,
        &mut &*input,
        repository_options,
        extensions,
        &mut output,
    )?;
    Ok(output)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn run_upload_pack_to(
    repo_path: &Path,
    protocol_version: Option<u8>,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &mut dyn Read,
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
    output: &mut dyn std::io::Write,
) -> Result<()> {
    run_upload_pack_with_session(
        repo_path,
        protocol_version,
        stateless_rpc,
        advertise_refs,
        input,
        repository_options,
        extensions,
        output,
        &ServeSession::none(),
    )
    .map(|_| ())
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn run_upload_pack_with_session(
    repo_path: &Path,
    protocol_version: Option<u8>,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &mut dyn Read,
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
    output: &mut dyn std::io::Write,
    session: &ServeSession,
) -> Result<UploadOutcome> {
    let without_fetcher = repository_options
        .clone()
        .with_promisor_fetcher(None)
        .for_serving();
    let repo = Repository::open(repo_path, &without_fetcher)?;
    let config =
        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
    let mut opts = ServeOptions {
        protocol: protocol_version_from_header(protocol_version),
        stateless_rpc,
        advertise_refs,
        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
        hidden_refs,
        bundle_list: extensions.bundle_list.clone(),
        push_bundle: None,
        lazy_fetch: ServeOptions::lazy_fetch_from_environment(repo.environment()),
        ..ServeOptions::default()
    };
    // The promisor fetcher in `repository_options` is used only when this request may
    // fetch missing promised objects; otherwise the served repository fetches nothing.
    opts.attach_promisor_fetcher(&repo, &config, repository_options.promisor_fetcher.clone());
    serve::upload_pack_cancellable(&repo, input, output, &mut opts, session.cancel())
        .map_err(Error::from)
}

pub(crate) fn run_receive_pack(
    repo_path: &Path,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &mut dyn Read,
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
) -> Result<Vec<u8>> {
    let mut output = Vec::new();
    run_receive_pack_to(
        repo_path,
        stateless_rpc,
        advertise_refs,
        input,
        repository_options,
        extensions,
        &mut output,
    )?;
    Ok(output)
}

pub(crate) fn run_receive_pack_to(
    repo_path: &Path,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &mut dyn Read,
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
    output: &mut dyn Write,
) -> Result<()> {
    run_receive_pack_with_session(
        repo_path,
        stateless_rpc,
        advertise_refs,
        input,
        repository_options,
        extensions,
        output,
        &ServeSession::none(),
    )
    .map(|_| ())
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn run_receive_pack_with_session(
    repo_path: &Path,
    stateless_rpc: bool,
    advertise_refs: bool,
    input: &mut dyn Read,
    repository_options: &RepositoryOptions,
    extensions: &Extensions,
    output: &mut dyn Write,
    session: &ServeSession,
) -> Result<ReceiveOutcome> {
    let options = repository_options
        .clone()
        .with_promisor_fetcher(None)
        .for_serving();
    let repo = Repository::open(repo_path, &options)?;
    let config =
        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
    let opts = ServeOptions {
        protocol: ProtocolVersion::V0,
        stateless_rpc,
        advertise_refs,
        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
        hidden_refs,
        bundle_list: None,
        push_bundle: extensions.push_bundle.clone(),
        ..ServeOptions::default()
    };
    let policy = ReceivePolicy::from_config(&config);
    let guard = PushGuard::for_repository(&repo);
    let hook = GuardedHook {
        guard,
        extra: session.receive_hook.clone(),
    };
    serve::receive_pack_with_hook_cancellable(
        &repo,
        input,
        output,
        &opts,
        &policy,
        &hook,
        session.cancel(),
    )
    .map_err(Error::from)
}

#[cfg(test)]
mod tests {
    use super::*;
    use grit_lib::remote::serve::ProtocolVersion;

    #[test]
    fn pushes_of_the_target_are_told_what_to_do_instead() {
        let result = |refname: &str, error: Option<RefUpdateRefusal>| RefUpdateResult {
            refname: refname.to_owned(),
            old: None,
            new: None,
            error,
        };
        let refused = Some(RefUpdateRefusal::TargetBranch {
            target: "main".to_owned(),
        });
        assert_eq!(
            PushGuard::default().message(&[result("refs/heads/main", refused.clone())]),
            None,
            "a repository without checkouts has no guard"
        );
        let guard = PushGuard {
            target: Some(TargetGuard::new("main")),
        };
        assert_eq!(guard.target(), Some("main"));
        assert_eq!(guard.message(&[result("refs/heads/main", None)]), None);
        assert_eq!(
            guard.message(&[result(
                "refs/heads/topic",
                Some(RefUpdateRefusal::StaleInfo)
            )]),
            None
        );
        let advice = guard
            .message(&[
                result("refs/heads/topic", None),
                result("refs/heads/main", refused),
            ])
            .unwrap_or_default();
        assert!(
            advice.starts_with("main is the server's target branch"),
            "{advice}"
        );
        assert!(advice.contains("grit integrate <branch>"), "{advice}");
        // Refused for Git's own reasons (a checked-out branch), it still explains.
        assert!(guard
            .message(&[result(
                "refs/heads/main",
                Some(RefUpdateRefusal::CurrentBranch)
            )])
            .is_some());
    }

    #[test]
    fn protocol_header_maps_versions() {
        assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
        assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
    }
}