relay_event_normalization/transactions/
rules.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use std::borrow::Cow;

use chrono::{DateTime, Utc};
use relay_common::glob2::LazyGlob;
use relay_event_schema::protocol::OperationType;
use serde::{Deserialize, Serialize};

/// Object containing transaction attributes the rules must only be applied to.
///
/// This is part of [`SpanDescriptionRule`].
#[derive(Debug, Clone, Serialize, Deserialize, Default, Eq, PartialEq)]
pub struct SpanDescriptionRuleScope {
    /// The span operation type to match on.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub op: OperationType,
}

/// Default value for substitution in [`RedactionRule`].
fn default_substitution() -> String {
    "*".to_string()
}

/// Describes what to do with the matched pattern.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(tag = "method", rename_all = "snake_case")]
pub enum RedactionRule {
    /// Replaces the matched pattern with a placeholder.
    Replace {
        /// The string to substitute with.
        ///
        /// Defaults to `"*"`.
        #[serde(default = "default_substitution")]
        substitution: String,
    },

    /// Unsupported redaction rule for forward compatibility.
    #[serde(other)]
    Unknown,
}

impl Default for RedactionRule {
    fn default() -> Self {
        Self::Replace {
            substitution: default_substitution(),
        }
    }
}

/// The rule describes how span descriptions should be changed.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SpanDescriptionRule {
    /// The pattern which will be applied to the span description.
    pub pattern: LazyGlob,
    /// Date time when the rule expires and it should not be applied anymore.
    pub expiry: DateTime<Utc>,
    /// Object containing transaction attributes the rules must only be applied to.
    pub scope: SpanDescriptionRuleScope,
    /// Object describing what to do with the matched pattern.
    pub redaction: RedactionRule,
}

impl From<&TransactionNameRule> for SpanDescriptionRule {
    fn from(value: &TransactionNameRule) -> Self {
        SpanDescriptionRule {
            pattern: LazyGlob::new(format!("**{}", value.pattern.as_str())),
            expiry: value.expiry,
            scope: SpanDescriptionRuleScope::default(),
            redaction: value.redaction.clone(),
        }
    }
}

impl SpanDescriptionRule {
    /// Applies the span description rule to the given string, if it matches the pattern.
    ///
    /// TODO(iker): we should check the rule's domain, similar to transaction name rules.
    pub fn match_and_apply(&self, mut string: Cow<String>) -> Option<String> {
        let slash_is_present = string.ends_with('/');
        if !slash_is_present {
            string.to_mut().push('/');
        }
        let is_matched = self.matches(&string);

        if is_matched {
            let mut result = self.apply(&string);
            if !slash_is_present {
                result.pop();
            }
            Some(result)
        } else {
            None
        }
    }

    /// Returns `true` if the rule isn't expired yet and its pattern matches the given string.
    fn matches(&self, string: &str) -> bool {
        let now = Utc::now();
        self.expiry > now && self.pattern.compiled().is_match(string)
    }

    /// Applies the rule to the provided value.
    fn apply(&self, value: &str) -> String {
        match &self.redaction {
            RedactionRule::Replace { substitution } => self
                .pattern
                .compiled()
                .replace_captures(value, substitution),
            _ => {
                relay_log::trace!("Replacement rule type is unsupported!");
                value.to_owned()
            }
        }
    }
}

/// The rule describes how transaction name should be changed.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct TransactionNameRule {
    /// The pattern which will be applied to transaction name.
    pub pattern: LazyGlob,
    /// Date time when the rule expires and it should not be applied anymore.
    pub expiry: DateTime<Utc>,
    /// Object describing what to do with the matched pattern.
    pub redaction: RedactionRule,
}

impl TransactionNameRule {
    /// Checks is the current rule matches and tries to apply it.
    pub fn match_and_apply(&self, mut transaction: Cow<String>) -> Option<String> {
        let slash_is_present = transaction.ends_with('/');
        if !slash_is_present {
            transaction.to_mut().push('/');
        }
        let is_matched = self.matches(&transaction);

        if is_matched {
            let mut result = self.apply(&transaction);
            if !slash_is_present {
                result.pop();
            }
            Some(result)
        } else {
            None
        }
    }

    /// Applies the rule to the provided value.
    ///
    /// Note: currently only `url` source for rules supported.
    fn apply(&self, value: &str) -> String {
        match &self.redaction {
            RedactionRule::Replace { substitution } => self
                .pattern
                .compiled()
                .replace_captures(value, substitution),
            _ => {
                relay_log::trace!("Replacement rule type is unsupported!");
                value.to_owned()
            }
        }
    }

    /// Returns `true` if the current rule pattern matches transaction, expected transaction
    /// source, and not expired yet.
    fn matches(&self, transaction: &str) -> bool {
        self.expiry > Utc::now() && self.pattern.compiled().is_match(transaction)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rule_format() {
        let json = r#"
        {
          "pattern": "/auth/login/*/**",
          "expiry": "2022-11-30T00:00:00.000000Z",
          "scope": {
            "source": "url"
          },
          "redaction": {
            "method": "replace",
            "substitution": ":id"
          }
        }
        "#;

        let rule: TransactionNameRule = serde_json::from_str(json).unwrap();

        let parsed_time = DateTime::parse_from_rfc3339("2022-11-30T00:00:00Z").unwrap();
        let result = TransactionNameRule {
            pattern: LazyGlob::new("/auth/login/*/**".to_string()),
            expiry: DateTime::from_naive_utc_and_offset(parsed_time.naive_utc(), Utc),
            redaction: RedactionRule::Replace {
                substitution: String::from(":id"),
            },
        };

        assert_eq!(rule, result);
    }

    #[test]
    fn test_rule_format_defaults() {
        let json = r#"
        {
          "pattern": "/auth/login/*/**",
          "expiry": "2022-11-30T00:00:00.000000Z",
          "redaction": {
            "method": "replace"
          }
        }
        "#;

        let rule: TransactionNameRule = serde_json::from_str(json).unwrap();

        let parsed_time = DateTime::parse_from_rfc3339("2022-11-30T00:00:00Z").unwrap();
        let result = TransactionNameRule {
            pattern: LazyGlob::new("/auth/login/*/**".to_string()),
            expiry: DateTime::from_naive_utc_and_offset(parsed_time.naive_utc(), Utc),
            redaction: RedactionRule::Replace {
                substitution: default_substitution(),
            },
        };

        assert_eq!(rule, result);
    }

    #[test]
    fn test_rule_format_unsupported_reduction() {
        let json = r#"
        {
          "pattern": "/auth/login/*/**",
          "expiry": "2022-11-30T00:00:00.000000Z",
          "redaction": {
            "method": "update"
          }
        }
        "#;

        let rule: TransactionNameRule = serde_json::from_str(json).unwrap();
        let result = rule.apply("/auth/login/test/");

        assert_eq!(result, "/auth/login/test/".to_string());
    }

    #[test]
    fn test_rule_format_roundtrip() {
        let json = r#"{
  "pattern": "/auth/login/*/**",
  "expiry": "2022-11-30T00:00:00Z",
  "redaction": {
    "method": "replace",
    "substitution": ":id"
  }
}"#;

        let rule: TransactionNameRule = serde_json::from_str(json).unwrap();
        let rule_json = serde_json::to_string_pretty(&rule).unwrap();
        // Make sure that we can  serialize into the same format we receive from the wire.
        assert_eq!(json, rule_json);
    }
}