#![deny(clippy::unwrap_used, clippy::expect_used)]
use alloc::string::ToString;
use alloc::vec::Vec;
use base64::Engine;
use crate::core::VerifyOptions;
use crate::core::crypto::{
RsaSha256Check, check_rsa_pkcs1v15_sha256, extract_rsa_pubkey_from_x509,
};
use crate::core::error::VerifyError;
use crate::core::headers::HeaderMap;
use crate::core::options::VerifyingKeyMaterial;
use crate::core::replay::{check_replay, parse_rfc3339_timestamp};
use crate::core::secret::Secret;
pub(crate) const TRANSMISSION_ID_HEADER: &str = "PayPal-Transmission-Id";
pub(crate) const TRANSMISSION_TIME_HEADER: &str = "PayPal-Transmission-Time";
pub(crate) const TRANSMISSION_SIG_HEADER: &str = "PayPal-Transmission-Sig";
pub(crate) const CERT_URL_HEADER: &str = "PayPal-Cert-Url";
pub(crate) const AUTH_ALGO_HEADER: &str = "PayPal-Auth-Algo";
const EXPECTED_AUTH_ALGO: &str = "SHA256withRSA";
pub(crate) fn verify(
headers: &dyn HeaderMap,
raw_body: &[u8],
_secret: &Secret,
options: &VerifyOptions,
) -> Result<(), VerifyError> {
let transmission_id =
headers
.get(TRANSMISSION_ID_HEADER)
.ok_or(VerifyError::MissingHeader {
header: TRANSMISSION_ID_HEADER,
})?;
let transmission_time =
headers
.get(TRANSMISSION_TIME_HEADER)
.ok_or(VerifyError::MissingHeader {
header: TRANSMISSION_TIME_HEADER,
})?;
let signature_value =
headers
.get(TRANSMISSION_SIG_HEADER)
.ok_or(VerifyError::MissingHeader {
header: TRANSMISSION_SIG_HEADER,
})?;
let cert_url = headers
.get(CERT_URL_HEADER)
.ok_or(VerifyError::MissingHeader {
header: CERT_URL_HEADER,
})?;
let auth_algo = headers
.get(AUTH_ALGO_HEADER)
.ok_or(VerifyError::MissingHeader {
header: AUTH_ALGO_HEADER,
})?;
if transmission_id.is_empty() {
return Err(VerifyError::MalformedHeader {
header: TRANSMISSION_ID_HEADER,
reason: "header is empty",
});
}
if cert_url.is_empty() {
return Err(VerifyError::MalformedHeader {
header: CERT_URL_HEADER,
reason: "header is empty",
});
}
let webhook_id = options
.webhook_id
.as_deref()
.filter(|id| !id.is_empty())
.ok_or(VerifyError::MissingContext {
reason: "PayPal requires VerifyOptions::webhook_id",
})?;
let verifying_key = verifying_key(options)?;
check_auth_algo(auth_algo)?;
let provided_signature = parse_signature(signature_value)?;
let timestamp = parse_rfc3339_timestamp(TRANSMISSION_TIME_HEADER, transmission_time)?;
let crc = crate::core::crypto::crc32_body(raw_body);
let mut message = Vec::with_capacity(
transmission_id.len() + transmission_time.len() + webhook_id.len() + 16 + 3,
);
message.extend_from_slice(transmission_id.as_bytes());
message.push(b'|');
message.extend_from_slice(transmission_time.as_bytes());
message.push(b'|');
message.extend_from_slice(webhook_id.as_bytes());
message.push(b'|');
message.extend_from_slice(crc.to_string().as_bytes());
match check_rsa_pkcs1v15_sha256(&verifying_key, &message, &provided_signature) {
RsaSha256Check::Verified => {}
RsaSha256Check::BadSignature => {
return Err(VerifyError::BadEncoding {
reason: "signature is not a valid RSASSA-PKCS1-v1_5 signature",
});
}
RsaSha256Check::Mismatch => return Err(VerifyError::SignatureMismatch),
}
check_replay(timestamp, options)
}
fn check_auth_algo(value: &str) -> Result<(), VerifyError> {
if value.is_empty() {
return Err(VerifyError::MalformedHeader {
header: AUTH_ALGO_HEADER,
reason: "header is empty",
});
}
if !value.eq_ignore_ascii_case(EXPECTED_AUTH_ALGO) {
return Err(VerifyError::MalformedHeader {
header: AUTH_ALGO_HEADER,
reason: "unsupported auth algorithm (expected SHA256withRSA)",
});
}
Ok(())
}
fn verifying_key(options: &VerifyOptions) -> Result<rsa::RsaPublicKey, VerifyError> {
let material = options
.verifying_material
.as_ref()
.ok_or(VerifyError::MissingContext {
reason: "PayPal requires VerifyOptions::verifying_material",
})?;
match material {
VerifyingKeyMaterial::X509Certificate(cert_bytes) => {
extract_rsa_pubkey_from_x509(cert_bytes)
}
VerifyingKeyMaterial::EcdsaP256PublicKey(_) => Err(VerifyError::InvalidSecret {
reason: "verifying_material must be X509Certificate for PayPal",
}),
}
}
fn parse_signature(value: &str) -> Result<Vec<u8>, VerifyError> {
if value.is_empty() {
return Err(VerifyError::MalformedHeader {
header: TRANSMISSION_SIG_HEADER,
reason: "header is empty",
});
}
base64::engine::general_purpose::STANDARD
.decode(value.as_bytes())
.map_err(|_| VerifyError::BadEncoding {
reason: "signature is not valid standard base64",
})
}
#[cfg(test)]
mod tests {
use super::{
AUTH_ALGO_HEADER, CERT_URL_HEADER, TRANSMISSION_ID_HEADER, TRANSMISSION_SIG_HEADER,
TRANSMISSION_TIME_HEADER,
};
use crate::core::error::VerifyError;
use crate::core::options::{VerifyOptions, VerifyingKeyMaterial};
use crate::core::secret::Secret;
use crate::test_helpers::clocked_at;
use crate::verify;
use alloc::vec;
use base64::Engine;
use std::time::Duration;
const TRANSMISSION_ID: &str = "db49fb10-1343-11ef-ac58-e32457403f67";
const TRANSMISSION_TIME: &str = "2024-05-16T05:19:23Z";
const TRANSMISSION_TIME_UNIX: u64 = 1_715_836_763;
const WEBHOOK_ID: &str = "0NH55953DH663215D";
const CERT_URL: &str = "https://example.invalid/cert-url";
const SIGNATURE_B64: &str = "aGYe/s6lwrASh2zyTRIAz8Edo705ezMKekirejT08ev3VXdWAkq4JWADiNPUGelx5qrEKxC7mPIHmAwQ5hOT6unhY9n33M/DbXTKGsuITPdXRA7qYVmc2wsIp68BpzB6pC6+5vt/YLQvflsrwrutGa0KyZc5FinuYNN8pTNomv4uiygasWqfnDyKViKQPNZecowag6tY/9pj7+bgBu/joBpYUq0+cQxfGqNnlvywBJ7HCOf4edeTIvM/c1CvvAHGtNTU54kLjWGue640twn6iXPL8tnaABZ8Fr9m0z87v8oY0vBobERV0Yu8thUToKhvQEFF26Rckqy07VVddg1CmA==";
const CERT_PEM: &[u8] = include_bytes!("../../tests/data/paypal_test_cert.pem");
const OTHER_CERT_PEM: &[u8] = include_bytes!("../../tests/data/paypal_other_cert.pem");
const BODY: &[u8] = include_bytes!("../../tests/data/paypal_docs_body.json");
const CRC32_DECIMAL: u32 = 1_529_064_350;
const HEADERS: [(&str, &str); 5] = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
fn vector_options() -> VerifyOptions {
clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()))
}
fn verify_vector_with(
options: VerifyOptions,
headers: &[(&str, &str)],
) -> Result<(), VerifyError> {
let owned: Vec<(String, String)> = headers
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect();
verify(
crate::Provider::PayPal,
&owned,
BODY,
&Secret::new("unused"),
options,
)
}
#[test]
fn vector_verifies() {
assert_eq!(verify_vector_with(vector_options(), &HEADERS), Ok(()));
}
#[test]
fn secret_argument_is_ignored() {
let secret = Secret::new("");
let owned: Vec<(String, String)> = HEADERS
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect();
assert_eq!(
verify(
crate::Provider::PayPal,
&owned,
BODY,
&secret,
vector_options()
),
Ok(())
);
}
#[test]
fn header_names_are_case_insensitive() {
let lowercase: [(&str, &str); 5] = [
("paypal-transmission-id", TRANSMISSION_ID),
("paypal-transmission-time", TRANSMISSION_TIME),
("paypal-transmission-sig", SIGNATURE_B64),
("paypal-cert-url", CERT_URL),
("paypal-auth-algo", "SHA256withRSA"),
];
assert_eq!(verify_vector_with(vector_options(), &lowercase), Ok(()));
}
#[test]
fn negative_flipped_signature_byte_fails() {
let mut sig = match base64::engine::general_purpose::STANDARD.decode(SIGNATURE_B64) {
Ok(bytes) => bytes,
Err(_) => panic!("test-vector base64 must decode"),
};
sig[0] ^= 0x01;
let tampered = base64::engine::general_purpose::STANDARD.encode(sig);
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, tampered.as_str()),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn negative_wrong_certificate_fails() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(
OTHER_CERT_PEM.to_vec(),
));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn negative_wrong_webhook_id_fails() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id("A-DIFFERENT-WEBHOOK-ID")
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_body_fails() {
let mut body = BODY.to_vec();
let idx = body
.windows(4)
.position(|w| w == b"\"id\"")
.unwrap_or_else(|| panic!("fixture body must contain a bare id key"))
+ 2;
body[idx] = body[idx].to_ascii_uppercase();
assert_ne!(body, BODY);
let owned: Vec<(String, String)> = HEADERS
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect();
assert_eq!(
verify(
crate::Provider::PayPal,
&owned,
&body,
&Secret::new("unused"),
vector_options(),
),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_transmission_id_fails() {
let headers = [
(
TRANSMISSION_ID_HEADER,
"00000000-0000-0000-0000-000000000000",
),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_transmission_time_fails_signature_check() {
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, "2024-05-16T05:19:24Z"),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn replay_old_transmission_time_out_of_tolerance() {
let options = clocked_at(TRANSMISSION_TIME_UNIX + 301, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::TimestampOutOfTolerance {
skew: Duration::from_secs(301),
max_age: Duration::from_secs(300),
})
);
}
#[test]
fn replay_future_transmission_time_out_of_tolerance() {
let options = clocked_at(TRANSMISSION_TIME_UNIX - 301, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::TimestampOutOfTolerance {
skew: Duration::from_secs(301),
max_age: Duration::from_secs(300),
})
);
}
#[test]
fn replay_within_tolerance_verifies_at_window_edges() {
for now in [TRANSMISSION_TIME_UNIX - 300, TRANSMISSION_TIME_UNIX + 300] {
let options = clocked_at(now, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(verify_vector_with(options, &HEADERS), Ok(()), "now = {now}");
}
}
#[test]
fn disabled_max_age_accepts_stale_transmission_time() {
let options = clocked_at(TRANSMISSION_TIME_UNIX + 86_400 * 365, None)
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(verify_vector_with(options, &HEADERS), Ok(()));
}
#[test]
fn missing_headers_error_distinctly() {
for (missing, expected) in [
(
TRANSMISSION_ID_HEADER,
VerifyError::MissingHeader {
header: TRANSMISSION_ID_HEADER,
},
),
(
TRANSMISSION_TIME_HEADER,
VerifyError::MissingHeader {
header: TRANSMISSION_TIME_HEADER,
},
),
(
TRANSMISSION_SIG_HEADER,
VerifyError::MissingHeader {
header: TRANSMISSION_SIG_HEADER,
},
),
(
CERT_URL_HEADER,
VerifyError::MissingHeader {
header: CERT_URL_HEADER,
},
),
(
AUTH_ALGO_HEADER,
VerifyError::MissingHeader {
header: AUTH_ALGO_HEADER,
},
),
] {
let headers: Vec<(&str, &str)> = HEADERS
.iter()
.copied()
.filter(|(name, _)| *name != missing)
.collect();
assert_eq!(
verify_vector_with(vector_options(), &headers),
Err(expected),
"missing {missing}"
);
}
}
#[test]
fn malformed_signature_header_errors_distinctly() {
let cases: Vec<(&str, Result<(), VerifyError>)> = vec![
(
"",
Err(VerifyError::MalformedHeader {
header: TRANSMISSION_SIG_HEADER,
reason: "header is empty",
}),
),
(
"****not base64****",
Err(VerifyError::BadEncoding {
reason: "signature is not valid standard base64",
}),
),
(
"QUJDRA",
Err(VerifyError::BadEncoding {
reason: "signature is not valid standard base64",
}),
),
(
"3q2+7w==",
Err(VerifyError::BadEncoding {
reason: "signature is not a valid RSASSA-PKCS1-v1_5 signature",
}),
),
];
for (value, expected) in cases {
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, value),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
expected,
"input: {value:?}"
);
}
}
#[test]
fn malformed_transmission_time_header_errors_distinctly() {
let malformed_time = Err(VerifyError::MalformedHeader {
header: TRANSMISSION_TIME_HEADER,
reason: "timestamp is not a valid RFC 3339 timestamp",
});
let cases: Vec<(&str, Result<(), VerifyError>)> = vec![
("", malformed_time),
("not-a-timestamp", malformed_time),
("1715836763", malformed_time),
("2024-05-16T25:19:23Z", malformed_time),
("2024-05-16T05:19:23+25:00", malformed_time),
];
for (value, expected) in cases {
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, value),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
expected,
"input: {value:?}"
);
}
}
#[test]
fn malformed_transmission_id_header_errors_distinctly() {
let empty = Err(VerifyError::MalformedHeader {
header: TRANSMISSION_ID_HEADER,
reason: "header is empty",
});
let cases: Vec<(&str, Result<(), VerifyError>)> = vec![
("", empty),
(
"***not-a-transmission-id***",
Err(VerifyError::SignatureMismatch),
),
];
for (value, expected) in cases {
let headers = [
(TRANSMISSION_ID_HEADER, value),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
expected,
"input: {value:?}"
);
}
}
#[test]
fn malformed_cert_url_header_errors_distinctly() {
let empty = Err(VerifyError::MalformedHeader {
header: CERT_URL_HEADER,
reason: "header is empty",
});
let cases: Vec<(&str, Result<(), VerifyError>)> = vec![
("", empty),
("***not-a-url***", Ok(())),
];
for (value, expected) in cases {
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, value),
(AUTH_ALGO_HEADER, "SHA256withRSA"),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
expected,
"input: {value:?}"
);
}
}
#[test]
fn malformed_auth_algo_header_errors_distinctly() {
let cases: Vec<(&str, Result<(), VerifyError>)> = vec![
(
"",
Err(VerifyError::MalformedHeader {
header: AUTH_ALGO_HEADER,
reason: "header is empty",
}),
),
(
"SHA1withRSA",
Err(VerifyError::MalformedHeader {
header: AUTH_ALGO_HEADER,
reason: "unsupported auth algorithm (expected SHA256withRSA)",
}),
),
(
"garbage-value",
Err(VerifyError::MalformedHeader {
header: AUTH_ALGO_HEADER,
reason: "unsupported auth algorithm (expected SHA256withRSA)",
}),
),
("sha256withrsa", Ok(())),
];
for (value, expected) in cases {
let headers = [
(TRANSMISSION_ID_HEADER, TRANSMISSION_ID),
(TRANSMISSION_TIME_HEADER, TRANSMISSION_TIME),
(TRANSMISSION_SIG_HEADER, SIGNATURE_B64),
(CERT_URL_HEADER, CERT_URL),
(AUTH_ALGO_HEADER, value),
];
assert_eq!(
verify_vector_with(vector_options(), &headers),
expected,
"input: {value:?}"
);
}
}
#[test]
fn missing_webhook_id_errors_as_missing_context() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::MissingContext {
reason: "PayPal requires VerifyOptions::webhook_id"
})
);
}
#[test]
fn empty_webhook_id_errors_as_missing_context() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(CERT_PEM.to_vec()))
.with_webhook_id("");
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::MissingContext {
reason: "PayPal requires VerifyOptions::webhook_id"
})
);
}
#[test]
fn missing_verifying_material_errors_as_missing_context() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID);
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::MissingContext {
reason: "PayPal requires VerifyOptions::verifying_material"
})
);
}
#[test]
fn wrong_material_variant_errors_as_invalid_secret() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::EcdsaP256PublicKey(vec![
0x30, 0x59, 0x13,
]));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::InvalidSecret {
reason: "verifying_material must be X509Certificate for PayPal"
})
);
}
#[test]
fn malformed_certificate_errors_as_invalid_secret() {
let options = clocked_at(TRANSMISSION_TIME_UNIX, Some(Duration::from_secs(300)))
.with_webhook_id(WEBHOOK_ID)
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(
b"definitely not a certificate".to_vec(),
));
assert_eq!(
verify_vector_with(options, &HEADERS),
Err(VerifyError::InvalidSecret {
reason: "certificate is not a valid X.509 certificate"
})
);
}
#[test]
fn signed_string_uses_decimal_crc_of_raw_body() {
assert_eq!(crate::core::crypto::crc32_body(BODY), CRC32_DECIMAL);
}
}