wme-cli 0.1.3

CLI tool for the Wikimedia Enterprise API
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
//! Configuration management for the Wikimedia Enterprise CLI.
//!
//! This module handles loading, saving, and managing CLI configuration,
//! including authentication tokens. Configuration is stored in JSON format
//! at `~/.wme/config.json` by default.
//!
//! # Example
//!
//! ```rust
//! use wme_cli::config::Config;
//! use std::path::Path;
//!
//! # fn example() -> anyhow::Result<()> {
//! // Load config from default location
//! let config = Config::load(None)?;
//!
//! // Check if token is expired
//! if config.is_token_expired() {
//!     println!("Token expired, please login again");
//! }
//!
//! // Get access token if available
//! if let Some(token) = config.get_access_token() {
//!     println!("Using token: {}", token);
//! }
//! # Ok(())
//! # }
//! ```

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

/// Default config directory name
const CONFIG_DIR: &str = "wme";
/// Default config file name
const CONFIG_FILE: &str = "config.json";

/// CLI configuration stored in ~/.wme/config.json
///
/// Stores user authentication tokens and metadata. The configuration
/// file is created automatically on first login and updated when
/// tokens are refreshed or revoked.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    /// Username associated with the stored tokens
    pub username: Option<String>,
    /// Access token for API authentication
    pub access_token: Option<String>,
    /// Refresh token for obtaining new access tokens
    pub refresh_token: Option<String>,
    /// Access token expiration time in RFC3339 format
    pub token_expires_at: Option<String>,
    /// Refresh token expiration time in RFC3339 format (90 days from issue)
    pub refresh_token_expires_at: Option<String>,
    /// Additional settings (for forward compatibility)
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl Config {
    /// Load configuration from a file path.
    ///
    /// If no path is provided, loads from the default location (`~/.wme/config.json`).
    /// If the file does not exist, returns a default empty configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path to the config file. If `None`, uses default location.
    ///
    /// # Errors
    ///
    /// Returns an error if the file exists but cannot be read or parsed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use wme_cli::config::Config;
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// // Load from default location
    /// let config = Config::load(None)?;
    ///
    /// // Load from specific path
    /// let config = Config::load(Some(std::path::Path::new("/path/to/config.json")))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn load(path: Option<&Path>) -> Result<Self> {
        let config_path = match path {
            Some(p) => p.to_path_buf(),
            None => default_config_path()?,
        };

        if config_path.exists() {
            let content = fs::read_to_string(&config_path)
                .with_context(|| format!("Failed to read config from {}", config_path.display()))?;
            let config: Config = serde_json::from_str(&content).with_context(|| {
                format!("Failed to parse config from {}", config_path.display())
            })?;
            Ok(config)
        } else {
            Ok(Config::default())
        }
    }

    /// Save configuration to a file.
    ///
    /// If no path is provided, saves to the default location (`~/.wme/config.json`).
    /// Creates parent directories if they don't exist.
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path to save the config file. If `None`, uses default location.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written or directories cannot be created.
    pub fn save(&self, path: Option<&Path>) -> Result<()> {
        let config_path = match path {
            Some(p) => p.to_path_buf(),
            None => default_config_path()?,
        };

        // Ensure parent directory exists
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory {}", parent.display())
            })?;
        }

        let content = serde_json::to_string_pretty(self).context("Failed to serialize config")?;
        fs::write(&config_path, content)
            .with_context(|| format!("Failed to write config to {}", config_path.display()))?;

        Ok(())
    }

    /// Returns the default configuration file path.
    ///
    /// The default path is `~/.wme/config.json` on Unix systems.
    ///
    /// # Errors
    ///
    /// Returns an error if the home directory cannot be determined.
    pub fn default_path() -> Result<PathBuf> {
        default_config_path()
    }

    /// Check if the stored access token is expired.
    ///
    /// Parses the `token_expires_at` field and compares it to the current time.
    /// Returns `true` if the token is expired or if no expiration time is set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use wme_cli::config::Config;
    ///
    /// # fn example() {
    /// let config = Config::default();
    /// assert!(config.is_token_expired()); // No token = expired
    /// # }
    /// ```
    pub fn is_token_expired(&self) -> bool {
        match &self.token_expires_at {
            Some(expires_at) => {
                match chrono::DateTime::parse_from_rfc3339(expires_at) {
                    Ok(expiry) => chrono::Utc::now() > expiry.with_timezone(&chrono::Utc),
                    Err(_) => true, // If we can't parse, consider it expired
                }
            }
            None => true, // No expiry means expired
        }
    }

    /// Get the access token if it's available and not expired.
    ///
    /// Returns `Some(token)` if a valid (non-expired) access token exists,
    /// otherwise returns `None`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use wme_cli::config::Config;
    ///
    /// # fn example() {
    /// let config = Config::default();
    /// assert_eq!(config.get_access_token(), None); // No token
    /// # }
    /// ```
    pub fn get_access_token(&self) -> Option<String> {
        if self.is_token_expired() {
            None
        } else {
            self.access_token.clone()
        }
    }

    /// Store authentication tokens after a successful login.
    ///
    /// Updates the username, access token, refresh token, and calculates
    /// the expiration time based on the provided `expires_in` seconds.
    ///
    /// # Arguments
    ///
    /// * `username` - The username for the authenticated session
    /// * `access_token` - The access token from the authentication response
    /// * `refresh_token` - The refresh token from the authentication response
    /// * `expires_in` - Token lifetime in seconds
    pub fn set_tokens(
        &mut self,
        username: &str,
        access_token: &str,
        refresh_token: &str,
        expires_in: u64,
    ) {
        self.username = Some(username.to_string());
        self.access_token = Some(access_token.to_string());
        self.refresh_token = Some(refresh_token.to_string());

        let expires_at = chrono::Utc::now() + chrono::Duration::seconds(expires_in as i64);
        self.token_expires_at = Some(expires_at.to_rfc3339());

        // Refresh tokens expire after 90 days
        let refresh_expires_at = chrono::Utc::now() + chrono::Duration::days(90);
        self.refresh_token_expires_at = Some(refresh_expires_at.to_rfc3339());
    }

    /// Clear all authentication tokens.
    ///
    /// Removes the username, access token, refresh token, and expiration time.
    /// This effectively logs out the user.
    pub fn clear_tokens(&mut self) {
        self.username = None;
        self.access_token = None;
        self.refresh_token = None;
        self.token_expires_at = None;
        self.refresh_token_expires_at = None;
    }
}

/// Get the default config path (~/.wme/config.json)
fn default_config_path() -> Result<PathBuf> {
    let dirs = directories::BaseDirs::new().context("Failed to get home directory")?;
    Ok(dirs
        .home_dir()
        .join(format!(".{}", CONFIG_DIR))
        .join(CONFIG_FILE))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(config.username.is_none());
        assert!(config.access_token.is_none());
        assert!(config.refresh_token.is_none());
        assert!(config.token_expires_at.is_none());
        assert!(config.extra.is_empty());
    }

    #[test]
    fn test_config_load_nonexistent() {
        // Load from a non-existent path should return default config
        let result = Config::load(Some(Path::new("/nonexistent/path/config.json")));
        assert!(result.is_ok());
        let config = result.unwrap();
        assert!(config.username.is_none());
    }

    #[test]
    fn test_config_load_and_save() {
        let temp_file = NamedTempFile::new().unwrap();

        // Create a config and save it
        let config = Config {
            username: Some("testuser".to_string()),
            access_token: Some("test_token".to_string()),
            refresh_token: Some("refresh_token".to_string()),
            token_expires_at: Some("2099-12-31T23:59:59Z".to_string()),
            refresh_token_expires_at: Some("2099-12-31T23:59:59Z".to_string()),
            extra: std::collections::HashMap::default(),
        };

        config.save(Some(temp_file.path())).unwrap();

        // Load it back
        let loaded = Config::load(Some(temp_file.path())).unwrap();
        assert_eq!(loaded.username, Some("testuser".to_string()));
        assert_eq!(loaded.access_token, Some("test_token".to_string()));
        assert_eq!(loaded.refresh_token, Some("refresh_token".to_string()));
        assert_eq!(
            loaded.token_expires_at,
            Some("2099-12-31T23:59:59Z".to_string())
        );
    }

    #[test]
    fn test_is_token_expired_no_expiry() {
        let config = Config::default();
        assert!(config.is_token_expired());
    }

    #[test]
    fn test_is_token_expired_past() {
        // Set expiry to the past
        let config = Config {
            token_expires_at: Some("2000-01-01T00:00:00Z".to_string()),
            ..Default::default()
        };
        assert!(config.is_token_expired());
    }

    #[test]
    fn test_is_token_expired_future() {
        // Set expiry to far future
        let config = Config {
            token_expires_at: Some("2099-12-31T23:59:59Z".to_string()),
            ..Default::default()
        };
        assert!(!config.is_token_expired());
    }

    #[test]
    fn test_is_token_expired_invalid_format() {
        // Invalid format should be treated as expired
        let config = Config {
            token_expires_at: Some("not-a-date".to_string()),
            ..Default::default()
        };
        assert!(config.is_token_expired());
    }

    #[test]
    fn test_get_access_token_expired() {
        let config = Config {
            access_token: Some("token".to_string()),
            token_expires_at: Some("2000-01-01T00:00:00Z".to_string()),
            ..Default::default()
        };
        assert_eq!(config.get_access_token(), None);
    }

    #[test]
    fn test_get_access_token_valid() {
        let config = Config {
            access_token: Some("valid_token".to_string()),
            token_expires_at: Some("2099-12-31T23:59:59Z".to_string()),
            ..Default::default()
        };
        assert_eq!(config.get_access_token(), Some("valid_token".to_string()));
    }

    #[test]
    fn test_set_tokens() {
        let mut config = Config::default();
        config.set_tokens("myuser", "access123", "refresh456", 3600);

        assert_eq!(config.username, Some("myuser".to_string()));
        assert_eq!(config.access_token, Some("access123".to_string()));
        assert_eq!(config.refresh_token, Some("refresh456".to_string()));
        assert!(config.token_expires_at.is_some());
        // Should not be expired immediately after setting
        assert!(!config.is_token_expired());
    }

    #[test]
    fn test_clear_tokens() {
        let mut config = Config::default();
        config.set_tokens("user", "access", "refresh", 3600);
        config.clear_tokens();

        assert!(config.username.is_none());
        assert!(config.access_token.is_none());
        assert!(config.refresh_token.is_none());
        assert!(config.token_expires_at.is_none());
        assert!(config.refresh_token_expires_at.is_none());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config {
            username: Some("test".to_string()),
            access_token: Some("token".to_string()),
            refresh_token: Some("refresh".to_string()),
            token_expires_at: Some("2099-01-01T00:00:00Z".to_string()),
            refresh_token_expires_at: Some("2099-04-01T00:00:00Z".to_string()),
            extra: {
                let mut map = HashMap::new();
                map.insert("custom_key".to_string(), serde_json::json!("custom_value"));
                map
            },
        };

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("test"));
        assert!(json.contains("custom_key"));

        let deserialized: Config = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.username, config.username);
        assert_eq!(
            deserialized.extra.get("custom_key").unwrap(),
            "custom_value"
        );
    }
}