Skip to main content

datadog_agent_config/
env_decode.rs

1//! Decode a raw environment-variable string into the JSON shape the schema declares for a leaf.
2//!
3//! The Datadog Agent turns an environment string into a typed value in one place
4//! (`insertNodeFromString`): a registered per-key transformer when the schema names an
5//! `env_parser`, otherwise a cast against the key's default type. This module ports both halves so
6//! ADP can build a resolved view of real JSON arrays, objects, numbers, and booleans at each
7//! nested path, which a single ordinary deserialization then reads.
8//!
9//! Supported splitting and delimiter behavior matches the Agent bug-for-bug (see the per-function
10//! notes, which cite the Agent source). Error handling deliberately diverges: the Agent logs a malformed
11//! value and substitutes an empty result, while this module propagates a hard error so the caller
12//! can reject the value instead of silently losing it. [`crate::cast_de`] notes the one exception.
13//!
14//! The scalar type fallbacks are the string half of [`crate::cast_de`], which every configuration
15//! source shares, so an environment variable and a file accept the same spellings for a leaf.
16//!
17//! One type is intentionally left as a string: a `Duration` leaf keeps its raw text and is parsed by
18//! `crate::duration_de` at deserialize time, because a duration also arrives from the file (a Go
19//! duration string) and from the Agent stream (integer nanoseconds), so that leaf must stay
20//! shape-tolerant regardless of the environment.
21
22use serde_json::{Map, Number, Value};
23
24use crate::cast_de;
25
26/// How to decode a raw environment string into a JSON value for one leaf.
27///
28/// The named-parser variants mirror the schema's `env_parser`, and the type fallbacks are the casts
29/// the Agent applies when no `env_parser` is declared, keyed by the leaf's declared type. The
30/// remaining variants are for Saluki-only keys, which have no Agent cast to match; the Datadog table
31/// never uses them.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum EnvDecode {
34    /// `env_parser: json`: parse the string as a JSON document.
35    Json,
36    /// `env_parser: comma_separated`: split on `,`, no trimming.
37    CommaSeparated,
38    /// `env_parser: comma_and_space_separated`: split on `,` or space, dropping empties.
39    CommaAndSpaceSeparated,
40    /// `env_parser: comma_then_space_separated`: split on `,` if present else space, trimmed.
41    CommaThenSpaceSeparated,
42    /// `env_parser: csv_comma_separated`: the first CSV record, with leading spaces trimmed and lazy quotes.
43    CsvCommaSeparated,
44    /// `env_parser: json_list_or_comma_separated`: a `[...]` JSON list, else split on `,`.
45    JsonListOrCommaSeparated,
46    /// `env_parser: json_list_or_space_separated`: a `[...]` JSON list, else split on space.
47    JsonListOrSpaceSeparated,
48    /// `env_parser: traces_span`: `svc|op=rate,...` into a `{name: rate}` object.
49    TracesSpan,
50    /// Type fallback: a plain string, taken verbatim.
51    RawString,
52    /// Type fallback: a boolean, parsed with Go's `strconv.ParseBool` grammar.
53    Bool,
54    /// Type fallback: a signed integer, in Go's `strconv.ParseInt` base-0 grammar (the Agent's `int`
55    /// cast): optional sign, `0x`/`0o`/`0b` prefixes, a leading `0` as octal, and `_` separators.
56    Integer,
57    /// Type fallback: a finite floating-point number, in Go's `strconv.ParseFloat` grammar.
58    Float,
59    /// Type fallback: a string list (the Agent's `[]string` cast). A JSON array of strings or `null`
60    /// is decoded as JSON; anything else is split on whitespace.
61    StringList,
62    /// Type fallback: a duration, carried through as a string for `crate::duration_de`.
63    DurationString,
64    /// Type fallback: a map/object (or any non-scalar), parsed as a JSON document.
65    JsonValue,
66    /// Saluki-only: a signed decimal integer, optionally followed by an all-zero fraction. A leading
67    /// `0` is decimal.
68    DecimalInteger,
69    /// Saluki-only: a decimal floating-point number, with no `_` separators or hexadecimal form.
70    DecimalFloat,
71    /// Saluki-only: a string list split on whitespace, with no JSON form.
72    WhitespaceList,
73}
74
75/// Decodes `raw` into the JSON value `how` prescribes.
76///
77/// # Errors
78///
79/// Returns a human-readable message when `raw` is malformed for `how` (invalid JSON, a bad boolean
80/// or number, or a `traces_span` token that is not `name=rate`). The caller pairs it with the
81/// environment variable name.
82pub fn decode(raw: &str, how: EnvDecode) -> Result<Value, String> {
83    match how {
84        EnvDecode::Json | EnvDecode::JsonValue => parse_json(raw),
85        EnvDecode::CommaSeparated => Ok(comma_separated(raw)),
86        EnvDecode::CommaAndSpaceSeparated => Ok(comma_and_space_separated(raw)),
87        EnvDecode::CommaThenSpaceSeparated => Ok(comma_then_space_separated(raw)),
88        EnvDecode::CsvCommaSeparated => Ok(string_array(csv_comma_separated(raw))),
89        EnvDecode::JsonListOrCommaSeparated => json_list_or_split(raw, ','),
90        EnvDecode::JsonListOrSpaceSeparated => json_list_or_split(raw, ' '),
91        EnvDecode::TracesSpan => traces_span(raw),
92        EnvDecode::RawString | EnvDecode::DurationString => Ok(Value::String(raw.to_string())),
93        EnvDecode::Bool => cast_de::parse_bool(raw).map(Value::Bool),
94        EnvDecode::Integer => cast_de::parse_i64(raw).map(|n| Value::Number(n.into())),
95        EnvDecode::Float => cast_de::parse_f64(raw).map(finite_number),
96        EnvDecode::StringList => Ok(string_array(cast_de::parse_string_list(raw))),
97        EnvDecode::DecimalInteger => cast_de::parse_decimal_i64(raw).map(|n| Value::Number(n.into())),
98        EnvDecode::DecimalFloat => cast_de::parse_decimal_f64(raw).map(finite_number),
99        EnvDecode::WhitespaceList => Ok(string_array(raw.split_whitespace())),
100    }
101}
102
103/// `env_parser: json` and the map/object type fallback (`ParseEnvJSON`, `config.go:734`).
104///
105/// The Agent decodes into the declared type; we parse to a generic `Value` and let the leaf's
106/// own deserializer enforce its shape. A parse error propagates (the Agent logs and yields the zero
107/// value).
108fn parse_json(raw: &str) -> Result<Value, String> {
109    serde_json::from_str(raw).map_err(|e| format!("invalid JSON: {e}"))
110}
111
112/// `env_parser: comma_separated` (`ParseEnvSplitComma`, `config.go:704`).
113///
114/// `strings.Split` on `,` with no trimming; an empty string yields an empty list (the Agent's
115/// explicit special case), not a one-element list containing `""`.
116fn comma_separated(raw: &str) -> Value {
117    if raw.is_empty() {
118        return Value::Array(Vec::new());
119    }
120    string_array(raw.split(','))
121}
122
123/// `env_parser: comma_and_space_separated` (`ParseEnvSplitCommaAndSpace`, `helper/env.go:87`).
124///
125/// `strings.FieldsFunc` on `,` or space: consecutive separators collapse and empty fields are
126/// dropped.
127fn comma_and_space_separated(raw: &str) -> Value {
128    string_array(raw.split([',', ' ']).filter(|s| !s.is_empty()))
129}
130
131/// `env_parser: comma_then_space_separated` (`ParseEnvSplitCommaThenSpace`, `helper/env.go:99`).
132///
133/// If the string contains a comma, split on commas only; otherwise split on spaces. Each element is
134/// trimmed, and empties are kept (`strings.Split` semantics), so `a,,b` yields three elements.
135fn comma_then_space_separated(raw: &str) -> Value {
136    let sep = if raw.contains(',') { ',' } else { ' ' };
137    string_array(raw.split(sep).map(str::trim))
138}
139
140/// `env_parser: csv_comma_separated` (`ParseEnvCSVSplit`, `helper/env.go:69`).
141///
142/// The first record of `encoding/csv` with `TrimLeadingSpace` and `LazyQuotes` set, ported from
143/// `Reader.readRecord`:
144///
145/// - Lines end at `\n`, and `\r\n` reads as `\n`. Empty lines before the record are skipped, and an
146///   input with no record yields an empty list (the Agent logs `EOF` and yields an empty list).
147/// - Leading whitespace is trimmed from every field. An unquoted field runs to the next `,` or the
148///   end of the line, and keeps any `"` it contains.
149/// - A field starting with `"` is quoted: `""` reads as `"`, the field ends at a `"` followed by
150///   `,` or the end of the line, any other `"` is kept, and the field may span lines. A quoted field
151///   that never closes runs to the end of the input.
152///
153/// With lazy quotes, `encoding/csv` has no other error for a first record, so this can't fail.
154fn csv_comma_separated(raw: &str) -> Vec<String> {
155    // `readLine` reads `\r\n` as `\n`, and drops a `\r` that ends the input.
156    let normalized = raw.replace("\r\n", "\n");
157    let mut lines = normalized
158        .strip_suffix('\r')
159        .unwrap_or(&normalized)
160        .split_inclusive('\n');
161
162    // Skip the empty lines before the record.
163    let Some(mut line) = lines.find(|line| *line != "\n") else {
164        return Vec::new();
165    };
166
167    let mut fields = Vec::new();
168    loop {
169        line = line.trim_start();
170        if !line.starts_with('"') {
171            match line.split_once(',') {
172                Some((field, rest)) => {
173                    fields.push(field.to_string());
174                    line = rest;
175                    continue;
176                }
177                None => {
178                    fields.push(line.strip_suffix('\n').unwrap_or(line).to_string());
179                    return fields;
180                }
181            }
182        }
183
184        // A quoted field.
185        line = &line[1..];
186        let mut field = String::new();
187        loop {
188            if let Some((before, after)) = line.split_once('"') {
189                field.push_str(before);
190                line = after;
191                if let Some(rest) = line.strip_prefix('"') {
192                    field.push('"');
193                    line = rest;
194                } else if let Some(rest) = line.strip_prefix(',') {
195                    fields.push(field);
196                    line = rest;
197                    break;
198                } else if line.is_empty() || line == "\n" {
199                    fields.push(field);
200                    return fields;
201                } else {
202                    field.push('"');
203                }
204            } else if !line.is_empty() {
205                field.push_str(line);
206                line = lines.next().unwrap_or("");
207            } else {
208                fields.push(field);
209                return fields;
210            }
211        }
212    }
213}
214
215/// `env_parser: json_list_or_{comma,space}_separated` (`jsonOrSplitBy`, `helper/env.go:120`).
216///
217/// A value delimited by `[` and `]` is parsed as a JSON string list, where a `null` element is an
218/// empty string as in Go's `json.Unmarshal`; anything else is split on `sep`. The input is trimmed
219/// before the `[...]` test. A JSON list that fails to parse propagates an error (the Agent logs and
220/// yields nil).
221fn json_list_or_split(raw: &str, sep: char) -> Result<Value, String> {
222    let trimmed = raw.trim();
223    if trimmed.starts_with('[') && trimmed.ends_with(']') {
224        let list: Vec<Option<String>> =
225            serde_json::from_str(trimmed).map_err(|e| format!("invalid JSON string list: {e}"))?;
226        return Ok(string_array(list.into_iter().map(Option::unwrap_or_default)));
227    }
228    Ok(string_array(trimmed.split(sep)))
229}
230
231/// `env_parser: traces_span` (`parseAnalyzedSpans`, `helper/env.go:35`).
232///
233/// `service|operation=rate,...` into `{ "service|operation": rate }`. An empty string yields an
234/// empty object; a token that is not `name=rate` with a numeric rate propagates an error.
235fn traces_span(raw: &str) -> Result<Value, String> {
236    let mut map = Map::new();
237    if raw.is_empty() {
238        return Ok(Value::Object(map));
239    }
240    for token in raw.split(',') {
241        let (name, rate) = token
242            .split_once('=')
243            .ok_or_else(|| format!("bad traces_span token `{token}`: expected name=rate"))?;
244        // Unlike `parse_f64`, the Agent's `strconv.ParseFloat` here does not trim whitespace.
245        let rate = Some(rate)
246            .filter(|rate| rate.trim() == *rate)
247            .and_then(|rate| cast_de::parse_f64(rate).ok())
248            .ok_or_else(|| format!("bad traces_span rate in `{token}`"))?;
249        map.insert(name.to_string(), finite_number(rate));
250    }
251    Ok(Value::Object(map))
252}
253
254/// A JSON number for a float the `cast_de` parsers accepted, which they guarantee is finite.
255fn finite_number(parsed: f64) -> Value {
256    Value::Number(Number::from_f64(parsed).expect("a finite float is a JSON number"))
257}
258
259/// Collects strings into a JSON array of strings.
260fn string_array<S: AsRef<str>, I: IntoIterator<Item = S>>(items: I) -> Value {
261    Value::Array(
262        items
263            .into_iter()
264            .map(|s| Value::String(s.as_ref().to_string()))
265            .collect(),
266    )
267}
268
269#[cfg(test)]
270mod tests {
271    use serde_json::json;
272
273    use super::*;
274
275    fn arr(items: &[&str]) -> Value {
276        json!(items)
277    }
278
279    #[test]
280    fn json_parses_arbitrary_documents() {
281        assert_eq!(decode(r#"["a","b"]"#, EnvDecode::Json).unwrap(), arr(&["a", "b"]));
282        assert_eq!(
283            decode(r#"{"k":["v"]}"#, EnvDecode::JsonValue).unwrap(),
284            json!({"k": ["v"]})
285        );
286        assert!(decode("{bad", EnvDecode::Json).is_err());
287    }
288
289    #[test]
290    fn comma_separated_does_not_trim() {
291        assert_eq!(decode("a, b", EnvDecode::CommaSeparated).unwrap(), arr(&["a", " b"]));
292        assert_eq!(decode("", EnvDecode::CommaSeparated).unwrap(), Value::Array(vec![]));
293    }
294
295    #[test]
296    fn comma_and_space_drops_empties() {
297        assert_eq!(
298            decode("a, b c,,d", EnvDecode::CommaAndSpaceSeparated).unwrap(),
299            arr(&["a", "b", "c", "d"])
300        );
301    }
302
303    #[test]
304    fn comma_then_space_keeps_empties_and_trims() {
305        assert_eq!(
306            decode("a,,b", EnvDecode::CommaThenSpaceSeparated).unwrap(),
307            arr(&["a", "", "b"])
308        );
309        assert_eq!(
310            decode("a b  c", EnvDecode::CommaThenSpaceSeparated).unwrap(),
311            arr(&["a", "b", "", "c"])
312        );
313    }
314
315    #[test]
316    fn csv_comma_separated_reads_the_first_record_like_encoding_csv() {
317        // Expected values are the output of Go's `encoding/csv` with the Agent's reader settings.
318        let cases: &[(&str, &[&str])] = &[
319            ("", &[]),
320            ("\n\n", &[]),
321            ("a", &["a"]),
322            ("a, b ,  c", &["a", "b ", "c"]),
323            (
324                "(GET|POST) /healthcheck,GET /ping",
325                &["(GET|POST) /healthcheck", "GET /ping"],
326            ),
327            (r#""a,b",c"#, &["a,b", "c"]),
328            (r#""a""b",c"#, &["a\"b", "c"]),
329            (r#"a"b,c"#, &["a\"b", "c"]),
330            (r#""a"b,c"#, &["a\"b,c"]),
331            (r#""a" ,b"#, &["a\" ,b"]),
332            (r#""unterminated,x"#, &["unterminated,x"]),
333            ("a\nb", &["a"]),
334            ("\n\na,b\nc", &["a", "b"]),
335            ("\"a\nb\",c", &["a\nb", "c"]),
336            ("a,b\r\n", &["a", "b"]),
337            ("a,b\r", &["a", "b"]),
338            ("a,\n", &["a", ""]),
339            (r#""a","#, &["a", ""]),
340            ("  ", &[""]),
341            ("\u{a0}a,\tb", &["a", "b"]),
342        ];
343        for (raw, expected) in cases {
344            assert_eq!(
345                decode(raw, EnvDecode::CsvCommaSeparated).unwrap(),
346                arr(expected),
347                "{raw:?}"
348            );
349        }
350    }
351
352    #[test]
353    fn json_list_or_comma_takes_either_branch() {
354        assert_eq!(
355            decode(r#"  ["a","b"] "#, EnvDecode::JsonListOrCommaSeparated).unwrap(),
356            arr(&["a", "b"])
357        );
358        assert_eq!(
359            decode("a,b", EnvDecode::JsonListOrCommaSeparated).unwrap(),
360            arr(&["a", "b"])
361        );
362        assert!(decode("[bad", EnvDecode::JsonListOrCommaSeparated).is_ok()); // no closing ], so split
363        assert!(decode(r#"["unterminated"#, EnvDecode::JsonListOrCommaSeparated).is_ok());
364        assert!(decode("[1,2]", EnvDecode::JsonListOrCommaSeparated).is_err()); // JSON list of non-strings
365    }
366
367    #[test]
368    fn json_list_reads_a_null_element_as_an_empty_string() {
369        assert_eq!(
370            decode(r#"["a",null]"#, EnvDecode::JsonListOrSpaceSeparated).unwrap(),
371            arr(&["a", ""])
372        );
373    }
374
375    #[test]
376    fn json_list_or_space_splits_on_space() {
377        assert_eq!(
378            decode("a b", EnvDecode::JsonListOrSpaceSeparated).unwrap(),
379            arr(&["a", "b"])
380        );
381    }
382
383    #[test]
384    fn traces_span_builds_a_rate_map() {
385        assert_eq!(
386            decode("svc|op=0.5,other|op2=1", EnvDecode::TracesSpan).unwrap(),
387            json!({ "svc|op": 0.5, "other|op2": 1.0 })
388        );
389        assert_eq!(
390            decode("svc|op=0x1p-1,other|op2=1_0", EnvDecode::TracesSpan).unwrap(),
391            json!({ "svc|op": 0.5, "other|op2": 10.0 })
392        );
393        assert_eq!(decode("", EnvDecode::TracesSpan).unwrap(), json!({}));
394        assert!(decode("svc|op", EnvDecode::TracesSpan).is_err());
395        assert!(decode("svc|op=notnum", EnvDecode::TracesSpan).is_err());
396        assert!(decode("svc|op= 0.5", EnvDecode::TracesSpan).is_err());
397    }
398
399    #[test]
400    fn scalar_fallbacks() {
401        assert_eq!(decode("hello", EnvDecode::RawString).unwrap(), json!("hello"));
402        assert_eq!(decode("true", EnvDecode::Bool).unwrap(), json!(true));
403        assert_eq!(decode("T", EnvDecode::Bool).unwrap(), json!(true));
404        assert!(decode("yes", EnvDecode::Bool).is_err());
405        assert_eq!(decode("9125", EnvDecode::Integer).unwrap(), json!(9125));
406        assert_eq!(decode("9125.0", EnvDecode::Integer).unwrap(), json!(9125));
407        assert!(decode("9125.5", EnvDecode::Integer).is_err());
408        assert_eq!(decode("1.5", EnvDecode::Float).unwrap(), json!(1.5));
409    }
410
411    #[test]
412    fn string_list_follows_the_go_slice_cast() {
413        for (raw, expected) in cast_de::STRING_LIST_CASES {
414            assert_eq!(decode(raw, EnvDecode::StringList).unwrap(), arr(expected), "{raw:?}");
415        }
416    }
417
418    #[test]
419    fn integer_reads_the_go_base_prefixes() {
420        for (raw, expected) in [
421            ("0x10", 16),
422            ("010", 8),
423            ("0b11", 3),
424            ("0o17", 15),
425            ("1_000", 1000),
426            ("-0x10", -16),
427        ] {
428            assert_eq!(decode(raw, EnvDecode::Integer).unwrap(), json!(expected), "{raw}");
429        }
430        // An invalid octal digit reads as 0, as with the Agent's integer getter.
431        assert_eq!(decode("08", EnvDecode::Integer).unwrap(), json!(0));
432        assert!(decode("08.", EnvDecode::Integer).is_err());
433    }
434
435    #[test]
436    fn float_reads_go_literals() {
437        assert_eq!(decode("0x1p4", EnvDecode::Float).unwrap(), json!(16.0));
438        assert_eq!(decode("1_000.5", EnvDecode::Float).unwrap(), json!(1000.5));
439        assert!(decode("0x10", EnvDecode::Float).is_err());
440        assert!(decode("inf", EnvDecode::Float).is_err());
441    }
442
443    #[test]
444    fn decimal_integer_keeps_a_leading_zero_decimal() {
445        assert_eq!(decode("010", EnvDecode::DecimalInteger).unwrap(), json!(10));
446        assert_eq!(decode("9125.0", EnvDecode::DecimalInteger).unwrap(), json!(9125));
447        for rejected in ["0x10", "0b11", "1_000", "9125.5"] {
448            assert!(decode(rejected, EnvDecode::DecimalInteger).is_err(), "{rejected}");
449        }
450    }
451
452    #[test]
453    fn decimal_float_has_no_go_only_spellings() {
454        assert_eq!(decode("1.5e1", EnvDecode::DecimalFloat).unwrap(), json!(15.0));
455        for rejected in ["0x1p4", "1_000.5", "inf"] {
456            assert!(decode(rejected, EnvDecode::DecimalFloat).is_err(), "{rejected}");
457        }
458    }
459
460    #[test]
461    fn whitespace_list_never_reads_json() {
462        assert_eq!(
463            decode("env:prod  team:core", EnvDecode::WhitespaceList).unwrap(),
464            arr(&["env:prod", "team:core"])
465        );
466        assert_eq!(
467            decode(r#"["a","b"]"#, EnvDecode::WhitespaceList).unwrap(),
468            arr(&[r#"["a","b"]"#])
469        );
470        assert_eq!(decode("   ", EnvDecode::WhitespaceList).unwrap(), Value::Array(vec![]));
471    }
472
473    #[test]
474    fn duration_is_carried_through_as_a_string() {
475        // A duration leaf stays shape-tolerant; the raw text reaches `duration_de` unchanged.
476        assert_eq!(decode("10s", EnvDecode::DurationString).unwrap(), json!("10s"));
477        assert_eq!(decode("30", EnvDecode::DurationString).unwrap(), json!("30"));
478    }
479}