Skip to main content

relay_event_normalization/eap/
user_agent.rs

1use std::cell::OnceCell;
2
3use relay_conventions::attributes::{BROWSER__NAME, BROWSER__VERSION, USER_AGENT__ORIGINAL};
4use relay_event_schema::protocol::{Attributes, BrowserContext};
5use relay_protocol::{Annotated, Value};
6
7use crate::{ClientHints, FromUserAgentInfo as _};
8
9// The vendored uap-core fixtures top out at 50 bytes for names and 27 for versions.
10// Leave room for longer values while bounding what enrichment copies into each item.
11const MAX_BROWSER_FIELD_BYTES: usize = 128;
12
13/// Lazy browser enrichment shared by the items in one container.
14///
15/// Transport parsing, including unsuccessful parses, happens at most once.
16/// Oversized derived browser fields are skipped before being copied into items.
17pub struct UserAgentNormalizer {
18    transport_user_agent: Option<String>,
19    sec_ch_ua: Option<String>,
20    hints: OnceCell<Option<Browser>>,
21    user_agent: OnceCell<Option<Browser>>,
22}
23
24impl UserAgentNormalizer {
25    /// Creates a cache for one container from its transport headers.
26    /// Omit the headers when transport inference is disabled.
27    pub fn new(user_agent: Option<&str>, sec_ch_ua: Option<&str>) -> Self {
28        Self {
29            transport_user_agent: user_agent.map(str::to_owned),
30            sec_ch_ua: sec_ch_ua.map(str::to_owned),
31            hints: OnceCell::new(),
32            user_agent: OnceCell::new(),
33        }
34    }
35
36    /// Normalizes the user agent/client information into [`Attributes`].
37    ///
38    /// Does not modify the attributes if there is already browser information present,
39    /// to preserve original values. An explicit user agent takes precedence over both transport
40    /// headers.
41    pub fn normalize(&self, attributes: &mut Annotated<Attributes>) {
42        let attributes = attributes.get_or_insert_with(Default::default);
43        if attributes.contains_key(BROWSER__NAME) || attributes.contains_key(BROWSER__VERSION) {
44            return;
45        }
46
47        let browser = if attributes.contains_key(USER_AGENT__ORIGINAL) {
48            // Even an invalid explicit attribute prevents transport inference.
49            attributes
50                .get_value(USER_AGENT__ORIGINAL)
51                .and_then(Value::as_str)
52                .and_then(Browser::from_user_agent)
53        } else {
54            if let Some(original) = &self.transport_user_agent {
55                attributes.insert(USER_AGENT__ORIGINAL, original.clone());
56            }
57            self.browser_from_hints()
58                .or_else(|| self.browser_from_transport())
59                .cloned()
60        };
61
62        if let Some(browser) = browser {
63            attributes.insert(BROWSER__NAME, browser.name);
64            attributes.insert(BROWSER__VERSION, browser.version);
65        }
66    }
67
68    fn browser_from_hints(&self) -> Option<&Browser> {
69        self.hints
70            .get_or_init(|| {
71                Browser::from_hints(ClientHints {
72                    sec_ch_ua: self.sec_ch_ua.as_deref(),
73                    ..Default::default()
74                })
75            })
76            .as_ref()
77    }
78
79    fn browser_from_transport(&self) -> Option<&Browser> {
80        self.user_agent
81            .get_or_init(|| Browser::from_user_agent(self.transport_user_agent.as_deref()?))
82            .as_ref()
83    }
84}
85
86#[derive(Clone)]
87struct Browser {
88    name: Annotated<String>,
89    version: Annotated<String>,
90}
91
92impl Browser {
93    fn from_hints(hints: ClientHints<&str>) -> Option<Self> {
94        let (name, version) = hints.browser()?;
95        if !browser_fields_fit(Some(name), Some(version)) {
96            return None;
97        }
98        Some(Self {
99            name: Annotated::new(name.to_owned()),
100            version: Annotated::new(version.to_owned()),
101        })
102    }
103
104    fn from_user_agent(user_agent: &str) -> Option<Self> {
105        let browser = BrowserContext::parse_user_agent(user_agent)?;
106        if !browser_fields_fit(
107            browser.name.value().map(String::as_str),
108            browser.version.value().map(String::as_str),
109        ) {
110            return None;
111        }
112        Some(Self {
113            name: browser.name,
114            version: browser.version,
115        })
116    }
117}
118
119fn browser_fields_fit(name: Option<&str>, version: Option<&str>) -> bool {
120    [name, version]
121        .into_iter()
122        .flatten()
123        .all(|value| value.len() <= MAX_BROWSER_FIELD_BYTES)
124}
125
126#[cfg(test)]
127mod tests {
128    use relay_protocol::assert_annotated_snapshot;
129
130    use super::*;
131
132    const CHROME_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
133
134    #[test]
135    fn test_browser_from_hints_rejects_oversized_name() {
136        let name = "é".repeat(65);
137        let header = format!(r#""{name}";v="123""#);
138        assert!(
139            Browser::from_hints(ClientHints {
140                sec_ch_ua: Some(&header),
141                ..Default::default()
142            })
143            .is_none()
144        );
145    }
146
147    #[test]
148    fn test_browser_from_hints_rejects_oversized_version() {
149        let version = "1".repeat(129);
150        let header = format!(r#""TestBrowser";v="{version}""#);
151        assert!(
152            Browser::from_hints(ClientHints {
153                sec_ch_ua: Some(&header),
154                ..Default::default()
155            })
156            .is_none()
157        );
158    }
159
160    #[test]
161    fn test_browser_from_hints_preserves_values_at_limit() {
162        let name = "é".repeat(64);
163        let version = "1".repeat(128);
164        let header = format!(r#""{name}";v="{version}""#);
165        let browser = Browser::from_hints(ClientHints {
166            sec_ch_ua: Some(&header),
167            ..Default::default()
168        })
169        .unwrap();
170
171        assert_eq!(browser.name.value(), Some(&name));
172        assert_eq!(browser.version.value(), Some(&version));
173    }
174
175    #[test]
176    fn test_normalize_user_agent_falls_back_after_oversized_hints() {
177        let hints = format!(r#""{}";v="123""#, "x".repeat(129));
178        let normalizer = UserAgentNormalizer::new(Some(CHROME_USER_AGENT), Some(&hints));
179        let mut attributes = Annotated::default();
180        normalizer.normalize(&mut attributes);
181        let attributes = attributes.value().unwrap();
182
183        assert_eq!(
184            attributes.get_value(BROWSER__NAME).and_then(Value::as_str),
185            Some("Chrome")
186        );
187        assert_eq!(
188            attributes
189                .get_value(BROWSER__VERSION)
190                .and_then(Value::as_str),
191            Some("131.0.0")
192        );
193    }
194
195    #[test]
196    fn test_normalize_user_agent_prefers_item_ua_over_transport() {
197        let firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0";
198        let normalizer =
199            UserAgentNormalizer::new(Some(CHROME_USER_AGENT), Some(r#""Edge";v="131""#));
200        let mut attributes = Attributes::default();
201        attributes.insert(USER_AGENT__ORIGINAL, firefox);
202        let mut attributes = Annotated::new(attributes);
203        normalizer.normalize(&mut attributes);
204        let attributes = attributes.value().unwrap();
205
206        assert_eq!(
207            attributes
208                .get_value(USER_AGENT__ORIGINAL)
209                .and_then(Value::as_str),
210            Some(firefox)
211        );
212        assert_eq!(
213            attributes.get_value(BROWSER__NAME).and_then(Value::as_str),
214            Some("Firefox")
215        );
216        assert_eq!(
217            attributes
218                .get_value(BROWSER__VERSION)
219                .and_then(Value::as_str),
220            Some("128.0")
221        );
222
223        let mut next = Annotated::default();
224        normalizer.normalize(&mut next);
225        assert_eq!(
226            next.value()
227                .unwrap()
228                .get_value(BROWSER__NAME)
229                .and_then(Value::as_str),
230            Some("Edge")
231        );
232    }
233
234    #[test]
235    fn test_normalize_user_agent_none() {
236        let normalizer = UserAgentNormalizer::new(Some(CHROME_USER_AGENT), None);
237        let mut attributes = Default::default();
238        normalizer.normalize(&mut attributes);
239
240        assert_annotated_snapshot!(attributes, @r###"
241        {
242          "browser.name": {
243            "type": "string",
244            "value": "Chrome"
245          },
246          "browser.version": {
247            "type": "string",
248            "value": "131.0.0"
249          },
250          "user_agent.original": {
251            "type": "string",
252            "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
253          }
254        }
255        "###);
256    }
257
258    #[test]
259    fn test_normalize_user_agent_existing() {
260        let normalizer = UserAgentNormalizer::new(Some(CHROME_USER_AGENT), None);
261        let mut attributes = Annotated::from_json(
262            r#"{
263          "browser.name": {
264            "type": "string",
265            "value": "Very Special"
266          },
267          "browser.version": {
268            "type": "string",
269            "value": "13.3.7"
270          }
271        }"#,
272        )
273        .unwrap();
274
275        normalizer.normalize(&mut attributes);
276
277        assert_annotated_snapshot!(attributes, @r#"
278        {
279          "browser.name": {
280            "type": "string",
281            "value": "Very Special"
282          },
283          "browser.version": {
284            "type": "string",
285            "value": "13.3.7"
286          }
287        }
288        "#
289        );
290
291        // Either prefilled browser field prevents enrichment on its own.
292        for (key, other, expected) in [
293            (BROWSER__NAME, BROWSER__VERSION, "Very Special"),
294            (BROWSER__VERSION, BROWSER__NAME, "13.3.7"),
295        ] {
296            let mut partial = attributes.clone();
297            partial.value_mut().as_mut().unwrap().remove(other);
298            normalizer.normalize(&mut partial);
299            let partial = partial.value().unwrap();
300            assert_eq!(
301                partial.get_value(key).and_then(Value::as_str),
302                Some(expected)
303            );
304            assert!(!partial.contains_key(other));
305            assert!(!partial.contains_key(USER_AGENT__ORIGINAL));
306        }
307        assert!(normalizer.hints.get().is_none());
308        assert!(normalizer.user_agent.get().is_none());
309
310        let mut missing = Annotated::default();
311        normalizer.normalize(&mut missing);
312        assert_eq!(
313            missing
314                .value()
315                .unwrap()
316                .get_value(BROWSER__NAME)
317                .and_then(Value::as_str),
318            Some("Chrome")
319        );
320    }
321}