structured_proxy/transcode/error.rs
1//! gRPC → HTTP error mapping.
2//!
3//! Converts `tonic::Status` to appropriate HTTP status codes and JSON error bodies
4//! following the gRPC-HTTP status code mapping from the gRPC specification, and
5//! renders the typed `google.rpc.Status` details the upstream attached in the
6//! `grpc-status-details-bin` trailer.
7
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Response};
10use axum::Json;
11use base64::Engine as _;
12use globset::GlobMatcher;
13use prost::Message as _;
14use prost_reflect::{
15 Cardinality, DescriptorPool, DynamicMessage, Kind, MessageDescriptor, ReflectMessage,
16 SerializeOptions, Value as PbValue,
17};
18use serde_json::{Map, Value};
19
20/// Full name of `google.rpc.DebugInfo`. It carries stack traces and server
21/// internals meant for the service's operators, so it never reaches an HTTP
22/// client.
23const DEBUG_INFO: &str = "google.rpc.DebugInfo";
24
25/// Map a gRPC status code to the corresponding HTTP status code.
26///
27/// Based on <https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md>
28pub fn grpc_to_http_status(code: tonic::Code) -> StatusCode {
29 match code {
30 tonic::Code::Ok => StatusCode::OK,
31 tonic::Code::Cancelled => StatusCode::from_u16(499).unwrap_or(StatusCode::BAD_REQUEST),
32 tonic::Code::Unknown => StatusCode::INTERNAL_SERVER_ERROR,
33 tonic::Code::InvalidArgument => StatusCode::BAD_REQUEST,
34 tonic::Code::DeadlineExceeded => StatusCode::GATEWAY_TIMEOUT,
35 tonic::Code::NotFound => StatusCode::NOT_FOUND,
36 tonic::Code::AlreadyExists => StatusCode::CONFLICT,
37 tonic::Code::PermissionDenied => StatusCode::FORBIDDEN,
38 tonic::Code::ResourceExhausted => StatusCode::TOO_MANY_REQUESTS,
39 tonic::Code::FailedPrecondition => StatusCode::BAD_REQUEST,
40 tonic::Code::Aborted => StatusCode::CONFLICT,
41 tonic::Code::OutOfRange => StatusCode::BAD_REQUEST,
42 tonic::Code::Unimplemented => StatusCode::NOT_IMPLEMENTED,
43 tonic::Code::Internal => StatusCode::INTERNAL_SERVER_ERROR,
44 tonic::Code::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
45 tonic::Code::DataLoss => StatusCode::INTERNAL_SERVER_ERROR,
46 tonic::Code::Unauthenticated => StatusCode::UNAUTHORIZED,
47 }
48}
49
50/// Message of the `INTERNAL` a client gets instead of an upstream error whose
51/// details cannot be rendered faithfully. The cause stays in the proxy's log.
52const MALFORMED_STATUS_MESSAGE: &str = "upstream returned a malformed error status";
53
54/// An upstream error status whose details cannot be rendered faithfully: a
55/// trailer that is not a `google.rpc.Status`, or a detail of a known type whose
56/// bytes do not decode or whose value has no valid JSON form. Its cause is
57/// logged where it is detected.
58#[derive(Debug)]
59struct MalformedStatus;
60
61/// Convert a `tonic::Status` into an axum HTTP response with a JSON error body
62/// `{"error", "message", "code"}`, without status details.
63///
64/// Use [`status_to_response_with_details`] to also render the upstream's
65/// `google.rpc.Status` details.
66pub fn status_to_response(status: tonic::Status) -> Response {
67 status_to_response_with_details(&status, None)
68}
69
70/// Convert a `tonic::Status` into an axum HTTP response with a JSON error body.
71///
72/// The body is `{"error", "message", "code"}`, plus a `details` array when
73/// `details` is given (see [`error_body`]). The HTTP status follows the code the
74/// body reports, so a malformed upstream status answers 500.
75pub fn status_to_response_with_details(
76 status: &tonic::Status,
77 details: Option<&StatusDetails>,
78) -> Response {
79 let (code, body) = render(status, details);
80 (grpc_to_http_status(code), Json(body)).into_response()
81}
82
83/// The JSON error body for a failed call, shared by the unary response and the
84/// terminal frame of a stream so a client parses one shape everywhere.
85///
86/// `error` is the gRPC code name, `code` its number and `message` the status
87/// message. With `details`, the body also carries `details`: the upstream's
88/// `google.rpc.Status.details` in proto3 JSON form (empty when the upstream sent
89/// none), plus `opaqueDetails` for details whose type no descriptor describes
90/// when the renderer forwards them ([`StatusDetails::with_opaque_details`]);
91/// without it, both keys are absent and the trailer is not read. When the
92/// details cannot be rendered faithfully the whole body is a generic `INTERNAL`
93/// instead, never a partial or reinterpreted set of details.
94pub fn error_body(status: &tonic::Status, details: Option<&StatusDetails>) -> Value {
95 render(status, details).1
96}
97
98/// The error body and the gRPC code it reports: the upstream's own, or
99/// `INTERNAL` when its details cannot be rendered faithfully.
100fn render(status: &tonic::Status, details: Option<&StatusDetails>) -> (tonic::Code, Value) {
101 let Some(details) = details else {
102 return (status.code(), body(status.code(), status.message(), None));
103 };
104 match details.render(status) {
105 Ok(rendered) => (
106 status.code(),
107 body(status.code(), status.message(), Some(rendered)),
108 ),
109 Err(MalformedStatus) => (
110 tonic::Code::Internal,
111 body(
112 tonic::Code::Internal,
113 MALFORMED_STATUS_MESSAGE,
114 Some(RenderedDetails::default()),
115 ),
116 ),
117 }
118}
119
120/// `opaqueDetails` appears only when a detail went to the extension, so a
121/// client that does not handle it sees nothing new otherwise.
122fn body(code: tonic::Code, message: &str, details: Option<RenderedDetails>) -> Value {
123 let mut body = Map::with_capacity(5);
124 body.insert("error".into(), grpc_code_name(code).into());
125 body.insert("message".into(), message.into());
126 body.insert("code".into(), (code as i32).into());
127 if let Some(rendered) = details {
128 body.insert("details".into(), Value::Array(rendered.details));
129 if !rendered.opaque.is_empty() {
130 body.insert("opaqueDetails".into(), Value::Array(rendered.opaque));
131 }
132 }
133 Value::Object(body)
134}
135
136/// Human-readable gRPC code name for JSON error responses.
137pub(crate) fn grpc_code_name(code: tonic::Code) -> &'static str {
138 match code {
139 tonic::Code::Ok => "OK",
140 tonic::Code::Cancelled => "CANCELLED",
141 tonic::Code::Unknown => "UNKNOWN",
142 tonic::Code::InvalidArgument => "INVALID_ARGUMENT",
143 tonic::Code::DeadlineExceeded => "DEADLINE_EXCEEDED",
144 tonic::Code::NotFound => "NOT_FOUND",
145 tonic::Code::AlreadyExists => "ALREADY_EXISTS",
146 tonic::Code::PermissionDenied => "PERMISSION_DENIED",
147 tonic::Code::ResourceExhausted => "RESOURCE_EXHAUSTED",
148 tonic::Code::FailedPrecondition => "FAILED_PRECONDITION",
149 tonic::Code::Aborted => "ABORTED",
150 tonic::Code::OutOfRange => "OUT_OF_RANGE",
151 tonic::Code::Unimplemented => "UNIMPLEMENTED",
152 tonic::Code::Internal => "INTERNAL",
153 tonic::Code::Unavailable => "UNAVAILABLE",
154 tonic::Code::DataLoss => "DATA_LOSS",
155 tonic::Code::Unauthenticated => "UNAUTHENTICATED",
156 }
157}
158
159/// Which routes return `details` in their error bodies.
160///
161/// A global switch plus per-route overrides, checked in the order they were
162/// added: the first whose pattern matches the route decides. A pattern is a
163/// glob over the mounted route path, where `*` stays within one segment and
164/// `**` spans segments; every path parameter counts as one segment, so
165/// `/v1/users/*` matches the route `/v1/users/{id}`. Decided once per route
166/// when the router is built, so a request pays nothing for it.
167///
168/// # Examples
169///
170/// ```
171/// use structured_proxy::transcode::error::ErrorDetailsPolicy;
172///
173/// // Details everywhere except the internal admin surface.
174/// let policy = ErrorDetailsPolicy::default()
175/// .route("/v1/admin/**", false)
176/// .unwrap();
177/// assert!(policy.enabled_for("/v1/users/{id}"));
178/// assert!(!policy.enabled_for("/v1/admin/users/{id}"));
179///
180/// // Off by default, back on for one sub-route.
181/// let policy = ErrorDetailsPolicy::disabled()
182/// .route("/v1/public/**", true)
183/// .unwrap();
184/// assert!(!policy.enabled_for("/v1/users/{id}"));
185/// assert!(policy.enabled_for("/v1/public/items"));
186///
187/// // The opaque-detail extension, off unless switched on, here for one route.
188/// let policy = ErrorDetailsPolicy::default()
189/// .opaque_route("/v1/partner/**", true)
190/// .unwrap();
191/// assert!(!policy.opaque_for("/v1/users/{id}"));
192/// assert!(policy.opaque_for("/v1/partner/orders"));
193/// ```
194#[derive(Debug, Clone)]
195pub struct ErrorDetailsPolicy {
196 enabled: bool,
197 opaque: bool,
198 routes: Vec<RouteRule>,
199}
200
201/// One override: a route glob and the switches it sets. A switch it leaves
202/// `None` is decided by a later rule or the global value.
203#[derive(Debug, Clone)]
204struct RouteRule {
205 matcher: GlobMatcher,
206 enabled: Option<bool>,
207 opaque: Option<bool>,
208}
209
210impl ErrorDetailsPolicy {
211 /// No details on any route, until a [`route`](Self::route) switches them on.
212 pub fn disabled() -> Self {
213 Self {
214 enabled: false,
215 opaque: false,
216 routes: Vec::new(),
217 }
218 }
219
220 /// Add an override for the routes `pattern` matches, checked after the
221 /// ones added before it.
222 ///
223 /// # Errors
224 ///
225 /// A pattern that does not start with `/` (it could never match a route)
226 /// or is not a valid glob.
227 pub fn route(self, pattern: &str, enabled: bool) -> Result<Self, String> {
228 self.rule(pattern, Some(enabled), None)
229 }
230
231 /// Set, for every route without an override, whether a detail whose type
232 /// no descriptor describes goes to `opaqueDetails` (see
233 /// [`StatusDetails::with_opaque_details`]). Off by default: such bytes
234 /// cannot be checked for a nested DebugInfo.
235 pub fn with_opaque_details(mut self, enabled: bool) -> Self {
236 self.opaque = enabled;
237 self
238 }
239
240 /// Add an override of the opaque-detail extension for the routes `pattern`
241 /// matches, checked after the ones added before it.
242 ///
243 /// # Errors
244 ///
245 /// As [`route`](Self::route).
246 pub fn opaque_route(self, pattern: &str, enabled: bool) -> Result<Self, String> {
247 self.rule(pattern, None, Some(enabled))
248 }
249
250 /// Add an override setting either switch or both; the first matching rule
251 /// that sets a switch decides it.
252 ///
253 /// # Errors
254 ///
255 /// As [`route`](Self::route).
256 pub(crate) fn rule(
257 mut self,
258 pattern: &str,
259 enabled: Option<bool>,
260 opaque: Option<bool>,
261 ) -> Result<Self, String> {
262 // Route paths always start with `/`; a relative pattern is a
263 // missing-slash typo that would silently never apply.
264 if !pattern.starts_with('/') {
265 return Err(format!(
266 "error details route pattern {pattern:?} must start with '/'"
267 ));
268 }
269 self.routes.push(RouteRule {
270 matcher: crate::shield::matcher::path_glob(pattern)?,
271 enabled,
272 opaque,
273 });
274 Ok(self)
275 }
276
277 /// Whether the route mounted at `route_path` (axum form, e.g.
278 /// `/v1/users/{id}`) returns details: the first matching rule that sets
279 /// it decides, otherwise the global switch.
280 pub fn enabled_for(&self, route_path: &str) -> bool {
281 self.decide(route_path, |rule| rule.enabled)
282 .unwrap_or(self.enabled)
283 }
284
285 /// Whether the route mounted at `route_path` forwards details of unknown
286 /// types in `opaqueDetails`: the first matching rule that sets it decides,
287 /// otherwise the global switch.
288 pub fn opaque_for(&self, route_path: &str) -> bool {
289 self.decide(route_path, |rule| rule.opaque)
290 .unwrap_or(self.opaque)
291 }
292
293 fn decide(
294 &self,
295 route_path: &str,
296 switch: impl Fn(&RouteRule) -> Option<bool>,
297 ) -> Option<bool> {
298 self.routes
299 .iter()
300 .filter_map(|rule| switch(rule).map(|value| (rule, value)))
301 .find(|(rule, _)| rule.matcher.is_match(route_path))
302 .map(|(_, value)| value)
303 }
304}
305
306impl Default for ErrorDetailsPolicy {
307 /// Details on every route, the opaque-detail extension off.
308 fn default() -> Self {
309 Self {
310 enabled: true,
311 opaque: false,
312 routes: Vec::new(),
313 }
314 }
315}
316
317/// Whether `full_name` is a well-known type with a special ProtoJSON
318/// representation, which an `Any` carries under `value`
319/// (<https://protobuf.dev/programming-guides/json/#any>). The same set
320/// prost-reflect wraps when it serializes an `Any`.
321fn has_special_json(full_name: &str) -> bool {
322 matches!(
323 full_name,
324 "google.protobuf.Any"
325 | "google.protobuf.Timestamp"
326 | "google.protobuf.Duration"
327 | "google.protobuf.Struct"
328 | "google.protobuf.FloatValue"
329 | "google.protobuf.DoubleValue"
330 | "google.protobuf.Int32Value"
331 | "google.protobuf.Int64Value"
332 | "google.protobuf.UInt32Value"
333 | "google.protobuf.UInt64Value"
334 | "google.protobuf.BoolValue"
335 | "google.protobuf.StringValue"
336 | "google.protobuf.BytesValue"
337 | "google.protobuf.FieldMask"
338 | "google.protobuf.ListValue"
339 | "google.protobuf.Value"
340 | "google.protobuf.Empty"
341 )
342}
343
344/// Full name of `google.protobuf.Any`.
345const ANY: &str = "google.protobuf.Any";
346
347/// The type name an `Any.type_url` names, or `None` when the URL is malformed.
348///
349/// The URL must contain a `/`, and the part after the last one is the type's
350/// full name (`google/protobuf/any.proto`). Anything else (a bare name, a
351/// trailing `/`, a query suffix, an empty segment) could disguise a
352/// DebugInfo, so callers refuse the whole status on `None`.
353fn any_type_name(type_url: &str) -> Option<&str> {
354 let (_, name) = type_url.rsplit_once('/')?;
355 is_full_name(name).then_some(name)
356}
357
358/// Whether `name` is a protobuf full name: dot-separated identifiers, each a
359/// letter or `_` followed by letters, digits or `_`.
360fn is_full_name(name: &str) -> bool {
361 !name.is_empty()
362 && name.split('.').all(|part| {
363 let mut chars = part.chars();
364 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
365 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
366 })
367}
368
369/// The rendered details of one status.
370#[derive(Debug, Default)]
371struct RenderedDetails {
372 /// ProtoJSON `Any` entries, in upstream order.
373 details: Vec<Value>,
374 /// Opaque-detail extension entries, in upstream order.
375 opaque: Vec<Value>,
376}
377
378/// An entry of the structured-proxy opaque-detail extension, for a detail whose
379/// type no descriptor describes: `{"index", "typeUrl", "bytes"}`, where `index`
380/// is its position among the forwarded details (so merging `details` and
381/// `opaqueDetails` by position restores the upstream order), `typeUrl` the
382/// original type URL and `bytes` the standard base64 of the original bytes.
383/// It carries no `@type` and lives outside `details`, so it cannot be taken for
384/// a ProtoJSON `Any`.
385fn opaque_entry(index: usize, type_url: &str, value: &[u8]) -> Value {
386 let mut out = Map::with_capacity(3);
387 out.insert("index".into(), index.into());
388 out.insert("typeUrl".into(), type_url.into());
389 out.insert(
390 "bytes".into(),
391 base64::engine::general_purpose::STANDARD
392 .encode(value)
393 .into(),
394 );
395 Value::Object(out)
396}
397
398/// Add to `pool` every top-level message and enum of `canonical` it does not
399/// define, per type rather than per file.
400///
401/// A product may define some canonical types itself: in a file of another name,
402/// or in its own revision of the canonical file holding only a subset. Those
403/// definitions win. The canonical types it lacks still go in, through a copy
404/// of the canonical file renamed under `structured-proxy/canonical/` and
405/// reduced to the missing types; the copy also imports the product files that
406/// define the types it dropped, so its references resolve to the product's
407/// revisions.
408fn complete_with_canonical(pool: &mut DescriptorPool, canonical: &DescriptorPool) {
409 use std::collections::{BTreeSet, HashMap};
410
411 // Canonical file name → the pool files that now provide its types in its
412 // place (its renamed copy, product files defining some of them). A file
413 // importing it imports those instead.
414 let mut stand_ins: HashMap<String, BTreeSet<String>> = HashMap::new();
415 // `files()` lists dependencies before their dependents, so each file finds
416 // its imports already merged.
417 for file in canonical.files() {
418 let mut proto = file.file_descriptor_proto().clone();
419 let package = proto.package().to_owned();
420 let full = |name: &str| {
421 if package.is_empty() {
422 name.to_owned()
423 } else {
424 format!("{package}.{name}")
425 }
426 };
427 // Files of the pool that already define a type of this file.
428 let mut defining_files = BTreeSet::new();
429 proto.message_type.retain(|message| {
430 match pool.get_message_by_name(&full(message.name())) {
431 Some(existing) => {
432 defining_files.insert(existing.parent_file().name().to_owned());
433 false
434 }
435 None => true,
436 }
437 });
438 proto
439 .enum_type
440 .retain(|en| match pool.get_enum_by_name(&full(en.name())) {
441 Some(existing) => {
442 defining_files.insert(existing.parent_file().name().to_owned());
443 false
444 }
445 None => true,
446 });
447 let everything_present = proto.message_type.is_empty() && proto.enum_type.is_empty();
448 let file_present = pool.get_file_by_name(file.name()).is_some();
449 if everything_present {
450 // Typically the very same file. When the types live in files of
451 // other names, importers of this one import those instead.
452 if !file_present {
453 stand_ins.insert(file.name().to_owned(), defining_files);
454 }
455 continue;
456 }
457 // A copy that leaves types out, or whose name the product already uses,
458 // goes in under its own name; importers then need it plus the product
459 // files that define the rest.
460 let renamed = !defining_files.is_empty() || file_present;
461 let mut provided_by = defining_files.clone();
462 if renamed {
463 let name = format!("structured-proxy/canonical/{}", file.name());
464 proto.name = Some(name.clone());
465 provided_by.insert(name);
466 }
467 let mut dependencies = BTreeSet::new();
468 for dep in &proto.dependency {
469 match stand_ins.get(dep) {
470 Some(files) => {
471 // A product revision of the dependency stays importable
472 // next to the copy that completes it.
473 if pool.get_file_by_name(dep).is_some() {
474 dependencies.insert(dep.clone());
475 }
476 dependencies.extend(files.iter().cloned());
477 }
478 None => {
479 dependencies.insert(dep.clone());
480 }
481 }
482 }
483 dependencies.extend(defining_files);
484 proto.dependency = dependencies.into_iter().collect();
485 // Indexes into the old dependency list; nothing here needs them.
486 proto.public_dependency.clear();
487 proto.weak_dependency.clear();
488 proto.source_code_info = None;
489 match pool.add_file_descriptor_proto(proto) {
490 Ok(()) => {
491 if renamed {
492 stand_ins.insert(file.name().to_owned(), provided_by);
493 }
494 }
495 Err(e) => {
496 tracing::debug!(file = %file.name(), "canonical descriptor not merged: {e}");
497 }
498 }
499 }
500}
501
502/// Renders the typed details of a gRPC status (`grpc-status-details-bin`) as
503/// proto3 JSON.
504///
505/// Detail types resolve in one pool: the product descriptors, completed with
506/// the well-known types and the canonical `google/rpc/status.proto` and
507/// `error_details.proto` for whatever the product does not define itself. A
508/// service's own detail messages (and its own `google.rpc` revision) render as
509/// it defines them, the canonical ones are always available even when the
510/// product descriptors do not import them, and a type packed inside another
511/// detail resolves from the same pool as the detail itself.
512///
513/// Details use the canonical proto3 JSON mapping (unset fields omitted, 64-bit
514/// integers as strings), the form clients of the `google.rpc` model expect.
515#[derive(Debug, Clone)]
516pub struct StatusDetails {
517 pool: DescriptorPool,
518 opaque: bool,
519}
520
521impl StatusDetails {
522 /// Build a renderer over `product`, completed with the canonical
523 /// descriptors it lacks. The opaque-detail extension starts off.
524 pub fn new(product: &DescriptorPool) -> Self {
525 let mut canonical = DescriptorPool::global();
526 canonical
527 .decode_file_descriptor_set(tonic_types::pb::FILE_DESCRIPTOR_SET)
528 .expect("tonic-types ships a valid google.rpc descriptor set");
529 let mut pool = product.clone();
530 complete_with_canonical(&mut pool, &canonical);
531 Self {
532 pool,
533 opaque: false,
534 }
535 }
536
537 /// Whether a detail whose type no descriptor describes goes to
538 /// `opaqueDetails` (see [`opaque_entry`]) instead of being withheld. Its
539 /// bytes cannot be inspected, so a DebugInfo it carries in a field would
540 /// reach the client: switch it on only for upstreams trusted not to nest
541 /// one in types the proxy has no descriptor for.
542 pub fn with_opaque_details(mut self, enabled: bool) -> Self {
543 self.opaque = enabled;
544 self
545 }
546
547 /// The details of `status`, `google.rpc.DebugInfo` left out.
548 ///
549 /// A detail whose type resolves goes to `details` in its ProtoJSON `Any`
550 /// form: `@type` plus the message fields, or `@type` plus `value` for a
551 /// well-known type with a special JSON representation. A type no descriptor
552 /// describes has no ProtoJSON form (the mapping requires the type) and its
553 /// bytes cannot be checked for a DebugInfo, so it is withheld, or goes to
554 /// the opaque-detail extension (see [`opaque_entry`]) when switched on.
555 ///
556 /// # Errors
557 ///
558 /// [`MalformedStatus`] when the trailer is not a `google.rpc.Status`, or a
559 /// detail of a known type does not decode or has no valid JSON form. Such a
560 /// detail is never passed on as opaque bytes, since that would present a
561 /// broken value as an unknown one.
562 fn render(&self, status: &tonic::Status) -> Result<RenderedDetails, MalformedStatus> {
563 let mut rendered = RenderedDetails::default();
564 let raw = status.details();
565 if raw.is_empty() {
566 return Ok(rendered);
567 }
568 let decoded = tonic_types::pb::Status::decode(raw).map_err(|e| {
569 tracing::error!("malformed grpc-status-details-bin trailer: {e}");
570 MalformedStatus
571 })?;
572 // The trailer must describe the same error as grpc-status and
573 // grpc-message (gRPC richer error model); otherwise its details would
574 // be attached to an error they were not written for.
575 if decoded.code != status.code() as i32 || decoded.message != status.message() {
576 tracing::error!(
577 trailer_code = decoded.code,
578 status_code = status.code() as i32,
579 "grpc-status-details-bin disagrees with grpc-status / grpc-message"
580 );
581 return Err(MalformedStatus);
582 }
583 rendered.details.reserve(decoded.details.len());
584 // Position among the forwarded details: DebugInfo takes no index, so
585 // the numbering does not reveal that one was withheld.
586 let mut index = 0usize;
587 for any in &decoded.details {
588 let type_url = any.type_url.as_str();
589 let Some(type_name) = any_type_name(type_url) else {
590 tracing::error!(%type_url, "error detail with a malformed type URL");
591 return Err(MalformedStatus);
592 };
593 if type_name == DEBUG_INFO {
594 continue;
595 }
596 match self.resolve(type_name) {
597 Some(desc) => match self.typed_entry(type_url, type_name, desc, &any.value)? {
598 Some(entry) => rendered.details.push(entry),
599 // An Any detail packing DebugInfo, withheld like a direct one.
600 None => continue,
601 },
602 None if self.opaque => {
603 rendered
604 .opaque
605 .push(opaque_entry(index, type_url, &any.value));
606 }
607 None => {
608 tracing::debug!(%type_url, "error detail of an unknown type withheld");
609 continue;
610 }
611 }
612 index += 1;
613 }
614 Ok(rendered)
615 }
616
617 /// The ProtoJSON `Any` form of a detail whose type resolved, with every
618 /// DebugInfo packed inside it removed; `None` when the detail is itself an
619 /// `Any` packing a DebugInfo.
620 fn typed_entry(
621 &self,
622 type_url: &str,
623 type_name: &str,
624 desc: MessageDescriptor,
625 value: &[u8],
626 ) -> Result<Option<Value>, MalformedStatus> {
627 // ProtoJSON puts a well-known type with a special JSON representation
628 // under `value` whatever that JSON looks like (a Struct is an object,
629 // yet still wrapped), so the choice follows the type, not the shape.
630 // Empty is one of them (JSON `{}` in the ProtoJSON table), as in Go's
631 // protojson and prost-reflect, so it is wrapped too.
632 let wrapped = has_special_json(desc.full_name());
633 let mut msg = DynamicMessage::decode(desc, value).map_err(|e| {
634 tracing::error!(detail = %type_name, "undecodable error detail: {e}");
635 MalformedStatus
636 })?;
637 if self.scrub(&mut msg)?.is_none() {
638 return Ok(None);
639 }
640 let json = msg
641 .serialize_with_options(serde_json::value::Serializer, &SerializeOptions::new())
642 .map_err(|e| {
643 tracing::error!(detail = %type_name, "error detail has no valid JSON form: {e}");
644 MalformedStatus
645 })?;
646 let mut out = Map::new();
647 out.insert("@type".into(), type_url.into());
648 match json {
649 Value::Object(fields) if !wrapped => {
650 // A field whose JSON name is `@type` would replace the Any's
651 // own type URL, and there is no faithful ProtoJSON form for it.
652 if fields.contains_key("@type") {
653 tracing::error!(detail = %type_name, "error detail has a field named @type");
654 return Err(MalformedStatus);
655 }
656 out.extend(fields);
657 }
658 other => {
659 out.insert("value".into(), other);
660 }
661 }
662 Ok(Some(Value::Object(out)))
663 }
664
665 fn resolve(&self, type_name: &str) -> Option<MessageDescriptor> {
666 self.pool.get_message_by_name(type_name)
667 }
668
669 /// Remove every DebugInfo anywhere below `msg`: a message field typed as
670 /// DebugInfo, or an `Any` packing one, whether singular, repeated or a map
671 /// value. Only the message types decide, so data such as a `Struct` key
672 /// named `@type` is never mistaken for one. Returns `None` when `msg` is
673 /// itself a DebugInfo or an `Any` packing one (the caller drops it),
674 /// otherwise whether anything changed. A message missing a proto2
675 /// `required` field is [`MalformedStatus`]: decoding accepts it, but it has
676 /// no valid ProtoJSON form.
677 fn scrub(&self, msg: &mut DynamicMessage) -> Result<Option<bool>, MalformedStatus> {
678 let desc = msg.descriptor();
679 if desc.full_name() == ANY {
680 return self.scrub_any(msg);
681 }
682 if desc.full_name() == DEBUG_INFO {
683 return Ok(None);
684 }
685 for field in desc.fields() {
686 if field.cardinality() == Cardinality::Required && !msg.has_field(&field) {
687 tracing::error!(
688 message = %desc.full_name(),
689 field = %field.name(),
690 "error detail lacks a required field"
691 );
692 return Err(MalformedStatus);
693 }
694 }
695 let mut changed = false;
696 let mut dropped_fields = Vec::new();
697 for (field, value) in msg.fields_mut() {
698 if !matches!(field.kind(), Kind::Message(_)) {
699 continue;
700 }
701 if !self.scrub_value(value, &mut changed)? {
702 // A proto2 `required` field cannot be cleared without making
703 // the message invalid, so the whole message goes instead.
704 if field.cardinality() == Cardinality::Required {
705 return Ok(None);
706 }
707 dropped_fields.push(field);
708 }
709 }
710 // Extensions are not among the message's own fields, yet ProtoJSON
711 // renders them (as `[full.name]`), so they are scrubbed the same way.
712 let mut dropped_extensions = Vec::new();
713 for (extension, value) in msg.extensions_mut() {
714 if !matches!(extension.kind(), Kind::Message(_)) {
715 continue;
716 }
717 if !self.scrub_value(value, &mut changed)? {
718 dropped_extensions.push(extension);
719 }
720 }
721 for field in dropped_fields {
722 msg.clear_field(&field);
723 changed = true;
724 }
725 for extension in dropped_extensions {
726 msg.clear_extension(&extension);
727 changed = true;
728 }
729 Ok(Some(changed))
730 }
731
732 /// [`scrub`](Self::scrub) applied to one set field or extension value:
733 /// repeated elements and map entries that must go are removed in place.
734 /// Returns `false` when the value is a singular message that must go, so
735 /// the caller clears the field.
736 fn scrub_value(
737 &self,
738 value: &mut PbValue,
739 changed: &mut bool,
740 ) -> Result<bool, MalformedStatus> {
741 match value {
742 PbValue::Message(inner) => match self.scrub(inner)? {
743 Some(inner_changed) => *changed |= inner_changed,
744 None => return Ok(false),
745 },
746 PbValue::List(items) => {
747 let before = items.len();
748 let mut failed = None;
749 items.retain_mut(|item| match item {
750 PbValue::Message(inner) if failed.is_none() => match self.scrub(inner) {
751 Ok(Some(inner_changed)) => {
752 *changed |= inner_changed;
753 true
754 }
755 Ok(None) => false,
756 Err(e) => {
757 failed = Some(e);
758 true
759 }
760 },
761 _ => true,
762 });
763 if let Some(e) = failed {
764 return Err(e);
765 }
766 *changed |= items.len() != before;
767 }
768 PbValue::Map(entries) => {
769 let mut dropped = Vec::new();
770 for (key, value) in entries.iter_mut() {
771 if let PbValue::Message(inner) = value {
772 match self.scrub(inner)? {
773 Some(inner_changed) => *changed |= inner_changed,
774 None => dropped.push(key.clone()),
775 }
776 }
777 }
778 for key in dropped {
779 entries.remove(&key);
780 *changed = true;
781 }
782 }
783 _ => {}
784 }
785 Ok(true)
786 }
787
788 /// [`scrub`](Self::scrub) for an `Any`: its type URL is checked like a
789 /// top-level detail's, a DebugInfo is reported for dropping, and a packed
790 /// message of a known type is scrubbed and re-packed if it changed.
791 fn scrub_any(&self, any: &mut DynamicMessage) -> Result<Option<bool>, MalformedStatus> {
792 let type_url = match any.get_field_by_name("type_url").as_deref() {
793 Some(PbValue::String(url)) => url.clone(),
794 _ => String::new(),
795 };
796 let Some(type_name) = any_type_name(&type_url) else {
797 tracing::error!(%type_url, "packed Any with a malformed type URL");
798 return Err(MalformedStatus);
799 };
800 if type_name == DEBUG_INFO {
801 return Ok(None);
802 }
803 // An unknown packed type has no JSON form; serialization reports it.
804 let Some(desc) = self.resolve(type_name) else {
805 return Ok(Some(false));
806 };
807 let bytes = match any.get_field_by_name("value").as_deref() {
808 Some(PbValue::Bytes(bytes)) => bytes.clone(),
809 _ => Default::default(),
810 };
811 let mut inner = DynamicMessage::decode(desc, bytes).map_err(|e| {
812 tracing::error!(detail = %type_name, "undecodable packed Any: {e}");
813 MalformedStatus
814 })?;
815 match self.scrub(&mut inner)? {
816 None => Ok(None),
817 Some(false) => Ok(Some(false)),
818 Some(true) => {
819 any.set_field_by_name("value", PbValue::Bytes(inner.encode_to_vec().into()));
820 Ok(Some(true))
821 }
822 }
823 }
824}
825
826#[cfg(test)]
827mod tests;