Skip to main content

relay_event_normalization/normalize/
user_agent.rs

1//! Generate context data from user agent and client hints.
2//!
3//! This module is responsible for taking the user agent string parsing it and filling in
4//! the browser, os and device information in the event.
5//!
6//! ## NOTICE
7//!
8//! Adding user_agent parsing to your module will incur a latency penalty in the test suite.
9//! Because of this some integration tests may fail. To fix this, you will need to add a timeout
10//! to your consumer.
11
12use std::borrow::Cow;
13use std::fmt::Write;
14use std::sync::OnceLock;
15
16use regex::Regex;
17use relay_event_schema::protocol::{
18    BrowserContext, Context, Contexts, DefaultContext, DeviceContext, Event, HeaderName,
19    HeaderValue, Headers, OsContext,
20};
21use relay_protocol::Annotated;
22use serde::{Deserialize, Serialize};
23
24/// Generates context data from client hints or user agent.
25pub fn normalize_user_agent(event: &mut Event) {
26    let headers = match event
27        .request
28        .value()
29        .and_then(|request| request.headers.value())
30    {
31        Some(headers) => headers,
32        None => return,
33    };
34
35    let user_agent_info = RawUserAgentInfo::from_headers(headers);
36
37    let contexts = event.contexts.get_or_insert_with(Contexts::new);
38    normalize_user_agent_info_generic(contexts, &event.platform, &user_agent_info);
39}
40
41/// Low-level version of [`normalize_user_agent`] operating on parts.
42///
43/// This can be used to create contexts from client information without a full [`Event`] instance.
44pub fn normalize_user_agent_info_generic(
45    contexts: &mut Contexts,
46    platform: &Annotated<String>,
47    user_agent_info: &RawUserAgentInfo<&str>,
48) {
49    if !contexts.contains::<BrowserContext>()
50        && let Some(browser_context) = BrowserContext::from_hints_or_ua(user_agent_info)
51    {
52        contexts.add(browser_context);
53    }
54
55    if !contexts.contains::<DeviceContext>()
56        && let Some(device_context) = DeviceContext::from_hints_or_ua(user_agent_info)
57    {
58        contexts.add(device_context);
59    }
60
61    // avoid conflicts with OS-context sent by a serverside SDK by using `contexts.client_os`
62    // instead of `contexts.os`. This is then preferred by the UI to show alongside device and
63    // browser context.
64    //
65    // Why not move the existing `contexts.os` into a different key on conflicts? Because we still
66    // want to index (derive tags from) the SDK-sent context.
67    let os_context_key = match platform.as_str() {
68        Some("javascript") => OsContext::default_key(),
69        _ => "client_os",
70    };
71
72    if !contexts.contains_key(os_context_key)
73        && let Some(os_context) = OsContext::from_hints_or_ua(user_agent_info)
74    {
75        contexts.insert(os_context_key.to_owned(), Context::Os(Box::new(os_context)));
76    }
77}
78
79fn is_known(family: &str) -> bool {
80    family != "Other"
81}
82
83fn get_version(
84    major: &Option<Cow<'_, str>>,
85    minor: &Option<Cow<'_, str>>,
86    patch: &Option<Cow<'_, str>>,
87) -> Option<String> {
88    let mut version = major.as_ref()?.to_string();
89
90    if let Some(minor) = minor {
91        write!(version, ".{minor}").ok();
92        if let Some(patch) = patch {
93            write!(version, ".{patch}").ok();
94        }
95    }
96
97    Some(version)
98}
99
100/// A container housing both the user-agent string and the client hint headers.
101///
102/// Useful for the scenarios where you will use either information from client hints if it exists,
103/// and if not fall back to user agent string.
104#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq)]
105pub struct RawUserAgentInfo<S: Default + AsRef<str>> {
106    /// The "old style" of a single UA string.
107    pub user_agent: Option<S>,
108    /// User-Agent client hints.
109    pub client_hints: ClientHints<S>,
110}
111
112impl<S: AsRef<str> + Default> RawUserAgentInfo<S> {
113    /// Checks if key matches a user agent header, in which case it sets the value accordingly.
114    ///  TODO(tor): make it generic over different header types.
115    pub fn set_ua_field_from_header(&mut self, key: &str, value: Option<S>) {
116        match key.to_lowercase().as_str() {
117            "user-agent" => self.user_agent = value,
118
119            "sec-ch-ua" => self.client_hints.sec_ch_ua = value,
120            "sec-ch-ua-model" => self.client_hints.sec_ch_ua_model = value,
121            "sec-ch-ua-platform" => self.client_hints.sec_ch_ua_platform = value,
122            "sec-ch-ua-platform-version" => {
123                self.client_hints.sec_ch_ua_platform_version = value;
124            }
125            _ => {}
126        }
127    }
128
129    /// Convert user-agent info to HTTP headers as stored in the `Request` interface.
130    ///
131    /// This function does not overwrite any pre-existing headers.
132    pub fn populate_event_headers(&self, headers: &mut Headers) {
133        let mut insert_header = |key: &str, val: Option<&S>| {
134            if let Some(val) = val
135                && !headers.contains(key)
136            {
137                headers.insert(HeaderName::new(key), Annotated::new(HeaderValue::new(val)));
138            }
139        };
140
141        insert_header(RawUserAgentInfo::USER_AGENT, self.user_agent.as_ref());
142        insert_header(
143            ClientHints::SEC_CH_UA_PLATFORM,
144            self.client_hints.sec_ch_ua_platform.as_ref(),
145        );
146        insert_header(
147            ClientHints::SEC_CH_UA_PLATFORM_VERSION,
148            self.client_hints.sec_ch_ua_platform_version.as_ref(),
149        );
150        insert_header(ClientHints::SEC_CH_UA, self.client_hints.sec_ch_ua.as_ref());
151        insert_header(
152            ClientHints::SEC_CH_UA_MODEL,
153            self.client_hints.sec_ch_ua_model.as_ref(),
154        );
155    }
156
157    /// Returns `true`, if neither a user agent nor client hints are available.
158    pub fn is_empty(&self) -> bool {
159        self.user_agent.is_none() && self.client_hints.is_empty()
160    }
161}
162
163impl RawUserAgentInfo<String> {
164    /// The name of the user agent HTTP header.
165    pub const USER_AGENT: &'static str = "User-Agent";
166
167    /// Converts to a borrowed `RawUserAgentInfo`.
168    pub fn as_deref(&self) -> RawUserAgentInfo<&str> {
169        RawUserAgentInfo::<&str> {
170            user_agent: self.user_agent.as_deref(),
171            client_hints: self.client_hints.as_deref(),
172        }
173    }
174}
175
176impl<'a> RawUserAgentInfo<&'a str> {
177    /// Computes a borrowed `RawUserAgentInfo` from the given HTTP headers.
178    ///
179    /// This extracts both the user agent as well as client hints if available. Use
180    /// [`is_empty`](Self::is_empty) to check whether information could be extracted.
181    pub fn from_headers(headers: &'a Headers) -> Self {
182        let mut contexts: RawUserAgentInfo<&str> = Self::default();
183
184        for item in headers.iter() {
185            if let Some((o_k, v)) = item.value()
186                && let Some(k) = o_k.as_str()
187            {
188                contexts.set_ua_field_from_header(k, v.as_str());
189            }
190        }
191        contexts
192    }
193}
194
195/// The client hint variable names mirror the name of the "SEC-CH" headers.
196///
197/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#user_agent_client_hints>
198#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq)]
199pub struct ClientHints<S>
200where
201    S: Default + AsRef<str>,
202{
203    /// The client's OS, e.g. macos, android...
204    pub sec_ch_ua_platform: Option<S>,
205    /// The version number of the client's OS.
206    pub sec_ch_ua_platform_version: Option<S>,
207    /// Name of the client's web browser and its version.
208    pub sec_ch_ua: Option<S>,
209    /// Device model, e.g. samsung galaxy 3.
210    pub sec_ch_ua_model: Option<S>,
211}
212
213impl<S> ClientHints<S>
214where
215    S: AsRef<str> + Default,
216{
217    /// Checks every field of a passed-in ClientHints instance if it contains a value, and if it
218    /// does, copy it to self.
219    pub fn copy_from(&mut self, other: ClientHints<S>) {
220        if other.sec_ch_ua_platform_version.is_some() {
221            self.sec_ch_ua_platform_version = other.sec_ch_ua_platform_version;
222        }
223        if other.sec_ch_ua_platform.is_some() {
224            self.sec_ch_ua_platform = other.sec_ch_ua_platform;
225        }
226        if other.sec_ch_ua_model.is_some() {
227            self.sec_ch_ua_model = other.sec_ch_ua_model;
228        }
229        if other.sec_ch_ua.is_some() {
230            self.sec_ch_ua = other.sec_ch_ua;
231        }
232    }
233
234    /// Checks if every field is of value None.
235    pub fn is_empty(&self) -> bool {
236        self.sec_ch_ua_platform.is_none()
237            && self.sec_ch_ua_platform_version.is_none()
238            && self.sec_ch_ua.is_none()
239            && self.sec_ch_ua_model.is_none()
240    }
241}
242
243impl ClientHints<String> {
244    /// Provides the platform or operating system on which the user agent is running.
245    ///
246    /// For example: `"Windows"` or `"Android"`.
247    ///
248    /// `Sec-CH-UA-Platform` is a low entropy hint. Unless blocked by a user agent permission
249    /// policy, it is sent by default (without the server opting in by sending `Accept-CH`).
250    pub const SEC_CH_UA_PLATFORM: &'static str = "SEC-CH-UA-Platform";
251
252    /// Provides the version of the operating system on which the user agent is running.
253    pub const SEC_CH_UA_PLATFORM_VERSION: &'static str = "SEC-CH-UA-Platform-Version";
254
255    /// Provides the user agent's branding and significant version information.
256    ///
257    /// A brand is a commercial name for the user agent like: Chromium, Opera, Google Chrome,
258    /// Microsoft Edge, Firefox, and Safari. A user agent might have several associated brands. For
259    /// example, Opera, Chrome, and Edge are all based on Chromium, and will provide both brands in
260    /// the `Sec-CH-UA` header.
261    ///
262    /// The significant version is the "marketing" version identifier that is used to distinguish
263    /// between major releases of the brand. For example a Chromium build with full version number
264    /// "96.0.4664.45" has a significant version number of "96".
265    ///
266    /// The header may include "fake" brands in any position and with any name. This is a feature
267    /// designed to prevent servers from rejecting unknown user agents outright, forcing user agents
268    /// to lie about their brand identity.
269    ///
270    /// `Sec-CH-UA` is a low entropy hint. Unless blocked by a user agent permission policy, it is
271    /// sent by default (without the server opting in by sending `Accept-CH`).
272    pub const SEC_CH_UA: &'static str = "SEC-CH-UA";
273
274    /// Indicates the device model on which the browser is running.
275    pub const SEC_CH_UA_MODEL: &'static str = "SEC-CH-UA-Model";
276
277    /// Returns an instance of `ClientHints` that borrows from the original data.
278    pub fn as_deref(&self) -> ClientHints<&str> {
279        ClientHints {
280            sec_ch_ua_platform: self.sec_ch_ua_platform.as_deref(),
281            sec_ch_ua_platform_version: self.sec_ch_ua_platform_version.as_deref(),
282            sec_ch_ua: self.sec_ch_ua.as_deref(),
283            sec_ch_ua_model: self.sec_ch_ua_model.as_deref(),
284        }
285    }
286}
287
288impl ClientHints<&str> {
289    /// Returns the normalized browser name and version from the client hints.
290    pub fn browser(&self) -> Option<(&str, &str)> {
291        let (name, version) = browser_from_client_hints(self.sec_ch_ua?)?;
292        Some((normalize_browser_name(name), version))
293    }
294
295    /// Creates owned [`ClientHints`].
296    pub fn to_owned(&self) -> ClientHints<String> {
297        ClientHints {
298            sec_ch_ua_platform: self.sec_ch_ua_platform.map(Into::into),
299            sec_ch_ua_platform_version: self.sec_ch_ua_platform_version.map(Into::into),
300            sec_ch_ua: self.sec_ch_ua.map(Into::into),
301            sec_ch_ua_model: self.sec_ch_ua_model.map(Into::into),
302        }
303    }
304}
305
306/// Computes a [`Context`] from either a user agent string and client hints.
307pub trait FromUserAgentInfo: Sized {
308    /// Tries to populate the context from client hints.
309    fn parse_client_hints(client_hints: &ClientHints<&str>) -> Option<Self>;
310
311    /// Tries to populate the context from a user agent header string.
312    fn parse_user_agent(user_agent: &str) -> Option<Self>;
313
314    /// Tries to populate the context from client hints or a user agent header string.
315    fn from_hints_or_ua(raw_info: &RawUserAgentInfo<&str>) -> Option<Self> {
316        Self::parse_client_hints(&raw_info.client_hints)
317            .or_else(|| raw_info.user_agent.and_then(Self::parse_user_agent))
318    }
319}
320
321impl FromUserAgentInfo for DeviceContext {
322    fn parse_client_hints(client_hints: &ClientHints<&str>) -> Option<Self> {
323        let device = client_hints.sec_ch_ua_model?.trim().replace('\"', "");
324
325        if device.is_empty() {
326            return None;
327        }
328
329        Some(Self {
330            model: Annotated::new(device),
331            ..Default::default()
332        })
333    }
334
335    fn parse_user_agent(user_agent: &str) -> Option<Self> {
336        let device = relay_ua::parse_device(user_agent);
337
338        if !is_known(&device.family) {
339            return None;
340        }
341
342        Some(Self {
343            family: Annotated::new(device.family.into_owned()),
344            model: Annotated::from(device.model.map(|cow| cow.into_owned())),
345            brand: Annotated::from(device.brand.map(|cow| cow.into_owned())),
346            ..DeviceContext::default()
347        })
348    }
349}
350
351fn normalize_browser_name(name: &str) -> &str {
352    match name {
353        "Google Chrome" => "Chrome",
354        _ => name,
355    }
356}
357
358impl FromUserAgentInfo for BrowserContext {
359    fn parse_client_hints(client_hints: &ClientHints<&str>) -> Option<Self> {
360        let (browser, version) = client_hints.browser()?;
361
362        Some(Self {
363            name: Annotated::new(browser.to_owned()),
364            version: Annotated::new(version.to_owned()),
365            ..Default::default()
366        })
367    }
368
369    fn parse_user_agent(user_agent: &str) -> Option<Self> {
370        let browser = relay_ua::parse_user_agent(user_agent);
371
372        if !is_known(&browser.family) {
373            return None;
374        }
375
376        Some(Self {
377            name: Annotated::from(normalize_browser_name(&browser.family).to_owned()),
378            version: Annotated::from(get_version(&browser.major, &browser.minor, &browser.patch)),
379            ..BrowserContext::default()
380        })
381    }
382}
383
384/// The sec-ch-ua field looks something like this:
385/// "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"
386/// The order of the items are randomly shuffled.
387///
388/// It tries to detect the "not a brand" item and the browser engine, if it's neither its assumed
389/// to be a browser and gets returned as such.
390///
391/// Returns borrowed values so callers can bound them before copying, or None if no browser is detected.
392pub fn browser_from_client_hints(s: &str) -> Option<(&str, &str)> {
393    static UA_RE: OnceLock<Regex> = OnceLock::new();
394    let regex = UA_RE.get_or_init(|| Regex::new(r#""([^"]*)";v="([^"]*)""#).unwrap());
395    for item in s.split(',') {
396        // if it contains one of these then we can know it isn't a browser field. atm chromium
397        // browsers are the only ones supporting client hints.
398        if item.contains("Brand")
399            || item.contains("Chromium")
400            || item.contains("Gecko") // useless until firefox and safari support client hints
401            || item.contains("WebKit")
402        {
403            continue;
404        }
405
406        let captures = regex.captures(item)?;
407
408        let browser = captures.get(1)?.as_str();
409        let version = captures.get(2)?.as_str();
410
411        if browser.trim().is_empty() || version.trim().is_empty() {
412            return None;
413        }
414
415        return Some((browser, version));
416    }
417    None
418}
419
420impl FromUserAgentInfo for OsContext {
421    fn parse_client_hints(client_hints: &ClientHints<&str>) -> Option<Self> {
422        let platform = client_hints.sec_ch_ua_platform?.trim().replace('\"', "");
423
424        // We only return early if the platform is empty, not the version number. This is because
425        // an empty version number might suggest that the user need to request additional
426        // client hints data.
427        if platform.is_empty() {
428            return None;
429        }
430
431        let version = client_hints
432            .sec_ch_ua_platform_version
433            .map(|version| version.trim().replace('\"', ""));
434
435        Some(Self {
436            name: Annotated::new(platform),
437            version: Annotated::from(version),
438            ..Default::default()
439        })
440    }
441
442    fn parse_user_agent(user_agent: &str) -> Option<Self> {
443        let os = relay_ua::parse_os(user_agent);
444        let mut version = get_version(&os.major, &os.minor, &os.patch);
445
446        if !is_known(&os.family) {
447            return None;
448        }
449
450        let name = os.family.into_owned();
451
452        // Since user-agent strings freeze the OS-version at windows 10 and mac os 10.15.7,
453        // we will indicate that the version may in reality be higher.
454        if name == "Windows" {
455            if let Some(v) = version.as_mut()
456                && v == "10"
457            {
458                v.insert_str(0, ">=");
459            }
460        } else if name == "Mac OS X"
461            && let Some(v) = version.as_mut()
462            && v == "10.15.7"
463        {
464            v.insert_str(0, ">=");
465        }
466
467        Some(Self {
468            name: Annotated::new(name),
469            version: Annotated::from(version),
470            ..OsContext::default()
471        })
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use relay_event_schema::protocol::{PairList, Request};
478    use relay_protocol::assert_annotated_snapshot;
479
480    use super::*;
481
482    /// Creates an Event with the specified user agent.
483    fn get_event_with_user_agent(user_agent: &str) -> Event {
484        let headers = vec![
485            Annotated::new((
486                Annotated::new("Accept".to_owned().into()),
487                Annotated::new("application/json".to_owned().into()),
488            )),
489            Annotated::new((
490                Annotated::new("UsEr-AgeNT".to_owned().into()),
491                Annotated::new(user_agent.to_owned().into()),
492            )),
493            Annotated::new((
494                Annotated::new("WWW-Authenticate".to_owned().into()),
495                Annotated::new("basic".to_owned().into()),
496            )),
497        ];
498
499        Event {
500            request: Annotated::new(Request {
501                headers: Annotated::new(Headers(PairList(headers))),
502                ..Request::default()
503            }),
504            ..Event::default()
505        }
506    }
507
508    const GOOD_UA: &str = "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19";
509
510    #[test]
511    fn test_version_none() {
512        assert_eq!(get_version(&None, &None, &None), None);
513    }
514
515    #[test]
516    fn test_version_major() {
517        assert_eq!(
518            get_version(&Some("X".into()), &None, &None),
519            Some("X".into())
520        )
521    }
522
523    #[test]
524    fn test_version_major_minor() {
525        assert_eq!(
526            get_version(&Some("X".into()), &Some("Y".into()), &None),
527            Some("X.Y".into())
528        )
529    }
530
531    #[test]
532    fn test_version_major_minor_patch() {
533        assert_eq!(
534            get_version(&Some("X".into()), &Some("Y".into()), &Some("Z".into())),
535            Some("X.Y.Z".into())
536        )
537    }
538
539    #[test]
540    fn test_verison_missing_minor() {
541        assert_eq!(
542            get_version(&Some("X".into()), &None, &Some("Z".into())),
543            Some("X".into())
544        )
545    }
546
547    #[test]
548    fn test_skip_no_user_agent() {
549        let mut event = Event::default();
550        normalize_user_agent(&mut event);
551        assert_eq!(event.contexts.value(), None);
552    }
553
554    #[test]
555    fn test_skip_unrecognizable_user_agent() {
556        let mut event = get_event_with_user_agent("a dont no");
557        normalize_user_agent(&mut event);
558        assert!(event.contexts.value().unwrap().0.is_empty());
559    }
560
561    #[test]
562    fn test_browser_context() {
563        let ua = "Mozilla/5.0 (-; -; -) - Chrome/18.0.1025.133 Mobile Safari/535.19";
564
565        let mut event = get_event_with_user_agent(ua);
566        normalize_user_agent(&mut event);
567        assert_annotated_snapshot!(event.contexts, @r###"
568        {
569          "browser": {
570            "name": "Chrome Mobile",
571            "version": "18.0.1025",
572            "type": "browser"
573          }
574        }
575        "###);
576    }
577
578    #[test]
579    fn test_os_context() {
580        let ua = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) - -";
581
582        let mut event = get_event_with_user_agent(ua);
583        normalize_user_agent(&mut event);
584        assert_annotated_snapshot!(event.contexts, @r###"
585        {
586          "client_os": {
587            "name": "Windows",
588            "version": "7",
589            "type": "os"
590          }
591        }
592        "###);
593    }
594
595    #[test]
596    fn test_os_context_short_version() {
597        let ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) - (-)";
598        let mut event = get_event_with_user_agent(ua);
599        normalize_user_agent(&mut event);
600        assert_annotated_snapshot!(event.contexts, @r###"
601        {
602          "browser": {
603            "name": "Mobile Safari UI/WKWebView",
604            "type": "browser"
605          },
606          "client_os": {
607            "name": "iOS",
608            "version": "12.1",
609            "type": "os"
610          },
611          "device": {
612            "family": "iPhone",
613            "model": "iPhone",
614            "brand": "Apple",
615            "type": "device"
616          }
617        }
618        "###);
619    }
620
621    #[test]
622    fn test_os_context_full_version() {
623        let ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) - (-)";
624        let mut event = get_event_with_user_agent(ua);
625        normalize_user_agent(&mut event);
626        assert_annotated_snapshot!(event.contexts, @r###"
627        {
628          "client_os": {
629            "name": "Mac OS X",
630            "version": "10.13.4",
631            "type": "os"
632          },
633          "device": {
634            "family": "Mac",
635            "model": "Mac",
636            "brand": "Apple",
637            "type": "device"
638          }
639        }
640        "###);
641    }
642
643    #[test]
644    fn test_device_context() {
645        let ua = "- (-; -; Galaxy Nexus Build/IMM76B) - (-) ";
646
647        let mut event = get_event_with_user_agent(ua);
648        normalize_user_agent(&mut event);
649        assert_annotated_snapshot!(event.contexts, @r###"
650        {
651          "device": {
652            "family": "Samsung Galaxy Nexus",
653            "model": "Galaxy Nexus",
654            "brand": "Samsung",
655            "type": "device"
656          }
657        }
658        "###);
659    }
660
661    #[test]
662    fn test_all_contexts() {
663        let mut event = get_event_with_user_agent(GOOD_UA);
664        normalize_user_agent(&mut event);
665        assert_annotated_snapshot!(event.contexts, @r###"
666        {
667          "browser": {
668            "name": "Chrome Mobile",
669            "version": "18.0.1025",
670            "type": "browser"
671          },
672          "client_os": {
673            "name": "Android",
674            "version": "4.0.4",
675            "type": "os"
676          },
677          "device": {
678            "family": "Samsung Galaxy Nexus",
679            "model": "Galaxy Nexus",
680            "brand": "Samsung",
681            "type": "device"
682          }
683        }
684        "###);
685    }
686
687    #[test]
688    fn test_user_agent_does_not_override_prefilled() {
689        let mut event = get_event_with_user_agent(GOOD_UA);
690        let mut contexts = Contexts::new();
691        contexts.add(BrowserContext {
692            name: Annotated::from("BR_FAMILY".to_owned()),
693            version: Annotated::from("BR_VERSION".to_owned()),
694            ..BrowserContext::default()
695        });
696        contexts.add(DeviceContext {
697            family: Annotated::from("DEV_FAMILY".to_owned()),
698            model: Annotated::from("DEV_MODEL".to_owned()),
699            brand: Annotated::from("DEV_BRAND".to_owned()),
700            ..DeviceContext::default()
701        });
702        contexts.add(OsContext {
703            name: Annotated::from("OS_FAMILY".to_owned()),
704            version: Annotated::from("OS_VERSION".to_owned()),
705            ..OsContext::default()
706        });
707
708        event.contexts = Annotated::new(contexts);
709
710        normalize_user_agent(&mut event);
711        assert_annotated_snapshot!(event.contexts, @r###"
712        {
713          "browser": {
714            "name": "BR_FAMILY",
715            "version": "BR_VERSION",
716            "type": "browser"
717          },
718          "client_os": {
719            "name": "Android",
720            "version": "4.0.4",
721            "type": "os"
722          },
723          "device": {
724            "family": "DEV_FAMILY",
725            "model": "DEV_MODEL",
726            "brand": "DEV_BRAND",
727            "type": "device"
728          },
729          "os": {
730            "name": "OS_FAMILY",
731            "version": "OS_VERSION",
732            "type": "os"
733          }
734        }
735        "###);
736    }
737
738    #[test]
739    fn test_fallback_to_ua_if_no_client_hints() {
740        let headers = Headers([
741            Annotated::new((
742                Annotated::new("user-agent".to_owned().into()),
743                Annotated::new(r#""Mozilla/5.0 (Linux; Android 11; foo g31(w)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Mobile Safari/537.36""#.to_owned().into()),
744            )),
745            Annotated::new((
746                Annotated::new("invalid header".to_owned().into()),
747                Annotated::new("moto g31(w)".to_owned().into()),
748            )),
749        ].into_iter().collect());
750
751        let device = DeviceContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers));
752        assert_eq!(device.unwrap().family.as_str().unwrap(), "foo g31(w)");
753    }
754    #[test]
755    fn test_use_client_hints_for_device() {
756        let headers = Headers([
757            Annotated::new((
758                Annotated::new("user-agent".to_owned().into()),
759                Annotated::new(r#""Mozilla/5.0 (Linux; Android 11; foo g31(w)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Mobile Safari/537.36""#.to_owned().into()),
760            )),
761            Annotated::new((
762                Annotated::new("SEC-CH-UA-MODEL".to_owned().into()),
763                Annotated::new("moto g31(w)".to_owned().into()),
764            )),
765        ].into_iter().collect());
766
767        let device = DeviceContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers));
768        assert_eq!(device.unwrap().model.as_str().unwrap(), "moto g31(w)");
769    }
770
771    #[test]
772    fn test_strip_whitespace_and_quotes() {
773        let headers = Headers(
774            [Annotated::new((
775                Annotated::new("SEC-CH-UA-MODEL".to_owned().into()),
776                Annotated::new("   \"moto g31(w)\"".to_owned().into()),
777            ))]
778            .into_iter()
779            .collect(),
780        );
781
782        let device = DeviceContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers));
783        assert_eq!(device.unwrap().model.as_str().unwrap(), "moto g31(w)");
784    }
785
786    #[test]
787    fn test_ignore_empty_device() {
788        let headers = Headers(
789            [Annotated::new((
790                Annotated::new("SEC-CH-UA-MODEL".to_owned().into()),
791                Annotated::new("".to_owned().into()),
792            ))]
793            .into_iter()
794            .collect(),
795        );
796
797        let client_hints = RawUserAgentInfo::from_headers(&headers).client_hints;
798        let from_hints = DeviceContext::parse_client_hints(&client_hints);
799        assert!(from_hints.is_none())
800    }
801
802    #[test]
803    fn test_client_hint_parser() {
804        let chrome = browser_from_client_hints(
805            r#"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"#,
806        )
807        .unwrap();
808        assert_eq!(chrome.0, "Google Chrome".to_owned());
809        assert_eq!(chrome.1, "109".to_owned());
810
811        let opera = browser_from_client_hints(
812            r#""Chromium";v="108", "Opera";v="94", "Not)A;Brand";v="99""#,
813        )
814        .unwrap();
815        assert_eq!(opera.0, "Opera".to_owned());
816        assert_eq!(opera.1, "94".to_owned());
817
818        let mystery_browser = browser_from_client_hints(
819            r#""Chromium";v="108", "mystery-browser";v="94", "Not)A;Brand";v="99""#,
820        )
821        .unwrap();
822
823        assert_eq!(mystery_browser.0, "mystery-browser".to_owned());
824        assert_eq!(mystery_browser.1, "94".to_owned());
825    }
826
827    #[test]
828    fn test_client_hints_detected() {
829        let headers = Headers({
830            let headers = vec![
831            Annotated::new((
832                Annotated::new("user-agent".to_owned().into()),
833                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
834            )),
835            Annotated::new((
836                Annotated::new("SEC-CH-UA".to_owned().into()),
837                Annotated::new(r#"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"#.to_owned().into()),
838            )),
839        ];
840            PairList(headers)
841        });
842
843        let browser =
844            BrowserContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
845
846        insta::assert_debug_snapshot!(browser, @r###"
847        BrowserContext {
848            browser: ~,
849            name: "Chrome",
850            version: "109",
851            other: {},
852        }
853        "###);
854    }
855
856    #[test]
857    fn test_ignore_empty_browser() {
858        let headers = Headers({
859            let headers = vec![Annotated::new((
860                Annotated::new("SEC-CH-UA".to_owned().into()),
861                Annotated::new(
862                    // browser field missing
863                    r#"Not_A Brand";v="99", " ";v="109", "Chromium";v="109"#
864                        .to_owned()
865                        .into(),
866                ),
867            ))];
868            PairList(headers)
869        });
870
871        let client_hints = RawUserAgentInfo::from_headers(&headers).client_hints;
872        let from_hints = BrowserContext::parse_client_hints(&client_hints);
873        assert!(from_hints.is_none())
874    }
875
876    #[test]
877    fn test_client_hints_with_unknown_browser() {
878        let headers = Headers({
879            let headers = vec![
880            Annotated::new((
881                Annotated::new("user-agent".to_owned().into()),
882                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
883            )),
884            Annotated::new((
885                Annotated::new("SEC-CH-UA".to_owned().into()),
886                Annotated::new(r#"Not_A Brand";v="99", "weird browser";v="109", "Chromium";v="109"#.to_owned().into()),
887            )),
888            Annotated::new((
889                Annotated::new("SEC-CH-UA-FULL-VERSION".to_owned().into()),
890                Annotated::new("109.0.5414.87".to_owned().into()),
891            )),
892        ];
893            PairList(headers)
894        });
895
896        let browser =
897            BrowserContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
898
899        insta::assert_debug_snapshot!(browser, @r###"
900        BrowserContext {
901            browser: ~,
902            name: "weird browser",
903            version: "109",
904            other: {},
905        }
906        "###);
907    }
908
909    #[test]
910    fn fallback_on_ua_string_when_missing_browser_field() {
911        let headers = Headers({
912            let headers = vec![
913            Annotated::new((
914                Annotated::new("user-agent".to_owned().into()),
915                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
916            )),
917            Annotated::new((
918                Annotated::new("SEC-CH-UA".to_owned().into()),
919                Annotated::new(r#"Not_A Brand";v="99", "Chromium";v="108"#.to_owned().into()), // no browser field here
920            )),
921        ];
922            PairList(headers)
923        });
924
925        let browser =
926            BrowserContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
927        assert_eq!(
928            browser.version.as_str().unwrap(),
929            "109.0.0" // notice the version number is from UA string not from client hints
930        );
931
932        assert_eq!("Chrome", browser.name.as_str().unwrap());
933    }
934
935    #[test]
936    fn test_strip_quotes() {
937        let headers = Headers({
938            let headers = vec![
939                Annotated::new((
940                    Annotated::new("SEC-CH-UA-PLATFORM".to_owned().into()),
941                    Annotated::new("\"macOS\"".to_owned().into()), // no browser field here
942                )),
943                Annotated::new((
944                    Annotated::new("SEC-CH-UA-PLATFORM-VERSION".to_owned().into()),
945                    Annotated::new("\"13.1.0\"".to_owned().into()),
946                )),
947            ];
948            PairList(headers)
949        });
950        let os = OsContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers));
951
952        assert_eq!(os.clone().unwrap().name.value().unwrap(), "macOS");
953        assert_eq!(os.unwrap().version.value().unwrap(), "13.1.0");
954    }
955
956    /// Verifies that client hints are chosen over ua string when available.
957    #[test]
958    fn test_choose_client_hints_for_os_context() {
959        let headers = Headers({
960            let headers = vec![
961            Annotated::new((
962                Annotated::new("user-agent".to_owned().into()),
963                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
964            )),
965            Annotated::new((
966                Annotated::new("SEC-CH-UA-PLATFORM".to_owned().into()),
967                Annotated::new(r#"macOS"#.to_owned().into()), // no browser field here
968            )),
969            Annotated::new((
970                Annotated::new("SEC-CH-UA-PLATFORM-VERSION".to_owned().into()),
971                Annotated::new("13.1.0".to_owned().into()),
972            )),
973        ];
974            PairList(headers)
975        });
976
977        let os = OsContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
978
979        insta::assert_debug_snapshot!(os, @r###"
980        OsContext {
981            os: ~,
982            name: "macOS",
983            version: "13.1.0",
984            build: ~,
985            kernel_version: ~,
986            rooted: ~,
987            distribution_name: ~,
988            distribution_version: ~,
989            distribution_pretty_name: ~,
990            raw_description: ~,
991            other: {},
992        }
993        "###);
994    }
995
996    #[test]
997    fn test_ignore_empty_os() {
998        let headers = Headers({
999            let headers = vec![Annotated::new((
1000                Annotated::new("SEC-CH-UA-PLATFORM".to_owned().into()),
1001                Annotated::new(r#""#.to_owned().into()),
1002            ))];
1003            PairList(headers)
1004        });
1005
1006        let client_hints = RawUserAgentInfo::from_headers(&headers).client_hints;
1007        let from_hints = OsContext::parse_client_hints(&client_hints);
1008        assert!(from_hints.is_none())
1009    }
1010
1011    #[test]
1012    fn test_keep_empty_os_version() {
1013        let headers = Headers({
1014            let headers = vec![
1015                Annotated::new((
1016                    Annotated::new("SEC-CH-UA-PLATFORM".to_owned().into()),
1017                    Annotated::new(r#"macOs"#.to_owned().into()),
1018                )),
1019                Annotated::new((
1020                    Annotated::new("SEC-CH-UA-PLATFORM-VERSION".to_owned().into()),
1021                    Annotated::new("".to_owned().into()),
1022                )),
1023            ];
1024            PairList(headers)
1025        });
1026
1027        let client_hints = RawUserAgentInfo::from_headers(&headers).client_hints;
1028        let from_hints = OsContext::parse_client_hints(&client_hints);
1029        assert!(from_hints.is_some())
1030    }
1031
1032    #[test]
1033    fn test_fallback_on_ua_string_for_os() {
1034        let headers = Headers({
1035            let headers = vec![
1036            Annotated::new((
1037                Annotated::new("user-agent".to_owned().into()),
1038                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
1039            )),
1040            Annotated::new((
1041                Annotated::new("invalid header".to_owned().into()),
1042                Annotated::new(r#"macOS"#.to_owned().into()),
1043            )),
1044            Annotated::new((
1045                Annotated::new("SEC-CH-UA-PLATFORM-VERSION".to_owned().into()),
1046                Annotated::new("13.1.0".to_owned().into()),
1047            )),
1048        ];
1049            PairList(headers)
1050        });
1051
1052        let os = OsContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
1053
1054        insta::assert_debug_snapshot!(os, @r###"
1055        OsContext {
1056            os: ~,
1057            name: "Mac OS X",
1058            version: "10.15.6",
1059            build: ~,
1060            kernel_version: ~,
1061            rooted: ~,
1062            distribution_name: ~,
1063            distribution_version: ~,
1064            distribution_pretty_name: ~,
1065            raw_description: ~,
1066            other: {},
1067        }
1068        "###);
1069    }
1070
1071    #[test]
1072    fn test_indicate_frozen_os_windows() {
1073        let headers = Headers({
1074            let headers = vec![
1075            Annotated::new((
1076                Annotated::new("user-agent".to_owned().into()),
1077                Annotated::new(r#"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"#.to_owned().into()),
1078            )),
1079        ];
1080            PairList(headers)
1081        });
1082
1083        let os = OsContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
1084
1085        // Checks that the '>=' prefix is added.
1086        assert_eq!(os.version.value().unwrap(), ">=10");
1087    }
1088
1089    #[test]
1090    fn test_indicate_frozen_os_mac() {
1091        let headers = Headers({
1092            let headers = vec![
1093            Annotated::new((
1094                Annotated::new("user-agent".to_owned().into()),
1095                Annotated::new(r#"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"#.to_owned().into()),
1096            )),
1097        ];
1098            PairList(headers)
1099        });
1100
1101        let os = OsContext::from_hints_or_ua(&RawUserAgentInfo::from_headers(&headers)).unwrap();
1102
1103        // Checks that the '>=' prefix is added.
1104        assert_eq!(os.version.value().unwrap(), ">=10.15.7");
1105    }
1106
1107    #[test]
1108    fn test_default_empty() {
1109        assert!(RawUserAgentInfo::<&str>::default().is_empty());
1110    }
1111}