1use std::path::{Path, PathBuf};
23
24use anyhow::{anyhow, Result};
25
26pub const CONFIG_DIR_ENV: &str = "ATLASSIAN_CLI_CONFIG_DIR";
27pub const XDG_CONFIG_HOME_ENV: &str = "XDG_CONFIG_HOME";
28
29pub const APP_DIR: &str = "atlassian-cli";
32
33pub const LEGACY_DIRS: [&str; 2] = [".atlassian-cli", ".atlcli"];
35
36pub const CONFIG_FILENAME: &str = "config.yaml";
37pub const CREDENTIALS_FILENAME: &str = "credentials";
38pub const ENCRYPTED_FILENAME: &str = "credentials.enc";
39
40pub const OWNED_FILES: [&str; 3] = [CONFIG_FILENAME, CREDENTIALS_FILENAME, ENCRYPTED_FILENAME];
42
43pub const ARCHIVE_SUFFIX: &str = ".migrated";
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum ConfigDirSource {
49 Explicit,
52 Xdg,
54 Default,
56 Legacy,
58}
59
60#[derive(Debug, Clone, Default)]
66pub struct PathEnv {
67 pub explicit_dir: Option<String>,
68 pub xdg_config_home: Option<String>,
69 pub home: Option<PathBuf>,
70 pub native_config: Option<PathBuf>,
73}
74
75impl PathEnv {
76 pub fn from_process() -> Self {
77 Self {
78 explicit_dir: std::env::var(CONFIG_DIR_ENV).ok(),
79 xdg_config_home: std::env::var(XDG_CONFIG_HOME_ENV).ok(),
80 home: dirs::home_dir(),
81 native_config: dirs::config_local_dir(),
82 }
83 }
84}
85
86#[derive(Debug, Clone)]
88pub struct ConfigPaths {
89 dir: PathBuf,
90 preferred: PathBuf,
93 source: ConfigDirSource,
94 config_file_override: Option<PathBuf>,
96}
97
98fn non_empty(value: Option<&String>) -> Option<&str> {
99 value.map(|v| v.trim()).filter(|v| !v.is_empty())
100}
101
102fn default_base(env: &PathEnv) -> Option<PathBuf> {
104 if cfg!(windows) {
105 env.native_config.clone()
109 } else {
110 env.home.as_ref().map(|h| h.join(".config"))
111 }
112}
113
114impl ConfigPaths {
115 pub fn resolve() -> Result<Self> {
117 Self::resolve_with(&PathEnv::from_process(), &is_populated)
118 }
119
120 pub fn resolve_from(explicit: Option<PathBuf>) -> Result<Self> {
122 let mut env = PathEnv::from_process();
123 if let Some(dir) = explicit {
124 env.explicit_dir = Some(dir.to_string_lossy().into_owned());
125 }
126 Self::resolve_with(&env, &is_populated)
127 }
128
129 pub fn resolve_with(env: &PathEnv, populated: &dyn Fn(&Path) -> bool) -> Result<Self> {
132 if let Some(explicit) = non_empty(env.explicit_dir.as_ref()) {
137 let dir = expand_home(Path::new(explicit), env.home.as_deref());
138 return Ok(Self::at(dir, ConfigDirSource::Explicit));
139 }
140
141 let (base, source) = match non_empty(env.xdg_config_home.as_ref())
147 .map(Path::new)
148 .filter(|p| p.is_absolute())
149 {
150 Some(xdg) => (xdg.to_path_buf(), ConfigDirSource::Xdg),
151 None => match default_base(env) {
152 Some(base) => (base, ConfigDirSource::Default),
153 None => {
154 return Err(anyhow!(
155 "Cannot determine your home directory. \
156 Set {CONFIG_DIR_ENV} or pass --config-dir to choose where \
157 atlassian-cli should keep its files."
158 ))
159 }
160 },
161 };
162 let preferred = base.join(APP_DIR);
163
164 if populated(&preferred) {
166 return Ok(Self::at(preferred, source));
167 }
168
169 if let Some(home) = env.home.as_deref() {
174 for legacy in LEGACY_DIRS {
175 let candidate = home.join(legacy);
176 if populated(&candidate) {
177 return Ok(Self {
178 dir: candidate,
179 preferred,
180 source: ConfigDirSource::Legacy,
181 config_file_override: None,
182 });
183 }
184 }
185 }
186
187 Ok(Self::at(preferred, source))
189 }
190
191 fn at(dir: PathBuf, source: ConfigDirSource) -> Self {
192 Self {
193 preferred: dir.clone(),
194 dir,
195 source,
196 config_file_override: None,
197 }
198 }
199
200 pub fn for_dir(dir: impl Into<PathBuf>) -> Self {
202 Self::at(dir.into(), ConfigDirSource::Explicit)
203 }
204
205 #[doc(hidden)]
207 pub fn for_legacy(dir: impl Into<PathBuf>, preferred: impl Into<PathBuf>) -> Self {
208 Self {
209 dir: dir.into(),
210 preferred: preferred.into(),
211 source: ConfigDirSource::Legacy,
212 config_file_override: None,
213 }
214 }
215
216 pub fn with_config_file_override(mut self, file: Option<PathBuf>) -> Self {
219 self.config_file_override = file;
220 self
221 }
222
223 pub fn dir(&self) -> &Path {
224 &self.dir
225 }
226
227 pub fn preferred(&self) -> &Path {
228 &self.preferred
229 }
230
231 pub fn source(&self) -> ConfigDirSource {
232 self.source
233 }
234
235 pub fn config_file(&self) -> PathBuf {
236 self.config_file_override
237 .clone()
238 .unwrap_or_else(|| self.dir.join(CONFIG_FILENAME))
239 }
240
241 pub fn credentials_file(&self) -> PathBuf {
242 self.dir.join(CREDENTIALS_FILENAME)
243 }
244
245 pub fn encrypted_file(&self) -> PathBuf {
246 self.dir.join(ENCRYPTED_FILENAME)
247 }
248}
249
250pub fn is_populated(dir: &Path) -> bool {
252 OWNED_FILES.iter().any(|name| dir.join(name).exists())
253}
254
255fn expand_home(path: &Path, home: Option<&Path>) -> PathBuf {
257 let (Some(home), Some(text)) = (home, path.to_str()) else {
258 return path.to_path_buf();
259 };
260 match text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {
261 Some(rest) => home.join(rest),
262 None if text == "~" => home.to_path_buf(),
263 None => path.to_path_buf(),
264 }
265}
266
267#[derive(Debug)]
269pub enum DirMigration {
270 NotNeeded,
271 Migrated {
272 from: PathBuf,
273 to: PathBuf,
274 files: Vec<&'static str>,
275 archived: Option<PathBuf>,
278 scrubbed_plaintext: bool,
282 },
283 Failed {
285 from: PathBuf,
286 to: PathBuf,
287 error: String,
288 },
289}
290
291pub fn migrate_legacy_dir(paths: ConfigPaths) -> (ConfigPaths, DirMigration) {
306 if paths.source() != ConfigDirSource::Legacy {
307 return (paths, DirMigration::NotNeeded);
308 }
309
310 let from = paths.dir().to_path_buf();
311 let to = paths.preferred().to_path_buf();
312
313 if let (Ok(a), Ok(b)) = (from.canonicalize(), to.canonicalize()) {
316 if a == b {
317 return (paths, DirMigration::NotNeeded);
318 }
319 }
320
321 if is_populated(&to) {
323 return (paths, DirMigration::NotNeeded);
324 }
325
326 match stage_and_promote(&from, &to) {
327 Ok(files) => {
328 let archived = archive_legacy_dir(&from);
329 let scrubbed_plaintext = files.contains(&CREDENTIALS_FILENAME)
336 && scrub_file(
337 &archived
338 .clone()
339 .unwrap_or_else(|| from.clone())
340 .join(CREDENTIALS_FILENAME),
341 );
342 let migrated = ConfigPaths {
343 dir: to.clone(),
344 preferred: to.clone(),
345 source: ConfigDirSource::Default,
346 config_file_override: paths.config_file_override.clone(),
347 };
348 (
349 migrated,
350 DirMigration::Migrated {
351 from,
352 to,
353 files,
354 archived,
355 scrubbed_plaintext,
356 },
357 )
358 }
359 Err(error) => (
360 paths,
361 DirMigration::Failed {
362 from,
363 to,
364 error: error.to_string(),
365 },
366 ),
367 }
368}
369
370fn stage_and_promote(from: &Path, to: &Path) -> Result<Vec<&'static str>> {
371 let parent = to
372 .parent()
373 .ok_or_else(|| anyhow!("{} has no parent directory", to.display()))?;
374 std::fs::create_dir_all(parent)
375 .map_err(|e| anyhow!("Unable to create {}: {}", parent.display(), e))?;
376
377 let staging = parent.join(format!("{APP_DIR}.migrating.{}", std::process::id()));
378 let _ = std::fs::remove_dir_all(&staging);
379 create_private_dir(&staging)?;
380
381 let mut copied = Vec::new();
382 for name in OWNED_FILES {
383 let src = from.join(name);
384 if !src.exists() {
385 continue;
386 }
387 let result = std::fs::read(&src)
388 .map_err(|e| anyhow!("Unable to read {}: {}", src.display(), e))
389 .and_then(|bytes| write_private(&staging.join(name), &bytes));
390 if let Err(e) = result {
391 let _ = std::fs::remove_dir_all(&staging);
392 return Err(e);
393 }
394 copied.push(name);
395 }
396
397 if let Err(e) = std::fs::rename(&staging, to) {
400 if is_populated(to) {
401 let _ = std::fs::remove_dir_all(&staging);
402 return Ok(copied);
403 }
404 let result = promote_each_file(&staging, to, &copied);
412 let _ = std::fs::remove_dir_all(&staging);
413 return match result {
414 Ok(()) => Ok(copied),
415 Err(fallback) => Err(anyhow!(
416 "Unable to move {} into place: {} (and moving the files \
417 individually failed: {})",
418 to.display(),
419 e,
420 fallback
421 )),
422 };
423 }
424
425 Ok(copied)
426}
427
428fn promote_each_file(staging: &Path, to: &Path, files: &[&'static str]) -> Result<()> {
436 create_private_dir(to)?;
437
438 let mut moved: Vec<&'static str> = Vec::new();
439 for name in files {
440 match std::fs::rename(staging.join(name), to.join(name)) {
441 Ok(()) => moved.push(name),
442 Err(e) => {
443 for done in &moved {
444 let _ = std::fs::rename(to.join(done), staging.join(done));
445 }
446 return Err(anyhow!(
447 "Unable to write {}: {}",
448 to.join(name).display(),
449 e
450 ));
451 }
452 }
453 }
454
455 Ok(())
456}
457
458fn scrub_file(path: &Path) -> bool {
471 let Ok(metadata) = std::fs::symlink_metadata(path) else {
472 return false;
473 };
474
475 if metadata.is_symlink() {
476 let _ = std::fs::remove_file(path);
477 return false;
478 }
479 if !metadata.is_file() {
480 return false;
481 }
482
483 let _ = std::fs::write(path, vec![0u8; metadata.len() as usize]);
484 std::fs::remove_file(path).is_ok()
485}
486
487fn archive_legacy_dir(from: &Path) -> Option<PathBuf> {
489 let name = from.file_name()?.to_str()?;
490 for attempt in 0..10 {
491 let suffix = if attempt == 0 {
492 ARCHIVE_SUFFIX.to_string()
493 } else {
494 format!("{ARCHIVE_SUFFIX}.{attempt}")
495 };
496 let candidate = from.with_file_name(format!("{name}{suffix}"));
497 if candidate.exists() {
498 continue;
499 }
500 if std::fs::rename(from, &candidate).is_ok() {
501 return Some(candidate);
502 }
503 return None;
504 }
505 None
506}
507
508pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
512 use std::io::Write;
513
514 let dir = path.parent().unwrap_or_else(|| Path::new("."));
515 let tmp = dir.join(format!(
516 ".{}.tmp{}",
517 path.file_name().and_then(|n| n.to_str()).unwrap_or("file"),
518 std::process::id()
519 ));
520
521 {
522 let mut options = std::fs::OpenOptions::new();
527 options.write(true).create_new(true);
528 #[cfg(unix)]
529 {
530 use std::os::unix::fs::OpenOptionsExt;
531 options.mode(0o600);
532 }
533
534 let mut file = match options.open(&tmp) {
535 Ok(file) => file,
536 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
537 let stale = std::fs::symlink_metadata(&tmp)
538 .map(|m| m.is_file())
539 .unwrap_or(false);
540 if !stale {
541 return Err(anyhow!(
542 "Refusing to write {}: it exists and is not a regular file",
543 tmp.display()
544 ));
545 }
546 std::fs::remove_file(&tmp)
547 .map_err(|e| anyhow!("Unable to clear stale {}: {}", tmp.display(), e))?;
548 options
549 .open(&tmp)
550 .map_err(|e| anyhow!("Unable to write {}: {}", tmp.display(), e))?
551 }
552 Err(e) => return Err(anyhow!("Unable to write {}: {}", tmp.display(), e)),
553 };
554 file.write_all(bytes)
555 .map_err(|e| anyhow!("Unable to write {}: {}", tmp.display(), e))?;
556 file.sync_all().ok();
557 }
558
559 std::fs::rename(&tmp, path).map_err(|e| {
560 let _ = std::fs::remove_file(&tmp);
561 anyhow!("Unable to write {}: {}", path.display(), e)
562 })?;
563
564 Ok(())
565}
566
567pub fn create_private_dir(dir: &Path) -> Result<()> {
569 if dir.is_dir() {
573 return Ok(());
574 }
575
576 std::fs::create_dir_all(dir)
577 .map_err(|e| anyhow!("Unable to create directory {}: {}", dir.display(), e))?;
578
579 #[cfg(unix)]
580 {
581 use std::os::unix::fs::PermissionsExt;
582 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
583 .map_err(|e| anyhow!("Unable to restrict {}: {}", dir.display(), e))?;
584 }
585
586 Ok(())
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592 use std::collections::HashSet;
593
594 fn resolve(env: PathEnv, populated: &[&str]) -> Result<ConfigPaths> {
597 let set: HashSet<PathBuf> = populated.iter().map(PathBuf::from).collect();
598 ConfigPaths::resolve_with(&env, &move |p: &Path| set.contains(p))
599 }
600
601 fn env() -> PathEnv {
602 PathEnv {
603 home: Some(PathBuf::from("/home/u")),
604 ..Default::default()
605 }
606 }
607
608 #[test]
609 fn explicit_wins_over_everything() {
610 let paths = resolve(
611 PathEnv {
612 explicit_dir: Some("/explicit".into()),
613 xdg_config_home: Some("/xdg".into()),
614 ..env()
615 },
616 &["/xdg/atlassian-cli", "/home/u/.atlassian-cli"],
617 )
618 .unwrap();
619
620 assert_eq!(paths.dir(), Path::new("/explicit"));
621 assert_eq!(paths.source(), ConfigDirSource::Explicit);
622 }
623
624 #[test]
625 fn blank_explicit_is_treated_as_unset() {
626 for blank in ["", " "] {
627 let paths = resolve(
628 PathEnv {
629 explicit_dir: Some(blank.into()),
630 ..env()
631 },
632 &[],
633 )
634 .unwrap();
635 assert_eq!(paths.dir(), Path::new("/home/u/.config/atlassian-cli"));
636 }
637 }
638
639 #[test]
642 fn relative_explicit_is_honoured() {
643 let paths = resolve(
644 PathEnv {
645 explicit_dir: Some("ci-config".into()),
646 ..env()
647 },
648 &[],
649 )
650 .unwrap();
651 assert_eq!(paths.dir(), Path::new("ci-config"));
652 }
653
654 #[test]
655 fn explicit_expands_a_leading_tilde() {
656 let paths = resolve(
657 PathEnv {
658 explicit_dir: Some("~/elsewhere".into()),
659 ..env()
660 },
661 &[],
662 )
663 .unwrap();
664 assert_eq!(paths.dir(), Path::new("/home/u/elsewhere"));
665 }
666
667 #[test]
668 fn xdg_config_home_is_used_when_absolute() {
669 let paths = resolve(
670 PathEnv {
671 xdg_config_home: Some("/xdg".into()),
672 ..env()
673 },
674 &[],
675 )
676 .unwrap();
677 assert_eq!(paths.dir(), Path::new("/xdg/atlassian-cli"));
678 assert_eq!(paths.source(), ConfigDirSource::Xdg);
679 }
680
681 #[test]
684 fn relative_xdg_config_home_is_ignored() {
685 for value in ["relative/path", ""] {
686 let paths = resolve(
687 PathEnv {
688 xdg_config_home: Some(value.into()),
689 ..env()
690 },
691 &[],
692 )
693 .unwrap();
694 assert_eq!(paths.dir(), Path::new("/home/u/.config/atlassian-cli"));
695 assert_eq!(paths.source(), ConfigDirSource::Default);
696 }
697 }
698
699 #[test]
700 fn a_populated_legacy_directory_is_used() {
701 let paths = resolve(env(), &["/home/u/.atlassian-cli"]).unwrap();
702 assert_eq!(paths.dir(), Path::new("/home/u/.atlassian-cli"));
703 assert_eq!(paths.source(), ConfigDirSource::Legacy);
704 assert_eq!(
705 paths.preferred(),
706 Path::new("/home/u/.config/atlassian-cli"),
707 "the migration target should be the preferred location"
708 );
709 }
710
711 #[test]
713 fn an_empty_legacy_directory_is_ignored() {
714 let paths = resolve(env(), &[]).unwrap();
715 assert_eq!(paths.dir(), Path::new("/home/u/.config/atlassian-cli"));
716 assert_eq!(paths.source(), ConfigDirSource::Default);
717 }
718
719 #[test]
720 fn the_older_atlcli_directory_is_still_found() {
721 let paths = resolve(env(), &["/home/u/.atlcli"]).unwrap();
722 assert_eq!(paths.dir(), Path::new("/home/u/.atlcli"));
723 assert_eq!(paths.source(), ConfigDirSource::Legacy);
724 }
725
726 #[test]
727 fn the_newer_legacy_directory_wins_when_both_exist() {
728 let paths = resolve(env(), &["/home/u/.atlassian-cli", "/home/u/.atlcli"]).unwrap();
729 assert_eq!(paths.dir(), Path::new("/home/u/.atlassian-cli"));
730 }
731
732 #[test]
735 fn a_populated_preferred_directory_beats_legacy() {
736 let paths = resolve(
737 env(),
738 &["/home/u/.config/atlassian-cli", "/home/u/.atlassian-cli"],
739 )
740 .unwrap();
741 assert_eq!(paths.dir(), Path::new("/home/u/.config/atlassian-cli"));
742 assert_eq!(paths.source(), ConfigDirSource::Default);
743 }
744
745 #[test]
746 fn a_fresh_install_lands_in_the_preferred_directory() {
747 let paths = resolve(env(), &[]).unwrap();
748 assert_eq!(paths.dir(), Path::new("/home/u/.config/atlassian-cli"));
749 }
750
751 #[test]
754 fn no_home_and_no_override_is_an_error_naming_the_variable() {
755 let err = resolve(PathEnv::default(), &[]).unwrap_err().to_string();
756 assert!(err.contains(CONFIG_DIR_ENV), "got: {err}");
757 }
758
759 #[test]
760 fn no_home_is_fine_when_an_explicit_directory_is_given() {
761 let paths = resolve(
762 PathEnv {
763 explicit_dir: Some("/explicit".into()),
764 ..Default::default()
765 },
766 &[],
767 )
768 .unwrap();
769 assert_eq!(paths.dir(), Path::new("/explicit"));
770 }
771
772 #[test]
774 fn the_config_file_override_does_not_move_the_credentials() {
775 let paths = resolve(
776 PathEnv {
777 explicit_dir: Some("/dir".into()),
778 ..env()
779 },
780 &[],
781 )
782 .unwrap()
783 .with_config_file_override(Some(PathBuf::from("/elsewhere/custom.yaml")));
784
785 assert_eq!(paths.config_file(), Path::new("/elsewhere/custom.yaml"));
786 assert_eq!(paths.credentials_file(), Path::new("/dir/credentials"));
787 assert_eq!(paths.encrypted_file(), Path::new("/dir/credentials.enc"));
788 }
789
790 #[test]
791 fn file_names_hang_off_the_resolved_directory() {
792 let paths = ConfigPaths::for_dir("/dir");
793 assert_eq!(paths.config_file(), Path::new("/dir/config.yaml"));
794 assert_eq!(paths.credentials_file(), Path::new("/dir/credentials"));
795 assert_eq!(paths.encrypted_file(), Path::new("/dir/credentials.enc"));
796 }
797
798 use tempfile::TempDir;
803
804 fn seed(dir: &Path, files: &[(&str, &str)]) {
805 std::fs::create_dir_all(dir).unwrap();
806 for (name, body) in files {
807 std::fs::write(dir.join(name), body).unwrap();
808 }
809 }
810
811 #[test]
812 fn migration_copies_files_and_archives_the_original() {
813 let home = TempDir::new().unwrap();
814 let from = home.path().join(".atlassian-cli");
815 let to = home.path().join(".config").join(APP_DIR);
816 seed(
817 &from,
818 &[("config.yaml", "profiles: {}"), ("credentials.enc", "{}")],
819 );
820
821 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
822
823 match outcome {
824 DirMigration::Migrated {
825 files, archived, ..
826 } => {
827 assert_eq!(files, vec!["config.yaml", "credentials.enc"]);
828 let archived = archived.expect("the original should have been renamed");
829 assert!(archived.exists());
830 assert_eq!(archived.file_name().unwrap(), ".atlassian-cli.migrated");
831 }
832 other => panic!("expected a migration, got {other:?}"),
833 }
834
835 assert_eq!(
836 paths.dir(),
837 to,
838 "the caller should be pointed at the new location"
839 );
840 assert_eq!(
841 std::fs::read_to_string(to.join("config.yaml")).unwrap(),
842 "profiles: {}"
843 );
844 assert!(!from.exists(), "the original path should no longer resolve");
845 }
846
847 #[test]
854 fn migration_does_not_strand_a_plaintext_token_in_the_archive() {
855 let home = TempDir::new().unwrap();
856 let from = home.path().join(".atlassian-cli");
857 let to = home.path().join(".config").join(APP_DIR);
858 seed(
859 &from,
860 &[("config.yaml", "profiles: {}"), ("credentials", "w=secret")],
861 );
862
863 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
864
865 let (archived, scrubbed) = match outcome {
866 DirMigration::Migrated {
867 archived,
868 scrubbed_plaintext,
869 ..
870 } => (
871 archived.expect("the original should be renamed"),
872 scrubbed_plaintext,
873 ),
874 other => panic!("expected a migration, got {other:?}"),
875 };
876
877 assert!(scrubbed, "the user must be told the copy was removed");
878 assert!(
879 !archived.join("credentials").exists(),
880 "the archived plaintext token should be gone"
881 );
882 assert!(
883 archived.join("config.yaml").exists(),
884 "only the secret is removed; the rest of the archive stays"
885 );
886 assert_eq!(
887 std::fs::read_to_string(to.join("credentials")).unwrap(),
888 "w=secret",
889 "the surviving copy must be the one at the new location"
890 );
891 }
892
893 #[cfg(unix)]
900 #[test]
901 fn migration_does_not_scrub_through_a_symlinked_credentials_file() {
902 let home = TempDir::new().unwrap();
903 let from = home.path().join(".atlassian-cli");
904 let to = home.path().join(".config").join(APP_DIR);
905 let real = home.path().join("dotfiles").join("credentials");
906 seed(&from, &[("config.yaml", "profiles: {}")]);
907 std::fs::create_dir_all(real.parent().unwrap()).unwrap();
908 std::fs::write(&real, "w=secret").unwrap();
909 std::os::unix::fs::symlink(&real, from.join("credentials")).unwrap();
910
911 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
912
913 let (archived, scrubbed) = match outcome {
914 DirMigration::Migrated {
915 archived,
916 scrubbed_plaintext,
917 ..
918 } => (
919 archived.expect("the original should be renamed"),
920 scrubbed_plaintext,
921 ),
922 other => panic!("expected a migration, got {other:?}"),
923 };
924
925 assert_eq!(
926 std::fs::read_to_string(&real).unwrap(),
927 "w=secret",
928 "the user's own file must not be zeroed"
929 );
930 assert!(
931 !scrubbed,
932 "nothing was destroyed, so the notice must not say so"
933 );
934 assert!(
935 !archived.join("credentials").exists(),
936 "the dangling link should not be left in the archive"
937 );
938 assert_eq!(
939 std::fs::read_to_string(to.join("credentials")).unwrap(),
940 "w=secret",
941 "the copy is taken through the link, as before"
942 );
943 }
944
945 #[test]
948 fn migration_reports_no_scrub_when_there_was_no_plaintext_file() {
949 let home = TempDir::new().unwrap();
950 let from = home.path().join(".atlassian-cli");
951 let to = home.path().join(".config").join(APP_DIR);
952 seed(&from, &[("credentials.enc", "{}")]);
953
954 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
955
956 match outcome {
957 DirMigration::Migrated {
958 scrubbed_plaintext, ..
959 } => assert!(!scrubbed_plaintext),
960 other => panic!("expected a migration, got {other:?}"),
961 }
962 }
963
964 #[test]
971 fn migration_into_a_non_empty_but_unowned_target() {
972 let home = TempDir::new().unwrap();
973 let from = home.path().join(".atlassian-cli");
974 let to = home.path().join(".config").join(APP_DIR);
975 seed(
976 &from,
977 &[("config.yaml", "profiles: {}"), ("credentials.enc", "{}")],
978 );
979 seed(&to, &[(".DS_Store", "junk")]);
980
981 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
982
983 assert!(
984 matches!(outcome, DirMigration::Migrated { .. }),
985 "expected a migration, got {outcome:?}"
986 );
987 assert_eq!(paths.dir(), to);
988 assert_eq!(
989 std::fs::read_to_string(to.join("config.yaml")).unwrap(),
990 "profiles: {}"
991 );
992 assert!(to.join("credentials.enc").exists());
993 assert!(
994 to.join(".DS_Store").exists(),
995 "the unrelated file must survive"
996 );
997 assert!(!from.exists());
998 assert!(
999 std::fs::read_dir(to.parent().unwrap())
1000 .unwrap()
1001 .filter_map(|e| e.ok())
1002 .all(|e| !e.file_name().to_string_lossy().contains(".migrating.")),
1003 "the staging directory must not be left behind"
1004 );
1005 }
1006
1007 #[cfg(unix)]
1010 #[test]
1011 fn migration_into_a_symlinked_target_keeps_the_symlink() {
1012 let home = TempDir::new().unwrap();
1013 let from = home.path().join(".atlassian-cli");
1014 let real = home.path().join("dotfiles").join("atlassian-cli");
1015 let to = home.path().join(".config").join(APP_DIR);
1016 seed(&from, &[("config.yaml", "profiles: {}")]);
1017 std::fs::create_dir_all(&real).unwrap();
1018 std::fs::create_dir_all(to.parent().unwrap()).unwrap();
1019 std::os::unix::fs::symlink(&real, &to).unwrap();
1020
1021 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1022
1023 assert!(
1024 matches!(outcome, DirMigration::Migrated { .. }),
1025 "expected a migration, got {outcome:?}"
1026 );
1027 assert_eq!(paths.dir(), to);
1028 assert!(
1029 std::fs::symlink_metadata(&to).unwrap().is_symlink(),
1030 "the symlink must not be replaced by a real directory"
1031 );
1032 assert_eq!(
1033 std::fs::read_to_string(real.join("config.yaml")).unwrap(),
1034 "profiles: {}",
1035 "the file should land in the directory the symlink points at"
1036 );
1037 }
1038
1039 #[test]
1041 fn migration_copies_only_the_files_that_exist() {
1042 let home = TempDir::new().unwrap();
1043 let from = home.path().join(".atlcli");
1044 let to = home.path().join(".config").join(APP_DIR);
1045 seed(&from, &[("config.yaml", "x")]);
1046
1047 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1048
1049 match outcome {
1050 DirMigration::Migrated { files, .. } => assert_eq!(files, vec!["config.yaml"]),
1051 other => panic!("expected a migration, got {other:?}"),
1052 }
1053 assert!(!to.join("credentials.enc").exists());
1054 }
1055
1056 #[test]
1057 fn migration_is_idempotent() {
1058 let home = TempDir::new().unwrap();
1059 let from = home.path().join(".atlassian-cli");
1060 let to = home.path().join(".config").join(APP_DIR);
1061 seed(&from, &[("config.yaml", "x")]);
1062
1063 migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1064
1065 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1068 assert!(matches!(outcome, DirMigration::NotNeeded));
1069 assert!(!home.path().join(".atlassian-cli.migrated.1").exists());
1070 }
1071
1072 #[test]
1074 fn migration_refuses_a_populated_target() {
1075 let home = TempDir::new().unwrap();
1076 let from = home.path().join(".atlassian-cli");
1077 let to = home.path().join(".config").join(APP_DIR);
1078 seed(&from, &[("config.yaml", "old")]);
1079 seed(&to, &[("config.yaml", "new")]);
1080
1081 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1082
1083 assert!(matches!(outcome, DirMigration::NotNeeded));
1084 assert_eq!(paths.dir(), from);
1085 assert_eq!(
1086 std::fs::read_to_string(to.join("config.yaml")).unwrap(),
1087 "new"
1088 );
1089 }
1090
1091 #[cfg(unix)]
1093 #[test]
1094 fn migration_notices_the_two_paths_are_the_same_directory() {
1095 let home = TempDir::new().unwrap();
1096 let to = home.path().join(".config").join(APP_DIR);
1097 seed(&to, &[("config.yaml", "x")]);
1098 let from = home.path().join(".atlassian-cli");
1099 std::os::unix::fs::symlink(&to, &from).unwrap();
1100
1101 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1102
1103 assert!(matches!(outcome, DirMigration::NotNeeded));
1104 assert!(from.exists(), "the symlink must not be archived");
1105 assert_eq!(paths.dir(), from);
1106 }
1107
1108 #[test]
1109 fn migration_picks_another_name_when_the_archive_exists() {
1110 let home = TempDir::new().unwrap();
1111 let from = home.path().join(".atlassian-cli");
1112 let to = home.path().join(".config").join(APP_DIR);
1113 seed(&from, &[("config.yaml", "x")]);
1114 seed(
1115 &home.path().join(".atlassian-cli.migrated"),
1116 &[("stale", "x")],
1117 );
1118
1119 let (_, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1120
1121 match outcome {
1122 DirMigration::Migrated { archived, .. } => {
1123 let archived = archived.expect("should still archive");
1124 assert_eq!(archived.file_name().unwrap(), ".atlassian-cli.migrated.1");
1125 }
1126 other => panic!("expected a migration, got {other:?}"),
1127 }
1128 }
1129
1130 #[cfg(unix)]
1131 #[test]
1132 fn migrated_files_and_directory_are_owner_only() {
1133 use std::os::unix::fs::PermissionsExt;
1134
1135 let home = TempDir::new().unwrap();
1136 let from = home.path().join(".atlassian-cli");
1137 let to = home.path().join(".config").join(APP_DIR);
1138 seed(&from, &[("credentials.enc", "{}")]);
1139 std::fs::set_permissions(
1142 from.join("credentials.enc"),
1143 std::fs::Permissions::from_mode(0o644),
1144 )
1145 .unwrap();
1146
1147 migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1148
1149 let file_mode = std::fs::metadata(to.join("credentials.enc"))
1150 .unwrap()
1151 .permissions()
1152 .mode()
1153 & 0o777;
1154 let dir_mode = std::fs::metadata(&to).unwrap().permissions().mode() & 0o777;
1155 assert_eq!(file_mode, 0o600);
1156 assert_eq!(dir_mode, 0o700);
1157 }
1158
1159 #[cfg(unix)]
1163 #[test]
1164 fn a_failed_migration_leaves_no_partial_target() {
1165 use std::os::unix::fs::PermissionsExt;
1166
1167 let home = TempDir::new().unwrap();
1168 let from = home.path().join(".atlassian-cli");
1169 seed(&from, &[("config.yaml", "x"), ("credentials.enc", "{}")]);
1170
1171 let locked = home.path().join("locked");
1172 std::fs::create_dir_all(&locked).unwrap();
1173 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o500)).unwrap();
1174
1175 if std::fs::create_dir(locked.join(".probe")).is_ok() {
1177 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();
1178 return;
1179 }
1180
1181 let to = locked.join(APP_DIR);
1182 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_legacy(&from, &to));
1183
1184 assert!(matches!(outcome, DirMigration::Failed { .. }));
1185 assert_eq!(
1186 paths.dir(),
1187 from,
1188 "a failed migration must keep working from the old location"
1189 );
1190 assert!(from.join("config.yaml").exists(), "nothing may be lost");
1191 assert!(!to.exists(), "no partial target");
1192
1193 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();
1194 }
1195
1196 #[cfg(unix)]
1200 #[test]
1201 fn an_existing_directory_keeps_its_permissions() {
1202 use std::os::unix::fs::PermissionsExt;
1203
1204 let parent = TempDir::new().unwrap();
1205 let dir = parent.path().join("theirs");
1206 std::fs::create_dir(&dir).unwrap();
1207 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1208
1209 create_private_dir(&dir).unwrap();
1210
1211 let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
1212 assert_eq!(
1213 mode, 0o755,
1214 "we must not re-permission a directory we found"
1215 );
1216 }
1217
1218 #[cfg(unix)]
1219 #[test]
1220 fn a_directory_we_create_is_owner_only() {
1221 use std::os::unix::fs::PermissionsExt;
1222
1223 let parent = TempDir::new().unwrap();
1224 let dir = parent.path().join("nested").join("ours");
1225
1226 create_private_dir(&dir).unwrap();
1227
1228 let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
1229 assert_eq!(mode, 0o700);
1230 }
1231
1232 #[cfg(unix)]
1234 #[test]
1235 fn a_file_written_into_someone_elses_directory_is_still_owner_only() {
1236 use std::os::unix::fs::PermissionsExt;
1237
1238 let parent = TempDir::new().unwrap();
1239 let dir = parent.path().join("theirs");
1240 std::fs::create_dir(&dir).unwrap();
1241 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1242
1243 write_private(&dir.join("config.yaml"), b"profiles: {}").unwrap();
1244
1245 let mode = std::fs::metadata(dir.join("config.yaml"))
1246 .unwrap()
1247 .permissions()
1248 .mode()
1249 & 0o777;
1250 assert_eq!(mode, 0o600);
1251 }
1252
1253 #[test]
1254 fn nothing_happens_when_the_directory_was_chosen_explicitly() {
1255 let home = TempDir::new().unwrap();
1256 let dir = home.path().join("explicit");
1257 seed(&dir, &[("config.yaml", "x")]);
1258
1259 let (paths, outcome) = migrate_legacy_dir(ConfigPaths::for_dir(&dir));
1260
1261 assert!(matches!(outcome, DirMigration::NotNeeded));
1262 assert_eq!(paths.dir(), dir);
1263 }
1264
1265 #[cfg(unix)]
1271 #[test]
1272 fn process_home_comes_from_home_and_the_default_is_dot_config() {
1273 let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) else {
1274 return; };
1276 let from_process = PathEnv::from_process();
1277 assert_eq!(from_process.home.as_deref(), Some(Path::new(&home)));
1278
1279 let paths = resolve(
1280 PathEnv {
1281 explicit_dir: None,
1282 xdg_config_home: None,
1283 ..from_process
1284 },
1285 &[],
1286 )
1287 .unwrap();
1288 assert_eq!(paths.dir(), Path::new(&home).join(".config").join(APP_DIR));
1289 assert_eq!(paths.source(), ConfigDirSource::Default);
1290 }
1291}