Skip to main content

libdd_common/
tag.rs

1// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! Datadog tag construction and validation.
5//!
6//! # Validation policy
7//!
8//! The Datadog documentation defines more tag rules than this module enforces:
9//! <https://docs.datadoghq.com/getting_started/tagging/#define-tags>. Enforcing rules that tracing
10//! and profiling do not apply consistently would produce a worse user experience, so runtime
11//! validation currently rejects only empty tags and likely colon-related mistakes. Compile-time
12//! validation by the [`tag!`](crate::tag!) macro is intentionally stricter.
13
14use core::fmt::{Display, Formatter};
15#[cfg(feature = "alloc")]
16use {
17    alloc::{
18        borrow::{Cow, ToOwned},
19        format,
20        string::{String, ToString},
21        vec,
22        vec::Vec,
23    },
24    core::fmt::Debug,
25    serde::{Deserialize, Serialize},
26};
27
28#[cfg(feature = "alloc")]
29pub use static_assertions::{const_assert, const_assert_ne};
30
31/// Describes some reasons why a tag is invalid.
32#[allow(missing_docs, reason = "variant names are self-documenting")]
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34#[non_exhaustive] // so we can add more cases without breaking semver
35pub enum TagValidationError {
36    Empty,
37    BeginsWithColon,
38    EndsWithColon,
39}
40
41impl Display for TagValidationError {
42    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
43        f.write_str(match self {
44            Self::Empty => "tag is empty",
45            Self::BeginsWithColon => "tag begins with a colon",
46            Self::EndsWithColon => "tag ends with a colon",
47        })
48    }
49}
50
51impl core::error::Error for TagValidationError {}
52
53/// A tag rejected while validating a tag.
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55pub struct InvalidTag<'a> {
56    /// The invalid serialized tag.
57    pub value: &'a str,
58    /// Why the tag is invalid.
59    pub error: TagValidationError,
60}
61
62impl Display for InvalidTag<'_> {
63    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
64        match self.error {
65            TagValidationError::Empty => f.write_str("tag is empty"),
66            TagValidationError::BeginsWithColon => {
67                write!(f, "tag '{}' begins with a colon", self.value)
68            }
69            TagValidationError::EndsWithColon => {
70                write!(f, "tag '{}' ends with a colon", self.value)
71            }
72        }
73    }
74}
75
76impl core::error::Error for InvalidTag<'_> {}
77
78/// Validates a tag that has already been serialized.
79#[inline]
80fn validate_serialized(value: &str) -> Result<(), TagValidationError> {
81    if value.is_empty() {
82        Err(TagValidationError::Empty)
83    } else if value.starts_with(':') {
84        Err(TagValidationError::BeginsWithColon)
85    } else if value.ends_with(':') {
86        Err(TagValidationError::EndsWithColon)
87    } else {
88        Ok(())
89    }
90}
91
92#[cfg(feature = "alloc")]
93#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
94#[serde(transparent)]
95pub struct Tag {
96    /// Many tags are made from literal strings, such as:
97    ///  - "language:native"
98    ///  - "src_library:libdatadog"
99    ///  - "type:timeout"
100    ///
101    /// So being able to save allocations is nice.
102    value: Cow<'static, str>,
103}
104
105#[cfg(feature = "alloc")]
106impl Tag {
107    /// Used by the `tag!` macro. Not meant to be used directly, please use
108    /// the macro instead.
109    /// # Safety
110    /// Do not use directly, use through the `tag!` macro which enforces the
111    /// safety invariants at compile time.
112    pub const unsafe fn from_static_unchecked(value: &'static str) -> Self {
113        Self {
114            value: Cow::Borrowed(value),
115        }
116    }
117}
118
119/// Creates a tag from a key and value known at compile-time, and fails to
120/// compile if it's known to be invalid (it may still emit an invalid tag, not
121/// all tag validation is currently done client-side). If the key or value
122/// aren't known at compile-time, then use [Tag::new].
123// todo: what's a good way to keep these in-sync with Tag::from_value?
124// This can be a little more strict because it's compile-time evaluated.
125// https://docs.datadoghq.com/getting_started/tagging/#define-tags
126#[macro_export]
127#[cfg(feature = "alloc")]
128macro_rules! tag {
129    ($key:expr, $val:expr) => {{
130        // Keys come in "value" or "key:value" format. This pattern is always
131        // the key:value format, which means the value should not be empty.
132        // todo: the implementation here differs subtly from Tag::from_value,
133        //       which checks that the whole thing doesn't end with a colon.
134        $crate::tag::const_assert!(!$val.is_empty());
135
136        const COMBINED: &'static str = $crate::const_format::concatcp!($key, ":", $val);
137
138        // Tags must start with a letter. This is more restrictive than is
139        // required (could be a unicode alphabetic char) and can be lifted
140        // if it's causing problems.
141        $crate::tag::const_assert!(COMBINED.as_bytes()[0].is_ascii_alphabetic());
142
143        // Tags can be up to 200 characters long and support Unicode letters
144        // (which includes most character sets, including languages such as
145        // Japanese).
146        // Presently, engineers interpretted this to be 200 bytes, not unicode
147        // characters. However, if the 200th character is unicode, it's
148        // allowed to spill over due to a historical bug. For now, we'll
149        // ignore this and hard-code 200 bytes.
150        $crate::tag::const_assert!(COMBINED.as_bytes().len() <= 200);
151
152        #[allow(unused_unsafe)]
153        let tag = unsafe { $crate::tag::Tag::from_static_unchecked(COMBINED) };
154        tag
155    }};
156}
157
158#[cfg(feature = "alloc")]
159impl Debug for Tag {
160    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
161        f.debug_struct("Tag").field("value", &self.value).finish()
162    }
163}
164
165#[cfg(feature = "alloc")]
166impl AsRef<str> for Tag {
167    fn as_ref(&self) -> &str {
168        self.value.as_ref()
169    }
170}
171
172// Any type which implements Display automatically has to_string.
173#[cfg(feature = "alloc")]
174impl Display for Tag {
175    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
176        write!(f, "{}", self.value)
177    }
178}
179
180#[cfg(feature = "alloc")]
181impl Tag {
182    /// Validates a tag key and value pair.
183    #[inline]
184    pub fn validate(key: &str, value: &str) -> Result<(), TagValidationError> {
185        if key.is_empty() || key.starts_with(':') {
186            Err(TagValidationError::BeginsWithColon)
187        } else if value.is_empty() || value.ends_with(':') {
188            Err(TagValidationError::EndsWithColon)
189        } else {
190            Ok(())
191        }
192    }
193
194    /// Validates a tag that has already been serialized.
195    #[inline]
196    pub fn validate_value(value: &str) -> Result<(), TagValidationError> {
197        validate_serialized(value)
198    }
199
200    /// Validates a tag.
201    fn from_value<'a, IntoCow>(value: IntoCow) -> anyhow::Result<Self>
202    where
203        IntoCow: Into<Cow<'a, str>>,
204    {
205        let value = value.into();
206        match Self::validate_value(&value) {
207            Ok(()) => Ok(Self {
208                value: Cow::Owned(value.into_owned()),
209            }),
210            Err(error) => {
211                let invalid = InvalidTag {
212                    value: value.as_ref(),
213                    error,
214                };
215                anyhow::bail!("{invalid}")
216            }
217        }
218    }
219
220    /// Creates a tag from a key and value. It's preferred to use the `tag!`
221    /// macro when the key and value are both known at compile-time.
222    pub fn new<K, V>(key: K, value: V) -> anyhow::Result<Self>
223    where
224        K: AsRef<str>,
225        V: AsRef<str>,
226    {
227        let key = key.as_ref();
228        let value = value.as_ref();
229
230        Tag::from_value(format!("{key}:{value}"))
231    }
232}
233
234/// An allocation-free iterator over validated tags in a comma- or space-separated string.
235pub struct TagParser<'a> {
236    chunks: core::str::Split<'a, &'static [char]>,
237}
238
239impl<'a> TagParser<'a> {
240    /// Creates an iterator over the tags in `input`.
241    pub fn new(input: &'a str) -> Self {
242        const SEPARATORS: &[char] = &[',', ' '];
243        Self {
244            chunks: input.split(SEPARATORS),
245        }
246    }
247}
248
249impl<'a> Iterator for TagParser<'a> {
250    type Item = Result<&'a str, InvalidTag<'a>>;
251
252    fn next(&mut self) -> Option<Self::Item> {
253        let tag = self.chunks.find(|chunk| !chunk.is_empty())?;
254        Some(
255            validate_serialized(tag)
256                .map(|()| tag)
257                .map_err(|error| InvalidTag { value: tag, error }),
258        )
259    }
260}
261
262/// Parse a string of tags typically provided by environment variables
263/// The tags are expected to be either space or comma separated:
264///     "key1:value1,key2:value2"
265///     "key1:value1 key2:value2"
266/// Tag names and values are required and may not be empty.
267///
268/// Returns a tuple of the correctly parsed tags and an optional error message
269/// describing issues encountered during parsing.
270#[cfg(feature = "alloc")]
271pub fn parse_tags(str: &str) -> (Vec<Tag>, Option<String>) {
272    let mut tags = vec![];
273    let mut error_message = String::new();
274    for result in TagParser::new(str) {
275        match result {
276            Ok(tag) => tags.push(Tag {
277                value: Cow::Owned(tag.to_owned()),
278            }),
279            Err(err) => {
280                if error_message.is_empty() {
281                    error_message += "Errors while parsing tags: ";
282                } else {
283                    error_message += ", ";
284                }
285                error_message += &err.to_string();
286            }
287        }
288    }
289
290    let error_message = if error_message.is_empty() {
291        None
292    } else {
293        Some(error_message)
294    };
295    (tags, error_message)
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn test_validate_serialized() {
304        assert_eq!(validate_serialized("key:value"), Ok(()));
305        assert_eq!(validate_serialized("key:value:with:colons"), Ok(()));
306        assert_eq!(validate_serialized("tag"), Ok(()));
307        assert_eq!(validate_serialized(""), Err(TagValidationError::Empty));
308        assert_eq!(
309            validate_serialized(":value"),
310            Err(TagValidationError::BeginsWithColon)
311        );
312        assert_eq!(
313            validate_serialized("key:"),
314            Err(TagValidationError::EndsWithColon)
315        );
316    }
317
318    #[test]
319    fn test_tag_parser() {
320        let mut parser = TagParser::new("key:value, :leading middle:colon trailing:  bare");
321        assert_eq!(parser.next(), Some(Ok("key:value")));
322        assert_eq!(
323            parser.next(),
324            Some(Err(InvalidTag {
325                value: ":leading",
326                error: TagValidationError::BeginsWithColon,
327            }))
328        );
329        assert_eq!(parser.next(), Some(Ok("middle:colon")));
330        assert_eq!(
331            parser.next(),
332            Some(Err(InvalidTag {
333                value: "trailing:",
334                error: TagValidationError::EndsWithColon,
335            }))
336        );
337        assert_eq!(parser.next(), Some(Ok("bare")));
338        assert_eq!(parser.next(), None);
339    }
340
341    #[test]
342    fn test_tag_parser_skips_empty_chunks() {
343        for input in ["", ",", " , ", ",, ,"] {
344            assert_eq!(TagParser::new(input).next(), None, "input: {input:?}");
345        }
346
347        let mut parser = TagParser::new(" ,key1:value1,, key2:value2 , ");
348        assert_eq!(parser.next(), Some(Ok("key1:value1")));
349        assert_eq!(parser.next(), Some(Ok("key2:value2")));
350        assert_eq!(parser.next(), None);
351    }
352}
353
354#[cfg(all(test, feature = "alloc"))]
355mod alloc_tests {
356    use super::*;
357    use proptest::prelude::*;
358
359    proptest! {
360        #[test]
361        fn prop_component_and_serialized_validation_are_consistent(
362            key in any::<String>(),
363            value in any::<String>(),
364        ) {
365            let serialized = format!("{key}:{value}");
366
367            prop_assert_eq!(
368                Tag::validate(&key, &value),
369                Tag::validate_value(&serialized)
370            );
371        }
372
373        #[test]
374        fn prop_constructor_and_validation_are_consistent(
375            key in any::<String>(),
376            value in any::<String>(),
377        ) {
378            let serialized = format!("{key}:{value}");
379            let validation = Tag::validate(&key, &value);
380            let result = Tag::new(&key, &value);
381
382            prop_assert_eq!(result.is_ok(), validation.is_ok());
383            if let Ok(tag) = result {
384                prop_assert_eq!(tag.as_ref(), serialized);
385            }
386        }
387
388        #[test]
389        fn prop_serialized_constructor_and_validation_are_consistent(
390            value in any::<String>(),
391        ) {
392            prop_assert_eq!(
393                Tag::from_value(value.as_str()).is_ok(),
394                Tag::validate_value(&value).is_ok()
395            );
396        }
397    }
398
399    #[test]
400    fn test_is_send() {
401        // fails to compile if false
402        fn is_send<T: Send>(_t: T) -> bool {
403            true
404        }
405        assert!(is_send(tag!("src_library", "libdatadog")));
406    }
407
408    #[test]
409    fn test_validation() {
410        assert_eq!(Tag::validate("key", "value"), Ok(()));
411        assert_eq!(Tag::validate("key", "value:with:colons"), Ok(()));
412        assert_eq!(
413            Tag::validate("", "value"),
414            Err(TagValidationError::BeginsWithColon)
415        );
416        assert_eq!(
417            Tag::validate(":key", "value"),
418            Err(TagValidationError::BeginsWithColon)
419        );
420        assert_eq!(
421            Tag::validate("key", ""),
422            Err(TagValidationError::EndsWithColon)
423        );
424        assert_eq!(
425            Tag::validate("key", "value:"),
426            Err(TagValidationError::EndsWithColon)
427        );
428    }
429
430    #[test]
431    fn test_empty_key() {
432        let error = Tag::new("", "woof").expect_err("empty key is not allowed");
433        assert_eq!(error.to_string(), "tag ':woof' begins with a colon");
434    }
435
436    #[test]
437    fn test_empty_value() {
438        let error = Tag::new("key1", "").expect_err("empty value is an error");
439        assert_eq!(error.to_string(), "tag 'key1:' ends with a colon");
440    }
441
442    #[test]
443    fn test_bad_utf8() {
444        // 0b1111_0xxx is the start of a 4-byte sequence, but there aren't any
445        // more chars, so it  will get converted into the utf8 replacement
446        // character. This results in a string with an "a" and a replacement
447        // char, so it should be an error (no valid chars). However, we don't
448        // enforce many things about tags yet client-side, so we let it slide.
449        let bytes = &[b'a', 0b1111_0111];
450        let key = String::from_utf8_lossy(bytes);
451        let t = Tag::new(key, "value").unwrap();
452        assert_eq!("a\u{FFFD}:value", t.to_string());
453    }
454
455    #[test]
456    fn test_value_has_colon() {
457        let result = Tag::new("env", "staging:east").expect("values can have colons");
458        assert_eq!("env:staging:east", result.to_string());
459
460        let result = tag!("env", "staging:east");
461        assert_eq!("env:staging:east", result.to_string());
462    }
463
464    #[test]
465    fn test_suspicious_tags() {
466        // Based on tag rules, these should all fail. However, there is a risk
467        // that profile tags will then differ or cause failures compared to
468        // trace tags. These require cross-team, cross-language collaboration.
469        let cases = [
470            ("_begins_with_non-letter".to_string(), "value"),
471            ("the-tag-length-is-over-200-characters".repeat(6), "value"),
472        ];
473
474        for case in cases {
475            let result = Tag::new(case.0, case.1);
476            // Again, these should fail, but it's not implemented yet
477            assert!(result.is_ok())
478        }
479    }
480
481    #[test]
482    fn test_missing_colon_parsing() {
483        let tag = Tag::from_value("tag").unwrap();
484        assert_eq!("tag", tag.to_string());
485    }
486
487    #[test]
488    fn test_leading_colon_parsing() {
489        let _ = Tag::from_value(":tag").expect_err("Cannot start with a colon");
490    }
491
492    #[test]
493    fn test_tailing_colon_parsing() {
494        let _ = Tag::from_value("tag:").expect_err("Cannot end with a colon");
495    }
496
497    #[test]
498    fn test_tag_parser_preserves_parse_tags_errors() {
499        let (tags, error) = parse_tags("valid:value,:leading,trailing:,also:valid");
500        assert_eq!(
501            tags,
502            vec![
503                Tag::new("valid", "value").unwrap(),
504                Tag::new("also", "valid").unwrap(),
505            ]
506        );
507        assert_eq!(
508            error.as_deref(),
509            Some(
510                "Errors while parsing tags: tag ':leading' begins with a colon, tag 'trailing:' ends with a colon"
511            )
512        );
513    }
514
515    #[test]
516    fn test_tags_parsing() {
517        let cases = [
518            ("", vec![]),
519            (",", vec![]),
520            (" , ", vec![]),
521            // Testing that values can contain colons
522            (
523                "env:staging:east,location:nyc:ny",
524                vec![
525                    Tag::new("env", "staging:east").unwrap(),
526                    Tag::new("location", "nyc:ny").unwrap(),
527                ],
528            ),
529            // Testing value format (no key)
530            ("value", vec![Tag::from_value("value").unwrap()]),
531            (
532                "state:utah,state:idaho",
533                vec![
534                    Tag::new("state", "utah").unwrap(),
535                    Tag::new("state", "idaho").unwrap(),
536                ],
537            ),
538            (
539                "key1:value1 key2:value2 key3:value3",
540                vec![
541                    Tag::new("key1", "value1").unwrap(),
542                    Tag::new("key2", "value2").unwrap(),
543                    Tag::new("key3", "value3").unwrap(),
544                ],
545            ),
546            (
547                // Testing consecutive separators being collapsed
548                "key1:value1, key2:value2 ,key3:value3 , key4:value4",
549                vec![
550                    Tag::new("key1", "value1").unwrap(),
551                    Tag::new("key2", "value2").unwrap(),
552                    Tag::new("key3", "value3").unwrap(),
553                    Tag::new("key4", "value4").unwrap(),
554                ],
555            ),
556        ];
557
558        for case in cases {
559            let expected = case.1;
560            let (actual, error_message) = parse_tags(case.0);
561            assert_eq!(expected, actual);
562            assert!(error_message.is_none());
563        }
564    }
565}