Debian Codegraph @

helix-loader/src/workspace_trust.rs

raw symbols SCIP
1 //! Workspace trust.
2 //!
3 //! Helix can load workspace-local configuration (`.helix/`) and launch language servers, both of
4 //! which can execute arbitrary code. By default these are gated behind explicit user trust granted
5 //! per-workspace.
6 //!
7 //! Trust is granted with `:workspace-trust` (or the popup) and revoked with `:workspace-untrust`.
8 //! A grant snapshots a hash of every file under `.helix/`. If those files change later the
9 //! workspace becomes [`TrustStatus::Stale`] and local config is no longer loaded until the user
10 //! re-runs `:workspace-trust`. Language servers continue to launch under stale trust because the
11 //! binaries are configured globally and were not part of the changed surface.
12 //!
13 //! ## Storage
14 //!
15 //! Each trust entry is a small file at `data_dir()/workspace_trust/<sha256(workspace_path)>`. The
16 //! filename is the SHA-256 of the workspace's absolute path; the contents are a small
17 //! `key = value` block:
18 //!
19 //! ```text
20 //! path = /home/user/proj1
21 //! hash = sha256:abc123...
22 //! excluded = false
23 //! ```
24 //!
25 //! `hash` is omitted for excluded entries. The "one file per workspace" shape is safe under
26 //! multiple concurrent helix instances writing trust for *different* workspaces (different
27 //! filenames). Two instances racing to trust the same workspace converge to identical content.
28 //!
29 //! ## Trusted globs (discouraged)
30 //!
31 //! `[editor.workspace-trust] trusted = [...]` is an escape hatch for users who keep many repos in a
32 //! predictable layout (`~/src/github.com/me/*`) and don't want to grant trust one workspace at a
33 //! time. A workspace whose path matches one of these globs is implicitly trusted for everything.
34 //!
35 //! This is deliberately weaker than an explicit `:workspace-trust` grant and is discouraged: it
36 //! bypasses the `.helix/` hash pin (changes to local config are never re-checked) and it trusts any
37 //! repository that happens to land under a matching directory, including ones cloned there later. An
38 //! explicit exclude still wins over a matching glob.
39
40 use std::{
41 collections::HashMap,
42 fmt::Write,
43 fs,
44 path::{Path, PathBuf},
45 sync::Arc,
46 };
47
48 use globset::{Glob, GlobSet, GlobSetBuilder};
49 use parking_lot::Mutex;
50 use sha2::{Digest, Sha256};
51
52 use crate::{data_dir, find_workspace, find_workspace_in};
53
54 /// Checks whether a specific capability is trusted
55 #[derive(Debug, Clone, Copy)]
56 pub enum TrustQuery {
57 /// Query language server permissions
58 Lsp,
59 /// Query debug adapter permissions
60 Dap,
61 /// Query whether `.helix/` config can be loaded
62 LocalConfig,
63 /// Query whether git integration can trust the .git/config
64 Git,
65 }
66
67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
68 pub enum TrustStatus {
69 /// Workspace is trusted for the queried capability.
70 Trusted,
71 /// No trust decision has been made (and no implicit trust applies).
72 Untrusted,
73 /// Workspace was previously trusted, but the `.helix/` tree has changed since the grant — the
74 /// user should re-trust before local config is re-loaded. LSP launches may still proceed under
75 /// stale trust because they use the (unchanged) globally-configured binaries.
76 Stale,
77 /// Workspace is on the exclude list. Never prompts again.
78 Excluded,
79 }
80
81 impl TrustStatus {
82 pub fn is_trusted(&self) -> bool {
83 matches!(self, Self::Trusted)
84 }
85
86 pub fn is_stale(&self) -> bool {
87 matches!(self, Self::Stale)
88 }
89
90 pub fn is_excluded(&self) -> bool {
91 matches!(self, Self::Excluded)
92 }
93 }
94
95 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
96 pub enum ImplicitTrustLevel {
97 /// Prompt for every workspace.
98 None,
99 /// Helix-launched server processes (LSP and DAP) start implicitly. Workspace-local config and
100 /// git `Trust::Full` still require explicit trust.
101 ///
102 /// Default: language servers are how most people use the editor and the binaries are global
103 /// (PATH-resolved, user-installed), so auto-launching them in a fresh workspace matches
104 /// expectations.
105 #[default]
106 Servers,
107 /// Everything is trusted unless the workspace is explicitly excluded.
108 Insecure,
109 }
110
111 #[derive(Debug, Clone)]
112 pub struct Config {
113 pub level: ImplicitTrustLevel,
114 /// Whether to surface the trust modal on `DocumentDidOpen` for untrusted workspaces.
115 pub prompt: bool,
116 /// Workspaces whose path matches one of these globs are implicitly trusted.
117 pub trusted_globs: GlobSet,
118 }
119
120 impl Default for Config {
121 fn default() -> Self {
122 Self {
123 level: ImplicitTrustLevel::default(),
124 prompt: true,
125 trusted_globs: GlobSet::empty(),
126 }
127 }
128 }
129
130 /// Compile workspace-trust glob patterns into a matcher. `~` and environment variables are expanded
131 /// in each pattern; invalid patterns are logged and skipped rather than failing the whole config
132 /// load. Returns an empty set (matches nothing) when `patterns` is empty or all entries are invalid.
133 pub fn build_trusted_globs(patterns: &[String]) -> GlobSet {
134 let mut builder = GlobSetBuilder::new();
135 for pattern in patterns {
136 let expanded = helix_stdx::path::expand(pattern);
137 match Glob::new(&expanded.to_string_lossy()) {
138 Ok(glob) => {
139 builder.add(glob);
140 }
141 Err(err) => log::error!("ignoring invalid workspace-trust glob {pattern:?}: {err}"),
142 }
143 }
144 builder.build().unwrap_or_else(|err| {
145 log::error!("failed to compile workspace-trust globs: {err}");
146 GlobSet::empty()
147 })
148 }
149
150 /// Runtime workspace-trust state. Cheap to clone (shared `Arc`).
151 #[derive(Clone)]
152 pub struct WorkspaceTrust {
153 inner: Arc<Mutex<HashMap<PathBuf, CacheEntry>>>,
154 config: Config,
155 }
156
157 #[derive(Clone, Copy)]
158 struct CacheEntry {
159 status: TrustStatus,
160 /// Whether `.helix/config.toml` or `.helix/languages.toml` exists in the workspace at the time
161 /// of the first uncached query. Snapshotted to keep [`WorkspaceTrust::workspace_restricted`]
162 /// off the syscall path on repeat calls (statusline indicator runs per render).
163 has_local_config: bool,
164 }
165
166 impl WorkspaceTrust {
167 pub fn new(config: Config) -> Self {
168 Self {
169 inner: Arc::new(Mutex::new(HashMap::new())),
170 config,
171 }
172 }
173
174 /// A trust state that grants every capability. Use for non-interactive contexts (CLI grammar
175 /// build, `hx --health`) where prompting isn't meaningful.
176 pub fn fully_trusted() -> Self {
177 Self::new(Config {
178 level: ImplicitTrustLevel::Insecure,
179 ..Config::default()
180 })
181 }
182
183 pub fn implicit_level(&self) -> ImplicitTrustLevel {
184 self.config.level
185 }
186
187 /// Whether the trust modal should be surfaced on `DocumentDidOpen`. When false the user is
188 /// only informed via the statusline indicator and acts explicitly via `:workspace-trust`.
189 pub fn prompts_enabled(&self) -> bool {
190 self.config.prompt
191 }
192
193 /// Replace the configuration in-place. Clears the trust cache so the next query re-reads from
194 /// disk. This catches external mutations to `.helix/` that happened while helix was running
195 /// (the editor's in-memory cache would otherwise keep returning a stale `Trusted` even though
196 /// `compute_workspace_hash` would now produce a different digest). Used by `:config-reload`.
197 ///
198 /// Session-only decisions made via [`Self::deny_once`] are discarded as part of the cache
199 /// clear; the trust popup's `prompted` set (scoped to the hook closure) is what suppresses
200 /// re-prompting across the reload, not this cache.
201 pub fn set_config(&mut self, config: Config) {
202 self.config = config;
203 self.inner.lock().clear();
204 }
205
206 /// Raw on-disk trust status for `workspace`, ignoring implicit-trust-level shortcuts and the
207 /// `demote_for_query` mapping. Use this when you need to distinguish *Stale* (was trusted,
208 /// `.helix/` changed) from *Untrusted* (never trusted)
209 pub fn status(&self, workspace: &Path) -> TrustStatus {
210 self.entry(workspace).status
211 }
212
213 /// Cache entry for `workspace`, loaded from disk on first call.
214 fn entry(&self, workspace: &Path) -> CacheEntry {
215 if let Some(entry) = self.inner.lock().get(workspace).copied() {
216 return entry;
217 }
218 let status = load_status(workspace);
219 let has_local_config = has_local_config(workspace);
220 let entry = CacheEntry {
221 status,
222 has_local_config,
223 };
224 self.inner.lock().insert(workspace.to_path_buf(), entry);
225 entry
226 }
227
228 /// Query trust for `workspace` from the perspective of a specific subsystem.
229 pub fn query(&self, workspace: &Path, query: TrustQuery) -> TrustStatus {
230 let raw = self.status(workspace);
231
232 // Explicit excludes always win.
233 if raw == TrustStatus::Excluded {
234 return TrustStatus::Excluded;
235 }
236
237 // Implicit-trust shortcuts only apply once we've ruled out excludes.
238 if self.config.level == ImplicitTrustLevel::Insecure {
239 return TrustStatus::Trusted;
240 }
241 // A config-listed glob grants full implicit trust to the matching workspace.
242 if self.is_glob_trusted(workspace) {
243 return TrustStatus::Trusted;
244 }
245 if self.config.level == ImplicitTrustLevel::Servers
246 && matches!(query, TrustQuery::Lsp | TrustQuery::Dap)
247 {
248 return TrustStatus::Trusted;
249 }
250
251 demote_for_query(raw, query)
252 }
253
254 /// Query trust for the workspace containing `file`.
255 pub fn query_for_file(&self, file: &Path, query: TrustQuery) -> TrustStatus {
256 let workspace = file
257 .parent()
258 .map(|dir| find_workspace_in(dir).0)
259 .unwrap_or_else(|| find_workspace().0);
260 self.query(&workspace, query)
261 }
262
263 /// Query trust for the current working directory's workspace.
264 pub fn query_current(&self, query: TrustQuery) -> TrustStatus {
265 let workspace = find_workspace().0;
266 self.query(&workspace, query)
267 }
268
269 /// Whether `workspace` matches one of the configured trust globs. Empty glob set never matches.
270 fn is_glob_trusted(&self, workspace: &Path) -> bool {
271 !self.config.trusted_globs.is_empty() && self.config.trusted_globs.is_match(workspace)
272 }
273
274 /// Workspace-wide "is this workspace in restricted mode and would running `trust`
275 /// change anything visible at the workspace level?" check.
276 ///
277 /// Reads the entire cache entry through `Self::entry` in a single lock acquisition (so the
278 /// `Untrusted` branch's `has_local_config` snapshot is consistent with the status read). Cheap
279 /// on the hot render path after the first query.
280 pub fn workspace_restricted(&self, workspace: &Path) -> bool {
281 // If the workspace is fully trusted there's no restrictions.
282 if self.config.level == ImplicitTrustLevel::Insecure || self.is_glob_trusted(workspace) {
283 return false;
284 }
285 let entry = self.entry(workspace);
286 match entry.status {
287 TrustStatus::Stale => true,
288 TrustStatus::Trusted | TrustStatus::Excluded => false,
289 TrustStatus::Untrusted => entry.has_local_config,
290 }
291 }
292
293 /// Per-document version of [`Self::workspace_restricted`].
294 pub fn restricted_for_doc(&self, workspace: &Path, servers_to_load: bool) -> bool {
295 if self.workspace_restricted(workspace) {
296 return true;
297 }
298 if !servers_to_load {
299 return false;
300 }
301 if self.status(workspace) != TrustStatus::Untrusted {
302 return false;
303 }
304 !self.query(workspace, TrustQuery::Lsp).is_trusted()
305 || !self.query(workspace, TrustQuery::Dap).is_trusted()
306 }
307
308 /// Mark `workspace` trusted. Snapshots the current `.helix/` hash.
309 pub fn trust(&self, workspace: &Path) {
310 let hash = compute_workspace_hash(workspace);
311 let has_local_config = has_local_config(workspace);
312 write_entry(
313 workspace,
314 &DiskEntry {
315 hash,
316 excluded: false,
317 },
318 );
319 self.inner.lock().insert(
320 workspace.to_path_buf(),
321 CacheEntry {
322 status: TrustStatus::Trusted,
323 has_local_config,
324 },
325 );
326 }
327
328 /// Revoke any persisted trust grant or exclusion for `workspace`.
329 pub fn untrust(&self, workspace: &Path) {
330 remove_entry(workspace);
331 self.inner.lock().remove(workspace);
332 }
333
334 /// Mark `workspace` excluded — never prompts again.
335 pub fn exclude(&self, workspace: &Path) {
336 let has_local_config = has_local_config(workspace);
337 write_entry(
338 workspace,
339 &DiskEntry {
340 hash: None,
341 excluded: true,
342 },
343 );
344 self.inner.lock().insert(
345 workspace.to_path_buf(),
346 CacheEntry {
347 status: TrustStatus::Excluded,
348 has_local_config,
349 },
350 );
351 }
352
353 /// Cache an untrusted decision for the current session.
354 pub fn deny_once(&self, workspace: &Path) {
355 let has_local_config = has_local_config(workspace);
356 self.inner.lock().insert(
357 workspace.to_path_buf(),
358 CacheEntry {
359 status: TrustStatus::Untrusted,
360 has_local_config,
361 },
362 );
363 }
364 }
365
366 fn has_local_config(workspace: &Path) -> bool {
367 workspace.join(".helix").join("config.toml").exists()
368 || workspace.join(".helix").join("languages.toml").exists()
369 }
370
371 fn demote_for_query(status: TrustStatus, query: TrustQuery) -> TrustStatus {
372 // Stale workspaces have their `.helix/` config changed since trust was granted. LSP launches
373 // still rely on globally-configured binaries that weren't part of the changed surface, so they
374 // remain Trusted; other queries demote to Untrusted until the user re-trusts.
375 match (status, query) {
376 (TrustStatus::Stale, TrustQuery::Lsp) => TrustStatus::Trusted,
377 (TrustStatus::Stale, _) => TrustStatus::Untrusted,
378 _ => status,
379 }
380 }
381
382 fn load_status(workspace: &Path) -> TrustStatus {
383 match read_entry(workspace) {
384 Some(entry) if entry.excluded => TrustStatus::Excluded,
385 Some(entry) => {
386 let current = compute_workspace_hash(workspace);
387 if entry.hash == current {
388 TrustStatus::Trusted
389 } else {
390 TrustStatus::Stale
391 }
392 }
393 None => TrustStatus::Untrusted,
394 }
395 }
396
397 // ---------- on-disk format ----------
398 //
399 // `data_dir()/workspace_trust/<sha256(canonical_workspace_path)>` is a small key-value file. The
400 // filename derives from the path, so concurrent helix instances writing trust for *different*
401 // workspaces never touch the same file. The original path is stored inside as a sanity check and
402 // for `cat workspace_trust/*` debugging.
403
404 struct DiskEntry {
405 hash: Option<String>,
406 excluded: bool,
407 }
408
409 fn workspace_trust_dir() -> PathBuf {
410 data_dir().join("workspace_trust")
411 }
412
413 fn entry_path(workspace: &Path) -> PathBuf {
414 workspace_trust_dir().join(path_filename(workspace))
415 }
416
417 fn path_filename(workspace: &Path) -> String {
418 let mut hasher = Sha256::new();
419 // `Path` is OsStr; encode lossy-but-deterministically. Two workspaces whose normalized paths
420 // differ only in non-UTF-8 bytes will collide here, but find_workspace() returns paths derived
421 // from CWD walking and that's already lossy on the FS side — accepting parity.
422 hasher.update(workspace.as_os_str().to_string_lossy().as_bytes());
423 let digest = hasher.finalize();
424 format!("{digest:x}")
425 }
426
427 fn read_entry(workspace: &Path) -> Option<DiskEntry> {
428 let path = entry_path(workspace);
429 let contents = match fs::read_to_string(&path) {
430 Ok(s) => s,
431 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
432 Err(err) => {
433 log::error!("workspace trust file {path:?} unreadable: {err:?}");
434 return None;
435 }
436 };
437
438 let mut stored_path: Option<String> = None;
439 let mut hash: Option<String> = None;
440 let mut excluded = false;
441 for line in contents.lines() {
442 let line = line.trim();
443 if line.is_empty() || line.starts_with('#') {
444 continue;
445 }
446 let Some((k, v)) = line.split_once('=') else {
447 continue;
448 };
449 let k = k.trim();
450 let v = v.trim();
451 match k {
452 "path" => stored_path = Some(v.to_string()),
453 "hash" => hash = Some(v.to_string()),
454 "excluded" => excluded = v == "true",
455 _ => {}
456 }
457 }
458
459 // Sanity check that we didn't hit a path collision: the path inside the file should match the
460 // workspace we looked up.
461 if let Some(stored) = stored_path {
462 if Path::new(&stored) != workspace {
463 log::error!(
464 "workspace trust file {path:?} contains path {stored:?}, expected {workspace:?}"
465 );
466 return None;
467 }
468 }
469
470 Some(DiskEntry { hash, excluded })
471 }
472
473 fn write_entry(workspace: &Path, entry: &DiskEntry) {
474 let dir = workspace_trust_dir();
475 if let Err(err) = fs::create_dir_all(&dir) {
476 log::error!("Couldn't create workspace trust dir {dir:?}: {err:?}");
477 return;
478 }
479 let path = entry_path(workspace);
480
481 let mut contents = String::new();
482 let _ = writeln!(contents, "path = {}", workspace.display());
483 if let Some(hash) = &entry.hash {
484 let _ = writeln!(contents, "hash = {hash}");
485 }
486 let _ = writeln!(contents, "excluded = {}", entry.excluded);
487
488 if let Err(err) = fs::write(&path, contents) {
489 log::error!("Error writing workspace trust file {path:?}: {err:?}");
490 }
491 }
492
493 fn remove_entry(workspace: &Path) {
494 let path = entry_path(workspace);
495 match fs::remove_file(&path) {
496 Ok(()) => {}
497 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
498 Err(err) => log::error!("Error removing workspace trust file {path:?}: {err:?}"),
499 }
500 }
501
502 // ---------- hashing ----------
503
504 /// SHA-256 of all files under `.helix/`, used to detect changes to local config after trust was
505 /// granted. Returns `None` if `.helix/` is absent or has no files, so a workspace with no local
506 /// config can still be trusted.
507 pub fn compute_workspace_hash(workspace: &Path) -> Option<String> {
508 let helix_dir = workspace.join(".helix");
509 if !helix_dir.is_dir() {
510 return None;
511 }
512
513 let mut files: Vec<PathBuf> = Vec::new();
514 walk(&helix_dir, &mut files);
515 if files.is_empty() {
516 return None;
517 }
518 files.sort();
519
520 let mut hasher = Sha256::new();
521 for file in &files {
522 let rel = file.strip_prefix(&helix_dir).unwrap_or(file);
523 hash_field(&mut hasher, rel.to_string_lossy().as_bytes());
524 match fs::read(file) {
525 Ok(bytes) => hash_field(&mut hasher, &bytes),
526 Err(err) => {
527 log::warn!("workspace hash: treating unreadable file {file:?} as empty: {err:?}");
528 hash_field(&mut hasher, &[]);
529 }
530 }
531 }
532 let digest = hasher.finalize();
533 Some(format!("sha256:{digest:x}"))
534 }
535
536 /// Length-prefix a field before feeding it to the hasher.
537 fn hash_field(hasher: &mut Sha256, bytes: &[u8]) {
538 hasher.update((bytes.len() as u64).to_le_bytes());
539 hasher.update(bytes);
540 }
541
542 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
543 let Ok(entries) = fs::read_dir(dir) else {
544 return;
545 };
546 for entry in entries.flatten() {
547 let path = entry.path();
548 let Ok(direct) = entry.file_type() else {
549 continue;
550 };
551 if direct.is_dir() {
552 // Real directories only — don't follow symlinked directories to avoid filesystem
553 // cycles via path-loop symlinks.
554 walk(&path, out);
555 } else if direct.is_file() {
556 out.push(path);
557 } else if direct.is_symlink() {
558 // Symlinks to files (extremely common: dotfiles managers symlink `.helix/config.toml`
559 // to an external location). Follow once via `fs::metadata` which traverses links, then
560 // include the file in the hash so mutations to the *target* are still detected.
561 if let Ok(target) = fs::metadata(&path) {
562 if target.is_file() {
563 out.push(path);
564 }
565 }
566 }
567 }
568 }
569
570 #[cfg(test)]
571 mod test {
572 use super::*;
573 use std::io::Write;
574
575 fn write_file(path: &Path, contents: &str) {
576 if let Some(parent) = path.parent() {
577 fs::create_dir_all(parent).unwrap();
578 }
579 let mut f = fs::File::create(path).unwrap();
580 f.write_all(contents.as_bytes()).unwrap();
581 }
582
583 #[test]
584 fn hash_changes_when_helix_dir_changes() {
585 let dir = tempfile::tempdir().unwrap();
586 let workspace = dir.path();
587
588 let empty = compute_workspace_hash(workspace);
589 assert_eq!(empty, None, ".helix/ absent should hash to None");
590
591 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
592 let h1 = compute_workspace_hash(workspace).expect("has files");
593 assert!(h1.starts_with("sha256:"));
594
595 // Same content → same hash
596 let h1b = compute_workspace_hash(workspace).expect("has files");
597 assert_eq!(h1, h1b);
598
599 // Different content → different hash
600 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
601 let h2 = compute_workspace_hash(workspace).expect("has files");
602 assert_ne!(h1, h2);
603
604 // Added file → different hash
605 write_file(&workspace.join(".helix").join("languages.toml"), "");
606 let h3 = compute_workspace_hash(workspace).expect("has files");
607 assert_ne!(h2, h3);
608 }
609
610 #[test]
611 fn sha256_known_vector() {
612 // Cross-check sha2 crate against a well-known SHA-256 of "abc".
613 let mut h = Sha256::new();
614 h.update(b"abc");
615 assert_eq!(
616 format!("{:x}", h.finalize()),
617 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
618 );
619 }
620
621 #[test]
622 fn workspace_restricted_hides_when_no_local_config() {
623 let dir = tempfile::tempdir().unwrap();
624 let workspace = dir.path();
625
626 let trust = WorkspaceTrust::new(Config::default());
627 // Untrusted + no .helix/ → indicator should hide.
628 assert!(!trust.workspace_restricted(workspace));
629
630 // Untrusted + .helix/config.toml exists → indicator should show.
631 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
632 // Bust the cache so the new file is picked up.
633 trust.untrust(workspace);
634 assert!(trust.workspace_restricted(workspace));
635
636 // After explicit trust, indicator hides.
637 trust.trust(workspace);
638 assert!(!trust.workspace_restricted(workspace));
639
640 // After mutation (and revoking the cached entry to simulate fresh load), workspace becomes
641 // Stale → indicator should show again.
642 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
643 trust.inner.lock().remove(workspace);
644 assert!(trust.workspace_restricted(workspace));
645 }
646
647 #[test]
648 fn set_config_invalidates_cache_so_stale_is_detected() {
649 // Regression: prior to this fix the editor's WorkspaceTrust cache held a `Trusted` entry
650 // after `:workspace-trust` was run. If the user (or another process) modified `.helix/`
651 // while helix was running, subsequent queries kept returning Trusted even though
652 // `Config::load_default`'s transient WorkspaceTrust would correctly see Stale. Reloading
653 // config now clears the cache so the editor sees the new state on the next query.
654 let dir = tempfile::tempdir().unwrap();
655 let workspace = dir.path();
656 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
657
658 let mut trust = WorkspaceTrust::new(Config::default());
659 trust.trust(workspace);
660 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
661
662 // External mutation while helix is running.
663 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
664
665 // Without a refresh, the cache still says Trusted.
666 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
667
668 // Simulate `:config-reload`.
669 trust.set_config(Config::default());
670
671 // Fresh disk read now detects the hash mismatch.
672 assert_eq!(trust.status(workspace), TrustStatus::Stale);
673 }
674
675 #[cfg(unix)]
676 #[test]
677 fn hash_includes_symlinked_config_file() {
678 // Regression: `.helix/config.toml` is commonly a symlink to an external location (dotfiles
679 // managers). The old `walk` only matched `is_dir() | is_file()`, so symlinks fell through
680 // and were excluded from the hash entirely — trust was granted with an effectively empty
681 // hash and config mutations went undetected.
682 use std::os::unix::fs::symlink;
683
684 let dir = tempfile::tempdir().unwrap();
685 let workspace = dir.path();
686 let external = dir.path().join("external_config.toml");
687 write_file(&external, "a = 1");
688
689 fs::create_dir_all(workspace.join(".helix")).unwrap();
690 symlink(&external, workspace.join(".helix").join("config.toml")).unwrap();
691
692 let h1 = compute_workspace_hash(workspace).expect("symlink should be hashed");
693
694 // Mutating the symlink *target* must change the hash.
695 write_file(&external, "a = 2");
696 let h2 = compute_workspace_hash(workspace).expect("symlink should be hashed");
697 assert_ne!(
698 h1, h2,
699 "symlinked config file mutations must affect the hash"
700 );
701 }
702
703 #[test]
704 fn hash_distinguishes_file_split() {
705 // Regression: without length-prefixing, two files
706 // foo.toml: "a"
707 // bar.toml: "b"
708 // would feed the same byte stream to the hasher as a single file
709 // foo.toml: "a\0bar.toml\0b"
710 // because the \0 separators were indistinguishable from content.
711 let dir1 = tempfile::tempdir().unwrap();
712 let split = dir1.path();
713 write_file(&split.join(".helix").join("foo.toml"), "a");
714 write_file(&split.join(".helix").join("bar.toml"), "b");
715
716 let dir2 = tempfile::tempdir().unwrap();
717 let merged = dir2.path();
718 write_file(&merged.join(".helix").join("foo.toml"), "a\0bar.toml\0b");
719
720 let h1 = compute_workspace_hash(split).expect("split has files");
721 let h2 = compute_workspace_hash(merged).expect("merged has files");
722 assert_ne!(
723 h1, h2,
724 "length-prefixing must prevent file-vs-content ambiguity"
725 );
726 }
727
728 #[test]
729 fn level_insecure_does_not_bypass_excluded() {
730 // Regression: under `level = "insecure"` an exclude entry on disk must still produce
731 // `TrustStatus::Excluded` from `query()`. The old shortcut read only the in-memory cache,
732 // so a cold cache silently returned `Trusted`.
733 let dir = tempfile::tempdir().unwrap();
734 let workspace = dir.path();
735
736 // Seed an excluded entry via a level=None trust state.
737 let bootstrap = WorkspaceTrust::new(Config::default());
738 bootstrap.exclude(workspace);
739
740 // Fresh state (cold cache) under level=Insecure.
741 let trust = WorkspaceTrust::new(Config {
742 level: ImplicitTrustLevel::Insecure,
743 ..Config::default()
744 });
745 assert_eq!(
746 trust.query(workspace, TrustQuery::Lsp),
747 TrustStatus::Excluded,
748 "level=insecure must honor disk-persisted excludes even on a cold cache"
749 );
750 assert_eq!(
751 trust.query(workspace, TrustQuery::LocalConfig),
752 TrustStatus::Excluded
753 );
754 }
755
756 #[test]
757 fn trusted_glob_grants_full_trust_but_exclude_wins() {
758 let dir = tempfile::tempdir().unwrap();
759 let trusted = dir.path().join("trusted_proj");
760 fs::create_dir_all(&trusted).unwrap();
761
762 let pattern = format!("{}/*", dir.path().display());
763 let trust = WorkspaceTrust::new(Config {
764 level: ImplicitTrustLevel::None,
765 trusted_globs: build_trusted_globs(&[pattern]),
766 ..Config::default()
767 });
768
769 // Matching workspace is fully trusted for every capability, even local config (which
770 // `level = "servers"` would still gate).
771 assert_eq!(
772 trust.query(&trusted, TrustQuery::LocalConfig),
773 TrustStatus::Trusted
774 );
775 assert_eq!(trust.query(&trusted, TrustQuery::Git), TrustStatus::Trusted);
776 assert!(!trust.workspace_restricted(&trusted));
777
778 // A non-matching path (no `dir/*` segment match: it has a deeper component) still trusts
779 // since `other` is directly under `dir`. Use a sibling outside `dir` to confirm no match.
780 let outside = tempfile::tempdir().unwrap();
781 assert_eq!(
782 trust.query(outside.path(), TrustQuery::LocalConfig),
783 TrustStatus::Untrusted
784 );
785
786 // Explicit excludes beat a matching glob.
787 trust.exclude(&trusted);
788 assert_eq!(
789 trust.query(&trusted, TrustQuery::LocalConfig),
790 TrustStatus::Excluded
791 );
792 assert_eq!(
793 trust.query(&trusted, TrustQuery::Lsp),
794 TrustStatus::Excluded
795 );
796 }
797
798 #[test]
799 fn workspace_restricted_detects_stale() {
800 // Regression: a previously-trusted workspace whose .helix/ has since been modified must be
801 // reported as restricted (so the indicator and stale-hint can fire). The old code piped
802 // Stale through `demote_for_query` and matched Untrusted, which made the `Stale` arm of
803 // `workspace_restricted` unreachable.
804 let dir = tempfile::tempdir().unwrap();
805 let workspace = dir.path();
806 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
807
808 let trust = WorkspaceTrust::new(Config::default());
809 trust.trust(workspace);
810 assert!(!trust.workspace_restricted(workspace));
811 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
812
813 // Mutate `.helix/` and bust the in-memory cache to force a re-read.
814 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
815 trust.inner.lock().remove(workspace);
816
817 assert_eq!(trust.status(workspace), TrustStatus::Stale);
818 assert!(
819 trust.workspace_restricted(workspace),
820 "Stale workspace must light up the restricted indicator"
821 );
822 }
823
824 #[test]
825 fn path_filename_is_stable_and_path_specific() {
826 let a = path_filename(Path::new("/home/u/proj1"));
827 let b = path_filename(Path::new("/home/u/proj1"));
828 let c = path_filename(Path::new("/home/u/proj2"));
829 assert_eq!(a, b);
830 assert_ne!(a, c);
831 assert_eq!(a.len(), 64); // hex sha256
832 }
833 }