gcp-lite-rs 0.1.1

Lightweight HTTP client for Google Cloud Platform APIs
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Application Default Credentials (ADC) implementation for GCP authentication.
//!
//! This module provides `AdcCredential`, which implements the `TokenProvider`
//! trait using the Application Default Credentials resolution chain. This is the
//! same credential resolution strategy used by the `gcloud` CLI and official
//! Google Cloud client libraries.
//!
//! # ADC Resolution Chain
//!
//! The credential resolution follows this order:
//! 1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable - if set, parse the file at that path
//! 2. Well-known path `~/.config/gcloud/application_default_credentials.json` - if exists, parse it
//! 3. GCP metadata server - for instances running on GCP infrastructure
//!
//! # Quota Project
//!
//! When using user credentials (authorized_user type), some APIs require a quota
//! project to be set for billing. This is read from the `quota_project_id` field
//! in the ADC JSON file. You can set it using:
//!
//! ```bash
//! gcloud auth application-default set-quota-project YOUR_PROJECT
//! ```
//!
//! The `GOOGLE_CLOUD_QUOTA_PROJECT` environment variable can override this value.
//!
//! # Example
//!
//! ```no_run
//! use gcp_lite::auth::AdcCredential;
//! use gcp_lite::token::TokenProvider;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create ADC credential - automatically resolves the credential chain
//! let cred = AdcCredential::new().await?;
//!
//! // Get a token
//! let token = cred.get_token(&["https://www.googleapis.com/auth/cloud-platform"]).await?;
//! # Ok(())
//! # }
//! ```

use async_trait::async_trait;
use std::env;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;

use crate::auth::authorized_user::AuthorizedUserCredential;
use crate::auth::metadata::MetadataServerCredential;
use crate::auth::service_account::ServiceAccountCredential;
use crate::auth::types::CredentialFile;
use crate::token::{TokenError, TokenProvider};

/// Environment variable for specifying the credential file path.
const GOOGLE_APPLICATION_CREDENTIALS: &str = "GOOGLE_APPLICATION_CREDENTIALS";

/// Metadata server IP address.
const METADATA_SERVER_IP: IpAddr = IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254));

/// Metadata server port.
const METADATA_SERVER_PORT: u16 = 80;

/// Timeout for metadata server connectivity check (1 second).
const METADATA_SERVER_CONNECTIVITY_TIMEOUT: Duration = Duration::from_secs(1);

/// The underlying credential type resolved by ADC.
#[derive(Debug)]
enum InnerCredential {
    /// A service account credential.
    ServiceAccount(ServiceAccountCredential),
    /// An authorized user credential.
    AuthorizedUser(AuthorizedUserCredential),
    /// A metadata server credential (for GCP-hosted environments).
    MetadataServer(MetadataServerCredential),
    /// A gcloud CLI credential.
    Gcloud(crate::auth::gcloud::GcloudCredential),
}

/// A credential provider that uses Application Default Credentials (ADC).
///
/// This credential type automatically resolves credentials using the standard
/// ADC chain:
///
/// 1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable
/// 2. Well-known path `~/.config/gcloud/application_default_credentials.json`
/// 3. GCP metadata server
///
/// # Thread Safety
///
/// `AdcCredential` is `Send + Sync` and can be safely shared across threads.
/// Token caching is handled by the underlying credential implementation.
#[derive(Debug)]
pub struct AdcCredential {
    /// The resolved inner credential.
    inner: InnerCredential,
    /// The source of the credential (for debugging/logging).
    source: AdcSource,
}

/// Describes how the ADC credential was resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdcSource {
    /// From `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
    EnvironmentVariable(PathBuf),
    /// From the well-known path `~/.config/gcloud/application_default_credentials.json`.
    WellKnownPath(PathBuf),
    /// From the GCP metadata server.
    MetadataServer,
    /// From gcloud CLI.
    Gcloud,
}

/// Check if the metadata server is reachable.
///
/// Performs a fast TCP SYN check to 169.254.169.254:80 with a 1-second timeout.
/// This prevents 60-second hangs when running on non-GCP infrastructure.
///
/// # Arguments
///
/// * `timeout` - Maximum time to wait for connection attempt
///
/// # Returns
///
/// `true` if the metadata server is reachable, `false` otherwise.
async fn can_reach_metadata_server(timeout: Duration) -> bool {
    let addr = SocketAddr::new(METADATA_SERVER_IP, METADATA_SERVER_PORT);

    match tokio::time::timeout(timeout, tokio::net::TcpStream::connect(addr)).await {
        Ok(Ok(_)) => {
            tracing::debug!("Metadata server at {} is reachable", addr);
            true
        }
        Ok(Err(e)) => {
            tracing::debug!("Metadata server at {} is unreachable: {}", addr, e);
            false
        }
        Err(_) => {
            tracing::debug!(
                "Metadata server connectivity check timed out after {:?}",
                timeout
            );
            false
        }
    }
}

impl std::fmt::Display for AdcSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AdcSource::EnvironmentVariable(path) => {
                write!(f, "GOOGLE_APPLICATION_CREDENTIALS={}", path.display())
            }
            AdcSource::WellKnownPath(path) => {
                write!(f, "well-known path: {}", path.display())
            }
            AdcSource::MetadataServer => write!(f, "GCP metadata server"),
            AdcSource::Gcloud => write!(f, "gcloud CLI"),
        }
    }
}

impl AdcCredential {
    /// Create a new ADC credential by resolving the credential chain.
    ///
    /// This method attempts to find credentials in the following order:
    /// 0. If `GOOGLE_AUTH_USE_GCLOUD` is set, try gcloud CLI first (with fallback)
    /// 1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable
    /// 2. Well-known path `~/.config/gcloud/application_default_credentials.json`
    /// 3. GCP metadata server
    ///
    /// # Errors
    ///
    /// Returns an error if no valid credentials can be found or if a credential
    /// file exists but is invalid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use gcp_lite::auth::AdcCredential;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let cred = AdcCredential::new().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new() -> Result<Self, AdcError> {
        // Step 0: Check gcloud if env var is set
        if env::var("GOOGLE_AUTH_USE_GCLOUD").is_ok()
            && let Ok(cred) = Self::try_gcloud().await
        {
            return Ok(cred);
        }
        // Fall through to standard chain if gcloud fails

        // Step 1: Check GOOGLE_APPLICATION_CREDENTIALS env var
        if let Ok(path) = env::var(GOOGLE_APPLICATION_CREDENTIALS) {
            let path = PathBuf::from(&path);
            return Self::from_file(&path, AdcSource::EnvironmentVariable(path.clone())).await;
        }

        // Step 2: Check well-known path
        if let Some(well_known_path) = Self::well_known_path()
            && well_known_path.exists()
        {
            return Self::from_file(
                &well_known_path,
                AdcSource::WellKnownPath(well_known_path.clone()),
            )
            .await;
        }

        // Step 3: Try metadata server (only if reachable)
        // Check connectivity first to avoid 60-second hangs on non-GCP infrastructure
        if can_reach_metadata_server(METADATA_SERVER_CONNECTIVITY_TIMEOUT).await {
            tracing::debug!("Metadata server is reachable, using metadata server credentials");
            return Ok(Self {
                inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
                source: AdcSource::MetadataServer,
            });
        }

        tracing::debug!("Metadata server is not reachable");
        Err(AdcError::NoCredentialsFound)
    }

    /// Create an ADC credential from a specific file path.
    ///
    /// This allows explicitly specifying a credential file rather than using
    /// the automatic resolution chain.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the credential file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or contains invalid credentials.
    pub async fn from_file(path: &PathBuf, source: AdcSource) -> Result<Self, AdcError> {
        let json = std::fs::read_to_string(path).map_err(|e| AdcError::FileReadError {
            path: path.clone(),
            source: e,
        })?;

        let cred_file = CredentialFile::from_json(json.as_bytes()).map_err(|e| {
            AdcError::InvalidCredentials {
                message: e.to_string(),
                source_path: Some(path.clone()),
            }
        })?;

        match cred_file {
            CredentialFile::ServiceAccount(_) => {
                let cred = ServiceAccountCredential::from_json(&json).map_err(|e| {
                    AdcError::InvalidCredentials {
                        message: e.to_string(),
                        source_path: Some(path.clone()),
                    }
                })?;
                Ok(Self {
                    inner: InnerCredential::ServiceAccount(cred),
                    source,
                })
            }
            CredentialFile::AuthorizedUser(_creds) => {
                let cred = AuthorizedUserCredential::from_json(&json).map_err(|e| {
                    AdcError::InvalidCredentials {
                        message: e.to_string(),
                        source_path: Some(path.clone()),
                    }
                })?;
                Ok(Self {
                    inner: InnerCredential::AuthorizedUser(cred),
                    source,
                })
            }
        }
    }

    /// Try to create a credential from gcloud CLI.
    ///
    /// Returns an error if gcloud is not installed or not authenticated.
    /// Logs a warning on failure.
    async fn try_gcloud() -> Result<Self, AdcError> {
        use crate::auth::gcloud::GcloudCredential;

        match GcloudCredential::new().await {
            Ok(cred) => Ok(Self {
                inner: InnerCredential::Gcloud(cred),
                source: AdcSource::Gcloud,
            }),
            Err(e) => {
                tracing::warn!("gcloud auth check failed, continuing ADC chain: {}", e);
                Err(AdcError::GcloudUnavailable(e))
            }
        }
    }

    /// Get the well-known path for gcloud application default credentials.
    ///
    /// Returns `~/.config/gcloud/application_default_credentials.json` on Unix
    /// or the equivalent on other platforms.
    fn well_known_path() -> Option<PathBuf> {
        dirs::home_dir().map(|home| {
            home.join(".config")
                .join("gcloud")
                .join("application_default_credentials.json")
        })
    }

    /// Get the source of the resolved credential.
    ///
    /// This is useful for debugging and logging to understand which credential
    /// source was used.
    pub fn source(&self) -> &AdcSource {
        &self.source
    }

    /// Returns true if the credential was resolved from a file.
    pub fn is_from_file(&self) -> bool {
        matches!(
            self.source,
            AdcSource::EnvironmentVariable(_) | AdcSource::WellKnownPath(_)
        )
    }

    /// Returns true if the credential was resolved from the metadata server.
    pub fn is_from_metadata_server(&self) -> bool {
        matches!(self.source, AdcSource::MetadataServer)
    }
}

#[async_trait]
impl TokenProvider for AdcCredential {
    async fn get_token(&self, scopes: &[&str]) -> Result<String, TokenError> {
        match &self.inner {
            InnerCredential::ServiceAccount(cred) => cred.get_token(scopes).await,
            InnerCredential::AuthorizedUser(cred) => cred.get_token(scopes).await,
            InnerCredential::MetadataServer(cred) => cred.get_token(scopes).await,
            InnerCredential::Gcloud(cred) => cred.get_token(scopes).await,
        }
    }

    fn on_token_rejected(&self) {
        match &self.inner {
            InnerCredential::ServiceAccount(cred) => cred.on_token_rejected(),
            InnerCredential::AuthorizedUser(cred) => cred.on_token_rejected(),
            InnerCredential::MetadataServer(cred) => cred.on_token_rejected(),
            InnerCredential::Gcloud(cred) => cred.on_token_rejected(),
        }
    }

    fn quota_project_id(&self) -> Option<&str> {
        match &self.inner {
            InnerCredential::ServiceAccount(cred) => cred.quota_project_id(),
            InnerCredential::AuthorizedUser(cred) => cred.quota_project_id(),
            InnerCredential::MetadataServer(cred) => cred.quota_project_id(),
            InnerCredential::Gcloud(cred) => cred.quota_project_id(),
        }
    }
}

/// Errors that can occur when using ADC credentials.
#[derive(Debug, thiserror::Error)]
pub enum AdcError {
    /// Failed to read the credentials file.
    #[error("Failed to read credentials file at {path}: {source}")]
    FileReadError {
        /// Path to the file that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },

    /// Invalid credentials format.
    #[error("Invalid credentials{}: {message}", source_path.as_ref().map(|p| format!(" at {}", p.display())).unwrap_or_default())]
    InvalidCredentials {
        /// Error description.
        message: String,
        /// Path to the credential file, if any.
        source_path: Option<PathBuf>,
    },

    /// No credentials found in any source.
    #[error("No credentials found in ADC chain")]
    NoCredentialsFound,

    /// Gcloud unavailable.
    #[error("gcloud unavailable: {0}")]
    GcloudUnavailable(#[from] crate::auth::gcloud::GcloudError),

    /// Failed to create HTTP client.
    #[error("Failed to create HTTP client: {source}")]
    HttpClientCreation {
        /// The underlying reqwest error.
        #[source]
        source: reqwest::Error,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::env;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create a test service account JSON file.
    fn create_service_account_json() -> String {
        r#"{
            "type": "service_account",
            "project_id": "test-project",
            "private_key_id": "key123",
            "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAv/ZgLU6ZAC6tVLSjrzeVeigCbmFVXFqeohH0wsveMsgUnktr\nKoQUhclteEs7iGLwKPQdWyOMIaQFC320l1wqvJKg7XbWtYyC856yBtHBisXzjUIP\nvppA7Ie6N0uKtqZ1HLXKbqEd5bNPEU61LJJgLXOdXRbb+9EhLusQpWQb3cPLI/za\nqmSa6UYwEv8GCtIgNqTjKycHCi0MqKpjNZ6wFzvPruLqnkOhtA2LVsklp+9jYxca\nyv9UBS5xVQ01WHHSR/J//G2v0yCUzmitdDJTQyOd4zlPkHpm6T69m7NaE1fTVSiP\nsVfO3Hn7VfzAgbQkZH40Q+OSlTubBQcZ8JyJWQIDAQABAoIBAAJOMBqt3GO2lnbT\nYjmJvPDAt8IXHFUVsoeG7diuuvOtraUMCf9dTY4gx0DgAxjwz+pnVM3s0p3vJW9d\nT7SsqEe8/r6eBCyd1s8cYLjOaUO50Q0T1h1nfAWgiKw+1Zg6zg0YTX7VeQbdR9hm\nSKyTx8tr8sp01T4EOuDgdQH40+aD0ivfbFdIyim82IGh7HHvJyMVxTsMHG1fRo/d\nkYpT3g2jOpEYCe0EnmAp2bB1kLLonlW+Xp3OOYShLXUtwXf8q/fOMcYbm3BV2OvC\nzhTaKmvStEpMhLHihsNJIf0uQZypY6lNu9IDhj2dacKjRNEpZn+ulwfdcx46VEAy\ngnt9IKECgYEA/Y4fSVQ4TsGJvH4vjb0+3o4uckWEPTffUwJG6r4PYSZGA8qQpr1E\noyxXdZt0atcsXs1Qd1E2t2FruumS18CTQvJE0+q06kqa6djYH7svOzfjxC5F4Np4\nEkMYEVecJ5qG1bU77BqJwY4rTRQ96e5PmgjTPV9hfxvNX51JTm06gfECgYEAwdA3\npabK+6x2hjxyNLldPdcctFZqA16OeL5VWk5/7L2kLFUYVjyz129vAtkJKnB+GAJs\nuZcNwhBbqSiK0vv5WoQOIzrSzbzLZ7STjymMzZ6FOkdElbD6H811idKpI87fQD0O\nEo4L5wslqIVxR8ktoRJgRvI6sFm1ajSsarlrlekCgYAC7cJUwYFI/5lMsRRxia8R\nOQk2TrFBV8Tfm5YgHgPldmC2qH9VPbhuPhPgiuQkW8nqamq0hh6graJl7U7B6TqK\nOmwrGnnufuAdNWEBtNLN105tNK+f8kYSx+2ePanTF0jZbRd9Ga1fq/m6ETLJ4fPP\nbqyp99ETe8m6ggGXw1E6sQKBgG950rf90pylWtrk44992qqaEtGLLpjXhzzdxPwX\nUK8beNVi8IeRjKNqXcCWkxYM9AndQyoQPwKTJBWM0yR9d7PfZr5OtDdP0vLIQ2NB\ns9IEzn5xxXoP/B3UsDlgqJaHA5PQSkrT1vbCS5u9fSWcChmuFyBXbPhH8PewakdM\ndRwZAoGAexRCCrNBek6bxaCVI8JqRRIGYPAwr9sUjKwn8Tdhutx8lvcKOk6AHG1I\nuQAVf8HQ3eHRgsCSodf1XeoLWX+0Nxt/KJ1KotVlchFlCLuSzpNkR7WbLC7QfCkJ\nRLK9OKOIcBVVctVsUtrWLjTEHyKVhYwIW98X+LAal+i55n75SHU=\n-----END RSA PRIVATE KEY-----\n",
            "client_email": "sa@test-project.iam.gserviceaccount.com",
            "client_id": "123456789",
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token"
        }"#.to_string()
    }

    /// Helper to create a test authorized user JSON file.
    fn create_authorized_user_json() -> String {
        r#"{
            "type": "authorized_user",
            "client_id": "test-client-id.apps.googleusercontent.com",
            "client_secret": "test-client-secret",
            "refresh_token": "1//test-refresh-token"
        }"#
        .to_string()
    }

    #[test]
    fn test_well_known_path() {
        let path = AdcCredential::well_known_path();
        assert!(path.is_some());
        let path = path.unwrap();
        assert!(
            path.to_string_lossy()
                .contains("application_default_credentials.json")
        );
        assert!(path.to_string_lossy().contains(".config"));
        assert!(path.to_string_lossy().contains("gcloud"));
    }

    #[test]
    fn test_adc_source_display() {
        let source = AdcSource::EnvironmentVariable(PathBuf::from("/path/to/creds.json"));
        assert!(
            source
                .to_string()
                .contains("GOOGLE_APPLICATION_CREDENTIALS")
        );
        assert!(source.to_string().contains("/path/to/creds.json"));

        let source = AdcSource::WellKnownPath(PathBuf::from("/home/user/.config/gcloud/adc.json"));
        assert!(source.to_string().contains("well-known path"));

        let source = AdcSource::MetadataServer;
        assert!(source.to_string().contains("metadata server"));
    }

    #[tokio::test]
    async fn test_from_file_service_account() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("service_account.json");
        fs::write(&cred_path, create_service_account_json()).unwrap();

        let result = AdcCredential::from_file(
            &cred_path,
            AdcSource::EnvironmentVariable(cred_path.clone()),
        )
        .await;

        assert!(result.is_ok());
        let cred = result.unwrap();
        assert!(matches!(cred.inner, InnerCredential::ServiceAccount(_)));
        assert!(cred.is_from_file());
        assert!(!cred.is_from_metadata_server());
    }

    #[tokio::test]
    async fn test_from_file_authorized_user() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("authorized_user.json");
        fs::write(&cred_path, create_authorized_user_json()).unwrap();

        let result =
            AdcCredential::from_file(&cred_path, AdcSource::WellKnownPath(cred_path.clone())).await;

        assert!(result.is_ok());
        let cred = result.unwrap();
        assert!(matches!(cred.inner, InnerCredential::AuthorizedUser(_)));
        assert!(cred.is_from_file());
        assert!(!cred.is_from_metadata_server());
    }

    #[tokio::test]
    async fn test_from_file_not_found() {
        let path = PathBuf::from("/nonexistent/file.json");
        let result =
            AdcCredential::from_file(&path, AdcSource::EnvironmentVariable(path.clone())).await;

        assert!(result.is_err());
        assert!(matches!(result, Err(AdcError::FileReadError { .. })));
    }

    #[tokio::test]
    async fn test_from_file_invalid_json() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("invalid.json");
        fs::write(&cred_path, "not valid json").unwrap();

        let result = AdcCredential::from_file(
            &cred_path,
            AdcSource::EnvironmentVariable(cred_path.clone()),
        )
        .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(AdcError::InvalidCredentials { .. })));
    }

    #[tokio::test]
    async fn test_from_file_unknown_type() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("unknown.json");
        fs::write(&cred_path, r#"{"type": "unknown_type"}"#).unwrap();

        let result = AdcCredential::from_file(
            &cred_path,
            AdcSource::EnvironmentVariable(cred_path.clone()),
        )
        .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(AdcError::InvalidCredentials { .. })));
    }

    #[tokio::test]
    #[serial]
    async fn test_new_with_env_var() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("env_creds.json");
        fs::write(&cred_path, create_service_account_json()).unwrap();

        // Set the environment variable
        let prev_value = env::var(GOOGLE_APPLICATION_CREDENTIALS).ok();
        let prev_gcloud = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();
        // SAFETY: This is a test and we restore the value after
        unsafe {
            env::set_var(GOOGLE_APPLICATION_CREDENTIALS, &cred_path);
            env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
        }

        let result = AdcCredential::new().await;

        // Restore the environment variable
        // SAFETY: This is a test and we're restoring the original value
        unsafe {
            if let Some(prev) = prev_value {
                env::set_var(GOOGLE_APPLICATION_CREDENTIALS, prev);
            } else {
                env::remove_var(GOOGLE_APPLICATION_CREDENTIALS);
            }
            if let Some(prev) = prev_gcloud {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            }
        }

        assert!(result.is_ok());
        let cred = result.unwrap();
        assert!(matches!(cred.source, AdcSource::EnvironmentVariable(_)));
        assert!(matches!(cred.inner, InnerCredential::ServiceAccount(_)));
    }

    #[tokio::test]
    #[serial]
    async fn test_new_env_var_invalid_file() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("invalid.json");
        fs::write(&cred_path, "invalid json content").unwrap();

        // Set the environment variable
        let prev_value = env::var(GOOGLE_APPLICATION_CREDENTIALS).ok();
        let prev_gcloud = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();
        // SAFETY: This is a test and we restore the value after
        unsafe {
            env::set_var(GOOGLE_APPLICATION_CREDENTIALS, &cred_path);
            env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
        }

        let result = AdcCredential::new().await;

        // Restore the environment variable
        // SAFETY: This is a test and we're restoring the original value
        unsafe {
            if let Some(prev) = prev_value {
                env::set_var(GOOGLE_APPLICATION_CREDENTIALS, prev);
            } else {
                env::remove_var(GOOGLE_APPLICATION_CREDENTIALS);
            }
            if let Some(prev) = prev_gcloud {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            }
        }

        assert!(result.is_err());
    }

    #[tokio::test]
    #[serial]
    async fn test_new_env_var_missing_file() {
        // Set the environment variable to a non-existent file
        let prev_value = env::var(GOOGLE_APPLICATION_CREDENTIALS).ok();
        let prev_gcloud = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();
        // SAFETY: This is a test and we restore the value after
        unsafe {
            env::set_var(
                GOOGLE_APPLICATION_CREDENTIALS,
                "/nonexistent/path/to/creds.json",
            );
            env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
        }

        let result = AdcCredential::new().await;

        // Restore the environment variable
        // SAFETY: This is a test and we're restoring the original value
        unsafe {
            if let Some(prev) = prev_value {
                env::set_var(GOOGLE_APPLICATION_CREDENTIALS, prev);
            } else {
                env::remove_var(GOOGLE_APPLICATION_CREDENTIALS);
            }
            if let Some(prev) = prev_gcloud {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            }
        }

        assert!(result.is_err());
        assert!(matches!(result, Err(AdcError::FileReadError { .. })));
    }

    #[tokio::test]
    #[serial]
    async fn test_new_fallback_to_metadata() {
        // Remove environment variable and ensure no well-known file exists
        let prev_value = env::var(GOOGLE_APPLICATION_CREDENTIALS).ok();
        // SAFETY: This is a test and we restore the value after
        unsafe {
            env::remove_var(GOOGLE_APPLICATION_CREDENTIALS);
        }

        // Create a temporary home that won't have the well-known file
        // Note: This test assumes the well-known path doesn't exist in the test environment
        // or will fall back to metadata server

        let result = AdcCredential::new().await;

        // Restore the environment variable
        // SAFETY: This is a test and we're restoring the original value
        unsafe {
            if let Some(prev) = prev_value {
                env::set_var(GOOGLE_APPLICATION_CREDENTIALS, prev);
            }
        }

        // If well-known path doesn't exist and metadata server is unreachable,
        // should return NoCredentialsFound
        // This test may pass with either a file or metadata server depending on environment
        assert!(result.is_ok() || result.is_err()); // Either outcome is valid
    }

    #[tokio::test]
    async fn test_can_reach_metadata_server_unreachable() {
        // Test that connectivity check completes without hanging
        // 169.254.169.254 should be unreachable in most test environments
        use std::time::Instant;

        let timeout = Duration::from_millis(200);
        let start = Instant::now();
        let _reachable = can_reach_metadata_server(timeout).await;
        let elapsed = start.elapsed();

        // Should complete within timeout + small buffer (150ms)
        // This verifies we don't hang waiting for unreachable server
        assert!(
            elapsed < timeout + Duration::from_millis(150),
            "Connectivity check took too long: {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_can_reach_metadata_server_timeout() {
        // Test that connectivity check respects timeout
        use std::time::Instant;

        let timeout = Duration::from_millis(50);
        let start = Instant::now();
        let _reachable = can_reach_metadata_server(timeout).await;
        let elapsed = start.elapsed();

        // Should complete within timeout + small buffer (100ms)
        assert!(
            elapsed < timeout + Duration::from_millis(100),
            "Connectivity check took too long: {:?}",
            elapsed
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_new_no_credentials_metadata_server_unreachable() {
        // Test that ADC returns NoCredentialsFound when no credentials exist
        // and metadata server is unreachable

        // Remove environment variables
        let prev_gac = env::var(GOOGLE_APPLICATION_CREDENTIALS).ok();
        let prev_gcloud = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();

        unsafe {
            env::remove_var(GOOGLE_APPLICATION_CREDENTIALS);
            env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
        }

        // In non-GCP environments, this should return NoCredentialsFound
        // because metadata server is unreachable
        let result = AdcCredential::new().await;

        // Restore environment variables
        unsafe {
            if let Some(prev) = prev_gac {
                env::set_var(GOOGLE_APPLICATION_CREDENTIALS, prev);
            }
            if let Some(prev) = prev_gcloud {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            }
        }

        // If well-known path doesn't exist (common in test environments),
        // should return NoCredentialsFound when metadata server is unreachable
        if result.is_err() {
            assert!(matches!(result, Err(AdcError::NoCredentialsFound)));
        }
    }

    #[test]
    fn test_is_from_file() {
        let cred_env = AdcCredential {
            inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
            source: AdcSource::EnvironmentVariable(PathBuf::from("/test")),
        };
        assert!(cred_env.is_from_file());

        let cred_well_known = AdcCredential {
            inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
            source: AdcSource::WellKnownPath(PathBuf::from("/test")),
        };
        assert!(cred_well_known.is_from_file());

        let cred_metadata = AdcCredential {
            inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
            source: AdcSource::MetadataServer,
        };
        assert!(!cred_metadata.is_from_file());
    }

    #[test]
    fn test_is_from_metadata_server() {
        let cred = AdcCredential {
            inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
            source: AdcSource::MetadataServer,
        };
        assert!(cred.is_from_metadata_server());

        let cred = AdcCredential {
            inner: InnerCredential::MetadataServer(MetadataServerCredential::new()),
            source: AdcSource::EnvironmentVariable(PathBuf::from("/test")),
        };
        assert!(!cred.is_from_metadata_server());
    }

    #[test]
    fn test_error_display() {
        let err = AdcError::FileReadError {
            path: PathBuf::from("/test/path.json"),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"),
        };
        assert!(err.to_string().contains("/test/path.json"));
        assert!(err.to_string().contains("file not found"));

        let err = AdcError::InvalidCredentials {
            message: "unknown type".to_string(),
            source_path: Some(PathBuf::from("/creds.json")),
        };
        assert!(err.to_string().contains("unknown type"));
        assert!(err.to_string().contains("/creds.json"));

        let err = AdcError::InvalidCredentials {
            message: "missing field".to_string(),
            source_path: None,
        };
        assert!(err.to_string().contains("missing field"));
        // When source_path is None, the error should not include " at "
        assert!(!err.to_string().contains(" at "));

        let err = AdcError::NoCredentialsFound;
        assert!(err.to_string().contains("No credentials found"));
    }

    #[test]
    fn test_error_display_gcloud_unavailable() {
        use crate::auth::gcloud::GcloudError;

        let gcloud_err = GcloudError::NotInstalled;
        let err = AdcError::GcloudUnavailable(gcloud_err);
        assert!(err.to_string().contains("gcloud unavailable"));
        assert!(err.to_string().contains("not found in PATH"));
    }

    #[test]
    fn test_adc_source_gcloud_display() {
        let source = AdcSource::Gcloud;
        assert_eq!(source.to_string(), "gcloud CLI");
    }

    #[test]
    fn test_adc_source_gcloud_equality() {
        let source1 = AdcSource::Gcloud;
        let source2 = AdcSource::Gcloud;
        assert_eq!(source1, source2);

        let source3 = AdcSource::MetadataServer;
        assert_ne!(source1, source3);
    }

    #[tokio::test]
    async fn test_try_gcloud_not_installed() {
        // Gcloud not installed should return error
        // We can't easily test this without mocking, so we test the structure
        // The actual integration will be tested in task 11
    }

    #[tokio::test]
    #[serial]
    async fn test_adc_with_gcloud_env_var_not_installed() {
        // Set env var but gcloud not installed
        let prev_value = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();
        unsafe {
            env::set_var("GOOGLE_AUTH_USE_GCLOUD", "1");
        }

        // Should fall back to next source (metadata server in this case)
        let result = AdcCredential::new().await;

        unsafe {
            if let Some(prev) = prev_value {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            } else {
                env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
            }
        }

        // Either succeeds with fallback or fails with AdcError
        // We can't assert success because it depends on environment
        assert!(result.is_ok() || result.is_err());
    }

    #[tokio::test]
    #[serial]
    async fn test_adc_without_gcloud_env_var_skips_gcloud() {
        // Ensure env var is not set
        let prev_value = env::var("GOOGLE_AUTH_USE_GCLOUD").ok();
        unsafe {
            env::remove_var("GOOGLE_AUTH_USE_GCLOUD");
        }

        let result = AdcCredential::new().await;

        unsafe {
            if let Some(prev) = prev_value {
                env::set_var("GOOGLE_AUTH_USE_GCLOUD", prev);
            }
        }

        // Should not use gcloud source
        if let Ok(cred) = result {
            assert!(!matches!(cred.source, AdcSource::Gcloud));
        }
    }

    #[test]
    fn test_adc_source_equality() {
        let source1 = AdcSource::EnvironmentVariable(PathBuf::from("/path1"));
        let source2 = AdcSource::EnvironmentVariable(PathBuf::from("/path1"));
        let source3 = AdcSource::EnvironmentVariable(PathBuf::from("/path2"));

        assert_eq!(source1, source2);
        assert_ne!(source1, source3);

        assert_eq!(AdcSource::MetadataServer, AdcSource::MetadataServer);
        assert_ne!(AdcSource::MetadataServer, source1);
    }

    #[tokio::test]
    async fn test_quota_project_id_from_service_account() {
        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("service_account.json");
        fs::write(&cred_path, create_service_account_json()).unwrap();

        let cred = AdcCredential::from_file(
            &cred_path,
            AdcSource::EnvironmentVariable(cred_path.clone()),
        )
        .await
        .unwrap();

        // Service account's project_id should be used as quota project
        assert_eq!(cred.quota_project_id(), Some("test-project"));
    }

    #[tokio::test]
    async fn test_quota_project_id_from_authorized_user_with_quota() {
        let json = r#"{
            "type": "authorized_user",
            "client_id": "test-client-id.apps.googleusercontent.com",
            "client_secret": "test-client-secret",
            "refresh_token": "1//test-refresh-token",
            "quota_project_id": "my-quota-project"
        }"#;

        let temp_dir = TempDir::new().unwrap();
        let cred_path = temp_dir.path().join("authorized_user.json");
        fs::write(&cred_path, json).unwrap();

        let cred =
            AdcCredential::from_file(&cred_path, AdcSource::WellKnownPath(cred_path.clone()))
                .await
                .unwrap();

        assert_eq!(cred.quota_project_id(), Some("my-quota-project"));
    }
}