Skip to main content

smithy4rs_core/serde/
debug.rs

1//! Utilities for implementing [`Debug`] for generated shapes
2//!
3//! Smithy shape debug implementations are similar to the default
4//! implementation derived by the `Debug` macro. However, unlike
5//! the default implementation the Smithy implementations must respect
6//! the `@sensitive` trait. Fields and structures with this trait should
7//! _always_ be redacted when written to a string in order to avoid leaking
8//! sensitive info into logs and API responses.
9//!
10//! ## Derived Debug Implementations
11//!
12//! The `SmithyShape` derive macro will automatically derive a `Debug` implementation
13//! for Smithy Shapes.
14//!
15use core::fmt;
16use std::fmt::{Debug, DebugList, DebugMap, DebugStruct, Display, Error, Formatter};
17
18use log::error;
19use thiserror::Error;
20
21use crate::{
22    BigDecimal, BigInt, ByteBuffer, Instant,
23    schema::{Document, SchemaRef, SmithyTrait, prelude::SensitiveTrait},
24    serde::{
25        debug::FmtError::Custom,
26        se::{ListSerializer, MapSerializer, SerializeWithSchema, Serializer, StructSerializer},
27    },
28};
29// ============================================================================
30// Wrapper
31// ============================================================================
32
33/// Wrapper struct used to adapt debug implementations to use schema-base serialization
34///
35/// This class should not be used directly by users. Instead, users should use generated
36/// `Debug` implementation for shapes.
37pub struct DebugWrapper<'a, T: SerializeWithSchema>(&'a SchemaRef, &'a T);
38impl<'a, T: SerializeWithSchema> DebugWrapper<'a, T> {
39    /// Construct a new Debug wrapper to format type `T` using the provided schema.
40    pub const fn new(schema: &'a SchemaRef, value: &'a T) -> Self {
41        DebugWrapper(schema, value)
42    }
43}
44impl<T: SerializeWithSchema> Debug for DebugWrapper<'_, T> {
45    #[inline]
46    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
47        self.1
48            .serialize_with_schema(self.0, DebugSerializer { fmt })
49            .map_err(|e| {
50                error!("Encountered error while printing debug repr: {}", e);
51                Error
52            })
53    }
54}
55
56// ============================================================================
57// Errors
58// ============================================================================
59
60/// Errors that can occur when serializing a shape into a string representation
61#[derive(Error, Debug)]
62#[doc(hidden)]
63pub enum FmtError {
64    #[error(transparent)]
65    Fmt(#[from] Error),
66    #[error("Expected Member Schema but found: {0}")]
67    ExpectedMember(String),
68    #[error("Formatting error: {0}")]
69    Custom(String),
70}
71use crate::serde::se::Error as SerdeError;
72impl SerdeError for FmtError {
73    fn custom<T>(msg: T) -> Self
74    where
75        T: Display,
76    {
77        Custom(msg.to_string())
78    }
79}
80
81// ============================================================================
82// Debug Serializer
83// ============================================================================
84
85macro_rules! redact {
86    ($self:ident, $schema:ident, $value:ident) => {
87        if $schema.contains_type::<SensitiveTrait>() {
88            $self.fmt.write_str(REDACTED_ITEM)?;
89        } else {
90            Debug::fmt(&$value, $self.fmt)?;
91        }
92    };
93}
94
95/// Serializer used to generate `Debug` implementations that respect `@sensitive` fields.
96struct DebugSerializer<'a, 'b: 'a> {
97    fmt: &'a mut Formatter<'b>,
98}
99const REDACTED_ITEM: &str = "**REDACTED**";
100const REDACTED_LIST: &str = "[**REDACTED**]";
101const REDACTED_MAP: &str = "{**REDACTED**}";
102
103impl<'a, 'b> Serializer for DebugSerializer<'a, 'b> {
104    type Error = FmtError;
105    type Ok = ();
106    type SerializeList = DebugListSerializer<'a, 'b>;
107    type SerializeMap = DebugMapSerializer<'a, 'b>;
108    type SerializeStruct = DebugStructSerializer<'a, 'b>;
109
110    fn write_struct(
111        self,
112        schema: &SchemaRef,
113        _: usize,
114    ) -> Result<Self::SerializeStruct, Self::Error> {
115        if schema.contains_type::<SensitiveTrait>() {
116            self.fmt.write_str(schema.id().name())?;
117            // Replace entire structure contents with redacted placeholder
118            self.fmt.write_str(REDACTED_MAP)?;
119            Ok(DebugStructSerializer::Redacted)
120        } else {
121            Ok(DebugStructSerializer::Unredacted(
122                self.fmt.debug_struct(schema.id().name()),
123            ))
124        }
125    }
126
127    fn write_map(self, schema: &SchemaRef, _: usize) -> Result<Self::SerializeMap, Self::Error> {
128        if schema.contains_type::<SensitiveTrait>() {
129            // Replace entire map with redacted placeholder
130            self.fmt.write_str(REDACTED_MAP)?;
131            Ok(DebugMapSerializer::Redacted)
132        } else {
133            Ok(DebugMapSerializer::Unredacted(self.fmt.debug_map()))
134        }
135    }
136
137    fn write_list(self, schema: &SchemaRef, _: usize) -> Result<Self::SerializeList, Self::Error> {
138        if schema.contains_type::<SensitiveTrait>() {
139            // Replace entire list with redacted placeholder
140            self.fmt.write_str(REDACTED_LIST)?;
141            Ok(DebugListSerializer::Redacted)
142        } else {
143            Ok(DebugListSerializer::Unredacted(self.fmt.debug_list()))
144        }
145    }
146
147    #[inline]
148    fn write_boolean(self, schema: &SchemaRef, value: bool) -> Result<Self::Ok, Self::Error> {
149        redact!(self, schema, value);
150        Ok(())
151    }
152
153    #[inline]
154    fn write_byte(self, schema: &SchemaRef, value: i8) -> Result<Self::Ok, Self::Error> {
155        redact!(self, schema, value);
156        Ok(())
157    }
158
159    #[inline]
160    fn write_short(self, schema: &SchemaRef, value: i16) -> Result<Self::Ok, Self::Error> {
161        redact!(self, schema, value);
162        Ok(())
163    }
164
165    #[inline]
166    fn write_integer(self, schema: &SchemaRef, value: i32) -> Result<Self::Ok, Self::Error> {
167        redact!(self, schema, value);
168        Ok(())
169    }
170
171    #[inline]
172    fn write_long(self, schema: &SchemaRef, value: i64) -> Result<Self::Ok, Self::Error> {
173        redact!(self, schema, value);
174        Ok(())
175    }
176
177    #[inline]
178    fn write_float(self, schema: &SchemaRef, value: f32) -> Result<Self::Ok, Self::Error> {
179        redact!(self, schema, value);
180        Ok(())
181    }
182
183    #[inline]
184    fn write_double(self, schema: &SchemaRef, value: f64) -> Result<Self::Ok, Self::Error> {
185        redact!(self, schema, value);
186        Ok(())
187    }
188
189    #[inline]
190    fn write_big_integer(
191        self,
192        schema: &SchemaRef,
193        value: &BigInt,
194    ) -> Result<Self::Ok, Self::Error> {
195        redact!(self, schema, value);
196        Ok(())
197    }
198
199    #[inline]
200    fn write_big_decimal(
201        self,
202        schema: &SchemaRef,
203        value: &BigDecimal,
204    ) -> Result<Self::Ok, Self::Error> {
205        redact!(self, schema, value);
206        Ok(())
207    }
208
209    #[inline]
210    fn write_string(self, schema: &SchemaRef, value: &str) -> Result<Self::Ok, Self::Error> {
211        redact!(self, schema, value);
212        Ok(())
213    }
214
215    #[inline]
216    fn write_blob(self, schema: &SchemaRef, value: &ByteBuffer) -> Result<Self::Ok, Self::Error> {
217        redact!(self, schema, value);
218        Ok(())
219    }
220
221    #[inline]
222    fn write_timestamp(self, schema: &SchemaRef, value: &Instant) -> Result<Self::Ok, Self::Error> {
223        redact!(self, schema, value);
224        Ok(())
225    }
226
227    #[inline]
228    fn write_document(
229        self,
230        schema: &SchemaRef,
231        value: &Box<dyn Document>,
232    ) -> Result<Self::Ok, Self::Error> {
233        redact!(self, schema, value);
234        Ok(())
235    }
236
237    #[inline]
238    fn write_null(self, _schema: &SchemaRef) -> Result<Self::Ok, Self::Error> {
239        self.fmt.write_str("null")?;
240        Ok(())
241    }
242
243    #[inline]
244    fn skip(self, _schema: &SchemaRef) -> Result<Self::Ok, Self::Error> {
245        Ok(())
246    }
247}
248
249enum DebugListSerializer<'a, 'b: 'a> {
250    Unredacted(DebugList<'a, 'b>),
251    Redacted,
252}
253impl ListSerializer for DebugListSerializer<'_, '_> {
254    type Error = FmtError;
255    type Ok = ();
256
257    fn serialize_element<T>(
258        &mut self,
259        element_schema: &SchemaRef,
260        value: &T,
261    ) -> Result<(), Self::Error>
262    where
263        T: SerializeWithSchema,
264    {
265        let DebugListSerializer::Unredacted(inner) = self else {
266            // Redacted lists do not write any entries.
267            return Ok(());
268        };
269        inner.entry(&DebugWrapper::new(element_schema, value));
270        Ok(())
271    }
272
273    #[inline]
274    fn end(self, _: &SchemaRef) -> Result<Self::Ok, Self::Error> {
275        if let DebugListSerializer::Unredacted(mut inner) = self {
276            inner.finish()?;
277        }
278        Ok(())
279    }
280}
281
282enum DebugMapSerializer<'a, 'b: 'a> {
283    Unredacted(DebugMap<'a, 'b>),
284    Redacted,
285}
286
287impl MapSerializer for DebugMapSerializer<'_, '_> {
288    type Error = FmtError;
289    type Ok = ();
290
291    fn serialize_entry<K, V>(
292        &mut self,
293        key_schema: &SchemaRef,
294        value_schema: &SchemaRef,
295        key: &K,
296        value: &V,
297    ) -> Result<(), Self::Error>
298    where
299        K: SerializeWithSchema,
300        V: SerializeWithSchema,
301    {
302        let DebugMapSerializer::Unredacted(inner) = self else {
303            // Redacted lists do not write any entries.
304            return Ok(());
305        };
306        inner.entry(
307            &DebugWrapper::new(key_schema, key),
308            &DebugWrapper::new(value_schema, value),
309        );
310        Ok(())
311    }
312
313    #[inline]
314    fn end(self, _: &SchemaRef) -> Result<Self::Ok, Self::Error> {
315        if let DebugMapSerializer::Unredacted(mut inner) = self {
316            inner.finish()?;
317        }
318        Ok(())
319    }
320}
321
322enum DebugStructSerializer<'a, 'b: 'a> {
323    Unredacted(DebugStruct<'a, 'b>),
324    Redacted,
325}
326
327impl StructSerializer for DebugStructSerializer<'_, '_> {
328    type Error = FmtError;
329    type Ok = ();
330
331    fn serialize_member<T>(
332        &mut self,
333        member_schema: &SchemaRef,
334        value: &T,
335    ) -> Result<(), Self::Error>
336    where
337        T: SerializeWithSchema,
338    {
339        let DebugStructSerializer::Unredacted(inner) = self else {
340            // Redacted lists do not write any entries.
341            return Ok(());
342        };
343        let Some(me) = member_schema.as_member() else {
344            return Err(FmtError::ExpectedMember(format!(
345                "{:?}",
346                member_schema.id()
347            )));
348        };
349        inner.field(me.name.as_str(), &DebugWrapper::new(member_schema, value));
350        Ok(())
351    }
352
353    fn serialize_member_named<T>(
354        &mut self,
355        member_name: &str,
356        member_schema: &SchemaRef,
357        value: &T,
358    ) -> Result<(), Self::Error>
359    where
360        T: SerializeWithSchema,
361    {
362        let DebugStructSerializer::Unredacted(inner) = self else {
363            // Redacted lists do not write any entries.
364            return Ok(());
365        };
366        inner.field(member_name, &DebugWrapper(member_schema, value));
367        Ok(())
368    }
369
370    #[inline]
371    fn end(self, _: &SchemaRef) -> Result<Self::Ok, Self::Error> {
372        if let DebugStructSerializer::Unredacted(mut inner) = self {
373            inner.finish()?;
374        }
375        Ok(())
376    }
377}
378
379// ============================================================================
380// Type impls
381// ============================================================================
382impl Debug for Box<dyn Document> {
383    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
384        let mut s = f.debug_struct("Document");
385        s.field("schema", &self.schema());
386        s.field("value", &DebugWrapper::new(self.schema(), self));
387        self.discriminator()
388            .map(|v| s.field("discriminator", &v.id()));
389        s.finish()
390    }
391}
392
393impl Debug for dyn SmithyTrait {
394    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
395        let mut s = f.debug_tuple(self.id().id());
396        // Only print document value if it is non-null.
397        if !&self.value().is_null() {
398            // Use the debug wrapper to avoid writing document wrapper info into the trait debug.
399            s.field(&DebugWrapper::new(self.value().schema(), self.value()));
400        }
401        s.finish()
402    }
403}
404
405#[cfg(test)]
406mod tests {
407
408    use super::*;
409    use crate::{
410        IndexMap,
411        derive::SmithyShape,
412        schema::prelude::{MediaTypeTrait, STRING},
413        smithy,
414    };
415
416    smithy!("com.example#Map": {
417        map MAP_SCHEMA {
418            key: STRING
419            value: STRING
420        }
421    });
422    smithy!("com.example#List": {
423        list LIST_SCHEMA {
424            member: STRING
425        }
426    });
427    smithy!("com.example#Shape": {
428        structure SCHEMA {
429            A: STRING = "a"
430            @SensitiveTrait;
431            B: STRING = "b"
432            C: STRING = "c"
433            MAP: MAP_SCHEMA = "map"
434            LIST: LIST_SCHEMA = "list"
435        }
436    });
437    smithy!("com.example#Shape": {
438        structure REDACTED_AGGREGATES {
439            @SensitiveTrait;
440            MAP_REDACT: MAP_SCHEMA = "map"
441            @SensitiveTrait;
442            @MediaTypeTrait::new("application/json");
443            LIST_REDACT: LIST_SCHEMA = "list"
444        }
445    });
446
447    #[derive(SmithyShape)]
448    #[smithy_schema(SCHEMA)]
449    pub struct SerializeMe {
450        #[smithy_schema(A)]
451        pub member_a: String,
452        #[smithy_schema(B)]
453        pub member_b: String,
454        #[smithy_schema(C)]
455        pub member_optional: Option<String>,
456        #[smithy_schema(LIST)]
457        pub member_list: Vec<String>,
458        #[smithy_schema(MAP)]
459        pub member_map: IndexMap<String, String>,
460    }
461
462    #[derive(SmithyShape)]
463    #[smithy_schema(REDACTED_AGGREGATES)]
464    pub struct RedactMe {
465        #[smithy_schema(LIST_REDACT)]
466        pub member_list: Vec<String>,
467        #[smithy_schema(MAP_REDACT)]
468        pub member_map: IndexMap<String, String>,
469    }
470
471    #[test]
472    fn debug_prints_shape() {
473        let mut map = IndexMap::new();
474        map.insert(String::from("a"), String::from("b"));
475        let list = vec!["a".to_string(), "b".to_string()];
476        let struct_to_write = SerializeMe {
477            member_a: "a".to_string(),
478            member_b: "b".to_string(),
479            member_optional: Some("c".to_string()),
480            member_map: map,
481            member_list: list,
482        };
483        assert_eq!(
484            format!("{struct_to_write:?}"),
485            "Shape { member_a: \"a\", member_b: **REDACTED**, member_optional: \"c\", member_list: [\"a\", \"b\"], member_map: {\"a\": \"b\"} }"
486        );
487    }
488
489    #[test]
490    fn debug_respects_pretty_print() {
491        let mut map = IndexMap::new();
492        map.insert(String::from("a"), String::from("b"));
493        let list = vec!["a".to_string(), "b".to_string()];
494        let struct_to_write = SerializeMe {
495            member_a: "a".to_string(),
496            member_b: "b".to_string(),
497            member_optional: Some("c".to_string()),
498            member_map: map,
499            member_list: list,
500        };
501        assert_eq!(
502            format!("{struct_to_write:#?}"),
503            r#"Shape {
504    member_a: "a",
505    member_b: **REDACTED**,
506    member_optional: "c",
507    member_list: [
508        "a",
509        "b",
510    ],
511    member_map: {
512        "a": "b",
513    },
514}"#
515        );
516    }
517
518    #[test]
519    fn redacts_aggregates() {
520        let mut map = IndexMap::new();
521        map.insert(String::from("a"), String::from("b"));
522        let list = vec!["a".to_string(), "b".to_string()];
523        let struct_to_write = RedactMe {
524            member_list: list,
525            member_map: map,
526        };
527        let output = format!("{struct_to_write:?}");
528        assert_eq!(
529            output,
530            "Shape { member_list: [**REDACTED**], member_map: {**REDACTED**} }"
531        );
532    }
533
534    #[test]
535    fn document_conversion_retains_redaction() {
536        let mut map = IndexMap::new();
537        map.insert(String::from("a"), String::from("b"));
538        let list = vec!["a".to_string(), "b".to_string()];
539        let struct_to_write = RedactMe {
540            member_list: list,
541            member_map: map,
542        };
543        let document: Box<dyn Document> = struct_to_write.into();
544        let output = format!("{document:#?}");
545        let expected = r#"Document {
546    schema: StructSchema {
547        shape_type: Structure,
548        id: "com.example#Shape",
549        traits: [],
550        members: {
551            "map": {
552                "target": "com.example#Map",
553                "traits": [
554                    smithy.api#sensitive,
555                ],
556            },
557            "list": {
558                "target": "com.example#List",
559                "traits": [
560                    smithy.api#mediaType(
561                        "application/json",
562                    ),
563                    smithy.api#sensitive,
564                ],
565            },
566        },
567    },
568    value: Shape {
569        list: [**REDACTED**],
570        map: {**REDACTED**},
571    },
572    discriminator: "com.example#Shape",
573}"#;
574        assert_eq!(output, expected);
575    }
576}