1use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24
25use serde::{Deserialize, Serialize};
26
27use crate::error::{Error, Result};
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(deny_unknown_fields)]
31pub struct Config {
32 #[serde(default)]
34 pub activation: ActivationMode,
35 pub remote: RemoteConfig,
36 #[serde(default)]
37 pub local: LocalConfig,
38 #[serde(default)]
39 pub limits: Limits,
40 #[serde(default)]
41 pub audit: AuditConfig,
42 #[serde(default)]
43 pub guard: GuardConfig,
44 #[serde(default)]
45 pub approval: ApprovalConfig,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct RemoteConfig {
51 pub host: String,
55 pub workdir: String,
59 #[serde(default)]
63 pub os: Os,
64 #[serde(default = "default_shell")]
70 pub shell: Vec<String>,
71 #[serde(default = "default_connect_timeout")]
72 pub connect_timeout_secs: u64,
73 #[serde(default = "default_alive_interval")]
75 pub server_alive_interval_secs: u64,
76}
77
78pub fn default_shell() -> Vec<String> {
79 vec!["bash".into(), "-lc".into()]
80}
81
82#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "lowercase")]
85pub enum Os {
86 #[default]
87 Auto,
88 Posix,
90 Windows,
92}
93fn default_connect_timeout() -> u64 {
94 20
95}
96fn default_alive_interval() -> u64 {
97 30
98}
99
100#[derive(Debug, Clone, Default, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct LocalConfig {
103 #[serde(default)]
106 pub allowed_dirs: Vec<PathBuf>,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct Limits {
112 #[serde(default = "default_command_timeout")]
113 pub command_timeout_secs: u64,
114 #[serde(default = "default_max_command_timeout")]
115 pub max_command_timeout_secs: u64,
116 #[serde(default = "default_max_output_bytes")]
117 pub max_output_bytes: usize,
118 #[serde(default = "default_max_read_bytes")]
119 pub max_read_bytes: usize,
120 #[serde(default = "default_max_transfer_bytes")]
121 pub max_transfer_bytes: u64,
122 #[serde(default = "default_max_transfer_files")]
123 pub max_transfer_files: usize,
124}
125
126fn default_command_timeout() -> u64 {
127 120
128}
129fn default_max_command_timeout() -> u64 {
130 1800
131}
132fn default_max_output_bytes() -> usize {
133 100 * 1024
134}
135fn default_max_read_bytes() -> usize {
136 512 * 1024
137}
138fn default_max_transfer_bytes() -> u64 {
139 1024 * 1024 * 1024
140}
141fn default_max_transfer_files() -> usize {
142 5000
143}
144
145impl Default for Limits {
146 fn default() -> Self {
147 Self {
148 command_timeout_secs: default_command_timeout(),
149 max_command_timeout_secs: default_max_command_timeout(),
150 max_output_bytes: default_max_output_bytes(),
151 max_read_bytes: default_max_read_bytes(),
152 max_transfer_bytes: default_max_transfer_bytes(),
153 max_transfer_files: default_max_transfer_files(),
154 }
155 }
156}
157
158#[derive(Debug, Clone, Default, Serialize, Deserialize)]
159#[serde(deny_unknown_fields)]
160pub struct AuditConfig {
161 pub log_dir: Option<PathBuf>,
165}
166
167#[derive(Debug, Clone, Default, Serialize, Deserialize)]
168#[serde(deny_unknown_fields)]
169pub struct GuardConfig {
170 #[serde(default)]
173 pub deny_globs: Vec<String>,
174 #[serde(default)]
176 pub deny_content: Vec<String>,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
182#[serde(rename_all = "lowercase")]
183pub enum ActivationMode {
184 Always,
186 #[default]
191 Project,
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum Source {
197 Explicit,
198 Env,
199 Project,
200 Global,
201}
202
203#[derive(Debug, Clone)]
206pub struct Loaded {
207 pub config: Config,
208 pub path: PathBuf,
209 pub source: Source,
210 pub notices: Vec<String>,
213}
214
215impl Loaded {
216 pub fn active(&self) -> bool {
217 match self.source {
218 Source::Explicit | Source::Env | Source::Project => true,
219 Source::Global => self.config.activation == ActivationMode::Always,
220 }
221 }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "lowercase")]
229pub enum ApprovalMode {
230 Ask,
233 Auto,
235 Strict,
237}
238
239impl ApprovalMode {
240 pub fn as_str(self) -> &'static str {
241 match self {
242 ApprovalMode::Ask => "ask",
243 ApprovalMode::Auto => "auto",
244 ApprovalMode::Strict => "strict",
245 }
246 }
247}
248
249pub const MUTATING_TOOLS: &[&str] = &[
251 "remote_shell",
252 "remote_write",
253 "remote_edit",
254 "upload",
255 "download",
256];
257
258pub const READ_ONLY_TOOLS: &[&str] = &[
260 "remote_read",
261 "remote_ls",
262 "remote_glob",
263 "remote_grep",
264 "local_ls",
265 "local_read",
266 "remote_info",
267];
268
269#[derive(Debug, Clone, Serialize, Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct ApprovalConfig {
272 #[serde(default = "default_approval")]
274 pub mode: ApprovalMode,
275 #[serde(default)]
277 pub tools: BTreeMap<String, ApprovalMode>,
278}
279
280fn default_approval() -> ApprovalMode {
281 ApprovalMode::Ask
282}
283
284impl Default for ApprovalConfig {
285 fn default() -> Self {
286 Self {
287 mode: default_approval(),
288 tools: BTreeMap::new(),
289 }
290 }
291}
292
293impl ApprovalConfig {
294 pub fn effective(&self) -> BTreeMap<&'static str, ApprovalMode> {
297 let mutating = match self.mode {
298 ApprovalMode::Auto => ApprovalMode::Auto,
299 ApprovalMode::Ask | ApprovalMode::Strict => ApprovalMode::Ask,
300 };
301 let read_only = match self.mode {
302 ApprovalMode::Strict => ApprovalMode::Ask,
303 ApprovalMode::Ask | ApprovalMode::Auto => ApprovalMode::Auto,
304 };
305 MUTATING_TOOLS
306 .iter()
307 .map(|t| (*t, mutating))
308 .chain(READ_ONLY_TOOLS.iter().map(|t| (*t, read_only)))
309 .map(|(t, m)| (t, self.tools.get(t).copied().unwrap_or(m)))
310 .collect()
311 }
312}
313
314impl Config {
315 pub fn example() -> &'static str {
316 EXAMPLE
317 }
318
319 pub fn load(explicit: Option<&Path>) -> Result<(Self, PathBuf)> {
322 let l = Self::load_in(None, explicit)?;
323 Ok((l.config, l.path))
324 }
325
326 pub fn load_in(cwd: Option<&Path>, explicit: Option<&Path>) -> Result<Loaded> {
329 let (path, source) = match explicit {
330 Some(p) if p.file_name() == Some(".farhand.toml".as_ref()) => {
333 (p.to_path_buf(), Source::Project)
334 }
335 Some(p) => (p.to_path_buf(), Source::Explicit),
336 None => Self::locate(cwd)?,
337 };
338 let text = std::fs::read_to_string(&path)
339 .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?;
340 let base = match source {
344 Source::Global => None,
345 _ => path.parent().map(Path::to_path_buf),
346 };
347 let (config, notices) = if source == Source::Project {
348 let global = Self::global_path();
349 let mut notices = Vec::new();
350 let baseline = if global.symlink_metadata().is_ok() {
355 let c = std::fs::read_to_string(&global)
356 .map_err(Error::from)
357 .and_then(|t| Self::parse(&t))
358 .map_err(|e| {
359 Error::Config(format!(
360 "the global config {} does not load ({e}); fix or remove it",
361 global.display()
362 ))
363 })?;
364 Some(c)
365 } else {
366 None
367 };
368 let (config, more) = Self::parse_project(&text, base.as_deref(), baseline.as_ref())?;
369 notices.extend(more);
370 (config, notices)
371 } else {
372 (Self::parse_at(&text, base.as_deref())?, Vec::new())
373 };
374 Ok(Loaded {
375 config,
376 path,
377 source,
378 notices,
379 })
380 }
381
382 pub fn parse_project(
386 text: &str,
387 base: Option<&Path>,
388 baseline: Option<&Config>,
389 ) -> Result<(Self, Vec<String>)> {
390 let mut cfg: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
391 let mut notices = Vec::new();
392 let requested = std::mem::take(&mut cfg.local.allowed_dirs);
393 for d in requested {
394 if d.is_absolute() || d.to_string_lossy().starts_with('~') {
395 notices.push(format!(
396 "local.allowed_dirs entry `{}` ignored: a project .farhand.toml may only \
397 allow folders inside its own directory (`\".\"`, `\"assets\"`); put other \
398 folders in the global config",
399 d.display()
400 ));
401 } else {
402 cfg.local.allowed_dirs.push(d);
403 }
404 }
405 if let Some(d) = cfg.audit.log_dir.take() {
406 notices.push(format!(
407 "audit.log_dir `{}` ignored: only the global config may move the audit log",
408 d.display()
409 ));
410 }
411 cfg.validate(base)?;
412 let project = base
418 .map(|b| {
419 if b.as_os_str().is_empty() {
420 Path::new(".")
421 } else {
422 b
423 }
424 })
425 .and_then(|b| b.canonicalize().ok());
426 for d in std::mem::take(&mut cfg.local.allowed_dirs) {
427 match (d.canonicalize(), &project) {
428 (Ok(c), Some(p)) if c.starts_with(p) && c.is_dir() => {
429 cfg.local.allowed_dirs.push(c)
430 }
431 (Ok(_), _) => notices.push(format!(
432 "local.allowed_dirs entry `{}` ignored: it is not a folder inside the \
433 project directory once symlinks are resolved",
434 d.display()
435 )),
436 (Err(e), _) => notices.push(format!(
437 "local.allowed_dirs entry `{}` ignored: {e}",
438 d.display()
439 )),
440 }
441 }
442 cfg.audit.log_dir = baseline.and_then(|b| b.audit.log_dir.clone());
443
444 let floor = baseline.map(|b| b.approval.clone()).unwrap_or_default();
445 let floor = floor.effective();
446 let mut loosened = Vec::new();
447 let mut tools = BTreeMap::new();
448 for (tool, mode) in cfg.approval.effective() {
449 let mode = if mode == ApprovalMode::Auto && floor[tool] == ApprovalMode::Ask {
450 loosened.push(tool);
451 ApprovalMode::Ask
452 } else {
453 mode
454 };
455 tools.insert(tool.to_string(), mode);
456 }
457 if !loosened.is_empty() {
458 notices.push(format!(
459 "[approval] `auto` ignored for {}: a project .farhand.toml may make approval \
460 stricter, not looser; set it in the global config",
461 loosened.join(", ")
462 ));
463 cfg.approval.tools = tools;
466 }
467
468 if let Some(b) = baseline {
470 for g in &b.guard.deny_globs {
471 if !cfg.guard.deny_globs.contains(g) {
472 cfg.guard.deny_globs.push(g.clone());
473 }
474 }
475 for r in &b.guard.deny_content {
476 if !cfg.guard.deny_content.contains(r) {
477 cfg.guard.deny_content.push(r.clone());
478 }
479 }
480 }
481 Ok((cfg, notices))
482 }
483
484 pub fn parse(text: &str) -> Result<Self> {
487 Self::parse_at(text, None)
488 }
489
490 pub fn parse_at(text: &str, base: Option<&Path>) -> Result<Self> {
493 let mut cfg: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
494 cfg.validate(base)?;
495 Ok(cfg)
496 }
497
498 fn locate(cwd: Option<&Path>) -> Result<(PathBuf, Source)> {
499 if let Some(p) = std::env::var_os("FARHAND_CONFIG") {
500 return Ok((PathBuf::from(p), Source::Env));
501 }
502 let local = match cwd {
503 Some(d) => d.join(".farhand.toml"),
504 None => PathBuf::from(".farhand.toml"),
505 };
506 if local.is_file() {
507 return Ok((local, Source::Project));
508 }
509 let p = Self::global_path();
510 if p.is_file() {
511 return Ok((p, Source::Global));
512 }
513 Err(Error::NoConfig)
514 }
515
516 pub fn global_path() -> PathBuf {
517 xdg_dir("XDG_CONFIG_HOME", ".config")
518 .join("farhand")
519 .join("config.toml")
520 }
521
522 fn validate(&mut self, base: Option<&Path>) -> Result<()> {
523 if self.remote.host.trim().is_empty() {
524 return Err(Error::Config("remote.host is empty".into()));
525 }
526 if self.remote.host.starts_with('-') {
527 return Err(Error::Config("remote.host may not start with '-'".into()));
528 }
529 let raw = self.remote.workdir.trim();
530 let w = raw.trim_end_matches(['/', '\\']);
531 let w = if w.is_empty() && raw.starts_with('/') {
532 "/".to_string()
533 } else if is_drive_root(raw) {
534 format!("{}\\", &raw[..2])
536 } else {
537 w.to_string()
538 };
539 let windows_abs = w.len() >= 3
540 && w.as_bytes()[0].is_ascii_alphabetic()
541 && w.as_bytes()[1] == b':'
542 && (w.as_bytes()[2] == b'\\' || w.as_bytes()[2] == b'/');
543 if !(w.starts_with('/')
544 || w == "~"
545 || w.starts_with("~/")
546 || w.starts_with("~\\")
547 || windows_abs)
548 {
549 return Err(Error::Config(
550 "remote.workdir must be an absolute path (`/srv/app`, `C:\\work`) or start with `~` \
551 (the remote home)"
552 .into(),
553 ));
554 }
555 self.remote.workdir = w;
556 if self.remote.shell.is_empty() {
557 return Err(Error::Config("remote.shell is empty".into()));
558 }
559 if self.limits.command_timeout_secs == 0 || self.limits.max_command_timeout_secs == 0 {
560 return Err(Error::Config("timeouts must be positive".into()));
561 }
562 let mut dirs = Vec::with_capacity(self.local.allowed_dirs.len());
563 let home = dirs::home_dir();
564 let home_canon = home.as_deref().and_then(|h| h.canonicalize().ok());
565 for d in &self.local.allowed_dirs {
566 let mut expanded = expand_home(d);
567 if expanded
570 .components()
571 .any(|c| matches!(c, std::path::Component::ParentDir))
572 {
573 return Err(Error::Config(format!(
574 "local.allowed_dirs entry `{}` may not contain `..`",
575 d.display()
576 )));
577 }
578 if !expanded.is_absolute() {
579 let Some(base) = base else {
582 return Err(Error::Config(format!(
583 "local.allowed_dirs entry `{}` is relative; only a project \
584 .farhand.toml may use relative entries (`\".\"` for its own folder)",
585 d.display()
586 )));
587 };
588 expanded = base.join(expanded);
589 }
590 let canon = expanded.canonicalize().ok();
594 let covers_home = |h: &Path| {
595 h.starts_with(&expanded) || canon.as_deref().is_some_and(|c| h.starts_with(c))
596 };
597 if expanded.parent().is_none()
598 || home.as_deref().is_some_and(covers_home)
599 || home_canon.as_deref().is_some_and(covers_home)
600 {
601 return Err(Error::Config(format!(
602 "local.allowed_dirs may not contain `/`, the home directory or a folder \
603 above it ({}); allow a specific folder instead",
604 d.display()
605 )));
606 }
607 dirs.push(expanded);
608 }
609 self.local.allowed_dirs = dirs;
610 if let Some(d) = &self.audit.log_dir {
611 self.audit.log_dir = Some(expand_home(d));
612 }
613 for (t, m) in &self.approval.tools {
614 if t == "remote_bash" {
615 return Err(Error::Config(
616 "approval.tools: `remote_bash` was renamed to `remote_shell` in 0.2.1".into(),
617 ));
618 }
619 if !MUTATING_TOOLS.contains(&t.as_str()) && !READ_ONLY_TOOLS.contains(&t.as_str()) {
620 return Err(Error::Config(format!(
621 "approval.tools: `{t}` is not a tool (one of {}, {})",
622 MUTATING_TOOLS.join(", "),
623 READ_ONLY_TOOLS.join(", ")
624 )));
625 }
626 if *m == ApprovalMode::Strict {
627 return Err(Error::Config(format!(
628 "approval.tools.{t}: use `ask` or `auto` (`strict` is a global mode)"
629 )));
630 }
631 }
632 Ok(())
633 }
634
635 pub fn audit_dir(&self) -> PathBuf {
636 self.audit.log_dir.clone().unwrap_or_else(|| {
637 xdg_dir("XDG_DATA_HOME", ".local/share")
638 .join("farhand")
639 .join("audit")
640 })
641 }
642}
643
644fn xdg_dir(var: &str, fallback: &str) -> PathBuf {
648 if let Some(v) = std::env::var_os(var) {
649 if !v.is_empty() {
650 return PathBuf::from(v);
651 }
652 }
653 dirs::home_dir()
654 .unwrap_or_else(|| PathBuf::from("."))
655 .join(fallback)
656}
657
658fn is_drive_root(s: &str) -> bool {
661 let b = s.as_bytes();
662 (b.len() == 2 || b.len() == 3)
663 && b[0].is_ascii_alphabetic()
664 && b[1] == b':'
665 && (b.len() == 2 || b[2] == b'\\' || b[2] == b'/')
666}
667
668pub fn expand_home(p: &Path) -> PathBuf {
669 let s = p.to_string_lossy();
670 if s == "~" {
671 return dirs::home_dir().unwrap_or_else(|| p.to_path_buf());
672 }
673 if let Some(rest) = s.strip_prefix("~/") {
674 if let Some(home) = dirs::home_dir() {
675 return home.join(rest);
676 }
677 }
678 p.to_path_buf()
679}
680
681const EXAMPLE: &str = r#"# FarHand configuration.
682# As .farhand.toml in a project root, it makes that project remote.
683# As ~/.config/farhand/config.toml it is optional: only needed for
684# activation = "always" (or as the target of --config / FARHAND_CONFIG).
685
686# "project" (default): only directories that carry a .farhand.toml are
687# remote; anywhere else the agent keeps its local tools and FarHand
688# stays out of the way.
689# "always": every agent session on this machine is remote, using the
690# [remote] section below.
691# Only meaningful in this global file; a project's .farhand.toml is always
692# active in its own directory.
693# activation = "project"
694
695[remote]
696# An alias from ~/.ssh/config or user@host. Keys, ports, jump hosts and
697# agent forwarding all come from your OpenSSH config.
698host = "devbox"
699# Directory on the remote where every command starts and relative paths
700# resolve. Absolute, or `~/...` for the remote user's home. Created on
701# first connection if it does not exist.
702workdir = "~/project"
703# os = "auto" # "posix" or "windows"; detected on connect, but set it so
704# # the model knows which shell it is writing for
705# shell = ["bash", "-lc"] # Windows: ["powershell"] (default) or ["pwsh"]
706# connect_timeout_secs = 20
707# server_alive_interval_secs = 30
708
709[local]
710# The only local directories the model may list, read from, upload from or
711# download into. Leave empty to close the local filesystem completely.
712# In a project .farhand.toml, "." means this folder: drop files here to
713# upload them, and downloads land here. A project file may only name this
714# folder or folders inside it; absolute and `~` entries belong in the
715# global config. Never allow your home directory or anything above it.
716allowed_dirs = ["."]
717
718[limits]
719# command_timeout_secs = 120
720# max_command_timeout_secs = 1800
721# max_output_bytes = 102400
722# max_read_bytes = 524288
723# max_transfer_bytes = 1073741824
724# max_transfer_files = 5000
725
726[audit]
727# Global config only; a project file cannot move the log.
728# log_dir = "~/.local/share/farhand/audit"
729
730[guard]
731# Extra globs that may never leave this machine (added to the built-in list).
732# deny_globs = ["*.internal"]
733# Extra regexes that mark content as secret.
734# deny_content = ["ACME-[0-9]{12}"]
735
736[approval]
737# "ask": the agent prompts you before remote_shell, remote_write,
738# remote_edit, upload and download; read-only tools run freely.
739# "auto": nothing prompts; the audit log is your record.
740# "strict": every tool prompts, reads and searches included.
741# A project .farhand.toml can make this stricter than the global config,
742# never looser: `auto` there only holds where the global config allows it.
743mode = "ask"
744# Per-tool overrides (`ask` or `auto`), any tool name:
745# tools = { remote_write = "auto", remote_edit = "auto", remote_read = "ask" }
746"#;
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751
752 #[test]
753 fn example_parses() {
754 let cfg = Config::parse_at(Config::example(), Some(Path::new("/proj"))).unwrap();
757 assert_eq!(cfg.remote.host, "devbox");
758 assert_eq!(cfg.remote.shell, vec!["bash", "-lc"]);
759 assert_eq!(cfg.local.allowed_dirs, vec![PathBuf::from("/proj")]);
760 assert!(Config::parse(Config::example()).is_err());
761 }
762
763 #[test]
764 fn rejects_home_and_root_as_allowed_dirs() {
765 for d in ["/", "~"] {
766 let err = Config::parse(&format!(
767 "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['{d}']"
768 ))
769 .unwrap_err();
770 assert!(err.to_string().contains("home directory"), "{d}: {err}");
771 }
772 assert!(
773 Config::parse("[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['~/out']")
774 .is_ok()
775 );
776 }
777
778 #[test]
779 fn relative_allowed_dirs_resolve_against_the_project_file() {
780 let text = "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['.', 'assets']";
781 let err = Config::parse(text).unwrap_err();
782 assert!(err.to_string().contains("relative"), "{err}");
783 let cfg = Config::parse_at(text, Some(Path::new("/proj"))).unwrap();
784 assert_eq!(
785 cfg.local.allowed_dirs,
786 vec![PathBuf::from("/proj"), PathBuf::from("/proj/assets")]
787 );
788 let err = Config::parse_at(
789 "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['../x']",
790 Some(Path::new("/proj")),
791 )
792 .unwrap_err();
793 assert!(err.to_string().contains(".."), "{err}");
794 }
795
796 #[test]
797 fn old_tool_name_points_at_the_new_one() {
798 let err = Config::parse(
799 "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ remote_bash='ask' }",
800 )
801 .unwrap_err();
802 assert!(
803 err.to_string().contains("renamed to `remote_shell`"),
804 "{err}"
805 );
806 }
807
808 #[test]
809 fn rejects_relative_workdir() {
810 let err = Config::parse("[remote]\nhost='h'\nworkdir='rel'").unwrap_err();
811 assert!(err.to_string().contains("absolute"));
812 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='~/'").unwrap();
813 assert_eq!(cfg.remote.workdir, "~");
814 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='/srv/app/'").unwrap();
815 assert_eq!(cfg.remote.workdir, "/srv/app");
816 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='C:\\work\\'").unwrap();
817 assert_eq!(cfg.remote.workdir, "C:\\work");
818 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='D:/'").unwrap();
819 assert_eq!(cfg.remote.workdir, "D:\\");
820 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='C:'").unwrap();
821 assert_eq!(cfg.remote.workdir, "C:\\");
822 assert!(Config::parse("[remote]\nhost='h'\nworkdir='work'").is_err());
823 let cfg = Config::parse("[remote]\nhost='h'\nworkdir='/'\nos='windows'").unwrap();
824 assert_eq!(cfg.remote.os, Os::Windows);
825 }
826
827 #[test]
828 fn approval_overrides_apply() {
829 let cfg = Config::parse(
830 "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'\ntools={ remote_shell='ask' }",
831 )
832 .unwrap();
833 let e = cfg.approval.effective();
834 assert_eq!(e["remote_shell"], ApprovalMode::Ask);
835 assert_eq!(e["remote_write"], ApprovalMode::Auto);
836 assert_eq!(e["remote_read"], ApprovalMode::Auto);
837 assert_eq!(e.len(), MUTATING_TOOLS.len() + READ_ONLY_TOOLS.len());
838
839 let strict = Config::parse(
840 "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='strict'\ntools={ remote_info='auto' }",
841 )
842 .unwrap();
843 let e = strict.approval.effective();
844 assert_eq!(e["remote_read"], ApprovalMode::Ask);
845 assert_eq!(e["remote_shell"], ApprovalMode::Ask);
846 assert_eq!(e["remote_info"], ApprovalMode::Auto);
847
848 let default = Config::parse("[remote]\nhost='h'\nworkdir='/'").unwrap();
849 assert_eq!(
850 default.approval.effective()["remote_read"],
851 ApprovalMode::Auto
852 );
853 assert!(Config::parse(
854 "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ nope='auto' }"
855 )
856 .is_err());
857 assert!(Config::parse(
858 "[remote]\nhost='h'\nworkdir='/'\n[approval]\ntools={ upload='strict' }"
859 )
860 .is_err());
861 }
862
863 #[test]
864 fn activation_depends_on_source() {
865 let mk = |activation: &str, source: Source| Loaded {
866 config: Config::parse(&format!(
867 "activation='{activation}'\n[remote]\nhost='h'\nworkdir='/'"
868 ))
869 .unwrap(),
870 path: PathBuf::new(),
871 source,
872 notices: Vec::new(),
873 };
874 assert!(mk("always", Source::Global).active());
875 assert!(!mk("project", Source::Global).active());
876 assert!(mk("project", Source::Project).active());
877 assert!(mk("project", Source::Explicit).active());
878 assert_eq!(
879 Config::parse("[remote]\nhost='h'\nworkdir='/'")
880 .unwrap()
881 .activation,
882 ActivationMode::Project
883 );
884 }
885
886 #[test]
887 fn allowed_dirs_refuse_home_ancestors_and_dotdot() {
888 let home = dirs::home_dir().unwrap();
889 let parent = home.parent().unwrap().display().to_string();
890 for d in [parent.as_str(), "~/..", "~/../x", "/tmp/../etc"] {
891 let err = Config::parse(&format!(
892 "[remote]\nhost='h'\nworkdir='/w'\n[local]\nallowed_dirs=['{d}']"
893 ))
894 .unwrap_err();
895 assert!(err.to_string().contains("allowed_dirs"), "{d}: {err}");
896 }
897 }
898
899 fn project(text: &str, baseline: Option<&str>) -> (Config, Vec<String>, tempfile::TempDir) {
901 let d = tempfile::tempdir().unwrap();
902 let baseline = baseline.map(|b| Config::parse(b).unwrap());
903 let (cfg, notes) = Config::parse_project(text, Some(d.path()), baseline.as_ref()).unwrap();
904 (cfg, notes, d)
905 }
906
907 #[test]
908 fn project_file_cannot_loosen_approval() {
909 let (cfg, notes, _d) = project(
910 "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'",
911 None,
912 );
913 let e = cfg.approval.effective();
914 assert_eq!(e["remote_shell"], ApprovalMode::Ask);
915 assert_eq!(e["upload"], ApprovalMode::Ask);
916 assert_eq!(e["remote_read"], ApprovalMode::Auto);
917 assert_eq!(notes.len(), 1);
918 assert!(notes[0].contains("remote_shell"), "{notes:?}");
919
920 let global = "[remote]\nhost='g'\nworkdir='/'\n[approval]\nmode='auto'";
922 let (cfg, notes, _d) = project(
923 "[remote]\nhost='h'\nworkdir='/'\n[approval]\nmode='auto'\ntools={ upload='ask' }",
924 Some(global),
925 );
926 assert!(notes.is_empty(), "{notes:?}");
927 assert_eq!(cfg.approval.effective()["remote_shell"], ApprovalMode::Auto);
928 assert_eq!(cfg.approval.effective()["upload"], ApprovalMode::Ask);
929
930 let strict = "[remote]\nhost='g'\nworkdir='/'\n[approval]\nmode='strict'";
932 let (cfg, notes, _d) = project("[remote]\nhost='h'\nworkdir='/'", Some(strict));
933 assert_eq!(cfg.approval.effective()["remote_read"], ApprovalMode::Ask);
934 assert!(notes[0].contains("remote_read"), "{notes:?}");
935 }
936
937 #[test]
938 fn project_file_keeps_to_its_own_folder_and_the_global_log() {
939 let (cfg, notes, d) = project(
940 "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['.', '/Users', '~/x']\n\
941 [audit]\nlog_dir='/dev'",
942 Some("[remote]\nhost='g'\nworkdir='/'\n[audit]\nlog_dir='/var/log/fh'\n[guard]\ndeny_globs=['*.corp']"),
943 );
944 assert_eq!(
945 cfg.local.allowed_dirs,
946 vec![d.path().canonicalize().unwrap()]
947 );
948 assert_eq!(cfg.audit.log_dir, Some(PathBuf::from("/var/log/fh")));
949 assert_eq!(cfg.guard.deny_globs, vec!["*.corp".to_string()]);
950 assert_eq!(notes.len(), 3, "{notes:?}");
951 let err = Config::parse_project(
952 "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['../x']",
953 Some(Path::new("/proj")),
954 None,
955 )
956 .unwrap_err();
957 assert!(err.to_string().contains(".."), "{err}");
958 }
959
960 #[cfg(unix)]
961 #[test]
962 fn project_folders_may_not_leave_the_project_through_a_symlink() {
963 let d = tempfile::tempdir().unwrap();
964 let proj = d.path().join("proj");
965 let outside = d.path().join("outside");
966 std::fs::create_dir_all(proj.join("real/sub")).unwrap();
967 std::fs::create_dir_all(&outside).unwrap();
968 std::os::unix::fs::symlink(&outside, proj.join("assets")).unwrap();
969 std::os::unix::fs::symlink(proj.join("real/sub"), proj.join("inner")).unwrap();
970 let (cfg, notes) = Config::parse_project(
971 "[remote]\nhost='h'\nworkdir='/'\n[local]\nallowed_dirs=['assets', 'inner', 'missing', 'real']",
972 Some(&proj),
973 None,
974 )
975 .unwrap();
976 let real = proj.join("real").canonicalize().unwrap();
977 assert_eq!(cfg.local.allowed_dirs, vec![real.join("sub"), real]);
978 assert_eq!(notes.len(), 2, "{notes:?}");
979 assert!(notes[0].contains("/assets`"), "{notes:?}");
980 assert!(notes[1].contains("/missing`"), "{notes:?}");
981 }
982
983 #[test]
984 fn a_farhand_toml_passed_by_path_is_still_a_project_file() {
985 let d = tempfile::tempdir().unwrap();
986 let p = d.path().join(".farhand.toml");
987 std::fs::write(
988 &p,
989 "[remote]\nhost='h'\nworkdir='/'\n[audit]\nlog_dir='/dev'",
990 )
991 .unwrap();
992 let l = Config::load_in(None, Some(&p)).unwrap();
993 assert_eq!(l.source, Source::Project);
994 assert!(
995 l.notices.iter().any(|n| n.contains("log_dir")),
996 "{:?}",
997 l.notices
998 );
999 let other = d.path().join("fh.toml");
1000 std::fs::copy(&p, &other).unwrap();
1001 let l = Config::load_in(None, Some(&other)).unwrap();
1002 assert_eq!(l.source, Source::Explicit);
1003 assert_eq!(l.config.audit.log_dir, Some(PathBuf::from("/dev")));
1004 }
1005
1006 #[test]
1007 fn rejects_unknown_fields() {
1008 assert!(Config::parse("[remote]\nhost='h'\nworkdir='/'\nbogus=1").is_err());
1009 }
1010}