Skip to content

Commit

Permalink
chore(keymanager): add tenant-id to keymanager requests (#6968)
Browse files Browse the repository at this point in the history
Co-authored-by: hyperswitch-bot[bot] <148525504+hyperswitch-bot[bot]@users.noreply.github.com>
  • Loading branch information
dracarys18 and hyperswitch-bot[bot] authored Jan 6, 2025
1 parent 84a4fb1 commit 7901302
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 11 deletions.
2 changes: 1 addition & 1 deletion config/config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ sdk_eligible_payment_methods = "card"

[multitenancy]
enabled = false
global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}

[multitenancy.tenants.public]
base_url = "http://localhost:8080" # URL of the tenant
Expand Down
2 changes: 1 addition & 1 deletion config/deployments/env_specific.toml
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.

[multitenancy]
enabled = false
global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}

[multitenancy.tenants.public]
base_url = "http://localhost:8080"
Expand Down
2 changes: 1 addition & 1 deletion config/development.toml
Original file line number Diff line number Diff line change
Expand Up @@ -794,7 +794,7 @@ sdk_eligible_payment_methods = "card"

[multitenancy]
enabled = false
global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
global_tenant = { tenant_id = "global" ,schema = "public", redis_key_prefix = "global", clickhouse_database = "default"}

[multitenancy.tenants.public]
base_url = "http://localhost:8080"
Expand Down
2 changes: 1 addition & 1 deletion config/docker_compose.toml
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ sdk_eligible_payment_methods = "card"

[multitenancy]
enabled = false
global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default" }

[multitenancy.tenants.public]
base_url = "http://localhost:8080"
Expand Down
3 changes: 3 additions & 0 deletions crates/common_utils/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,6 @@ pub const APPLEPAY_VALIDATION_URL: &str =

/// Request ID
pub const X_REQUEST_ID: &str = "x-request-id";

/// Default Tenant ID for the `Global` tenant
pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global";
12 changes: 11 additions & 1 deletion crates/common_utils/src/id_type/tenant.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::errors::{CustomResult, ValidationError};
use crate::{
consts::DEFAULT_GLOBAL_TENANT_ID,
errors::{CustomResult, ValidationError},
};

crate::id_type!(
TenantId,
Expand All @@ -15,6 +18,13 @@ crate::impl_queryable_id_type!(TenantId);
crate::impl_to_sql_from_sql_id_type!(TenantId);

impl TenantId {
/// Get the default global tenant ID
pub fn get_default_global_tenant_id() -> Self {
Self(super::LengthId::new_unchecked(
super::AlphaNumericId::new_unchecked(DEFAULT_GLOBAL_TENANT_ID.to_string()),
))
}

/// Get tenant id from String
pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(std::borrow::Cow::from(tenant_id))
Expand Down
15 changes: 12 additions & 3 deletions crates/common_utils/src/keymanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ use once_cell::sync::OnceCell;
use router_env::{instrument, logger, tracing};

use crate::{
consts::BASE64_ENGINE,
consts::{BASE64_ENGINE, TENANT_HEADER},
errors,
types::keymanager::{
BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest,
EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState,
EncryptionCreateRequest, EncryptionTransferRequest, GetKeymanagerTenant, KeyManagerState,
TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
},
};
Expand Down Expand Up @@ -100,7 +100,7 @@ pub async fn call_encryption_service<T, R>(
request_body: T,
) -> errors::CustomResult<R, errors::KeyManagerClientError>
where
T: ConvertRaw + Send + Sync + 'static + Debug,
T: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug,
R: serde::de::DeserializeOwned,
{
let url = format!("{}/{endpoint}", &state.url);
Expand All @@ -122,6 +122,15 @@ where
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
))
}

//Add Tenant ID
header.push((
HeaderName::from_str(TENANT_HEADER)
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
HeaderValue::from_str(request_body.get_tenant_id(state).get_string_repr())
.change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?,
));

let response = send_encryption_request(
state,
HeaderMap::from_iter(header.into_iter()),
Expand Down
30 changes: 30 additions & 0 deletions crates/common_utils/src/types/keymanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,23 @@ use crate::{
transformers::{ForeignFrom, ForeignTryFrom},
};

macro_rules! impl_get_tenant_for_request {
($ty:ident) => {
impl GetKeymanagerTenant for $ty {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId {
match self.identifier {
Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(),
Identifier::Merchant(_) => state.tenant_id.clone(),
}
}
}
};
}

#[derive(Debug, Clone)]
pub struct KeyManagerState {
pub tenant_id: id_type::TenantId,
pub global_tenant_id: id_type::TenantId,
pub enabled: bool,
pub url: String,
pub client_idle_timeout: Option<u64>,
Expand All @@ -35,6 +50,11 @@ pub struct KeyManagerState {
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
}

pub trait GetKeymanagerTenant {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId;
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[serde(tag = "data_identifier", content = "key_identifier")]
pub enum Identifier {
Expand Down Expand Up @@ -70,6 +90,10 @@ pub struct BatchEncryptDataRequest {
pub data: DecryptedDataGroup,
}

impl_get_tenant_for_request!(EncryptionCreateRequest);
impl_get_tenant_for_request!(EncryptionTransferRequest);
impl_get_tenant_for_request!(BatchEncryptDataRequest);

impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<Vec<u8>>,
Expand Down Expand Up @@ -219,6 +243,12 @@ pub struct DecryptDataRequest {
pub data: StrongSecret<String>,
}

impl_get_tenant_for_request!(EncryptDataRequest);
impl_get_tenant_for_request!(TransientBatchDecryptDataRequest);
impl_get_tenant_for_request!(TransientDecryptDataRequest);
impl_get_tenant_for_request!(BatchDecryptDataRequest);
impl_get_tenant_for_request!(DecryptDataRequest);

impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)>
for FxHashMap<String, Encryptable<Secret<T, S>>>
where
Expand Down
12 changes: 12 additions & 0 deletions crates/router/src/configs/defaults.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::{HashMap, HashSet};

use api_models::{enums, payment_methods::RequiredFieldInfo};
use common_utils::id_type;

#[cfg(feature = "payouts")]
pub mod payout_required_fields;
Expand Down Expand Up @@ -138,6 +139,17 @@ impl Default for super::settings::KvConfig {
}
}

impl Default for super::settings::GlobalTenant {
fn default() -> Self {
Self {
tenant_id: id_type::TenantId::get_default_global_tenant_id(),
schema: String::from("global"),
redis_key_prefix: String::from("global"),
clickhouse_database: String::from("global"),
}
}
}

#[allow(clippy::derivable_impls)]
impl Default for super::settings::ApiKeys {
fn default() -> Self {
Expand Down
6 changes: 4 additions & 2 deletions crates/router/src/configs/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub struct Platform {
pub enabled: bool,
}

#[derive(Debug, Deserialize, Clone, Default)]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Multitenancy {
pub tenants: TenantConfig,
pub enabled: bool,
Expand Down Expand Up @@ -195,8 +195,10 @@ impl storage_impl::config::TenantConfig for Tenant {
}
}

#[derive(Debug, Deserialize, Clone, Default)]
#[derive(Debug, Deserialize, Clone)]
pub struct GlobalTenant {
#[serde(default = "id_type::TenantId::get_default_global_tenant_id")]
pub tenant_id: id_type::TenantId,
pub schema: String,
pub redis_key_prefix: String,
pub clickhouse_database: String,
Expand Down
2 changes: 2 additions & 0 deletions crates/router/src/types/domain/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ impl From<&crate::SessionState> for KeyManagerState {
fn from(state: &crate::SessionState) -> Self {
let conf = state.conf.key_manager.get_inner();
Self {
global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
enabled: conf.enabled,
url: conf.url.clone(),
client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout,
Expand Down
2 changes: 1 addition & 1 deletion loadtest/config/development.toml
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ keys = "accept-language,user-agent,x-profile-id"

[multitenancy]
enabled = false
global_tenant = { schema = "public", redis_key_prefix = "" }
global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "" }

[multitenancy.tenants.public]
base_url = "http://localhost:8080"
Expand Down

0 comments on commit 7901302

Please sign in to comment.