Skip to main content

alibi_plugins/oauth/providers/
cognito.rs

1//! Cognito's configured hosted domain, authenticated subject and profile fallback.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthScopeEncoding, OAuthTokenEndpointAuth,
4    OAuthUserInfo, OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use crate::oauth::{
7    HttpOAuthJwksSource, OAuthIdTokenConfig, OAuthJwksSelection, OAuthJwksSource,
8    OAuthNonceComparison,
9};
10use async_trait::async_trait;
11use base64::Engine;
12use serde_json::Map;
13use serde_json::Value;
14use std::sync::Arc;
15
16/// Immutable Cognito settings. Application callback and signup policies remain
17/// configurable on the returned provider.
18#[derive(Clone)]
19pub struct CognitoOptions {
20    pub client_ids: Vec<String>,
21    pub client_secret: Option<String>,
22    /// Forwarded only during authorization-code exchange, as the pinned helper
23    /// ignores this option during refresh.
24    pub client_key: Option<String>,
25    pub domain: String,
26    pub region: String,
27    pub user_pool_id: String,
28    pub require_client_secret: bool,
29    pub scope: Vec<String>,
30    pub disable_default_scope: bool,
31    pub prompt: Option<String>,
32    pub identity_provider: Option<String>,
33    pub authorization_endpoint: Option<String>,
34    pub redirect_uri: Option<String>,
35    /// Application-owned transport override; token claims cannot select it.
36    pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
37    /// Trusted user-info transport override retaining Cognito's profile mapping.
38    pub user_info_endpoint: Option<String>,
39    /// Receives the original profile, with the ID-token name fallback applied.
40    /// Its mapped ID cannot replace the authenticated raw `sub`.
41    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
42}
43impl CognitoOptions {
44    #[must_use]
45    pub fn new(
46        client_id: impl Into<String>,
47        client_secret: Option<String>,
48        domain: impl Into<String>,
49        region: impl Into<String>,
50        user_pool_id: impl Into<String>,
51    ) -> Self {
52        Self {
53            client_ids: vec![client_id.into()],
54            client_secret,
55            client_key: None,
56            domain: domain.into(),
57            region: region.into(),
58            user_pool_id: user_pool_id.into(),
59            require_client_secret: false,
60            scope: Vec::new(),
61            disable_default_scope: false,
62            prompt: None,
63            identity_provider: None,
64            authorization_endpoint: None,
65            redirect_uri: None,
66            jwks_source: None,
67            user_info_endpoint: None,
68            map_profile_to_user: None,
69        }
70    }
71}
72impl std::fmt::Debug for CognitoOptions {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("CognitoOptions")
75            .field("client_ids", &self.client_ids)
76            .field("domain", &self.domain)
77            .field("region", &self.region)
78            .field("user_pool_id", &self.user_pool_id)
79            .field("scope", &self.scope)
80            .field("disable_default_scope", &self.disable_default_scope)
81            .field("require_client_secret", &self.require_client_secret)
82            .finish_non_exhaustive()
83    }
84}
85impl OAuthProvider {
86    /// Builds the published Cognito provider from application-owned configuration.
87    ///
88    /// # Errors
89    /// Returns an error if the domain, region or user pool is empty.
90    pub fn cognito(options: CognitoOptions) -> Result<Self, String> {
91        if options.domain.is_empty() || options.region.is_empty() || options.user_pool_id.is_empty()
92        {
93            return Err("DOMAIN_AND_REGION_REQUIRED".into());
94        }
95        let domain = options
96            .domain
97            .strip_prefix("https://")
98            .or_else(|| options.domain.strip_prefix("http://"))
99            .unwrap_or(&options.domain);
100        let issuer = format!(
101            "https://cognito-idp.{}.amazonaws.com/{}",
102            options.region, options.user_pool_id
103        );
104        let endpoint = options
105            .user_info_endpoint
106            .unwrap_or_else(|| format!("https://{domain}/oauth2/userinfo"));
107        let verification = OAuthIdTokenConfig {
108            issuers: vec![issuer.clone()],
109            audience: None,
110            client_ids: Some(options.client_ids.clone()),
111            jwks_source: options.jwks_source.unwrap_or_else(|| {
112                Arc::new(HttpOAuthJwksSource::new(format!(
113                    "{issuer}/.well-known/jwks.json"
114                )))
115            }),
116            max_age_secs: Some(3600),
117            allow_opaque_token: false,
118            algorithm: None,
119            selection: OAuthJwksSelection::ExactKid,
120            nonce_comparison: OAuthNonceComparison::Exact,
121            verify_claims: None,
122        };
123        let mut clients = options.client_ids.into_iter();
124        let token_endpoint_auth = if options
125            .client_secret
126            .as_ref()
127            .is_some_and(|value| !value.is_empty())
128        {
129            OAuthTokenEndpointAuth::ClientSecretPost
130        } else {
131            OAuthTokenEndpointAuth::None
132        };
133        Ok(Self {
134            client_id: clients.next().unwrap_or_default(),
135            additional_client_ids: clients.collect(),
136            client_secret: options.client_secret.unwrap_or_default(),
137            hosted_domain: None,
138            require_email_verification: false,
139            auth_url: options
140                .authorization_endpoint
141                .filter(|value| !value.is_empty())
142                .unwrap_or_else(|| format!("https://{domain}/oauth2/authorize")),
143            token_url: format!("https://{domain}/oauth2/token"),
144            user_info_url: Some(endpoint.clone()),
145            scopes: vec!["openid".into(), "profile".into(), "email".into()],
146            authorization: Some(OAuthAuthorizationPolicy {
147                configured_scopes: options.scope,
148                scope_encoding: OAuthScopeEncoding::UriComponent,
149                disable_default_scopes: options.disable_default_scope,
150                require_client_id: true,
151                require_client_secret: options.require_client_secret,
152                token_endpoint_auth: Some(token_endpoint_auth),
153                authorization_code_client_key: options.client_key,
154                prompt: options.prompt,
155                redirect_uri: options.redirect_uri,
156                login_hint: false,
157                ..OAuthAuthorizationPolicy::default()
158            }),
159            authorization_params: options
160                .identity_provider
161                .map(|value| vec![("identity_provider".into(), value)])
162                .unwrap_or_default(),
163            map_user_info: None,
164            account_subject: Some(subject),
165            get_user_info: Some(Arc::new(CognitoUserInfo {
166                endpoint,
167                mapper: options.map_profile_to_user,
168            })),
169            refresh_access_token: None,
170            verify_id_token: None,
171            id_token: Some(verification),
172            disable_id_token_sign_in: false,
173            disable_implicit_sign_up: false,
174            disable_sign_up: false,
175            allow_idp_initiated: false,
176            override_user_info_on_sign_in: false,
177        })
178    }
179}
180struct CognitoUserInfo {
181    endpoint: String,
182    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
183}
184#[async_trait]
185impl OAuthUserInfoHandler for CognitoUserInfo {
186    async fn get_user_info(
187        &self,
188        request: OAuthUserInfoRequest,
189    ) -> Result<OAuthUserInfoResponse, String> {
190        if let Some(token) = request.id_token.filter(|value| !value.is_empty())
191            && let Ok(mut profile) = decode_profile(&token)
192        {
193            let name = profile_name(&profile);
194            if let Some(object) = profile.as_object_mut() {
195                _ = object.insert("name".into(), name);
196            }
197            // Only decoding or the application's mapper may select the access-token
198            // fallback. An invalid raw subject remains an admission failure.
199            if let Ok(mapped) = self
200                .mapper
201                .map(|mapper| mapper(profile.clone()))
202                .transpose()
203            {
204                return finish_profile(profile, mapped);
205            }
206        }
207        let access_token = request
208            .access_token
209            .filter(|value| !value.is_empty())
210            .ok_or("Missing Cognito access token")?;
211        let profile: Value = reqwest::Client::new()
212            .get(&self.endpoint)
213            .bearer_auth(access_token)
214            .send()
215            .await
216            .map_err(|error| error.to_string())?
217            .error_for_status()
218            .map_err(|error| error.to_string())?
219            .json()
220            .await
221            .map_err(|error| error.to_string())?;
222        let mapped = self
223            .mapper
224            .map(|mapper| mapper(profile.clone()))
225            .transpose()?;
226        finish_profile(profile, mapped)
227    }
228}
229fn decode_profile(token: &str) -> Result<Value, String> {
230    let parts: Vec<_> = token.split('.').collect();
231    let [_, payload, _] = parts.as_slice() else {
232        return Err("Invalid Cognito ID token".into());
233    };
234    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
235        .decode(payload)
236        .map_err(|error| error.to_string())?;
237    let profile: Value =
238        alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
239    if !profile.is_object() {
240        return Err("Invalid Cognito ID-token claims set".into());
241    }
242    Ok(profile)
243}
244fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
245    match value {
246        None | Some(Value::Null) => Ok(None),
247        Some(Value::String(value)) => Ok(Some(value.clone())),
248        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
249            .map(Some)
250            .map_err(|error| error.to_string()),
251        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
252        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Cognito profile field".into()),
253    }
254}
255fn truthy(value: &Value) -> bool {
256    match value {
257        Value::Null | Value::Bool(false) => false,
258        Value::Number(value) => value.as_f64() != Some(0.0),
259        Value::String(value) => !value.is_empty(),
260        Value::Bool(true) | Value::Array(_) | Value::Object(_) => true,
261    }
262}
263fn profile_name(profile: &Value) -> Value {
264    ["name", "given_name", "username"]
265        .into_iter()
266        .filter_map(|key| profile.get(key))
267        .find(|value| truthy(value))
268        .cloned()
269        .unwrap_or_else(|| Value::String(String::new()))
270}
271fn finish_profile(
272    profile: Value,
273    mapped: Option<OAuthUserInfo>,
274) -> Result<OAuthUserInfoResponse, String> {
275    let id = scalar(profile.get("sub"))?.unwrap_or_default();
276    let user_output = mapped.as_ref().map(|user| user.public_profile(true));
277    let user = match mapped {
278        Some(user) => user,
279        None => OAuthUserInfo {
280            additional_fields: Map::default(),
281            id,
282            email: profile
283                .get("email")
284                .and_then(Value::as_str)
285                .unwrap_or_default()
286                .into(),
287            name: Some(scalar(Some(&profile_name(&profile)))?.unwrap_or_default()),
288            image: scalar(profile.get("picture"))?,
289            email_verified: profile
290                .get("email_verified")
291                .and_then(Value::as_bool)
292                .unwrap_or(false),
293        },
294    };
295    Ok(OAuthUserInfoResponse {
296        user_output,
297        user,
298        data: profile,
299    })
300}
301fn subject(profile: &Value) -> Result<String, String> {
302    let id = scalar(profile.get("sub"))?.ok_or("Missing Cognito subject")?;
303    if id
304        .trim_matches(|character: char| {
305            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
306        })
307        .is_empty()
308        || id == "null"
309        || id == "undefined"
310    {
311        return Err("Invalid Cognito subject".into());
312    }
313    Ok(id)
314}