use std::fmt;
use crate::endpoint::Endpoint;
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub mod code {
pub const INVALID_CONFIG: i32 = 1001;
pub const VERIFY_FAILED: i32 = 1003;
pub const API: i32 = 1004;
pub const NETWORK: i32 = 1005;
pub const INVALID_RESPONSE: i32 = 1006;
pub const INVALID_PARAM: i32 = 1007;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TransportErrorKind {
Timeout,
Connect,
Redirect,
Body,
Request,
Other,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Config,
InvalidParameter,
Verification,
Provider,
Transport,
InvalidResponse,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("invalid configuration: {0}")]
Config(&'static str),
#[error("invalid parameter: {0}")]
Param(&'static str),
#[error("invalid notify: {message}")]
Notify {
message: String,
},
#[error("signature verification failed")]
VerifyFailed,
#[error("epay API error at {endpoint} (code {code}): {message}")]
Api {
endpoint: Endpoint,
code: i32,
message: String,
},
#[error("HTTP transport error ({kind:?}): {message}")]
Transport {
kind: TransportErrorKind,
message: String,
},
#[error("unexpected HTTP status {status}: {body}")]
Http {
status: u16,
body: String,
},
#[error("invalid response from {endpoint}: {message}")]
InvalidResponse {
endpoint: Endpoint,
message: String,
},
#[error("response body exceeds configured limit of {limit} bytes")]
ResponseTooLarge {
limit: usize,
},
}
impl Error {
pub fn kind(&self) -> ErrorKind {
match self {
Self::Config(_) => ErrorKind::Config,
Self::Param(_) | Self::Notify { .. } => ErrorKind::InvalidParameter,
Self::VerifyFailed => ErrorKind::Verification,
Self::Api { .. } => ErrorKind::Provider,
Self::Transport { .. } | Self::Http { .. } | Self::ResponseTooLarge { .. } => {
ErrorKind::Transport
}
Self::InvalidResponse { .. } => ErrorKind::InvalidResponse,
}
}
pub fn code(&self) -> i32 {
match self.kind() {
ErrorKind::Config => code::INVALID_CONFIG,
ErrorKind::InvalidParameter => code::INVALID_PARAM,
ErrorKind::Verification => code::VERIFY_FAILED,
ErrorKind::Provider => code::API,
ErrorKind::Transport => code::NETWORK,
ErrorKind::InvalidResponse => code::INVALID_RESPONSE,
}
}
pub fn endpoint(&self) -> Option<Endpoint> {
match self {
Self::Api { endpoint, .. } | Self::InvalidResponse { endpoint, .. } => Some(*endpoint),
_ => None,
}
}
pub fn transport_kind(&self) -> Option<TransportErrorKind> {
match self {
Self::Transport { kind, .. } => Some(*kind),
_ => None,
}
}
pub fn is_timeout(&self) -> bool {
self.transport_kind() == Some(TransportErrorKind::Timeout)
}
pub fn is_retryable(&self) -> bool {
match self {
Self::Transport { kind, .. } => {
matches!(
kind,
TransportErrorKind::Timeout | TransportErrorKind::Connect
)
}
Self::Http { status, .. } => matches!(status, 502..=504),
_ => false,
}
}
pub fn transport(kind: TransportErrorKind, message: impl fmt::Display) -> Self {
Self::Transport {
kind,
message: redact_secrets(&message.to_string()),
}
}
pub(crate) fn notify(message: impl Into<String>) -> Self {
Self::Notify {
message: redact_secrets(&message.into()),
}
}
pub(crate) fn api(endpoint: Endpoint, code: i32, message: impl Into<String>) -> Self {
Self::Api {
endpoint,
code,
message: redact_secrets(&message.into()),
}
}
pub(crate) fn invalid_response(
endpoint: Endpoint,
err: impl fmt::Display,
body: &[u8],
) -> Self {
Self::InvalidResponse {
endpoint,
message: format!("{err}: {}", body_preview(body)),
}
}
pub(crate) fn invalid_response_message(endpoint: Endpoint, message: impl Into<String>) -> Self {
Self::InvalidResponse {
endpoint,
message: redact_secrets(&message.into()),
}
}
pub fn http(status: u16, body: &[u8]) -> Self {
Self::Http {
status,
body: body_preview(body),
}
}
pub(crate) fn sanitized(self) -> Self {
match self {
Self::Transport { kind, message } => Self::Transport {
kind,
message: redact_secrets(&message),
},
Self::Http { status, body } => Self::Http {
status,
body: redact_secrets(&body),
},
Self::Api {
endpoint,
code,
message,
} => Self::Api {
endpoint,
code,
message: redact_secrets(&message),
},
Self::InvalidResponse { endpoint, message } => Self::InvalidResponse {
endpoint,
message: redact_secrets(&message),
},
Self::Notify { message } => Self::Notify {
message: redact_secrets(&message),
},
other => other,
}
}
}
impl Error {
pub const INVALID_PID: Self = Self::Config("invalid PID: must be greater than 0");
pub const INVALID_KEY: Self = Self::Config("invalid Key: must not be empty");
pub const INVALID_API_URL: Self = Self::Config("invalid API base URL");
pub const INSECURE_API_URL: Self = Self::Config(
"API base URL must use HTTPS; call allow_insecure_http(true) for a legacy HTTP gateway",
);
pub const INVALID_NOTIFY_URL: Self = Self::Param("notify_url must be an absolute HTTP(S) URL");
pub const INVALID_RETURN_URL: Self = Self::Param("return_url must be an absolute HTTP(S) URL");
pub const INSECURE_NOTIFY_URL: Self = Self::Param(
"notify_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
);
pub const INSECURE_RETURN_URL: Self = Self::Param(
"return_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
);
pub const MISSING_OUT_TRADE_NO: Self = Self::Param("out_trade_no is required");
pub const INVALID_OUT_TRADE_NO: Self =
Self::Param("out_trade_no must be 1..=64 ASCII characters from [A-Za-z0-9._|-]");
pub const MISSING_NOTIFY_URL: Self = Self::Param("notify_url is required");
pub const MISSING_NAME: Self = Self::Param("name is required");
pub const NAME_TOO_LONG: Self = Self::Param("name exceeds 255 bytes");
pub const NAME_HAS_CONTROL_CHARS: Self =
Self::Param("name must not contain control characters");
pub const SITENAME_HAS_CONTROL_CHARS: Self =
Self::Param("sitename must not contain control characters");
pub const PARAM_TOO_LONG: Self = Self::Param("param exceeds 255 bytes");
pub const SITENAME_TOO_LONG: Self = Self::Param("sitename exceeds 64 bytes");
pub const CALLBACK_URL_TOO_LONG: Self =
Self::Param("notify_url / return_url exceeds 1024 bytes");
pub const REQUEST_TOO_LARGE: Self =
Self::Param("encoded request exceeds 4096 bytes; shorten name, param or callback URLs");
pub const INVALID_PAY_TYPE: Self =
Self::Param("payment type must be 1..=32 characters from [A-Za-z0-9_-]");
pub const INVALID_DEVICE: Self =
Self::Param("device must be 1..=32 characters from [A-Za-z0-9_-]");
pub const INVALID_MONEY: Self = Self::Param("money must be greater than 0");
pub const INVALID_MONEY_PRECISION: Self =
Self::Param("money must have at most two fractional decimal places");
pub const MONEY_OUT_OF_RANGE: Self = Self::Param("money exceeds the i64 fen range");
pub const MISSING_TRADE_NO: Self =
Self::Param("exactly one of trade_no or out_trade_no is required");
pub const INVALID_TRADE_NO: Self = Self::Param("trade_no must be a non-blank ASCII identifier");
pub const MISSING_CLIENT_IP: Self = Self::Param("clientip is required by mapi.php");
pub const INVALID_CLIENT_IP: Self = Self::Param("clientip must be a valid IPv4/IPv6 address");
}
pub(crate) fn body_preview(body: &[u8]) -> String {
redact_secrets(&String::from_utf8_lossy(body))
.chars()
.take(256)
.collect()
}
pub(crate) fn redact_secrets(input: &str) -> String {
redact_form_secrets(&redact_json_secrets(input))
}
pub(crate) fn redact_json_secrets(body: &str) -> String {
let mut out = String::with_capacity(body.len());
let mut rest = body;
while let Some((idx, needle)) = find_secret_member(rest) {
let (head, tail) = rest.split_at(idx + needle.len());
out.push_str(head);
let Some(after_colon) = tail.trim_start().strip_prefix(':') else {
rest = tail;
continue;
};
let Some(value) = after_colon.trim_start().strip_prefix('"') else {
rest = tail;
continue;
};
out.push_str(":\"***\"");
rest = match json_string_end(value) {
Some(end) => &value[end + 1..],
None => "",
};
}
out.push_str(rest);
out
}
fn redact_form_secrets(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
loop {
let next = ["key=", "sign="]
.into_iter()
.filter_map(|needle| rest.find(needle).map(|idx| (idx, needle)))
.filter(|(idx, _)| {
*idx == 0
|| rest[..*idx]
.chars()
.next_back()
.is_some_and(|c| matches!(c, '?' | '&' | ' ' | '\'' | '"'))
})
.min_by_key(|(idx, _)| *idx);
let Some((idx, needle)) = next else {
out.push_str(rest);
break;
};
let value_start = idx + needle.len();
out.push_str(&rest[..value_start]);
out.push_str("***");
let value = &rest[value_start..];
let end = value
.char_indices()
.find(|(_, c)| matches!(c, '&' | ' ' | '\'' | '"' | ')' | ']'))
.map(|(idx, _)| idx)
.unwrap_or(value.len());
rest = &value[end..];
}
out
}
fn find_secret_member(s: &str) -> Option<(usize, &'static str)> {
["\"key\"", "\"sign\""]
.into_iter()
.filter_map(|needle| s.find(needle).map(|idx| (idx, needle)))
.min_by_key(|(idx, _)| *idx)
}
fn json_string_end(s: &str) -> Option<usize> {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return Some(i),
_ => i += 1,
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_and_code() {
let err = Error::api(Endpoint::CreatePayment, -1, "余额不足");
assert_eq!(err.code(), code::API);
assert_eq!(err.kind(), ErrorKind::Provider);
assert_eq!(err.endpoint(), Some(Endpoint::CreatePayment));
assert_eq!(Error::VerifyFailed.kind(), ErrorKind::Verification);
assert_eq!(Error::VerifyFailed.endpoint(), None);
assert_eq!(Error::INVALID_PID.kind(), ErrorKind::Config);
assert_eq!(
Error::ResponseTooLarge { limit: 1 }.kind(),
ErrorKind::Transport
);
assert!(err.to_string().contains("mapi.php"));
assert!(err.to_string().contains("code -1"));
assert!(err.to_string().contains("余额不足"));
let timeout = Error::transport(TransportErrorKind::Timeout, "timeout");
assert_eq!(timeout.code(), code::NETWORK);
assert!(timeout.is_timeout());
assert!(timeout.is_retryable());
assert_eq!(timeout.transport_kind(), Some(TransportErrorKind::Timeout));
assert_eq!(Error::VerifyFailed.transport_kind(), None);
assert!(Error::http(503, b"").is_retryable());
assert!(!Error::http(500, b"").is_retryable());
assert!(!Error::transport(TransportErrorKind::Redirect, "x").is_retryable());
assert!(!err.is_retryable());
}
#[test]
fn transport_messages_are_redacted() {
let err = Error::transport(
TransportErrorKind::Other,
"failed https://pay.example/api.php?key=super-secret",
);
assert!(!err.to_string().contains("super-secret"), "{err}");
}
#[test]
fn redacts_json_and_url_secrets() {
assert_eq!(
redact_secrets(r#"{"code":1,"key":"super-secret","sign":"deadbeef"}"#),
r#"{"code":1,"key":"***","sign":"***"}"#
);
let text =
redact_secrets("request https://pay.example/api.php?act=query&key=super-secret&pid=1");
assert!(!text.contains("super-secret"), "{text}");
assert!(text.contains("key=***"), "{text}");
}
#[test]
fn truncated_json_secret_is_removed() {
assert_eq!(redact_secrets(r#"{"key":"super-sec"#), r#"{"key":"***""#);
}
#[test]
fn error_previews_are_redacted_and_capped() {
let body = br#"PHP Warning: x{"code":1,"key":"super-secret"}"#;
let err = Error::invalid_response(Endpoint::QueryMerchant, "expected value", body);
assert!(!err.to_string().contains("super-secret"), "{err}");
let long = format!(r#"{{"msg":"{}","key":"super-secret"}}"#, "x".repeat(300));
let err = Error::invalid_response(Endpoint::QueryMerchant, "eof", long.as_bytes());
assert!(!err.to_string().contains("super-secret"), "{err}");
assert!(err.to_string().len() < 350);
}
}