Skip to content

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

feat(oidc): Add OIDC infrastructure and discovery endpoints (#10145)

Kanika Bansal356c2f756d81
diff --git a/config/config.example.toml b/config/config.example.toml
index 6ef0fce62f..df39904d6c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -487,6 +487,19 @@ base_url = "" # Base url used for user specific redirects
force_two_factor_auth = false # Whether to force two factor authentication for all users
force_cookies = true # Whether to use only cookies for JWT extraction and authentication
+[oidc.key.k1]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
+
+[oidc.key.k2]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
+
+[oidc.client.c1]
+client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
+client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
+redirect_uri = "" # Redirect URI registered for the OIDC client
+
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 70a8fc3b43..ea17197f7e 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -451,3 +451,16 @@ polling_interval = 15 # Polling interval in seconds fo
[trace_header]
header_name = "x-request-id" # HTTP header name for request tracing
id_reuse = "ignore_incoming" # Policy for handling incoming request IDs: "use_incoming" or "ignore_incoming"
+
+[oidc.key.k1]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
+
+[oidc.key.k2]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
+
+[oidc.client.c1]
+client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
+client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
+redirect_uri = "" # Redirect URI registered for the OIDC client
\ No newline at end of file
diff --git a/config/development.toml b/config/development.toml
index fb86df981c..ba4569005b 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -421,6 +421,20 @@ base_url = "http://localhost:8080"
force_two_factor_auth = false
force_cookies = true
+[oidc.key.k1]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
+
+[oidc.key.k2]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
+
+[oidc.client.c1]
+client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
+client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
+redirect_uri = "" # Redirect URI registered for the OIDC client
+
+
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index d843cbbc54..27323a5a2c 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -62,6 +62,19 @@ base_url = "http://localhost:9000"
force_two_factor_auth = false
force_cookies = false
+[oidc.key.k1]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
+
+[oidc.key.k2]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
+
+[oidc.client.c1]
+client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
+client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
+redirect_uri = "" # Redirect URI registered for the OIDC client
+
[locker]
host = ""
host_rs = ""
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index 2c2eefe925..50e08674d4 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -25,6 +25,7 @@ pub mod gsm;
pub mod health_check;
pub mod locker_migration;
pub mod mandates;
+pub mod oidc;
pub mod open_router;
pub mod organization;
pub mod payment_methods;
diff --git a/crates/api_models/src/oidc.rs b/crates/api_models/src/oidc.rs
new file mode 100644
index 0000000000..bb9b797194
--- /dev/null
+++ b/crates/api_models/src/oidc.rs
@@ -0,0 +1,355 @@
+use std::str::FromStr;
+
+use common_utils::events::ApiEventMetric;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+const RESPONSE_TYPES_SUPPORTED: &[ResponseType] = &[ResponseType::Code];
+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 TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED: &[TokenAuthMethod] =
+ &[TokenAuthMethod::ClientSecretBasic];
+const CLAIMS_SUPPORTED: &[Claim] = &[
+ Claim::Aud,
+ Claim::Email,
+ Claim::EmailVerified,
+ Claim::Exp,
+ Claim::Iat,
+ Claim::Iss,
+ Claim::Sub,
+];
+
+/// OIDC Response Type
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ResponseType {
+ Code,
+}
+
+/// OIDC Response Mode
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ResponseMode {
+ Query,
+}
+
+/// OIDC Subject Type
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SubjectType {
+ Public,
+}
+
+/// OIDC Signing Algorithm
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+pub enum SigningAlgorithm {
+ #[serde(rename = "RS256")]
+ Rs256,
+}
+
+/// JWK Key Type
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+pub enum KeyType {
+ #[serde(rename = "RSA")]
+ Rsa,
+}
+
+/// JWK Key Use
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum KeyUse {
+ Sig,
+}
+
+/// OIDC Grant Type
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum GrantType {
+ AuthorizationCode,
+}
+
+/// OIDC Scope
+#[derive(
+ Copy, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum Scope {
+ Openid,
+ Email,
+}
+
+/// OIDC Token Endpoint Authentication Method
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TokenAuthMethod {
+ ClientSecretBasic,
+}
+
+/// OIDC Claim
+#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Claim {
+ Aud,
+ Email,
+ EmailVerified,
+ Exp,
+ 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,
+}
+
+/// OpenID Connect Discovery Response
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct OidcDiscoveryResponse {
+ /// The issuer identifier for the OpenID Provider
+ #[schema(example = "https://sandbox.hyperswitch.io")]
+ pub issuer: String,
+
+ /// URL of the authorization endpoint
+ #[schema(example = "https://app.hyperswitch.io/oauth2/authorize")]
+ pub authorization_endpoint: String,
+
+ /// URL of the token endpoint
+ #[schema(example = "https://sandbox.hyperswitch.io/oauth2/token")]
+ pub token_endpoint: String,
+
+ /// URL of the JSON Web Key Set document
+ #[schema(example = "https://sandbox.hyperswitch.io/oauth2/jwks")]
+ pub jwks_uri: String,
+
+ /// List of OAuth 2.0 response_type values supported
+ pub response_types_supported: Vec<ResponseType>,
+
+ /// List of OAuth 2.0 response_mode values supported
+ pub response_modes_supported: Vec<ResponseMode>,
+
+ /// List of Subject Identifier types supported
+ pub subject_types_supported: Vec<SubjectType>,
+
+ /// List of JWS signing algorithms supported for ID Tokens
+ pub id_token_signing_alg_values_supported: Vec<SigningAlgorithm>,
+
+ /// List of OAuth 2.0 grant type values supported
+ pub grant_types_supported: Vec<GrantType>,
+
+ /// List of OAuth 2.0 scope values supported
+ pub scopes_supported: Vec<Scope>,
+
+ /// List of Client Authentication methods supported by the token endpoint
+ pub token_endpoint_auth_methods_supported: Vec<TokenAuthMethod>,
+
+ /// List of Claim Names supported
+ pub claims_supported: Vec<Claim>,
+
+ /// Whether the claims parameter is supported
+ #[serde(default)]
+ #[schema(example = false)]
+ pub claims_parameter_supported: bool,
+
+ /// Whether the request parameter is supported
+ #[serde(default)]
+ #[schema(example = false)]
+ pub request_parameter_supported: bool,
+
+ /// Whether the request_uri parameter is supported
+ #[serde(default)]
+ #[schema(example = false)]
+ pub request_uri_parameter_supported: bool,
+}
+
+impl OidcDiscoveryResponse {
+ pub fn new(issuer: String, control_center_url: String) -> Self {
+ let authorization_endpoint = format!("{}/oauth2/authorize", control_center_url);
+ let token_endpoint = format!("{}/oauth2/token", issuer);
+ let jwks_uri = format!("{}/oauth2/jwks", issuer);
+
+ Self {
+ issuer,
+ authorization_endpoint,
+ token_endpoint,
+ jwks_uri,
+ response_types_supported: RESPONSE_TYPES_SUPPORTED.to_vec(),
+ response_modes_supported: RESPONSE_MODES_SUPPORTED.to_vec(),
+ subject_types_supported: SUBJECT_TYPES_SUPPORTED.to_vec(),
+ id_token_signing_alg_values_supported: ID_TOKEN_SIGNING_ALGS_SUPPORTED.to_vec(),
+ grant_types_supported: GRANT_TYPES_SUPPORTED.to_vec(),
+ scopes_supported: SCOPES_SUPPORTED.to_vec(),
+ token_endpoint_auth_methods_supported: TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED.to_vec(),
+ claims_supported: CLAIMS_SUPPORTED.to_vec(),
+ claims_parameter_supported: false,
+ request_parameter_supported: false,
+ request_uri_parameter_supported: false,
+ }
+ }
+}
+
+/// JWKS (JSON Web Key Set) response
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct JwksResponse {
+ /// Array of JSON Web Keys
+ pub keys: Vec<Jwk>,
+}
+
+/// JSON Web Key (JWK) for RSA public key
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct Jwk {
+ /// Key type
+ pub kty: KeyType,
+
+ /// Key ID
+ #[schema(example = "key-1")]
+ pub kid: String,
+
+ /// Public key use
+ #[serde(rename = "use")]
+ pub key_use: KeyUse,
+
+ /// Algorithm
+ pub alg: SigningAlgorithm,
+
+ /// RSA public key modulus
+ pub n: String,
+
+ /// RSA public key exponent
+ #[schema(example = "AQAB")]
+ pub e: String,
+}
+
+/// Custom deserializer for space-separated scope strings
+fn deserialize_scope_vec<'de, D>(deserializer: D) -> Result<Vec<Scope>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ use serde::de::Error;
+ let s = String::deserialize(deserializer)?;
+ s.split_whitespace()
+ .map(|scope_str| {
+ Scope::from_str(scope_str)
+ .map_err(|_| D::Error::custom(format!("Invalid scope: '{}'", scope_str)))
+ })
+ .collect()
+}
+
+/// OIDC Authorization Request
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct OidcAuthorizeQuery {
+ /// OAuth 2.0 Response Type value
+ pub response_type: ResponseType,
+
+ /// OAuth 2.0 Client Identifier
+ #[schema(example = "client_abc123")]
+ pub client_id: String,
+
+ /// Redirection URI to which the response will be sent
+ #[schema(example = "https://example.com/callback")]
+ pub redirect_uri: String,
+
+ /// OpenID Connect scope values
+ #[serde(deserialize_with = "deserialize_scope_vec")]
+ pub scope: Vec<Scope>,
+
+ /// Opaque value used to maintain state between request and callback
+ #[schema(example = "state_xyz789")]
+ pub state: String,
+
+ /// String value used to associate a Client session with an ID Token
+ #[schema(example = "nonce_abc123")]
+ pub nonce: Option<String>,
+}
+
+/// OIDC Token Request
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct OidcTokenRequest {
+ /// OAuth 2.0 Grant Type value
+ pub grant_type: GrantType,
+
+ /// Authorization code received from the authorization server
+ #[schema(example = "auth_code_xyz789")]
+ pub code: String,
+
+ /// 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 {
+ /// ID Token value associated with the authenticated session
+ #[schema(value_type = String)]
+ pub id_token: Secret<String>,
+
+ /// OAuth 2.0 Token Type value
+ #[schema(example = "Bearer")]
+ pub token_type: String,
+
+ /// Expiration time of the ID Token in seconds since the response was generated
+ #[schema(example = 3600)]
+ pub expires_in: u64,
+}
+
+impl ApiEventMetric for OidcDiscoveryResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::Oidc)
+ }
+}
+
+impl ApiEventMetric for JwksResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::Oidc)
+ }
+}
+
+impl ApiEventMetric for OidcAuthorizeQuery {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::Oidc)
+ }
+}
+
+impl ApiEventMetric for OidcTokenRequest {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::Oidc)
+ }
+}
+
+impl ApiEventMetric for OidcTokenResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::Oidc)
+ }
+}
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index 9146384d26..ef2e7e876f 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -3,7 +3,7 @@ use std::ops::Deref;
use base64::Engine;
use error_stack::ResultExt;
-use masking::{ExposeInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac, rand as ring_rand,
@@ -11,10 +11,15 @@ use ring::{
};
#[cfg(feature = "logs")]
use router_env::logger;
-use rsa::{pkcs8::DecodePublicKey, signature::Verifier};
+use rsa::{
+ pkcs1::DecodeRsaPrivateKey,
+ pkcs8::{DecodePrivateKey, DecodePublicKey},
+ signature::Verifier,
+ traits::PublicKeyParts,
+};
use crate::{
- consts::BASE64_ENGINE,
+ consts::{BASE64_ENGINE, BASE64_ENGINE_URL_SAFE_NO_PAD},
errors::{self, CustomResult},
pii::{self, EncryptionStrategy},
};
@@ -729,6 +734,35 @@ pub type EncryptableName = Encryptable<Secret<String>>;
/// Type alias for `Encryptable<Secret<String>>` used for `email` field
pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>;
+/// Extract RSA public key components (n, e) from a private key PEM for JWKS
+/// Returns base64url-encoded modulus and exponent
+pub fn extract_rsa_public_key_components(
+ private_key_pem: &Secret<String>,
+) -> CustomResult<(String, String), errors::CryptoError> {
+ let pem_str = private_key_pem.peek();
+ let parsed_pem = pem::parse(pem_str).change_context(errors::CryptoError::EncodingFailed)?;
+
+ let private_key = match parsed_pem.tag() {
+ "PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs8_der(parsed_pem.contents())
+ .change_context(errors::CryptoError::InvalidKeyLength),
+ "RSA PRIVATE KEY" => rsa::RsaPrivateKey::from_pkcs1_der(parsed_pem.contents())
+ .change_context(errors::CryptoError::InvalidKeyLength),
+ tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
+ "Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'"
+ )),
+ }
+ .attach_printable("Failed to extract RSA public key components from private key")?;
+
+ let public_key = private_key.to_public_key();
+ let n_bytes = public_key.n().to_bytes_be();
+ let e_bytes = public_key.e().to_bytes_be();
+
+ let n_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(n_bytes);
+ let e_b64 = BASE64_ENGINE_URL_SAFE_NO_PAD.encode(e_bytes);
+
+ Ok((n_b64, e_b64))
+}
+
/// Represents the RSA-PSS-SHA256 signing algorithm
#[derive(Debug)]
pub struct RsaPssSha256;
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 3f35443ee5..d6f3bab662 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -142,6 +142,7 @@ pub enum ApiEventsType {
},
ThreeDsDecisionRule,
Chat,
+ Oidc,
}
impl ApiEventMetric for serde_json::Value {}
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
index 84550c1979..5e73910044 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -307,6 +307,11 @@ pub enum ApiErrorResponse {
ConnectedAccountAuthNotSupported,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_50", message = "Invalid connected account operation")]
InvalidConnectedOperation,
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_51",
+ message = "Access forbidden, invalid Basic authentication credentials"
+ )]
+ InvalidBasicAuth,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
WebhookAuthenticationFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
@@ -598,6 +603,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
}
Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
+ Self::InvalidBasicAuth => AER::Unauthorized(ApiError::new("IR", 51, "Access forbidden, invalid Basic authentication credentials", None)),
Self::GenericUnauthorized { message } => {
AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
},
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 65b05b39b4..6661fb9509 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -454,6 +454,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
match value {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
+ | errors::ApiErrorResponse::InvalidBasicAuth
| errors::ApiErrorResponse::GenericUnauthorized { .. }
| errors::ApiErrorResponse::AccessForbidden { .. }
| errors::ApiErrorResponse::InvalidCookie
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index c612acb28d..1619935c36 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -351,6 +351,50 @@ impl SecretsHandler for settings::NetworkTokenizationService {
}
}
+#[async_trait::async_trait]
+impl SecretsHandler for settings::OidcSettings {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let oidc_settings = value.get_inner();
+
+ let mut decrypted_keys = std::collections::HashMap::new();
+ for (key_id, oidc_key) in &oidc_settings.key {
+ let private_key = secret_management_client
+ .get_secret(oidc_key.private_key.clone())
+ .await?;
+ decrypted_keys.insert(
+ key_id.clone(),
+ settings::OidcKey {
+ kid: oidc_key.kid.clone(),
+ private_key,
+ },
+ );
+ }
+
+ let mut decrypted_clients = std::collections::HashMap::new();
+ for (client_key, oidc_client) in &oidc_settings.client {
+ let client_secret = secret_management_client
+ .get_secret(oidc_client.client_secret.clone())
+ .await?;
+ decrypted_clients.insert(
+ client_key.clone(),
+ settings::OidcClient {
+ client_id: oidc_client.client_id.clone(),
+ client_secret,
+ redirect_uri: oidc_client.redirect_uri.clone(),
+ },
+ );
+ }
+
+ Ok(value.transition_state(|_| Self {
+ key: decrypted_keys,
+ client: decrypted_clients,
+ }))
+ }
+}
+
/// # Panics
///
/// Will panic even if kms decryption fails for at least one field
@@ -487,6 +531,11 @@ pub(crate) async fn fetch_raw_secrets(
.await
.expect("Failed to decrypt superposition config");
+ #[allow(clippy::expect_used)]
+ let oidc = settings::OidcSettings::convert_to_raw_secret(conf.oidc, secret_management_client)
+ .await
+ .expect("Failed to decrypt oidc configs");
+
Settings {
server: conf.server,
application_source: conf.application_source,
@@ -525,6 +574,7 @@ pub(crate) async fn fetch_raw_secrets(
#[cfg(feature = "email")]
email: conf.email,
user: conf.user,
+ oidc,
mandates: conf.mandates,
zero_mandates: conf.zero_mandates,
network_transaction_id_supported_connectors: conf
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 5aaa08e8c6..490c9c0ea3 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -109,6 +109,7 @@ pub struct Settings<S: SecretState> {
#[cfg(feature = "email")]
pub email: EmailSettings,
pub user: UserSettings,
+ pub oidc: SecretStateContainer<OidcSettings, S>,
pub crm: CrmManagerConfig,
pub cors: CorsSettings,
pub mandates: Mandates,
@@ -277,14 +278,14 @@ impl TenantConfig {
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
- let store = AppState::get_store_interface(
+ let store = Box::pin(AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
- )
+ ))
.await
.get_storage_interface();
(tenant_name.clone(), store)
@@ -310,14 +311,14 @@ impl TenantConfig {
.await
.expect("Failed to create event handler");
futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async {
- let store = AppState::get_store_interface(
+ let store = Box::pin(AppState::get_store_interface(
storage_impl,
&event_handler,
conf,
tenant,
cache_store.clone(),
testable,
- )
+ ))
.await
.get_accounts_storage_interface();
(tenant_name.clone(), store)
@@ -701,6 +702,40 @@ pub struct UserSettings {
pub force_cookies: bool,
}
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct OidcSettings {
+ pub key: HashMap<String, OidcKey>,
+ pub client: HashMap<String, OidcClient>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct OidcKey {
+ pub kid: String,
+ pub private_key: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct OidcClient {
+ pub client_id: String,
+ pub client_secret: Secret<String>,
+ pub redirect_uri: String,
+}
+
+impl OidcSettings {
+ pub fn get_client(&self, client_id: &str) -> Option<&OidcClient> {
+ self.client.values().find(|c| c.client_id == client_id)
+ }
+
+ pub fn get_signing_key(&self) -> Option<&OidcKey> {
+ self.key.values().next()
+ }
+
+ pub fn get_all_keys(&self) -> Vec<&OidcKey> {
+ self.key.values().collect()
+ }
+}
+
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Locker {
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 316e362856..8850b8697a 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -1,3 +1,4 @@
+pub mod oidc;
pub mod opensearch;
#[cfg(feature = "olap")]
pub mod user;
diff --git a/crates/router/src/consts/oidc.rs b/crates/router/src/consts/oidc.rs
new file mode 100644
index 0000000000..8d0bfb3898
--- /dev/null
+++ b/crates/router/src/consts/oidc.rs
@@ -0,0 +1,5 @@
+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 AUTH_CODE_LENGTH: usize = 32;
+pub const TOKEN_TYPE_BEARER: &str = "Bearer";
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 8e64f5daf4..e567d711c3 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -235,6 +235,7 @@ pub fn mk_app(
.service(routes::Gsm::server(state.clone()))
.service(routes::RecoveryDataBackfill::server(state.clone()));
}
+ server_app = server_app.service(routes::Oidc::server(state.clone()));
}
#[cfg(all(feature = "payouts", feature = "v1"))]
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index a41c1df68f..7d54cfea13 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -30,6 +30,7 @@ pub mod lock_utils;
pub mod locker_migration;
pub mod mandates;
pub mod metrics;
+pub mod oidc;
#[cfg(feature = "v1")]
pub mod payment_link;
pub mod payment_methods;
@@ -94,7 +95,7 @@ pub use self::app::Recon;
pub use self::app::{
ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, Cards, Chat, Configs,
ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm,
- Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink,
+ Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount, Oidc, PaymentLink,
PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile,
ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, ThreeDsDecisionRule,
User, UserDeprecated, Webhooks,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 13bbfc3da2..759504ee75 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -67,7 +67,7 @@ use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_ve
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
- admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*,
+ admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*, oidc,
profiles, relay, user, user_role,
};
#[cfg(feature = "v1")]
@@ -442,14 +442,14 @@ impl AppState {
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
- let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface(
+ let global_store: Box<dyn GlobalStorageInterface> = Box::pin(Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
&conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
- )
+ ))
.await
.get_global_storage_interface();
#[cfg(feature = "olap")]
@@ -1788,6 +1788,20 @@ impl Hypersense {
}
}
+pub struct Oidc;
+
+impl Oidc {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("")
+ .app_data(web::Data::new(state))
+ .service(
+ web::resource("/.well-known/openid-configuration")
+ .route(web::get().to(oidc::oidc_discovery)),
+ )
+ .service(web::resource("/oauth2/jwks").route(web::get().to(oidc::jwks_endpoint)))
+ }
+}
+
#[cfg(feature = "olap")]
pub struct Blocklist;
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index dda2f679b3..881a153325 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -288,6 +288,10 @@ impl From<Flow> for ApiIdentifier {
| Flow::UserTransferKey
| Flow::GetSsoAuthUrl
| Flow::SignInWithSso
+ | Flow::OidcDiscovery
+ | Flow::OidcJwks
+ | Flow::OidcAuthorize
+ | Flow::OidcToken
| Flow::ListOrgForUser
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
diff --git a/crates/router/src/routes/oidc.rs b/crates/router/src/routes/oidc.rs
new file mode 100644
index 0000000000..b98f51ff30
--- /dev/null
+++ b/crates/router/src/routes/oidc.rs
@@ -0,0 +1,40 @@
+use actix_web::{web, HttpRequest, HttpResponse};
+use router_env::{instrument, tracing, Flow};
+
+use crate::{
+ core::api_locking,
+ routes::app::AppState,
+ services::{api, authentication as auth, oidc_provider},
+};
+
+/// 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,
+ state,
+ &req,
+ (),
+ |state, _: (), _, _| oidc_provider::get_discovery_document(state),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+/// 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,
+ state,
+ &req,
+ (),
+ |state, _: (), _, _| oidc_provider::get_jwks(state),
+ &auth::NoAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 8acdecfe1a..8c7e5892b4 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -13,6 +13,8 @@ pub mod pm_auth;
pub mod card_testing_guard;
#[cfg(feature = "olap")]
+pub mod oidc_provider;
+#[cfg(feature = "olap")]
pub mod openidconnect;
use std::sync::Arc;
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 4ef8585a57..e69de3ed28 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,4 +1,4 @@
-use std::str::FromStr;
+use std::{marker::PhantomData, str::FromStr};
use actix_web::http::header::HeaderMap;
#[cfg(feature = "v2")]
@@ -9,6 +9,7 @@ use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts;
use async_trait::async_trait;
+use base64::Engine;
use common_enums::{MerchantAccountType, TokenPurpose};
use common_utils::{date_time, fp_utils, id_type};
#[cfg(feature = "v2")]
@@ -39,6 +40,7 @@ use crate::core::errors::UserResult;
use crate::core::metrics;
use crate::{
configs::settings,
+ consts::BASE64_ENGINE,
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
@@ -157,6 +159,9 @@ pub enum AuthenticationType {
org_id: id_type::OrganizationId,
user_id: String,
},
+ BasicAuth {
+ username: String,
+ },
MerchantJwt {
merchant_id: id_type::MerchantId,
user_id: Option<String>,
@@ -224,6 +229,7 @@ impl AuthenticationType {
| Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
+ | Self::BasicAuth { .. }
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
| Self::SinglePurposeOrLoginJwt { .. }
@@ -396,6 +402,56 @@ pub struct ApiKeyAuth {
pub struct NoAuth;
+pub trait BasicAuthProvider {
+ type Identity;
+
+ fn get_credentials<A>(
+ state: &A,
+ identifier: &str,
+ ) -> RouterResult<(Self::Identity, masking::Secret<String>)>
+ where
+ A: SessionStateInfo;
+}
+
+#[derive(Debug, Default)]
+pub struct BasicAuth<P> {
+ _marker: PhantomData<P>,
+}
+
+impl<P> BasicAuth<P> {
+ pub const fn new() -> Self {
+ Self {
+ _marker: PhantomData,
+ }
+ }
+}
+
+pub struct OidcAuthProvider;
+
+impl BasicAuthProvider for OidcAuthProvider {
+ type Identity = String;
+
+ fn get_credentials<A>(
+ state: &A,
+ identifier: &str,
+ ) -> RouterResult<(Self::Identity, masking::Secret<String>)>
+ where
+ A: SessionStateInfo,
+ {
+ let session = state.session_state();
+ let client = session
+ .conf
+ .oidc
+ .get_inner()
+ .get_client(identifier)
+ .ok_or(errors::ApiErrorResponse::InvalidBasicAuth)?;
+
+ Ok((client.client_id.clone(), client.client_secret.clone()))
+ }
+}
+
+pub const OIDC_CLIENT_AUTH: BasicAuth<OidcAuthProvider> = BasicAuth::<OidcAuthProvider>::new();
+
#[cfg(feature = "partial-auth")]
impl GetAuthType for ApiKeyAuth {
fn get_auth_type(&self) -> detached::PayloadType {
@@ -463,6 +519,36 @@ where
}
}
+#[async_trait]
+impl<A, P> AuthenticateAndFetch<P::Identity, A> for BasicAuth<P>
+where
+ A: SessionStateInfo + Sync,
+ P: BasicAuthProvider + Send + Sync,
+ P::Identity: Clone,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(P::Identity, AuthenticationType)> {
+ let (provided_identifier, provided_secret) = parse_basic_auth_credentials(request_headers)?;
+
+ let (authenticated_entity, expected_secret) =
+ P::get_credentials(state, &provided_identifier)?;
+
+ if provided_secret.peek() != expected_secret.peek() {
+ return Err(errors::ApiErrorResponse::InvalidBasicAuth.into());
+ }
+
+ Ok((
+ authenticated_entity.clone(),
+ AuthenticationType::BasicAuth {
+ username: provided_identifier,
+ },
+ ))
+ }
+}
+
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth
@@ -4066,6 +4152,27 @@ where
}
}
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<Option<UserFromToken>, A> for DashboardNoPermissionAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(Option<UserFromToken>, AuthenticationType)> {
+ <Self as AuthenticateAndFetch<UserFromToken, A>>::authenticate_and_fetch(
+ self,
+ request_headers,
+ state,
+ )
+ .await
+ .map(|(user, auth_type)| (Some(user), auth_type))
+ }
+}
+
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for DashboardNoPermissionAuth
@@ -4511,6 +4618,45 @@ pub fn strip_jwt_token(token: &str) -> RouterResult<&str> {
.ok_or_else(|| errors::ApiErrorResponse::InvalidJwtToken.into())
}
+pub fn strip_basic_auth_token(token: &str) -> RouterResult<&str> {
+ token
+ .strip_prefix("Basic ")
+ .ok_or_else(|| errors::ApiErrorResponse::InvalidBasicAuth.into())
+}
+
+fn parse_basic_auth_credentials(
+ headers: &HeaderMap,
+) -> RouterResult<(String, masking::Secret<String>)> {
+ let authorization_header = get_header_value_by_key(headers::AUTHORIZATION.to_string(), headers)
+ .change_context(errors::ApiErrorResponse::InvalidBasicAuth)?
+ .get_required_value(headers::AUTHORIZATION)?;
+
+ let encoded_credentials = strip_basic_auth_token(authorization_header)?;
+
+ let decoded_bytes = BASE64_ENGINE
+ .decode(encoded_credentials)
+ .change_context(errors::ApiErrorResponse::InvalidBasicAuth)?;
+
+ let credential_string = String::from_utf8(decoded_bytes)
+ .change_context(errors::ApiErrorResponse::InvalidBasicAuth)?;
+
+ let (identifier, secret) = credential_string
+ .split_once(':')
+ .ok_or(errors::ApiErrorResponse::InvalidBasicAuth)?;
+
+ let identifier = identifier.trim();
+ let secret = secret.trim();
+
+ if identifier.is_empty() || secret.is_empty() {
+ return Err(errors::ApiErrorResponse::InvalidBasicAuth.into());
+ }
+
+ Ok((
+ identifier.to_string(),
+ masking::Secret::new(secret.to_string()),
+ ))
+}
+
pub fn auth_type<'a, T, A>(
default_auth: &'a dyn AuthenticateAndFetch<T, A>,
jwt_auth_type: &'a dyn AuthenticateAndFetch<T, A>,
diff --git a/crates/router/src/services/oidc_provider.rs b/crates/router/src/services/oidc_provider.rs
new file mode 100644
index 0000000000..b0a758534d
--- /dev/null
+++ b/crates/router/src/services/oidc_provider.rs
@@ -0,0 +1,55 @@
+use api_models::oidc::{
+ Jwk, JwksResponse, KeyType, KeyUse, OidcDiscoveryResponse, SigningAlgorithm,
+};
+use error_stack::ResultExt;
+use once_cell::sync::OnceCell;
+
+use crate::{
+ core::errors::{ApiErrorResponse, RouterResponse},
+ routes::app::SessionState,
+ services::api::ApplicationResponse,
+ utils::user as user_utils,
+};
+
+/// Build OIDC discovery document
+pub async fn get_discovery_document(state: SessionState) -> RouterResponse<OidcDiscoveryResponse> {
+ let backend_base_url = state.tenant.base_url.clone();
+ let control_center_url = user_utils::get_base_url(&state);
+
+ Ok(ApplicationResponse::Json(OidcDiscoveryResponse::new(
+ backend_base_url,
+ control_center_url.into(),
+ )))
+}
+
+static 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> {
+ CACHED_JWKS
+ .get_or_try_init(|| {
+ let oidc_keys = state.conf.oidc.get_inner().get_all_keys();
+ let mut keys = Vec::with_capacity(oidc_keys.len());
+
+ for key_config in oidc_keys {
+ let (n, e) = common_utils::crypto::extract_rsa_public_key_components(
+ &key_config.private_key,
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to extract public key from private key")?;
+
+ let jwk = Jwk {
+ kty: KeyType::Rsa,
+ kid: key_config.kid.clone(),
+ key_use: KeyUse::Sig,
+ alg: SigningAlgorithm::Rs256,
+ n,
+ e,
+ };
+
+ keys.push(jwk);
+ }
+
+ Ok::<_, error_stack::Report<ApiErrorResponse>>(JwksResponse { keys })
+ })
+ .map(ApplicationResponse::Json)
+}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 03a53f92fe..b8544073cb 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -47,6 +47,7 @@ use crate::{
pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
+pub mod oidc;
pub mod user_authentication_method;
use super::{types as domain_types, UserKeyStore};
diff --git a/crates/router/src/types/domain/user/oidc.rs b/crates/router/src/types/domain/user/oidc.rs
new file mode 100644
index 0000000000..a4f6545e3f
--- /dev/null
+++ b/crates/router/src/types/domain/user/oidc.rs
@@ -0,0 +1,13 @@
+use api_models::oidc::Scope;
+use common_utils::pii;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AuthCodeData {
+ pub sub: String,
+ pub client_id: String,
+ pub redirect_uri: String,
+ pub scope: Vec<Scope>,
+ pub nonce: Option<String>,
+ pub email: pii::Email,
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 43a27a9e03..b5bddc2ec8 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -56,6 +56,14 @@ pub enum Flow {
HealthCheck,
/// Deep health Check
DeepHealthCheck,
+ /// OIDC Discovery endpoint
+ OidcDiscovery,
+ /// OIDC JWKS endpoint
+ OidcJwks,
+ /// OIDC Authorize endpoint
+ OidcAuthorize,
+ /// OIDC Token endpoint
+ OidcToken,
/// Organization create flow
OrganizationCreate,
/// Organization retrieve flow
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 4065e56972..3215484804 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -38,6 +38,19 @@ totp_issuer_name = "Hyperswitch"
force_two_factor_auth = false
force_cookies = true
+[oidc.key.k1]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private.key 4096)
+
+[oidc.key.k2]
+kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
+private_key = "" # RSA private key used for signing ID tokens (Generate using: openssl genrsa -out private2.key 4096)
+
+[oidc.client.c1]
+client_id = "" # OIDC client identifier for the relying party (Generate using: openssl rand -hex 8)
+client_secret = "" # Client secret used to authenticate the client (Generate using: openssl rand -hex 32)
+redirect_uri = "" # Redirect URI registered for the OIDC client
+
[locker]
host = ""
host_rs = ""