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(user): POST /user/launch_trace — federated HyperSage Trace session mint (#13081)
Prajjwal Kumarc64e80a117dd
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 58555ce785..f22ef5642c 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -450,6 +450,12 @@ enabled = false # Enable or disable chat featureshyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow hostencryption_key = "" # Key to encrypt and decrypt chats+[sage]+enabled = false # Master switch for sage sessions+base_url = "" # Sage base URL (e.g. https://sage.<env>.example.com)+mint_path = "" # Path on sage that mints a session (e.g. /api/session)+infra_key = "" # Shared bearer presented to sage; KMS-decrypted at boot+[proxy_status_mapping]proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the responsediff --git a/config/development.toml b/config/development.tomlindex 4c74d2d705..5c73a298bb 100644--- a/config/development.toml+++ b/config/development.toml@@ -1535,6 +1535,12 @@ enabled = falsehyperswitch_ai_host = "http://0.0.0.0:8000"encryption_key = ""+[sage]+enabled = false # Master switch for sage sessions+base_url = "" # Sage base URL+mint_path = "" # Path on sage that mints a session+infra_key = "" # Shared bearer presented to sage+[proxy_status_mapping]proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response[list_dispute_supported_connectors]diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex e3acdbbe8a..0184a3ef28 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1357,6 +1357,12 @@ enabled = falsehyperswitch_ai_host = "http://0.0.0.0:8000"encryption_key = ""+[sage]+enabled = false # Master switch for sage sessions+base_url = "" # Sage base URL+mint_path = "" # Path on sage that mints a session+infra_key = "" # Shared bearer presented to sage+[authentication_providers]click_to_pay = {connector_list = "adyen, cybersource, trustpay"}diff --git a/crates/api_models/src/launch_sage.rs b/crates/api_models/src/launch_sage.rsnew file mode 100644index 0000000000..8b58b5503a--- /dev/null+++ b/crates/api_models/src/launch_sage.rs@@ -0,0 +1,63 @@+use std::collections::HashMap;++use common_utils::events::{ApiEventMetric, ApiEventsType};+use serde::{Deserialize, Serialize};+use serde_json::Value;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LaunchSageResponse {+ pub handoff_url: String,++ #[serde(skip_serializing_if = "Option::is_none")]+ pub expires_at: Option<String>,+}++impl ApiEventMetric for LaunchSageResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Miscellaneous)+ }+}++/// A single authorisation grant. One `ScopeEntry` per `user_roles` row.+///+/// The shape is deliberately generic so new authorisation dimensions can be+/// added without a schema change:+/// - `entity_type` is a string, not an enum — new levels (e.g. `"connector"`,+/// `"region"`) are additive.+/// - `path` is an open map of ancestor ids — new hierarchy levels just add+/// new keys.+/// - `constraints` is an open JSON bag for attribute-level restrictions+/// (e.g. `{"currency": ["INR"]}`, `{"valid_until": "2026-12-31"}`).+///+/// Consumers deny by default when they encounter an unknown `entity_type` or+/// an unrecognised constraint — old readers stay safe under new shapes.+///+/// Wildcards are implicit at each level: a `merchant`-level grant covers all+/// profiles under that merchant. Only restricted access needs lower-level+/// entries.+#[derive(Debug, Clone, Serialize)]+pub struct ScopeEntry {+ pub entity_type: String,+ pub entity_id: String,+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]+ pub path: HashMap<String, String>,+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]+ pub constraints: HashMap<String, Value>,+}++/// Outbound Sage mint-request body. Not part of the public API surface —+/// co-located with the response shape so reviewers see the full contract+/// in one place. Identity fields are read from the verified AuthToken+/// inside the handler, never from inbound input.+#[derive(Debug, Clone, Serialize)]+pub struct SageSessionRequest {+ pub user_id: String,+ pub launch_merchant_id: String,+ pub launch_profile_id: String,+ pub org_id: String,+ pub role: String,+ pub source: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub subject_jti: Option<String>,+ pub scope: Vec<ScopeEntry>,+}diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex 526361ff02..59a46fff7a 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -24,6 +24,7 @@ pub mod feature_matrix;pub mod files;pub mod gsm;pub mod health_check;+pub mod launch_sage;pub mod mandates;pub mod merchant_connector_webhook_management;pub mod oidc;diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex ea6ccb82e6..deca61bbf6 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -314,6 +314,30 @@ impl SecretsHandler for settings::ChatSettings {}}+#[async_trait::async_trait]+impl SecretsHandler for settings::SageSettings {+ async fn convert_to_raw_secret(+ value: SecretStateContainer<Self, SecuredSecret>,+ secret_management_client: &dyn SecretManagementInterface,+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {+ let sage_settings = value.get_inner();++ // Skip the secret fetch when disabled — costs zero.+ let infra_key = if sage_settings.enabled {+ secret_management_client+ .get_secret(sage_settings.infra_key.clone())+ .await?+ } else {+ sage_settings.infra_key.clone()+ };++ Ok(value.transition_state(|sage_settings| Self {+ infra_key,+ ..sage_settings+ }))+ }+}+#[async_trait::async_trait]impl SecretsHandler for settings::NetworkTokenizationService {async fn convert_to_raw_secret(@@ -515,6 +539,11 @@ pub(crate) async fn fetch_raw_secrets(.await.expect("Failed to decrypt chat configs");+ #[allow(clippy::expect_used)]+ let sage = settings::SageSettings::convert_to_raw_secret(conf.sage, secret_management_client)+ .await+ .expect("Failed to decrypt sage configs");+#[allow(clippy::expect_used)]let superposition =external_services::superposition::SuperpositionClientConfig::convert_to_raw_secret(@@ -533,6 +562,7 @@ pub(crate) async fn fetch_raw_secrets(server: conf.server,application_source: conf.application_source,chat,+ sage,master_database,redis: conf.redis,log: conf.log,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex a6d207d9b6..64da24fe9e 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -83,6 +83,7 @@ pub struct Settings<S: SecretState> {pub proxy: Proxy,pub env: Env,pub chat: SecretStateContainer<ChatSettings, S>,+ pub sage: SecretStateContainer<SageSettings, S>,pub master_database: SecretStateContainer<Database, S>,#[cfg(feature = "olap")]pub replica_database: SecretStateContainer<Database, S>,@@ -243,6 +244,15 @@ pub struct ChatSettings {pub encryption_key: Secret<String>,}+#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct SageSettings {+ pub enabled: bool,+ pub base_url: String,+ pub mint_path: String,+ pub infra_key: Secret<String>,+}+#[derive(Debug, Clone, Default, Deserialize)]pub struct Multitenancy {pub tenants: TenantConfig,@@ -1214,6 +1224,7 @@ impl Settings<SecuredSecret> {self.locker.validate()?;self.connectors.validate("connectors")?;self.chat.get_inner().validate()?;+ self.sage.get_inner().validate()?;self.cors.validate()?;self.schedulerdiff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 19165a2b65..57c6b674e4 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -359,3 +359,28 @@ impl super::settings::ChatSettings {})}}++impl super::settings::SageSettings {+ pub fn validate(&self) -> Result<(), ApplicationError> {+ use common_utils::fp_utils::when;++ when(self.enabled && self.base_url.trim().is_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "sage.base_url must be set if sage.enabled is true".into(),+ ))+ })?;+ when(self.enabled && self.mint_path.trim().is_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "sage.mint_path must be set if sage.enabled is true".into(),+ ))+ })?;+ when(+ self.enabled && self.infra_key.peek().trim().is_empty(),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "sage.infra_key must be set if sage.enabled is true".into(),+ ))+ },+ )+ }+}diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex 53f3467b05..f33cccc5d2 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -2,6 +2,8 @@ pub mod chat;pub mod customers_error_response;pub mod error_handlers;#[cfg(feature = "olap")]+pub mod launch_sage;+#[cfg(feature = "olap")]pub mod oidc;pub mod transformers;#[cfg(feature = "olap")]diff --git a/crates/router/src/core/errors/launch_sage.rs b/crates/router/src/core/errors/launch_sage.rsnew file mode 100644index 0000000000..81663f1c23--- /dev/null+++ b/crates/router/src/core/errors/launch_sage.rs@@ -0,0 +1,45 @@+#[derive(Debug, thiserror::Error)]+pub enum LaunchSageErrors {+ #[error("Sage is not enabled in this environment")]+ SageDisabled,++ #[error("Sage is not available for this role")]+ Forbidden,++ #[error("Sage call failed")]+ SageError,++ #[error("Internal server error")]+ InternalServerError,+}++impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>+ for LaunchSageErrors+{+ fn switch(&self) -> api_models::errors::types::ApiErrorResponse {+ use api_models::errors::types::{ApiError, ApiErrorResponse as AER};+ let sub_code = "SG";+ match self {+ Self::SageDisabled => {+ AER::NotFound(ApiError::new(sub_code, 1, self.get_error_message(), None))+ }+ Self::Forbidden => {+ AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None))+ }+ Self::SageError | Self::InternalServerError => {+ AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))+ }+ }+ }+}++impl LaunchSageErrors {+ pub fn get_error_message(&self) -> String {+ match self {+ Self::SageDisabled => "Not found".to_string(),+ Self::Forbidden => "Not allowed".to_string(),+ Self::SageError => "Sage temporarily unavailable, please retry".to_string(),+ Self::InternalServerError => "Something went wrong".to_string(),+ }+ }+}diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex 321933f85d..f134f3db25 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -57,6 +57,7 @@ use crate::{db::user_role::ListUserRolesByOrgIdPayload, types::transformers::Foruse crate::{services::email::types as email_types, utils::user as user_utils};pub mod dashboard_metadata;+pub mod launch_sage;#[cfg(feature = "dummy_connector")]pub mod sample_data;pub mod theme;diff --git a/crates/router/src/core/user/launch_sage.rs b/crates/router/src/core/user/launch_sage.rsnew file mode 100644index 0000000000..54b0b2c7df--- /dev/null+++ b/crates/router/src/core/user/launch_sage.rs@@ -0,0 +1,225 @@+use std::collections::HashMap;++use api_models::launch_sage as launch_sage_api;+use common_enums::EntityType;+use common_utils::{+ consts::REQUEST_TIME_OUT_FOR_AI_SERVICE,+ errors::CustomResult,+ request::{Method, RequestBuilder, RequestContent},+};+use diesel_models::enums::UserStatus;+use error_stack::ResultExt;+use external_services::http_client;+use hyperswitch_masking::PeekInterface;+use router_env::{instrument, logger, tracing};++use crate::{+ core::errors::launch_sage::LaunchSageErrors,+ db::user_role::ListUserRolesByUserIdPayload,+ routes::SessionState,+ services::{authentication as auth, authorization::roles, ApplicationResponse},+};++// Reusing the AI-service timeout until a dedicated constant is added.+const REQUEST_TIMEOUT_SECS: u64 = REQUEST_TIME_OUT_FOR_AI_SERVICE;++const SAGE_SOURCE: &str = "hyperswitch-cc";++#[instrument(skip_all, fields(user_id, merchant_id))]+pub async fn launch_sage(+ state: SessionState,+ user_from_token: auth::UserFromToken,+) -> CustomResult<ApplicationResponse<launch_sage_api::LaunchSageResponse>, LaunchSageErrors> {+ let conf = state.conf.sage.get_inner();++ if !conf.enabled {+ return Err(error_stack::Report::new(LaunchSageErrors::SageDisabled))+ .attach_printable("sage flag is off in this env");+ }++ let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(+ &state,+ &user_from_token.role_id,+ &user_from_token.org_id,+ user_from_token+ .tenant_id+ .as_ref()+ .unwrap_or(&state.tenant.tenant_id),+ )+ .await+ .change_context(LaunchSageErrors::InternalServerError)+ .attach_printable("Failed to retrieve role information")?;++ if role_info.is_internal() {+ return Err(error_stack::Report::new(LaunchSageErrors::Forbidden))+ .attach_printable("Internal roles are not eligible for sage");+ }++ let capped_role = map_entity_type_to_role(role_info.get_entity_type());++ // Send the full authorised scope on the mint request so sage can support+ // multi-merchant / multi-profile sessions. Shape mirrors+ // analytics::get_global_search_results (analytics.rs:3982).+ let scope = build_user_scope(&state, &user_from_token).await?;++ // Every id MUST come from the verified AuthToken — the route handler+ // takes an empty body by design.+ let request_body = launch_sage_api::SageSessionRequest {+ user_id: user_from_token.user_id.clone(),+ launch_merchant_id: user_from_token.merchant_id.get_string_repr().to_owned(),+ launch_profile_id: user_from_token.profile_id.get_string_repr().to_owned(),+ org_id: user_from_token.org_id.get_string_repr().to_owned(),+ role: capped_role.to_string(),+ source: SAGE_SOURCE.to_owned(),+ subject_jti: None,+ scope,+ };++ let url = format!("{}{}", conf.base_url, conf.mint_path);++ let request = RequestBuilder::new()+ .method(Method::Post)+ .url(&url)+ .attach_default_headers()+ .header(+ "Authorization",+ &format!("Bearer {}", conf.infra_key.peek()),+ )+ .set_body(RequestContent::Json(Box::new(request_body)))+ .build();++ let response =+ http_client::send_request(&state.conf.proxy, request, Some(REQUEST_TIMEOUT_SECS))+ .await+ .change_context(LaunchSageErrors::SageError)+ .attach_printable("Error calling sage")?;++ let status = response.status();+ if !status.is_success() {+ // 401 is a specific SRE-actionable signal (shared infra key drift).+ // Surface it loudly in logs; the caller still sees a generic 5xx.+ if status.as_u16() == 401 {+ logger::error!("sage: upstream 401 — likely infra key drift");+ }+ return Err(error_stack::Report::new(LaunchSageErrors::SageError))+ .attach_printable(format!("sage returned status {status}"));+ }++ let parsed = response+ .json::<launch_sage_api::LaunchSageResponse>()+ .await+ .change_context(LaunchSageErrors::SageError)+ .attach_printable("Failed to deserialize sage handoff response")?;++ // Strip the `?t=…` bearer before logging — it's a single-use credential+ // that must not survive log aggregation.+ if let Some(url_only) = parsed.handoff_url.split('?').next() {+ logger::info!(handoff_url_path = %url_only, "sage: minted federated session");+ }++ Ok(ApplicationResponse::Json(parsed))+}++/// Enumerate the caller's active user_roles in the JWT's org and emit one+/// generic `ScopeEntry` per row. Wildcards are implicit at each level — a+/// merchant-level entry covers all profiles under that merchant without any+/// explicit wildcard field.+async fn build_user_scope(+ state: &SessionState,+ user_from_token: &auth::UserFromToken,+) -> CustomResult<Vec<launch_sage_api::ScopeEntry>, LaunchSageErrors> {+ let tenant_id = user_from_token+ .tenant_id+ .as_ref()+ .unwrap_or(&state.tenant.tenant_id);++ let user_roles = state+ .global_store+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {+ user_id: &user_from_token.user_id,+ tenant_id,+ org_id: Some(&user_from_token.org_id),+ merchant_id: None,+ profile_id: None,+ entity_id: None,+ version: None,+ status: Some(UserStatus::Active),+ limit: None,+ })+ .await+ .change_context(LaunchSageErrors::InternalServerError)+ .attach_printable("Failed to list user roles for scope enumeration")?;++ let mut scope: Vec<launch_sage_api::ScopeEntry> = Vec::with_capacity(user_roles.len());++ for user_role in &user_roles {+ let Some((entity_id, entity_type)) = user_role.get_entity_id_and_type() else {+ continue;+ };+ scope.push(user_role_to_scope_entry(user_role, entity_id, entity_type));+ }++ // Deterministic ordering for clean wire diffs across identical calls.+ scope.sort_by(|a, b| {+ a.entity_type+ .cmp(&b.entity_type)+ .then_with(|| a.entity_id.cmp(&b.entity_id))+ });++ Ok(scope)+}++fn user_role_to_scope_entry(+ user_role: &diesel_models::user_role::UserRole,+ entity_id: String,+ entity_type: EntityType,+) -> launch_sage_api::ScopeEntry {+ let mut path: HashMap<String, String> = HashMap::new();+ path.insert(+ "tenant_id".to_owned(),+ user_role.tenant_id.get_string_repr().to_owned(),+ );+ let (include_org, include_merchant) = match entity_type {+ EntityType::Tenant | EntityType::Organization => (false, false),+ EntityType::Merchant => (true, false),+ EntityType::Profile => (true, true),+ };+ if include_org {+ if let Some(org_id) = user_role.org_id.as_ref() {+ path.insert("org_id".to_owned(), org_id.get_string_repr().to_owned());+ }+ }+ if include_merchant {+ if let Some(merchant_id) = user_role.merchant_id.as_ref() {+ path.insert(+ "merchant_id".to_owned(),+ merchant_id.get_string_repr().to_owned(),+ );+ }+ }+ launch_sage_api::ScopeEntry {+ entity_type: entity_type.to_string(),+ entity_id,+ path,+ constraints: HashMap::new(),+ }+}++/// Wire-contract vocabulary for the `role` field on `SageSessionRequest` —+/// mirrors hypersage's `src/web/auth.py:Role` enum. Kept private to this+/// module so the shared API-models crate stays free of sage-side vocabulary+/// coupling; the string leaves this file via `.to_string()` at the mint+/// call site.+#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display)]+#[strum(serialize_all = "snake_case")]+enum SageRole {+ Operator,+ Viewer,+}++fn map_entity_type_to_role(entity: EntityType) -> SageRole {+ match entity {+ EntityType::Tenant | EntityType::Organization => SageRole::Operator,+ EntityType::Merchant | EntityType::Profile => SageRole::Viewer,+ }+}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex ee09dc61ca..b810ff890a 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -2838,6 +2838,7 @@ impl User {route = route.service(web::resource("").route(web::get().to(user::get_active_user_details))).service(web::resource("/signin").route(web::post().to(user::user_signin)))+ .service(web::resource("/launch_sage").route(web::post().to(user::launch_sage))).service(web::resource("/v2/signin").route(web::post().to(user::user_signin)))// signin/signup with sso using openidconnect.service(web::resource("/oidc").route(web::post().to(user::sso_sign)))diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 6d58af8a93..7ed80ca2c8 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -333,7 +333,8 @@ impl From<Flow> for ApiIdentifier {| Flow::GetEmbeddedToken| Flow::GetUserDetailsInternal| Flow::ListUsersInternal- | Flow::ListMembersForEntity => Self::User,+ | Flow::ListMembersForEntity+ | Flow::LaunchSage => Self::User,Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rsindex d542aba42f..b868809b2b 100644--- a/crates/router/src/routes/user.rs+++ b/crates/router/src/routes/user.rs@@ -39,6 +39,27 @@ pub async fn get_active_user_details(state: web::Data<AppState>, req: HttpReques.await}+/// `POST /user/launch_sage` — mint a sage session for the Control Center+/// user. Body is empty by design; identity is read from the verified+/// `AuthToken`. Sage performs the authoritative merchant-access gate.+#[cfg(feature = "olap")]+pub async fn launch_sage(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {+ let flow = Flow::LaunchSage;+ Box::pin(api::server_wrap(+ flow,+ state,+ &http_req,+ (),+ |state, user: auth::UserFromToken, _, _| user_core::launch_sage::launch_sage(state, user),+ &auth::DashboardNoPermissionAuth {+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "email")]pub async fn user_signup_with_merchant_id(state: web::Data<AppState>,diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex f76f6ba2fe..8a813d51ab 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -419,6 +419,8 @@ pub enum Flow {GetDataFromHyperswitchAiFlow,// List all chat interactionsListAllChatInteractions,+ /// Mint a sage session for the dashboard user.+ LaunchSage,/// User Sign UpUserSignUp,/// User Sign Up