Skip to main content

erpc_sdk/
error.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// Result type returned by this crate.
7pub type Result<T> = std::result::Result<T, ErpcError>;
8
9/// Stable category for an SDK error.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum ErpcErrorCode {
12    /// A caller-provided cancellation token was cancelled.
13    Aborted,
14    /// A locally enforced batch policy was violated.
15    BatchPolicy,
16    /// Client configuration was invalid.
17    Config,
18    /// A requested service has no configured transport.
19    NotConfigured,
20    /// An HTTP response had a non-success status.
21    Http,
22    /// A response did not satisfy the ERPC contract.
23    InvalidResponse,
24    /// A JSON-RPC error response was returned.
25    Rpc,
26    /// A request exceeded its timeout.
27    Timeout,
28    /// A transport could not reach ERPC.
29    Transport,
30}
31
32/// Wire representation of a JSON-RPC error object.
33#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
34pub struct JsonRpcErrorObject {
35    /// Numeric JSON-RPC error code.
36    pub code: i64,
37    /// Public error message, with the configured credential redacted.
38    pub message: String,
39    /// Optional structured error data.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub data: Option<Value>,
42}
43
44/// All errors produced by the SDK.
45#[derive(Debug, thiserror::Error)]
46pub enum ErpcError {
47    /// A caller cancelled the request.
48    #[error("ERPC request was aborted")]
49    Aborted,
50    /// A batch violates a server boundary that must remain intact.
51    #[error("{0}")]
52    BatchPolicy(String),
53    /// Invalid client configuration.
54    #[error("{0}")]
55    Config(String),
56    /// A requested namespace has no configured transport.
57    #[error("ERPC namespace '{0}' is not configured")]
58    NotConfigured(String),
59    /// Non-success HTTP response.
60    #[error("ERPC request failed with HTTP {status}")]
61    Http {
62        /// HTTP status code.
63        status: u16,
64    },
65    /// Malformed or contract-incompatible response.
66    #[error("{0}")]
67    InvalidResponse(String),
68    /// JSON-RPC error returned by ERPC.
69    #[error("{message}")]
70    JsonRpc {
71        /// Numeric JSON-RPC error code.
72        code: i64,
73        /// Redacted server message.
74        message: String,
75        /// Redacted optional server data.
76        data: Option<Value>,
77    },
78    /// Request timeout.
79    #[error("ERPC request timed out after {timeout_ms}ms")]
80    Timeout {
81        /// Configured timeout in milliseconds.
82        timeout_ms: u64,
83    },
84    /// Sanitized network or WebSocket failure.
85    #[error("{0}")]
86    Transport(String),
87}
88
89impl ErpcError {
90    /// Returns a stable error category.
91    #[must_use]
92    pub const fn code(&self) -> ErpcErrorCode {
93        match self {
94            Self::Aborted => ErpcErrorCode::Aborted,
95            Self::BatchPolicy(_) => ErpcErrorCode::BatchPolicy,
96            Self::Config(_) => ErpcErrorCode::Config,
97            Self::NotConfigured(_) => ErpcErrorCode::NotConfigured,
98            Self::Http { .. } => ErpcErrorCode::Http,
99            Self::InvalidResponse(_) => ErpcErrorCode::InvalidResponse,
100            Self::JsonRpc { .. } => ErpcErrorCode::Rpc,
101            Self::Timeout { .. } => ErpcErrorCode::Timeout,
102            Self::Transport(_) => ErpcErrorCode::Transport,
103        }
104    }
105}
106
107pub(crate) fn invalid_response(message: impl Into<String>) -> ErpcError {
108    ErpcError::InvalidResponse(message.into())
109}
110
111pub(crate) fn timeout(duration: std::time::Duration) -> ErpcError {
112    let millis = u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
113    ErpcError::Timeout { timeout_ms: millis }
114}
115
116fn encoded_variants(credential: &str) -> Vec<String> {
117    if credential.is_empty() {
118        return Vec::new();
119    }
120    let mut values = vec![credential.to_owned()];
121    let query_encoded: String =
122        url::form_urlencoded::byte_serialize(credential.as_bytes()).collect();
123    let component_encoded = credential
124        .as_bytes()
125        .iter()
126        .map(|byte| {
127            if byte.is_ascii_alphanumeric() || b"-_.!~*'()".contains(byte) {
128                char::from(*byte).to_string()
129            } else {
130                format!("%{byte:02X}")
131            }
132        })
133        .collect::<String>();
134    for encoded in [query_encoded, component_encoded] {
135        if !encoded.is_empty() && !values.contains(&encoded) {
136            values.push(encoded);
137        }
138    }
139    values.sort_by_key(|right| std::cmp::Reverse(right.len()));
140    values
141}
142
143fn redaction_variants(secrets: &[String]) -> Vec<String> {
144    let mut variants = secrets
145        .iter()
146        .flat_map(|secret| encoded_variants(secret))
147        .collect::<Vec<_>>();
148    variants.sort_by_key(|value| std::cmp::Reverse(value.len()));
149    variants.dedup();
150    variants
151}
152
153fn redact_text_with_variants(value: &str, variants: &[String]) -> String {
154    variants.iter().fold(value.to_owned(), |result, variant| {
155        let result = result.replace(variant, "[REDACTED]");
156        if has_percent_escape(variant) {
157            redact_percent_escape_case_insensitive(&result, variant)
158        } else {
159            result
160        }
161    })
162}
163
164fn has_percent_escape(value: &str) -> bool {
165    value.as_bytes().windows(3).any(is_percent_escape)
166}
167
168fn is_percent_escape(bytes: &[u8]) -> bool {
169    bytes.len() == 3
170        && bytes[0] == b'%'
171        && bytes[1].is_ascii_hexdigit()
172        && bytes[2].is_ascii_hexdigit()
173}
174
175fn redact_percent_escape_case_insensitive(value: &str, pattern: &str) -> String {
176    let value_bytes = value.as_bytes();
177    let pattern_bytes = pattern.as_bytes();
178    if !pattern.is_ascii() || pattern_bytes.len() > value_bytes.len() {
179        return value.to_owned();
180    }
181    let mut result = String::with_capacity(value.len());
182    let mut cursor = 0;
183    while cursor + pattern_bytes.len() <= value_bytes.len() {
184        let Some(relative) = value_bytes[cursor..]
185            .windows(pattern_bytes.len())
186            .position(|candidate| percent_escape_pattern_matches(candidate, pattern_bytes))
187        else {
188            break;
189        };
190        let start = cursor + relative;
191        let end = start + pattern_bytes.len();
192        result.push_str(&value[cursor..start]);
193        result.push_str("[REDACTED]");
194        cursor = end;
195    }
196    if result.is_empty() {
197        return value.to_owned();
198    }
199    result.push_str(&value[cursor..]);
200    result
201}
202
203fn percent_escape_pattern_matches(candidate: &[u8], pattern: &[u8]) -> bool {
204    let mut index = 0;
205    while index < pattern.len() {
206        if index + 2 < pattern.len()
207            && pattern[index] == b'%'
208            && pattern[index + 1].is_ascii_hexdigit()
209            && pattern[index + 2].is_ascii_hexdigit()
210        {
211            if candidate[index] != b'%'
212                || !candidate[index + 1].eq_ignore_ascii_case(&pattern[index + 1])
213                || !candidate[index + 2].eq_ignore_ascii_case(&pattern[index + 2])
214            {
215                return false;
216            }
217            index += 3;
218        } else {
219            if candidate[index] != pattern[index] {
220                return false;
221            }
222            index += 1;
223        }
224    }
225    true
226}
227
228fn redact_value_with_variants(value: Value, variants: &[String], depth: usize) -> Value {
229    if depth >= 32 {
230        return Value::String("[REDACTED]".to_owned());
231    }
232    match value {
233        Value::String(value) => Value::String(redact_text_with_variants(&value, variants)),
234        Value::Array(values) => Value::Array(
235            values
236                .into_iter()
237                .map(|value| redact_value_with_variants(value, variants, depth + 1))
238                .collect(),
239        ),
240        Value::Object(values) => Value::Object(
241            values
242                .into_iter()
243                .map(|(key, value)| {
244                    (
245                        redact_text_with_variants(&key, variants),
246                        redact_value_with_variants(value, variants, depth + 1),
247                    )
248                })
249                .collect(),
250        ),
251        other => other,
252    }
253}
254
255pub(crate) fn rpc_error_with_secrets(error: JsonRpcErrorObject, secrets: &[String]) -> ErpcError {
256    let variants = redaction_variants(secrets);
257    ErpcError::JsonRpc {
258        code: error.code,
259        message: redact_text_with_variants(&error.message, &variants),
260        data: error
261            .data
262            .map(|value| redact_value_with_variants(value, &variants, 0)),
263    }
264}
265
266impl fmt::Display for ErpcErrorCode {
267    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
268        let code = match self {
269            Self::Aborted => "ERPC_ABORTED",
270            Self::BatchPolicy => "ERPC_BATCH_POLICY",
271            Self::Config => "ERPC_CONFIG",
272            Self::NotConfigured => "ERPC_NOT_CONFIGURED",
273            Self::Http => "ERPC_HTTP",
274            Self::InvalidResponse => "ERPC_INVALID_RESPONSE",
275            Self::Rpc => "ERPC_RPC",
276            Self::Timeout => "ERPC_TIMEOUT",
277            Self::Transport => "ERPC_TRANSPORT",
278        };
279        formatter.write_str(code)
280    }
281}