#![deny(clippy::unwrap_used, clippy::expect_used)]
use alloc::vec::Vec;
use crate::core::VerifyOptions;
use crate::core::crypto::verify_hmac_sha256;
use crate::core::error::VerifyError;
use crate::core::headers::HeaderMap;
use crate::core::secret::Secret;
use base64::Engine;
pub(crate) const SIGNATURE_HEADER: &str = "X-Square-HmacSha256-Signature";
const SIGNATURE_LEN_BYTES: usize = 32;
pub(crate) fn verify(
headers: &dyn HeaderMap,
raw_body: &[u8],
secret: &Secret,
options: &VerifyOptions,
) -> Result<(), VerifyError> {
let value = headers
.get(SIGNATURE_HEADER)
.ok_or(VerifyError::MissingHeader {
header: SIGNATURE_HEADER,
})?;
let notification_url = options
.request_url
.as_deref()
.filter(|url| !url.is_empty())
.ok_or(VerifyError::MissingContext {
reason: "Square signs the notification URL; set VerifyOptions::request_url",
})?;
let provided = parse_signature(value)?;
let key = signing_key(secret.as_bytes())?;
let mut signed_string = Vec::with_capacity(notification_url.len() + raw_body.len());
signed_string.extend_from_slice(notification_url.as_bytes());
signed_string.extend_from_slice(raw_body);
if verify_hmac_sha256(key, &signed_string, &provided) {
Ok(())
} else {
Err(VerifyError::SignatureMismatch)
}
}
fn signing_key(secret: &[u8]) -> Result<&[u8], VerifyError> {
if secret.is_empty() {
return Err(VerifyError::InvalidSecret {
reason: "signature key is empty",
});
}
Ok(secret)
}
fn parse_signature(value: &str) -> Result<Vec<u8>, VerifyError> {
if value.is_empty() {
return Err(VerifyError::MalformedHeader {
header: SIGNATURE_HEADER,
reason: "header is empty",
});
}
let bytes = base64::engine::general_purpose::STANDARD
.decode(value)
.map_err(|_| VerifyError::BadEncoding {
reason: "signature is not valid standard base64",
})?;
if bytes.len() != SIGNATURE_LEN_BYTES {
return Err(VerifyError::BadEncoding {
reason: "signature does not decode to 32 bytes",
});
}
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::SIGNATURE_HEADER;
use crate::core::error::VerifyError;
use crate::core::options::VerifyOptions;
use crate::core::secret::Secret;
use crate::verify;
use std::time::Duration;
const OFFICIAL_URL: &str = "https://example.com/webhook";
const OFFICIAL_KEY: &str = "asdf1234";
const OFFICIAL_BODY: &[u8] = br#"{"hello":"world"}"#;
const OFFICIAL_SIGNATURE: &str = "2kRE5qRU2tR+tBGlDwMEw2avJ7QM4ikPYD/PJ3bd9Og=";
const EMPTY_BODY_SIGNATURE: &str = "ynbHtv7mmd+3xVChP9MsT9iQ4vULFz7Gx8Sq9SZy4QM=";
const UNICODE_BODY_SIGNATURE: &str = "kRB6TPxZKvkPG92MGNd+qTSjhIhhb1KBL3mc/6moa4A=";
fn square_headers(signature: &str) -> Vec<(String, String)> {
vec![(SIGNATURE_HEADER.to_string(), signature.to_string())]
}
fn verify_with(body: &[u8], signature: &str) -> Result<(), VerifyError> {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
verify(
crate::Provider::Square,
&square_headers(signature),
body,
&Secret::new(OFFICIAL_KEY),
options,
)
}
#[test]
fn official_vector_verifies() {
assert_eq!(verify_with(OFFICIAL_BODY, OFFICIAL_SIGNATURE), Ok(()));
}
#[test]
fn boundary_bodies_verify() {
assert_eq!(verify_with(b"", EMPTY_BODY_SIGNATURE), Ok(()));
assert_eq!(
verify_with("héllo, 🦀 world!".as_bytes(), UNICODE_BODY_SIGNATURE),
Ok(())
);
}
#[test]
fn header_name_lookup_is_case_insensitive() {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
let result = verify(
crate::Provider::Square,
&[("x-square-hmacsha256-signature", OFFICIAL_SIGNATURE)],
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options,
);
assert_eq!(result, Ok(()));
}
#[test]
fn negative_flipped_signature_byte_fails() {
let flipped = format!("{}B{}", &OFFICIAL_SIGNATURE[..3], &OFFICIAL_SIGNATURE[4..]);
assert_ne!(flipped, OFFICIAL_SIGNATURE);
assert_eq!(
verify_with(OFFICIAL_BODY, &flipped),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_body_fails() {
assert_eq!(
verify_with(br#"{"hello":"w0rld"}"#, OFFICIAL_SIGNATURE),
Err(VerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_notification_url_fails() {
let options = VerifyOptions::default().with_request_url("https://example.com/webhook/");
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options,
);
assert_eq!(result, Err(VerifyError::SignatureMismatch));
}
#[test]
fn wrong_secret_fails() {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new("another-subscription-key"),
options,
);
assert_eq!(result, Err(VerifyError::SignatureMismatch));
}
#[test]
fn empty_secret_fails_closed_as_invalid_secret() {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new(""),
options,
);
assert_eq!(
result,
Err(VerifyError::InvalidSecret {
reason: "signature key is empty"
})
);
}
#[test]
fn max_age_has_no_effect_for_square() {
let options = VerifyOptions {
max_age: Some(Duration::ZERO),
request_url: Some(OFFICIAL_URL.to_string()),
..VerifyOptions::default()
};
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options,
);
assert_eq!(result, Ok(()));
}
#[test]
fn missing_request_url_fails_closed_as_missing_context() {
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
VerifyOptions::default(),
);
assert_eq!(
result,
Err(VerifyError::MissingContext {
reason: "Square signs the notification URL; set VerifyOptions::request_url"
})
);
let result = verify(
crate::Provider::Square,
&square_headers(OFFICIAL_SIGNATURE),
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
VerifyOptions::default().with_request_url(""),
);
assert!(matches!(result, Err(VerifyError::MissingContext { .. })));
}
#[test]
fn missing_header_errors_distinctly() {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
let result = verify(
crate::Provider::Square,
&Vec::<(String, String)>::new(),
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options,
);
assert_eq!(
result,
Err(VerifyError::MissingHeader {
header: SIGNATURE_HEADER
})
);
}
#[test]
fn malformed_and_bad_encoding_errors_are_distinct() {
let options = VerifyOptions::default().with_request_url(OFFICIAL_URL);
let cases: &[(&str, VerifyError)] = &[
(
"",
VerifyError::MalformedHeader {
header: SIGNATURE_HEADER,
reason: "header is empty",
},
),
(
"not base64!!",
VerifyError::BadEncoding {
reason: "signature is not valid standard base64",
},
),
(
"2jmj7l5rSw0yVb/vlWAYkK/YBwk=",
VerifyError::BadEncoding {
reason: "signature does not decode to 32 bytes",
},
),
];
for &(value, expected) in cases {
let result = verify(
crate::Provider::Square,
&[(SIGNATURE_HEADER, value)],
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options.clone(),
);
assert_eq!(result, Err(expected), "input: {value:?}");
}
let value = OFFICIAL_SIGNATURE.trim_end_matches('=');
let result = verify(
crate::Provider::Square,
&[(SIGNATURE_HEADER, value)],
OFFICIAL_BODY,
&Secret::new(OFFICIAL_KEY),
options.clone(),
);
match result {
Err(VerifyError::BadEncoding { .. }) => {}
other => panic!("expected BadEncoding for {value:?}, got {other:?}"),
}
}
}