cull_gmail/
client_config.rs

1//! # Gmail Client Configuration Module
2//!
3//! This module provides configuration management for Gmail API authentication and client setup.
4//! It handles OAuth2 credential loading, configuration parsing, and client initialization
5//! with flexible configuration sources including files, environment variables, and direct parameters.
6//!
7//! ## Overview
8//!
9//! The configuration system supports multiple authentication methods:
10//!
11//! - **File-based OAuth2 credentials**: Load Google Cloud Platform OAuth2 credentials from JSON files
12//! - **Direct configuration**: Set OAuth2 parameters programmatically via builder pattern
13//! - **Mixed configuration**: Combine file-based and programmatic configuration as needed
14//!
15//! ## Configuration Sources
16//!
17//! The module supports hierarchical configuration loading:
18//!
19//! 1. **Direct OAuth2 parameters** (highest priority)
20//! 2. **Credential file** specified via `credential_file` parameter
21//! 3. **Environment variables** via the `config` crate integration
22//!
23//! ## Security Considerations
24//!
25//! - **Credential Storage**: OAuth2 secrets are handled securely and never logged
26//! - **File Permissions**: Credential files should have restricted permissions (600 or similar)
27//! - **Error Handling**: File I/O and parsing errors are propagated with context
28//! - **Token Persistence**: OAuth2 tokens are stored in configurable directories with appropriate permissions
29//!
30//! ## Configuration Directory Structure
31//!
32//! The module supports flexible directory structures:
33//!
34//! ```text
35//! ~/.cull-gmail/                  # Default configuration root
36//! ├── client_secret.json         # OAuth2 credentials
37//! ├── gmail1/                    # OAuth2 token cache
38//! │   ├── tokencache.json        # Cached access/refresh tokens
39//! │   └── ...                    # Other OAuth2 artifacts
40//! └── config.toml                # Application configuration
41//! ```
42//!
43//! ## Path Resolution
44//!
45//! The module supports multiple path resolution schemes:
46//!
47//! - `h:path` - Resolve relative to user's home directory
48//! - `r:path` - Resolve relative to system root directory
49//! - `c:path` - Resolve relative to current working directory
50//! - `path` - Use path as-is (no prefix resolution)
51//!
52//! ## Usage Examples
53//!
54//! ### Builder Pattern with Credential File
55//!
56//! ```rust,no_run
57//! use cull_gmail::ClientConfig;
58//!
59//! let config = ClientConfig::builder()
60//!     .with_credential_file("client_secret.json")
61//!     .with_config_path("~/.cull-gmail")
62//!     .build();
63//! ```
64//!
65//! ### Builder Pattern with Direct OAuth2 Parameters
66//!
67//! ```rust
68//! use cull_gmail::ClientConfig;
69//!
70//! let config = ClientConfig::builder()
71//!     .with_client_id("your-client-id.googleusercontent.com")
72//!     .with_client_secret("your-client-secret")
73//!     .with_auth_uri("https://accounts.google.com/o/oauth2/auth")
74//!     .with_token_uri("https://oauth2.googleapis.com/token")
75//!     .add_redirect_uri("http://localhost:8080")
76//!     .build();
77//! ```
78//!
79//! ### Configuration from Config File
80//!
81//! ```rust,no_run
82//! use cull_gmail::ClientConfig;
83//! use config::Config;
84//!
85//! let app_config = Config::builder()
86//!     .set_default("credential_file", "client_secret.json")?
87//!     .set_default("config_root", "h:.cull-gmail")?
88//!     .add_source(config::File::with_name("config.toml"))
89//!     .build()?;
90//!
91//! let client_config = ClientConfig::new_from_configuration(app_config)?;
92//! # Ok::<(), Box<dyn std::error::Error>>(())
93//! ```
94//!
95//! ## Integration with Gmail Client
96//!
97//! The configuration integrates seamlessly with the Gmail client:
98//!
99//! ```rust,no_run
100//! use cull_gmail::{ClientConfig, GmailClient};
101//!
102//! # async fn example() -> cull_gmail::Result<()> {
103//! let config = ClientConfig::builder()
104//!     .with_credential_file("client_secret.json")
105//!     .build();
106//!
107//! let client = GmailClient::new_with_config(config).await?;
108//! # Ok(())
109//! # }
110//! ```
111//!
112//! ## Error Handling
113//!
114//! The module uses the crate's unified error type for consistent error handling:
115//!
116//! ```rust,no_run
117//! use cull_gmail::{ClientConfig, Result};
118//! use config::Config;
119//!
120//! fn load_config(app_config: Config) -> Result<ClientConfig> {
121//!     match ClientConfig::new_from_configuration(app_config) {
122//!         Ok(config) => Ok(config),
123//!         Err(e) => {
124//!             eprintln!("Configuration error: {}", e);
125//!             Err(e)
126//!         }
127//!     }
128//! }
129//! ```
130//!
131//! ## Thread Safety
132//!
133//! All configuration types are safe to clone and use across threads. However,
134//! file I/O operations are synchronous and should be performed during application
135//! initialization rather than in performance-critical paths.
136
137use std::{fs, path::PathBuf};
138
139use config::Config;
140use google_gmail1::yup_oauth2::{ApplicationSecret, ConsoleApplicationSecret};
141
142use crate::Result;
143
144mod config_root;
145
146use config_root::ConfigRoot;
147
148/// Gmail client configuration containing OAuth2 credentials and persistence settings.
149///
150/// This struct holds all necessary configuration for Gmail API authentication and client setup,
151/// including OAuth2 application secrets, configuration directory paths, and token persistence settings.
152///
153/// # Fields
154///
155/// The struct contains private fields that are accessed through getter methods to ensure
156/// proper encapsulation and prevent accidental mutation of sensitive configuration data.
157///
158/// # Security
159///
160/// The `secret` field contains sensitive OAuth2 credentials including client secrets.
161/// These values are never logged or exposed in debug output beyond their type information.
162///
163/// # Thread Safety
164///
165/// `ClientConfig` is safe to clone and use across threads. All contained data is either
166/// immutable or safely clonable.
167///
168/// # Examples
169///
170/// ```rust
171/// use cull_gmail::ClientConfig;
172///
173/// // Create configuration with builder pattern
174/// let config = ClientConfig::builder()
175///     .with_client_id("test-client-id")
176///     .with_client_secret("test-secret")
177///     .build();
178///
179/// // Access configuration values
180/// assert_eq!(config.secret().client_id, "test-client-id");
181/// assert!(config.persist_path().contains("gmail1"));
182/// ```
183#[derive(Debug)]
184pub struct ClientConfig {
185    /// OAuth2 application secret containing client credentials and endpoints.
186    /// This field contains sensitive information and should be handled carefully.
187    secret: ApplicationSecret,
188
189    /// Configuration root path resolver for determining base directories.
190    /// Supports multiple path resolution schemes (home, root, current directory).
191    config_root: ConfigRoot,
192
193    /// Full path where OAuth2 tokens should be persisted.
194    /// Typically resolves to something like `~/.cull-gmail/gmail1`.
195    persist_path: String,
196}
197
198impl ClientConfig {
199    /// Creates a new configuration builder for constructing `ClientConfig` instances.
200    ///
201    /// The builder pattern allows for flexible configuration construction with method chaining.
202    /// This is the preferred way to create new configurations as it provides compile-time
203    /// guarantees about required fields and allows for incremental configuration building.
204    ///
205    /// # Returns
206    ///
207    /// A new `ConfigBuilder` instance initialized with sensible defaults.
208    ///
209    /// # Examples
210    ///
211    /// ```rust
212    /// use cull_gmail::ClientConfig;
213    ///
214    /// let config = ClientConfig::builder()
215    ///     .with_client_id("your-client-id")
216    ///     .with_client_secret("your-secret")
217    ///     .build();
218    /// ```
219    pub fn builder() -> ConfigBuilder {
220        ConfigBuilder::default()
221    }
222
223    /// Creates a new `ClientConfig` from an external configuration source.
224    ///
225    /// This method supports hierarchical configuration loading with the following priority:
226    /// 1. Direct OAuth2 parameters (`client_id`, `client_secret`, `token_uri`, `auth_uri`)
227    /// 2. Credential file specified via `credential_file` parameter
228    ///
229    /// # Configuration Parameters
230    ///
231    /// ## Required Parameters (one of these sets):
232    ///
233    /// **Direct OAuth2 Configuration:**
234    /// - `client_id`: OAuth2 client identifier
235    /// - `client_secret`: OAuth2 client secret
236    /// - `token_uri`: Token exchange endpoint URL
237    /// - `auth_uri`: Authorization endpoint URL
238    ///
239    /// **OR**
240    ///
241    /// **File-based Configuration:**
242    /// - `credential_file`: Path to JSON credential file (relative to `config_root`)
243    ///
244    /// ## Always Required:
245    /// - `config_root`: Base directory for configuration files (supports path prefixes)
246    ///
247    /// # Arguments
248    ///
249    /// * `configs` - Configuration object containing OAuth2 and path settings
250    ///
251    /// # Returns
252    ///
253    /// Returns `Ok(ClientConfig)` on successful configuration loading, or an error if:
254    /// - Required configuration parameters are missing
255    /// - Credential file cannot be read or parsed
256    /// - OAuth2 credential structure is invalid
257    ///
258    /// # Errors
259    ///
260    /// This method can return errors for:
261    /// - Missing required configuration keys
262    /// - File I/O errors when reading credential files
263    /// - JSON parsing errors for malformed credential files
264    /// - Invalid OAuth2 credential structure
265    ///
266    /// # Examples
267    ///
268    /// ```rust,no_run
269    /// use cull_gmail::ClientConfig;
270    /// use config::Config;
271    ///
272    /// // Configuration with credential file
273    /// let app_config = Config::builder()
274    ///     .set_default("credential_file", "client_secret.json")?
275    ///     .set_default("config_root", "h:.cull-gmail")?
276    ///     .build()?;
277    ///
278    /// let client_config = ClientConfig::new_from_configuration(app_config)?;
279    /// # Ok::<(), Box<dyn std::error::Error>>(())
280    /// ```
281    ///
282    /// ```rust,no_run
283    /// use cull_gmail::ClientConfig;
284    /// use config::Config;
285    ///
286    /// // Configuration with direct OAuth2 parameters
287    /// let app_config = Config::builder()
288    ///     .set_default("client_id", "your-client-id")?
289    ///     .set_default("client_secret", "your-secret")?
290    ///     .set_default("token_uri", "https://oauth2.googleapis.com/token")?
291    ///     .set_default("auth_uri", "https://accounts.google.com/o/oauth2/auth")?
292    ///     .set_default("config_root", "h:.cull-gmail")?
293    ///     .build()?;
294    ///
295    /// let client_config = ClientConfig::new_from_configuration(app_config)?;
296    /// # Ok::<(), Box<dyn std::error::Error>>(())
297    /// ```
298    pub fn new_from_configuration(configs: Config) -> Result<Self> {
299        let root = configs.get_string("config_root")?;
300        let config_root = ConfigRoot::parse(&root);
301
302        let secret = if let Ok(client_id) = configs.get_string("client_id")
303            && let Ok(client_secret) = configs.get_string("client_secret")
304            && let Ok(token_uri) = configs.get_string("token_uri")
305            && let Ok(auth_uri) = configs.get_string("auth_uri")
306        {
307            ApplicationSecret {
308                client_id,
309                client_secret,
310                token_uri,
311                auth_uri,
312                project_id: None,
313                redirect_uris: Vec::new(),
314                client_email: None,
315                auth_provider_x509_cert_url: None,
316                client_x509_cert_url: None,
317            }
318        } else {
319            let credential_file = configs.get_string("credential_file")?;
320            log::info!("root: {config_root}");
321            let path = config_root.full_path().join(credential_file);
322            log::info!("path: {}", path.display());
323            let json_str = fs::read_to_string(path).expect("could not read path");
324
325            let console: ConsoleApplicationSecret =
326                serde_json::from_str(&json_str).expect("could not convert to struct");
327
328            console.installed.unwrap()
329        };
330
331        let persist_path = format!("{}/gmail1", config_root.full_path().display());
332
333        Ok(ClientConfig {
334            config_root,
335            secret,
336            persist_path,
337        })
338    }
339
340    /// Returns a reference to the OAuth2 application secret.
341    ///
342    /// This provides access to the OAuth2 credentials including client ID, client secret,
343    /// and endpoint URLs required for Gmail API authentication.
344    ///
345    /// # Security Note
346    ///
347    /// The returned `ApplicationSecret` contains sensitive information including the
348    /// OAuth2 client secret. Handle this data carefully and avoid logging or exposing it.
349    ///
350    /// # Examples
351    ///
352    /// ```rust
353    /// use cull_gmail::ClientConfig;
354    ///
355    /// let config = ClientConfig::builder()
356    ///     .with_client_id("test-client-id")
357    ///     .build();
358    ///
359    /// let secret = config.secret();
360    /// assert_eq!(secret.client_id, "test-client-id");
361    /// ```
362    pub fn secret(&self) -> &ApplicationSecret {
363        &self.secret
364    }
365
366    /// Returns the full path where OAuth2 tokens should be persisted.
367    ///
368    /// This path is used by the OAuth2 library to store and retrieve cached tokens,
369    /// enabling automatic token refresh without requiring user re-authentication.
370    ///
371    /// # Path Format
372    ///
373    /// The path typically follows the pattern: `{config_root}/gmail1`
374    ///
375    /// For example:
376    /// - `~/.cull-gmail/gmail1` (when config_root is `h:.cull-gmail`)
377    /// - `/etc/cull-gmail/gmail1` (when config_root is `r:etc/cull-gmail`)
378    ///
379    /// # Examples
380    ///
381    /// ```rust
382    /// use cull_gmail::ClientConfig;
383    ///
384    /// let config = ClientConfig::builder().build();
385    /// let persist_path = config.persist_path();
386    /// assert!(persist_path.contains("gmail1"));
387    /// ```
388    pub fn persist_path(&self) -> &str {
389        &self.persist_path
390    }
391
392    /// Returns a reference to the configuration root path resolver.
393    ///
394    /// The `ConfigRoot` handles path resolution with support for different base directories
395    /// including home directory, system root, and current working directory.
396    ///
397    /// # Examples
398    ///
399    /// ```rust
400    /// use cull_gmail::ClientConfig;
401    ///
402    /// let config = ClientConfig::builder()
403    ///     .with_config_path(".cull-gmail")
404    ///     .build();
405    ///
406    /// let config_root = config.config_root();
407    /// // config_root can be used to resolve additional paths
408    /// ```
409    pub fn config_root(&self) -> &ConfigRoot {
410        &self.config_root
411    }
412
413    /// Returns the fully resolved configuration directory path as a string.
414    ///
415    /// This method resolves the configuration root path to an absolute path string,
416    /// applying any path prefix resolution (home directory, system root, etc.).
417    ///
418    /// # Examples
419    ///
420    /// ```rust
421    /// use cull_gmail::ClientConfig;
422    ///
423    /// let config = ClientConfig::builder()
424    ///     .with_config_path(".cull-gmail")
425    ///     .build();
426    ///
427    /// let full_path = config.full_path();
428    /// // Returns the absolute path to the configuration directory
429    /// ```
430    pub fn full_path(&self) -> String {
431        self.config_root.full_path().display().to_string()
432    }
433}
434
435/// Builder for constructing `ClientConfig` instances with flexible configuration options.
436///
437/// The `ConfigBuilder` provides a fluent interface for constructing Gmail client configurations
438/// with support for both file-based and programmatic OAuth2 credential setup. It implements
439/// the builder pattern to ensure required configuration is provided while allowing optional
440/// parameters to be set incrementally.
441///
442/// # Configuration Methods
443///
444/// The builder supports two primary configuration approaches:
445///
446/// 1. **File-based configuration**: Load OAuth2 credentials from JSON files
447/// 2. **Direct configuration**: Set OAuth2 parameters programmatically
448///
449/// # Thread Safety
450///
451/// The builder is not thread-safe and should be used to construct configurations
452/// in a single-threaded context. The resulting `ClientConfig` instances are thread-safe.
453///
454/// # Examples
455///
456/// ## File-based Configuration
457///
458/// ```rust,no_run
459/// use cull_gmail::ClientConfig;
460///
461/// let config = ClientConfig::builder()
462///     .with_credential_file("client_secret.json")
463///     .with_config_path(".cull-gmail")
464///     .build();
465/// ```
466///
467/// ## Direct OAuth2 Configuration
468///
469/// ```rust
470/// use cull_gmail::ClientConfig;
471///
472/// let config = ClientConfig::builder()
473///     .with_client_id("your-client-id.googleusercontent.com")
474///     .with_client_secret("your-client-secret")
475///     .with_auth_uri("https://accounts.google.com/o/oauth2/auth")
476///     .with_token_uri("https://oauth2.googleapis.com/token")
477///     .add_redirect_uri("http://localhost:8080")
478///     .with_project_id("your-project-id")
479///     .build();
480/// ```
481///
482/// ## Mixed Configuration
483///
484/// ```rust,no_run
485/// use cull_gmail::ClientConfig;
486///
487/// let config = ClientConfig::builder()
488///     .with_credential_file("base_credentials.json")
489///     .add_redirect_uri("http://localhost:3000")  // Additional redirect URI
490///     .with_project_id("override-project-id")    // Override from file
491///     .build();
492/// ```
493#[derive(Debug)]
494pub struct ConfigBuilder {
495    /// OAuth2 application secret being constructed.
496    /// Contains client credentials, endpoints, and additional parameters.
497    secret: ApplicationSecret,
498
499    /// Configuration root path resolver for determining base directories.
500    /// Used to resolve relative paths in credential files and token storage.
501    config_root: ConfigRoot,
502}
503
504impl Default for ConfigBuilder {
505    /// Creates a new `ConfigBuilder` with sensible OAuth2 defaults.
506    ///
507    /// The default configuration includes:
508    /// - Standard Google OAuth2 endpoints (auth_uri, token_uri)
509    /// - Empty client credentials (must be set before use)
510    /// - Default configuration root (no path prefix)
511    ///
512    /// # Note
513    ///
514    /// The default instance requires additional configuration before it can be used
515    /// to create a functional `ClientConfig`. At minimum, you must set either:
516    /// - Client credentials via `with_client_id()` and `with_client_secret()`, or
517    /// - A credential file via `with_credential_file()`
518    fn default() -> Self {
519        let secret = ApplicationSecret {
520            auth_uri: "https://accounts.google.com/o/oauth2/auth".to_string(),
521            token_uri: "https://oauth2.googleapis.com/token".to_string(),
522            ..Default::default()
523        };
524
525        Self {
526            secret,
527            config_root: Default::default(),
528        }
529    }
530}
531
532impl ConfigBuilder {
533    pub fn with_config_base(&mut self, value: &config_root::RootBase) -> &mut Self {
534        self.config_root.set_root_base(value);
535        self
536    }
537
538    pub fn with_config_path(&mut self, value: &str) -> &mut Self {
539        self.config_root.set_path(value);
540        self
541    }
542
543    pub fn with_credential_file(&mut self, credential_file: &str) -> &mut Self {
544        let path = PathBuf::from(self.config_root.to_string()).join(credential_file);
545        log::info!("path: {}", path.display());
546        let json_str = fs::read_to_string(path).expect("could not read path");
547
548        let console: ConsoleApplicationSecret =
549            serde_json::from_str(&json_str).expect("could not convert to struct");
550
551        self.secret = console.installed.unwrap();
552        self
553    }
554
555    pub fn with_client_id(&mut self, value: &str) -> &mut Self {
556        self.secret.client_id = value.to_string();
557        self
558    }
559
560    pub fn with_client_secret(&mut self, value: &str) -> &mut Self {
561        self.secret.client_secret = value.to_string();
562        self
563    }
564
565    pub fn with_token_uri(&mut self, value: &str) -> &mut Self {
566        self.secret.token_uri = value.to_string();
567        self
568    }
569
570    pub fn with_auth_uri(&mut self, value: &str) -> &mut Self {
571        self.secret.auth_uri = value.to_string();
572        self
573    }
574
575    pub fn add_redirect_uri(&mut self, value: &str) -> &mut Self {
576        self.secret.redirect_uris.push(value.to_string());
577        self
578    }
579
580    pub fn with_project_id(&mut self, value: &str) -> &mut Self {
581        self.secret.project_id = Some(value.to_string());
582        self
583    }
584
585    pub fn with_client_email(&mut self, value: &str) -> &mut Self {
586        self.secret.client_email = Some(value.to_string());
587        self
588    }
589    pub fn with_auth_provider_x509_cert_url(&mut self, value: &str) -> &mut Self {
590        self.secret.auth_provider_x509_cert_url = Some(value.to_string());
591        self
592    }
593    pub fn with_client_x509_cert_url(&mut self, value: &str) -> &mut Self {
594        self.secret.client_x509_cert_url = Some(value.to_string());
595        self
596    }
597
598    fn full_path(&self) -> String {
599        self.config_root.full_path().display().to_string()
600    }
601
602    pub fn build(&self) -> ClientConfig {
603        let persist_path = format!("{}/gmail1", self.full_path());
604
605        ClientConfig {
606            secret: self.secret.clone(),
607            config_root: self.config_root.clone(),
608            persist_path,
609        }
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use crate::test_utils::get_test_logger;
617    use config::Config;
618    use std::env;
619    use std::fs;
620    use tempfile::TempDir;
621
622    /// Helper function to create a temporary credential file for testing
623    fn create_test_credential_file(temp_dir: &TempDir, filename: &str, content: &str) -> String {
624        let file_path = temp_dir.path().join(filename);
625        fs::write(&file_path, content).expect("Failed to write test file");
626        file_path.to_string_lossy().to_string()
627    }
628
629    /// Sample valid OAuth2 credential JSON for testing
630    fn sample_valid_credential() -> &'static str {
631        r#"{
632  "installed": {
633    "client_id": "123456789-test.googleusercontent.com",
634    "project_id": "test-project",
635    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
636    "token_uri": "https://oauth2.googleapis.com/token",
637    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
638    "client_secret": "test-client-secret",
639    "redirect_uris": ["http://localhost"]
640  }
641}"#
642    }
643
644    #[test]
645    fn test_config_builder_defaults() {
646        let builder = ConfigBuilder::default();
647
648        assert_eq!(
649            builder.secret.auth_uri,
650            "https://accounts.google.com/o/oauth2/auth"
651        );
652        assert_eq!(
653            builder.secret.token_uri,
654            "https://oauth2.googleapis.com/token"
655        );
656        assert!(builder.secret.client_id.is_empty());
657        assert!(builder.secret.client_secret.is_empty());
658    }
659
660    #[test]
661    fn test_builder_pattern_direct_oauth2() {
662        let config = ClientConfig::builder()
663            .with_client_id("test-client-id")
664            .with_client_secret("test-client-secret")
665            .with_auth_uri("https://auth.example.com")
666            .with_token_uri("https://token.example.com")
667            .add_redirect_uri("http://localhost:8080")
668            .add_redirect_uri("http://localhost:3000")
669            .with_project_id("test-project")
670            .with_client_email("test@example.com")
671            .with_auth_provider_x509_cert_url("https://certs.example.com")
672            .with_client_x509_cert_url("https://client-cert.example.com")
673            .build();
674
675        assert_eq!(config.secret().client_id, "test-client-id");
676        assert_eq!(config.secret().client_secret, "test-client-secret");
677        assert_eq!(config.secret().auth_uri, "https://auth.example.com");
678        assert_eq!(config.secret().token_uri, "https://token.example.com");
679        assert_eq!(
680            config.secret().redirect_uris,
681            vec!["http://localhost:8080", "http://localhost:3000"]
682        );
683        assert_eq!(config.secret().project_id, Some("test-project".to_string()));
684        assert_eq!(
685            config.secret().client_email,
686            Some("test@example.com".to_string())
687        );
688        assert_eq!(
689            config.secret().auth_provider_x509_cert_url,
690            Some("https://certs.example.com".to_string())
691        );
692        assert_eq!(
693            config.secret().client_x509_cert_url,
694            Some("https://client-cert.example.com".to_string())
695        );
696        assert!(config.persist_path().contains("gmail1"));
697    }
698
699    #[test]
700    fn test_builder_with_config_path() {
701        let config = ClientConfig::builder()
702            .with_client_id("test-id")
703            .with_config_path(".test-config")
704            .build();
705
706        let full_path = config.full_path();
707        assert_eq!(full_path, ".test-config");
708        assert!(config.persist_path().contains(".test-config/gmail1"));
709    }
710
711    #[test]
712    fn test_builder_with_config_base_home() {
713        let config = ClientConfig::builder()
714            .with_client_id("test-id")
715            .with_config_base(&config_root::RootBase::Home)
716            .with_config_path(".test-config")
717            .build();
718
719        let expected_path = env::home_dir()
720            .unwrap_or_default()
721            .join(".test-config")
722            .display()
723            .to_string();
724
725        assert_eq!(config.full_path(), expected_path);
726    }
727
728    #[test]
729    fn test_builder_with_config_base_root() {
730        let config = ClientConfig::builder()
731            .with_client_id("test-id")
732            .with_config_base(&config_root::RootBase::Root)
733            .with_config_path("etc/test-config")
734            .build();
735
736        assert_eq!(config.full_path(), "/etc/test-config");
737    }
738
739    #[test]
740    fn test_config_from_direct_oauth2_params() {
741        let app_config = Config::builder()
742            .set_default("client_id", "direct-client-id")
743            .unwrap()
744            .set_default("client_secret", "direct-client-secret")
745            .unwrap()
746            .set_default("token_uri", "https://token.direct.com")
747            .unwrap()
748            .set_default("auth_uri", "https://auth.direct.com")
749            .unwrap()
750            .set_default("config_root", "h:.test-direct")
751            .unwrap()
752            .build()
753            .unwrap();
754
755        let config = ClientConfig::new_from_configuration(app_config).unwrap();
756
757        assert_eq!(config.secret().client_id, "direct-client-id");
758        assert_eq!(config.secret().client_secret, "direct-client-secret");
759        assert_eq!(config.secret().token_uri, "https://token.direct.com");
760        assert_eq!(config.secret().auth_uri, "https://auth.direct.com");
761        assert_eq!(config.secret().project_id, None);
762        assert!(config.secret().redirect_uris.is_empty());
763    }
764
765    #[test]
766    fn test_config_from_credential_file() {
767        get_test_logger();
768        let temp_dir = TempDir::new().expect("Failed to create temp dir");
769        let _cred_file =
770            create_test_credential_file(&temp_dir, "test_creds.json", sample_valid_credential());
771
772        let config_root = format!("c:{}", temp_dir.path().display());
773        let app_config = Config::builder()
774            .set_default("credential_file", "test_creds.json")
775            .unwrap()
776            .set_default("config_root", config_root.as_str())
777            .unwrap()
778            .build()
779            .unwrap();
780
781        let config = ClientConfig::new_from_configuration(app_config).unwrap();
782
783        assert_eq!(
784            config.secret().client_id,
785            "123456789-test.googleusercontent.com"
786        );
787        assert_eq!(config.secret().client_secret, "test-client-secret");
788        assert_eq!(config.secret().project_id, Some("test-project".to_string()));
789        assert_eq!(config.secret().redirect_uris, vec!["http://localhost"]);
790    }
791
792    #[test]
793    fn test_config_missing_required_params() {
794        // Test with missing config_root
795        let app_config = Config::builder()
796            .set_default("client_id", "test-id")
797            .unwrap()
798            .build()
799            .unwrap();
800
801        let result = ClientConfig::new_from_configuration(app_config);
802        assert!(result.is_err());
803    }
804
805    #[test]
806    fn test_config_incomplete_oauth2_params() {
807        // Test with some but not all OAuth2 parameters
808        let app_config = Config::builder()
809            .set_default("client_id", "test-id")
810            .unwrap()
811            .set_default("client_secret", "test-secret")
812            .unwrap()
813            // Missing token_uri and auth_uri
814            .set_default("config_root", "h:.test")
815            .unwrap()
816            .build()
817            .unwrap();
818
819        // Should fall back to credential_file approach, which should fail
820        let result = ClientConfig::new_from_configuration(app_config);
821        assert!(result.is_err());
822    }
823
824    #[test]
825    #[should_panic(expected = "could not read path")]
826    fn test_config_invalid_credential_file() {
827        let app_config = Config::builder()
828            .set_default("credential_file", "nonexistent.json")
829            .unwrap()
830            .set_default("config_root", "h:.test")
831            .unwrap()
832            .build()
833            .unwrap();
834
835        // This should panic with "could not read path" since the code uses .expect()
836        let _result = ClientConfig::new_from_configuration(app_config);
837    }
838
839    #[test]
840    #[should_panic(expected = "could not convert to struct")]
841    fn test_config_malformed_credential_file() {
842        get_test_logger();
843        let temp_dir = TempDir::new().expect("Failed to create temp dir");
844        let _cred_file = create_test_credential_file(&temp_dir, "malformed.json", "{ invalid json");
845
846        let config_root = format!("c:{}", temp_dir.path().display());
847        let app_config = Config::builder()
848            .set_default("credential_file", "malformed.json")
849            .unwrap()
850            .set_default("config_root", config_root.as_str())
851            .unwrap()
852            .build()
853            .unwrap();
854
855        // This should panic with "could not convert to struct" since the code uses .expect()
856        let _result = ClientConfig::new_from_configuration(app_config);
857    }
858
859    #[test]
860    #[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
861    fn test_config_credential_file_wrong_structure() {
862        get_test_logger();
863        let temp_dir = TempDir::new().expect("Failed to create temp dir");
864        let wrong_structure = r#"{"wrong": "structure"}"#;
865        let _cred_file = create_test_credential_file(&temp_dir, "wrong.json", wrong_structure);
866
867        let config_root = format!("c:{}", temp_dir.path().display());
868        let app_config = Config::builder()
869            .set_default("credential_file", "wrong.json")
870            .unwrap()
871            .set_default("config_root", config_root.as_str())
872            .unwrap()
873            .build()
874            .unwrap();
875
876        // This should panic with unwrap on None since console.installed is None
877        let _result = ClientConfig::new_from_configuration(app_config);
878    }
879
880    #[test]
881    fn test_persist_path_generation() {
882        let config = ClientConfig::builder()
883            .with_client_id("test")
884            .with_config_path("/custom/path")
885            .build();
886
887        assert_eq!(config.persist_path(), "/custom/path/gmail1");
888    }
889
890    #[test]
891    fn test_config_accessor_methods() {
892        let config = ClientConfig::builder()
893            .with_client_id("accessor-test-id")
894            .with_client_secret("accessor-test-secret")
895            .with_config_path("/test/path")
896            .build();
897
898        // Test secret() accessor
899        let secret = config.secret();
900        assert_eq!(secret.client_id, "accessor-test-id");
901        assert_eq!(secret.client_secret, "accessor-test-secret");
902
903        // Test persist_path() accessor
904        assert_eq!(config.persist_path(), "/test/path/gmail1");
905
906        // Test full_path() accessor
907        assert_eq!(config.full_path(), "/test/path");
908
909        // Test config_root() accessor
910        let config_root = config.config_root();
911        assert_eq!(config_root.full_path().display().to_string(), "/test/path");
912    }
913
914    #[test]
915    fn test_builder_method_chaining() {
916        // Test that all builder methods return &mut Self for chaining
917        let config = ClientConfig::builder()
918            .with_client_id("chain-test")
919            .with_client_secret("chain-secret")
920            .with_auth_uri("https://auth.chain.com")
921            .with_token_uri("https://token.chain.com")
922            .add_redirect_uri("http://redirect1.com")
923            .add_redirect_uri("http://redirect2.com")
924            .with_project_id("chain-project")
925            .with_client_email("chain@test.com")
926            .with_auth_provider_x509_cert_url("https://cert1.com")
927            .with_client_x509_cert_url("https://cert2.com")
928            .with_config_base(&config_root::RootBase::Home)
929            .with_config_path(".chain-test")
930            .build();
931
932        assert_eq!(config.secret().client_id, "chain-test");
933        assert_eq!(config.secret().redirect_uris.len(), 2);
934    }
935
936    #[test]
937    fn test_configuration_priority() {
938        // Test that direct OAuth2 params take priority over credential file
939        get_test_logger();
940        let temp_dir = TempDir::new().expect("Failed to create temp dir");
941        let _cred_file =
942            create_test_credential_file(&temp_dir, "priority.json", sample_valid_credential());
943
944        let config_root = format!("c:{}", temp_dir.path().display());
945        let app_config = Config::builder()
946            // Direct OAuth2 params (should take priority)
947            .set_default("client_id", "priority-client-id")
948            .unwrap()
949            .set_default("client_secret", "priority-client-secret")
950            .unwrap()
951            .set_default("token_uri", "https://priority.token.com")
952            .unwrap()
953            .set_default("auth_uri", "https://priority.auth.com")
954            .unwrap()
955            // Credential file (should be ignored)
956            .set_default("credential_file", "priority.json")
957            .unwrap()
958            .set_default("config_root", config_root.as_str())
959            .unwrap()
960            .build()
961            .unwrap();
962
963        let config = ClientConfig::new_from_configuration(app_config).unwrap();
964
965        // Should use direct params, not file contents
966        assert_eq!(config.secret().client_id, "priority-client-id");
967        assert_eq!(config.secret().client_secret, "priority-client-secret");
968        assert_eq!(config.secret().token_uri, "https://priority.token.com");
969        assert_ne!(
970            config.secret().client_id,
971            "123456789-test.googleusercontent.com"
972        ); // From file
973    }
974
975    #[test]
976    fn test_empty_redirect_uris() {
977        let config = ClientConfig::builder().with_client_id("test-id").build();
978
979        assert!(config.secret().redirect_uris.is_empty());
980    }
981
982    #[test]
983    fn test_multiple_redirect_uris() {
984        let config = ClientConfig::builder()
985            .with_client_id("test-id")
986            .add_redirect_uri("http://localhost:8080")
987            .add_redirect_uri("http://localhost:3000")
988            .add_redirect_uri("https://example.com/callback")
989            .build();
990
991        assert_eq!(config.secret().redirect_uris.len(), 3);
992        assert!(
993            config
994                .secret()
995                .redirect_uris
996                .contains(&"http://localhost:8080".to_string())
997        );
998        assert!(
999            config
1000                .secret()
1001                .redirect_uris
1002                .contains(&"http://localhost:3000".to_string())
1003        );
1004        assert!(
1005            config
1006                .secret()
1007                .redirect_uris
1008                .contains(&"https://example.com/callback".to_string())
1009        );
1010    }
1011
1012    #[test]
1013    fn test_optional_fields() {
1014        let config = ClientConfig::builder()
1015            .with_client_id("optional-test")
1016            .build();
1017
1018        assert_eq!(config.secret().project_id, None);
1019        assert_eq!(config.secret().client_email, None);
1020        assert_eq!(config.secret().auth_provider_x509_cert_url, None);
1021        assert_eq!(config.secret().client_x509_cert_url, None);
1022    }
1023
1024    #[test]
1025    fn test_unicode_in_configuration() {
1026        let config = ClientConfig::builder()
1027            .with_client_id("unicode-客戶端-🔐-test")
1028            .with_client_secret("secret-with-unicode-密碼")
1029            .with_project_id("project-項目-id")
1030            .with_config_path(".unicode-配置")
1031            .build();
1032
1033        assert_eq!(config.secret().client_id, "unicode-客戶端-🔐-test");
1034        assert_eq!(config.secret().client_secret, "secret-with-unicode-密碼");
1035        assert_eq!(
1036            config.secret().project_id,
1037            Some("project-項目-id".to_string())
1038        );
1039        assert!(config.full_path().contains(".unicode-配置"));
1040    }
1041}