Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 6.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! What differs between a working copy and its base, and the secrets guard.
5
6use braid_format::ChangeOp;
7
8use crate::paths::{is_within, split_last};
9use crate::scan::Delta;
10use crate::tree::same_class;
11
12/// New files larger than this are not committed until `braid track` marks
13/// them: 1 MiB.
14pub const GUARD_SIZE: u64 = 1 << 20;
15
16/// How a path differs from the base.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum ChangeKind {
19 /// A new file.
20 Added,
21 /// A file whose content or executable bit changed.
22 Modified,
23 /// A file that is gone.
24 Deleted,
25 /// A path that changed between a regular file, a symlink and a gitlink.
26 TypeChanged,
27}
28
29impl ChangeKind {
30 /// A short, stable name for reports and JSON.
31 pub fn name(self) -> &'static str {
32 match self {
33 ChangeKind::Added => "added",
34 ChangeKind::Modified => "modified",
35 ChangeKind::Deleted => "deleted",
36 ChangeKind::TypeChanged => "typechange",
37 }
38 }
39}
40
41/// One path that differs from the base.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct PathChange {
44 /// The path.
45 pub path: Vec<u8>,
46 /// How it differs.
47 pub kind: ChangeKind,
48 /// What committing it records: the file as it is now, or a delete.
49 pub op: ChangeOp,
50}
51
52/// How a working copy differs from its base.
53#[derive(Clone, Debug, Default, PartialEq, Eq)]
54pub struct Status {
55 /// Every path that a commit would record, sorted by path.
56 pub changes: Vec<PathChange>,
57 /// New files held back by the secrets guard until `braid track` marks
58 /// them, sorted.
59 pub needs_track: Vec<Vec<u8>>,
60}
61
62impl Status {
63 /// Whether nothing would be committed. Files waiting for `braid track`
64 /// do not count: they are not committed until marked.
65 pub fn is_clean(&self) -> bool {
66 self.changes.is_empty()
67 }
68}
69
70/// Whether a new file must be marked with `braid track` before it is
71/// committed: its name looks like a secret (`.env*`, `*.pem`, `id_*`, in
72/// any letter case) or it is larger than [`GUARD_SIZE`].
73pub fn is_guarded(path: &[u8], size: u64) -> bool {
74 let name = split_last(path).1.to_ascii_lowercase();
75 size > GUARD_SIZE
76 || name.starts_with(b".env")
77 || name.ends_with(b".pem")
78 || name.starts_with(b"id_")
79}
80
81/// The status of a scan's deltas (see [`Delta`]). A new file that the
82/// guard holds back is listed in `needs_track` instead, unless one of
83/// `marks` (paths given to `braid track`) is it or a directory above it.
84pub(crate) fn compare(deltas: &[Delta], marks: &[Vec<u8>]) -> Status {
85 let mut status = Status::default();
86 for delta in deltas {
87 let path = &delta.path;
88 match (&delta.old, &delta.new) {
89 (Some(_), None) => status.changes.push(PathChange {
90 path: path.clone(),
91 kind: ChangeKind::Deleted,
92 op: ChangeOp::Delete,
93 }),
94 (None, Some(new)) => {
95 if is_guarded(path, size_of(new)) && !marks.iter().any(|mark| is_within(path, mark))
96 {
97 status.needs_track.push(path.clone());
98 } else {
99 status.changes.push(PathChange {
100 path: path.clone(),
101 kind: ChangeKind::Added,
102 op: new.clone(),
103 });
104 }
105 }
106 (Some(old), Some(new)) if old != new => {
107 let kind = if same_class(old, new) {
108 ChangeKind::Modified
109 } else {
110 ChangeKind::TypeChanged
111 };
112 status.changes.push(PathChange {
113 path: path.clone(),
114 kind,
115 op: new.clone(),
116 });
117 }
118 _ => {}
119 }
120 }
121 status
122}
123
124fn size_of(op: &ChangeOp) -> u64 {
125 match op {
126 ChangeOp::File { size, .. }
127 | ChangeOp::Executable { size, .. }
128 | ChangeOp::Symlink { size, .. } => *size,
129 ChangeOp::Gitlink { .. } | ChangeOp::Delete => 0,
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use braid_format::{Kind, ObjectId};
137
138 fn file(content: &str) -> ChangeOp {
139 ChangeOp::File {
140 blob: ObjectId::hash(Kind::Blob, content.as_bytes()),
141 size: content.len() as u64,
142 }
143 }
144
145 #[test]
146 fn the_guard() {
147 for guarded in [
148 ".env",
149 ".env.local",
150 "config/.ENV",
151 "key.pem",
152 "id_rsa",
153 "a/id_ed25519",
154 ] {
155 assert!(is_guarded(guarded.as_bytes(), 10), "{guarded}");
156 }
157 for plain in ["env", "README.md", "pem.txt", "my_id_rsa", "src/main.rs"] {
158 assert!(!is_guarded(plain.as_bytes(), 10), "{plain}");
159 }
160 assert!(is_guarded(b"big.bin", GUARD_SIZE + 1));
161 assert!(!is_guarded(b"exact.bin", GUARD_SIZE));
162 }
163
164 #[test]
165 fn comparing() {
166 let delta = |path: &str, old: Option<ChangeOp>, new: Option<ChangeOp>| Delta {
167 path: path.as_bytes().to_vec(),
168 old,
169 new,
170 };
171 let target = ObjectId::hash(Kind::Blob, b"t");
172 let link = ChangeOp::Symlink {
173 blob: target,
174 size: 1,
175 };
176 // Sorted by path, as a scan gives them.
177 let deltas = [
178 delta("edited", Some(file("1")), Some(file("2"))),
179 delta("gone", Some(file("1")), None),
180 delta("keys/id_rsa", None, Some(file("k"))),
181 delta("link", Some(file("1")), Some(link)),
182 delta("new", None, Some(file("3"))),
183 delta("same", Some(file("1")), Some(file("1"))),
184 delta("secrets/.env", None, Some(file("k=v"))),
185 ];
186
187 let status = compare(&deltas, &[b"keys".to_vec()]);
188 let kinds: Vec<(&[u8], ChangeKind)> = status
189 .changes
190 .iter()
191 .map(|c| (c.path.as_slice(), c.kind))
192 .collect();
193 assert_eq!(
194 kinds,
195 [
196 (&b"edited"[..], ChangeKind::Modified),
197 (b"gone", ChangeKind::Deleted),
198 (b"keys/id_rsa", ChangeKind::Added),
199 (b"link", ChangeKind::TypeChanged),
200 (b"new", ChangeKind::Added),
201 ]
202 );
203 assert_eq!(status.changes[1].op, ChangeOp::Delete);
204 assert_eq!(status.needs_track, [b"secrets/.env".to_vec()]);
205 assert!(!status.is_clean());
206 }
207}