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(auth): implemented embedded tokens (#10424)

Rachit Naithani9039a5e88392
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 911baf8808..d8aba26e8b 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -14,13 +14,14 @@ use crate::user::{
AcceptInviteFromEmailRequest, AcceptInviteResponse, AuthSelectRequest, AuthorizeResponse,
BeginTotpResponse, ChangePasswordRequest, CloneConnectorRequest, ConnectAccountRequest,
CreateInternalUserRequest, CreateTenantUserRequest, CreateUserAuthenticationMethodRequest,
- CreateUserAuthenticationMethodResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest,
- GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
- GetUserRoleDetailsResponseV2, InviteUserRequest, PlatformAccountCreateRequest,
- PlatformAccountCreateResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
- TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest,
+ CreateUserAuthenticationMethodResponse, EmbeddedTokenInfoResponse, ForgotPasswordRequest,
+ GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,
+ GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest,
+ IssueEmbeddedTokenResponse, PlatformAccountCreateRequest, PlatformAccountCreateResponse,
+ ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest,
+ SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest,
+ SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse,
+ TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest,
UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse,
UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest,
VerifyRecoveryCodeRequest, VerifyTotpRequest,
@@ -76,7 +77,9 @@ common_utils::impl_api_event_type!(
GetSsoAuthUrlRequest,
SsoSignInRequest,
AuthSelectRequest,
- CloneConnectorRequest
+ CloneConnectorRequest,
+ IssueEmbeddedTokenResponse,
+ EmbeddedTokenInfoResponse
)
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7d84082515..b0fe921940 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -470,3 +470,16 @@ pub struct ListProfilesForUserInOrgAndMerchantAccountResponse {
pub profile_id: id_type::ProfileId,
pub profile_name: String,
}
+
+#[derive(Debug, serde::Serialize)]
+pub struct IssueEmbeddedTokenResponse {
+ pub token: Secret<String>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct EmbeddedTokenInfoResponse {
+ pub org_id: id_type::OrganizationId,
+ pub merchant_id: id_type::MerchantId,
+ pub merchant_account_version: common_enums::ApiVersion,
+ pub profile_id: id_type::ProfileId,
+}
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index f328c0858f..3ccd2f1228 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -1443,6 +1443,11 @@ impl_enum_str!(
/// user id of creator.
user_id: String,
},
+ /// EmbeddedToken variant
+ EmbeddedToken {
+ /// merchant id of creator.
+ merchant_id: String,
+ },
}
);
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 c82010ff06..bdca4e6176 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -334,6 +334,11 @@ pub enum ApiErrorResponse {
TokenizationRecordNotFound { id: String },
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
+ #[error(
+ error_type = ErrorType::InvalidRequestError, code = "IR_48",
+ message = "Access forbidden, expired JWT token was used"
+ )]
+ ExpiredJwtToken,
}
#[derive(Clone)]
@@ -736,6 +741,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::SubscriptionError { operation } => {
AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None))
}
+ Self::ExpiredJwtToken => AER::Unauthorized(ApiError::new("IR", 48, "Access forbidden, expired JWT token was used", None)),
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/platform.rs b/crates/hyperswitch_domain_models/src/platform.rs
index c67771b2bb..febb2595dd 100644
--- a/crates/hyperswitch_domain_models/src/platform.rs
+++ b/crates/hyperswitch_domain_models/src/platform.rs
@@ -59,6 +59,9 @@ pub enum Initiator {
Jwt {
user_id: String,
},
+ EmbeddedToken {
+ merchant_id: common_utils::id_type::MerchantId,
+ },
Admin,
}
@@ -74,6 +77,11 @@ impl Initiator {
Self::Api { merchant_id, .. } => Some(common_utils::types::CreatedBy::Api {
merchant_id: merchant_id.get_string_repr().to_string(),
}),
+ Self::EmbeddedToken { merchant_id, .. } => {
+ Some(common_utils::types::CreatedBy::EmbeddedToken {
+ merchant_id: merchant_id.get_string_repr().to_string(),
+ })
+ }
Self::Jwt { user_id } => Some(common_utils::types::CreatedBy::Jwt {
user_id: user_id.clone(),
}),
@@ -96,7 +104,7 @@ impl Initiator {
// If this returns Option<Initiator>, just return it directly (NO extra Some)
api_models::platform::Initiator::from_merchant_account_type(*merchant_account_type)
}
- Self::Jwt { .. } | Self::Admin => None,
+ Self::Jwt { .. } | Self::EmbeddedToken { .. } | Self::Admin => None,
}
}
}
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index bbdc9fd75b..734c1cd7d4 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -460,6 +460,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
| errors::ApiErrorResponse::InvalidCookie
| errors::ApiErrorResponse::InvalidEphemeralKey
| errors::ApiErrorResponse::InvalidPaymentIdProvided { .. }
+ | errors::ApiErrorResponse::ExpiredJwtToken
| errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 1b6c2323e4..a052ad3671 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -62,6 +62,7 @@ pub const LOCKER_REDIS_PREFIX: &str = "LOCKER_PM_TOKEN";
pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
+pub const JWT_EMBEDDED_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 3; // 3 hours
// This should be one day, but it is causing issue while checking token in blacklist.
// TODO: This should be fixed in future.
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 4488ea2af4..12ebddccc5 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -114,6 +114,8 @@ pub enum UserErrors {
InvalidCloneConnectorOperation(String),
#[error("Error cloning connector: {0}")]
ErrorCloningConnector(String),
+ #[error("Invalid Embedded Operation : {0}")]
+ InvalidEmbeddedOperation(String),
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -298,6 +300,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
self.get_error_message(),
None,
)),
+ Self::InvalidEmbeddedOperation(_) => {
+ AER::BadRequest(ApiError::new(sub_code, 60, self.get_error_message(), None))
+ }
}
}
}
@@ -374,6 +379,9 @@ impl UserErrors {
Self::ErrorCloningConnector(error_message) => {
format!("Error cloning connector: {error_message}")
}
+ Self::InvalidEmbeddedOperation(error_message) => {
+ format!("Invalid Embedded Operation: {error_message}")
+ }
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index aef9951e2a..6b9dea4000 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -3904,3 +3904,62 @@ pub async fn clone_connector(
})
.attach_printable("Failed to create cloned connector")
}
+
+#[cfg(feature = "v1")]
+pub async fn issue_embedded_token(
+ state: SessionState,
+ processor: domain::Processor,
+ business_profile: Option<domain::Profile>,
+) -> UserResponse<user_api::IssueEmbeddedTokenResponse> {
+ let profile_id = business_profile
+ .ok_or(UserErrors::InvalidEmbeddedOperation(
+ "No business profile ID provided".to_string(),
+ ))
+ .attach_printable("No profile_id provided in headers for embedded token")?
+ .get_id()
+ .clone();
+ state
+ .store
+ .find_business_profile_by_merchant_id_profile_id(
+ processor.get_key_store(),
+ processor.get_account().get_id(),
+ &profile_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidEmbeddedOperation(
+ "Invalid business profile ID".to_string(),
+ ))?;
+ auth::embedded::EmbeddedToken::new_token(
+ state.tenant.tenant_id,
+ processor.get_account().get_org_id().clone(),
+ processor.get_account().get_id().clone(),
+ profile_id,
+ &state.conf,
+ )
+ .await
+ .map(|token| {
+ ApplicationResponse::Json(user_api::IssueEmbeddedTokenResponse {
+ token: token.into(),
+ })
+ })
+}
+
+#[cfg(feature = "v1")]
+pub async fn embedded_token_info(
+ _state: SessionState,
+ processor: domain::Processor,
+ business_profile: Option<domain::Profile>,
+) -> UserResponse<user_api::EmbeddedTokenInfoResponse> {
+ Ok(ApplicationResponse::Json(
+ user_api::EmbeddedTokenInfoResponse {
+ org_id: processor.get_account().get_org_id().clone(),
+ merchant_id: processor.get_account().get_id().clone(),
+ merchant_account_version: processor.get_account().version,
+ profile_id: business_profile
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Missing Profile ID")?
+ .get_id()
+ .clone(),
+ },
+ ))
+}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 1a87b51049..f268bedd9c 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -223,7 +223,8 @@ pub fn mk_app(
.service(routes::ConnectorOnboarding::server(state.clone()))
.service(routes::Analytics::server(state.clone()))
.service(routes::WebhookEvents::server(state.clone()))
- .service(routes::FeatureMatrix::server(state.clone()));
+ .service(routes::FeatureMatrix::server(state.clone()))
+ .service(routes::Embedded::server(state.clone()));
}
#[cfg(feature = "v2")]
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 7d54cfea13..fc39516933 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -94,9 +94,9 @@ pub use self::app::Proxy;
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, Oidc, PaymentLink,
- PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile,
+ ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, FeatureMatrix, Files, Forex,
+ Gsm, 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/admin.rs b/crates/router/src/routes/admin.rs
index 63bf64e708..f24635a2d0 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -531,9 +531,9 @@ pub async fn connector_create(
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
- &auth::JWTAuthMerchantFromRoute {
- merchant_id: merchant_id.clone(),
- required_permission: Permission::ProfileConnectorWrite,
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: Some(merchant_id.clone()),
+ permission: Some(Permission::ProfileConnectorWrite),
},
req.headers(),
),
@@ -608,12 +608,12 @@ pub async fn connector_retrieve(
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
- &auth::JWTAuthMerchantFromRoute {
- merchant_id,
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: Some(merchant_id.clone()),
// This should ideally be ProfileConnectorRead, but since this API responds with
// sensitive data, keeping this as ProfileConnectorWrite
// TODO: Convert this to ProfileConnectorRead once data is masked.
- required_permission: Permission::ProfileConnectorWrite,
+ permission: Some(Permission::ProfileConnectorWrite),
},
req.headers(),
),
@@ -750,9 +750,9 @@ pub async fn connector_list_profile(
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
- &auth::JWTAuthMerchantFromRoute {
- merchant_id,
- required_permission: Permission::ProfileConnectorRead,
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: Some(merchant_id),
+ permission: Some(Permission::ProfileConnectorRead),
},
req.headers(),
),
@@ -794,9 +794,9 @@ pub async fn connector_update(
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
- &auth::JWTAuthMerchantFromRoute {
- merchant_id: merchant_id.clone(),
- required_permission: Permission::ProfileConnectorWrite,
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: Some(merchant_id.clone()),
+ permission: Some(Permission::ProfileConnectorWrite),
},
req.headers(),
),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ff4b6683d3..99aa201c97 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -3097,6 +3097,18 @@ impl ConnectorOnboarding {
}
}
+pub struct Embedded;
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+impl Embedded {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/embedded")
+ .app_data(web::Data::new(state))
+ .service(web::resource("").route(web::get().to(user::embedded_token_info)))
+ .service(web::resource("/token").route(web::get().to(user::issue_embedded_token)))
+ }
+}
+
#[cfg(feature = "olap")]
pub struct WebhookEvents;
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index a26a0ea2f5..12bed2a845 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -314,7 +314,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::UploadFileToUserThemeStorage
| Flow::GetUserThemeUsingLineage
| Flow::ListAllThemesInLineage
- | Flow::CloneConnector => Self::User,
+ | Flow::CloneConnector
+ | Flow::EmbeddedTokenInfo
+ | Flow::GetEmbeddedToken => Self::User,
Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,
diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs
index 1caef3d458..6ff7b2a610 100644
--- a/crates/router/src/routes/profiles.rs
+++ b/crates/router/src/routes/profiles.rs
@@ -153,9 +153,9 @@ pub async fn profile_retrieve(
},
auth::auth_type(
&auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),
- &auth::JWTAuthMerchantFromRoute {
- merchant_id: merchant_id.clone(),
- required_permission: permissions::Permission::ProfileAccountRead,
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: Some(merchant_id.clone()),
+ permission: Some(permissions::Permission::ProfileAccountRead),
},
req.headers(),
),
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a50565302f..8767ab81ec 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -1063,3 +1063,57 @@ pub async fn clone_connector(
))
.await
}
+
+#[cfg(feature = "v1")]
+pub async fn issue_embedded_token(
+ state: web::Data<AppState>,
+ http_req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::GetEmbeddedToken;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &http_req,
+ (),
+ |state, auth_data, _, _| {
+ user_core::issue_embedded_token(
+ state,
+ auth_data.platform.get_processor().clone(),
+ auth_data.profile,
+ )
+ },
+ &auth::ApiKeyAuth {
+ is_platform_allowed: false,
+ is_connected_allowed: false,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v1")]
+pub async fn embedded_token_info(
+ state: web::Data<AppState>,
+ http_req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::EmbeddedTokenInfo;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &http_req,
+ (),
+ |state, auth_data, _, _| {
+ user_core::embedded_token_info(
+ state,
+ auth_data.platform.get_processor().clone(),
+ auth_data.profile,
+ )
+ },
+ &auth::JWTAndEmbeddedAuth {
+ merchant_id_from_route: None,
+ permission: None,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index ddb8153528..7ad68e29f8 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -15,7 +15,9 @@ use common_utils::{date_time, fp_utils, id_type};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
-use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
+use jsonwebtoken::{
+ decode, errors::ErrorKind::ExpiredSignature, Algorithm, DecodingKey, Validation,
+};
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::PeekInterface;
@@ -55,6 +57,7 @@ use crate::{
pub mod blacklist;
pub mod cookies;
pub mod decision;
+pub mod embedded;
#[cfg(feature = "partial-auth")]
mod detached;
@@ -167,6 +170,10 @@ pub enum AuthenticationType {
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
},
+ EmbeddedJwt {
+ merchant_id: id_type::MerchantId,
+ profile_id: id_type::ProfileId,
+ },
NoAuth,
}
@@ -197,7 +204,8 @@ impl AuthenticationType {
}
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id }
- | Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id),
+ | Self::InternalMerchantIdProfileId { merchant_id, .. }
+ | Self::EmbeddedJwt { merchant_id, .. } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
| Self::BasicAuth { .. }
@@ -323,6 +331,36 @@ pub struct SinglePurposeOrLoginToken {
pub tenant_id: Option<id_type::TenantId>,
}
+#[derive(serde::Deserialize)]
+#[serde(untagged)]
+pub enum AuthOrEmbeddedClaims {
+ AuthToken(AuthToken),
+ EmbeddedToken(embedded::EmbeddedToken),
+}
+
+impl AuthOrEmbeddedClaims {
+ fn get_tenant_id(&self) -> Option<&id_type::TenantId> {
+ match self {
+ Self::AuthToken(payload) => payload.tenant_id.as_ref(),
+ Self::EmbeddedToken(payload) => Some(&payload.tenant_id),
+ }
+ }
+
+ fn get_merchant_id(&self) -> &id_type::MerchantId {
+ match self {
+ Self::AuthToken(payload) => &payload.merchant_id,
+ Self::EmbeddedToken(payload) => &payload.merchant_id,
+ }
+ }
+
+ fn get_profile_id(&self) -> &id_type::ProfileId {
+ match self {
+ Self::AuthToken(payload) => &payload.profile_id,
+ Self::EmbeddedToken(payload) => &payload.profile_id,
+ }
+ }
+}
+
#[async_trait]
pub trait AuthenticateAndFetch<T, A>
where
@@ -4460,6 +4498,112 @@ where
}
}
+pub struct JWTAndEmbeddedAuth {
+ pub merchant_id_from_route: Option<id_type::MerchantId>,
+ pub permission: Option<Permission>,
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAndEmbeddedAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthOrEmbeddedClaims>(request_headers, state).await?;
+
+ if let AuthOrEmbeddedClaims::AuthToken(ref auth_payload) = payload {
+ if auth_payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+ if let Some(required_permission) = self.permission {
+ let role_info = authorization::get_role_info(state, auth_payload).await?;
+ authorization::check_permission(required_permission, &role_info)?;
+ }
+ }
+
+ authorization::check_tenant(
+ payload.get_tenant_id().cloned(),
+ &state.session_state().tenant.tenant_id,
+ )?;
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ payload.get_merchant_id(),
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(payload.get_merchant_id(), &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch merchant account for the merchant id")?;
+
+ let profile = state
+ .store()
+ .find_business_profile_by_merchant_id_profile_id(
+ &key_store,
+ payload.get_merchant_id(),
+ payload.get_profile_id(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
+ .attach_printable("Failed to fetch business profile")?;
+
+ fp_utils::when(
+ self.merchant_id_from_route
+ .as_ref()
+ .is_some_and(|mid_from_route| payload.get_merchant_id() != mid_from_route),
+ || Err(report!(errors::ApiErrorResponse::InvalidJwtToken)),
+ )?;
+
+ let initiator = if let AuthOrEmbeddedClaims::AuthToken(ref auth_payload) = payload {
+ Some(domain::Initiator::Jwt {
+ user_id: auth_payload.user_id.clone(),
+ })
+ } else {
+ Some(domain::Initiator::EmbeddedToken {
+ merchant_id: payload.get_merchant_id().clone(),
+ })
+ };
+
+ let platform = domain::Platform::new(
+ merchant.clone(),
+ key_store.clone(),
+ merchant,
+ key_store,
+ initiator,
+ );
+
+ let auth = AuthenticationData {
+ platform,
+ profile: Some(profile),
+ };
+ let auth_type = match payload {
+ AuthOrEmbeddedClaims::AuthToken(auth_payload) => AuthenticationType::MerchantJwt {
+ merchant_id: auth_payload.merchant_id,
+ user_id: Some(auth_payload.user_id),
+ },
+ AuthOrEmbeddedClaims::EmbeddedToken(embedded_payload) => {
+ AuthenticationType::EmbeddedJwt {
+ merchant_id: embedded_payload.merchant_id,
+ profile_id: embedded_payload.profile_id,
+ }
+ }
+ };
+ Ok((auth, auth_type))
+ }
+}
+
pub trait ClientSecretFetch {
fn get_client_secret(&self) -> Option<&String>;
}
@@ -4794,7 +4938,13 @@ where
let key = DecodingKey::from_secret(secret);
decode::<T>(token, &key, &Validation::new(Algorithm::HS256))
.map(|decoded| decoded.claims)
- .change_context(errors::ApiErrorResponse::InvalidJwtToken)
+ .map_err(|e| {
+ if e.kind() == &ExpiredSignature {
+ report!(errors::ApiErrorResponse::ExpiredJwtToken)
+ } else {
+ report!(errors::ApiErrorResponse::InvalidJwtToken)
+ }
+ })
}
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> {
diff --git a/crates/router/src/services/authentication/embedded.rs b/crates/router/src/services/authentication/embedded.rs
new file mode 100644
index 0000000000..c187451f6c
--- /dev/null
+++ b/crates/router/src/services/authentication/embedded.rs
@@ -0,0 +1,43 @@
+use std::time::Duration;
+
+use common_utils::id_type;
+
+use super::jwt;
+use crate::{configs::Settings, consts, core::errors::UserResult};
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct EmbeddedToken {
+ pub tenant_id: id_type::TenantId,
+ pub org_id: id_type::OrganizationId,
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: id_type::ProfileId,
+ pub token_access_type: EmbeddedTokenAllowList,
+ exp: u64,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub enum EmbeddedTokenAllowList {
+ All,
+}
+
+impl EmbeddedToken {
+ pub async fn new_token(
+ tenant_id: id_type::TenantId,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ profile_id: id_type::ProfileId,
+ settings: &Settings,
+ ) -> UserResult<String> {
+ let exp_duration = Duration::from_secs(consts::JWT_EMBEDDED_TOKEN_TIME_IN_SECS);
+ let exp = jwt::generate_exp(exp_duration)?.as_secs();
+ let token_payload = Self {
+ tenant_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ token_access_type: EmbeddedTokenAllowList::All,
+ exp,
+ };
+ jwt::generate_jwt(&token_payload, settings).await
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 66a30e24dc..291c684a7d 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -717,6 +717,10 @@ pub enum Flow {
ApplyPaymentMethodData,
/// Payouts aggregates flow
PayoutsAggregate,
+ // Get embedded token flow
+ GetEmbeddedToken,
+ // Get embedded token info flow
+ EmbeddedTokenInfo,
}
/// Trait for providing generic behaviour to flow metric