allowthem-core 0.0.9

Core types, database, and auth logic for allowthem
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
//! Google `SocialProvider` implementation.
//!
//! ## Token URL injection for tests
//!
//! The Google token endpoint is hardcoded to `https://oauth2.googleapis.com/token`
//! in the public `new()` constructor. Tests that need to point at a wiremock server
//! use the crate-private `new_with_token_url()` constructor instead. This avoids
//! the `OnceLock`-override pattern which is parallel-test-hostile.

use base64ct::{Base64UrlUnpadded, Encoding};
use serde::Deserialize;
use url::Url;

use crate::auth_client::AuthFuture;
use crate::error::AuthError;
use crate::social_providers::{ProviderType, SocialProvider, SocialProviderConfig, SocialUserInfo};

// ── Struct ────────────────────────────────────────────────────────────────────

/// Google OAuth 2.0 + OIDC social provider.
///
/// Constructed from a [`SocialProviderConfig`] via [`Self::new`]. The
/// `exchange_code` method returns the `id_token` JWT from the token
/// response; `fetch_user_info` decodes it locally — no second HTTP call.
#[derive(Debug)]
pub struct GoogleSocialProvider {
    client_id: String,
    client_secret: String,
    scopes: Vec<String>,
    http: reqwest::Client,
    /// Token endpoint URL. Always `https://oauth2.googleapis.com/token` in
    /// production; overridden in tests via `new_with_token_url`.
    token_url: String,
}

// ── Private claims struct ─────────────────────────────────────────────────────

#[derive(Deserialize)]
struct GoogleIdTokenClaims {
    sub: String,
    email: String,
    email_verified: bool,
    name: Option<String>,
    picture: Option<String>,
}

// ── Constructors ──────────────────────────────────────────────────────────────

impl GoogleSocialProvider {
    /// Build a `GoogleSocialProvider` from a decrypted config.
    ///
    /// Returns `AuthError::Validation` if `provider_type` is not `Google`
    /// or `scopes` is empty.
    pub fn new(config: SocialProviderConfig) -> Result<Self, AuthError> {
        Self::new_with_token_url(config, "https://oauth2.googleapis.com/token".into())
    }

    /// Like [`Self::new`] but with an overrideable token endpoint URL.
    ///
    /// Used by tests to point at a wiremock server.
    pub(crate) fn new_with_token_url(
        config: SocialProviderConfig,
        token_url: String,
    ) -> Result<Self, AuthError> {
        if config.provider_type != ProviderType::Google {
            return Err(AuthError::Validation(
                "provider_type mismatch: expected Google".into(),
            ));
        }
        if config.scopes.is_empty() {
            return Err(AuthError::Validation("scopes must not be empty".into()));
        }
        let http = reqwest::Client::builder()
            .user_agent("allowthem-oauth")
            .build()
            .map_err(|e| AuthError::Validation(format!("reqwest client build failed: {e}")))?;
        Ok(Self {
            client_id: config.client_id,
            client_secret: config.client_secret,
            scopes: config.scopes,
            http,
            token_url,
        })
    }
}

// ── SocialProvider impl ───────────────────────────────────────────────────────

impl SocialProvider for GoogleSocialProvider {
    fn provider_type(&self) -> ProviderType {
        ProviderType::Google
    }

    fn authorize_url(&self, redirect_uri: &str, state: &str, pkce_challenge: &str) -> String {
        let mut url =
            Url::parse("https://accounts.google.com/o/oauth2/v2/auth").expect("static URL");
        url.query_pairs_mut()
            .append_pair("client_id", &self.client_id)
            .append_pair("redirect_uri", redirect_uri)
            .append_pair("response_type", "code")
            .append_pair("scope", &self.scopes.join(" "))
            .append_pair("state", state)
            .append_pair("code_challenge", pkce_challenge)
            .append_pair("code_challenge_method", "S256");
        url.into()
    }

    fn exchange_code<'a>(
        &'a self,
        code: &'a str,
        redirect_uri: &'a str,
        pkce_verifier: &'a str,
    ) -> AuthFuture<'a, String> {
        Box::pin(async move {
            let resp = self
                .http
                .post(&self.token_url)
                .form(&[
                    ("code", code),
                    ("client_id", self.client_id.as_str()),
                    ("client_secret", self.client_secret.as_str()),
                    ("redirect_uri", redirect_uri),
                    ("grant_type", "authorization_code"),
                    ("code_verifier", pkce_verifier),
                ])
                .send()
                .await
                .map_err(|e| AuthError::OAuthHttp(format!("{e}")))?;

            let status = resp.status();
            if !status.is_success() {
                let body = resp.text().await.unwrap_or_default();
                return Err(AuthError::OAuthTokenExchange(format!("{status}: {body}")));
            }

            let json: serde_json::Value = resp
                .json()
                .await
                .map_err(|e| AuthError::OAuthHttp(format!("{e}")))?;

            json.get("id_token")
                .and_then(|v| v.as_str())
                .map(|s| s.to_owned())
                .ok_or_else(|| {
                    AuthError::OAuthTokenExchange(
                        "missing id_token in Google token response".into(),
                    )
                })
        })
    }

    fn fetch_user_info<'a>(&'a self, access_token: &'a str) -> AuthFuture<'a, SocialUserInfo> {
        Box::pin(async move {
            let claims = decode_id_token(access_token)?;
            Ok(SocialUserInfo {
                provider_user_id: claims.sub,
                email: claims.email,
                email_verified: claims.email_verified,
                name: claims.name,
                avatar_url: claims.picture,
            })
        })
    }
}

// ── id_token decode helper ────────────────────────────────────────────────────

fn decode_id_token(token: &str) -> Result<GoogleIdTokenClaims, AuthError> {
    // A JWT is exactly three base64url segments separated by '.'.
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() != 3 {
        return Err(AuthError::OAuthUserInfoFetch("malformed id_token".into()));
    }
    let raw = Base64UrlUnpadded::decode_vec(parts[1]).map_err(|_| {
        AuthError::OAuthUserInfoFetch("id_token payload is not valid base64url".into())
    })?;
    serde_json::from_slice::<GoogleIdTokenClaims>(&raw).map_err(|e| {
        AuthError::OAuthUserInfoFetch(format!("id_token payload JSON parse error: {e}"))
    })
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::SocialProviderId;

    fn google_config() -> SocialProviderConfig {
        SocialProviderConfig {
            id: SocialProviderId::new(),
            provider_type: ProviderType::Google,
            display_name: "Google".into(),
            client_id: "test-client-id".into(),
            client_secret: "test-client-secret".into(),
            scopes: vec!["openid".into(), "email".into()],
            enabled: true,
            priority: 0,
            config: None,
        }
    }

    // ── Constructor validation ────────────────────────────────────────────────

    #[test]
    fn new_rejects_provider_type_mismatch() {
        let mut cfg = google_config();
        cfg.provider_type = ProviderType::Github;
        let err = GoogleSocialProvider::new(cfg).unwrap_err();
        assert!(matches!(err, AuthError::Validation(_)));
    }

    #[test]
    fn new_rejects_empty_scopes() {
        let mut cfg = google_config();
        cfg.scopes = vec![];
        let err = GoogleSocialProvider::new(cfg).unwrap_err();
        assert!(matches!(err, AuthError::Validation(_)));
    }

    // ── authorize_url ─────────────────────────────────────────────────────────

    #[test]
    fn authorize_url_contains_required_params() {
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let url = provider.authorize_url("https://example.com/callback", "mystate", "mychallenge");
        assert!(url.contains("client_id=test-client-id"), "url: {url}");
        assert!(url.contains("redirect_uri="), "url: {url}");
        assert!(url.contains("response_type=code"), "url: {url}");
        assert!(url.contains("state=mystate"), "url: {url}");
        assert!(url.contains("code_challenge=mychallenge"), "url: {url}");
        assert!(url.contains("code_challenge_method=S256"), "url: {url}");
    }

    #[test]
    fn authorize_url_uses_config_scopes_joined_by_space() {
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let url = provider.authorize_url("https://example.com/callback", "s", "c");
        // url crate percent-encodes spaces as %20 in query values
        assert!(
            url.contains("scope=openid+email") || url.contains("scope=openid%20email"),
            "url: {url}"
        );
    }

    #[test]
    fn authorize_url_does_not_leak_client_secret() {
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let url = provider.authorize_url("https://example.com/callback", "s", "c");
        assert!(!url.contains("test-client-secret"), "url: {url}");
    }

    // ── fetch_user_info (id_token decoding) ──────────────────────────────────

    fn make_id_token(payload: &serde_json::Value) -> String {
        let header = Base64UrlUnpadded::encode_string(b"{\"alg\":\"RS256\"}");
        let body = Base64UrlUnpadded::encode_string(payload.to_string().as_bytes());
        format!("{header}.{body}.fakesig")
    }

    #[tokio::test]
    async fn decode_id_token_extracts_claims() {
        let payload = serde_json::json!({
            "sub": "google-user-123",
            "email": "user@example.com",
            "email_verified": true,
            "name": "Test User",
            "picture": "https://example.com/photo.jpg"
        });
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let info = provider
            .fetch_user_info(&make_id_token(&payload))
            .await
            .unwrap();
        assert_eq!(info.provider_user_id, "google-user-123");
        assert_eq!(info.email, "user@example.com");
        assert!(info.email_verified);
        assert_eq!(info.name.as_deref(), Some("Test User"));
        assert_eq!(
            info.avatar_url.as_deref(),
            Some("https://example.com/photo.jpg")
        );
    }

    #[tokio::test]
    async fn decode_id_token_rejects_malformed_token() {
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let err = provider.fetch_user_info("only.two").await.unwrap_err();
        assert!(matches!(err, AuthError::OAuthUserInfoFetch(_)));
    }

    #[tokio::test]
    async fn decode_id_token_rejects_invalid_base64() {
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let err = provider
            .fetch_user_info("header.!!!invalid!!!.sig")
            .await
            .unwrap_err();
        assert!(matches!(err, AuthError::OAuthUserInfoFetch(_)));
    }

    #[tokio::test]
    async fn decode_id_token_rejects_non_json_payload() {
        let payload_b64 = Base64UrlUnpadded::encode_string(b"not json at all");
        let token = format!("header.{payload_b64}.sig");
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let err = provider.fetch_user_info(&token).await.unwrap_err();
        assert!(matches!(err, AuthError::OAuthUserInfoFetch(_)));
    }

    #[tokio::test]
    async fn decode_id_token_email_unverified_propagates() {
        let payload = serde_json::json!({
            "sub": "u1",
            "email": "u@example.com",
            "email_verified": false,
        });
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let info = provider
            .fetch_user_info(&make_id_token(&payload))
            .await
            .unwrap();
        assert!(!info.email_verified);
    }

    #[tokio::test]
    async fn decode_id_token_picture_maps_to_avatar_url() {
        let payload = serde_json::json!({
            "sub": "u1",
            "email": "u@example.com",
            "email_verified": true,
            "picture": "https://cdn.example.com/avatar.png"
        });
        let provider = GoogleSocialProvider::new(google_config()).unwrap();
        let info = provider
            .fetch_user_info(&make_id_token(&payload))
            .await
            .unwrap();
        assert_eq!(
            info.avatar_url.as_deref(),
            Some("https://cdn.example.com/avatar.png")
        );
    }

    // ── HTTP tests (wiremock) ─────────────────────────────────────────────────

    #[tokio::test]
    async fn exchange_code_extracts_id_token_on_success() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "unused-access",
                "id_token": "header.payload.sig",
                "token_type": "Bearer"
            })))
            .mount(&server)
            .await;

        let token_url = format!("{}/token", server.uri());
        let provider =
            GoogleSocialProvider::new_with_token_url(google_config(), token_url).unwrap();
        let id_token = provider
            .exchange_code("mycode", "https://example.com/cb", "pkce_v")
            .await
            .unwrap();
        assert_eq!(id_token, "header.payload.sig");
    }

    #[tokio::test]
    async fn exchange_code_returns_token_exchange_error_on_4xx() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/token"))
            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "error": "invalid_grant"
            })))
            .mount(&server)
            .await;

        let token_url = format!("{}/token", server.uri());
        let provider =
            GoogleSocialProvider::new_with_token_url(google_config(), token_url).unwrap();
        let err = provider
            .exchange_code("badcode", "https://example.com/cb", "v")
            .await
            .unwrap_err();
        assert!(matches!(err, AuthError::OAuthTokenExchange(_)));
    }

    #[tokio::test]
    async fn exchange_code_returns_token_exchange_error_on_missing_id_token() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "some-access-token",
                "token_type": "Bearer"
            })))
            .mount(&server)
            .await;

        let token_url = format!("{}/token", server.uri());
        let provider =
            GoogleSocialProvider::new_with_token_url(google_config(), token_url).unwrap();
        let err = provider
            .exchange_code("code", "https://example.com/cb", "v")
            .await
            .unwrap_err();
        match err {
            AuthError::OAuthTokenExchange(msg) => {
                assert!(msg.contains("missing id_token"), "got: {msg}");
            }
            other => panic!("expected OAuthTokenExchange, got {other:?}"),
        }
    }
}