Skip to main content

surjection_core/store/
log.rs

1//! Store history (SPEC 9.3, log only): commits with op, entities, scope,
2//! machine and time, filtered by entity or scope; and the leak scan of the
3//! whole history (SPEC 11.8, `surject doctor --scan-history`).
4
5use std::collections::HashSet;
6use std::path::Path;
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use git2::{Commit, ObjectType, Oid, Sort, Tree, TreeWalkMode, TreeWalkResult};
10
11use crate::error::CoreError;
12use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, LeakFinding, scan_text};
13use crate::store::trailers::{Scope, Trailers, message_summary};
14use crate::store::{CommitId, Store, git_error, utc_datetime};
15
16/// A possible leak in a past commit.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct HistoryFinding {
19    /// The newest commit holding the flagged file version (or message).
20    pub commit: CommitId,
21    pub finding: LeakFinding,
22}
23
24/// One store commit.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct LogEntry {
27    pub id: CommitId,
28    /// Commit time.
29    pub time: SystemTime,
30    pub author_name: String,
31    pub author_email: String,
32    /// The first line of the message.
33    pub summary: String,
34    pub trailers: Trailers,
35}
36
37impl LogEntry {
38    /// [`Self::time`] as RFC 3339 in UTC (`2026-01-01T00:00:00Z`).
39    pub fn time_rfc3339(&self) -> String {
40        utc_datetime(self.time).to_string()
41    }
42}
43
44/// Which commits [`Store::log`] returns. The default is every commit.
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct LogFilter {
47    /// Commits naming this entity in a `Surjection-Entity` trailer, or changing
48    /// one of its files (so hand-made commits are found too).
49    pub entity: Option<String>,
50    /// Commits whose `Surjection-Scope` is this scope.
51    pub scope: Option<Scope>,
52    /// At most this many commits, newest first.
53    pub limit: Option<usize>,
54    /// Only commits after this one in the walk (older than it): the cursor
55    /// of a paged list, the last commit of the previous page. A commit the
56    /// walk never reaches gives no commits.
57    pub before: Option<CommitId>,
58}
59
60/// Store-relative files and directories holding an entity
61/// (`server/github` is `servers/github.toml`). Unknown kinds hold none.
62pub fn entity_paths(entity: &str) -> Vec<String> {
63    match entity.split_once('/') {
64        Some(("server", id)) => vec![format!("servers/{id}.toml")],
65        Some(("skill", id)) => vec![format!("skills/{id}"), format!("skill-meta/{id}.toml")],
66        Some(("project", id)) => vec![format!("projects/{id}")],
67        Some(("machine", id)) => vec![
68            format!("machines/{id}.toml"),
69            format!("machines/{id}.applied.toml"),
70        ],
71        None if matches!(entity, "secrets" | "clients" | "settings" | "sources") => {
72            vec![format!("{entity}.toml")]
73        }
74        _ => Vec::new(),
75    }
76    .into_iter()
77    .filter(|path| !path.split('/').any(|part| part.is_empty() || part == ".."))
78    .collect()
79}
80
81impl Store<'_> {
82    /// How many commits HEAD reaches; walks ids only, reads no commit.
83    pub fn commit_count(&self) -> Result<usize, CoreError> {
84        let mut walk = self.repo.revwalk().map_err(git_error)?;
85        walk.push_head().map_err(git_error)?;
86        let mut count = 0;
87        for oid in walk {
88            oid.map_err(git_error)?;
89            count += 1;
90        }
91        Ok(count)
92    }
93
94    /// Commits reachable from HEAD, newest first, matching `filter`.
95    pub fn log(&self, filter: &LogFilter) -> Result<Vec<LogEntry>, CoreError> {
96        let mut walk = self.repo.revwalk().map_err(git_error)?;
97        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
98            .map_err(git_error)?;
99        walk.push_head().map_err(git_error)?;
100        let paths = filter
101            .entity
102            .as_deref()
103            .map(entity_paths)
104            .unwrap_or_default();
105
106        let mut entries = Vec::new();
107        let mut past_cursor = filter.before.is_none();
108        for oid in walk {
109            if filter.limit.is_some_and(|limit| entries.len() >= limit) {
110                break;
111            }
112            let oid = oid.map_err(git_error)?;
113            if !past_cursor {
114                // Skipped commits are not read, only compared by id.
115                past_cursor = filter.before.as_ref() == Some(&CommitId::from_oid(oid));
116                continue;
117            }
118            let commit = self.repo.find_commit(oid).map_err(git_error)?;
119            let message = String::from_utf8_lossy(commit.message_bytes());
120            let trailers = Trailers::parse(&message);
121            if filter
122                .scope
123                .as_ref()
124                .is_some_and(|scope| trailers.scope.as_ref() != Some(scope))
125            {
126                continue;
127            }
128            if let Some(entity) = &filter.entity
129                && !trailers.entities.contains(entity)
130                && !touches(&commit, &paths)?
131            {
132                continue;
133            }
134            entries.push(log_entry(&commit, trailers));
135        }
136        Ok(entries)
137    }
138
139    /// The commit `id` as a log entry, with its full message.
140    pub fn entry(&self, id: &CommitId) -> Result<(LogEntry, String), CoreError> {
141        let oid = Oid::from_str(id.as_str()).map_err(git_error)?;
142        let commit = self.repo.find_commit(oid).map_err(git_error)?;
143        let message = String::from_utf8_lossy(commit.message_bytes()).into_owned();
144        let trailers = Trailers::parse(&message);
145        Ok((log_entry(&commit, trailers), message))
146    }
147
148    /// The leak scanner over every commit message and every file version
149    /// reachable from HEAD (SPEC 11.8), for stores imported from
150    /// elsewhere. Reports only; history is never rewritten. Each file
151    /// version is scanned once, at the newest commit holding it; the
152    /// working tree's allowlist applies.
153    pub fn scan_history(&self) -> Result<Vec<HistoryFinding>, CoreError> {
154        let allow = Allowlist::parse(&self.read_to_string(ALLOWLIST_FILE)?.unwrap_or_default());
155        let mut walk = self.repo.revwalk().map_err(git_error)?;
156        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
157            .map_err(git_error)?;
158        walk.push_head().map_err(git_error)?;
159        let mut seen = HashSet::new();
160        let mut findings = Vec::new();
161        for oid in walk {
162            let commit = self
163                .repo
164                .find_commit(oid.map_err(git_error)?)
165                .map_err(git_error)?;
166            let id = CommitId::from_oid(commit.id());
167            let mut found = scan_text(
168                "commit message",
169                commit.message_bytes(),
170                false,
171                &self.secrets,
172                &allow,
173            );
174            let mut blobs = Vec::new();
175            commit
176                .tree()
177                .map_err(git_error)?
178                .walk(TreeWalkMode::PreOrder, |root, entry| {
179                    if entry.kind() == Some(ObjectType::Blob) && seen.insert(entry.id()) {
180                        let name = String::from_utf8_lossy(entry.name_bytes());
181                        blobs.push((format!("{root}{name}"), entry.id()));
182                    }
183                    TreeWalkResult::Ok
184                })
185                .map_err(git_error)?;
186            for (path, blob) in blobs {
187                let blob = self.repo.find_blob(blob).map_err(git_error)?;
188                found.extend(scan_text(
189                    &path,
190                    blob.content(),
191                    path.ends_with(".toml"),
192                    &self.secrets,
193                    &allow,
194                ));
195            }
196            findings.extend(found.into_iter().map(|finding| HistoryFinding {
197                commit: id.clone(),
198                finding,
199            }));
200        }
201        Ok(findings)
202    }
203}
204
205/// Whether `commit` changed any of `paths` relative to its first parent.
206pub(crate) fn touches(commit: &Commit<'_>, paths: &[String]) -> Result<bool, CoreError> {
207    if paths.is_empty() {
208        return Ok(false);
209    }
210    let tree = commit.tree().map_err(git_error)?;
211    let parent_tree = match commit.parent(0) {
212        Ok(parent) => Some(parent.tree().map_err(git_error)?),
213        Err(_) => None,
214    };
215    Ok(paths
216        .iter()
217        .any(|path| entry_id(Some(&tree), path) != entry_id(parent_tree.as_ref(), path)))
218}
219
220fn entry_id(tree: Option<&Tree<'_>>, path: &str) -> Option<Oid> {
221    tree?.get_path(Path::new(path)).ok().map(|entry| entry.id())
222}
223
224pub(crate) fn commit_time(commit: &Commit<'_>) -> SystemTime {
225    let seconds = commit.time().seconds();
226    match u64::try_from(seconds) {
227        Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
228        Err(_) => UNIX_EPOCH,
229    }
230}
231
232fn log_entry(commit: &Commit<'_>, trailers: Trailers) -> LogEntry {
233    let message = String::from_utf8_lossy(commit.message_bytes());
234    let author = commit.author();
235    LogEntry {
236        id: CommitId::from_oid(commit.id()),
237        time: commit_time(commit),
238        author_name: String::from_utf8_lossy(author.name_bytes()).into_owned(),
239        author_email: String::from_utf8_lossy(author.email_bytes()).into_owned(),
240        summary: message_summary(&message).to_owned(),
241        trailers,
242    }
243}