alibi_plugins/oauth/providers/
cognito.rs1use 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#[derive(Clone)]
19pub struct CognitoOptions {
20 pub client_ids: Vec<String>,
21 pub client_secret: Option<String>,
22 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 pub jwks_source: Option<Arc<dyn OAuthJwksSource>>,
37 pub user_info_endpoint: Option<String>,
39 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 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 allowed_request_params: Vec::new(),
160 authorization_params: options
161 .identity_provider
162 .map(|value| vec![("identity_provider".into(), value)])
163 .unwrap_or_default(),
164 map_user_info: None,
165 account_subject: Some(subject),
166 get_user_info: Some(Arc::new(CognitoUserInfo {
167 endpoint,
168 mapper: options.map_profile_to_user,
169 })),
170 refresh_access_token: None,
171 verify_id_token: None,
172 id_token: Some(verification),
173 disable_id_token_sign_in: false,
174 disable_implicit_sign_up: false,
175 disable_sign_up: false,
176 allow_idp_initiated: false,
177 override_user_info_on_sign_in: false,
178 })
179 }
180}
181struct CognitoUserInfo {
182 endpoint: String,
183 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
184}
185#[async_trait]
186impl OAuthUserInfoHandler for CognitoUserInfo {
187 async fn get_user_info(
188 &self,
189 request: OAuthUserInfoRequest,
190 ) -> Result<OAuthUserInfoResponse, String> {
191 if let Some(token) = request.id_token.filter(|value| !value.is_empty())
192 && let Ok(mut profile) = decode_profile(&token)
193 {
194 let name = profile_name(&profile);
195 if let Some(object) = profile.as_object_mut() {
196 _ = object.insert("name".into(), name);
197 }
198 if let Ok(mapped) = self
201 .mapper
202 .map(|mapper| mapper(profile.clone()))
203 .transpose()
204 {
205 return finish_profile(profile, mapped);
206 }
207 }
208 let access_token = request
209 .access_token
210 .filter(|value| !value.is_empty())
211 .ok_or("Missing Cognito access token")?;
212 let profile: Value = reqwest::Client::new()
213 .get(&self.endpoint)
214 .bearer_auth(access_token)
215 .send()
216 .await
217 .map_err(|error| error.to_string())?
218 .error_for_status()
219 .map_err(|error| error.to_string())?
220 .json()
221 .await
222 .map_err(|error| error.to_string())?;
223 let mapped = self
224 .mapper
225 .map(|mapper| mapper(profile.clone()))
226 .transpose()?;
227 finish_profile(profile, mapped)
228 }
229}
230fn decode_profile(token: &str) -> Result<Value, String> {
231 let parts: Vec<_> = token.split('.').collect();
232 let [_, payload, _] = parts.as_slice() else {
233 return Err("Invalid Cognito ID token".into());
234 };
235 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
236 .decode(payload)
237 .map_err(|error| error.to_string())?;
238 let profile: Value =
239 alibi_core::utils::json::from_slice(&bytes).map_err(|error| error.to_string())?;
240 if !profile.is_object() {
241 return Err("Invalid Cognito ID-token claims set".into());
242 }
243 Ok(profile)
244}
245fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
246 match value {
247 None | Some(Value::Null) => Ok(None),
248 Some(Value::String(value)) => Ok(Some(value.clone())),
249 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
250 .map(Some)
251 .map_err(|error| error.to_string()),
252 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
253 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Cognito profile field".into()),
254 }
255}
256fn truthy(value: &Value) -> bool {
257 match value {
258 Value::Null | Value::Bool(false) => false,
259 Value::Number(value) => value.as_f64() != Some(0.0),
260 Value::String(value) => !value.is_empty(),
261 Value::Bool(true) | Value::Array(_) | Value::Object(_) => true,
262 }
263}
264fn profile_name(profile: &Value) -> Value {
265 ["name", "given_name", "username"]
266 .into_iter()
267 .filter_map(|key| profile.get(key))
268 .find(|value| truthy(value))
269 .cloned()
270 .unwrap_or_else(|| Value::String(String::new()))
271}
272fn finish_profile(
273 profile: Value,
274 mapped: Option<OAuthUserInfo>,
275) -> Result<OAuthUserInfoResponse, String> {
276 let id = scalar(profile.get("sub"))?.unwrap_or_default();
277 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
278 let user = match mapped {
279 Some(user) => user,
280 None => OAuthUserInfo {
281 additional_fields: Map::default(),
282 id,
283 email: profile
284 .get("email")
285 .and_then(Value::as_str)
286 .unwrap_or_default()
287 .into(),
288 name: Some(scalar(Some(&profile_name(&profile)))?.unwrap_or_default()),
289 image: scalar(profile.get("picture"))?,
290 email_verified: profile
291 .get("email_verified")
292 .and_then(Value::as_bool)
293 .unwrap_or(false),
294 },
295 };
296 Ok(OAuthUserInfoResponse {
297 user_output,
298 user,
299 data: profile,
300 })
301}
302fn subject(profile: &Value) -> Result<String, String> {
303 let id = scalar(profile.get("sub"))?.ok_or("Missing Cognito subject")?;
304 if id
305 .trim_matches(|character: char| {
306 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
307 })
308 .is_empty()
309 || id == "null"
310 || id == "undefined"
311 {
312 return Err("Invalid Cognito subject".into());
313 }
314 Ok(id)
315}