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(payment_link): added csp nounce for foreign script injection prevention (#15071)

Sahkal Poddar69c4464e228f
diff --git a/crates/common_utils/src/link_utils.rs b/crates/common_utils/src/link_utils.rs
index 84e276d2a0..4354dc5a13 100644
--- a/crates/common_utils/src/link_utils.rs
+++ b/crates/common_utils/src/link_utils.rs
@@ -23,7 +23,7 @@ use utoipa::ToSchema;
#[cfg(feature = "diesel")]
use crate::errors::ParsingError;
-use crate::{consts, id_type, types::MinorUnit};
+use crate::{consts, crypto, id_type, types::MinorUnit};
#[derive(Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, ToSchema)]
#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression))]
@@ -263,6 +263,29 @@ pub fn validate_wildcard_domain(domain: &str) -> bool {
.unwrap_or(false)
}
+/// Domain type for the Content-Security-Policy nonce that link pages generate per response
+#[derive(Debug)]
+pub struct CspNonce(Secret<String>);
+
+impl CspNonce {
+ /// Generate a new nonce from a cryptographically secure source
+ pub fn generate() -> Self {
+ Self(Secret::new(
+ crypto::generate_cryptographically_secure_random_string(32),
+ ))
+ }
+
+ /// Get the nonce value to place in the CSP header
+ pub fn peek(&self) -> &str {
+ self.0.peek()
+ }
+
+ /// Get the `nonce` attribute to place on the page's script and preload tags
+ pub fn get_html_attribute(&self) -> String {
+ format!(r#"nonce="{}""#, self.peek())
+ }
+}
+
#[cfg(test)]
mod domain_tests {
use regex::Regex;
diff --git a/crates/payment_link/src/template_renderer.rs b/crates/payment_link/src/template_renderer.rs
index 671cb14b11..7d5415f3ee 100644
--- a/crates/payment_link/src/template_renderer.rs
+++ b/crates/payment_link/src/template_renderer.rs
@@ -1,3 +1,4 @@
+use common_utils::link_utils::CspNonce;
use error_stack::{Result, ResultExt};
use tera::{Context, Tera};
@@ -13,8 +14,9 @@ pub enum PaymentLinkError {
pub fn build_payment_link_html(
payment_link_data: PaymentLinkFormData,
+ csp_nonce: Option<&CspNonce>,
) -> Result<String, PaymentLinkError> {
- let (tera, mut context) = build_payment_link_template(payment_link_data)
+ let (tera, mut context) = build_payment_link_template(payment_link_data, csp_nonce)
.change_context(PaymentLinkError::TemplateBuildError)
.attach_printable("Failed to build payment link's HTML template")?;
@@ -31,8 +33,9 @@ pub fn build_payment_link_html(
pub fn build_secure_payment_link_html(
payment_link_data: PaymentLinkFormData,
+ csp_nonce: Option<&CspNonce>,
) -> Result<String, PaymentLinkError> {
- let (tera, mut context) = build_payment_link_template(payment_link_data)
+ let (tera, mut context) = build_payment_link_template(payment_link_data, csp_nonce)
.change_context(PaymentLinkError::TemplateBuildError)
.attach_printable("Failed to build payment link's HTML template")?;
@@ -49,6 +52,7 @@ pub fn build_secure_payment_link_html(
fn build_payment_link_template(
payment_link_data: PaymentLinkFormData,
+ csp_nonce: Option<&CspNonce>,
) -> Result<(Tera, Context), PaymentLinkError> {
let mut tera = Tera::default();
@@ -107,14 +111,18 @@ fn build_payment_link_template(
.to_string();
let _ = tera.add_raw_template("payment_link", &html_template);
+ let csp_nonce_attribute = csp_nonce
+ .map(CspNonce::get_html_attribute)
+ .unwrap_or_default();
context.insert("rendered_meta_tag_html", &payment_link_data.html_meta_tags);
+ context.insert("csp_nonce_attribute", &csp_nonce_attribute);
context.insert(
"preload_link_tags",
- &get_preload_link_html_template(&payment_link_data.sdk_url),
+ &get_preload_link_html_template(&payment_link_data.sdk_url, &csp_nonce_attribute),
);
context.insert(
"hyperloader_sdk_link",
- &get_hyper_loader_sdk(&payment_link_data.sdk_url),
+ &get_hyper_loader_sdk(&payment_link_data.sdk_url, &csp_nonce_attribute),
);
context.insert("locale_template", &locale_template);
context.insert("rendered_css", &rendered_css);
@@ -132,19 +140,25 @@ fn build_payment_link_template(
Ok((tera, context))
}
-fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String {
- format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
+fn get_hyper_loader_sdk(sdk_url: &url::Url, csp_nonce_attribute: &str) -> String {
+ // The CSP blocks inline `onload` handlers, so the SDK is initialised from a
+ // nonced script, which the parser runs only after the loader has executed.
+ format!(
+ r#"<script {csp_nonce_attribute} src="{sdk_url}"></script>
+ <script {csp_nonce_attribute}>if (window.Hyper) {{ initializeSDK(); }}</script>"#
+ )
}
-fn get_preload_link_html_template(sdk_url: &url::Url) -> String {
+fn get_preload_link_html_template(sdk_url: &url::Url, csp_nonce_attribute: &str) -> String {
format!(
r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style">
- <link rel="preload" href="{sdk_url}" as="script">"#,
+ <link rel="preload" href="{sdk_url}" as="script" {csp_nonce_attribute}>"#,
)
}
pub fn get_payment_link_status(
payment_link_data: PaymentLinkStatusData,
+ csp_nonce: Option<&CspNonce>,
) -> Result<String, PaymentLinkError> {
let mut tera = Tera::default();
@@ -204,6 +218,12 @@ pub fn get_payment_link_status(
context.insert("rendered_js", &rendered_js);
context.insert("logging_template", &logging_template);
+ context.insert(
+ "csp_nonce_attribute",
+ &csp_nonce
+ .map(CspNonce::get_html_attribute)
+ .unwrap_or_default(),
+ );
tera.render("payment_link_status", &context)
.change_context(PaymentLinkError::TemplateRenderError)
diff --git a/crates/payment_link/src/wasm.rs b/crates/payment_link/src/wasm.rs
index 11c2d189a5..99c8974c26 100644
--- a/crates/payment_link/src/wasm.rs
+++ b/crates/payment_link/src/wasm.rs
@@ -82,7 +82,7 @@ pub fn generate_payment_link_preview_impl(config_json: &str) -> Result<String, S
redirection_log_endpoint: None,
};
- build_payment_link_html(payment_link_form_data)
+ build_payment_link_html(payment_link_form_data, None)
.map_err(|e| format!("Failed to build payment link HTML: {:?}", e))
}
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index 1a024e24c3..a411e86000 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -1,7 +1,10 @@
use std::{future::Future, sync::Arc, time::Instant};
use actix_web::{HttpRequest, HttpResponse, Responder};
-use common_utils::errors::{CustomResult, ErrorSwitch};
+use common_utils::{
+ errors::{CustomResult, ErrorSwitch},
+ link_utils::CspNonce,
+};
use router_env::{instrument, tracing, Tag};
use serde::Serialize;
@@ -145,6 +148,7 @@ where
match services::generic_link_response::build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
+ &CspNonce::generate(),
) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => {
@@ -154,9 +158,10 @@ where
}
Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
+ let csp_nonce = CspNonce::generate();
match *boxed_payment_link_data {
api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
- match api::build_payment_link_html(payment_link_data) {
+ match api::build_payment_link_html(payment_link_data, &csp_nonce) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => api::http_response_err(
r#"{
@@ -168,7 +173,7 @@ where
}
}
api::PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
- match api::get_payment_link_status(payment_link_data) {
+ match api::get_payment_link_status(payment_link_data, &csp_nonce) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => api::http_response_err(
r#"{
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
index 3871b236c9..6aa0d52ab9 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.html
@@ -202,10 +202,7 @@
</div>
<div class="hyper-checkout-image-header">
<div id="hyper-checkout-merchant-image"></div>
- <div
- id="hyper-checkout-cart-image"
- onclick="viewCartInMobileView()"
- >
+ <div id="hyper-checkout-cart-image">
<svg
width="30"
height="30"
@@ -258,7 +255,6 @@
width="25"
height="25"
class="cart-close"
- onclick="hideCartInMobileView()"
>
<use
xlink:href="#cart-close"
@@ -301,8 +297,9 @@
</div>
</div>
</div>
- <script>
+ <script {{csp_nonce_attribute}}>
window.__REDIRECTION_LOG_ENDPOINT = '{{redirection_log_endpoint}}';
+ window.__REDIRECTION_LOG_MESSAGE_ORIGINS = ['{{sdk_origin}}'];
{{logging_template}}
{{locale_template}}
{{rendered_js}}
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
index 66cb33fe74..3c5e225e99 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js
@@ -321,6 +321,7 @@ function isObject(val) {
* Use - add event listeners for changing UI on
* - Screen resize
* - Form inputs
+ * - Opening and closing the cart in mobile view
* @param {PaymentDetails} paymentDetails
*/
function initializeEventListeners(paymentDetails) {
@@ -368,6 +369,12 @@ function initializeEventListeners(paymentDetails) {
if (hyperCheckoutCartImageNode instanceof HTMLDivElement) {
hyperCheckoutCartImageNode.style.backgroundColor = contrastingTone;
+ hyperCheckoutCartImageNode.addEventListener("click", viewCartInMobileView);
+ }
+
+ var cartCloseNode = document.querySelector(".cart-close");
+ if (cartCloseNode instanceof SVGSVGElement) {
+ cartCloseNode.addEventListener("click", hideCartInMobileView);
}
if (window.innerWidth <= 1199) {
diff --git a/crates/router/src/core/payment_link/payment_link_status/status.html b/crates/router/src/core/payment_link/payment_link_status/status.html
index cb3cd9e2e7..5e57291f84 100644
--- a/crates/router/src/core/payment_link/payment_link_status/status.html
+++ b/crates/router/src/core/payment_link/payment_link_status/status.html
@@ -10,14 +10,15 @@
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800"
/>
- <script>
+ <script {{csp_nonce_attribute}}>
window.__REDIRECTION_LOG_ENDPOINT = '{{redirection_log_endpoint}}';
+ window.__REDIRECTION_LOG_MESSAGE_ORIGINS = [];
{{logging_template}}
{{locale_template}}
{{ rendered_js }}
</script>
</head>
- <body onload="boot()" class="hidden">
+ <body class="hidden">
<div>
<div class="hyper-checkout-status-wrap">
<div id="hyper-checkout-status-header"></div>
diff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.js
index e1737f5596..ecadc546d3 100644
--- a/crates/router/src/core/payment_link/payment_link_status/status.js
+++ b/crates/router/src/core/payment_link/payment_link_status/status.js
@@ -160,6 +160,7 @@ function boot() {
initializeEventListeners(paymentDetails);
}
}
+window.addEventListener("load", boot);
/**
* Trigger - on boot
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 7cf11fe15d..af47009cac 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -22,13 +22,14 @@ pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
+ link_utils::CspNonce,
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types;
pub use hyperswitch_domain_models::{
api::{
ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData,
- GenericLinks, PaymentLinkAction, RedirectionFormData, WebhookResponse,
+ GenericLinks, GenericLinksData, PaymentLinkAction, RedirectionFormData, WebhookResponse,
},
payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
@@ -514,22 +515,32 @@ where
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
+ let is_secure_payment_link = matches!(
+ boxed_generic_link_data.data,
+ GenericLinksData::SecurePaymentLink(_)
+ );
+ let csp_nonce = CspNonce::generate();
match build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
+ &csp_nonce,
) {
Ok(rendered_html) => {
- let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
+ let mut csp_directives = Vec::new();
+ if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
.allowed_domains
.into_iter()
.collect::<Vec<String>>()
.join(" ");
- let csp_header = format!("frame-ancestors 'self' {domains_str};");
- Some(HashSet::from([("content-security-policy", csp_header)]))
- } else {
- None
- };
+ csp_directives.push(format!("frame-ancestors 'self' {domains_str};"));
+ }
+ if is_secure_payment_link {
+ csp_directives.push(get_payment_link_csp(&csp_nonce));
+ }
+ let headers = (!csp_directives.is_empty()).then(|| {
+ HashSet::from([("content-security-policy", csp_directives.join(" "))])
+ });
http_response_html_data(rendered_html, headers)
}
Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")),
@@ -537,14 +548,12 @@ where
}
Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
+ let csp_nonce = CspNonce::generate();
let mut headers = HashSet::new();
- headers.insert((
- "content-security-policy",
- "default-src 'self' http: https:; script-src 'self' 'unsafe-inline' http: https:; style-src 'self' 'unsafe-inline' http: https:; img-src * data: blob:; font-src * data:; connect-src *; frame-src *; object-src 'none';".to_string(),
- ));
+ headers.insert(("content-security-policy", get_payment_link_csp(&csp_nonce)));
match *boxed_payment_link_data {
PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
- match build_payment_link_html(payment_link_data) {
+ match build_payment_link_html(payment_link_data, &csp_nonce) {
Ok(rendered_html) => http_response_html_data(rendered_html, Some(headers)),
Err(_) => http_response_err(
r#"{
@@ -556,7 +565,7 @@ where
}
}
PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
- match get_payment_link_status(payment_link_data) {
+ match get_payment_link_status(payment_link_data, &csp_nonce) {
Ok(rendered_html) => http_response_html_data(rendered_html, Some(headers)),
Err(_) => http_response_err(
r#"{
@@ -1836,10 +1845,28 @@ pub fn build_redirection_form(
}
}
+/// Only nonced scripts and the scripts they load may run; `https:` is a fallback for browsers
+/// without `'strict-dynamic'`.
+fn get_payment_link_csp(csp_nonce: &CspNonce) -> String {
+ let csp_nonce = csp_nonce.peek();
+ format!(
+ "default-src 'self' https:; \
+ script-src 'nonce-{csp_nonce}' 'strict-dynamic' https:; \
+ style-src 'self' 'unsafe-inline' https:; \
+ img-src * data: blob:; \
+ font-src * data:; \
+ connect-src *; \
+ frame-src *; \
+ object-src 'none'; \
+ base-uri 'none';"
+ )
+}
+
pub fn build_payment_link_html(
payment_link_data: PaymentLinkFormData,
+ csp_nonce: &CspNonce,
) -> CustomResult<String, errors::ApiErrorResponse> {
- payment_link::build_payment_link_html(payment_link_data)
+ payment_link::build_payment_link_html(payment_link_data, Some(csp_nonce))
.map_err(|e| {
logger::error!("Failed to build payment link HTML: {:?}", e);
errors::ApiErrorResponse::InternalServerError
@@ -1849,8 +1876,9 @@ pub fn build_payment_link_html(
pub fn build_secure_payment_link_html(
payment_link_data: PaymentLinkFormData,
+ csp_nonce: &CspNonce,
) -> CustomResult<String, errors::ApiErrorResponse> {
- payment_link::build_secure_payment_link_html(payment_link_data)
+ payment_link::build_secure_payment_link_html(payment_link_data, Some(csp_nonce))
.map_err(|e| {
logger::error!("Failed to build secure payment link HTML: {:?}", e);
errors::ApiErrorResponse::InternalServerError
@@ -1860,8 +1888,9 @@ pub fn build_secure_payment_link_html(
pub fn get_payment_link_status(
payment_link_data: PaymentLinkStatusData,
+ csp_nonce: &CspNonce,
) -> CustomResult<String, errors::ApiErrorResponse> {
- payment_link::get_payment_link_status(payment_link_data)
+ payment_link::get_payment_link_status(payment_link_data, Some(csp_nonce))
.map_err(|e| {
logger::error!("Failed to get payment link status: {:?}", e);
errors::ApiErrorResponse::InternalServerError
diff --git a/crates/router/src/services/api/generic_link_response.rs b/crates/router/src/services/api/generic_link_response.rs
index d00049adf2..de93f1cb7e 100644
--- a/crates/router/src/services/api/generic_link_response.rs
+++ b/crates/router/src/services/api/generic_link_response.rs
@@ -1,4 +1,4 @@
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, link_utils::CspNonce};
use error_stack::ResultExt;
use hyperswitch_domain_models::api::{
GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData,
@@ -12,6 +12,7 @@ pub mod context;
pub fn build_generic_link_html(
boxed_generic_link_data: GenericLinksData,
locale: String,
+ csp_nonce: &CspNonce,
) -> CustomResult<String, errors::ApiErrorResponse> {
match boxed_generic_link_data {
GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data),
@@ -30,7 +31,7 @@ pub fn build_generic_link_html(
build_payout_link_status_html(&pm_collect_data, locale.as_str())
}
GenericLinksData::SecurePaymentLink(payment_link_data) => {
- build_secure_payment_link_html(payment_link_data)
+ build_secure_payment_link_html(payment_link_data, csp_nonce)
}
}
}
diff --git a/crates/router/src/services/redirection/assets/redirect_error_logs_push.js b/crates/router/src/services/redirection/assets/redirect_error_logs_push.js
index 859b1ee54c..c602c5f1cf 100644
--- a/crates/router/src/services/redirection/assets/redirect_error_logs_push.js
+++ b/crates/router/src/services/redirection/assets/redirect_error_logs_push.js
@@ -45,7 +45,18 @@ function parseRoute(url) {
: "https://app.hyperswitch.io/api/logs/redirection";
}
-
+ /*
+ * Payment-link pages set `window.__REDIRECTION_LOG_MESSAGE_ORIGINS` to the
+ * origins of the frames they embed, so a parent or opener page cannot push
+ * messages into our logs. Redirection forms leave it unset because connector
+ * frames post from origins that are not known up front.
+ */
+ function shouldLogMessage(event) {
+ const allowedOrigins = window.__REDIRECTION_LOG_MESSAGE_ORIGINS;
+ return !Array.isArray(allowedOrigins) || allowedOrigins.includes(event.origin);
+ }
+
+
async function postLog(log, urlToPost) {
try {
@@ -80,18 +91,20 @@ window.addEventListener("error", (event) => {
});
window.addEventListener("message", (event) => {
- let url = window.location.href;
- let { paymentId, merchantId, attemptId, connector } = parseRoute(url);
- let urlToPost = getEnvRoute(url);
- let log = {
- message: event.data,
- url,
- paymentId,
- merchantId,
- attemptId,
- connector,
- };
- postLog(log, urlToPost);
+ if (shouldLogMessage(event)) {
+ let url = window.location.href;
+ let { paymentId, merchantId, attemptId, connector } = parseRoute(url);
+ let urlToPost = getEnvRoute(url);
+ let log = {
+ message: event.data,
+ url,
+ paymentId,
+ merchantId,
+ attemptId,
+ connector,
+ };
+ postLog(log, urlToPost);
+ }
});
\ No newline at end of file