egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Self-update from GitHub releases, in the same shape as tokenix: a check at
//! most once a day in a detached process, then a SHA-256-verified download that
//! replaces the running binary. The result is announced on the next run.

use crate::paths::Paths;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const REPO: &str = "juninmd/egrix";
const CHECK_INTERVAL_SECS: u64 = 86_400;
const MAX_JSON_BYTES: u64 = 1024 * 1024;
const MAX_CHECKSUM_BYTES: u64 = 64 * 1024;
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;

#[derive(Debug, Serialize, Deserialize)]
pub struct Cache {
    #[serde(default)]
    last_checked: u64,
    #[serde(default)]
    latest: String,
    #[serde(default = "enabled")]
    auto_install: bool,
    #[serde(default)]
    just_updated: bool,
}

fn enabled() -> bool {
    true
}

impl Default for Cache {
    fn default() -> Self {
        Self { last_checked: 0, latest: String::new(), auto_install: true, just_updated: false }
    }
}

#[derive(Deserialize)]
struct Release {
    tag_name: String,
    html_url: String,
    #[serde(default)]
    assets: Vec<Asset>,
}

#[derive(Deserialize)]
struct Asset {
    name: String,
    browser_download_url: String,
    size: u64,
}

/// `egrix update` flags.
#[derive(Default)]
pub struct Options {
    pub check: bool,
    pub enable_auto: bool,
    pub disable_auto: bool,
}

pub fn current_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// `major.minor.patch`, ignoring a leading `v` and any pre-release suffix.
fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
    let mut parts = s.trim().trim_start_matches('v').split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts.next()?.split('-').next()?.parse().ok()?;
    Some((major, minor, patch))
}

fn env_value(name: &str) -> Option<String> {
    std::env::var(name).ok().map(|v| v.trim().to_ascii_lowercase())
}

/// False when updates are switched off by environment, or on a CI runner.
fn check_enabled() -> bool {
    if matches!(env_value("EGRIX_NO_UPDATE").as_deref(), Some("1" | "true")) {
        return false;
    }
    if matches!(env_value("CI").as_deref(), Some("1" | "true")) {
        return false;
    }
    !matches!(env_value("EGRIX_AUTO_UPDATE").as_deref(), Some("0" | "false" | "off"))
}

/// Whether a newer release is installed without asking.
fn install_enabled(cache: &Cache) -> bool {
    if !check_enabled() {
        return false;
    }
    match env_value("EGRIX_AUTO_UPDATE").as_deref() {
        Some("0" | "false" | "off" | "no" | "notify") => false,
        Some("1" | "true" | "auto" | "install") => true,
        _ => cache.auto_install,
    }
}

fn cache_path(paths: &Paths) -> PathBuf {
    paths.config.join("update.json")
}

fn lock_path(paths: &Paths) -> PathBuf {
    paths.config.join("update.lock")
}

fn load_cache(paths: &Paths) -> Cache {
    std::fs::read_to_string(cache_path(paths)).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default()
}

fn save_cache(paths: &Paths, cache: &Cache) -> Result<()> {
    std::fs::create_dir_all(&paths.config)?;
    std::fs::write(cache_path(paths), serde_json::to_string_pretty(cache)?)?;
    Ok(())
}

fn now() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}

/// Release binary for this platform, named as the release workflow publishes it.
fn asset_name() -> Result<&'static str> {
    match (std::env::consts::OS, std::env::consts::ARCH) {
        ("linux", "x86_64") => Ok("egrix-linux-x86_64"),
        ("linux", "aarch64") => Ok("egrix-linux-aarch64"),
        ("macos", "aarch64") => Ok("egrix-macos-aarch64"),
        ("windows", "x86_64") => Ok("egrix-windows-x86_64.exe"),
        (os, arch) => bail!("no prebuilt binary for {os}-{arch}; use `cargo install --locked egrix`"),
    }
}

fn agent(timeout: Duration, follow_redirects: bool) -> ureq::Agent {
    use ureq::tls::{RootCerts, TlsConfig};
    let mut config = ureq::Agent::config_builder()
        .user_agent(concat!("egrix/", env!("CARGO_PKG_VERSION")))
        .timeout_global(Some(timeout))
        // Status codes are checked by the callers, with their own messages.
        .http_status_as_error(false)
        .tls_config(TlsConfig::builder().root_certs(RootCerts::PlatformVerifier).build());
    if !follow_redirects {
        config = config.max_redirects(0).max_redirects_will_error(false);
    }
    config.build().into()
}

fn read_capped(reader: impl Read, cap: u64) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    reader.take(cap + 1).read_to_end(&mut buf)?;
    if buf.len() as u64 > cap {
        bail!("response exceeds the {cap}-byte limit");
    }
    Ok(buf)
}

fn fetch_latest() -> Result<Release> {
    let url = format!("https://api.github.com/repos/{REPO}/releases/latest");
    let client = agent(Duration::from_secs(15), false);
    let mut request = client.get(&url).header("Accept", "application/vnd.github+json");
    let token = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN")).ok();
    if let Some(token) = token.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
        request = request.header("Authorization", format!("Bearer {token}"));
    }
    let mut response = request.call().context("cannot reach GitHub releases")?;
    if !response.status().is_success() {
        bail!("GitHub API error: HTTP {}", response.status());
    }
    let body = read_capped(response.body_mut().as_reader(), MAX_JSON_BYTES)?;
    serde_json::from_slice(&body).context("cannot parse the release JSON")
}

/// Only the release's own assets on github.com are fetched; anything else is refused.
fn verified_url(release: &Release, asset: &Asset) -> Result<String> {
    let prefix = format!("https://github.com/{REPO}/releases/download/{}/", release.tag_name);
    let rest = asset.browser_download_url.strip_prefix(&prefix);
    match rest {
        Some(name) if name == asset.name && !name.contains(['?', '#', '@']) => Ok(asset.browser_download_url.clone()),
        _ => bail!("unexpected download URL for {}", asset.name),
    }
}

fn expected_hash(sums: &str, file: &str) -> Option<String> {
    sums.lines().find_map(|line| {
        let mut parts = line.split_whitespace();
        let hash = parts.next()?;
        let name = parts.next()?.trim_start_matches('*');
        (name == file).then(|| hash.to_ascii_lowercase())
    })
}

/// Downloads the release binary next to `target`, checks its SHA-256 against
/// `sha256sums.txt`, and swaps it in. Nothing is replaced on a mismatch.
fn install(release: &Release, target: &Path) -> Result<()> {
    let name = asset_name()?;
    let binary =
        release.assets.iter().find(|a| a.name == name).ok_or_else(|| anyhow!("asset {name} is missing from {}", release.tag_name))?;
    let sums_asset = release
        .assets
        .iter()
        .find(|a| a.name == "sha256sums.txt")
        .ok_or_else(|| anyhow!("sha256sums.txt is missing from {}", release.tag_name))?;

    let client = agent(Duration::from_secs(300), true);
    let mut sums = client.get(&verified_url(release, sums_asset)?).call()?;
    if !sums.status().is_success() {
        bail!("cannot download sha256sums.txt: HTTP {}", sums.status());
    }
    let sums = String::from_utf8(read_capped(sums.body_mut().as_reader(), MAX_CHECKSUM_BYTES)?).context("sha256sums.txt is not UTF-8")?;
    let expected = expected_hash(&sums, name).ok_or_else(|| anyhow!("{name} has no checksum entry"))?;

    let dir = target.parent().ok_or_else(|| anyhow!("target has no parent directory"))?;
    let temp = dir.join(format!("egrix_download_{}.tmp", std::process::id()));
    let result = download_to(&client, &verified_url(release, binary)?, binary.size, &temp)
        .and_then(
            |actual| {
                if actual == expected {
                    Ok(())
                } else {
                    bail!("SHA-256 mismatch for {name}: expected {expected}, got {actual}")
                }
            },
        )
        .and_then(|()| replace(&temp, target));
    if result.is_err() {
        let _ = std::fs::remove_file(&temp);
    }
    result
}

fn download_to(client: &ureq::Agent, url: &str, declared_size: u64, temp: &Path) -> Result<String> {
    let mut response = client.get(url).call().context("download failed")?;
    if !response.status().is_success() {
        bail!("download failed: HTTP {}", response.status());
    }
    let cap = declared_size.min(MAX_BINARY_BYTES);
    let mut file = std::fs::File::create(temp).context("cannot create the temporary file")?;
    let mut hasher = Sha256::new();
    let mut reader = response.body_mut().as_reader();
    let mut buffer = vec![0u8; 64 * 1024];
    let mut total = 0u64;
    loop {
        let n = reader.read(&mut buffer)?;
        if n == 0 {
            break;
        }
        total += n as u64;
        if total > cap {
            bail!("download exceeds the {cap}-byte limit");
        }
        hasher.update(&buffer[..n]);
        file.write_all(&buffer[..n])?;
    }
    file.flush()?;
    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

fn replace(temp: &Path, target: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(temp, std::fs::Permissions::from_mode(0o755))?;
        std::fs::rename(temp, target).with_context(|| format!("cannot replace {}", target.display()))?;
    }
    #[cfg(windows)]
    {
        // A running .exe cannot be overwritten, but it can be renamed away.
        let old = target.with_file_name(format!("egrix.exe.old.{}", std::process::id()));
        std::fs::rename(target, &old).with_context(|| format!("cannot move {} aside", target.display()))?;
        if let Err(e) = std::fs::rename(temp, target) {
            let _ = std::fs::rename(&old, target);
            return Err(e).context("cannot install the new binary");
        }
        let _ = std::fs::remove_file(&old);
    }
    Ok(())
}

/// Removes leftovers of earlier updates (a `.old` binary or a stray download)
/// once they are a day old, so a Windows update cannot leave clutter behind.
pub fn clean_stale_files(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        let stale_name = name.starts_with("egrix.exe.old.") || (name.starts_with("egrix_download_") && name.ends_with(".tmp"));
        let old_enough = entry
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.elapsed().ok())
            .is_some_and(|age| age >= Duration::from_secs(86_400));
        if stale_name && old_enough {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// Removes the lock file when the background check ends, however it ends.
struct LockGuard(PathBuf);

impl Drop for LockGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

/// Foreground hook, run on every start: prints what the last check found and
/// starts a new check in a detached process once the cached one is a day old.
pub fn on_startup(paths: &Paths) {
    if !check_enabled() {
        return;
    }
    let mut cache = load_cache(paths);
    if cache.just_updated {
        cache.just_updated = false;
        let _ = save_cache(paths, &cache);
        eprintln!("✓ egrix was automatically updated to {}.", current_version());
        return;
    }
    let stale = now().saturating_sub(cache.last_checked) > CHECK_INTERVAL_SECS;
    if stale {
        spawn_background_check(paths);
    }
    let newer = parse_version(&cache.latest) > parse_version(current_version());
    if newer {
        if install_enabled(&cache) {
            eprintln!("tip: a newer egrix is available ({} -> {}). Automatic updates are enabled.", current_version(), cache.latest);
        } else {
            eprintln!("tip: a newer egrix is available ({} -> {}). Run `egrix update` to upgrade.", current_version(), cache.latest);
        }
    }
}

fn spawn_background_check(paths: &Paths) {
    let lock = lock_path(paths);
    let _ = std::fs::create_dir_all(&paths.config);
    let acquire = || std::fs::OpenOptions::new().write(true).create_new(true).open(&lock);
    if acquire().is_err() {
        // A crashed check leaves its lock behind; a stale one is taken over.
        let stale = std::fs::metadata(&lock)
            .and_then(|m| m.modified())
            .and_then(|t| t.elapsed().map_err(std::io::Error::other))
            .is_ok_and(|age| age >= Duration::from_secs(600));
        if !stale {
            return;
        }
        let _ = std::fs::remove_file(&lock);
        if acquire().is_err() {
            return;
        }
    }
    let Ok(exe) = std::env::current_exe() else {
        let _ = std::fs::remove_file(&lock);
        return;
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.args(["update", "--check-background"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        // DETACHED_PROCESS | CREATE_NO_WINDOW: no console flashes up.
        cmd.creation_flags(0x0000_0008 | 0x0800_0000);
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    if cmd.spawn().is_err() {
        let _ = std::fs::remove_file(&lock);
    }
}

/// The detached check: fetch the latest release, record it, and install it when
/// automatic updates are on. Never prints; its result shows on the next start.
fn background(paths: &Paths) -> Result<()> {
    let _guard = LockGuard(lock_path(paths));
    if !check_enabled() {
        return Ok(());
    }
    let release = fetch_latest()?;
    let latest = parse_version(&release.tag_name).ok_or_else(|| anyhow!("bad tag {}", release.tag_name))?;
    let mut cache = load_cache(paths);
    cache.last_checked = now();
    cache.latest = release.tag_name.clone();
    // A debug build is someone's working copy: never overwrite it silently.
    if latest > parse_version(current_version()).unwrap_or_default() && install_enabled(&cache) && !cfg!(debug_assertions) {
        let target = std::env::current_exe()?;
        if install(&release, &target).is_ok() {
            cache.just_updated = true;
            clean_stale_files(target.parent().unwrap_or(Path::new(".")));
        }
    }
    save_cache(paths, &cache)
}

/// `egrix update`, and the hidden `--check-background` used by the detached check.
pub fn run(paths: &Paths, opts: Options, check_background: bool) -> Result<()> {
    if check_background {
        return background(paths);
    }
    if opts.enable_auto || opts.disable_auto {
        let mut cache = load_cache(paths);
        cache.auto_install = opts.enable_auto;
        save_cache(paths, &cache)?;
        println!("Automatic updates {}.", if opts.enable_auto { "enabled" } else { "disabled" });
        return Ok(());
    }

    let release = fetch_latest()?;
    let latest = parse_version(&release.tag_name).ok_or_else(|| anyhow!("bad tag {}", release.tag_name))?;
    let mut cache = load_cache(paths);
    cache.last_checked = now();
    cache.latest = release.tag_name.clone();
    save_cache(paths, &cache)?;

    if latest <= parse_version(current_version()).unwrap_or_default() {
        println!("egrix {} is up to date.", current_version());
        return Ok(());
    }
    if opts.check {
        println!("Update available: {} -> {} ({})", current_version(), release.tag_name, release.html_url);
        return Ok(());
    }
    let target = std::env::current_exe()?;
    install(&release, &target)?;
    clean_stale_files(target.parent().unwrap_or(Path::new(".")));
    println!("Updated egrix {} -> {}.", current_version(), release.tag_name);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn versions_compare_by_number_not_text() {
        assert!(parse_version("v0.10.0") > parse_version("0.9.9"));
        assert_eq!(parse_version("v1.2.3-rc1"), Some((1, 2, 3)));
        assert_eq!(parse_version("nonsense"), None);
    }

    #[test]
    fn checksum_lookup_matches_the_exact_asset() {
        let sums = "AAAA  egrix-linux-x86_64\nBBBB *egrix-windows-x86_64.exe\n";
        assert_eq!(expected_hash(sums, "egrix-windows-x86_64.exe").as_deref(), Some("bbbb"));
        assert_eq!(expected_hash(sums, "egrix-macos-aarch64"), None);
    }

    #[test]
    fn only_the_release_own_asset_urls_are_fetched() {
        let release = Release { tag_name: "v1.0.0".into(), html_url: String::new(), assets: vec![] };
        let good = Asset {
            name: "egrix-linux-x86_64".into(),
            browser_download_url: format!("https://github.com/{REPO}/releases/download/v1.0.0/egrix-linux-x86_64"),
            size: 1,
        };
        assert!(verified_url(&release, &good).is_ok());
        let evil = Asset { browser_download_url: "https://evil.example/egrix-linux-x86_64".into(), ..good };
        assert!(verified_url(&release, &evil).is_err());
    }
}