Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(oidc): Implement OIDC authorize and token flows (#10147)
Kanika Bansal37cc3f7f7193
diff --git a/crates/api_models/src/oidc.rs b/crates/api_models/src/oidc.rsindex bb9b797194..e756f77f57 100644--- a/crates/api_models/src/oidc.rs+++ b/crates/api_models/src/oidc.rs@@ -10,7 +10,7 @@ const RESPONSE_MODES_SUPPORTED: &[ResponseMode] = &[ResponseMode::Query];const SUBJECT_TYPES_SUPPORTED: &[SubjectType] = &[SubjectType::Public];const ID_TOKEN_SIGNING_ALGS_SUPPORTED: &[SigningAlgorithm] = &[SigningAlgorithm::Rs256];const GRANT_TYPES_SUPPORTED: &[GrantType] = &[GrantType::AuthorizationCode];-const SCOPES_SUPPORTED: &[Scope] = &[Scope::Openid, Scope::Email];+const SCOPES_SUPPORTED: &[Scope] = &[Scope::Openid, Scope::Email, Scope::Profile];const TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED: &[TokenAuthMethod] =&[TokenAuthMethod::ClientSecretBasic];const CLAIMS_SUPPORTED: &[Claim] = &[@@ -21,6 +21,7 @@ const CLAIMS_SUPPORTED: &[Claim] = &[Claim::Iat,Claim::Iss,Claim::Sub,+ Claim::PreferredUsername,];/// OIDC Response Type@@ -81,6 +82,7 @@ pub enum GrantType {pub enum Scope {Openid,Email,+ Profile,}/// OIDC Token Endpoint Authentication Method@@ -101,33 +103,7 @@ pub enum Claim {Iat,Iss,Sub,-}--/// OIDC Authorization Error as per RFC 6749-#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display)]-#[serde(rename_all = "snake_case")]-#[strum(serialize_all = "snake_case")]-pub enum OidcAuthorizationError {- InvalidRequest,- UnauthorizedClient,- AccessDenied,- UnsupportedResponseType,- InvalidScope,- ServerError,- TemporarilyUnavailable,-}--/// OIDC Token Error as per RFC 6749-#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display)]-#[serde(rename_all = "snake_case")]-#[strum(serialize_all = "snake_case")]-pub enum OidcTokenError {- InvalidRequest,- InvalidClient,- InvalidGrant,- UnauthorizedClient,- UnsupportedGrantType,- InvalidScope,+ PreferredUsername,}/// OpenID Connect Discovery Response@@ -286,7 +262,7 @@ pub struct OidcAuthorizeQuery {/// String value used to associate a Client session with an ID Token#[schema(example = "nonce_abc123")]- pub nonce: Option<String>,+ pub nonce: String,}/// OIDC Token Request@@ -302,15 +278,15 @@ pub struct OidcTokenRequest {/// Redirection URI that was used in the authorization request#[schema(example = "https://example.com/callback")]pub redirect_uri: String,-- /// OAuth 2.0 Client Identifier- #[schema(example = "client_abc123")]- pub client_id: String,}/// OIDC Token Response#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct OidcTokenResponse {+ /// Access Token value for API access+ #[schema(value_type = String)]+ pub access_token: Secret<String>,+/// ID Token value associated with the authenticated session#[schema(value_type = String)]pub id_token: Secret<String>,@@ -319,7 +295,7 @@ pub struct OidcTokenResponse {#[schema(example = "Bearer")]pub token_type: String,- /// Expiration time of the ID Token in seconds since the response was generated+ /// Expiration time of the Access Token in seconds since the response was generated#[schema(example = 3600)]pub expires_in: u64,}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 5284394bbe..f2766e4f40 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -40,6 +40,7 @@ pub use payment_methods::configs::settings::{SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,SupportedPaymentMethodsForMandate, ZeroMandates,};+use rand::seq::IteratorRandom;use redis_interface::RedisSettings;pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};use rust_decimal::Decimal;@@ -742,7 +743,8 @@ impl OidcSettings {}pub fn get_signing_key(&self) -> Option<&OidcKey> {- self.key.values().next()+ let mut rng = rand::thread_rng();+ self.key.values().choose_stable(&mut rng)}pub fn get_all_keys(&self) -> Vec<&OidcKey> {diff --git a/crates/router/src/consts/oidc.rs b/crates/router/src/consts/oidc.rsindex 8d0bfb3898..bafbf52b0d 100644--- a/crates/router/src/consts/oidc.rs+++ b/crates/router/src/consts/oidc.rs@@ -1,5 +1,6 @@pub const REDIS_AUTH_CODE_PREFIX: &str = "OIDC_AUTH_CODE_";pub const AUTH_CODE_TTL_IN_SECS: i64 = 60 * 5; // 5 minutes-pub const ID_TOKEN_TTL_IN_SECS: u64 = 60 * 60; // 1 hour+pub const ID_TOKEN_TTL_IN_SECS: u64 = 60 * 15; // 15 minutes+pub const ACCESS_TOKEN_TTL_IN_SECS: u64 = 60 * 60; // 1 hourpub const AUTH_CODE_LENGTH: usize = 32;pub const TOKEN_TYPE_BEARER: &str = "Bearer";diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex 39b52e16ab..9b8403e925 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -1,6 +1,8 @@pub mod chat;pub mod customers_error_response;pub mod error_handlers;+#[cfg(feature = "olap")]+pub mod oidc;pub mod transformers;#[cfg(feature = "olap")]pub mod user;diff --git a/crates/router/src/core/errors/oidc.rs b/crates/router/src/core/errors/oidc.rsnew file mode 100644index 0000000000..9f754bff24--- /dev/null+++ b/crates/router/src/core/errors/oidc.rs@@ -0,0 +1,123 @@+use common_utils::errors::CustomResult;++use crate::services::ApplicationResponse;++pub type OidcResult<T> = CustomResult<T, OidcErrors>;+pub type OidcResponse<T> = CustomResult<ApplicationResponse<T>, OidcErrors>;++#[derive(Debug, thiserror::Error)]+pub enum OidcErrors {+ #[error("Invalid OIDC request")]+ InvalidRequest,+ #[error("Unauthorized client")]+ UnauthorizedClient,+ #[error("Access denied")]+ AccessDenied,+ #[error("Invalid scope")]+ InvalidScope,+ #[error("OIDC server error")]+ ServerError,+ #[error("Invalid token request")]+ InvalidTokenRequest,+ #[error("Invalid client")]+ InvalidClient,+ #[error("Invalid grant")]+ InvalidGrant,+}++impl OidcErrors {+ /// Returns the RFC 6749 compliant error code+ fn get_rfc_error_code(&self) -> &'static str {+ match self {+ Self::InvalidRequest => "invalid_request",+ Self::UnauthorizedClient => "unauthorized_client",+ Self::AccessDenied => "access_denied",+ Self::InvalidScope => "invalid_scope",+ Self::ServerError => "server_error",+ Self::InvalidTokenRequest => "invalid_request",+ Self::InvalidClient => "invalid_client",+ Self::InvalidGrant => "invalid_grant",+ }+ }++ /// Returns the RFC 6749 compliant error description+ fn get_error_message(&self) -> &'static str {+ match self {+ Self::InvalidRequest => "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed",+ Self::UnauthorizedClient => "The client is not authorized to request an authorization code using this method",+ Self::AccessDenied => "The resource owner or authorization server denied the request",+ Self::InvalidScope => "The requested scope is invalid, unknown, or malformed",+ Self::ServerError => "The authorization server encountered an unexpected condition that prevented it from fulfilling the request",+ Self::InvalidTokenRequest => "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed",+ Self::InvalidClient => "Client authentication failed",+ Self::InvalidGrant => "The provided authorization grant is invalid, expired, revoked, or does not match the redirection URI used in the authorization request",+ }+ }++ /// Returns a formatted RFC-compliant error message+ pub fn get_rfc_formatted_message(&self) -> String {+ format!(+ "{}: {}",+ self.get_rfc_error_code(),+ self.get_error_message()+ )+ }+}++impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for OidcErrors {+ fn switch(&self) -> api_models::errors::types::ApiErrorResponse {+ use api_models::errors::types::{ApiError, ApiErrorResponse as AER};+ let sub_code = "OI";++ match self {+ Self::InvalidRequest => AER::BadRequest(ApiError::new(+ sub_code,+ 1,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::UnauthorizedClient => AER::Unauthorized(ApiError::new(+ sub_code,+ 2,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::AccessDenied => AER::Unauthorized(ApiError::new(+ sub_code,+ 3,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::InvalidScope => AER::BadRequest(ApiError::new(+ sub_code,+ 4,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::ServerError => AER::InternalServerError(ApiError::new(+ sub_code,+ 5,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::InvalidTokenRequest => AER::BadRequest(ApiError::new(+ sub_code,+ 6,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::InvalidClient => AER::Unauthorized(ApiError::new(+ sub_code,+ 7,+ self.get_rfc_formatted_message(),+ None,+ )),+ Self::InvalidGrant => AER::BadRequest(ApiError::new(+ sub_code,+ 8,+ self.get_rfc_formatted_message(),+ None,+ )),+ }+ }+}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 99aa201c97..c7ae538c87 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1820,6 +1820,8 @@ impl Oidc {.route(web::get().to(oidc::oidc_discovery)),).service(web::resource("/oauth2/jwks").route(web::get().to(oidc::jwks_endpoint)))+ .service(web::resource("/oidc/authorize").route(web::get().to(oidc::oidc_authorize)))+ .service(web::resource("/oauth2/token").route(web::post().to(oidc::oidc_token)))}}diff --git a/crates/router/src/routes/oidc.rs b/crates/router/src/routes/oidc.rsindex b98f51ff30..a1de0352e0 100644--- a/crates/router/src/routes/oidc.rs+++ b/crates/router/src/routes/oidc.rs@@ -1,4 +1,5 @@use actix_web::{web, HttpRequest, HttpResponse};+use api_models::oidc as oidc_types;use router_env::{instrument, tracing, Flow};use crate::{@@ -10,9 +11,8 @@ use crate::{/// OpenID Connect Discovery Document#[instrument(skip_all, fields(flow = ?Flow::OidcDiscovery))]pub async fn oidc_discovery(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {- let flow = Flow::OidcDiscovery;Box::pin(api::server_wrap(- flow,+ Flow::OidcDiscovery,state,&req,(),@@ -26,9 +26,8 @@ pub async fn oidc_discovery(state: web::Data<AppState>, req: HttpRequest) -> Htt/// JWKS Endpoint - Exposes public keys for ID token verification#[instrument(skip_all, fields(flow = ?Flow::OidcJwks))]pub async fn jwks_endpoint(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {- let flow = Flow::OidcJwks;Box::pin(api::server_wrap(- flow,+ Flow::OidcJwks,state,&req,(),@@ -38,3 +37,48 @@ pub async fn jwks_endpoint(state: web::Data<AppState>, req: HttpRequest) -> Http)).await}++#[instrument(skip_all, fields(flow = ?Flow::OidcAuthorize))]+pub async fn oidc_authorize(+ state: web::Data<AppState>,+ req: HttpRequest,+ query_params: web::Query<oidc_types::OidcAuthorizeQuery>,+) -> HttpResponse {+ Box::pin(api::server_wrap(+ Flow::OidcAuthorize,+ state,+ &req,+ query_params.into_inner(),+ |state,+ user: Option<auth::UserFromToken>,+ req_payload: oidc_types::OidcAuthorizeQuery,+ _| oidc_provider::process_authorize_request(state, req_payload, user),+ auth::auth_type(+ &auth::NoAuth,+ &auth::DashboardNoPermissionAuth,+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[instrument(skip_all, fields(flow = ?Flow::OidcToken))]+pub async fn oidc_token(+ state: web::Data<AppState>,+ req: HttpRequest,+ form_data: web::Form<oidc_types::OidcTokenRequest>,+) -> HttpResponse {+ Box::pin(api::server_wrap(+ Flow::OidcToken,+ state,+ &req,+ form_data.into_inner(),+ |state, client_id: String, req_body, _| {+ oidc_provider::process_token_request(state, req_body, client_id)+ },+ &auth::OIDC_CLIENT_AUTH,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/services/oidc_provider.rs b/crates/router/src/services/oidc_provider.rsindex b0a758534d..a08926f06d 100644--- a/crates/router/src/services/oidc_provider.rs+++ b/crates/router/src/services/oidc_provider.rs@@ -1,18 +1,27 @@+use std::time::{Duration, SystemTime, UNIX_EPOCH};+use api_models::oidc::{- Jwk, JwksResponse, KeyType, KeyUse, OidcDiscoveryResponse, SigningAlgorithm,+ Jwk, JwksResponse, KeyType, KeyUse, OidcAuthorizeQuery, OidcDiscoveryResponse,+ OidcTokenRequest, OidcTokenResponse, Scope, SigningAlgorithm,};-use error_stack::ResultExt;+use error_stack::{report, ResultExt};+use masking::PeekInterface;use once_cell::sync::OnceCell;+use router_env::logger;use crate::{- core::errors::{ApiErrorResponse, RouterResponse},+ consts::oidc::{+ ACCESS_TOKEN_TTL_IN_SECS, AUTH_CODE_LENGTH, ID_TOKEN_TTL_IN_SECS, TOKEN_TYPE_BEARER,+ },+ core::errors::oidc::{OidcErrors, OidcResponse, OidcResult},routes::app::SessionState,- services::api::ApplicationResponse,- utils::user as user_utils,+ services::{api::ApplicationResponse, authentication::UserFromToken, jwt},+ types::domain::user::oidc::{AccessTokenClaims, AuthCodeData, IdTokenClaims},+ utils::{oidc as oidc_utils, user as user_utils},};/// Build OIDC discovery document-pub async fn get_discovery_document(state: SessionState) -> RouterResponse<OidcDiscoveryResponse> {+pub async fn get_discovery_document(state: SessionState) -> OidcResponse<OidcDiscoveryResponse> {let backend_base_url = state.tenant.base_url.clone();let control_center_url = user_utils::get_base_url(&state);@@ -24,7 +33,7 @@ pub async fn get_discovery_document(state: SessionState) -> RouterResponse<OidcDstatic CACHED_JWKS: OnceCell<JwksResponse> = OnceCell::new();/// Build JWKS response with public keys (all keys for token validation)-pub async fn get_jwks(state: SessionState) -> RouterResponse<&'static JwksResponse> {+pub async fn get_jwks(state: SessionState) -> OidcResponse<&'static JwksResponse> {CACHED_JWKS.get_or_try_init(|| {let oidc_keys = state.conf.oidc.get_inner().get_all_keys();@@ -34,7 +43,7 @@ pub async fn get_jwks(state: SessionState) -> RouterResponse<&'static JwksResponlet (n, e) = common_utils::crypto::extract_rsa_public_key_components(&key_config.private_key,)- .change_context(ApiErrorResponse::InternalServerError)+ .change_context(OidcErrors::ServerError).attach_printable("Failed to extract public key from private key")?;let jwk = Jwk {@@ -49,7 +58,224 @@ pub async fn get_jwks(state: SessionState) -> RouterResponse<&'static JwksResponkeys.push(jwk);}- Ok::<_, error_stack::Report<ApiErrorResponse>>(JwksResponse { keys })+ Ok(JwksResponse { keys })}).map(ApplicationResponse::Json)}++fn validate_authorize_params(payload: &OidcAuthorizeQuery, state: &SessionState) -> OidcResult<()> {+ payload+ .scope+ .contains(&Scope::Openid)+ .then_some(())+ .ok_or_else(|| report!(OidcErrors::InvalidScope))+ .attach_printable("Missing required scope in authorization request")?;++ let client = state+ .conf+ .oidc+ .get_inner()+ .get_client(&payload.client_id)+ .ok_or_else(|| report!(OidcErrors::UnauthorizedClient))+ .attach_printable("Invalid client ID")?;++ oidc_utils::validate_redirect_uri_match(&client.redirect_uri, &payload.redirect_uri)+ .then_some(())+ .ok_or_else(|| report!(OidcErrors::InvalidRequest))+ .attach_printable("Redirect URI mismatch")+}++async fn generate_and_store_authorization_code(+ state: &SessionState,+ user_id: &str,+ payload: &OidcAuthorizeQuery,+) -> OidcResult<String> {+ let user_from_db = state+ .global_store+ .find_user_by_id(user_id)+ .await+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to fetch user from database")?;++ let auth_code =+ common_utils::crypto::generate_cryptographically_secure_random_string(AUTH_CODE_LENGTH);++ let auth_code_data = AuthCodeData {+ sub: user_id.to_string(),+ client_id: payload.client_id.clone(),+ redirect_uri: payload.redirect_uri.clone(),+ scope: payload.scope.clone(),+ nonce: payload.nonce.clone(),+ email: user_from_db.email,+ is_verified: user_from_db.is_verified,+ };++ oidc_utils::set_auth_code_in_redis(state, &auth_code, &auth_code_data)+ .await+ .attach_printable("Failed to store authorization code")?;++ Ok(auth_code)+}++pub async fn process_authorize_request(+ state: SessionState,+ payload: OidcAuthorizeQuery,+ user: Option<UserFromToken>,+) -> OidcResponse<()> {+ // Validate all parameters+ validate_authorize_params(&payload, &state)?;+ // TODO: Handle users who are not already logged in+ let user = user+ .ok_or_else(|| report!(OidcErrors::AccessDenied))+ .attach_printable("Missing authenticated user session")?;++ let auth_code = generate_and_store_authorization_code(&state, &user.user_id, &payload).await?;++ oidc_utils::build_oidc_redirect_url(&payload.redirect_uri, &auth_code, &payload.state)+ .attach_printable("Failed to build redirect URL")+ .map(oidc_utils::build_redirection_response)+}++fn validate_token_request(+ state: &SessionState,+ client_id: &str,+ redirect_uri: &str,+) -> OidcResult<()> {+ if redirect_uri.trim().is_empty() {+ return Err(report!(OidcErrors::InvalidTokenRequest))+ .attach_printable("Redirect URI is empty or contains only whitespace");+ }++ let registered_client = state+ .conf+ .oidc+ .get_inner()+ .get_client(client_id)+ .ok_or_else(|| report!(OidcErrors::InvalidClient))+ .attach_printable("Invalid client ID")?;++ if !oidc_utils::validate_redirect_uri_match(®istered_client.redirect_uri, redirect_uri) {+ return Err(report!(OidcErrors::InvalidTokenRequest))+ .attach_printable("Redirect URI mismatch");+ }++ Ok(())+}++async fn validate_and_consume_authorization_code(+ state: &SessionState,+ code: &str,+ client_id: &str,+ redirect_uri: &str,+) -> OidcResult<AuthCodeData> {+ let auth_code_data = oidc_utils::get_auth_code_from_redis(state, code).await?;++ if let Err(err) = oidc_utils::delete_auth_code_from_redis(state, code).await {+ logger::warn!(+ error = ?err,+ "Failed to delete authorization code from Redis after consumption"+ );+ }++ if !oidc_utils::validate_client_id_match(&auth_code_data.client_id, client_id) {+ return Err(report!(OidcErrors::InvalidGrant)).attach_printable("Client ID mismatch");+ }++ if !oidc_utils::validate_redirect_uri_match(&auth_code_data.redirect_uri, redirect_uri) {+ return Err(report!(OidcErrors::InvalidGrant)).attach_printable("Redirect URI mismatch");+ }++ Ok(auth_code_data)+}++async fn generate_id_token(+ state: &SessionState,+ auth_code_data: &AuthCodeData,+) -> OidcResult<String> {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .change_context(OidcErrors::ServerError)?+ .as_secs();+ let exp_duration = Duration::from_secs(ID_TOKEN_TTL_IN_SECS);+ let exp = jwt::generate_exp(exp_duration)+ .change_context(OidcErrors::ServerError)?+ .as_secs();++ let include_email_claims = auth_code_data.scope.contains(&Scope::Email);+ let include_profile_claims = auth_code_data.scope.contains(&Scope::Profile);++ let claims = IdTokenClaims {+ iss: state.tenant.base_url.clone(),+ sub: auth_code_data.sub.clone(),+ aud: auth_code_data.client_id.clone(),+ iat: now,+ exp,+ email: include_email_claims.then_some(auth_code_data.email.clone()),+ email_verified: include_email_claims.then_some(auth_code_data.is_verified),+ preferred_username: include_profile_claims+ .then_some(auth_code_data.email.peek().to_string()),+ nonce: auth_code_data.nonce.clone(),+ };++ oidc_utils::sign_oidc_token(state, claims, "ID token")+ .await+ .attach_printable("Failed to sign ID token")+}++async fn generate_access_token(+ state: &SessionState,+ auth_code_data: &AuthCodeData,+) -> OidcResult<String> {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .change_context(OidcErrors::ServerError)?+ .as_secs();+ let exp_duration = Duration::from_secs(ACCESS_TOKEN_TTL_IN_SECS);+ let exp = jwt::generate_exp(exp_duration)+ .change_context(OidcErrors::ServerError)?+ .as_secs();++ let include_profile_claims = auth_code_data.scope.contains(&Scope::Profile);++ let claims = AccessTokenClaims {+ iss: state.tenant.base_url.clone(),+ sub: auth_code_data.sub.clone(),+ aud: auth_code_data.client_id.clone(),+ iat: now,+ exp,+ email: auth_code_data.email.clone(),+ preferred_username: include_profile_claims+ .then_some(auth_code_data.email.peek().to_string()),+ scope: auth_code_data.scope.clone(),+ };++ oidc_utils::sign_oidc_token(state, claims, "access token")+ .await+ .attach_printable("Failed to sign access token")+}++pub async fn process_token_request(+ state: SessionState,+ payload: OidcTokenRequest,+ client_id: String,+) -> OidcResponse<OidcTokenResponse> {+ validate_token_request(&state, &client_id, &payload.redirect_uri)?;++ let auth_code_data = validate_and_consume_authorization_code(+ &state,+ &payload.code,+ &client_id,+ &payload.redirect_uri,+ )+ .await?;++ let access_token = generate_access_token(&state, &auth_code_data).await?;+ let id_token = generate_id_token(&state, &auth_code_data).await?;++ Ok(ApplicationResponse::Json(OidcTokenResponse {+ access_token: access_token.into(),+ id_token: id_token.into(),+ token_type: TOKEN_TYPE_BEARER.to_string(),+ expires_in: ACCESS_TOKEN_TTL_IN_SECS,+ }))+}diff --git a/crates/router/src/types/domain/user/oidc.rs b/crates/router/src/types/domain/user/oidc.rsindex a4f6545e3f..83a132927f 100644--- a/crates/router/src/types/domain/user/oidc.rs+++ b/crates/router/src/types/domain/user/oidc.rs@@ -8,6 +8,38 @@ pub struct AuthCodeData {pub client_id: String,pub redirect_uri: String,pub scope: Vec<Scope>,- pub nonce: Option<String>,+ pub nonce: String,pub email: pii::Email,+ pub is_verified: bool,+}++/// ID Token Claims structure for OIDC+#[derive(Debug, Serialize, Deserialize)]+pub struct IdTokenClaims {+ pub iss: String,+ pub sub: String,+ pub aud: String,+ pub iat: u64,+ pub exp: u64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub email: Option<pii::Email>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub email_verified: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub preferred_username: Option<String>,+ pub nonce: String,+}++/// Access Token Claims structure for OIDC+#[derive(Debug, Serialize, Deserialize)]+pub struct AccessTokenClaims {+ pub iss: String,+ pub sub: String,+ pub aud: String,+ pub iat: u64,+ pub exp: u64,+ pub email: pii::Email,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub preferred_username: Option<String>,+ pub scope: Vec<Scope>,}diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex b0647a94df..76a3a8f9c4 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -4,6 +4,8 @@ pub mod connector_onboarding;pub mod currency;pub mod db_utils;pub mod ext_traits;+#[cfg(feature = "olap")]+pub mod oidc;#[cfg(feature = "kv_store")]pub mod storage_partitioning;#[cfg(feature = "olap")]diff --git a/crates/router/src/utils/oidc.rs b/crates/router/src/utils/oidc.rsnew file mode 100644index 0000000000..4947bb2b88--- /dev/null+++ b/crates/router/src/utils/oidc.rs@@ -0,0 +1,155 @@+use common_utils::ext_traits::StringExt;+use error_stack::{report, ResultExt};+use masking::PeekInterface;+use url::Url;++use crate::{+ consts::oidc::{AUTH_CODE_TTL_IN_SECS, REDIS_AUTH_CODE_PREFIX},+ core::errors::oidc::{OidcErrors, OidcResult},+ routes::app::SessionState,+ services::{api::ApplicationResponse, encryption},+ types::domain::user::oidc::AuthCodeData,+ utils::user as user_utils,+};++#[inline]+fn get_auth_code_key(auth_code: &str) -> String {+ format!("{REDIS_AUTH_CODE_PREFIX}{auth_code}")+}++#[inline]+pub fn validate_client_id_match(registered_client_id: &str, provided_client_id: &str) -> bool {+ registered_client_id.trim() == provided_client_id.trim()+}++pub fn validate_redirect_uri_match(registered_uri: &str, provided_uri: &str) -> bool {+ let registered = registered_uri.trim();+ let provided = provided_uri.trim();++ match (Url::parse(registered), Url::parse(provided)) {+ (Ok(registered_url), Ok(provided_url)) => registered_url == provided_url,+ _ => registered == provided,+ }+}++pub fn build_oidc_redirect_url(+ redirect_uri: &str,+ auth_code: &str,+ state: &str,+) -> OidcResult<String> {+ Url::parse(redirect_uri)+ .map_err(|_| {+ report!(OidcErrors::InvalidRequest)+ .attach_printable("Invalid redirect_uri in OIDC authorize request")+ })+ .and_then(|base_url| {+ Url::parse_with_params(base_url.as_str(), &[("code", auth_code), ("state", state)])+ .map_err(|_| {+ report!(OidcErrors::ServerError)+ .attach_printable("Failed to build redirect URL with query parameters")+ })+ })+ .map(|url| url.to_string())+}++pub async fn set_auth_code_in_redis(+ state: &SessionState,+ auth_code: &str,+ auth_code_data: &AuthCodeData,+) -> OidcResult<()> {+ let connection = user_utils::get_redis_connection_for_global_tenant(state)+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to get redis connection")?;+ let key = get_auth_code_key(auth_code);+ connection+ .serialize_and_set_key_with_expiry(&key.into(), auth_code_data, AUTH_CODE_TTL_IN_SECS)+ .await+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to set authorization code in redis")+}++pub async fn get_auth_code_from_redis(+ state: &SessionState,+ code: &str,+) -> OidcResult<AuthCodeData> {+ let connection = user_utils::get_redis_connection_for_global_tenant(state)+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to get redis connection")?;+ let key = get_auth_code_key(code);+ let auth_code_data_string = connection+ .get_key::<Option<String>>(&key.into())+ .await+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to get authorization code from redis")?+ .ok_or_else(|| report!(OidcErrors::InvalidGrant))?;++ auth_code_data_string+ .parse_struct("AuthCodeData")+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to deserialize authorization code data")+}++pub async fn delete_auth_code_from_redis(state: &SessionState, code: &str) -> OidcResult<()> {+ let connection = user_utils::get_redis_connection_for_global_tenant(state)+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to get redis connection")?;+ let key = get_auth_code_key(code);+ connection+ .delete_key(&key.into())+ .await+ .change_context(OidcErrors::ServerError)+ .attach_printable("Failed to delete authorization code from redis")+ .map(|_| ())+}++#[cfg(feature = "v1")]+pub fn build_redirection_response(redirect_url: String) -> ApplicationResponse<()> {+ use api_models::payments::RedirectionResponse;+ ApplicationResponse::JsonForRedirection(RedirectionResponse {+ headers: Vec::new(),+ return_url: String::new(),+ http_method: String::new(),+ params: Vec::new(),+ return_url_with_query_params: redirect_url,+ })+}++#[cfg(feature = "v2")]+pub fn build_redirection_response(redirect_url: String) -> ApplicationResponse<()> {+ use api_models::payments::RedirectionResponse;+ ApplicationResponse::JsonForRedirection(RedirectionResponse {+ return_url_with_query_params: redirect_url,+ })+}++/// Sign OIDC JWT tokens with RS256+pub async fn sign_oidc_token<T>(+ state: &SessionState,+ claims: T,+ error_prefix: &str,+) -> OidcResult<String>+where+ T: serde::Serialize,+{+ let signing_key = state+ .conf+ .oidc+ .get_inner()+ .get_signing_key()+ .ok_or_else(|| {+ report!(OidcErrors::ServerError).attach_printable("No signing key configured for OIDC")+ })?;++ let payload_bytes = serde_json::to_vec(&claims)+ .change_context(OidcErrors::ServerError)+ .attach_printable(format!("Failed to serialize {} claims", error_prefix))?;++ encryption::jws_sign_payload(+ &payload_bytes,+ &signing_key.kid,+ signing_key.private_key.peek().as_bytes(),+ )+ .await+ .change_context(OidcErrors::ServerError)+ .attach_printable(format!("Failed to sign {}", error_prefix))+}