trusty-common 0.70.6

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Runtime detection of a `cargo test` harness process, so shared code can
//! refuse to mutate the operator's production state from a test run (#4255).
//!
//! Why: trusty-search already had a compile-time guard for this
//! (`persistence::default_data_dir`'s `#[cfg(test)]` arm, issue #4094), but
//! `cfg(test)` is set per *compilation unit*, not per *process*. A crate's
//! `tests/` integration tests and its `[[bin]]` unit tests link the library
//! built WITHOUT `cfg(test)`, so the guard silently did not apply to them —
//! its own doc comment said so. Worse, the pollution that reached the live
//! `indexes.toml` most recently did not come from trusty-search's tests at
//! all: trusty-code's and trusty-mpm's tests call
//! [`crate::search_index::ensure_project_indexed`], which POSTs to whatever
//! real trusty-search daemon is discoverable. That write happens in a
//! DIFFERENT process, so no compile-time guard anywhere in trusty-search can
//! ever prevent it. A runtime check is the only mechanism that covers both.
//!
//! What: [`running_under_test_harness`] answers "is this process a cargo test
//! binary?" from the running executable's own path, with two env-var
//! overrides. Cargo compiles every test target to a file named
//! `<name>-<metadata-hash>`: under `target/<profile>/deps/` up to rustc 1.99,
//! under `target/<profile>/build/<crate>/<hash>/out/` from 1.100 (#11138). A
//! `cargo run` binary (`target/<profile>/<name>`) and an installed one
//! (`~/.cargo/bin/<name>`) never carry the hash, so the check is true for
//! every test target — lib unit tests, bin unit tests, integration tests,
//! benches — and false for every way a user actually runs the software. When
//! the path cannot be read, or carries the hash in an unknown layout, the
//! answer is "test": a wrong `true` refuses a write, a wrong `false` reaches a
//! live daemon.
//!
//! Scope boundary: this reads THIS process's path. A test that spawns the
//! real binary (`env!("CARGO_BIN_EXE_…")` resolves to `target/<profile>/<name>`,
//! with no hash) produces a child that is not detected. Such a test must
//! set [`FORCE_ENV`] or `TRUSTY_DATA_DIR` on the child explicitly.
//!
//! It also owns [`test_repo_root`], the runtime answer to "which checkout is
//! this test reading?" (#9298).
//!
//! Test: `detect_*` and `is_cargo_test_binary_*` in this module's `tests`;
//! `resolve_repo_root_table` in `test_harness_repo_root_tests.rs`.
//!
//! [`FORCE_ENV`]: crate::test_harness::FORCE_ENV
//! [`test_repo_root`]: crate::test_harness::test_repo_root

use std::path::{Path, PathBuf};

/// Forces [`running_under_test_harness`] to report `true`.
///
/// Set this on a child process a test spawns, so the child inherits the
/// parent's test-isolation even though its own path (`target/<profile>/<name>`)
/// carries no cargo metadata hash.
pub const FORCE_ENV: &str = "TRUSTY_TEST_HARNESS";

/// Opt-in escape hatch: forces [`running_under_test_harness`] to report
/// `false`, letting a test deliberately exercise real production state.
///
/// Outranks everything else, including [`FORCE_ENV`] and `cfg!(test)`. This
/// exists so "a test needs the real registry" stays an explicit, greppable
/// decision rather than a hole every accident falls through.
pub const ALLOW_PRODUCTION_ENV: &str = "TRUSTY_ALLOW_PRODUCTION_STATE";

/// Is this process a `cargo test` binary?
///
/// Why: production-state mutations (registering an index in the operator's
/// `indexes.toml`, POSTing to the live daemon) must never happen from a test
/// run. Callers gate those mutations on this (#4255).
/// What: [`ALLOW_PRODUCTION_ENV`] wins first (→ `false`), then [`FORCE_ENV`]
/// (→ `true`), then this crate's own `cfg!(test)`, then the executable-path
/// check described in the module doc. An unreadable path is `true` (#11138).
/// Test: `running_under_test_harness_is_true_in_this_test_binary` — this
/// module's tests run in exactly the harness the function must detect.
pub fn running_under_test_harness() -> bool {
    let exe = std::env::current_exe();
    let allow_production = std::env::var(ALLOW_PRODUCTION_ENV).ok();
    if let Err(e) = &exe
        && !is_truthy(allow_production.as_deref())
    {
        // #11138: an unreadable exe path now fails closed (treated as a test),
        // so say once why production-state writes are being refused.
        static WARNED: std::sync::Once = std::sync::Once::new();
        WARNED.call_once(|| {
            tracing::warn!(
                "cannot read this process's executable path ({e}); treating it as a test \
                 process and refusing production-state writes (#11138). Set \
                 {ALLOW_PRODUCTION_ENV}=1 to override."
            );
        });
    }
    detect(
        allow_production.as_deref(),
        std::env::var(FORCE_ENV).ok().as_deref(),
        cfg!(test),
        exe.ok().as_deref(),
    )
}

/// Pure decision table behind [`running_under_test_harness`], with every
/// input injected so the precedence is testable without touching process
/// state (env vars are process-global and race concurrent tests).
///
/// Test: the `detect_*` tests in this module cover each precedence rung.
fn detect(
    allow_production: Option<&str>,
    force: Option<&str>,
    compiled_as_test: bool,
    current_exe: Option<&Path>,
) -> bool {
    if is_truthy(allow_production) {
        return false;
    }
    if is_truthy(force) || compiled_as_test {
        return true;
    }
    // #11138: no readable exe path cannot be decided — fail closed.
    current_exe.is_none_or(is_cargo_test_binary)
}

/// Shared truthiness parse for both override vars: `1`/`true`/`yes`/`on`,
/// case-insensitive. Anything else (including unset) is false.
fn is_truthy(value: Option<&str>) -> bool {
    value.is_some_and(|v| {
        matches!(
            v.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        )
    })
}

/// Does `exe` look like a cargo-compiled test binary?
///
/// Why: it must be true for every test target and false for every real
/// invocation. Cargo sets no runtime env var that tells `cargo test` from
/// `cargo run` (both get `CARGO`, `CARGO_MANIFEST_DIR`, `CARGO_PKG_*`), so the
/// path is the signal. #11138: rustc 1.100's cargo moved test binaries from
/// `target/<profile>/deps/` to `target/<profile>/build/<crate>/<hash>/out/`,
/// and the `deps`-only check returned false for every test.
/// What: after dropping a trailing ` (deleted)` (Linux `/proc/self/exe` on a
/// replaced binary), the file stem must end in `-<hex>` (cargo's metadata
/// hash, at least 8 hex digits). Then any one of:
/// 1. the parent directory is `deps` (cargo up to 1.99);
/// 2. the path ends `build/<crate>/<hash>/out/<name>-<hash>`, the same hash
///    twice (cargo 1.100);
/// 3. fail closed for a layout not listed yet: the hash is exactly 16 hex
///    digits, the width cargo writes.
///
/// Production rule: a binary a user runs never carries the hash. `cargo run`
/// and `cargo build` uplift to `target/<profile>/<name>`, and `cargo install`
/// writes `~/.cargo/bin/<name>`, both with the hash stripped.
///
/// Test: `is_cargo_test_binary_*`, `detect_fails_closed_for_an_unknown_layout_with_a_cargo_hash`,
/// `detect_is_false_for_production_shapes_beside_the_1100_layout`.
fn is_cargo_test_binary(exe: &Path) -> bool {
    /// A path's final component as UTF-8.
    fn dir_name(p: Option<&Path>) -> Option<&str> {
        p.and_then(Path::file_name).and_then(|n| n.to_str())
    }
    let Some(file_name) = exe.file_name().and_then(|s| s.to_str()) else {
        return false;
    };
    // #11138: Linux `/proc/self/exe` appends ` (deleted)` once a concurrent
    // build has replaced the binary; read the name cargo wrote.
    let file_name = file_name.strip_suffix(" (deleted)").unwrap_or(file_name);
    let Some(stem) = Path::new(file_name).file_stem().and_then(|s| s.to_str()) else {
        return false;
    };
    let Some(hash) = stem.rsplit_once('-').and_then(|(name, hash)| {
        (!name.is_empty() && hash.len() >= 8 && hash.chars().all(|c| c.is_ascii_hexdigit()))
            .then_some(hash)
    }) else {
        return false;
    };
    let parent = exe.parent();
    if dir_name(parent) == Some("deps") {
        return true;
    }
    // #11138: `build/<crate>/<hash>/out/<name>-<hash>`.
    let hash_dir = parent.and_then(Path::parent);
    let build_dir = hash_dir.and_then(Path::parent).and_then(Path::parent);
    if dir_name(parent) == Some("out")
        && dir_name(hash_dir) == Some(hash)
        && dir_name(build_dir) == Some("build")
    {
        return true;
    }
    // #11138: an unknown layout with cargo's 16-hex hash fails closed.
    hash.len() == 16
}

/// Names the repository root a test reads repo content from, outranking every
/// other source in [`test_repo_root`] (#9298).
pub const REPO_ROOT_ENV: &str = "TRUSTY_TEST_REPO_ROOT";

/// The Cargo workspace root this test process reads repository content from.
///
/// Why (#9298): `env!("CARGO_MANIFEST_DIR")` bakes the BUILD checkout's path
/// into the binary. With one `CARGO_TARGET_DIR` shared across worktrees, a test
/// binary built in one worktree and run for another read the first worktree's
/// files — or a reclaimed, deleted tree. The runtime value names the checkout
/// cargo is running the test for.
/// What: [`resolve_repo_root`] over [`REPO_ROOT_ENV`], the runtime
/// `CARGO_MANIFEST_DIR`, and the current directory. There is no compile-time
/// fallback.
/// Test: `resolve_repo_root_table`; end to end in trusty-mpm's
/// `repo_root_follows_the_runtime_checkout_9298`.
pub fn test_repo_root() -> std::io::Result<PathBuf> {
    let explicit = std::env::var_os(REPO_ROOT_ENV).map(PathBuf::from);
    let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from);
    let cwd = std::env::current_dir().ok();
    resolve_repo_root(explicit.as_deref(), manifest_dir.as_deref(), cwd.as_deref())
}

/// Pure resolution behind [`test_repo_root`]; reads the filesystem, never
/// process state.
///
/// What: the first source that answers wins, and the result is canonical.
/// 1. `explicit` must itself hold a `Cargo.toml` with a `[workspace]` line. It
///    is not walked up; an invalid value is `InvalidInput`.
/// 2. `manifest_dir`, walked up to the first workspace root.
/// 3. `cwd`, walked up the same way.
///
/// With no answer the error is `NotFound` and names [`REPO_ROOT_ENV`].
///
/// Test: `resolve_repo_root_table`.
pub fn resolve_repo_root(
    explicit: Option<&Path>,
    manifest_dir: Option<&Path>,
    cwd: Option<&Path>,
) -> std::io::Result<PathBuf> {
    use std::io::{Error, ErrorKind};
    if let Some(dir) = explicit {
        let root = (!dir.as_os_str().is_empty())
            .then(|| dir.canonicalize().ok())
            .flatten()
            .filter(|d| is_workspace_root(d));
        return root.ok_or_else(|| {
            Error::new(
                ErrorKind::InvalidInput,
                format!(
                    "{REPO_ROOT_ENV}={} does not hold a Cargo.toml with a [workspace] table",
                    dir.display()
                ),
            )
        });
    }
    for start in [manifest_dir, cwd].into_iter().flatten() {
        // A start that does not exist cannot name a checkout; try the next.
        let Ok(start) = start.canonicalize() else {
            continue;
        };
        if let Some(root) = start.ancestors().find(|d| is_workspace_root(d)) {
            return Ok(root.to_path_buf());
        }
    }
    Err(Error::new(
        ErrorKind::NotFound,
        format!(
            "no Cargo workspace root at or above CARGO_MANIFEST_DIR ({}) or the current \
             directory ({}); set {REPO_ROOT_ENV} to the checkout root",
            display_or_unset(manifest_dir),
            display_or_unset(cwd)
        ),
    ))
}

/// Does `dir/Cargo.toml` carry a `[workspace]` table header?
fn is_workspace_root(dir: &Path) -> bool {
    std::fs::read_to_string(dir.join("Cargo.toml"))
        .is_ok_and(|toml| toml.lines().any(|line| line.trim() == "[workspace]"))
}

/// A path for an error message, or `unset`.
fn display_or_unset(path: Option<&Path>) -> String {
    path.map_or_else(|| "unset".to_string(), |p| p.display().to_string())
}

#[cfg(test)]
#[path = "test_harness_repo_root_tests.rs"]
mod repo_root_tests;

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

    fn test_exe() -> PathBuf {
        PathBuf::from("/repo/target/debug/deps/integration_tests-f54141ba75b48011")
    }

    /// The whole point of the module: the real running test process must be
    /// detected, through the real public entry point, with no injection.
    ///
    /// Takes `ENV_LOCK` because this is the only test here that reads the
    /// process-global override vars, and a sibling test sets
    /// [`ALLOW_PRODUCTION_ENV`] for its own duration
    /// (`search_index_tests`' wire-body test). Without the lock the two race
    /// and this one fails for a reason that has nothing to do with detection.
    #[test]
    fn running_under_test_harness_is_true_in_this_test_binary() {
        let _guard = crate::data_dir::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        assert!(
            running_under_test_harness(),
            "a cargo test process must be detected as a test harness"
        );
    }

    #[test]
    fn detect_allow_production_outranks_everything() {
        assert!(
            !detect(Some("1"), Some("1"), true, Some(&test_exe())),
            "TRUSTY_ALLOW_PRODUCTION_STATE must win over force, cfg(test) and the path check"
        );
    }

    #[test]
    fn detect_force_env_wins_over_path_check() {
        let installed = PathBuf::from("/Users/me/.cargo/bin/trusty-search");
        assert!(detect(None, Some("true"), false, Some(&installed)));
    }

    #[test]
    fn detect_falls_back_to_exe_path() {
        assert!(detect(None, None, false, Some(&test_exe())));
    }

    #[test]
    fn detect_is_false_for_a_real_invocation() {
        for exe in [
            "/Users/me/.cargo/bin/trusty-search",
            "/opt/homebrew/bin/trusty-search",
            "/repo/target/debug/trusty-search",
            "/repo/target/release/trusty-search",
        ] {
            assert!(
                !detect(None, None, false, Some(Path::new(exe))),
                "{exe} must not be mistaken for a test binary"
            );
        }
    }

    /// #11138: an executable path that cannot be read is undecidable, and an
    /// undecidable process must not reach a live daemon — fail closed.
    #[test]
    fn detect_fails_closed_when_exe_is_unresolvable() {
        assert!(detect(None, None, false, None));
        // The explicit opt-in still wins, so production keeps an escape hatch.
        assert!(!detect(Some("1"), None, false, None));
    }

    /// #11138: rustc 1.100's cargo writes test binaries to
    /// `target/<profile>/build/<crate>/<hash>/out/<name>-<hash>`. These are
    /// the paths main CI run 43281734883 printed.
    #[test]
    fn is_cargo_test_binary_accepts_the_rust_1100_build_out_layout() {
        for exe in [
            "/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/trusty_mpm-98af4e218cd2e034",
            "/repo/target/debug/build/trusty-mpm/62c73b50a0eeb776/out/tm-62c73b50a0eeb776",
            "/repo/target/debug/build/trusty-mpm/3322f910a0c480bf/out/integration-3322f910a0c480bf",
            "/repo/target/release/build/trusty-search/0802fde7a9957161/out/registry_isolation-0802fde7a9957161",
        ] {
            assert!(
                detect(None, None, false, Some(Path::new(exe))),
                "{exe} is a cargo test binary"
            );
        }
    }

    /// #11138: a binary carrying cargo's 16-hex metadata hash in a directory
    /// layout this module does not know yet is still a test binary — the next
    /// cargo layout change must not reopen the live-daemon hole.
    /// #11138: on Linux `current_exe()` reads `/proc/self/exe`, which ends in
    /// ` (deleted)` once a concurrent build has replaced the test binary. That
    /// suffix must not turn a test process into production.
    #[test]
    fn is_cargo_test_binary_ignores_a_deleted_exe_suffix() {
        for exe in [
            "/repo/target/debug/deps/integration_tests-f54141ba75b48011 (deleted)",
            "/repo/target/debug/build/trusty-mpm/62c73b50a0eeb776/out/tm-62c73b50a0eeb776 (deleted)",
        ] {
            assert!(
                detect(None, None, false, Some(Path::new(exe))),
                "{exe} is a replaced cargo test binary"
            );
        }
    }

    #[test]
    fn detect_fails_closed_for_an_unknown_layout_with_a_cargo_hash() {
        for exe in [
            "/repo/target/debug/artifacts/trusty_mpm-98af4e218cd2e034",
            "/build-dir/x86_64/debug/trusty-mpm/out/tm-62c73b50a0eeb776",
        ] {
            assert!(
                detect(None, None, false, Some(Path::new(exe))),
                "{exe} carries cargo's metadata hash and must fail closed"
            );
        }
    }

    /// #11138: the production rule — cargo uplifts (`target/<profile>/<name>`)
    /// and `cargo install` writes (`~/.cargo/bin/<name>`) WITHOUT the hash, so
    /// an unhashed name is never a test, even inside the new `build/` tree.
    #[test]
    fn detect_is_false_for_production_shapes_beside_the_1100_layout() {
        for exe in [
            "/repo/target/debug/tm",
            "/repo/target/debug/trusty-search",
            "/Users/me/.cargo/bin/tm",
            "/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/build-script-build",
            "/repo/target/debug/build/trusty-mpm/98af4e218cd2e034/out/tm",
            // Rule 3's width: a hex-looking suffix that is not 16 digits.
            "/usr/local/bin/tool-deadbeef",
            "/opt/x/bin/agent-0123456789abc",
        ] {
            assert!(
                !detect(None, None, false, Some(Path::new(exe))),
                "{exe} must not be mistaken for a test binary"
            );
        }
    }

    #[test]
    fn is_cargo_test_binary_accepts_every_target_kind() {
        for exe in [
            // lib + bin unit tests, integration tests, benches
            "/repo/target/debug/deps/trusty_search-88c47ed536c1e550",
            "/repo/target/debug/deps/integration_tests-f54141ba75b48011",
            "/repo/target/release/deps/registry_isolation-0802fde7a9957161",
        ] {
            assert!(
                is_cargo_test_binary(Path::new(exe)),
                "{exe} is a cargo test binary"
            );
        }
    }

    #[test]
    fn is_cargo_test_binary_requires_the_metadata_hash() {
        // A `deps/` directory alone is not enough — a plain name with no
        // `-<hex>` suffix is not something cargo's test harness produces.
        assert!(!is_cargo_test_binary(Path::new("/repo/deps/trusty-search")));
        assert!(!is_cargo_test_binary(Path::new(
            "/repo/target/debug/deps/trusty-search-notahash"
        )));
        // Too short to be cargo's 16-hex metadata hash.
        assert!(!is_cargo_test_binary(Path::new(
            "/repo/target/debug/deps/thing-abc"
        )));
    }

    #[test]
    fn is_truthy_accepts_the_documented_spellings_only() {
        for yes in ["1", "true", "TRUE", "Yes", " on "] {
            assert!(is_truthy(Some(yes)), "{yes:?} must be truthy");
        }
        for no in ["0", "false", "", "no", "off", "maybe"] {
            assert!(!is_truthy(Some(no)), "{no:?} must not be truthy");
        }
        assert!(!is_truthy(None));
    }
}