tftio-asana-cli 3.1.0

An interface to the Asana API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Configuration management utilities for the Asana CLI.
//!
//! Phase 1 establishes the persistent configuration surface and token storage.
//! Subsequent phases will expand the persisted settings and runtime validation.

use crate::error::{Error, Result};
use directories::ProjectDirs;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::debug;

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

const ENV_TOKEN: &str = "ASANA_PAT";
const ENV_BASE_URL: &str = "ASANA_BASE_URL";
const ENV_WORKSPACE: &str = "ASANA_WORKSPACE";
const ENV_ASSIGNEE: &str = "ASANA_ASSIGNEE";
const ENV_PROJECT: &str = "ASANA_PROJECT";
const ENV_CONFIG_HOME: &str = "ASANA_CLI_CONFIG_HOME";
const ENV_DATA_HOME: &str = "ASANA_CLI_DATA_HOME";
/// Default Asana API base URL when no override is provided.
pub const DEFAULT_API_BASE_URL: &str = "https://app.asana.com/api/1.0";

/// Environment-derived configuration inputs, read once at the CLI entry edge.
///
/// Per `REPO_INVARIANTS.md` #5 the environment is read at the edge and threaded
/// inward as typed values; [`Config::load`] consumes this rather than reading
/// `std::env` itself.
#[derive(Clone, Debug, Default)]
pub struct EnvInputs {
    /// Personal access token (`ASANA_PAT`).
    pub token: Option<String>,
    /// API base URL override (`ASANA_BASE_URL`).
    pub base_url: Option<String>,
    /// Default workspace (`ASANA_WORKSPACE`).
    pub workspace: Option<String>,
    /// Default assignee (`ASANA_ASSIGNEE`).
    pub assignee: Option<String>,
    /// Default project (`ASANA_PROJECT`).
    pub project: Option<String>,
    /// Config-home override (`ASANA_CLI_CONFIG_HOME`).
    pub config_home: Option<PathBuf>,
    /// Data-home override (`ASANA_CLI_DATA_HOME`).
    pub data_home: Option<PathBuf>,
}

impl EnvInputs {
    /// Read the Asana configuration environment at the CLI entry edge.
    #[must_use]
    #[allow(
        clippy::disallowed_methods,
        reason = "ASANA_* env vars are intentional overrides layered over the TOML config (api_base_url, default_workspace, …), read once at the CLI entry edge (REPO_INVARIANTS.md #5)"
    )]
    pub fn from_env() -> Self {
        Self {
            token: env::var(ENV_TOKEN).ok(),
            base_url: env::var(ENV_BASE_URL).ok(),
            workspace: env::var(ENV_WORKSPACE).ok(),
            assignee: env::var(ENV_ASSIGNEE).ok(),
            project: env::var(ENV_PROJECT).ok(),
            config_home: env::var_os(ENV_CONFIG_HOME).map(PathBuf::from),
            data_home: env::var_os(ENV_DATA_HOME).map(PathBuf::from),
        }
    }
}

/// Persisted configuration document.
#[derive(Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(default)]
pub struct FileConfig {
    /// Optional custom API base URL for private deployments.
    pub api_base_url: Option<String>,
    /// Preferred default workspace identifier.
    pub default_workspace: Option<String>,
    /// Preferred default assignee identifier (email or gid).
    pub default_assignee: Option<String>,
    /// Preferred default project identifier.
    pub default_project: Option<String>,
    /// Stored Personal Access Token (if persisted on disk).
    pub personal_access_token: Option<String>,
}

impl fmt::Debug for FileConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileConfig")
            .field("api_base_url", &self.api_base_url)
            .field("default_workspace", &self.default_workspace)
            .field("default_assignee", &self.default_assignee)
            .field("default_project", &self.default_project)
            .field(
                "personal_access_token",
                &self.personal_access_token.as_ref().map(|_| "REDACTED"),
            )
            .finish()
    }
}

/// Runtime configuration including environment overrides and persisted settings.
pub struct Config {
    file: FileConfig,
    overrides: Overrides,
    paths: ConfigPaths,
}

impl Config {
    /// Load configuration from disk and environment.
    ///
    /// # Errors
    /// Returns an error if configuration directories cannot be created or files cannot be read.
    pub fn load(inputs: &EnvInputs) -> Result<Self> {
        let paths = resolve_paths(inputs)?;
        if let Some(parent) = paths.config_file.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::create_dir_all(&paths.cache_dir)?;

        let file = read_config_file(&paths.config_file)?;
        let overrides = Overrides::from_inputs(inputs);

        Ok(Self {
            file,
            overrides,
            paths,
        })
    }

    /// Return the path to the configuration file.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.paths.config_file
    }

    /// Directory used for API response caching.
    #[must_use]
    pub fn cache_dir(&self) -> &Path {
        &self.paths.cache_dir
    }

    /// Directory used for persistent data assets (templates, filters, etc.).
    #[must_use]
    pub fn data_dir(&self) -> &Path {
        &self.paths.data_dir
    }

    /// Directory where user templates are stored.
    #[must_use]
    pub fn templates_dir(&self) -> PathBuf {
        self.paths.data_dir.join("templates")
    }

    /// Directory storing reusable filter definitions.
    #[must_use]
    pub fn filters_dir(&self) -> PathBuf {
        self.paths.data_dir.join("filters")
    }

    /// Return the computed API base URL, considering environment overrides.
    #[must_use]
    pub fn api_base_url(&self) -> Option<&str> {
        self.overrides
            .api_base_url
            .as_deref()
            .or(self.file.api_base_url.as_deref())
    }

    /// Return the effective API base URL, falling back to the default value.
    #[must_use]
    pub fn effective_api_base_url(&self) -> &str {
        self.api_base_url().unwrap_or(DEFAULT_API_BASE_URL)
    }

    /// Return the default workspace identifier.
    #[must_use]
    pub fn default_workspace(&self) -> Option<&str> {
        self.overrides
            .default_workspace
            .as_deref()
            .or(self.file.default_workspace.as_deref())
    }

    /// Update the stored default workspace identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration file cannot be saved to disk.
    pub fn set_default_workspace(&mut self, workspace: Option<String>) -> Result<()> {
        self.file.default_workspace = workspace;
        self.save()
    }

    /// Return the default assignee identifier.
    #[must_use]
    pub fn default_assignee(&self) -> Option<&str> {
        self.overrides
            .default_assignee
            .as_deref()
            .or(self.file.default_assignee.as_deref())
    }

    /// Update the stored default assignee identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration file cannot be saved to disk.
    pub fn set_default_assignee(&mut self, assignee: Option<String>) -> Result<()> {
        self.file.default_assignee = assignee;
        self.save()
    }

    /// Return the default project identifier.
    #[must_use]
    pub fn default_project(&self) -> Option<&str> {
        self.overrides
            .default_project
            .as_deref()
            .or(self.file.default_project.as_deref())
    }

    /// Update the stored default project identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration file cannot be saved to disk.
    pub fn set_default_project(&mut self, project: Option<String>) -> Result<()> {
        self.file.default_project = project;
        self.save()
    }

    /// Persist the in-memory configuration to disk.
    ///
    /// # Errors
    /// Returns an error when the configuration cannot be encoded or written to disk.
    pub fn save(&self) -> Result<()> {
        if let Some(parent) = self.paths.config_file.parent() {
            fs::create_dir_all(parent)?;
            secure_directory(parent)?;
        }

        let serialized = toml::to_string_pretty(&self.file)?;
        fs::write(&self.paths.config_file, serialized)?;
        secure_file(&self.paths.config_file)?;
        Ok(())
    }

    /// Store the provided Personal Access Token in the configuration file.
    ///
    /// # Errors
    /// Returns an error if the configuration file cannot be updated.
    pub fn store_personal_access_token(&mut self, token: &SecretString) -> Result<()> {
        self.file
            .personal_access_token
            .replace(token.expose_secret().to_owned());
        self.save()
    }

    /// Retrieve the Personal Access Token, taking environment overrides into account.
    #[must_use]
    pub fn personal_access_token(&self) -> Option<SecretString> {
        if let Some(token) = self.overrides.personal_access_token.clone() {
            return Some(token);
        }
        self.file.personal_access_token.as_ref().and_then(|value| {
            if value.trim().is_empty() {
                None
            } else {
                Some(SecretString::new(value.clone().into()))
            }
        })
    }

    /// Remove any stored Personal Access Token.
    ///
    /// # Errors
    /// Returns an error when stored secrets cannot be removed.
    pub fn delete_personal_access_token(&mut self) -> Result<()> {
        self.file.personal_access_token = None;
        self.save()
    }

    /// Determine whether a token is persisted in the configuration file.
    #[must_use]
    pub fn has_persisted_token(&self) -> bool {
        self.file
            .personal_access_token
            .as_ref()
            .is_some_and(|value| !value.trim().is_empty())
    }

    /// Determine whether a token is provided by environment overrides.
    #[must_use]
    pub fn environment_token_available(&self) -> bool {
        self.overrides
            .personal_access_token
            .as_ref()
            .is_some_and(|value| !value.expose_secret().trim().is_empty())
    }

    /// Expose the underlying file configuration for mutation.
    pub fn file_config_mut(&mut self) -> &mut FileConfig {
        &mut self.file
    }
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Config")
            .field("file", &self.file)
            .field("overrides", &self.overrides)
            .field("paths", &self.paths)
            .finish()
    }
}

fn secure_directory(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        let metadata = fs::metadata(path)?;
        if metadata.is_dir() {
            let perms = metadata.permissions();
            let mode = perms.mode();
            if mode & 0o077 != 0 {
                let mut tightened = perms;
                tightened.set_mode(0o700);
                fs::set_permissions(path, tightened)?;
            }
        }
    }
    Ok(())
}

fn secure_file(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        let metadata = fs::metadata(path)?;
        if metadata.is_file() {
            let perms = metadata.permissions();
            let mode = perms.mode();
            if mode & 0o177 != 0o100 {
                let mut tightened = perms;
                tightened.set_mode(0o600);
                fs::set_permissions(path, tightened)?;
            }
        }
    }
    Ok(())
}

#[derive(Clone, Default)]
struct Overrides {
    api_base_url: Option<String>,
    default_workspace: Option<String>,
    default_assignee: Option<String>,
    default_project: Option<String>,
    personal_access_token: Option<SecretString>,
}

impl fmt::Debug for Overrides {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Overrides")
            .field("api_base_url", &self.api_base_url)
            .field("default_workspace", &self.default_workspace)
            .field("default_assignee", &self.default_assignee)
            .field("default_project", &self.default_project)
            .field(
                "personal_access_token",
                &self.personal_access_token.as_ref().map(|_| "REDACTED"),
            )
            .finish()
    }
}

impl Overrides {
    fn from_inputs(inputs: &EnvInputs) -> Self {
        Self {
            api_base_url: inputs.base_url.clone(),
            default_workspace: inputs.workspace.clone(),
            default_assignee: inputs.assignee.clone(),
            default_project: inputs.project.clone(),
            personal_access_token: inputs.token.clone().map(|s| SecretString::new(s.into())),
        }
    }
}

#[derive(Clone)]
struct ConfigPaths {
    config_file: PathBuf,
    data_dir: PathBuf,
    cache_dir: PathBuf,
}

impl fmt::Debug for ConfigPaths {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConfigPaths")
            .field("config_file", &self.config_file)
            .field("data_dir", &self.data_dir)
            .field("cache_dir", &self.cache_dir)
            .finish()
    }
}

fn resolve_paths(inputs: &EnvInputs) -> Result<ConfigPaths> {
    let project_dirs = if let Some(base) = inputs.config_home.clone() {
        ProjectDirs::from_path(base.clone()).ok_or_else(|| {
            Error::ProjectDirs(format!(
                "failed to construct project directories from {} (check {ENV_CONFIG_HOME})",
                base.display()
            ))
        })?
    } else {
        ProjectDirs::from("com", "asana", "asana-cli").ok_or_else(|| {
            Error::ProjectDirs("unable to resolve standard project directories".to_owned())
        })?
    };

    let config_dir = inputs
        .config_home
        .clone()
        .unwrap_or_else(|| project_dirs.config_dir().to_path_buf());

    let data_dir = inputs
        .data_home
        .clone()
        .unwrap_or_else(|| project_dirs.data_local_dir().to_path_buf());
    let cache_dir = data_dir.join("cache");

    Ok(ConfigPaths {
        config_file: config_dir.join("config.toml"),
        data_dir,
        cache_dir,
    })
}

fn read_config_file(path: &Path) -> Result<FileConfig> {
    if !path.exists() {
        debug!(config_path = %path.display(), "configuration file not found; using defaults");
        return Ok(FileConfig::default());
    }

    let contents = fs::read_to_string(path)?;
    let parsed: FileConfig = toml::from_str(&contents)?;
    Ok(parsed)
}

#[cfg(test)]
#[allow(unsafe_code)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::ffi::OsStr;
    use tempfile::TempDir;

    fn set_env<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
        unsafe {
            env::set_var(key, value);
        }
    }

    fn remove_env<K: AsRef<OsStr>>(key: K) {
        unsafe {
            env::remove_var(key);
        }
    }

    fn with_temp_env<F>(config_home: &TempDir, data_home: &TempDir, f: F)
    where
        F: FnOnce(),
    {
        set_env(ENV_CONFIG_HOME, config_home.path());
        set_env(ENV_DATA_HOME, data_home.path());
        f();
        remove_env(ENV_CONFIG_HOME);
        remove_env(ENV_DATA_HOME);
        remove_env(ENV_TOKEN);
        remove_env(ENV_BASE_URL);
        remove_env(ENV_WORKSPACE);
        remove_env(ENV_ASSIGNEE);
        remove_env(ENV_PROJECT);
    }

    #[test]
    #[serial]
    fn load_creates_directories_and_defaults() {
        let config_home = TempDir::new().unwrap();
        let data_home = TempDir::new().unwrap();

        with_temp_env(&config_home, &data_home, || {
            let cfg = Config::load(&EnvInputs::from_env()).expect("load config");
            let parent = cfg.path().parent().expect("config path has parent");
            assert!(parent.exists(), "config directory should exist");
            assert!(
                !cfg.path().exists(),
                "config file should not be created automatically"
            );
            assert!(cfg.personal_access_token().is_none());
            assert!(cfg.api_base_url().is_none());
        });
    }

    #[test]
    #[serial]
    fn environment_overrides_take_precedence() {
        let config_home = TempDir::new().unwrap();
        let data_home = TempDir::new().unwrap();

        with_temp_env(&config_home, &data_home, || {
            set_env(ENV_BASE_URL, "https://override.example.com");
            set_env(ENV_WORKSPACE, "workspace-123");
            set_env(ENV_ASSIGNEE, "owner@example.com");
            set_env(ENV_TOKEN, "env-token");

            let mut cfg = Config::load(&EnvInputs::from_env()).expect("load config");
            cfg.file_config_mut().api_base_url = Some("https://file.example.com".into());
            cfg.file_config_mut().default_workspace = Some("workspace-456".into());
            cfg.file_config_mut().default_assignee = Some("file@example.com".into());
            cfg.file_config_mut().personal_access_token = Some("file-token".into());
            cfg.save().expect("save config");

            let cfg = Config::load(&EnvInputs::from_env()).expect("reload config");
            assert_eq!(cfg.api_base_url(), Some("https://override.example.com"));
            assert_eq!(cfg.default_workspace(), Some("workspace-123"));
            assert_eq!(cfg.default_assignee(), Some("owner@example.com"));
            let token = cfg.personal_access_token().expect("token present");
            assert_eq!(token.expose_secret(), "env-token");
        });
    }

    #[test]
    #[serial]
    fn token_round_trip_in_config_file() {
        let config_home = TempDir::new().unwrap();
        let data_home = TempDir::new().unwrap();

        with_temp_env(&config_home, &data_home, || {
            let mut cfg = Config::load(&EnvInputs::from_env()).expect("load config");
            let token = SecretString::new("token-value".into());
            cfg.store_personal_access_token(&token)
                .expect("store token");

            let reloaded = Config::load(&EnvInputs::from_env()).expect("reload config");
            let loaded = reloaded.personal_access_token();
            assert_eq!(
                loaded.as_ref().map(|s| s.expose_secret().to_string()),
                Some("token-value".into())
            );
        });
    }

    #[test]
    #[serial]
    fn default_assignee_round_trip() {
        let config_home = TempDir::new().unwrap();
        let data_home = TempDir::new().unwrap();

        with_temp_env(&config_home, &data_home, || {
            let mut cfg = Config::load(&EnvInputs::from_env()).expect("load config");
            cfg.set_default_assignee(Some("user@example.com".into()))
                .expect("store assignee");

            let cfg = Config::load(&EnvInputs::from_env()).expect("reload config");
            assert_eq!(cfg.default_assignee(), Some("user@example.com"));

            let mut cfg = Config::load(&EnvInputs::from_env()).expect("load config to clear");
            cfg.set_default_assignee(None).expect("clear assignee");
            let cfg = Config::load(&EnvInputs::from_env()).expect("reload after clear");
            assert!(cfg.default_assignee().is_none());
        });
    }
}