Skip to main content

git_policy_cli/
policy_patch_validate.rs

1//! What:
2//!  The exact supported grammar of one policy-proposed Git patch.
3//! Why:
4//!  A policy patch is untrusted output, so only one ordinary text path, its declared headers
5//!  and the candidate base index line may reach `git apply`.
6//!  The rules are the incumbent's `validatePolicyPatch`
7//!  (`src/policy-engine/commit-transaction-patch.ts`).
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! validatePolicyPatch({ patch, expectedRevision });
12//! ```
13
14use super::policy_patch::{PatchError, PolicyPatch};
15
16/// What:
17///  The validation input: the proposed patch and the exact candidate blob it must base on.
18/// Why:
19///   One object keeps the check's two inputs named at every call site.
20///
21/// In TS you'd write (pseudocode):
22/// ```ts
23/// type PatchCheck = { patch: PolicyPatch; expectedRevision: string };
24/// ```
25pub struct PatchCheck<'a> {
26    /// Policy patch under check.
27    pub patch: &'a PolicyPatch,
28    /// Exact candidate blob revision the patch's index line names as its base.
29    pub expected_revision: &'a str,
30}
31
32/// What:
33///  Directive prefixes a single-file text patch must not contain.
34/// Why:
35///   Renames, copies, mode changes, binary and deleted or new files change more than the declared text path.
36///
37/// In TS you'd write (pseudocode):
38/// ```ts
39/// const FORBIDDEN_PATCH_PREFIXES = ['rename from ', 'rename to ', ...];
40/// ```
41const FORBIDDEN_PATCH_PREFIXES: [&str; 10] = [
42    "rename from ",
43    "rename to ",
44    "copy from ",
45    "copy to ",
46    "new file mode ",
47    "deleted file mode ",
48    "old mode ",
49    "new mode ",
50    "GIT binary patch",
51    "Binary files ",
52];
53
54/// What:
55///  Check a policy patch against the exact supported grammar.
56/// Why:
57///   Each rule removes one way a proposal could address another path or change another mode.
58///
59/// In TS you'd write (pseudocode):
60/// ```ts
61/// validatePolicyPatch({ patch, expectedRevision }); // throws TypeError
62/// ```
63pub fn validate_policy_patch(check: PatchCheck<'_>) -> Result<(), PatchError> {
64    if path_is_unsafe(check.patch.path.as_str()) {
65        return Err(PatchError::Rejected(format!(
66            "Patch path contains an unsupported delimiter or traversal segment: {}",
67            check.patch.path
68        )));
69    }
70    let text: String = String::from_utf8_lossy(check.patch.bytes.as_slice()).into_owned();
71    let lines: Vec<&str> = text.split('\n').collect();
72    if !headers_are_exact(lines.as_slice(), check.patch.path.as_str(), check.expected_revision) {
73        return Err(PatchError::Rejected(format!(
74            "Patch must contain exactly declared ordinary text path {}",
75            check.patch.path
76        )));
77    }
78    return Ok(());
79}
80
81/// What:
82///  Whether a repository path has a delimiter or a traversal segment.
83/// Why:
84///   The path is interpolated into patch headers, so it must not carry line breaks, absolute roots or `.`/`..`.
85///
86/// In TS you'd write (pseudocode):
87/// ```ts
88/// patch.path.includes('\n') || patch.path.startsWith('/') || segments.some(isTraversal);
89/// ```
90fn path_is_unsafe(path: &str) -> bool {
91    if path.contains('\n') || path.contains('\r') || path.starts_with('/') {
92        return true;
93    }
94    for segment in path.split('/') {
95        if segment == ".." || segment == "." {
96            return true;
97        }
98    }
99    return false;
100}
101
102/// What:
103///  Whether the patch lines carry exactly the declared headers and no other path, mode or directive.
104/// Why:
105///   `git apply --3way` trusts the headers it reads, so a single-path grammar is checked before Git sees them.
106///
107/// In TS you'd write (pseudocode):
108/// ```ts
109/// lines[0] === requiredHeader && counts.every(c => c === 1) && indexHeaders.length === 1;
110/// ```
111fn headers_are_exact(lines: &[&str], path: &str, expected_revision: &str) -> bool {
112    let required: String = format!("diff --git a/{path} b/{path}");
113    let old: String = format!("--- a/{path}");
114    let new: String = format!("+++ b/{path}");
115    if lines.first().copied() != Some(required.as_str()) {
116        return false;
117    }
118    if count_equal(lines, required.as_str()) != 1
119        || count_equal(lines, old.as_str()) != 1
120        || count_equal(lines, new.as_str()) != 1
121    {
122        return false;
123    }
124    let indexes: Vec<&str> = index_headers(lines);
125    if indexes.len() != 1 {
126        return false;
127    }
128    let Some(index_line) = indexes.first().copied() else {
129        return false;
130    };
131    let prefix: String = format!("index {expected_revision}..");
132    if !index_line.starts_with(prefix.as_str()) || !is_valid_index_header(index_line, expected_revision) {
133        return false;
134    }
135    for line in lines {
136        if mismatched_path_directive(line, required.as_str(), old.as_str(), new.as_str())
137            || forbidden_directive(line)
138        {
139            return false;
140        }
141    }
142    return true;
143}
144
145/// What:
146///  How many lines equal a wanted header.
147/// Why:
148///   Exactly one declared target means each header appears once.
149///
150/// In TS you'd write (pseudocode):
151/// ```ts
152/// lines.filter((line) => line === header).length;
153/// ```
154fn count_equal(lines: &[&str], wanted: &str) -> usize {
155    let mut count: usize = 0;
156    for line in lines {
157        if *line == wanted {
158            count += 1;
159        }
160    }
161    return count;
162}
163
164/// What:
165///  The `index ` lines of the patch.
166/// Why:
167///   A single-file patch carries one index line, which names the candidate base.
168///
169/// In TS you'd write (pseudocode):
170/// ```ts
171/// lines.filter((line) => line.startsWith('index '));
172/// ```
173fn index_headers<'a>(lines: &[&'a str]) -> Vec<&'a str> {
174    let mut found: Vec<&str> = Vec::new();
175    for line in lines {
176        if line.starts_with("index ") {
177            found.push(*line);
178        }
179    }
180    return found;
181}
182
183/// What:
184///  Whether a `diff --git`, `---` or `+++` line names a path other than the declared one.
185/// Why:
186///   A patch that names a second file would change a path the policy did not propose.
187///
188/// In TS you'd write (pseudocode):
189/// ```ts
190/// (line.startsWith('diff --git ') && line !== requiredHeader) || ...;
191/// ```
192fn mismatched_path_directive(line: &str, required: &str, old: &str, new: &str) -> bool {
193    return (line.starts_with("diff --git ") && line != required)
194        || (line.starts_with("--- ") && line != old)
195        || (line.starts_with("+++ ") && line != new);
196}
197
198/// What:
199///  Whether a line starts with a forbidden directive prefix.
200/// Why:
201///   Forbidden directives change more than the content of the declared text file.
202///
203/// In TS you'd write (pseudocode):
204/// ```ts
205/// FORBIDDEN_PATCH_PREFIXES.some((prefix) => line.startsWith(prefix));
206/// ```
207fn forbidden_directive(line: &str) -> bool {
208    for prefix in FORBIDDEN_PATCH_PREFIXES {
209        if line.starts_with(prefix) {
210            return true;
211        }
212    }
213    return false;
214}
215
216/// What:
217///  Whether an index line is `index <base>..<new> <100644|100755>` with the exact base.
218/// Why:
219///   The base must be the candidate blob, and the new side must be a same-length lowercase object ID.
220///
221/// In TS you'd write (pseudocode):
222/// ```ts
223/// const [range, mode] = line.slice(6).split(' '); // range === `${base}..${newId}`
224/// ```
225fn is_valid_index_header(line: &str, expected_revision: &str) -> bool {
226    let Some(fields_text) = line.strip_prefix("index ") else {
227        return false;
228    };
229    let fields: Vec<&str> = fields_text.split(' ').collect();
230    let [range_text, mode_text] = fields.as_slice() else {
231        return false;
232    };
233    let range: &str = range_text;
234    let mode: &str = mode_text;
235    if mode != "100644" && mode != "100755" {
236        return false;
237    }
238    let Some(delimiter) = range.find("..") else {
239        return false;
240    };
241    if range[delimiter + 2..].contains("..") {
242        return false;
243    }
244    let old_revision: &str = &range[..delimiter];
245    let new_revision: &str = &range[delimiter + 2..];
246    return old_revision == expected_revision
247        && new_revision.len() == expected_revision.len()
248        && new_revision.bytes().all(is_lowercase_hex_byte);
249}
250
251/// What:
252///  Whether a byte is a lowercase hexadecimal digit.
253/// Why:
254///   Git object IDs are lowercase hexadecimal, and a proposal must match that alphabet exactly.
255///
256/// In TS you'd write (pseudocode):
257/// ```ts
258/// /^[0-9a-f]$/.test(char);
259/// ```
260fn is_lowercase_hex_byte(byte: u8) -> bool {
261    return byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte);
262}