Skip to main content

saluki_components/transforms/trace_obfuscation/
mod.rs

1//! Trace obfuscation transform.
2//!
3//! Obfuscates the span data that can carry sensitive values: SQL queries, Redis, Valkey and Memcached commands, HTTP
4//! URLs, JSON query bodies, and credit card numbers. The obfuscation itself comes from a shared crate that works on
5//! Saluki's trace types through their trait implementations, so this transform only applies it to each trace.
6//!
7//! Tag replacement isn't applied here. It runs in the `trace_tag_replacer` transform, so that other steps can run
8//! between the two.
9
10use async_trait::async_trait;
11use libdd_trace_obfuscation::{
12    obfuscate::{obfuscate_chunk_attributes, obfuscate_span},
13    obfuscation_config::ObfuscationConfig,
14};
15use saluki_core::{
16    accounting::{MemoryBounds, MemoryBoundsBuilder},
17    components::{transforms::*, BuildContext},
18    data_model::event::trace::{AttributeValue, AttributeValueExt, Trace},
19    topology::EventsBuffer,
20};
21use saluki_error::GenericError;
22use stringtheory::MetaString;
23
24/// Trace obfuscation configuration.
25pub struct TraceObfuscationConfiguration {
26    config: ObfuscationConfig,
27    sql_dialect: MetaString,
28}
29
30impl TraceObfuscationConfiguration {
31    /// Creates a new `TraceObfuscationConfiguration` from the obfuscation settings.
32    ///
33    /// This transform never applies tag replacement rules: `TraceTagReplacerConfiguration` owns them, so any rules in
34    /// `config` are ignored. `sql_dialect` supplies the dialect when a span has no per-span hint.
35    pub fn new(mut config: ObfuscationConfig, sql_dialect: String) -> Self {
36        config.tag_replace_rules.clear();
37        Self {
38            config,
39            sql_dialect: sql_dialect.into(),
40        }
41    }
42}
43
44#[async_trait]
45impl SynchronousTransformBuilder for TraceObfuscationConfiguration {
46    async fn build(&self, _context: BuildContext) -> Result<Box<dyn SynchronousTransform + Send>, GenericError> {
47        Ok(Box::new(TraceObfuscation {
48            config: self.config.clone(),
49            sql_dialect: self.sql_dialect.clone(),
50        }))
51    }
52}
53
54impl MemoryBounds for TraceObfuscationConfiguration {
55    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
56        builder
57            .minimum()
58            .with_single_value::<TraceObfuscation>("component struct");
59    }
60}
61
62/// The obfuscation transform that processes traces.
63pub struct TraceObfuscation {
64    config: ObfuscationConfig,
65    sql_dialect: MetaString,
66}
67
68impl TraceObfuscation {
69    fn obfuscate_trace(&self, trace: &mut Trace) {
70        for span in trace.spans_mut() {
71            // The shared SQL obfuscator reads `db.type`. Supply the OTLP hint or configured fallback only for this call.
72            let dialect = if matches!(span.span_type(), "sql" | "cassandra") && !span.attributes.contains_key("db.type")
73            {
74                span.attributes
75                    .get("db.system")
76                    .and_then(AttributeValue::as_string)
77                    .filter(|hint| !hint.is_empty())
78                    .cloned()
79                    .or_else(|| (!self.sql_dialect.is_empty()).then(|| self.sql_dialect.clone()))
80            } else {
81                None
82            };
83            let temporary_hint = dialect.is_some();
84            if let Some(dialect) = dialect {
85                span.attributes
86                    .insert("db.type".into(), AttributeValue::String(dialect));
87            }
88            obfuscate_span(span, &self.config);
89            if temporary_hint {
90                span.attributes.remove("db.type");
91            }
92        }
93
94        // Attributes shared by every span of the trace are scrubbed too, since they are merged into each span when the
95        // trace is encoded.
96        obfuscate_chunk_attributes(trace, &self.config);
97    }
98}
99
100impl SynchronousTransform for TraceObfuscation {
101    fn transform_buffer(&mut self, buffer: &mut EventsBuffer) {
102        for trace in buffer.events_mut::<Trace>() {
103            self.obfuscate_trace(trace);
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use libdd_trace_obfuscation::{
111        json::JsonObfuscator,
112        obfuscation_config::{HttpConfig, JsonObfuscatorConfig},
113        replacer::parse_rules_from_string,
114    };
115    use saluki_common::collections::FastHashMap;
116    use saluki_core::data_model::event::trace::{AttributeValue, AttributeValueExt, Span, SpanEvent, TraceIngestInfo};
117
118    use super::*;
119
120    fn transform(config: ObfuscationConfig) -> TraceObfuscation {
121        TraceObfuscationConfiguration::new(config, String::new()).into_transform()
122    }
123
124    impl TraceObfuscationConfiguration {
125        fn into_transform(self) -> TraceObfuscation {
126            TraceObfuscation {
127                config: self.config,
128                sql_dialect: self.sql_dialect,
129            }
130        }
131    }
132
133    fn attributes(pairs: &[(&str, &str)]) -> FastHashMap<stringtheory::MetaString, AttributeValue> {
134        pairs
135            .iter()
136            .map(|(k, v)| ((*k).into(), AttributeValue::String((*v).into())))
137            .collect()
138    }
139
140    /// Runs `span` through the transform as the only span of a trace.
141    fn obfuscate(config: ObfuscationConfig, span: Span) -> Span {
142        let mut trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
143        transform(config).obfuscate_trace(&mut trace);
144        trace
145            .spans()
146            .first()
147            .cloned()
148            .expect("the span was removed from the trace")
149    }
150
151    fn attribute<'a>(span: &'a Span, key: &str) -> Option<&'a str> {
152        span.attributes
153            .get(key)
154            .and_then(AttributeValue::as_string)
155            .map(|s| &**s)
156    }
157
158    #[test]
159    fn sql_resource_is_obfuscated() {
160        let span = Span::new(
161            "svc",
162            "db.query",
163            "SELECT * FROM users WHERE id = 42",
164            "sql",
165            1,
166            0,
167            0,
168            0,
169            0,
170        );
171        let span = obfuscate(ObfuscationConfig::default(), span);
172
173        assert_eq!(span.resource(), "SELECT * FROM users WHERE id = ?");
174    }
175
176    #[test]
177    fn sql_dialect_prefers_native_then_otlp_then_configured_hints() {
178        for (pairs, fallback, expected) in [
179            (vec![], "postgresql", "SELECT doc #>> ? FROM t"),
180            (vec![("db.system", "postgresql")], "mysql", "SELECT doc #>> ? FROM t"),
181            (
182                vec![("db.type", "postgresql"), ("db.system", "mysql")],
183                "mysql",
184                "SELECT doc #>> ? FROM t",
185            ),
186            (vec![("db.type", "mysql")], "postgresql", "SELECT doc"),
187        ] {
188            let span = Span::new("svc", "query", "SELECT doc #>> '{a,b}' FROM t", "sql", 1, 0, 0, 0, 0)
189                .with_attributes(attributes(&pairs));
190            let original = span.attributes.clone();
191            let mut trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
192            TraceObfuscationConfiguration::new(ObfuscationConfig::default(), fallback.into())
193                .into_transform()
194                .obfuscate_trace(&mut trace);
195            assert_eq!(trace.spans()[0].resource(), expected, "{pairs:?}, fallback {fallback}");
196            for key in ["db.type", "db.system"] {
197                assert_eq!(
198                    trace.spans()[0].attributes.get(key),
199                    original.get(key),
200                    "dialect tag {key}"
201                );
202            }
203        }
204    }
205
206    #[test]
207    fn unparseable_sql_is_replaced_instead_of_forwarded() {
208        let span = Span::new("svc", "db.query", "#", "sql", 1, 0, 0, 0, 0);
209        let span = obfuscate(ObfuscationConfig::default(), span);
210
211        assert_eq!(span.resource(), "Non-parsable SQL query");
212    }
213
214    #[test]
215    fn redis_resource_keeps_the_first_three_commands() {
216        // At most three commands are kept, and a cut is marked with ` ...`.
217        let span = Span::new("svc", "redis.command", "SET k v\nGET k\nDEL k", "redis", 1, 0, 0, 0, 0);
218        let span = obfuscate(ObfuscationConfig::default(), span);
219
220        assert_eq!(span.resource(), "SET GET DEL ...");
221    }
222
223    #[test]
224    fn redis_raw_command_arguments_are_obfuscated() {
225        let span = Span::new("svc", "redis.command", "SET", "redis", 1, 0, 0, 0, 0)
226            .with_attributes(attributes(&[("redis.raw_command", "SET mykey secret-value")]));
227        let span = obfuscate(ObfuscationConfig::default(), span);
228
229        assert_eq!(attribute(&span, "redis.raw_command"), Some("SET mykey ?"));
230    }
231
232    #[test]
233    fn memcached_command_keeps_only_the_command_when_configured() {
234        let mut config = ObfuscationConfig::default();
235        config.memcached.keep_command = true;
236        let span = Span::new("svc", "memcached.cmd", "set", "memcached", 1, 0, 0, 0, 0)
237            .with_attributes(attributes(&[("memcached.command", "set mykey 0 60 5\r\nvalue")]));
238        let span = obfuscate(config, span);
239
240        assert_eq!(attribute(&span, "memcached.command"), Some("set mykey 0 60 5"));
241    }
242
243    fn http_span(url: &str) -> Span {
244        Span::new("svc", "http.request", "GET /x", "http", 1, 0, 0, 0, 0)
245            .with_attributes(attributes(&[("http.url", url)]))
246    }
247
248    fn obfuscated_url(url: &str, remove_query_string: bool, remove_path_digits: bool) -> String {
249        let config = ObfuscationConfig {
250            http: HttpConfig {
251                remove_query_string,
252                remove_path_digits,
253            },
254            ..Default::default()
255        };
256        let span = obfuscate(config, http_span(url));
257        attribute(&span, "http.url")
258            .expect("http.url was removed from the span")
259            .to_owned()
260    }
261
262    // A removed query string leaves a trailing `?`.
263    #[test]
264    fn http_url_query_string_and_path_digits_are_removed_when_configured() {
265        assert_eq!(
266            obfuscated_url("https://example.com/users/123/profile?token=abc", true, true),
267            "https://example.com/users/?/profile?"
268        );
269    }
270
271    // A URL that can't be parsed is redacted wholesale as soon as either option is on.
272    #[test]
273    fn unparseable_url_is_redacted_when_either_option_is_on() {
274        for url in ["https://example.com:port/x", "http://foo:bar.com/x", ":"] {
275            for (remove_query_string, remove_path_digits) in [(true, false), (false, true), (true, true)] {
276                assert_eq!(
277                    obfuscated_url(url, remove_query_string, remove_path_digits),
278                    "?",
279                    "expected wholesale redaction for {url:?}"
280                );
281            }
282        }
283    }
284
285    // With both options off the algorithm only strips userinfo, and an unparseable URL keeps everything else.
286    #[test]
287    fn unparseable_url_is_kept_when_both_options_are_off() {
288        assert_eq!(
289            obfuscated_url("https://example.com:port/x", false, false),
290            "https://example.com:port/x"
291        );
292    }
293
294    #[test]
295    fn credit_card_numbers_are_scrubbed_from_span_and_span_event_attributes() {
296        let event = SpanEvent::new(1, "exception").with_attributes(attributes(&[("card", "4111 1111 1111 1111")]));
297        let span = Span::new("svc", "op", "res", "custom", 1, 0, 0, 0, 0)
298            .with_attributes(attributes(&[
299                ("card", "4111 1111 1111 1111"),
300                ("note", "hello"),
301                // Known not to hold card numbers, although the value looks like one.
302                ("databricks_job_id", "4111111111111111"),
303            ]))
304            .with_span_events(vec![event]);
305        let span = obfuscate(ObfuscationConfig::default(), span);
306
307        assert_eq!(attribute(&span, "card"), Some("?"));
308        assert_eq!(attribute(&span, "note"), Some("hello"));
309        assert_eq!(attribute(&span, "databricks_job_id"), Some("4111111111111111"));
310        let event_card = span.span_events()[0]
311            .attributes()
312            .get("card")
313            .and_then(AttributeValue::as_string);
314        assert_eq!(event_card.map(|s| &**s), Some("?"));
315    }
316
317    #[test]
318    fn credit_card_numbers_are_scrubbed_from_trace_attributes() {
319        let mut trace = Trace::new(vec![Span::default()], TraceIngestInfo::Datadog);
320        std::sync::Arc::make_mut(&mut trace.attributes)
321            .insert("card".into(), AttributeValue::String("4111111111111111".into()));
322        transform(ObfuscationConfig::default()).obfuscate_trace(&mut trace);
323
324        let card = trace.attributes.get("card").and_then(AttributeValue::as_string);
325        assert_eq!(card.map(|s| &**s), Some("?"));
326    }
327
328    #[test]
329    fn credit_card_keep_values_are_not_scrubbed() {
330        let mut config = ObfuscationConfig::default();
331        config.credit_cards.keep_values.insert("order_ref".to_owned());
332        let span = Span::new("svc", "op", "res", "custom", 1, 0, 0, 0, 0)
333            .with_attributes(attributes(&[("order_ref", "4111111111111111")]));
334        let span = obfuscate(config, span);
335
336        assert_eq!(attribute(&span, "order_ref"), Some("4111111111111111"));
337    }
338
339    #[test]
340    fn elasticsearch_body_values_are_obfuscated() {
341        let span = Span::new("svc", "es.query", "search", "elasticsearch", 1, 0, 0, 0, 0).with_attributes(attributes(
342            &[("elasticsearch.body", r#"{"query":{"match":{"user":"alice"}}}"#)],
343        ));
344        let span = obfuscate(ObfuscationConfig::default(), span);
345
346        assert_eq!(
347            attribute(&span, "elasticsearch.body"),
348            Some(r#"{"query":{"match":{"user":"?"}}}"#)
349        );
350    }
351
352    // Replacement rules are applied by `trace_tag_replacer`, so this transform must leave them alone.
353    #[test]
354    fn tag_replacement_rules_are_not_applied_by_this_transform() {
355        let rules = parse_rules_from_string(r#"[{"name":"secret","pattern":".*","repl":"?"}]"#).unwrap();
356        let config = ObfuscationConfig {
357            tag_replace_rules: rules,
358            ..Default::default()
359        };
360        let span = Span::new("svc", "op", "res", "custom", 1, 0, 0, 0, 0)
361            .with_attributes(attributes(&[("secret", "hunter2")]));
362        let span = obfuscate(config, span);
363
364        assert_eq!(attribute(&span, "secret"), Some("hunter2"));
365    }
366
367    // The following tests record expected behavior that isn't implemented yet. They assert that behavior, so they fail
368    // today and are ignored. Remove the `ignore` once they pass.
369
370    // The raw query attributes are obfuscated along with the resource.
371    #[test]
372    #[ignore = "not implemented yet: db.statement and db.query.text are left unobfuscated (DataDog/libdatadog#2923)"]
373    fn sql_query_attributes_are_obfuscated_with_the_resource() {
374        let query = "SELECT * FROM users WHERE id = 42";
375        let span = Span::new("svc", "db.query", query, "sql", 1, 0, 0, 0, 0)
376            .with_attributes(attributes(&[("db.statement", query), ("db.query.text", query)]));
377        let span = obfuscate(ObfuscationConfig::default(), span);
378
379        assert_eq!(
380            attribute(&span, "db.statement"),
381            Some("SELECT * FROM users WHERE id = ?")
382        );
383        assert_eq!(
384            attribute(&span, "db.query.text"),
385            Some("SELECT * FROM users WHERE id = ?")
386        );
387        assert_eq!(attribute(&span, "sql.query"), None, "sql.query is not added");
388    }
389
390    // The tables a query uses are reported in `sql.tables`.
391    #[test]
392    #[ignore = "not implemented yet: table names aren't extracted (DataDog/libdatadog#2922)"]
393    fn sql_table_names_are_reported() {
394        let span = Span::new(
395            "svc",
396            "db.query",
397            "SELECT * FROM users JOIN orders ON users.id = 1",
398            "sql",
399            1,
400            0,
401            0,
402            0,
403            0,
404        );
405        let span = obfuscate(ObfuscationConfig::default(), span);
406
407        assert_eq!(attribute(&span, "sql.tables"), Some("users,orders"));
408    }
409
410    // Values under `obfuscate_sql_values` keys are obfuscated as SQL. The span-level obfuscation replaces the whole value
411    // with `?` instead.
412    #[test]
413    #[ignore = "not implemented yet: JSON values under transform keys aren't obfuscated as SQL"]
414    fn json_values_under_transform_keys_are_obfuscated_as_sql() {
415        let config = ObfuscationConfig {
416            elasticsearch: JsonObfuscator::new(JsonObfuscatorConfig {
417                enabled: true,
418                keep_keys: Default::default(),
419                transform_keys: ["query".to_owned()].into_iter().collect(),
420            }),
421            ..Default::default()
422        };
423        let span = Span::new("svc", "es.query", "search", "elasticsearch", 1, 0, 0, 0, 0).with_attributes(attributes(
424            &[("elasticsearch.body", r#"{"query":"SELECT * FROM t WHERE id = 7"}"#)],
425        ));
426        let span = obfuscate(config, span);
427
428        assert_eq!(
429            attribute(&span, "elasticsearch.body"),
430            Some(r#"{"query":"SELECT * FROM t WHERE id = ?"}"#)
431        );
432    }
433}