Skip to main content

git_policy_cli/
manual_push_probe.rs

1//! What:
2//!  The authoritative ref updates a `git push` would send, discovered by a private dry-run push.
3//! Why:
4//!  The manual-push policies must scan exactly what Git would publish, so the probe asks Git:
5//!  a private `pre-push` hook in a private directory records the update lines Git negotiated
6//!  (`src/policy-engine/manual-push-hook.ts`), and `git ls-remote --refs` confirms each destination value.
7//!  A remote ref that changed between negotiation and confirmation stops the probe.
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! const updates = await probeManualPushUpdates({ gitPath, cwd, args });
12//! ```
13
14/// The probe's Git runner and its environment.
15use super::auto_push_single_flight::{PushGit, git_command};
16/// Unguessable names for the private probe directory.
17use super::random_id::random_uuid;
18/// Owned OS strings for the probe's Git arguments.
19use std::ffi::OsString;
20/// Reading and writing the private hook and its captures.
21use std::fs;
22/// `Path` and `PathBuf` are borrowed and owned filesystem paths.
23use std::path::{Path, PathBuf};
24/// `Stdio` connects the probe's standard input and output.
25use std::process::Stdio;
26
27/// Environment variable naming the capture directory the hook writes to.
28pub const CAPTURE_DIRECTORY_ENV: &str = "CLI_GIT_PUSH_FACTS_DIRECTORY";
29
30/// Fields of one `pre-push` update record: local ref, local object, remote ref, remote object.
31pub const PRE_PUSH_FIELD_COUNT: usize = 4;
32
33/// Largest standard input the recording hook accepts, in bytes, as the incumbent's hook does.
34pub const MAX_HOOK_INPUT_BYTES: u64 = 16 * 1024 * 1024;
35
36/// Private directory mode for the probe directories, shared with the incumbent.
37const PRIVATE_DIRECTORY_MODE: u32 = 0o700;
38
39/// Name of the recording hook inside the private hooks directory.
40const HOOK_NAME: &str = "pre-push";
41
42/// Suffix of a capture file the hook writes, one per invocation.
43const CAPTURE_SUFFIX: &str = ".capture";
44
45/// What:
46///  Why the probe could not establish the updates Git would push.
47/// Why:
48///   Every variant stops the policy lifecycle with a content-unavailable failure; none guesses an update.
49///
50/// In TS you'd write (pseudocode):
51/// ```ts
52/// class ManualPushProbeError extends Error {}
53/// ```
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub struct ManualPushProbeError {
56    /// Diagnostic naming what could not be established.
57    pub message: String,
58}
59
60impl std::fmt::Display for ManualPushProbeError {
61    /// Writes the diagnostic text.
62    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        return formatter.write_str(&self.message);
64    }
65}
66
67impl std::error::Error for ManualPushProbeError {}
68
69/// Build a probe error from text.
70///
71/// In TS you'd write (pseudocode):
72/// ```ts
73/// new ManualPushProbeError(message)
74/// ```
75fn probe_error(message: String) -> ManualPushProbeError {
76    return ManualPushProbeError { message };
77}
78
79/// What:
80///  One update record a hook capture holds, before remote confirmation.
81/// Why:
82///   The advertised remote object is Git's negotiated value; the confirmation must agree with it.
83///
84/// In TS you'd write (pseudocode):
85/// ```ts
86/// type ProbedPushUpdate = { localRef; localOid; remoteName; remoteLocation; remoteRef; advertisedRemoteOid };
87/// ```
88#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct ProbedUpdate {
90    /// Local ref Git pushes from.
91    pub local_ref: String,
92    /// Local object name, all zeros for a deletion.
93    pub local_oid: String,
94    /// Destination remote name, as Git passed it to the hook.
95    pub remote_name: String,
96    /// Destination location, as Git passed it to the hook.
97    pub remote_location: String,
98    /// Destination ref Git updates.
99    pub remote_ref: String,
100    /// Destination object Git negotiated, all zeros when the ref is new.
101    pub advertised_remote_oid: String,
102}
103
104/// What:
105///  One confirmed push update, the public fact the policies read.
106/// Why:
107///   An absent value is `None`, which replaces the incumbent's `ABSENT_GIT_VALUE` sentinel.
108///
109/// In TS you'd write (pseudocode):
110/// ```ts
111/// type PushUpdate = { localOid: string | typeof ABSENT_GIT_VALUE; remoteOid: string | typeof ABSENT_GIT_VALUE; remoteName; remoteRef };
112/// ```
113#[derive(Clone, Debug, Eq, PartialEq)]
114pub struct PushUpdate {
115    /// Local object name; `None` for a deletion.
116    pub local_oid: Option<String>,
117    /// Destination object name confirmed by `ls-remote`; `None` when the ref is absent.
118    pub remote_oid: Option<String>,
119    /// Destination remote name.
120    pub remote_name: String,
121    /// Destination ref.
122    pub remote_ref: String,
123}
124
125/// What:
126///  Whether a hexadecimal object name is the all-zero absence value.
127///
128/// In TS you'd write (pseudocode):
129/// ```ts
130/// function isZeroOid(oid: string): boolean { return /^0+$/.test(oid); }
131/// ```
132pub fn is_zero_oid(oid: &str) -> bool {
133    return !oid.is_empty()
134        && oid.bytes().all(|byte| {
135            return byte == b'0';
136        });
137}
138
139/// What:
140///  Parse the hook's standard input, one update per line.
141/// Why:
142///   Git guarantees four space-separated fields per update record; anything else stops the probe.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// function parseCapture(capture): ProbedPushUpdate[];
147/// ```
148pub fn parse_update_records(
149    input: &str,
150    remote_name: &str,
151    remote_location: &str,
152) -> Result<Vec<ProbedUpdate>, ManualPushProbeError> {
153    let mut updates: Vec<ProbedUpdate> = Vec::new();
154    for line in input.split('\n').filter(|line| {
155        return !line.is_empty();
156    }) {
157        let parts: Vec<&str> = line.split(' ').collect();
158        if parts.len() != PRE_PUSH_FIELD_COUNT {
159            return Err(probe_error(format!(
160                "Malformed pre-push update record: {line}"
161            )));
162        }
163        updates.push(ProbedUpdate {
164            local_ref: parts[0].to_owned(),
165            local_oid: parts[1].to_owned(),
166            remote_name: remote_name.to_owned(),
167            remote_location: remote_location.to_owned(),
168            remote_ref: parts[2].to_owned(),
169            advertised_remote_oid: parts[3].to_owned(),
170        });
171    }
172    return Ok(updates);
173}
174
175/// What:
176///  The probe's Git arguments: the invocation's global options, the hook path override,
177///  then `push` with `--dry-run --verify` placed before any `--` terminator.
178/// Why:
179///   The `--` terminator is the user's; the options Git interprets must stay before it.
180///
181/// In TS you'd write (pseudocode):
182/// ```ts
183/// probeArgs({ args, hooksDirectory });
184/// ```
185pub fn probe_arguments(
186    global_prefix: &[OsString],
187    post_subcommand: &[OsString],
188    hooks_directory: &Path,
189) -> Vec<OsString> {
190    let separator = post_subcommand.iter().position(|argument| {
191        return argument.as_os_str() == "--";
192    });
193    let insertion = separator.unwrap_or(post_subcommand.len());
194    let mut arguments: Vec<OsString> = global_prefix.to_vec();
195    arguments.push(OsString::from("-c"));
196    arguments.push(OsString::from(format!(
197        "core.hooksPath={}",
198        hooks_directory.display()
199    )));
200    arguments.push(OsString::from("push"));
201    arguments.extend(post_subcommand[..insertion].iter().cloned());
202    arguments.push(OsString::from("--dry-run"));
203    arguments.push(OsString::from("--verify"));
204    arguments.extend(post_subcommand[insertion..].iter().cloned());
205    return arguments;
206}
207
208/// What:
209///  The recording hook's shell program: write the remote name and location, then the update lines, to a
210///  new capture file named by the hook's process ID.
211/// Why:
212///   `set -C` makes the redirection exclusive, so two destinations never overwrite each other's capture.
213///
214/// In TS you'd write (pseudocode):
215/// ```ts
216/// hookSource(): string; // `#!${process.execPath}` plus the capture writer
217/// ```
218pub fn hook_source() -> String {
219    return format!(
220        "#!/bin/sh\nset -C\n{{ printf '%s\\n%s\\n' \"$1\" \"$2\"; head -c {}; }} > \"${CAPTURE_DIRECTORY_ENV}/$$.capture\" || exit 1\n",
221        MAX_HOOK_INPUT_BYTES + 1
222    );
223}
224
225/// What:
226///  Create a private directory with mode `0700`.
227///
228/// In TS you'd write (pseudocode):
229/// ```ts
230/// await mkdtemp(join(tmpdir(), 'cli-git-push-facts-'));
231/// ```
232fn create_private_directory(path: &Path) -> std::io::Result<()> {
233    use std::os::unix::fs::DirBuilderExt;
234    return fs::DirBuilder::new()
235        .mode(PRIVATE_DIRECTORY_MODE)
236        .create(path);
237}
238
239/// What:
240///  Run the private dry-run push and read back the updates its hook captured.
241/// Why:
242///   Git may exit non-zero after the hook has captured the negotiated updates, so the captures decide,
243///  and an empty capture set is a probe failure.
244///
245/// In TS you'd write (pseudocode):
246/// ```ts
247/// async function captureProbedPushUpdates({ gitPath, cwd, args }): Promise<ProbedPushUpdate[]>;
248/// ```
249pub fn capture_probed_updates(
250    git: &PushGit,
251    global_prefix: &[OsString],
252    post_subcommand: &[OsString],
253    scratch: &Path,
254) -> Result<Vec<ProbedUpdate>, ManualPushProbeError> {
255    let hooks = scratch.join("hooks");
256    let captures = scratch.join("captures");
257    for directory in [scratch, hooks.as_path(), captures.as_path()] {
258        create_private_directory(directory).map_err(|error| {
259            return probe_error(format!(
260                "private probe directory {} could not be created: {error}",
261                directory.display()
262            ));
263        })?;
264    }
265    let hook_path = hooks.join(HOOK_NAME);
266    fs::write(&hook_path, hook_source()).map_err(|error| {
267        return probe_error(format!("hook write failed: {error}"));
268    })?;
269    set_executable(&hook_path)?;
270    let arguments = probe_arguments(global_prefix, post_subcommand, &hooks);
271    let mut command = git_command(git, &arguments);
272    command
273        .stdin(Stdio::null())
274        .env(CAPTURE_DIRECTORY_ENV, &captures);
275    let probe = command.output().map_err(|error| {
276        return probe_error(format!("probe push could not start: {error}"));
277    })?;
278    let mut names: Vec<PathBuf> = fs::read_dir(&captures)
279        .map_err(|error| {
280            return probe_error(format!("captures unreadable: {error}"));
281        })?
282        .map(|entry| {
283            return entry.map(|found| {
284                return found.path();
285            });
286        })
287        .collect::<Result<Vec<PathBuf>, std::io::Error>>()
288        .map_err(|error| {
289            return probe_error(format!("captures unreadable: {error}"));
290        })?;
291    names.retain(|path| {
292        return path.to_string_lossy().ends_with(CAPTURE_SUFFIX);
293    });
294    names.sort();
295    if names.is_empty() {
296        return Err(probe_error(format!(
297            "Git could not determine push updates: {}",
298            String::from_utf8_lossy(&probe.stderr).trim_end()
299        )));
300    }
301    let mut updates: Vec<ProbedUpdate> = Vec::new();
302    let _scratch_guard = ScratchGuard(scratch.to_path_buf());
303    for path in names {
304        let bytes = fs::read(&path).map_err(|error| {
305            return probe_error(format!("capture unreadable: {error}"));
306        })?;
307        let text = String::from_utf8_lossy(&bytes);
308        let mut lines = text.splitn(3, '\n');
309        let remote_name = lines.next().unwrap_or_default();
310        let remote_location = lines.next().unwrap_or_default();
311        let input = lines.next().unwrap_or_default();
312        if input.len() as u64 > MAX_HOOK_INPUT_BYTES {
313            return Err(probe_error(
314                "Pre-push input exceeded capture limit.".to_owned(),
315            ));
316        }
317        updates.extend(parse_update_records(input, remote_name, remote_location)?);
318    }
319    return Ok(updates);
320}
321
322/// What:
323///  Removes the private probe directory when the probe ends, on every path.
324/// Why:
325///   Captures hold the names and tips of unpublished refs and must not outlive the probe.
326///
327/// In TS you'd write (pseudocode):
328/// ```ts
329/// await using directory = await createProbeDirectory();
330/// ```
331struct ScratchGuard(PathBuf);
332
333impl Drop for ScratchGuard {
334    /// Removes the directory; a failure leaves only a private directory in the temporary area.
335    fn drop(&mut self) {
336        let _removed = fs::remove_dir_all(&self.0);
337    }
338}
339
340/// Mark a file executable by its owner only.
341///
342/// In TS you'd write (pseudocode):
343/// ```ts
344/// await chmod(hookPath, 0o700);
345/// ```
346fn set_executable(path: &Path) -> Result<(), ManualPushProbeError> {
347    use std::os::unix::fs::PermissionsExt;
348    return fs::set_permissions(path, fs::Permissions::from_mode(PRIVATE_DIRECTORY_MODE)).map_err(
349        |error| {
350            return probe_error(format!("hook mode failed: {error}"));
351        },
352    );
353}
354
355/// Parse `git ls-remote --refs` records into a ref-to-object map.
356///
357/// In TS you'd write (pseudocode):
358/// ```ts
359/// function parseRemoteRefs(output: string): ReadonlyMap<string, string>;
360/// ```
361pub fn parse_remote_refs(output: &str) -> Result<Vec<(String, String)>, ManualPushProbeError> {
362    let mut refs: Vec<(String, String)> = Vec::new();
363    for line in output.split('\n').filter(|line| {
364        return !line.is_empty();
365    }) {
366        let Some((oid, name)) = line.split_once('\t') else {
367            return Err(probe_error(format!("Malformed ls-remote record: {line}")));
368        };
369        refs.push((name.to_owned(), oid.to_owned()));
370    }
371    return Ok(refs);
372}
373
374/// What:
375///  Confirm one destination's values with `git ls-remote --refs` and turn each probed update into a public update.
376/// Why:
377///   A destination that changed after negotiation would publish something the scan did not see,
378///  so a mismatch between negotiation and confirmation is an error, never a silent repair.
379///
380/// In TS you'd write (pseudocode):
381/// ```ts
382/// async function resolveRemoteGroup({ gitPath, cwd, remoteLocation, updates }): Promise<PushUpdate[]>;
383/// ```
384pub fn confirm_group(
385    git: &PushGit,
386    remote_location: &str,
387    updates: &[ProbedUpdate],
388) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
389    let mut arguments: Vec<OsString> = vec![
390        OsString::from("ls-remote"),
391        OsString::from("--refs"),
392        OsString::from(remote_location),
393    ];
394    arguments.extend(updates.iter().map(|update| {
395        return OsString::from(&update.remote_ref);
396    }));
397    let output = git_command(git, &arguments)
398        .stdin(Stdio::null())
399        .output()
400        .map_err(|error| {
401            return probe_error(format!("ls-remote could not start: {error}"));
402        })?;
403    if !output.status.success() {
404        return Err(probe_error(format!(
405            "ls-remote of {remote_location} failed: {}",
406            String::from_utf8_lossy(&output.stderr).trim_end()
407        )));
408    }
409    let remote_refs = parse_remote_refs(&String::from_utf8_lossy(&output.stdout))?;
410    let mut confirmed: Vec<PushUpdate> = Vec::new();
411    for update in updates {
412        let authoritative: Option<&String> = remote_refs
413            .iter()
414            .find(|(name, _oid)| {
415                return name == &update.remote_ref;
416            })
417            .map(|(_name, oid)| {
418                return oid;
419            });
420        let advertised_absent = is_zero_oid(&update.advertised_remote_oid);
421        if authoritative.is_none() != advertised_absent {
422            return Err(probe_error(format!(
423                "Remote ref changed during manual-push discovery: {}",
424                update.remote_ref
425            )));
426        }
427        if let Some(oid) = authoritative
428            && *oid != update.advertised_remote_oid
429        {
430            return Err(probe_error(format!(
431                "Remote ref changed during manual-push discovery: {}",
432                update.remote_ref
433            )));
434        }
435        confirmed.push(PushUpdate {
436            local_oid: if is_zero_oid(&update.local_oid) {
437                None
438            } else {
439                Some(update.local_oid.clone())
440            },
441            remote_oid: authoritative.cloned(),
442            remote_name: update.remote_name.clone(),
443            remote_ref: update.remote_ref.clone(),
444        });
445    }
446    return Ok(confirmed);
447}
448
449/// What:
450///  Discover the exact updates the push would send, confirmed against each destination.
451/// Why:
452///   The lifecycle's candidates and published-set reads both start from these updates.
453///
454/// In TS you'd write (pseudocode):
455/// ```ts
456/// async function probeManualPushUpdates({ gitPath, cwd, args }): Promise<PushUpdate[]>;
457/// ```
458pub fn probe_manual_push_updates(
459    git: &PushGit,
460    global_prefix: &[OsString],
461    post_subcommand: &[OsString],
462) -> Result<Vec<PushUpdate>, ManualPushProbeError> {
463    let scratch = std::env::temp_dir().join(format!(
464        "cli-git-push-facts-{}",
465        random_uuid().map_err(|error| {
466            return probe_error(format!("random source failed: {}", error.0));
467        })?
468    ));
469    let probed = capture_probed_updates(git, global_prefix, post_subcommand, &scratch)?;
470    let mut locations: Vec<String> = Vec::new();
471    for update in &probed {
472        if !locations.contains(&update.remote_location) {
473            locations.push(update.remote_location.clone());
474        }
475    }
476    let mut confirmed: Vec<PushUpdate> = Vec::new();
477    for location in &locations {
478        let group: Vec<ProbedUpdate> = probed
479            .iter()
480            .filter(|update| {
481                return &update.remote_location == location;
482            })
483            .cloned()
484            .collect();
485        confirmed.extend(confirm_group(git, location, &group)?);
486    }
487    return Ok(confirmed);
488}
489
490/// The probe's parsers and its confirmation rules are controlled in the test module.
491#[cfg(test)]
492#[path = "manual_push_probe_tests.rs"]
493mod tests;