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 log::info!("Configs are: {configs:?}");
303
304 let secret = if let Ok(client_id) = configs.get_string("client_id")
305 && let Ok(client_secret) = configs.get_string("client_secret")
306 && let Ok(token_uri) = configs.get_string("token_uri")
307 && let Ok(auth_uri) = configs.get_string("auth_uri")
308 {
309 ApplicationSecret {
310 client_id,
311 client_secret,
312 token_uri,
313 auth_uri,
314 project_id: None,
315 redirect_uris: Vec::new(),
316 client_email: None,
317 auth_provider_x509_cert_url: None,
318 client_x509_cert_url: None,
319 }
320 } else {
321 let credential_file = configs.get_string("credential_file")?;
322 log::info!("root: {config_root}");
323 let path = config_root.full_path().join(credential_file);
324 log::info!("path: {}", path.display());
325 let json_str = fs::read_to_string(path).expect("could not read path");
326
327 let console: ConsoleApplicationSecret =
328 serde_json::from_str(&json_str).expect("could not convert to struct");
329
330 console.installed.unwrap()
331 };
332
333 let persist_path = format!("{}/gmail1", config_root.full_path().display());
334
335 Ok(ClientConfig {
336 config_root,
337 secret,
338 persist_path,
339 })
340 }
341
342 /// Returns a reference to the OAuth2 application secret.
343 ///
344 /// This provides access to the OAuth2 credentials including client ID, client secret,
345 /// and endpoint URLs required for Gmail API authentication.
346 ///
347 /// # Security Note
348 ///
349 /// The returned `ApplicationSecret` contains sensitive information including the
350 /// OAuth2 client secret. Handle this data carefully and avoid logging or exposing it.
351 ///
352 /// # Examples
353 ///
354 /// ```rust
355 /// use cull_gmail::ClientConfig;
356 ///
357 /// let config = ClientConfig::builder()
358 /// .with_client_id("test-client-id")
359 /// .build();
360 ///
361 /// let secret = config.secret();
362 /// assert_eq!(secret.client_id, "test-client-id");
363 /// ```
364 pub fn secret(&self) -> &ApplicationSecret {
365 &self.secret
366 }
367
368 /// Returns the full path where OAuth2 tokens should be persisted.
369 ///
370 /// This path is used by the OAuth2 library to store and retrieve cached tokens,
371 /// enabling automatic token refresh without requiring user re-authentication.
372 ///
373 /// # Path Format
374 ///
375 /// The path typically follows the pattern: `{config_root}/gmail1`
376 ///
377 /// For example:
378 /// - `~/.cull-gmail/gmail1` (when config_root is `h:.cull-gmail`)
379 /// - `/etc/cull-gmail/gmail1` (when config_root is `r:etc/cull-gmail`)
380 ///
381 /// # Examples
382 ///
383 /// ```rust
384 /// use cull_gmail::ClientConfig;
385 ///
386 /// let config = ClientConfig::builder().build();
387 /// let persist_path = config.persist_path();
388 /// assert!(persist_path.contains("gmail1"));
389 /// ```
390 pub fn persist_path(&self) -> &str {
391 &self.persist_path
392 }
393
394 /// Returns a reference to the configuration root path resolver.
395 ///
396 /// The `ConfigRoot` handles path resolution with support for different base directories
397 /// including home directory, system root, and current working directory.
398 ///
399 /// # Examples
400 ///
401 /// ```rust
402 /// use cull_gmail::ClientConfig;
403 ///
404 /// let config = ClientConfig::builder()
405 /// .with_config_path(".cull-gmail")
406 /// .build();
407 ///
408 /// let config_root = config.config_root();
409 /// // config_root can be used to resolve additional paths
410 /// ```
411 pub fn config_root(&self) -> &ConfigRoot {
412 &self.config_root
413 }
414
415 /// Returns the fully resolved configuration directory path as a string.
416 ///
417 /// This method resolves the configuration root path to an absolute path string,
418 /// applying any path prefix resolution (home directory, system root, etc.).
419 ///
420 /// # Examples
421 ///
422 /// ```rust
423 /// use cull_gmail::ClientConfig;
424 ///
425 /// let config = ClientConfig::builder()
426 /// .with_config_path(".cull-gmail")
427 /// .build();
428 ///
429 /// let full_path = config.full_path();
430 /// // Returns the absolute path to the configuration directory
431 /// ```
432 pub fn full_path(&self) -> String {
433 self.config_root.full_path().display().to_string()
434 }
435}
436
437/// Builder for constructing `ClientConfig` instances with flexible configuration options.
438///
439/// The `ConfigBuilder` provides a fluent interface for constructing Gmail client configurations
440/// with support for both file-based and programmatic OAuth2 credential setup. It implements
441/// the builder pattern to ensure required configuration is provided while allowing optional
442/// parameters to be set incrementally.
443///
444/// # Configuration Methods
445///
446/// The builder supports two primary configuration approaches:
447///
448/// 1. **File-based configuration**: Load OAuth2 credentials from JSON files
449/// 2. **Direct configuration**: Set OAuth2 parameters programmatically
450///
451/// # Thread Safety
452///
453/// The builder is not thread-safe and should be used to construct configurations
454/// in a single-threaded context. The resulting `ClientConfig` instances are thread-safe.
455///
456/// # Examples
457///
458/// ## File-based Configuration
459///
460/// ```rust,no_run
461/// use cull_gmail::ClientConfig;
462///
463/// let config = ClientConfig::builder()
464/// .with_credential_file("client_secret.json")
465/// .with_config_path(".cull-gmail")
466/// .build();
467/// ```
468///
469/// ## Direct OAuth2 Configuration
470///
471/// ```rust
472/// use cull_gmail::ClientConfig;
473///
474/// let config = ClientConfig::builder()
475/// .with_client_id("your-client-id.googleusercontent.com")
476/// .with_client_secret("your-client-secret")
477/// .with_auth_uri("https://accounts.google.com/o/oauth2/auth")
478/// .with_token_uri("https://oauth2.googleapis.com/token")
479/// .add_redirect_uri("http://localhost:8080")
480/// .with_project_id("your-project-id")
481/// .build();
482/// ```
483///
484/// ## Mixed Configuration
485///
486/// ```rust,no_run
487/// use cull_gmail::ClientConfig;
488///
489/// let config = ClientConfig::builder()
490/// .with_credential_file("base_credentials.json")
491/// .add_redirect_uri("http://localhost:3000") // Additional redirect URI
492/// .with_project_id("override-project-id") // Override from file
493/// .build();
494/// ```
495#[derive(Debug)]
496pub struct ConfigBuilder {
497 /// OAuth2 application secret being constructed.
498 /// Contains client credentials, endpoints, and additional parameters.
499 secret: ApplicationSecret,
500
501 /// Configuration root path resolver for determining base directories.
502 /// Used to resolve relative paths in credential files and token storage.
503 config_root: ConfigRoot,
504}
505
506impl Default for ConfigBuilder {
507 /// Creates a new `ConfigBuilder` with sensible OAuth2 defaults.
508 ///
509 /// The default configuration includes:
510 /// - Standard Google OAuth2 endpoints (auth_uri, token_uri)
511 /// - Empty client credentials (must be set before use)
512 /// - Default configuration root (no path prefix)
513 ///
514 /// # Note
515 ///
516 /// The default instance requires additional configuration before it can be used
517 /// to create a functional `ClientConfig`. At minimum, you must set either:
518 /// - Client credentials via `with_client_id()` and `with_client_secret()`, or
519 /// - A credential file via `with_credential_file()`
520 fn default() -> Self {
521 let secret = ApplicationSecret {
522 auth_uri: "https://accounts.google.com/o/oauth2/auth".to_string(),
523 token_uri: "https://oauth2.googleapis.com/token".to_string(),
524 ..Default::default()
525 };
526
527 Self {
528 secret,
529 config_root: Default::default(),
530 }
531 }
532}
533
534impl ConfigBuilder {
535 pub fn with_config_base(&mut self, value: &config_root::RootBase) -> &mut Self {
536 self.config_root.set_root_base(value);
537 self
538 }
539
540 pub fn with_config_path(&mut self, value: &str) -> &mut Self {
541 self.config_root.set_path(value);
542 self
543 }
544
545 pub fn with_credential_file(&mut self, credential_file: &str) -> &mut Self {
546 let path = PathBuf::from(self.config_root.to_string()).join(credential_file);
547 log::info!("path: {}", path.display());
548 let json_str = fs::read_to_string(path).expect("could not read path");
549
550 let console: ConsoleApplicationSecret =
551 serde_json::from_str(&json_str).expect("could not convert to struct");
552
553 self.secret = console.installed.unwrap();
554 self
555 }
556
557 pub fn with_client_id(&mut self, value: &str) -> &mut Self {
558 self.secret.client_id = value.to_string();
559 self
560 }
561
562 pub fn with_client_secret(&mut self, value: &str) -> &mut Self {
563 self.secret.client_secret = value.to_string();
564 self
565 }
566
567 pub fn with_token_uri(&mut self, value: &str) -> &mut Self {
568 self.secret.token_uri = value.to_string();
569 self
570 }
571
572 pub fn with_auth_uri(&mut self, value: &str) -> &mut Self {
573 self.secret.auth_uri = value.to_string();
574 self
575 }
576
577 pub fn add_redirect_uri(&mut self, value: &str) -> &mut Self {
578 self.secret.redirect_uris.push(value.to_string());
579 self
580 }
581
582 pub fn with_project_id(&mut self, value: &str) -> &mut Self {
583 self.secret.project_id = Some(value.to_string());
584 self
585 }
586
587 pub fn with_client_email(&mut self, value: &str) -> &mut Self {
588 self.secret.client_email = Some(value.to_string());
589 self
590 }
591 pub fn with_auth_provider_x509_cert_url(&mut self, value: &str) -> &mut Self {
592 self.secret.auth_provider_x509_cert_url = Some(value.to_string());
593 self
594 }
595 pub fn with_client_x509_cert_url(&mut self, value: &str) -> &mut Self {
596 self.secret.client_x509_cert_url = Some(value.to_string());
597 self
598 }
599
600 fn full_path(&self) -> String {
601 self.config_root.full_path().display().to_string()
602 }
603
604 pub fn build(&self) -> ClientConfig {
605 let persist_path = format!("{}/gmail1", self.full_path());
606
607 ClientConfig {
608 secret: self.secret.clone(),
609 config_root: self.config_root.clone(),
610 persist_path,
611 }
612 }
613}
614
615#[cfg(test)]
616mod tests {
617 use super::*;
618 use crate::test_utils::get_test_logger;
619 use config::Config;
620 use std::env;
621 use std::fs;
622 use tempfile::TempDir;
623
624 /// Helper function to create a temporary credential file for testing
625 fn create_test_credential_file(temp_dir: &TempDir, filename: &str, content: &str) -> String {
626 let file_path = temp_dir.path().join(filename);
627 fs::write(&file_path, content).expect("Failed to write test file");
628 file_path.to_string_lossy().to_string()
629 }
630
631 /// Sample valid OAuth2 credential JSON for testing
632 fn sample_valid_credential() -> &'static str {
633 r#"{
634 "installed": {
635 "client_id": "123456789-test.googleusercontent.com",
636 "project_id": "test-project",
637 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
638 "token_uri": "https://oauth2.googleapis.com/token",
639 "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
640 "client_secret": "test-client-secret",
641 "redirect_uris": ["http://localhost"]
642 }
643}"#
644 }
645
646 #[test]
647 fn test_config_builder_defaults() {
648 let builder = ConfigBuilder::default();
649
650 assert_eq!(
651 builder.secret.auth_uri,
652 "https://accounts.google.com/o/oauth2/auth"
653 );
654 assert_eq!(
655 builder.secret.token_uri,
656 "https://oauth2.googleapis.com/token"
657 );
658 assert!(builder.secret.client_id.is_empty());
659 assert!(builder.secret.client_secret.is_empty());
660 }
661
662 #[test]
663 fn test_builder_pattern_direct_oauth2() {
664 let config = ClientConfig::builder()
665 .with_client_id("test-client-id")
666 .with_client_secret("test-client-secret")
667 .with_auth_uri("https://auth.example.com")
668 .with_token_uri("https://token.example.com")
669 .add_redirect_uri("http://localhost:8080")
670 .add_redirect_uri("http://localhost:3000")
671 .with_project_id("test-project")
672 .with_client_email("test@example.com")
673 .with_auth_provider_x509_cert_url("https://certs.example.com")
674 .with_client_x509_cert_url("https://client-cert.example.com")
675 .build();
676
677 assert_eq!(config.secret().client_id, "test-client-id");
678 assert_eq!(config.secret().client_secret, "test-client-secret");
679 assert_eq!(config.secret().auth_uri, "https://auth.example.com");
680 assert_eq!(config.secret().token_uri, "https://token.example.com");
681 assert_eq!(
682 config.secret().redirect_uris,
683 vec!["http://localhost:8080", "http://localhost:3000"]
684 );
685 assert_eq!(config.secret().project_id, Some("test-project".to_string()));
686 assert_eq!(
687 config.secret().client_email,
688 Some("test@example.com".to_string())
689 );
690 assert_eq!(
691 config.secret().auth_provider_x509_cert_url,
692 Some("https://certs.example.com".to_string())
693 );
694 assert_eq!(
695 config.secret().client_x509_cert_url,
696 Some("https://client-cert.example.com".to_string())
697 );
698 assert!(config.persist_path().contains("gmail1"));
699 }
700
701 #[test]
702 fn test_builder_with_config_path() {
703 let config = ClientConfig::builder()
704 .with_client_id("test-id")
705 .with_config_path(".test-config")
706 .build();
707
708 let full_path = config.full_path();
709 assert_eq!(full_path, ".test-config");
710 assert!(config.persist_path().contains(".test-config/gmail1"));
711 }
712
713 #[test]
714 fn test_builder_with_config_base_home() {
715 let config = ClientConfig::builder()
716 .with_client_id("test-id")
717 .with_config_base(&config_root::RootBase::Home)
718 .with_config_path(".test-config")
719 .build();
720
721 let expected_path = env::home_dir()
722 .unwrap_or_default()
723 .join(".test-config")
724 .display()
725 .to_string();
726
727 assert_eq!(config.full_path(), expected_path);
728 }
729
730 #[test]
731 fn test_builder_with_config_base_root() {
732 let config = ClientConfig::builder()
733 .with_client_id("test-id")
734 .with_config_base(&config_root::RootBase::Root)
735 .with_config_path("etc/test-config")
736 .build();
737
738 assert_eq!(config.full_path(), "/etc/test-config");
739 }
740
741 #[test]
742 fn test_config_from_direct_oauth2_params() {
743 let app_config = Config::builder()
744 .set_default("client_id", "direct-client-id")
745 .unwrap()
746 .set_default("client_secret", "direct-client-secret")
747 .unwrap()
748 .set_default("token_uri", "https://token.direct.com")
749 .unwrap()
750 .set_default("auth_uri", "https://auth.direct.com")
751 .unwrap()
752 .set_default("config_root", "h:.test-direct")
753 .unwrap()
754 .build()
755 .unwrap();
756
757 let config = ClientConfig::new_from_configuration(app_config).unwrap();
758
759 assert_eq!(config.secret().client_id, "direct-client-id");
760 assert_eq!(config.secret().client_secret, "direct-client-secret");
761 assert_eq!(config.secret().token_uri, "https://token.direct.com");
762 assert_eq!(config.secret().auth_uri, "https://auth.direct.com");
763 assert_eq!(config.secret().project_id, None);
764 assert!(config.secret().redirect_uris.is_empty());
765 }
766
767 #[test]
768 fn test_config_from_credential_file() {
769 get_test_logger();
770 let temp_dir = TempDir::new().expect("Failed to create temp dir");
771 let _cred_file =
772 create_test_credential_file(&temp_dir, "test_creds.json", sample_valid_credential());
773
774 let config_root = format!("c:{}", temp_dir.path().display());
775 let app_config = Config::builder()
776 .set_default("credential_file", "test_creds.json")
777 .unwrap()
778 .set_default("config_root", config_root.as_str())
779 .unwrap()
780 .build()
781 .unwrap();
782
783 let config = ClientConfig::new_from_configuration(app_config).unwrap();
784
785 assert_eq!(
786 config.secret().client_id,
787 "123456789-test.googleusercontent.com"
788 );
789 assert_eq!(config.secret().client_secret, "test-client-secret");
790 assert_eq!(config.secret().project_id, Some("test-project".to_string()));
791 assert_eq!(config.secret().redirect_uris, vec!["http://localhost"]);
792 }
793
794 #[test]
795 fn test_config_missing_required_params() {
796 // Test with missing config_root
797 let app_config = Config::builder()
798 .set_default("client_id", "test-id")
799 .unwrap()
800 .build()
801 .unwrap();
802
803 let result = ClientConfig::new_from_configuration(app_config);
804 assert!(result.is_err());
805 }
806
807 #[test]
808 fn test_config_incomplete_oauth2_params() {
809 // Test with some but not all OAuth2 parameters
810 let app_config = Config::builder()
811 .set_default("client_id", "test-id")
812 .unwrap()
813 .set_default("client_secret", "test-secret")
814 .unwrap()
815 // Missing token_uri and auth_uri
816 .set_default("config_root", "h:.test")
817 .unwrap()
818 .build()
819 .unwrap();
820
821 // Should fall back to credential_file approach, which should fail
822 let result = ClientConfig::new_from_configuration(app_config);
823 assert!(result.is_err());
824 }
825
826 #[test]
827 #[should_panic(expected = "could not read path")]
828 fn test_config_invalid_credential_file() {
829 let app_config = Config::builder()
830 .set_default("credential_file", "nonexistent.json")
831 .unwrap()
832 .set_default("config_root", "h:.test")
833 .unwrap()
834 .build()
835 .unwrap();
836
837 // This should panic with "could not read path" since the code uses .expect()
838 let _result = ClientConfig::new_from_configuration(app_config);
839 }
840
841 #[test]
842 #[should_panic(expected = "could not convert to struct")]
843 fn test_config_malformed_credential_file() {
844 get_test_logger();
845 let temp_dir = TempDir::new().expect("Failed to create temp dir");
846 let _cred_file = create_test_credential_file(&temp_dir, "malformed.json", "{ invalid json");
847
848 let config_root = format!("c:{}", temp_dir.path().display());
849 let app_config = Config::builder()
850 .set_default("credential_file", "malformed.json")
851 .unwrap()
852 .set_default("config_root", config_root.as_str())
853 .unwrap()
854 .build()
855 .unwrap();
856
857 // This should panic with "could not convert to struct" since the code uses .expect()
858 let _result = ClientConfig::new_from_configuration(app_config);
859 }
860
861 #[test]
862 #[should_panic(expected = "called `Option::unwrap()` on a `None` value")]
863 fn test_config_credential_file_wrong_structure() {
864 get_test_logger();
865 let temp_dir = TempDir::new().expect("Failed to create temp dir");
866 let wrong_structure = r#"{"wrong": "structure"}"#;
867 let _cred_file = create_test_credential_file(&temp_dir, "wrong.json", wrong_structure);
868
869 let config_root = format!("c:{}", temp_dir.path().display());
870 let app_config = Config::builder()
871 .set_default("credential_file", "wrong.json")
872 .unwrap()
873 .set_default("config_root", config_root.as_str())
874 .unwrap()
875 .build()
876 .unwrap();
877
878 // This should panic with unwrap on None since console.installed is None
879 let _result = ClientConfig::new_from_configuration(app_config);
880 }
881
882 #[test]
883 fn test_persist_path_generation() {
884 let config = ClientConfig::builder()
885 .with_client_id("test")
886 .with_config_path("/custom/path")
887 .build();
888
889 assert_eq!(config.persist_path(), "/custom/path/gmail1");
890 }
891
892 #[test]
893 fn test_config_accessor_methods() {
894 let config = ClientConfig::builder()
895 .with_client_id("accessor-test-id")
896 .with_client_secret("accessor-test-secret")
897 .with_config_path("/test/path")
898 .build();
899
900 // Test secret() accessor
901 let secret = config.secret();
902 assert_eq!(secret.client_id, "accessor-test-id");
903 assert_eq!(secret.client_secret, "accessor-test-secret");
904
905 // Test persist_path() accessor
906 assert_eq!(config.persist_path(), "/test/path/gmail1");
907
908 // Test full_path() accessor
909 assert_eq!(config.full_path(), "/test/path");
910
911 // Test config_root() accessor
912 let config_root = config.config_root();
913 assert_eq!(config_root.full_path().display().to_string(), "/test/path");
914 }
915
916 #[test]
917 fn test_builder_method_chaining() {
918 // Test that all builder methods return &mut Self for chaining
919 let config = ClientConfig::builder()
920 .with_client_id("chain-test")
921 .with_client_secret("chain-secret")
922 .with_auth_uri("https://auth.chain.com")
923 .with_token_uri("https://token.chain.com")
924 .add_redirect_uri("http://redirect1.com")
925 .add_redirect_uri("http://redirect2.com")
926 .with_project_id("chain-project")
927 .with_client_email("chain@test.com")
928 .with_auth_provider_x509_cert_url("https://cert1.com")
929 .with_client_x509_cert_url("https://cert2.com")
930 .with_config_base(&config_root::RootBase::Home)
931 .with_config_path(".chain-test")
932 .build();
933
934 assert_eq!(config.secret().client_id, "chain-test");
935 assert_eq!(config.secret().redirect_uris.len(), 2);
936 }
937
938 #[test]
939 fn test_configuration_priority() {
940 // Test that direct OAuth2 params take priority over credential file
941 get_test_logger();
942 let temp_dir = TempDir::new().expect("Failed to create temp dir");
943 let _cred_file =
944 create_test_credential_file(&temp_dir, "priority.json", sample_valid_credential());
945
946 let config_root = format!("c:{}", temp_dir.path().display());
947 let app_config = Config::builder()
948 // Direct OAuth2 params (should take priority)
949 .set_default("client_id", "priority-client-id")
950 .unwrap()
951 .set_default("client_secret", "priority-client-secret")
952 .unwrap()
953 .set_default("token_uri", "https://priority.token.com")
954 .unwrap()
955 .set_default("auth_uri", "https://priority.auth.com")
956 .unwrap()
957 // Credential file (should be ignored)
958 .set_default("credential_file", "priority.json")
959 .unwrap()
960 .set_default("config_root", config_root.as_str())
961 .unwrap()
962 .build()
963 .unwrap();
964
965 let config = ClientConfig::new_from_configuration(app_config).unwrap();
966
967 // Should use direct params, not file contents
968 assert_eq!(config.secret().client_id, "priority-client-id");
969 assert_eq!(config.secret().client_secret, "priority-client-secret");
970 assert_eq!(config.secret().token_uri, "https://priority.token.com");
971 assert_ne!(
972 config.secret().client_id,
973 "123456789-test.googleusercontent.com"
974 ); // From file
975 }
976
977 #[test]
978 fn test_empty_redirect_uris() {
979 let config = ClientConfig::builder().with_client_id("test-id").build();
980
981 assert!(config.secret().redirect_uris.is_empty());
982 }
983
984 #[test]
985 fn test_multiple_redirect_uris() {
986 let config = ClientConfig::builder()
987 .with_client_id("test-id")
988 .add_redirect_uri("http://localhost:8080")
989 .add_redirect_uri("http://localhost:3000")
990 .add_redirect_uri("https://example.com/callback")
991 .build();
992
993 assert_eq!(config.secret().redirect_uris.len(), 3);
994 assert!(
995 config
996 .secret()
997 .redirect_uris
998 .contains(&"http://localhost:8080".to_string())
999 );
1000 assert!(
1001 config
1002 .secret()
1003 .redirect_uris
1004 .contains(&"http://localhost:3000".to_string())
1005 );
1006 assert!(
1007 config
1008 .secret()
1009 .redirect_uris
1010 .contains(&"https://example.com/callback".to_string())
1011 );
1012 }
1013
1014 #[test]
1015 fn test_optional_fields() {
1016 let config = ClientConfig::builder()
1017 .with_client_id("optional-test")
1018 .build();
1019
1020 assert_eq!(config.secret().project_id, None);
1021 assert_eq!(config.secret().client_email, None);
1022 assert_eq!(config.secret().auth_provider_x509_cert_url, None);
1023 assert_eq!(config.secret().client_x509_cert_url, None);
1024 }
1025
1026 #[test]
1027 fn test_unicode_in_configuration() {
1028 let config = ClientConfig::builder()
1029 .with_client_id("unicode-客戶端-🔐-test")
1030 .with_client_secret("secret-with-unicode-密碼")
1031 .with_project_id("project-項目-id")
1032 .with_config_path(".unicode-配置")
1033 .build();
1034
1035 assert_eq!(config.secret().client_id, "unicode-客戶端-🔐-test");
1036 assert_eq!(config.secret().client_secret, "secret-with-unicode-密碼");
1037 assert_eq!(
1038 config.secret().project_id,
1039 Some("project-項目-id".to_string())
1040 );
1041 assert!(config.full_path().contains(".unicode-配置"));
1042 }
1043}