Skip to main content

atlassian_cli_config/
paths.rs

1//! Where the CLI keeps its files.
2//!
3//! Historically everything lived in `~/.atlassian-cli/` with no way to move it:
4//! `--config` pointed at a different config *file*, but the two credential files
5//! had no flag and no environment variable. Anyone keeping their tools under
6//! `~/.config` needed a symlink.
7//!
8//! Resolution order:
9//!
10//! 1. `$ATLASSIAN_CLI_CONFIG_DIR` (or `--config-dir`)
11//! 2. `$XDG_CONFIG_HOME/atlassian-cli`
12//! 3. `~/.config/atlassian-cli`
13//! 4. the legacy `~/.atlassian-cli`, then `~/.atlcli`, if either still holds our files
14//!
15//! `~/.config` is used on macOS too. `dirs::config_dir()` would give
16//! `~/Library/Application Support` there, which is not what someone asking for
17//! XDG means.
18//!
19//! All three files live in whichever directory wins, so one setting moves
20//! everything.
21
22use 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
29/// Directory name under the XDG config root. No leading dot: it is already hidden
30/// by its parent.
31pub const APP_DIR: &str = "atlassian-cli";
32
33/// Older locations, newest first. `.atlcli` predates `.atlassian-cli`.
34pub 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
40/// Every file we own. A directory counts as ours if it holds at least one.
41pub const OWNED_FILES: [&str; 3] = [CONFIG_FILENAME, CREDENTIALS_FILENAME, ENCRYPTED_FILENAME];
42
43/// Suffix for a legacy directory that has been migrated away from.
44pub const ARCHIVE_SUFFIX: &str = ".migrated";
45
46/// Which rule picked the directory.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum ConfigDirSource {
49    /// `$ATLASSIAN_CLI_CONFIG_DIR` or `--config-dir`. Never migrated: an explicit
50    /// choice is not something to second-guess.
51    Explicit,
52    /// `$XDG_CONFIG_HOME/atlassian-cli`.
53    Xdg,
54    /// `~/.config/atlassian-cli`, or the platform equivalent on Windows.
55    Default,
56    /// A legacy directory that still holds our files.
57    Legacy,
58}
59
60/// The inputs resolution reads.
61///
62/// Built from the process in `from_process`, and constructed literally in tests.
63/// Keeping the environment out of the resolution itself is what lets the tests
64/// run in parallel without a lock around `set_var`.
65#[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    /// Windows only: `%LOCALAPPDATA%`. Deliberately the *local* one, not roaming;
71    /// see `default_base`.
72    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/// The resolved location of every file the CLI owns.
87#[derive(Debug, Clone)]
88pub struct ConfigPaths {
89    dir: PathBuf,
90    /// Where we would like to be. Differs from `dir` only when a legacy
91    /// directory won, in which case this is the migration target.
92    preferred: PathBuf,
93    source: ConfigDirSource,
94    /// From `--config`, which moves the config file alone.
95    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
102/// The base directory to put `atlassian-cli/` under when nothing is set.
103fn default_base(env: &PathEnv) -> Option<PathBuf> {
104    if cfg!(windows) {
105        // %LOCALAPPDATA%, not %APPDATA%. The encryption key derives from the
106        // machine id, so a roaming profile would replicate a credentials file
107        // that the second machine cannot decrypt.
108        env.native_config.clone()
109    } else {
110        env.home.as_ref().map(|h| h.join(".config"))
111    }
112}
113
114impl ConfigPaths {
115    /// Resolve from the process environment and the filesystem.
116    pub fn resolve() -> Result<Self> {
117        Self::resolve_with(&PathEnv::from_process(), &is_populated)
118    }
119
120    /// Resolve from an explicit override, falling back to the environment.
121    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    /// The resolution rules. `populated` is the only contact with the filesystem,
130    /// so tests can supply their own.
131    pub fn resolve_with(env: &PathEnv, populated: &dyn Fn(&Path) -> bool) -> Result<Self> {
132        // 1. An explicit directory wins outright, and is used verbatim. A
133        //    relative value is honoured here, unlike XDG below: this is our own
134        //    variable, and `ATLASSIAN_CLI_CONFIG_DIR=./ci-config` is a
135        //    reasonable thing to write in a job with a fixed working directory.
136        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        // 2/3. The XDG location, or the platform default.
142        //      A relative $XDG_CONFIG_HOME is ignored, as the basedir spec says
143        //      and as dirs-sys does. Resolving it against the current directory
144        //      would drop a credentials file into whatever repository the user
145        //      happens to be standing in.
146        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        // The preferred location already holds our files: nothing to consider.
165        if populated(&preferred) {
166            return Ok(Self::at(preferred, source));
167        }
168
169        // 4. A legacy directory, but only if it actually holds something. A
170        //    leftover empty ~/.atlassian-cli must not pin someone on the old
171        //    location forever, nor trigger a migration that copies nothing and
172        //    then renames a directory they may have created deliberately.
173        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        // Fresh install: land in the preferred location.
188        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    /// Use this directory as-is. For tests and embedding.
201    pub fn for_dir(dir: impl Into<PathBuf>) -> Self {
202        Self::at(dir.into(), ConfigDirSource::Explicit)
203    }
204
205    /// For tests that need to exercise the migration path.
206    #[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    /// Point the config file somewhere else. Affects `config_file` only: the
217    /// credentials stay in the resolved directory.
218    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
250/// Does this directory hold at least one of our files?
251pub fn is_populated(dir: &Path) -> bool {
252    OWNED_FILES.iter().any(|name| dir.join(name).exists())
253}
254
255/// Expand a leading `~` against the home directory.
256fn 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/// Outcome of moving a legacy directory to the preferred location.
268#[derive(Debug)]
269pub enum DirMigration {
270    NotNeeded,
271    Migrated {
272        from: PathBuf,
273        to: PathBuf,
274        files: Vec<&'static str>,
275        /// Where the old directory was renamed to. `None` if the rename failed,
276        /// which is untidy but not a correctness problem.
277        archived: Option<PathBuf>,
278        /// A plaintext `credentials` file was scrubbed from the archive after
279        /// its contents were copied to the new location. Worth telling the user
280        /// about: it is the one thing migration removes.
281        scrubbed_plaintext: bool,
282    },
283    /// Nothing was copied, and the returned paths still point at `from`.
284    Failed {
285        from: PathBuf,
286        to: PathBuf,
287        error: String,
288    },
289}
290
291/// Move a legacy directory to the preferred location, then rename the original.
292///
293/// Files are copied into a staging directory and promoted with a single rename,
294/// rather than written into the target one at a time. A half-populated target
295/// would be worse than no migration: the next run's resolver would see files in
296/// the new location, choose it, and the user would appear logged out while their
297/// tokens sat in a directory the CLI no longer reads.
298///
299/// The original is renamed to `<name>.migrated` rather than left in place. A
300/// lingering copy that is silently ignored is a trap: anyone editing it later is
301/// editing a dead file. Nothing is deleted.
302///
303/// Returns the paths to actually use. On failure that is the legacy directory,
304/// so someone whose new location is unwritable keeps working.
305pub 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    // A pre-existing symlink from the old path to the new one is a workaround
314    // people already use. Comparing canonical paths is what catches it.
315    if let (Ok(a), Ok(b)) = (from.canonicalize(), to.canonicalize()) {
316        if a == b {
317            return (paths, DirMigration::NotNeeded);
318        }
319    }
320
321    // Never merge into a directory that already holds something.
322    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            // The copy in the new location is now the only one that should
330            // exist. Leaving the archived plaintext token behind would be a
331            // regression against the pre-migration behaviour, where the next
332            // `auth login` shredded it: the file would sit in
333            // `~/.atlassian-cli.migrated/credentials` indefinitely, readable,
334            // while the user believed encryption had taken over.
335            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    // One atomic step. If a concurrent invocation won the race, the target is
398    // no longer empty and there is nothing left to do.
399    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        // `to` holds none of our files but is not a name we can rename onto:
405        // an existing directory with a `.DS_Store`, a `.keep`, or an unrelated
406        // file in it (ENOTEMPTY), or a symlink to a directory, which is exactly
407        // the shape a stow/chezmoi dotfile setup has - and dotfile users are
408        // who asked for this feature. Renaming a directory onto either fails
409        // forever, so without this fallback the migration would never complete
410        // and every single command would print the same warning.
411        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
428/// Move each staged file into an existing target directory, one atomic rename
429/// apiece, undoing them all if any fails.
430///
431/// The all-or-nothing part is the point. A target holding `config.yaml` but not
432/// `credentials.enc` is worse than an unmigrated one: the resolver would pick it
433/// on the next run and the user would look logged out while their token sat in a
434/// directory the CLI had stopped reading.
435fn 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
458/// Overwrite a file's bytes before removing it, and report whether it went.
459///
460/// The same one-pass overwrite the auth crate uses: it defeats an undelete on
461/// the filesystems people actually run, and claims nothing more than that. On a
462/// copy-on-write filesystem the old blocks may survive regardless.
463///
464/// `symlink_metadata`, so a symlinked `credentials` is not written through. That
465/// happens: pointing it at a dotfiles repository is one of the workarounds this
466/// feature replaces, and zeroing 21 bytes inside someone's git working tree
467/// because they migrated is not ours to do. The link itself is removed, and the
468/// caller reports nothing scrubbed, because the plaintext still exists at the
469/// far end of it.
470fn 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
487/// Rename the legacy directory aside so it cannot be edited by mistake.
488fn 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
508/// Write a file only its owner can read. See the auth crate for the same helper;
509/// duplicated rather than shared to avoid a dependency edge between two sibling
510/// crates for twelve lines.
511pub 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        // `create_new`, not `create`: the temp name is derived from the pid, so
523        // it is guessable, and opening an existing path would follow a symlink
524        // planted there and write a token wherever it points. A leftover file
525        // means a crash, and is cleared only once confirmed to be a plain file.
526        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
567/// Create a directory only its owner can enter.
568pub fn create_private_dir(dir: &Path) -> Result<()> {
569    // Only a directory we create is ours to set a mode on. Tightening one that
570    // already exists would mean `--config /shared/team.yaml` silently chmodding
571    // /shared, or `ATLASSIAN_CLI_CONFIG_DIR=$HOME` chmodding the home directory.
572    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    /// Resolution with a stated set of populated directories, so nothing touches
595    /// the filesystem or the process environment.
596    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    /// Our own variable, so a relative value is honoured: CI jobs with a fixed
640    /// working directory reasonably write `./ci-config`.
641    #[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    /// The basedir spec says a relative value must be ignored. Resolving it
682    /// against the cwd would write credentials into whatever repo you are in.
683    #[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    /// A leftover empty directory must not pin anyone on the old location.
712    #[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    /// An already-migrated install: the new location has files, so the legacy
733    /// one is never consulted.
734    #[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    /// Previously this fell back to the current directory, which under a single
752    /// shared directory would write credentials.enc into whatever repo you are in.
753    #[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    /// `--config` moves the config file alone; credentials stay put.
773    #[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    // ---------------------------------------------------------------------
799    // Migration
800    // ---------------------------------------------------------------------
801
802    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    /// The archive must not keep a second readable copy of a plaintext token.
848    ///
849    /// Before the directory moved, `auth login` shredded the one plaintext
850    /// `credentials` file it found. Copying it aside and leaving it there would
851    /// quietly undo that: the user encrypts their token and a cleartext copy
852    /// lives on in `~/.atlassian-cli.migrated` for as long as they never look.
853    #[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    /// A symlinked `credentials` is not written through.
894    ///
895    /// Pointing it at a dotfiles repository is one of the workarounds this
896    /// feature exists to replace, so the file at the far end is git-managed and
897    /// belongs to the user. The link goes; its target is left exactly as it was,
898    /// and nothing is reported as scrubbed, since the plaintext still exists.
899    #[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    /// An encrypted-only install has no plaintext file, so nothing is removed
946    /// and the notice must not claim otherwise.
947    #[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    /// A target directory that exists but holds none of our files.
965    ///
966    /// `.DS_Store`, a `.keep`, or anything else a dotfile manager drops there
967    /// makes `rename(staging, to)` fail with ENOTEMPTY every single run. The
968    /// files must be promoted individually instead of the migration warning
969    /// forever.
970    #[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    /// A symlinked config directory, which is how the people who asked for this
1008    /// feature already work around its absence.
1009    #[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    /// Only what is there. An install with no credentials must not create empty ones.
1040    #[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        // Second run: the source is gone, so resolution would never call this
1066        // again, but calling it must still be harmless.
1067        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    /// Never merge into a live directory.
1073    #[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    /// The symlink workaround people already use.
1092    #[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        // Loosen the source, so we are testing what we write rather than what
1140        // we happened to copy.
1141        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    /// The property that makes staging worth the complexity: a failure must not
1160    /// leave a half-populated target, because the next run would choose it and
1161    /// the user would appear logged out.
1162    #[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        // CI often runs as root, where 0500 denies nothing.
1176        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    /// A directory we did not create is not ours to re-permission. Tightening it
1197    /// would mean `--config /shared/team.yaml` silently chmodding /shared, or
1198    /// `ATLASSIAN_CLI_CONFIG_DIR=$HOME` chmodding the home directory.
1199    #[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    /// The file is ours whatever the directory, because it holds the token.
1233    #[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    /// Regression check for the `dirs` crate, the one place resolution reads
1266    /// the machine. dirs 7 changed only Windows `preference_dir`, which we do
1267    /// not use; this pins what we do use so a later bump that moves
1268    /// `home_dir` would fail here instead of silently relocating everyone's
1269    /// credentials. It only reads the environment, so it is safe in parallel.
1270    #[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; // nothing to compare against
1275        };
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}