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
//! # google-cloud-default
//!
//! Google Cloud Platform default configuration for google-cloud-rust.
//!
//! ## Quick Start
//!
//! * [pubsub](https://github.com/yoshidan/google-cloud-rust/tree/main/pubsub)
//! * [spanner](https://github.com/yoshidan/google-cloud-rust/tree/main/spanner)
//! * [storage](https://github.com/yoshidan/google-cloud-rust/tree/main/storage)
//!
use async_trait::async_trait;

use google_cloud_auth::error::Error;

#[async_trait]
pub trait WithAuthExt {
    async fn with_auth(mut self) -> Result<Self, Error>
    where
        Self: Sized;

    async fn with_credentials(
        self,
        credentials: google_cloud_auth::credentials::CredentialsFile,
    ) -> Result<Self, Error>
    where
        Self: Sized;
}

#[cfg(feature = "pubsub")]
#[async_trait]
impl WithAuthExt for google_cloud_pubsub::client::ClientConfig {
    async fn with_auth(mut self) -> Result<Self, Error> {
        if let google_cloud_gax::conn::Environment::GoogleCloud(_) = self.environment {
            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new(google_cloud_auth::project::Config {
                audience: Some(google_cloud_pubsub::apiv1::conn_pool::AUDIENCE),
                scopes: Some(&google_cloud_pubsub::apiv1::conn_pool::SCOPES),
            })
            .await?;
            self.project_id = ts.project_id.clone();
            self.environment = google_cloud_gax::conn::Environment::GoogleCloud(Box::new(ts))
        }
        Ok(self)
    }

    async fn with_credentials(
        mut self,
        credentials: google_cloud_auth::credentials::CredentialsFile,
    ) -> Result<Self, Error> {
        if let google_cloud_gax::conn::Environment::GoogleCloud(_) = self.environment {
            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
                google_cloud_auth::project::Config {
                    audience: Some(google_cloud_pubsub::apiv1::conn_pool::AUDIENCE),
                    scopes: Some(&google_cloud_pubsub::apiv1::conn_pool::SCOPES),
                },
                Box::new(credentials),
            )
            .await?;
            self.project_id = ts.project_id.clone();
            self.environment = google_cloud_gax::conn::Environment::GoogleCloud(Box::new(ts))
        }

        Ok(self)
    }
}

#[cfg(feature = "spanner")]
#[async_trait]
impl WithAuthExt for google_cloud_spanner::client::ClientConfig {
    async fn with_auth(mut self) -> Result<Self, Error> {
        if let google_cloud_gax::conn::Environment::GoogleCloud(_) = self.environment {
            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new(google_cloud_auth::project::Config {
                audience: Some(google_cloud_spanner::apiv1::conn_pool::AUDIENCE),
                scopes: Some(&google_cloud_spanner::apiv1::conn_pool::SCOPES),
            })
            .await?;
            self.environment = google_cloud_gax::conn::Environment::GoogleCloud(Box::new(ts))
        }
        Ok(self)
    }

    async fn with_credentials(
        mut self,
        credentials: google_cloud_auth::credentials::CredentialsFile,
    ) -> Result<Self, Error> {
        if let google_cloud_gax::conn::Environment::GoogleCloud(_) = self.environment {
            let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
                google_cloud_auth::project::Config {
                    audience: Some(google_cloud_spanner::apiv1::conn_pool::AUDIENCE),
                    scopes: Some(&google_cloud_spanner::apiv1::conn_pool::SCOPES),
                },
                Box::new(credentials),
            )
            .await?;
            self.environment = google_cloud_gax::conn::Environment::GoogleCloud(Box::new(ts))
        }
        Ok(self)
    }
}

#[cfg(feature = "storage")]
#[async_trait]
impl WithAuthExt for google_cloud_storage::client::ClientConfig {
    async fn with_auth(mut self) -> Result<Self, Error> {
        let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new(google_cloud_auth::project::Config {
            audience: None,
            scopes: Some(&google_cloud_storage::http::storage_client::SCOPES),
        })
        .await?;

        match &ts.source_credentials {
            // Credential file is used.
            Some(cred) => {
                self.project_id = cred.project_id.clone();
                if let Some(pk) = &cred.private_key {
                    self.default_sign_by =
                        Some(google_cloud_storage::sign::SignBy::PrivateKey(pk.clone().into_bytes()));
                }
                self.default_google_access_id = cred.client_email.clone();
            }
            // On Google Cloud
            None => {
                self.project_id = Some(google_cloud_metadata::project_id().await);
                self.default_sign_by = Some(google_cloud_storage::sign::SignBy::SignBytes);
                self.default_google_access_id = google_cloud_metadata::email("default").await.ok();
            }
        }

        self.token_source_provider = Box::new(ts);
        Ok(self)
    }

    async fn with_credentials(
        mut self,
        credentials: google_cloud_auth::credentials::CredentialsFile,
    ) -> Result<Self, Error> {
        let ts = google_cloud_auth::token::DefaultTokenSourceProvider::new_with_credentials(
            google_cloud_auth::project::Config {
                audience: None,
                scopes: Some(&google_cloud_storage::http::storage_client::SCOPES),
            },
            Box::new(credentials),
        )
        .await?;

        match &ts.source_credentials {
            // Credential file is used.
            Some(cred) => {
                self.project_id = cred.project_id.clone();
                if let Some(pk) = &cred.private_key {
                    self.default_sign_by =
                        Some(google_cloud_storage::sign::SignBy::PrivateKey(pk.clone().into_bytes()));
                }
                self.default_google_access_id = cred.client_email.clone();
            }
            // On Google Cloud
            None => {
                self.project_id = Some(google_cloud_metadata::project_id().await);
                self.default_sign_by = Some(google_cloud_storage::sign::SignBy::SignBytes);
                self.default_google_access_id = google_cloud_metadata::email("default").await.ok();
            }
        }

        self.token_source_provider = Box::new(ts);
        Ok(self)
    }
}

#[cfg(test)]
mod test {
    use google_cloud_gax::conn::Environment;

    use crate::WithAuthExt;

    #[tokio::test]
    async fn test_spanner() {
        let config = google_cloud_spanner::client::ClientConfig::default()
            .with_auth()
            .await
            .unwrap();
        if let Environment::Emulator(_) = config.environment {
            unreachable!()
        }
    }

    #[tokio::test]
    async fn test_pubsub() {
        let config = google_cloud_pubsub::client::ClientConfig::default()
            .with_auth()
            .await
            .unwrap();
        if let Environment::Emulator(_) = config.environment {
            unreachable!()
        }
    }

    #[tokio::test]
    async fn test_storage() {
        let config = google_cloud_storage::client::ClientConfig::default()
            .with_auth()
            .await
            .unwrap();
        assert!(config.default_google_access_id.is_some());
        assert!(config.default_sign_by.is_some());
    }
}