alibi-plugins 0.7.0

Built-in authentication plugins and API metadata for Alibi
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
//! Google One Tap authentication with verified Google ID tokens.
use crate::authentication_helpers::{JsonField, RequestBody, parse_body};
use crate::oauth::{
    OAuthConfig, OAuthProcessPolicy, OAuthSignInError, OAuthTokenSet, OAuthUserInfo,
    process_oauth_sign_in,
};
use alibi_core::utils::json::JsValue;
use alibi_core::{
    AuthContext, AuthPlugin, AuthRequest, AuthResponse, AuthResult, AuthRoute, AuthSchema,
    HttpMethod,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Map;
use serde_json::json;
use std::sync::Arc;

const MISSING_CLIENT: &str = "Google client ID is required for One Tap. Set it on the oneTap plugin (clientId) or on socialProviders.google.";

/// Google client IDs accepted as the ID-token audience.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OneTapClientId {
    Single(String),
    Multiple(Vec<String>),
}

impl From<String> for OneTapClientId {
    fn from(value: String) -> Self {
        Self::Single(value)
    }
}

impl From<&str> for OneTapClientId {
    fn from(value: &str) -> Self {
        Self::Single(value.into())
    }
}

impl From<Vec<String>> for OneTapClientId {
    fn from(value: Vec<String>) -> Self {
        Self::Multiple(value)
    }
}

pub use crate::oauth::OAuthJwksSource;

#[derive(Clone, Default)]
pub struct OneTapConfig {
    /// Overrides the registered Google provider's client IDs when truthy.
    pub client_id: Option<OneTapClientId>,
    pub disable_signup: bool,
    /// Optional application transport/cache; defaults to Google's official JWKS endpoint.
    pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
}

impl std::fmt::Debug for OneTapConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OneTapConfig").finish_non_exhaustive()
    }
}

pub struct OneTapPlugin {
    config: OneTapConfig,
    keys: Arc<dyn OAuthJwksSource>,
}

impl std::fmt::Debug for OneTapPlugin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OneTapPlugin").finish_non_exhaustive()
    }
}

impl Default for OneTapPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl OneTapPlugin {
    #[must_use]
    pub fn new() -> Self {
        Self::with_config(OneTapConfig::default())
    }
    #[must_use]
    pub fn with_config(config: OneTapConfig) -> Self {
        let keys = config.jwks_source.clone().unwrap_or_else(|| {
            Arc::new(crate::oauth::HttpOAuthJwksSource::new(
                "https://www.googleapis.com/oauth2/v3/certs",
            ))
        });
        Self { config, keys }
    }
    async fn callback<S: AuthSchema>(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<AuthResponse> {
        let content_type = req.headers.get("content-type");
        let media = content_type.map(|value| {
            value
                .split(';')
                .next()
                .unwrap_or_default()
                .trim()
                .to_ascii_lowercase()
        });
        if media.as_deref() != Some("application/json") {
            let message = media.map_or_else(
                || "Content-Type is required. Allowed types: application/json".to_owned(),
                |media| {
                    format!(
                        "Content-Type \"{media}\" is not allowed. Allowed types: application/json"
                    )
                },
            );
            return AuthResponse::json(
                415,
                &json!({"code":"UNSUPPORTED_MEDIA_TYPE","message":message}),
            )
            .map_err(Into::into);
        }
        let body: OneTapCallbackInput = match parse_body(req) {
            Ok(body) => body,
            Err(response) => return Ok(response),
        };
        if !ctx.config.current_origin_check_disabled()
            && body
                .callback_url
                .as_deref()
                .is_some_and(|url| !ctx.config.is_redirect_target_trusted(url))
        {
            return AuthResponse::json(
                403,
                &json!({"code":"INVALID_CALLBACK_URL","message":"Invalid callbackURL"}),
            )
            .map_err(Into::into);
        }
        self.callback_core(req, ctx, body).await
    }

    #[expect(
        clippy::too_many_lines,
        reason = "Keep provider token validation, account linking policy, and session issuance in their request order"
    )]
    async fn callback_core<S: AuthSchema>(
        &self,
        req: &impl alibi_core::session::SessionRequest,
        ctx: &AuthContext<S>,
        body: OneTapCallbackInput,
    ) -> AuthResult<AuthResponse> {
        use alibi_core::utils::cookie_utils::{
            create_session_cookie_with_max_age, create_session_like_cookie, related_cookie_name,
            sign_cookie_value, verify_cookie_value,
        };
        let oauth = ctx.extensions.get::<OAuthConfig>();
        let provider = oauth
            .as_ref()
            .and_then(|config| config.providers.get("google"));
        let audiences = match &self.config.client_id {
            Some(OneTapClientId::Single(value)) if !value.is_empty() => vec![value.clone()],
            Some(OneTapClientId::Multiple(values)) => values.clone(),
            _ => provider
                .map(|provider| {
                    let mut values = vec![provider.client_id.clone()];
                    values.extend(provider.additional_client_ids.clone());
                    values
                })
                .unwrap_or_default(),
        };
        if audiences.is_empty()
            || !matches!(&self.config.client_id, Some(OneTapClientId::Multiple(_)))
                && audiences.len() == 1
                && audiences.first().is_some_and(String::is_empty)
        {
            return message(400, MISSING_CLIENT);
        }
        let Some(payload) = self.verify(&body.id_token, &audiences).await else {
            return message(400, "invalid id token");
        };
        if !payload.get("sub").is_some_and(js_truthy) {
            return message(400, "invalid id token");
        }
        let hosted_domain = provider
            .and_then(|provider| provider.hosted_domain.as_deref())
            .filter(|domain| !domain.is_empty());
        if let Some(domain) = hosted_domain {
            let token_domain = payload
                .get("hd")
                .and_then(JsValue::as_str)
                .filter(|value| !value.is_empty());
            if token_domain.is_none() || domain != "*" && token_domain != Some(domain) {
                return message(400, "invalid id token");
            }
        }
        let Some(email) = payload
            .get("email")
            .and_then(JsValue::as_str)
            .filter(|value| !value.is_empty())
        else {
            return message(400, "Email not available in token");
        };
        let Some(sub) = payload
            .get("sub")
            .and_then(JsValue::as_str)
            .filter(|value| !value.is_empty())
        else {
            return message(400, "invalid id token");
        };
        let user = OAuthUserInfo {
            additional_fields: Map::default(),
            id: sub.into(),
            email: email.to_lowercase(),
            name: Some(
                payload
                    .get("name")
                    .and_then(JsValue::as_str)
                    .unwrap_or_default()
                    .into(),
            ),
            image: payload
                .get("picture")
                .and_then(JsValue::as_str)
                .map(str::to_owned),
            email_verified: payload.get("email_verified").is_some_and(|value| {
                value.as_bool() == Some(true) || value.as_str() == Some("true")
            }),
        };
        let policy = OAuthProcessPolicy {
            override_user_info: false,
            require_email_verification: provider
                .is_some_and(|provider| provider.require_email_verification),
            callback_url: None,
            use_updated_user: false,
        };
        let tokens = OAuthTokenSet {
            id_token: Some(body.id_token),
            scopes: vec!["openid".into(), "profile".into(), "email".into()],
            ..Default::default()
        };
        let headers = req.session_headers();
        let meta = if let Some(request) = req.physical_request() {
            alibi_core::RequestMeta::from_request(request)
        } else {
            alibi_core::RequestMeta {
                ip_address: Some(
                    ctx.config
                        .advanced
                        .ip_address
                        .resolve_ip(headers)
                        .unwrap_or_default(),
                ),
                user_agent: Some(headers.get("user-agent").cloned().unwrap_or_default()),
            }
        };
        let result = process_oauth_sign_in(
            super::oauth::handlers::OAuthIdentity {
                provider_name: "google",
                user: &user,
                profile: &payload.to_json_value()?,
            },
            &policy,
            &tokens,
            self.config.disable_signup || provider.is_some_and(|provider| provider.disable_sign_up),
            &meta,
            ctx,
        )
        .await;
        let outcome = match result {
            Ok(outcome) => outcome,
            Err(OAuthSignInError::IdentityDenied { code, message }) => {
                return AuthResponse::json(403, &json!({"code":code,"message":message}))
                    .map_err(Into::into);
            }
            Err(OAuthSignInError::AccountLookup(_)) => {
                return Ok(crate::oauth::handlers::ambiguous_account_sign_in_response(
                    ctx,
                ));
            }
            Err(OAuthSignInError::Generic(error)) => return message(401, &error),
            Err(OAuthSignInError::SessionAuth(error)) => return message(401, &error.to_string()),
            Err(OAuthSignInError::Banned(error)) => {
                return AuthResponse::json(403, &json!({"code":"BANNED_USER","message":error}))
                    .map_err(Into::into);
            }
            Err(OAuthSignInError::EmailNotVerified) => {
                return AuthResponse::json(
                    403,
                    &json!({"code":"EMAIL_NOT_VERIFIED","message":"Email not verified"}),
                )
                .map_err(Into::into);
            }
        };

        let dont_remember_name = related_cookie_name(&ctx.config, "dont_remember");
        let dont_remember = crate::helpers::get_cookie(req, &dont_remember_name)
            .and_then(|value| verify_cookie_value(&value, ctx.config.current_secret()))
            .is_some_and(|value| !value.is_empty());
        let max_age = (!dont_remember).then(|| ctx.config.session.expires_in.num_seconds());
        let mut response = AuthResponse::json(
            200,
            &json!({"token":outcome.session.token,"user":outcome.user}),
        )?
        .with_appended_header(
            "Set-Cookie",
            create_session_cookie_with_max_age(Some(&outcome.session.token), max_age, &ctx.config)?,
        );
        if dont_remember {
            response = response.with_appended_header(
                "Set-Cookie",
                create_session_like_cookie(
                    &dont_remember_name,
                    &sign_cookie_value("true", ctx.config.current_secret()),
                    None,
                    &ctx.config,
                )?,
            );
        }
        if let Some(cookie) = outcome.account_cookie.as_ref() {
            for header in crate::oauth::create_account_cookie_headers(&ctx.config, cookie, req)? {
                response.headers.append("Set-Cookie", header);
            }
        }
        Ok(response)
    }
    /// Authenticate a verified Google credential through the public server API.
    /// # Errors
    /// Returns an input serialization error.
    pub fn one_tap_callback_endpoint(
        input: &OneTapCallbackInput,
    ) -> AuthResult<alibi_core::endpoint::ServerEndpoint<OneTapAuthenticated>> {
        alibi_core::endpoint::ServerEndpoint::new("one-tap", "oneTapCallback").with_body(input)
    }

    async fn verify(&self, token: &str, audience: &[String]) -> Option<JsValue> {
        let mut policy = crate::oauth::OAuthIdTokenConfig::google();
        policy.selection = crate::oauth::OAuthJwksSelection::AllMatching;
        policy.jwks_source = self.keys.clone();
        crate::oauth::id_token::verify_jwks_token(token, audience, None, &policy).await
    }
}

/// Signed Google credential and optional callback URL for a One Tap server call.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OneTapCallbackInput {
    pub id_token: String,
    #[serde(rename = "callbackURL", skip_serializing_if = "Option::is_none")]
    pub callback_url: Option<String>,
}

/// The Google account owner's new session token and public user view.
#[derive(Debug, Deserialize)]
pub struct OneTapAuthenticated {
    pub token: String,
    pub user: Box<alibi_core::UserView>,
}

impl RequestBody for OneTapCallbackInput {
    const FIELDS: &'static [JsonField] = &[
        JsonField::string("idToken", true),
        JsonField::string("callbackURL", false),
    ];
}

#[async_trait]
impl<S: AuthSchema> AuthPlugin<S> for OneTapPlugin {
    route_openapi_metadata!(S);

    fn server_endpoints(&self) -> Vec<alibi_core::endpoint::EndpointDefinition> {
        vec![crate::endpoint::definition(
            "oneTapCallback",
            "oneTapCallback",
            Some("/one-tap/callback"),
            HttpMethod::Post,
        )]
    }
    fn validate_endpoint(
        &self,
        call: &alibi_core::endpoint::EndpointCall,
        _ctx: &AuthContext<S>,
    ) -> AuthResult<alibi_core::endpoint::EndpointInput> {
        Ok(alibi_core::endpoint::EndpointInput {
            body: Some(crate::endpoint::validate_fields(
                call.body(),
                "body",
                OneTapCallbackInput::FIELDS,
            )?),
            query: call.query().cloned(),
        })
    }
    async fn on_endpoint(
        &self,
        call: &alibi_core::endpoint::EndpointCall,
        ctx: &AuthContext<S>,
    ) -> AuthResult<alibi_core::endpoint::EndpointResponse> {
        let output = self.callback_core(call, ctx, call.body_as()?).await?;
        let value = alibi_core::utils::json::from_slice::<JsValue>(&output.body)?;
        let mut response = if output.status >= 400 {
            alibi_core::endpoint::EndpointResponse::error(crate::endpoint::error_response(
                output.clone(),
            ))
            .with_error_body(value)
        } else {
            alibi_core::endpoint::EndpointResponse::value(value)
        };
        response.set_status(Some(output.status));
        response.merge_headers(output.headers);
        Ok(response)
    }
    fn name(&self) -> &'static str {
        "one-tap"
    }
    fn routes(&self) -> Vec<AuthRoute> {
        vec![AuthRoute::post("/one-tap/callback", "one_tap_callback")]
    }
    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<AuthResponse>> {
        if req.method() == &HttpMethod::Post && req.path() == "/one-tap/callback" {
            return self.callback(req, ctx).await.map(Some);
        }
        Ok(None)
    }
}

fn js_truthy(value: &JsValue) -> bool {
    match value {
        JsValue::Null => false,
        JsValue::Bool(value) => *value,
        JsValue::Number(value) => *value != 0.0 && !value.is_nan(),
        JsValue::String(value) => !value.is_empty(),
        JsValue::Array(_) | JsValue::Object(_) => true,
    }
}

fn message(status: u16, message: &str) -> AuthResult<AuthResponse> {
    AuthResponse::json(status, &json!({"message":message})).map_err(Into::into)
}