1use std::fmt;
4
5use crate::endpoint::Endpoint;
6
7pub type Result<T, E = Error> = std::result::Result<T, E>;
9
10pub mod code {
12 pub const INVALID_CONFIG: i32 = 1001;
14 pub const VERIFY_FAILED: i32 = 1003;
16 pub const API: i32 = 1004;
18 pub const NETWORK: i32 = 1005;
20 pub const INVALID_RESPONSE: i32 = 1006;
22 pub const INVALID_PARAM: i32 = 1007;
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum TransportErrorKind {
34 Timeout,
36 Connect,
38 Redirect,
40 Body,
42 Request,
44 Other,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum ErrorKind {
57 Config,
59 InvalidParameter,
61 Verification,
63 Provider,
65 Transport,
67 InvalidResponse,
69}
70
71#[derive(Debug, thiserror::Error)]
76#[non_exhaustive]
77pub enum Error {
78 #[error("invalid configuration: {0}")]
80 Config(&'static str),
81
82 #[error("invalid parameter: {0}")]
84 Param(&'static str),
85
86 #[error("invalid notify: {message}")]
89 Notify {
90 message: String,
92 },
93
94 #[error("signature verification failed")]
96 VerifyFailed,
97
98 #[error("epay API error at {endpoint} (code {code}): {message}")]
100 Api {
101 endpoint: Endpoint,
103 code: i32,
105 message: String,
107 },
108
109 #[error("HTTP transport error ({kind:?}): {message}")]
111 Transport {
112 kind: TransportErrorKind,
114 message: String,
116 },
117
118 #[error("unexpected HTTP status {status}: {body}")]
120 Http {
121 status: u16,
123 body: String,
125 },
126
127 #[error("invalid response from {endpoint}: {message}")]
129 InvalidResponse {
130 endpoint: Endpoint,
132 message: String,
134 },
135
136 #[error("response body exceeds configured limit of {limit} bytes")]
138 ResponseTooLarge {
139 limit: usize,
141 },
142}
143
144impl Error {
145 pub fn kind(&self) -> ErrorKind {
147 match self {
148 Self::Config(_) => ErrorKind::Config,
149 Self::Param(_) | Self::Notify { .. } => ErrorKind::InvalidParameter,
150 Self::VerifyFailed => ErrorKind::Verification,
151 Self::Api { .. } => ErrorKind::Provider,
152 Self::Transport { .. } | Self::Http { .. } | Self::ResponseTooLarge { .. } => {
153 ErrorKind::Transport
154 }
155 Self::InvalidResponse { .. } => ErrorKind::InvalidResponse,
156 }
157 }
158
159 pub fn code(&self) -> i32 {
161 match self.kind() {
162 ErrorKind::Config => code::INVALID_CONFIG,
163 ErrorKind::InvalidParameter => code::INVALID_PARAM,
164 ErrorKind::Verification => code::VERIFY_FAILED,
165 ErrorKind::Provider => code::API,
166 ErrorKind::Transport => code::NETWORK,
167 ErrorKind::InvalidResponse => code::INVALID_RESPONSE,
168 }
169 }
170
171 pub fn endpoint(&self) -> Option<Endpoint> {
174 match self {
175 Self::Api { endpoint, .. } | Self::InvalidResponse { endpoint, .. } => Some(*endpoint),
176 _ => None,
177 }
178 }
179
180 pub fn transport_kind(&self) -> Option<TransportErrorKind> {
182 match self {
183 Self::Transport { kind, .. } => Some(*kind),
184 _ => None,
185 }
186 }
187
188 pub fn is_timeout(&self) -> bool {
190 self.transport_kind() == Some(TransportErrorKind::Timeout)
191 }
192
193 pub fn is_retryable(&self) -> bool {
201 match self {
202 Self::Transport { kind, .. } => {
203 matches!(
204 kind,
205 TransportErrorKind::Timeout | TransportErrorKind::Connect
206 )
207 }
208 Self::Http { status, .. } => matches!(status, 502..=504),
209 _ => false,
210 }
211 }
212
213 pub fn transport(kind: TransportErrorKind, message: impl fmt::Display) -> Self {
218 Self::Transport {
219 kind,
220 message: redact_secrets(&message.to_string()),
221 }
222 }
223
224 pub(crate) fn notify(message: impl Into<String>) -> Self {
225 Self::Notify {
226 message: redact_secrets(&message.into()),
227 }
228 }
229
230 pub(crate) fn api(endpoint: Endpoint, code: i32, message: impl Into<String>) -> Self {
231 Self::Api {
232 endpoint,
233 code,
234 message: redact_secrets(&message.into()),
235 }
236 }
237
238 pub(crate) fn invalid_response(
239 endpoint: Endpoint,
240 err: impl fmt::Display,
241 body: &[u8],
242 ) -> Self {
243 Self::InvalidResponse {
244 endpoint,
245 message: format!("{err}: {}", body_preview(body)),
246 }
247 }
248
249 pub(crate) fn invalid_response_message(endpoint: Endpoint, message: impl Into<String>) -> Self {
250 Self::InvalidResponse {
251 endpoint,
252 message: redact_secrets(&message.into()),
253 }
254 }
255
256 pub fn http(status: u16, body: &[u8]) -> Self {
260 Self::Http {
261 status,
262 body: body_preview(body),
263 }
264 }
265
266 pub(crate) fn sanitized(self) -> Self {
268 match self {
269 Self::Transport { kind, message } => Self::Transport {
270 kind,
271 message: redact_secrets(&message),
272 },
273 Self::Http { status, body } => Self::Http {
274 status,
275 body: redact_secrets(&body),
276 },
277 Self::Api {
278 endpoint,
279 code,
280 message,
281 } => Self::Api {
282 endpoint,
283 code,
284 message: redact_secrets(&message),
285 },
286 Self::InvalidResponse { endpoint, message } => Self::InvalidResponse {
287 endpoint,
288 message: redact_secrets(&message),
289 },
290 Self::Notify { message } => Self::Notify {
291 message: redact_secrets(&message),
292 },
293 other => other,
294 }
295 }
296}
297
298impl Error {
300 pub const INVALID_PID: Self = Self::Config("invalid PID: must be greater than 0");
302 pub const INVALID_KEY: Self = Self::Config("invalid Key: must not be empty");
304 pub const INVALID_API_URL: Self = Self::Config("invalid API base URL");
306 pub const INSECURE_API_URL: Self = Self::Config(
308 "API base URL must use HTTPS; call allow_insecure_http(true) for a legacy HTTP gateway",
309 );
310 pub const INVALID_NOTIFY_URL: Self = Self::Param("notify_url must be an absolute HTTP(S) URL");
312 pub const INVALID_RETURN_URL: Self = Self::Param("return_url must be an absolute HTTP(S) URL");
314 pub const INSECURE_NOTIFY_URL: Self = Self::Param(
316 "notify_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
317 );
318 pub const INSECURE_RETURN_URL: Self = Self::Param(
320 "return_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
321 );
322 pub const MISSING_OUT_TRADE_NO: Self = Self::Param("out_trade_no is required");
324 pub const INVALID_OUT_TRADE_NO: Self =
326 Self::Param("out_trade_no must be 1..=64 ASCII characters from [A-Za-z0-9._|-]");
327 pub const MISSING_NOTIFY_URL: Self = Self::Param("notify_url is required");
329 pub const MISSING_NAME: Self = Self::Param("name is required");
331 pub const NAME_TOO_LONG: Self = Self::Param("name exceeds 255 bytes");
333 pub const NAME_HAS_CONTROL_CHARS: Self =
335 Self::Param("name must not contain control characters");
336 pub const SITENAME_HAS_CONTROL_CHARS: Self =
338 Self::Param("sitename must not contain control characters");
339 pub const PARAM_TOO_LONG: Self = Self::Param("param exceeds 255 bytes");
341 pub const SITENAME_TOO_LONG: Self = Self::Param("sitename exceeds 64 bytes");
343 pub const CALLBACK_URL_TOO_LONG: Self =
345 Self::Param("notify_url / return_url exceeds 1024 bytes");
346 pub const REQUEST_TOO_LARGE: Self =
348 Self::Param("encoded request exceeds 4096 bytes; shorten name, param or callback URLs");
349 pub const INVALID_PAY_TYPE: Self =
351 Self::Param("payment type must be 1..=32 characters from [A-Za-z0-9_-]");
352 pub const INVALID_DEVICE: Self =
354 Self::Param("device must be 1..=32 characters from [A-Za-z0-9_-]");
355 pub const INVALID_MONEY: Self = Self::Param("money must be greater than 0");
357 pub const INVALID_MONEY_PRECISION: Self =
359 Self::Param("money must have at most two fractional decimal places");
360 pub const MONEY_OUT_OF_RANGE: Self = Self::Param("money exceeds the i64 fen range");
362 pub const MISSING_TRADE_NO: Self =
364 Self::Param("exactly one of trade_no or out_trade_no is required");
365 pub const INVALID_TRADE_NO: Self = Self::Param("trade_no must be a non-blank ASCII identifier");
367 pub const MISSING_CLIENT_IP: Self = Self::Param("clientip is required by mapi.php");
369 pub const INVALID_CLIENT_IP: Self = Self::Param("clientip must be a valid IPv4/IPv6 address");
371}
372
373pub(crate) fn body_preview(body: &[u8]) -> String {
375 redact_secrets(&String::from_utf8_lossy(body))
376 .chars()
377 .take(256)
378 .collect()
379}
380
381pub(crate) fn redact_secrets(input: &str) -> String {
383 redact_form_secrets(&redact_json_secrets(input))
384}
385
386pub(crate) fn redact_json_secrets(body: &str) -> String {
388 let mut out = String::with_capacity(body.len());
389 let mut rest = body;
390 while let Some((idx, needle)) = find_secret_member(rest) {
391 let (head, tail) = rest.split_at(idx + needle.len());
392 out.push_str(head);
393 let Some(after_colon) = tail.trim_start().strip_prefix(':') else {
394 rest = tail;
395 continue;
396 };
397 let Some(value) = after_colon.trim_start().strip_prefix('"') else {
398 rest = tail;
399 continue;
400 };
401 out.push_str(":\"***\"");
402 rest = match json_string_end(value) {
403 Some(end) => &value[end + 1..],
404 None => "",
405 };
406 }
407 out.push_str(rest);
408 out
409}
410
411fn redact_form_secrets(input: &str) -> String {
412 let mut out = String::with_capacity(input.len());
413 let mut rest = input;
414 loop {
415 let next = ["key=", "sign="]
416 .into_iter()
417 .filter_map(|needle| rest.find(needle).map(|idx| (idx, needle)))
418 .filter(|(idx, _)| {
419 *idx == 0
420 || rest[..*idx]
421 .chars()
422 .next_back()
423 .is_some_and(|c| matches!(c, '?' | '&' | ' ' | '\'' | '"'))
424 })
425 .min_by_key(|(idx, _)| *idx);
426 let Some((idx, needle)) = next else {
427 out.push_str(rest);
428 break;
429 };
430 let value_start = idx + needle.len();
431 out.push_str(&rest[..value_start]);
432 out.push_str("***");
433 let value = &rest[value_start..];
434 let end = value
435 .char_indices()
436 .find(|(_, c)| matches!(c, '&' | ' ' | '\'' | '"' | ')' | ']'))
437 .map(|(idx, _)| idx)
438 .unwrap_or(value.len());
439 rest = &value[end..];
440 }
441 out
442}
443
444fn find_secret_member(s: &str) -> Option<(usize, &'static str)> {
445 ["\"key\"", "\"sign\""]
446 .into_iter()
447 .filter_map(|needle| s.find(needle).map(|idx| (idx, needle)))
448 .min_by_key(|(idx, _)| *idx)
449}
450
451fn json_string_end(s: &str) -> Option<usize> {
452 let bytes = s.as_bytes();
453 let mut i = 0;
454 while i < bytes.len() {
455 match bytes[i] {
456 b'\\' => i += 2,
457 b'"' => return Some(i),
458 _ => i += 1,
459 }
460 }
461 None
462}
463
464#[cfg(test)]
465mod tests {
466 use super::*;
467
468 #[test]
469 fn display_and_code() {
470 let err = Error::api(Endpoint::CreatePayment, -1, "余额不足");
471 assert_eq!(err.code(), code::API);
472 assert_eq!(err.kind(), ErrorKind::Provider);
473 assert_eq!(err.endpoint(), Some(Endpoint::CreatePayment));
474 assert_eq!(Error::VerifyFailed.kind(), ErrorKind::Verification);
475 assert_eq!(Error::VerifyFailed.endpoint(), None);
476 assert_eq!(Error::INVALID_PID.kind(), ErrorKind::Config);
477 assert_eq!(
478 Error::ResponseTooLarge { limit: 1 }.kind(),
479 ErrorKind::Transport
480 );
481 assert!(err.to_string().contains("mapi.php"));
482 assert!(err.to_string().contains("code -1"));
483 assert!(err.to_string().contains("余额不足"));
484
485 let timeout = Error::transport(TransportErrorKind::Timeout, "timeout");
486 assert_eq!(timeout.code(), code::NETWORK);
487 assert!(timeout.is_timeout());
488 assert!(timeout.is_retryable());
489 assert_eq!(timeout.transport_kind(), Some(TransportErrorKind::Timeout));
490 assert_eq!(Error::VerifyFailed.transport_kind(), None);
491 assert!(Error::http(503, b"").is_retryable());
492 assert!(!Error::http(500, b"").is_retryable());
493 assert!(!Error::transport(TransportErrorKind::Redirect, "x").is_retryable());
494 assert!(!err.is_retryable());
495 }
496
497 #[test]
498 fn transport_messages_are_redacted() {
499 let err = Error::transport(
500 TransportErrorKind::Other,
501 "failed https://pay.example/api.php?key=super-secret",
502 );
503 assert!(!err.to_string().contains("super-secret"), "{err}");
504 }
505
506 #[test]
507 fn redacts_json_and_url_secrets() {
508 assert_eq!(
509 redact_secrets(r#"{"code":1,"key":"super-secret","sign":"deadbeef"}"#),
510 r#"{"code":1,"key":"***","sign":"***"}"#
511 );
512 let text =
513 redact_secrets("request https://pay.example/api.php?act=query&key=super-secret&pid=1");
514 assert!(!text.contains("super-secret"), "{text}");
515 assert!(text.contains("key=***"), "{text}");
516 }
517
518 #[test]
519 fn truncated_json_secret_is_removed() {
520 assert_eq!(redact_secrets(r#"{"key":"super-sec"#), r#"{"key":"***""#);
521 }
522
523 #[test]
524 fn error_previews_are_redacted_and_capped() {
525 let body = br#"PHP Warning: x{"code":1,"key":"super-secret"}"#;
526 let err = Error::invalid_response(Endpoint::QueryMerchant, "expected value", body);
527 assert!(!err.to_string().contains("super-secret"), "{err}");
528 let long = format!(r#"{{"msg":"{}","key":"super-secret"}}"#, "x".repeat(300));
529 let err = Error::invalid_response(Endpoint::QueryMerchant, "eof", long.as_bytes());
530 assert!(!err.to_string().contains("super-secret"), "{err}");
531 assert!(err.to_string().len() < 350);
532 }
533}