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 hex_encode(&digest)
425 }
426
427 fn hex_encode(bytes: &[u8]) -> String {
428 let mut out = String::with_capacity(bytes.len() * 2);
429 for byte in bytes {
430 let _ = write!(out, "{byte:02x}");
431 }
432 out
433 }
434
435 fn read_entry(workspace: &Path) -> Option<DiskEntry> {
436 let path = entry_path(workspace);
437 let contents = match fs::read_to_string(&path) {
438 Ok(s) => s,
439 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
440 Err(err) => {
441 log::error!("workspace trust file {path:?} unreadable: {err:?}");
442 return None;
443 }
444 };
445
446 let mut stored_path: Option<String> = None;
447 let mut hash: Option<String> = None;
448 let mut excluded = false;
449 for line in contents.lines() {
450 let line = line.trim();
451 if line.is_empty() || line.starts_with('#') {
452 continue;
453 }
454 let Some((k, v)) = line.split_once('=') else {
455 continue;
456 };
457 let k = k.trim();
458 let v = v.trim();
459 match k {
460 "path" => stored_path = Some(v.to_string()),
461 "hash" => hash = Some(v.to_string()),
462 "excluded" => excluded = v == "true",
463 _ => {}
464 }
465 }
466
467 // Sanity check that we didn't hit a path collision: the path inside the file should match the
468 // workspace we looked up.
469 if let Some(stored) = stored_path {
470 if Path::new(&stored) != workspace {
471 log::error!(
472 "workspace trust file {path:?} contains path {stored:?}, expected {workspace:?}"
473 );
474 return None;
475 }
476 }
477
478 Some(DiskEntry { hash, excluded })
479 }
480
481 fn write_entry(workspace: &Path, entry: &DiskEntry) {
482 let dir = workspace_trust_dir();
483 if let Err(err) = fs::create_dir_all(&dir) {
484 log::error!("Couldn't create workspace trust dir {dir:?}: {err:?}");
485 return;
486 }
487 let path = entry_path(workspace);
488
489 let mut contents = String::new();
490 let _ = writeln!(contents, "path = {}", workspace.display());
491 if let Some(hash) = &entry.hash {
492 let _ = writeln!(contents, "hash = {hash}");
493 }
494 let _ = writeln!(contents, "excluded = {}", entry.excluded);
495
496 if let Err(err) = fs::write(&path, contents) {
497 log::error!("Error writing workspace trust file {path:?}: {err:?}");
498 }
499 }
500
501 fn remove_entry(workspace: &Path) {
502 let path = entry_path(workspace);
503 match fs::remove_file(&path) {
504 Ok(()) => {}
505 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
506 Err(err) => log::error!("Error removing workspace trust file {path:?}: {err:?}"),
507 }
508 }
509
510 // ---------- hashing ----------
511
512 /// SHA-256 of all files under `.helix/`, used to detect changes to local config after trust was
513 /// granted. Returns `None` if `.helix/` is absent or has no files, so a workspace with no local
514 /// config can still be trusted.
515 pub fn compute_workspace_hash(workspace: &Path) -> Option<String> {
516 let helix_dir = workspace.join(".helix");
517 if !helix_dir.is_dir() {
518 return None;
519 }
520
521 let mut files: Vec<PathBuf> = Vec::new();
522 walk(&helix_dir, &mut files);
523 if files.is_empty() {
524 return None;
525 }
526 files.sort();
527
528 let mut hasher = Sha256::new();
529 for file in &files {
530 let rel = file.strip_prefix(&helix_dir).unwrap_or(file);
531 hash_field(&mut hasher, rel.to_string_lossy().as_bytes());
532 match fs::read(file) {
533 Ok(bytes) => hash_field(&mut hasher, &bytes),
534 Err(err) => {
535 log::warn!("workspace hash: treating unreadable file {file:?} as empty: {err:?}");
536 hash_field(&mut hasher, &[]);
537 }
538 }
539 }
540 let digest = hasher.finalize();
541 Some(format!("sha256:{}", hex_encode(&digest)))
542 }
543
544 /// Length-prefix a field before feeding it to the hasher.
545 fn hash_field(hasher: &mut Sha256, bytes: &[u8]) {
546 hasher.update((bytes.len() as u64).to_le_bytes());
547 hasher.update(bytes);
548 }
549
550 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
551 let Ok(entries) = fs::read_dir(dir) else {
552 return;
553 };
554 for entry in entries.flatten() {
555 let path = entry.path();
556 let Ok(direct) = entry.file_type() else {
557 continue;
558 };
559 if direct.is_dir() {
560 // Real directories only — don't follow symlinked directories to avoid filesystem
561 // cycles via path-loop symlinks.
562 walk(&path, out);
563 } else if direct.is_file() {
564 out.push(path);
565 } else if direct.is_symlink() {
566 // Symlinks to files (extremely common: dotfiles managers symlink `.helix/config.toml`
567 // to an external location). Follow once via `fs::metadata` which traverses links, then
568 // include the file in the hash so mutations to the *target* are still detected.
569 if let Ok(target) = fs::metadata(&path) {
570 if target.is_file() {
571 out.push(path);
572 }
573 }
574 }
575 }
576 }
577
578 #[cfg(test)]
579 mod test {
580 use super::*;
581 use std::io::Write;
582
583 fn write_file(path: &Path, contents: &str) {
584 if let Some(parent) = path.parent() {
585 fs::create_dir_all(parent).unwrap();
586 }
587 let mut f = fs::File::create(path).unwrap();
588 f.write_all(contents.as_bytes()).unwrap();
589 }
590
591 #[test]
592 fn hash_changes_when_helix_dir_changes() {
593 let dir = tempfile::tempdir().unwrap();
594 let workspace = dir.path();
595
596 let empty = compute_workspace_hash(workspace);
597 assert_eq!(empty, None, ".helix/ absent should hash to None");
598
599 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
600 let h1 = compute_workspace_hash(workspace).expect("has files");
601 assert!(h1.starts_with("sha256:"));
602
603 // Same content → same hash
604 let h1b = compute_workspace_hash(workspace).expect("has files");
605 assert_eq!(h1, h1b);
606
607 // Different content → different hash
608 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
609 let h2 = compute_workspace_hash(workspace).expect("has files");
610 assert_ne!(h1, h2);
611
612 // Added file → different hash
613 write_file(&workspace.join(".helix").join("languages.toml"), "");
614 let h3 = compute_workspace_hash(workspace).expect("has files");
615 assert_ne!(h2, h3);
616 }
617
618 #[test]
619 fn sha256_known_vector() {
620 // Cross-check sha2 crate against a well-known SHA-256 of "abc".
621 let mut h = Sha256::new();
622 h.update(b"abc");
623 assert_eq!(
624 hex_encode(&h.finalize()),
625 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
626 );
627 }
628
629 #[test]
630 fn workspace_restricted_hides_when_no_local_config() {
631 let dir = tempfile::tempdir().unwrap();
632 let workspace = dir.path();
633
634 let trust = WorkspaceTrust::new(Config::default());
635 // Untrusted + no .helix/ → indicator should hide.
636 assert!(!trust.workspace_restricted(workspace));
637
638 // Untrusted + .helix/config.toml exists → indicator should show.
639 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
640 // Bust the cache so the new file is picked up.
641 trust.untrust(workspace);
642 assert!(trust.workspace_restricted(workspace));
643
644 // After explicit trust, indicator hides.
645 trust.trust(workspace);
646 assert!(!trust.workspace_restricted(workspace));
647
648 // After mutation (and revoking the cached entry to simulate fresh load), workspace becomes
649 // Stale → indicator should show again.
650 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
651 trust.inner.lock().remove(workspace);
652 assert!(trust.workspace_restricted(workspace));
653 }
654
655 #[test]
656 fn set_config_invalidates_cache_so_stale_is_detected() {
657 // Regression: prior to this fix the editor's WorkspaceTrust cache held a `Trusted` entry
658 // after `:workspace-trust` was run. If the user (or another process) modified `.helix/`
659 // while helix was running, subsequent queries kept returning Trusted even though
660 // `Config::load_default`'s transient WorkspaceTrust would correctly see Stale. Reloading
661 // config now clears the cache so the editor sees the new state on the next query.
662 let dir = tempfile::tempdir().unwrap();
663 let workspace = dir.path();
664 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
665
666 let mut trust = WorkspaceTrust::new(Config::default());
667 trust.trust(workspace);
668 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
669
670 // External mutation while helix is running.
671 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
672
673 // Without a refresh, the cache still says Trusted.
674 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
675
676 // Simulate `:config-reload`.
677 trust.set_config(Config::default());
678
679 // Fresh disk read now detects the hash mismatch.
680 assert_eq!(trust.status(workspace), TrustStatus::Stale);
681 }
682
683 #[cfg(unix)]
684 #[test]
685 fn hash_includes_symlinked_config_file() {
686 // Regression: `.helix/config.toml` is commonly a symlink to an external location (dotfiles
687 // managers). The old `walk` only matched `is_dir() | is_file()`, so symlinks fell through
688 // and were excluded from the hash entirely — trust was granted with an effectively empty
689 // hash and config mutations went undetected.
690 use std::os::unix::fs::symlink;
691
692 let dir = tempfile::tempdir().unwrap();
693 let workspace = dir.path();
694 let external = dir.path().join("external_config.toml");
695 write_file(&external, "a = 1");
696
697 fs::create_dir_all(workspace.join(".helix")).unwrap();
698 symlink(&external, workspace.join(".helix").join("config.toml")).unwrap();
699
700 let h1 = compute_workspace_hash(workspace).expect("symlink should be hashed");
701
702 // Mutating the symlink *target* must change the hash.
703 write_file(&external, "a = 2");
704 let h2 = compute_workspace_hash(workspace).expect("symlink should be hashed");
705 assert_ne!(
706 h1, h2,
707 "symlinked config file mutations must affect the hash"
708 );
709 }
710
711 #[test]
712 fn hash_distinguishes_file_split() {
713 // Regression: without length-prefixing, two files
714 // foo.toml: "a"
715 // bar.toml: "b"
716 // would feed the same byte stream to the hasher as a single file
717 // foo.toml: "a\0bar.toml\0b"
718 // because the \0 separators were indistinguishable from content.
719 let dir1 = tempfile::tempdir().unwrap();
720 let split = dir1.path();
721 write_file(&split.join(".helix").join("foo.toml"), "a");
722 write_file(&split.join(".helix").join("bar.toml"), "b");
723
724 let dir2 = tempfile::tempdir().unwrap();
725 let merged = dir2.path();
726 write_file(&merged.join(".helix").join("foo.toml"), "a\0bar.toml\0b");
727
728 let h1 = compute_workspace_hash(split).expect("split has files");
729 let h2 = compute_workspace_hash(merged).expect("merged has files");
730 assert_ne!(
731 h1, h2,
732 "length-prefixing must prevent file-vs-content ambiguity"
733 );
734 }
735
736 #[test]
737 fn level_insecure_does_not_bypass_excluded() {
738 // Regression: under `level = "insecure"` an exclude entry on disk must still produce
739 // `TrustStatus::Excluded` from `query()`. The old shortcut read only the in-memory cache,
740 // so a cold cache silently returned `Trusted`.
741 let dir = tempfile::tempdir().unwrap();
742 let workspace = dir.path();
743
744 // Seed an excluded entry via a level=None trust state.
745 let bootstrap = WorkspaceTrust::new(Config::default());
746 bootstrap.exclude(workspace);
747
748 // Fresh state (cold cache) under level=Insecure.
749 let trust = WorkspaceTrust::new(Config {
750 level: ImplicitTrustLevel::Insecure,
751 ..Config::default()
752 });
753 assert_eq!(
754 trust.query(workspace, TrustQuery::Lsp),
755 TrustStatus::Excluded,
756 "level=insecure must honor disk-persisted excludes even on a cold cache"
757 );
758 assert_eq!(
759 trust.query(workspace, TrustQuery::LocalConfig),
760 TrustStatus::Excluded
761 );
762 }
763
764 #[test]
765 fn trusted_glob_grants_full_trust_but_exclude_wins() {
766 let dir = tempfile::tempdir().unwrap();
767 let trusted = dir.path().join("trusted_proj");
768 fs::create_dir_all(&trusted).unwrap();
769
770 let pattern = format!("{}/*", dir.path().display());
771 let trust = WorkspaceTrust::new(Config {
772 level: ImplicitTrustLevel::None,
773 trusted_globs: build_trusted_globs(&[pattern]),
774 ..Config::default()
775 });
776
777 // Matching workspace is fully trusted for every capability, even local config (which
778 // `level = "servers"` would still gate).
779 assert_eq!(
780 trust.query(&trusted, TrustQuery::LocalConfig),
781 TrustStatus::Trusted
782 );
783 assert_eq!(trust.query(&trusted, TrustQuery::Git), TrustStatus::Trusted);
784 assert!(!trust.workspace_restricted(&trusted));
785
786 // A non-matching path (no `dir/*` segment match: it has a deeper component) still trusts
787 // since `other` is directly under `dir`. Use a sibling outside `dir` to confirm no match.
788 let outside = tempfile::tempdir().unwrap();
789 assert_eq!(
790 trust.query(outside.path(), TrustQuery::LocalConfig),
791 TrustStatus::Untrusted
792 );
793
794 // Explicit excludes beat a matching glob.
795 trust.exclude(&trusted);
796 assert_eq!(
797 trust.query(&trusted, TrustQuery::LocalConfig),
798 TrustStatus::Excluded
799 );
800 assert_eq!(
801 trust.query(&trusted, TrustQuery::Lsp),
802 TrustStatus::Excluded
803 );
804 }
805
806 #[test]
807 fn workspace_restricted_detects_stale() {
808 // Regression: a previously-trusted workspace whose .helix/ has since been modified must be
809 // reported as restricted (so the indicator and stale-hint can fire). The old code piped
810 // Stale through `demote_for_query` and matched Untrusted, which made the `Stale` arm of
811 // `workspace_restricted` unreachable.
812 let dir = tempfile::tempdir().unwrap();
813 let workspace = dir.path();
814 write_file(&workspace.join(".helix").join("config.toml"), "a = 1");
815
816 let trust = WorkspaceTrust::new(Config::default());
817 trust.trust(workspace);
818 assert!(!trust.workspace_restricted(workspace));
819 assert_eq!(trust.status(workspace), TrustStatus::Trusted);
820
821 // Mutate `.helix/` and bust the in-memory cache to force a re-read.
822 write_file(&workspace.join(".helix").join("config.toml"), "a = 2");
823 trust.inner.lock().remove(workspace);
824
825 assert_eq!(trust.status(workspace), TrustStatus::Stale);
826 assert!(
827 trust.workspace_restricted(workspace),
828 "Stale workspace must light up the restricted indicator"
829 );
830 }
831
832 #[test]
833 fn path_filename_is_stable_and_path_specific() {
834 let a = path_filename(Path::new("/home/u/proj1"));
835 let b = path_filename(Path::new("/home/u/proj1"));
836 let c = path_filename(Path::new("/home/u/proj2"));
837 assert_eq!(a, b);
838 assert_ne!(a, c);
839 assert_eq!(a.len(), 64); // hex sha256
840 }
841 }