Skip to main content

epay_sdk/
error.rs

1//! Error type, stable numeric codes and log-safe redaction helpers.
2
3use std::fmt;
4
5use crate::endpoint::Endpoint;
6
7/// SDK result type.
8pub type Result<T, E = Error> = std::result::Result<T, E>;
9
10/// Stable SDK error codes, compatible with the original Go SDK mapping.
11pub mod code {
12    /// Invalid configuration.
13    pub const INVALID_CONFIG: i32 = 1001;
14    /// Signature verification failed.
15    pub const VERIFY_FAILED: i32 = 1003;
16    /// The gateway answered with a business error.
17    pub const API: i32 = 1004;
18    /// Transport failure, unexpected HTTP status or oversized response.
19    pub const NETWORK: i32 = 1005;
20    /// Successful envelope with an unusable payload.
21    pub const INVALID_RESPONSE: i32 = 1006;
22    /// Invalid request parameter or notification.
23    pub const INVALID_PARAM: i32 = 1007;
24}
25
26/// Coarse classification of transport failures.
27///
28/// Callers use this to decide whether a retry is reasonable. Retrying a
29/// mutating call such as [`crate::Client::create_payment`] still requires the
30/// application to reason about idempotency of the `out_trade_no`.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum TransportErrorKind {
34    /// The request or the response body read timed out.
35    Timeout,
36    /// The TCP or TLS connection could not be established.
37    Connect,
38    /// A redirect was received and rejected.
39    Redirect,
40    /// The response body could not be read or decoded.
41    Body,
42    /// The request could not be built or sent.
43    Request,
44    /// Any other failure.
45    Other,
46}
47
48/// Stable, coarse error category for metrics and HTTP mapping.
49///
50/// Low-cardinality and independent of the [`Error`] variants' payloads, so
51/// it is the right thing to match on in application code. It is still
52/// `#[non_exhaustive]`: keep a fallback arm, because a new category may be
53/// added in a future minor release (always with a changelog entry).
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum ErrorKind {
57    /// Client or protocol configuration is invalid.
58    Config,
59    /// A request parameter or notification is invalid.
60    InvalidParameter,
61    /// Signature verification failed.
62    Verification,
63    /// The gateway answered with a business error.
64    Provider,
65    /// Transport failure, unexpected HTTP status or oversized response.
66    Transport,
67    /// Successful envelope with an unusable payload.
68    InvalidResponse,
69}
70
71/// EPay SDK error.
72///
73/// Error text generated by the built-in client never includes a request URL.
74/// Response previews are bounded and have `key` / `sign` values masked.
75#[derive(Debug, thiserror::Error)]
76#[non_exhaustive]
77pub enum Error {
78    /// Invalid client or protocol configuration.
79    #[error("invalid configuration: {0}")]
80    Config(&'static str),
81
82    /// Invalid outbound request parameter.
83    #[error("invalid parameter: {0}")]
84    Param(&'static str),
85
86    /// A notification was malformed, unauthenticated by metadata, or
87    /// structurally invalid. Signature mismatches use [`Error::VerifyFailed`].
88    #[error("invalid notify: {message}")]
89    Notify {
90        /// Redacted description of the rejection.
91        message: String,
92    },
93
94    /// MD5 signature verification failed.
95    #[error("signature verification failed")]
96    VerifyFailed,
97
98    /// The gateway answered with a non-success `code`.
99    #[error("epay API error at {endpoint} (code {code}): {message}")]
100    Api {
101        /// Endpoint that produced the error.
102        endpoint: Endpoint,
103        /// Gateway `code` value.
104        code: i32,
105        /// Gateway `msg` value, redacted.
106        message: String,
107    },
108
109    /// The HTTP transport failed before a response status was available.
110    #[error("HTTP transport error ({kind:?}): {message}")]
111    Transport {
112        /// Failure classification.
113        kind: TransportErrorKind,
114        /// Redacted, URL-free description.
115        message: String,
116    },
117
118    /// The gateway returned a non-2xx status.
119    #[error("unexpected HTTP status {status}: {body}")]
120    Http {
121        /// HTTP status code.
122        status: u16,
123        /// Redacted preview of the response body.
124        body: String,
125    },
126
127    /// The gateway reported success but the payload is unusable.
128    #[error("invalid response from {endpoint}: {message}")]
129    InvalidResponse {
130        /// Endpoint that produced the response.
131        endpoint: Endpoint,
132        /// Redacted description including a bounded body preview.
133        message: String,
134    },
135
136    /// The response body exceeded the configured limit.
137    #[error("response body exceeds configured limit of {limit} bytes")]
138    ResponseTooLarge {
139        /// Configured limit in bytes.
140        limit: usize,
141    },
142}
143
144impl Error {
145    /// Coarse category; see [`ErrorKind`].
146    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    /// Numeric error code, compatible with the original Go SDK mapping.
160    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    /// Gateway endpoint involved, for [`Error::Api`] and
172    /// [`Error::InvalidResponse`].
173    pub fn endpoint(&self) -> Option<Endpoint> {
174        match self {
175            Self::Api { endpoint, .. } | Self::InvalidResponse { endpoint, .. } => Some(*endpoint),
176            _ => None,
177        }
178    }
179
180    /// Transport failure classification, if this is a transport error.
181    pub fn transport_kind(&self) -> Option<TransportErrorKind> {
182        match self {
183            Self::Transport { kind, .. } => Some(*kind),
184            _ => None,
185        }
186    }
187
188    /// Whether the failure was a transport timeout.
189    pub fn is_timeout(&self) -> bool {
190        self.transport_kind() == Some(TransportErrorKind::Timeout)
191    }
192
193    /// Whether the request never reached (or never received an answer from)
194    /// the gateway's application layer, so repeating it is safe for
195    /// read-only endpoints: transport timeouts / connection failures and
196    /// HTTP 502/503/504.
197    ///
198    /// [`crate::RetryPolicy`] consults this. Business errors
199    /// ([`Error::Api`]) and malformed responses are never retryable.
200    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    /// Build a transport error with a redacted message.
214    ///
215    /// Custom [`crate::Transport`] implementations should use this rather
216    /// than formatting a URL-bearing error into the message.
217    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    /// Build an [`Error::Http`] for a non-2xx response, keeping a bounded,
257    /// redacted preview of `body`. Custom [`crate::Transport`]s should use
258    /// this instead of embedding the raw body.
259    pub fn http(status: u16, body: &[u8]) -> Self {
260        Self::Http {
261            status,
262            body: body_preview(body),
263        }
264    }
265
266    /// Re-sanitize errors returned by custom transports before surfacing them.
267    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
298/// Well-known configuration and parameter errors.
299impl Error {
300    /// PID must be greater than zero.
301    pub const INVALID_PID: Self = Self::Config("invalid PID: must be greater than 0");
302    /// Merchant key must not be empty.
303    pub const INVALID_KEY: Self = Self::Config("invalid Key: must not be empty");
304    /// API base URL is malformed or carries credentials, query or fragment.
305    pub const INVALID_API_URL: Self = Self::Config("invalid API base URL");
306    /// API base URL uses plain HTTP without explicit opt-in.
307    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    /// `notify_url` is not an absolute HTTP(S) URL.
311    pub const INVALID_NOTIFY_URL: Self = Self::Param("notify_url must be an absolute HTTP(S) URL");
312    /// `return_url` is not an absolute HTTP(S) URL.
313    pub const INVALID_RETURN_URL: Self = Self::Param("return_url must be an absolute HTTP(S) URL");
314    /// `notify_url` uses plain HTTP without explicit opt-in.
315    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    /// `return_url` uses plain HTTP without explicit opt-in.
319    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    /// `out_trade_no` is empty.
323    pub const MISSING_OUT_TRADE_NO: Self = Self::Param("out_trade_no is required");
324    /// `out_trade_no` violates the accepted charset or length.
325    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    /// Neither the request nor the configuration provides a `notify_url`.
328    pub const MISSING_NOTIFY_URL: Self = Self::Param("notify_url is required");
329    /// Product `name` is blank.
330    pub const MISSING_NAME: Self = Self::Param("name is required");
331    /// Product `name` exceeds [`crate::limits::MAX_NAME_BYTES`].
332    pub const NAME_TOO_LONG: Self = Self::Param("name exceeds 255 bytes");
333    /// Product `name` contains control characters.
334    pub const NAME_HAS_CONTROL_CHARS: Self =
335        Self::Param("name must not contain control characters");
336    /// `sitename` contains control characters.
337    pub const SITENAME_HAS_CONTROL_CHARS: Self =
338        Self::Param("sitename must not contain control characters");
339    /// `param` exceeds [`crate::limits::MAX_PARAM_BYTES`].
340    pub const PARAM_TOO_LONG: Self = Self::Param("param exceeds 255 bytes");
341    /// `sitename` exceeds [`crate::limits::MAX_SITENAME_BYTES`].
342    pub const SITENAME_TOO_LONG: Self = Self::Param("sitename exceeds 64 bytes");
343    /// A callback URL exceeds [`crate::limits::MAX_CALLBACK_URL_BYTES`].
344    pub const CALLBACK_URL_TOO_LONG: Self =
345        Self::Param("notify_url / return_url exceeds 1024 bytes");
346    /// The signed request exceeds [`crate::limits::MAX_REQUEST_BYTES`].
347    pub const REQUEST_TOO_LARGE: Self =
348        Self::Param("encoded request exceeds 4096 bytes; shorten name, param or callback URLs");
349    /// Payment `type` is blank or not a short `[A-Za-z0-9_-]` identifier.
350    pub const INVALID_PAY_TYPE: Self =
351        Self::Param("payment type must be 1..=32 characters from [A-Za-z0-9_-]");
352    /// `device` is blank or not a short `[A-Za-z0-9_-]` identifier.
353    pub const INVALID_DEVICE: Self =
354        Self::Param("device must be 1..=32 characters from [A-Za-z0-9_-]");
355    /// Amount is not positive or not parseable.
356    pub const INVALID_MONEY: Self = Self::Param("money must be greater than 0");
357    /// Amount carries meaningful precision beyond two decimal places.
358    pub const INVALID_MONEY_PRECISION: Self =
359        Self::Param("money must have at most two fractional decimal places");
360    /// Amount does not fit the `i64` fen range.
361    pub const MONEY_OUT_OF_RANGE: Self = Self::Param("money exceeds the i64 fen range");
362    /// Exactly one of `trade_no` / `out_trade_no` must be given.
363    pub const MISSING_TRADE_NO: Self =
364        Self::Param("exactly one of trade_no or out_trade_no is required");
365    /// `trade_no` is not a non-blank ASCII identifier.
366    pub const INVALID_TRADE_NO: Self = Self::Param("trade_no must be a non-blank ASCII identifier");
367    /// `clientip` is required by `mapi.php`.
368    pub const MISSING_CLIENT_IP: Self = Self::Param("clientip is required by mapi.php");
369    /// `clientip` is not a valid IP address.
370    pub const INVALID_CLIENT_IP: Self = Self::Param("clientip must be a valid IPv4/IPv6 address");
371}
372
373/// First 256 characters of a response body with secrets masked.
374pub(crate) fn body_preview(body: &[u8]) -> String {
375    redact_secrets(&String::from_utf8_lossy(body))
376        .chars()
377        .take(256)
378        .collect()
379}
380
381/// Mask JSON members and form/query fragments named `key` or `sign`.
382pub(crate) fn redact_secrets(input: &str) -> String {
383    redact_form_secrets(&redact_json_secrets(input))
384}
385
386/// Mask the value of every `"key"` / `"sign"` member in JSON-like text.
387pub(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}