use crate::error::Error;
use crate::model::{Envelope, Pagination};
use crate::pricing::Pricing;
use crate::redaction::body_preview;
use serde_json::error::Category;
pub(crate) struct Decoded<T> {
pub payload: T,
pub pagination: Option<Pagination>,
}
impl<T: std::fmt::Debug> std::fmt::Debug for Decoded<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Decoded")
.field("payload", &self.payload)
.field("pagination", &self.pagination.is_some())
.finish()
}
}
const BODY_PREVIEW_MAX: usize = 256;
pub(crate) fn decode<T: serde::de::DeserializeOwned>(
status: http::StatusCode,
content_type: Option<&str>,
body: &[u8],
pricing: Pricing,
retry_after: Option<std::time::Duration>,
www_authenticate: Option<&str>,
) -> Result<Decoded<T>, Error> {
decode_with_txid_header(
status,
content_type,
body,
pricing,
retry_after,
www_authenticate,
None,
)
}
pub(crate) fn decode_with_txid_header<T: serde::de::DeserializeOwned>(
status: http::StatusCode,
content_type: Option<&str>,
body: &[u8],
pricing: Pricing,
retry_after: Option<std::time::Duration>,
www_authenticate: Option<&str>,
x_txid: Option<&str>,
) -> Result<Decoded<T>, Error> {
gate(
status,
content_type,
body,
pricing,
retry_after,
www_authenticate,
x_txid,
)?;
match serde_json::from_slice::<Envelope<T>>(body) {
Ok(envelope) => Ok(Decoded {
payload: envelope.response,
pagination: envelope.pagination,
}),
Err(err) => Err(body_parse_error(&err, body, status, pricing)),
}
}
pub(crate) fn decode_body_raw(
status: http::StatusCode,
content_type: Option<&str>,
body: &[u8],
pricing: Pricing,
retry_after: Option<std::time::Duration>,
www_authenticate: Option<&str>,
x_txid: Option<&str>,
) -> Result<serde_json::Value, Error> {
gate(
status,
content_type,
body,
pricing,
retry_after,
www_authenticate,
x_txid,
)?;
serde_json::from_slice::<serde_json::Value>(body)
.map_err(|err| body_parse_error(&err, body, status, pricing))
}
fn body_parse_error(
err: &serde_json::Error,
body: &[u8],
status: http::StatusCode,
pricing: Pricing,
) -> Error {
let lossy = String::from_utf8_lossy(body);
let message = if matches!(err.classify(), Category::Data) {
body_preview(
&format!(
"invalid data at line {} column {}",
err.line(),
err.column()
),
BODY_PREVIEW_MAX,
)
} else {
body_preview(&err.to_string(), BODY_PREVIEW_MAX)
};
Error::Decode {
message,
status,
body_preview: body_preview(&lossy, BODY_PREVIEW_MAX),
pricing,
}
}
fn gate(
status: http::StatusCode,
content_type: Option<&str>,
body: &[u8],
pricing: Pricing,
retry_after: Option<std::time::Duration>,
www_authenticate: Option<&str>,
x_txid: Option<&str>,
) -> Result<(), Error> {
if status.as_u16() >= 400 {
let txid = extract_txid(body, x_txid);
return Err(match status.as_u16() {
401 => Error::Auth {
message: body_preview(&String::from_utf8_lossy(body), BODY_PREVIEW_MAX),
pricing: Some(pricing),
},
408 => Error::VehicleOffline { pricing, txid },
_ => Error::Api {
status,
message: body_preview(
&error_message(body, www_authenticate, status),
BODY_PREVIEW_MAX,
),
retry_after,
body_preview: body_preview(&String::from_utf8_lossy(body), BODY_PREVIEW_MAX),
pricing,
txid,
},
});
}
let is_json = content_type
.map(|ct| ct.to_ascii_lowercase().contains("json"))
.unwrap_or(false);
if !is_json {
let lossy = String::from_utf8_lossy(body);
return Err(Error::Decode {
message: body_preview(
&format!(
"unexpected content-type: {}",
content_type.unwrap_or("<none>")
),
BODY_PREVIEW_MAX,
),
status,
body_preview: body_preview(&lossy, BODY_PREVIEW_MAX),
pricing,
});
}
Ok(())
}
fn non_empty(s: Option<&str>) -> Option<&str> {
s.filter(|v| !v.trim().is_empty())
}
fn error_message(body: &[u8], www_authenticate: Option<&str>, status: http::StatusCode) -> String {
let parsed = serde_json::from_slice::<serde_json::Value>(body).ok();
if let Some(v) = &parsed {
if let Some(s) = non_empty(v.get("error").and_then(|e| e.as_str())) {
return s.to_owned();
}
if let Some(s) = non_empty(v.get("error_description").and_then(|e| e.as_str())) {
return s.to_owned();
}
}
if let Some(desc) = www_authenticate
.and_then(extract_error_description)
.filter(|d| !d.trim().is_empty())
{
return desc;
}
status
.canonical_reason()
.unwrap_or("unknown error")
.to_owned()
}
fn extract_txid(body: &[u8], header_txid: Option<&str>) -> Option<String> {
serde_json::from_slice::<serde_json::Value>(body)
.ok()
.and_then(|v| non_empty(v.get("txid").and_then(|t| t.as_str())).map(str::to_owned))
.or_else(|| non_empty(header_txid).map(str::to_owned))
}
fn extract_error_description(header: &str) -> Option<String> {
let start = header.find("error_description=\"")? + "error_description=\"".len();
let rest = &header[start..];
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'\\' => out.push(chars.next()?),
'"' => return Some(out),
_ => out.push(c),
}
}
None }
#[cfg(test)]
mod tests {
use super::*;
use crate::pricing::Pricing;
#[test]
fn ok_json_unwraps_envelope() {
let r = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/json"),
br#"{"response":{"vin":"X"}}"#,
Pricing::NotCharged,
None,
None,
)
.unwrap();
assert_eq!(r.payload["vin"], serde_json::json!("X"));
}
#[test]
fn html_gateway_502_is_api_error_not_panic() {
let e = decode::<serde_json::Value>(
http::StatusCode::BAD_GATEWAY,
Some("text/html"),
b"<html>502</html>",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Api { .. }));
}
#[test]
fn status_408_is_vehicle_offline() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
b"{}",
Pricing::data(),
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::VehicleOffline { .. }));
}
#[test]
fn non_json_200_is_decode_error() {
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/pdf"),
b"%PDF",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Decode { .. }));
}
#[test]
fn missing_content_type_is_decode_error() {
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
None,
br#"{"response":{}}"#,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Decode { .. }));
}
#[test]
fn json_with_charset_and_vendor_suffix_are_accepted() {
let r1 = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/json; charset=utf-8"),
br#"{"response":1}"#,
Pricing::NotCharged,
None,
None,
)
.unwrap();
assert_eq!(r1.payload, serde_json::json!(1));
let r2 = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("APPLICATION/VND.API+JSON"),
br#"{"response":2}"#,
Pricing::NotCharged,
None,
None,
)
.unwrap();
assert_eq!(r2.payload, serde_json::json!(2));
}
#[test]
fn empty_body_200_json_is_decode_error_not_panic() {
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/json"),
b"",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Decode { .. }));
}
#[test]
fn status_401_is_auth_error_and_redacts_the_echoed_credential() {
let body = br#"{"error":"invalid_bearer_token","error_description":"Bearer eyJhbGciOiJIUzI1NiJ9.raw-secret-value.sig","vin":"5YJ3E1EA7KF000000"}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::UNAUTHORIZED,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Auth { message, .. } => {
assert!(message.contains("[REDACTED]"), "got: {message}");
assert!(message.contains("[VIN]"), "got: {message}");
assert!(!message.contains("raw-secret-value"));
assert!(!message.contains("eyJhbGciOiJIUzI1NiJ9"));
assert!(!message.contains("5YJ3E1EA7KF000000"));
}
other => panic!("expected Auth, got {other:?}"),
}
}
#[test]
fn status_401_html_proxy_auth_page_is_still_auth_error() {
let e = decode::<serde_json::Value>(
http::StatusCode::UNAUTHORIZED,
Some("text/html"),
b"<html><body>401 Unauthorized</body></html>",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Auth { .. }));
}
#[test]
fn status_401_on_paid_endpoint_reports_billed() {
use crate::pricing::Billing;
let e = decode::<serde_json::Value>(
http::StatusCode::UNAUTHORIZED,
Some("application/json"),
br#"{"error":"invalid_token"}"#,
Pricing::data(),
None,
None,
)
.err()
.unwrap();
match &e {
crate::error::Error::Auth { pricing, .. } => {
assert_eq!(*pricing, Some(Pricing::data()));
}
other => panic!("expected Auth, got {other:?}"),
}
assert_eq!(e.billing(), Billing::Billed);
let free = decode::<serde_json::Value>(
http::StatusCode::UNAUTHORIZED,
Some("application/json"),
br#"{"error":"invalid_token"}"#,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert_eq!(free.billing(), Billing::NotBilled);
}
#[test]
fn status_408_html_gateway_timeout_is_still_vehicle_offline() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("text/html"),
b"<html><body>408 Request Timeout</body></html>",
Pricing::data(),
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::VehicleOffline { .. }));
}
#[test]
fn non_utf8_body_does_not_panic() {
let bad_utf8: &[u8] = &[0xff, 0xfe, 0xfd];
let e = decode::<serde_json::Value>(
http::StatusCode::INTERNAL_SERVER_ERROR,
Some("text/plain"),
bad_utf8,
Pricing::data(),
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Api { .. }));
}
#[test]
fn valid_json_missing_response_key_is_decode_error() {
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/json"),
br#"{"not_response":{"vin":"X"}}"#,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Decode { .. }));
}
#[test]
fn status_ge_400_wins_over_bad_content_type() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(503).unwrap(),
None,
b"upstream connect error",
Pricing::data(),
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, crate::error::Error::Api { .. }));
}
#[test]
fn api_error_body_preview_is_exact_when_under_bound() {
let e = decode::<serde_json::Value>(
http::StatusCode::BAD_GATEWAY,
Some("application/json"),
br#"{"access_token":"SECRET_XYZ","note":"leaked"}"#,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Api { body_preview, .. } => {
assert_eq!(
body_preview,
r#"{"access_token":"[REDACTED]","note":"leaked"}"#
);
}
other => panic!("expected Api, got {other:?}"),
}
}
#[test]
fn api_error_body_preview_redacts_then_truncates_long_body() {
let long_note = "A".repeat(400);
let body = format!(r#"{{"access_token":"SECRET_XYZ","note":"{long_note}"}}"#);
let e = decode::<serde_json::Value>(
http::StatusCode::BAD_GATEWAY,
Some("application/json"),
body.as_bytes(),
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Api { body_preview, .. } => {
assert_eq!(body_preview.len(), BODY_PREVIEW_MAX);
assert!(!body_preview.contains("SECRET_XYZ"));
assert!(body_preview.starts_with(r#"{"access_token":"[REDACTED]","note":""#));
}
other => panic!("expected Api, got {other:?}"),
}
}
#[test]
fn decode_message_for_bad_content_type_is_exact_when_under_bound() {
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some("application/pdf"),
b"%PDF",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert_eq!(message, "unexpected content-type: application/pdf");
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn decode_message_for_bad_content_type_is_bounded_when_header_is_huge() {
let huge_ct = format!("application/x-{}", "a".repeat(400));
let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some(&huge_ct),
b"whatever",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert_eq!(message.len(), BODY_PREVIEW_MAX);
assert!(message.starts_with("unexpected content-type: application/x-a"));
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[derive(Debug, serde::Deserialize)]
struct TypedU64 {
#[allow(dead_code)]
token: u64,
}
#[test]
fn decode_parse_error_data_category_hides_body_value_reviewer_probe() {
let body = br#"{"response":{"token":"NA_a1b2c3d4e5f6g7"}}"#;
let independent_err = match serde_json::from_slice::<crate::model::Envelope<TypedU64>>(body)
{
Ok(_) => panic!("expected the malformed body to fail to parse"),
Err(err) => err,
};
assert_eq!(independent_err.classify(), Category::Data);
let expected = format!(
"invalid data at line {} column {}",
independent_err.line(),
independent_err.column()
);
let e = decode::<TypedU64>(
http::StatusCode::OK,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert_eq!(message, expected);
assert!(!message.contains("NA_a1b2c3d4e5f6g7"));
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn decode_parse_error_data_category_hides_pattern_matching_secrets_too() {
let body = br#"{"response":{"token":"Bearer eyJhbGciOiJIUzI1NiJ9.raw-secret-value.sig"}}"#;
let e = decode::<TypedU64>(
http::StatusCode::OK,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert!(!message.contains("raw-secret-value"));
assert!(!message.contains("eyJhbGciOiJIUzI1NiJ9"));
assert!(!message.contains("Bearer"));
assert!(message.starts_with("invalid data at line"));
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn decode_parse_error_syntax_category_keeps_grammar_detail_verbatim() {
let body = br#"{"response":{"vin":"X",}}"#;
let independent_err = match serde_json::from_slice::<crate::model::Envelope<TypedU64>>(body)
{
Ok(_) => panic!("expected the malformed body to fail to parse"),
Err(err) => err,
};
assert_eq!(independent_err.classify(), Category::Syntax);
let expected_detail = independent_err.to_string();
assert!(
expected_detail.contains("trailing comma"),
"expected a real grammar detail, got: {expected_detail}"
);
let e = decode::<TypedU64>(
http::StatusCode::OK,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert_eq!(message, expected_detail);
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn syntax_category_message_never_interpolates_body_content() {
let body = br#"{"response":{"token":1,"note":"ZZQXVDISTINCTIVEBODYTOKEN" "x":2}}"#;
let needle = "ZZQXVDISTINCTIVEBODYTOKEN";
let independent_err = match serde_json::from_slice::<crate::model::Envelope<TypedU64>>(body)
{
Ok(_) => panic!("expected the malformed body to fail to parse"),
Err(err) => err,
};
assert_eq!(
independent_err.classify(),
Category::Syntax,
"probe no longer produces a Syntax error; rewrite it"
);
let e = decode::<TypedU64>(
http::StatusCode::OK,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert!(
!message.contains(needle),
"a Syntax-category message interpolated body content — \
`decode`'s Category::Data-only guard is no longer sufficient: {message}"
);
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn eof_category_message_never_interpolates_body_content() {
let body = br#"{"response":{"token":1,"note":"ZZQXVDISTINCTIVEBODYTOKEN"#;
let needle = "ZZQXVDISTINCTIVEBODYTOKEN";
let independent_err = match serde_json::from_slice::<crate::model::Envelope<TypedU64>>(body)
{
Ok(_) => panic!("expected the malformed body to fail to parse"),
Err(err) => err,
};
assert_eq!(
independent_err.classify(),
Category::Eof,
"probe no longer produces an Eof error; rewrite it"
);
let e = decode::<TypedU64>(
http::StatusCode::OK,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert!(
!message.contains(needle),
"an Eof-category message interpolated body content: {message}"
);
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn decode_message_for_bad_content_type_redacts_secret_shaped_header() {
let hostile_ct = "text/html; Bearer eyJhbGciOiJIUzI1NiJ9.raw-secret-value.sig";
assert!(!hostile_ct.to_ascii_lowercase().contains("json")); let e = decode::<serde_json::Value>(
http::StatusCode::OK,
Some(hostile_ct),
b"whatever",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Decode { message, .. } => {
assert!(message.contains("[REDACTED]"), "got: {message}");
assert!(!message.contains("raw-secret-value"));
assert!(!message.contains("eyJhbGciOiJIUzI1NiJ9"));
}
other => panic!("expected Decode, got {other:?}"),
}
}
#[test]
fn decode_api_error_body_preview_redacts_drive_state_coordinates() {
let body = br#"{"drive_state":{"latitude":37.5665,"longitude":126.9780}}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::BAD_GATEWAY,
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
match e {
crate::error::Error::Api { body_preview, .. } => {
assert!(body_preview.contains("[COORD]"), "got: {body_preview}");
assert!(!body_preview.contains("37.5665"));
assert!(!body_preview.contains("126.978"));
}
other => panic!("expected Api, got {other:?}"),
}
}
use std::time::Duration;
#[test]
fn api_message_comes_from_body_error_field() {
let body = br#"{"error":"invalid bearer token"}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(403).unwrap(),
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(e.to_string().contains("invalid [REDACTED]"), "actual: {e}");
}
#[test]
fn api_message_falls_back_to_www_authenticate() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(403).unwrap(),
Some("text/html"),
b"",
Pricing::NotCharged,
None,
Some(r#"Bearer realm="Doorkeeper", error="invalid_token", error_description="The access token is invalid""#),
)
.err().unwrap();
assert!(
e.to_string().contains("The access token is invalid"),
"actual: {e}"
);
}
#[test]
fn api_message_falls_back_to_canonical_reason() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(502).unwrap(),
Some("text/html"),
b"",
Pricing::NotCharged,
None,
None,
)
.err()
.unwrap();
assert!(e.to_string().contains("Bad Gateway"), "actual: {e}");
}
#[test]
fn api_message_prefers_body_error_over_www_authenticate_when_both_present() {
let body = br#"{"error":"body wins"}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(403).unwrap(),
Some("application/json"),
body,
Pricing::NotCharged,
None,
Some(r#"Bearer error_description="header loses""#),
)
.err()
.unwrap();
assert!(e.to_string().contains("body wins"), "actual: {e}");
assert!(!e.to_string().contains("header loses"), "actual: {e}");
}
#[test]
fn empty_html_401_is_auth_not_decode() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(401).unwrap(),
Some("text/html"),
b"",
Pricing::data(),
None,
None,
)
.err()
.unwrap();
assert!(matches!(e, Error::Auth { .. }), "actual: {e:?}");
assert!(matches!(e.billing(), crate::pricing::Billing::Billed));
}
#[test]
fn retry_after_is_carried_and_capped() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(429).unwrap(),
Some("application/json"),
b"{}",
Pricing::NotCharged,
Some(Duration::from_secs(600)),
None,
)
.err()
.unwrap();
assert_eq!(e.retry_after(), Some(Duration::from_secs(120)));
}
#[test]
fn pagination_debug_never_prints_field_values() {
let d = Decoded {
payload: "irrelevant",
pagination: Some(Pagination {
previous: Some(918_273),
next: Some(645_129),
current: Some(837_465),
per_page: Some(192_837),
count: Some(564_738),
pages: Some(291_837),
}),
};
let out = format!("{d:?}");
for needle in ["918273", "645129", "837465", "192837", "564738", "291837"] {
assert!(!out.contains(needle), "actual: {out}");
}
assert!(out.contains("true"), "actual: {out}");
assert!(out.contains("irrelevant"), "actual: {out}");
}
#[test]
fn empty_error_is_skipped_and_description_wins() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(400).unwrap(),
Some("application/json"),
crate::test_support::FIXTURE_ERR_EMPTY_ERROR.as_bytes(),
Pricing::NotCharged,
None,
None,
)
.unwrap_err();
assert!(
e.to_string().contains("could not be reached"),
"actual: {e}"
);
}
#[test]
fn both_empty_falls_through_to_canonical_reason() {
let body = br#"{"response":null,"error":"","error_description":""}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(502).unwrap(),
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.unwrap_err();
assert!(e.to_string().contains("Bad Gateway"), "actual: {e}");
}
#[test]
fn txid_survives_on_vehicle_offline() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
crate::test_support::FIXTURE_408_OFFLINE.as_bytes(),
Pricing::data(),
None,
None,
)
.unwrap_err();
match e {
Error::VehicleOffline { txid, .. } => {
assert_eq!(txid.as_deref(), Some("432e7faaa94cf732bdda8f82f2184eea"));
}
other => panic!("should be VehicleOffline: {other:?}"),
}
}
#[test]
fn txid_falls_back_to_the_header() {
let e = decode_with_txid_header::<serde_json::Value>(
http::StatusCode::from_u16(500).unwrap(),
Some("application/json"),
br#"{"error":"boom"}"#,
Pricing::NotCharged,
None,
None,
Some("hdr-txid-123"),
)
.unwrap_err();
match e {
Error::Api { txid, .. } => assert_eq!(txid.as_deref(), Some("hdr-txid-123")),
other => panic!("should be Api: {other:?}"),
}
}
#[test]
fn txid_prefers_body_over_header_when_both_present() {
let e = decode_with_txid_header::<serde_json::Value>(
http::StatusCode::from_u16(500).unwrap(),
Some("application/json"),
br#"{"error":"boom","txid":"body-txid-wins"}"#,
Pricing::NotCharged,
None,
None,
Some("header-txid-loses"),
)
.unwrap_err();
match e {
Error::Api { txid, .. } => assert_eq!(txid.as_deref(), Some("body-txid-wins")),
other => panic!("should be Api: {other:?}"),
}
}
#[test]
fn txid_falls_back_to_the_header_when_body_txid_is_empty() {
let e = decode_with_txid_header::<serde_json::Value>(
http::StatusCode::from_u16(500).unwrap(),
Some("application/json"),
br#"{"error":"boom","txid":""}"#,
Pricing::NotCharged,
None,
None,
Some("432e7faaa94cf732bdda8f82f2184eea"),
)
.unwrap_err();
match e {
Error::Api { txid, .. } => {
assert_eq!(txid.as_deref(), Some("432e7faaa94cf732bdda8f82f2184eea"));
}
other => panic!("should be Api: {other:?}"),
}
}
#[test]
fn txid_survives_verbatim_even_when_it_is_vin_shaped() {
let body = br#"{"error":"boom","txid":"5YJ3E1EA1JF000001"}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(500).unwrap(),
Some("application/json"),
body,
Pricing::NotCharged,
None,
None,
)
.unwrap_err();
match &e {
Error::Api { txid, .. } => {
assert_eq!(txid.as_deref(), Some("5YJ3E1EA1JF000001"));
}
other => panic!("should be Api: {other:?}"),
}
assert!(
format!("{e:?}").contains("5YJ3E1EA1JF000001"),
"VIN-shaped txid must survive verbatim, not be redacted: {e:?}"
);
}
#[test]
fn txid_survives_verbatim_on_vehicle_offline_too() {
let vin_body = br#"{"error":"boom","txid":"5YJ3E1EA1JF000001"}"#;
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
vin_body,
Pricing::data(),
None,
None,
)
.unwrap_err();
match &e {
Error::VehicleOffline { txid, .. } => {
assert_eq!(txid.as_deref(), Some("5YJ3E1EA1JF000001"));
}
other => panic!("should be VehicleOffline: {other:?}"),
}
assert!(
format!("{e:?}").contains("5YJ3E1EA1JF000001"),
"VIN-shaped txid on the 408/VehicleOffline arm must survive verbatim: {e:?}"
);
let bearer_body =
br#"{"error":"boom","txid":"Bearer eyJhbGciOiJIUzI1NiJ9.raw-secret-value.sig"}"#;
let e2 = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
bearer_body,
Pricing::data(),
None,
None,
)
.unwrap_err();
match &e2 {
Error::VehicleOffline { txid, .. } => {
assert_eq!(
txid.as_deref(),
Some("Bearer eyJhbGciOiJIUzI1NiJ9.raw-secret-value.sig")
);
}
other => panic!("should be VehicleOffline: {other:?}"),
}
assert!(
format!("{e2:?}").contains("raw-secret-value"),
"Bearer/JWT-shaped txid on the 408/VehicleOffline arm must survive verbatim: {e2:?}"
);
}
#[test]
fn txid_is_not_redacted() {
let e = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
crate::test_support::FIXTURE_408_OFFLINE.as_bytes(),
Pricing::data(),
None,
None,
)
.unwrap_err();
assert!(
format!("{e:?}").contains("432e7faa"),
"the txid is gone: {e:?}"
);
}
#[test]
fn txid_never_appears_in_display_message() {
let offline = decode::<serde_json::Value>(
http::StatusCode::from_u16(408).unwrap(),
Some("application/json"),
crate::test_support::FIXTURE_408_OFFLINE.as_bytes(),
Pricing::data(),
None,
None,
)
.unwrap_err();
assert!(
!offline.to_string().contains("432e7faa"),
"txid leaked into VehicleOffline's Display: {offline}"
);
let api = decode_with_txid_header::<serde_json::Value>(
http::StatusCode::from_u16(500).unwrap(),
Some("application/json"),
br#"{"error":"boom"}"#,
Pricing::NotCharged,
None,
None,
Some("hdr-txid-123"),
)
.unwrap_err();
assert!(
!api.to_string().contains("hdr-txid-123"),
"txid leaked into Api's Display: {api}"
);
}
}