Skip to main content

lean_ctx/core/
integrity.rs

1//! Build-origin integrity verification and rebrand resistance.
2//!
3//! Detects if the binary has been modified by automated rebranding tools
4//! (e.g. `sed s/lean-ctx/better-ctx/g`). The integrity seed is a compile-time
5//! constant; its hash is precomputed and embedded. If the seed is altered by
6//! a text-replacement tool, the hash will no longer match.
7
8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};
10
11const INTEGRITY_SEED: &str = "lean-ctx";
12const ORIGIN_REPO: &str = env!("CARGO_PKG_REPOSITORY");
13const ORIGIN_NAME: &str = env!("CARGO_PKG_NAME");
14const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
15
16fn compute_seed_hash(seed: &str) -> u64 {
17    let mut hasher = DefaultHasher::new();
18    seed.hash(&mut hasher);
19    hasher.finish()
20}
21
22fn expected_hash() -> u64 {
23    compute_seed_hash("lean-ctx")
24}
25
26pub(crate) fn verify_integrity() -> bool {
27    compute_seed_hash(INTEGRITY_SEED) == expected_hash()
28}
29
30pub(crate) fn is_official_origin() -> bool {
31    ORIGIN_REPO.contains("yvgude/lean-ctx") && ORIGIN_NAME == "lean-ctx-engine"
32}
33
34/// Which pipeline built this binary, stamped by `build.rs` at compile time
35/// (never a runtime git call). `official` is the upstream release workflow
36/// only; `dogfood` the promoted Instance state, `dev` any other checkout,
37/// `source` a packaged crate or a tree without git.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct BuildInfo {
40    pub kind: &'static str,
41    /// Full 40-hex commit; empty when the build had none.
42    pub commit: &'static str,
43    /// Tracked files differed from `commit` when the build script last ran.
44    pub dirty: bool,
45}
46
47/// Commit digits shown in labels (`lean-ctx 3.12.2 (dogfood f78aff8dc5)`).
48const SHORT_COMMIT: usize = 10;
49
50impl BuildInfo {
51    pub fn short_commit(&self) -> &'static str {
52        self.commit.get(..SHORT_COMMIT).unwrap_or(self.commit)
53    }
54
55    pub fn is_official(&self) -> bool {
56        self.kind == "official"
57    }
58
59    /// `official`, `dogfood f78aff8dc5`, `dev 1a2b3c4d5e, dirty`, `source`.
60    pub fn label(&self) -> String {
61        if self.is_official() {
62            return "official".to_owned();
63        }
64        let mut label = self.kind.to_owned();
65        if !self.commit.is_empty() {
66            label.push(' ');
67            label.push_str(self.short_commit());
68        }
69        if self.dirty {
70            label.push_str(", dirty");
71        }
72        label
73    }
74
75    /// The additive `build` object of `--version --json` and the
76    /// capabilities documents.
77    pub fn to_json(&self) -> serde_json::Value {
78        serde_json::json!({
79            "kind": self.kind,
80            "commit": (!self.commit.is_empty()).then_some(self.commit),
81            "dirty": self.dirty,
82            "official": self.is_official(),
83        })
84    }
85}
86
87/// The Engine's own stamp. Outside a release build it carries no commit and
88/// no dirty flag (its build script never watches `HEAD`, so a commit leaves
89/// the Engine fresh); the binary's stamp supplies them at start.
90const ENGINE_BUILD: BuildInfo = BuildInfo {
91    kind: env!("LEANCTX_BUILD_KIND"),
92    commit: env!("LEANCTX_BUILD_COMMIT"),
93    dirty: matches!(env!("LEANCTX_BUILD_DIRTY").as_bytes(), b"1"),
94};
95
96/// The binary's commit, dirty flag and dogfood promotion, stamped over every
97/// crate's sources.
98static BINARY_STAMP: std::sync::OnceLock<(&'static str, bool, bool)> = std::sync::OnceLock::new();
99
100/// Called once by the `lean-ctx` binary at start with its own compile-time
101/// stamp (`crates/lean-ctx/build.rs`): the binary links every crate, so its
102/// commit and dirty flag describe the whole build, and `dogfood` promotes a
103/// `dev` Engine kind when `HEAD` was the promoted Instance state. An empty
104/// `commit` (a packaged crate, no git) keeps the Engine's stamp. An
105/// `official` build keeps its release commit.
106pub fn set_binary_stamp(commit: &'static str, dirty: bool, dogfood: bool) {
107    if !commit.is_empty() {
108        let _ = BINARY_STAMP.set((commit, dirty, dogfood));
109    }
110}
111
112/// The build stamped into this binary. A dev binary without a stamp (other
113/// binaries, tests) reports its kind with no commit.
114pub fn build() -> BuildInfo {
115    combine(ENGINE_BUILD, BINARY_STAMP.get().copied())
116}
117
118fn combine(engine: BuildInfo, stamp: Option<(&'static str, bool, bool)>) -> BuildInfo {
119    match stamp {
120        Some((commit, dirty, dogfood)) if !engine.is_official() => BuildInfo {
121            kind: if dogfood && engine.kind == "dev" {
122                "dogfood"
123            } else {
124                engine.kind
125            },
126            commit,
127            dirty,
128        },
129        _ => engine,
130    }
131}
132
133pub struct IntegrityReport {
134    pub seed_ok: bool,
135    pub origin_ok: bool,
136    pub repo: &'static str,
137    pub pkg_name: &'static str,
138    pub version: &'static str,
139    pub build: BuildInfo,
140}
141
142pub fn check() -> IntegrityReport {
143    IntegrityReport {
144        seed_ok: verify_integrity(),
145        origin_ok: is_official_origin(),
146        repo: ORIGIN_REPO,
147        pkg_name: ORIGIN_NAME,
148        version: PKG_VERSION,
149        build: build(),
150    }
151}
152
153/// `lean-ctx --version --json`.
154pub fn version_json() -> serde_json::Value {
155    let report = check();
156    serde_json::json!({
157        "name": "lean-ctx",
158        "version": report.version,
159        "repository": report.repo,
160        "unmodified": report.seed_ok && report.origin_ok,
161        "build": report.build.to_json(),
162    })
163}
164
165pub fn origin_line() -> String {
166    let report = check();
167    if report.seed_ok && report.origin_ok && report.build.is_official() {
168        format!("lean-ctx {} (official, {})", report.version, report.repo)
169    } else if report.seed_ok && report.origin_ok {
170        format!("lean-ctx {} ({})", report.version, report.build.label())
171    } else {
172        format!(
173            "WARNING: Modified redistribution detected. \
174             Official builds: https://github.com/yvgude/lean-ctx \
175             (pkg={}, repo={})",
176            report.pkg_name, report.repo
177        )
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn integrity_passes_in_official_build() {
187        assert!(verify_integrity());
188    }
189
190    #[test]
191    fn seed_hash_is_deterministic() {
192        let h1 = compute_seed_hash("lean-ctx");
193        let h2 = compute_seed_hash("lean-ctx");
194        assert_eq!(h1, h2);
195    }
196
197    #[test]
198    fn tampered_seed_fails() {
199        let tampered = compute_seed_hash("better-ctx");
200        assert_ne!(tampered, expected_hash());
201    }
202
203    #[test]
204    fn origin_is_official() {
205        assert!(is_official_origin());
206    }
207
208    #[test]
209    fn origin_line_contains_version() {
210        let line = origin_line();
211        assert!(line.contains(env!("CARGO_PKG_VERSION")));
212    }
213
214    #[test]
215    fn build_kind_labels_name_only_release_builds_official() {
216        let sha = "f78aff8dc5a1b2c3d4e5f60718293a4b5c6d7e8f";
217        let b = |kind, commit, dirty| BuildInfo {
218            kind,
219            commit,
220            dirty,
221        };
222        assert_eq!(b("official", sha, false).label(), "official");
223        assert_eq!(b("dogfood", sha, false).label(), "dogfood f78aff8dc5");
224        assert_eq!(b("dev", sha, true).label(), "dev f78aff8dc5, dirty");
225        assert_eq!(b("source", "", false).label(), "source");
226        assert_eq!(b("dev", sha, false).to_json()["official"], false);
227        assert_eq!(
228            b("source", "", false).to_json()["commit"],
229            serde_json::Value::Null
230        );
231
232        // The stamped build: "official" in the line exactly when build.rs saw
233        // the release workflow (release.yml runs this suite too).
234        let this = build();
235        assert!(
236            matches!(this.kind, "official" | "dev" | "dogfood" | "source"),
237            "{this:?}"
238        );
239        assert!(
240            this.commit.is_empty() || this.commit.len() == 40,
241            "{this:?}"
242        );
243        assert_eq!(
244            origin_line().contains("(official,"),
245            this.is_official(),
246            "{}",
247            origin_line()
248        );
249        assert_eq!(version_json()["build"]["kind"], this.kind);
250    }
251
252    #[test]
253    fn binary_stamp_supplies_commit_and_dogfood_but_never_overrides_official() {
254        let sha = "f78aff8dc5a1b2c3d4e5f60718293a4b5c6d7e8f";
255        let rel = "0123456789abcdef0123456789abcdef01234567";
256        let engine = |kind, commit| BuildInfo {
257            kind,
258            commit,
259            dirty: false,
260        };
261        // A dev Engine carries no commit; the binary's stamp fills it in.
262        let dev = combine(engine("dev", ""), Some((sha, true, false)));
263        assert_eq!(dev.label(), "dev f78aff8dc5, dirty");
264        assert_eq!(
265            combine(engine("dev", ""), Some((sha, false, true))).label(),
266            "dogfood f78aff8dc5"
267        );
268        // Only a `dev` kind is promoted: `source` or a requested kind stays.
269        assert_eq!(
270            combine(engine("source", ""), Some((sha, false, true))).kind,
271            "source"
272        );
273        // No stamp (other binaries, tests): kind only, no commit.
274        assert_eq!(combine(engine("dev", ""), None).label(), "dev");
275        let official = combine(engine("official", rel), Some((sha, true, true)));
276        assert_eq!((official.kind, official.commit), ("official", rel));
277    }
278}