Skip to content

Commit efd9e87

Browse files
committed
fix(libdd-trace-obfuscation): cargo clippy llm pass 1
1 parent 8937e2b commit efd9e87

9 files changed

Lines changed: 93 additions & 96 deletions

File tree

libdd-trace-obfuscation/src/credit_cards.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
/// `is_card_number` checks if b could be a credit card number by checking the digit count and IIN
5-
/// prefix. If `validate_luhn` is true, the Luhn checksum is also applied to potential candidates.
5+
/// prefix.
6+
///
7+
/// If `validate_luhn` is true, the Luhn checksum is also applied to potential candidates.
68
/// Note: This code is based on the code from datadog-agent/pkg/obfuscate/credit_cards.go
79
pub fn is_card_number<T: AsRef<str>>(s: T, validate_luhn: bool) -> bool {
810
let s = s.as_ref();
@@ -15,15 +17,14 @@ pub fn is_card_number<T: AsRef<str>>(s: T, validate_luhn: bool) -> bool {
1517
let mut len = 0;
1618
for c in s.chars() {
1719
// Only valid characters are 0-9, space (" ") and dash("-")
18-
#[allow(clippy::unwrap_used)]
1920
match c {
2021
' ' | '-' => continue,
2122
'0'..='9' => {
22-
num_s[len] = c.to_digit(10).unwrap();
23+
num_s[len] = u32::from(c) - u32::from('0');
2324
len += 1;
2425
}
2526
_ => return false,
26-
};
27+
}
2728
if len > 16 {
2829
// too long for any known card number; stop looking
2930
return false;
@@ -38,13 +39,17 @@ pub fn is_card_number<T: AsRef<str>>(s: T, validate_luhn: bool) -> bool {
3839
let mut is_valid_iin = FuzzyBool::Maybe;
3940
let mut cs = num_s.iter();
4041

41-
#[allow(clippy::unwrap_used)]
42-
let mut prefix: u32 = *cs.next().unwrap();
43-
#[allow(clippy::unwrap_used)]
42+
let Some(&first_digit) = cs.next() else {
43+
return false;
44+
};
45+
let mut prefix = first_digit;
4446
while is_valid_iin == FuzzyBool::Maybe {
4547
is_valid_iin = valid_card_prefix(prefix);
4648

47-
prefix = 10 * prefix + cs.next().unwrap();
49+
let Some(next_digit) = cs.next() else {
50+
return false;
51+
};
52+
prefix = 10 * prefix + *next_digit;
4853
}
4954

5055
if is_valid_iin == FuzzyBool::True && validate_luhn {
@@ -105,7 +110,7 @@ enum FuzzyBool {
105110
const fn valid_card_prefix(n: u32) -> FuzzyBool {
106111
// Validates IIN prefix possibilities
107112
// Source: https://www.regular-expressions.info/creditcard.html
108-
if n > 699999 {
113+
if n > 699_999 {
109114
// too long for any known prefix; stop looking
110115
return FuzzyBool::False;
111116
}
@@ -139,15 +144,15 @@ const fn valid_card_prefix(n: u32) -> FuzzyBool {
139144
_ => FuzzyBool::False,
140145
};
141146
}
142-
if n < 100000 {
147+
if n < 100_000 {
143148
return match n {
144149
22210..=27209 | 50000..=50999 | 56000..=58999 | 60000..=69999 => FuzzyBool::Maybe,
145150
_ => FuzzyBool::False,
146151
};
147152
}
148-
if n < 1000000 {
153+
if n < 1_000_000 {
149154
return match n {
150-
222100..=272099 | 500000..=509999 | 560000..=589999 | 600000..=699999 => {
155+
222_100..=272_099 | 500_000..=509_999 | 560_000..=589_999 | 600_000..=699_999 => {
151156
FuzzyBool::True
152157
}
153158
_ => FuzzyBool::False,

libdd-trace-obfuscation/src/http.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -147,15 +147,12 @@ pub fn obfuscate_url_string(
147147
}
148148
}
149149

150-
let uri = match UriRef::parse(pre.as_str()) {
151-
Ok(u) => u,
152-
Err(_) => {
153-
return if remove_query_string || remove_path_digits {
154-
"?".to_string()
155-
} else {
156-
url.to_string()
157-
};
158-
}
150+
let Ok(uri) = UriRef::parse(pre.as_str()) else {
151+
return if remove_query_string || remove_path_digits {
152+
"?".to_string()
153+
} else {
154+
url.to_string()
155+
};
159156
};
160157

161158
let mut out = String::new();

libdd-trace-obfuscation/src/ip_address.rs

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,13 @@ pub fn quantize_peer_ip_addresses<'a>(s: &'a str) -> Cow<'a, str> {
4242

4343
let quantized_values = values
4444
.map(|v| {
45-
if let Some(quantize_string) = quantize_ip(v) {
46-
should_return_new_string = true;
47-
Cow::from(quantize_string)
48-
} else {
49-
Cow::from(v)
50-
}
45+
quantize_ip(v).map_or_else(
46+
|| Cow::from(v),
47+
|quantize_string| {
48+
should_return_new_string = true;
49+
Cow::from(quantize_string)
50+
},
51+
)
5152
})
5253
.collect::<Vec<Cow<'a, str>>>();
5354

@@ -89,21 +90,22 @@ fn quantize_ip(s: &str) -> Option<String> {
8990
/// Split the ip prefix, can be either a provider specific prefix or a protocol
9091
fn split_prefix(s: &str) -> (&str, &str) {
9192
#[allow(clippy::unwrap_used)]
92-
if let Some(tail) = s.strip_prefix("ip-") {
93-
("ip-", tail)
94-
} else if let Some(protocol) = PREFIX_REGEX.find(s) {
95-
s.split_at(protocol.end())
96-
} else {
97-
("", s)
98-
}
93+
s.strip_prefix("ip-").map_or_else(
94+
|| {
95+
PREFIX_REGEX
96+
.find(s)
97+
.map_or(("", s), |protocol| s.split_at(protocol.end()))
98+
},
99+
|tail| ("ip-", tail),
100+
)
99101
}
100102

101103
/// Check if `s` starts with a valid ip. If it does return Some((ip, suffix)), else return None.
102104
fn parse_ip(s: &str) -> Option<(&str, &str)> {
103105
for ch in s.chars() {
104106
// Determine the version of the ip
105107
match ch {
106-
'0'..='9' => continue,
108+
'0'..='9' => {}
107109
'.' | '-' | '_' => return parse_ip_v4(s, ch),
108110
':' | 'A'..='F' | 'a'..='f' if s.parse::<Ipv6Addr>().is_ok() => {
109111
return Some((s, ""));

libdd-trace-obfuscation/src/json.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
use crate::json_scanner::{Op, Scanner};
55
use crate::obfuscation_config::{JsonObfuscatorConfig, JsonStringTransformer};
66

7-
/// Obfuscates a JSON string by replacing all leaf values with `"?"`, unless the value
8-
/// belongs to a key listed in `keep_keys`, in which case it is left verbatim.
7+
/// Obfuscates a JSON string by replacing all leaf values with `"?"`, unless the value belongs to a
8+
/// key listed in `keep_keys`, in which case it is left verbatim.
9+
///
910
/// Keys in `transform_keys` have their string values passed through a transformer function
1011
/// (e.g. SQL obfuscation) instead of being replaced with `"?"`.
1112
///
@@ -67,7 +68,7 @@ impl JsonObfuscator {
6768
&mut buf,
6869
&mut keeping,
6970
&mut transforming_value,
70-
&mut keep_depth,
71+
keep_depth,
7172
depth,
7273
self.config.transformer.as_ref(),
7374
);
@@ -79,7 +80,7 @@ impl JsonObfuscator {
7980
&mut buf,
8081
&mut keeping,
8182
&mut transforming_value,
82-
&mut keep_depth,
83+
keep_depth,
8384
depth,
8485
self.config.transformer.as_ref(),
8586
);
@@ -145,7 +146,7 @@ fn handle_value_done(
145146
buf: &mut String,
146147
keeping: &mut bool,
147148
transforming_value: &mut bool,
148-
keep_depth: &mut usize,
149+
keep_depth: usize,
149150
depth: usize,
150151
transformer: Option<&JsonStringTransformer>,
151152
) {
@@ -161,7 +162,7 @@ fn handle_value_done(
161162
*transforming_value = false;
162163
buf.clear();
163164
}
164-
} else if *keeping && depth < *keep_depth {
165+
} else if *keeping && depth < keep_depth {
165166
*keeping = false;
166167
}
167168
}

libdd-trace-obfuscation/src/obfuscate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ pub fn obfuscate_span(span: &mut pb::Span, config: &ObfuscationConfig) {
101101
.and_then(|dbms| TryInto::try_into(dbms).ok())
102102
.unwrap_or_default();
103103
let obfuscated_query = crate::sql::obfuscate_sql(&span.resource, &config.sql, dbms);
104-
span.resource = obfuscated_query.clone();
104+
span.resource.clone_from(&obfuscated_query);
105105
span.meta.insert(TAG_SQLQUERY.to_owned(), obfuscated_query);
106106
}
107107
"elasticsearch" if config.elasticsearch.enabled => {

libdd-trace-obfuscation/src/obfuscation_config.rs

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,20 +95,26 @@ pub struct ObfuscationConfig {
9595
}
9696

9797
impl ObfuscationConfig {
98+
/// Builds the obfuscation config from environment variables.
99+
///
100+
/// # Errors
101+
///
102+
/// Returns an error if one of the regular expressions used by the config cannot be compiled.
98103
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
99-
let tag_replace_rules: Option<Vec<ReplaceRule>> = match env::var("DD_APM_REPLACE_TAGS") {
100-
Ok(replace_rules_str) => match replacer::parse_rules_from_string(&replace_rules_str) {
101-
Ok(res) => {
102-
debug!("Successfully parsed DD_APM_REPLACE_TAGS: {res:?}");
103-
Some(res)
104-
}
105-
Err(e) => {
106-
error!("Failed to parse DD_APM_REPLACE_TAGS: {e}");
107-
None
108-
}
109-
},
110-
Err(_) => None,
111-
};
104+
let tag_replace_rules: Option<Vec<ReplaceRule>> = env::var("DD_APM_REPLACE_TAGS")
105+
.map_or_else(
106+
|_| None,
107+
|replace_rules_str| match replacer::parse_rules_from_string(&replace_rules_str) {
108+
Ok(res) => {
109+
debug!("Successfully parsed DD_APM_REPLACE_TAGS: {res:?}");
110+
Some(res)
111+
}
112+
Err(e) => {
113+
error!("Failed to parse DD_APM_REPLACE_TAGS: {e}");
114+
None
115+
}
116+
},
117+
);
112118
let http_remove_query_string =
113119
parse_env::bool("DD_APM_OBFUSCATION_HTTP_REMOVE_QUERY_STRING").unwrap_or(false);
114120
let http_remove_path_digits =

libdd-trace-obfuscation/src/redis.rs

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -128,13 +128,22 @@ fn obfuscate_redis_cmd<'a>(str: &mut String, cmd: &'a str, mut args: Vec<&'a str
128128
args.clear();
129129
args.push("?");
130130
}
131-
b"ACL"
132-
// Obfuscate all arguments after the subcommand:
131+
b"ACL" | b"GEOHASH" | b"GEOPOS" | b"GEODIST" | b"LPUSH" | b"RPUSH" | b"SREM" | b"ZREM"
132+
| b"SADD"
133+
// Obfuscate all arguments after the first token:
133134
// • ACL SETUSER username on >password ~keys &channels +commands
134135
// • ACL GETUSER username
135136
// • ACL DELUSER username [username ...]
136137
// • ACL LIST
137138
// • ACL WHOAMI
139+
// • GEOHASH key member [member ...]
140+
// • GEOPOS key member [member ...]
141+
// • GEODIST key member1 member2 [unit]
142+
// • LPUSH key value [value ...]
143+
// • RPUSH key value [value ...]
144+
// • SREM key member [member ...]
145+
// • ZREM key member [member ...]
146+
// • SADD key member [member ...]
138147
if args.len() > 1 => {
139148
args[1] = "?";
140149
args.drain(2..);
@@ -177,20 +186,6 @@ fn obfuscate_redis_cmd<'a>(str: &mut String, cmd: &'a str, mut args: Vec<&'a str
177186
// • LINSERT key BEFORE|AFTER pivot value
178187
args = obfuscate_redis_args_n(args, 3);
179188
}
180-
b"GEOHASH" | b"GEOPOS" | b"GEODIST" | b"LPUSH" | b"RPUSH" | b"SREM" | b"ZREM" | b"SADD"
181-
// Obfuscate all arguments after the first one.
182-
// • GEOHASH key member [member ...]
183-
// • GEOPOS key member [member ...]
184-
// • GEODIST key member1 member2 [unit]
185-
// • LPUSH key value [value ...]
186-
// • RPUSH key value [value ...]
187-
// • SREM key member [member ...]
188-
// • ZREM key member [member ...]
189-
// • SADD key member [member ...]
190-
if args.len() > 1 => {
191-
args[1] = "?";
192-
args.drain(2..);
193-
}
194189
b"GEOADD" => {
195190
// Obfuscating every 3rd argument starting from first
196191
// • GEOADD key longitude latitude member [longitude latitude member ...]
@@ -278,9 +273,8 @@ pub fn remove_all_redis_args(redis_cmd: &str) -> String {
278273
let mut obfuscated_cmd = String::new();
279274

280275
// If the redis command is empty, return immediately. Otherwise, store the command token.
281-
let cmd = match redis_cmd_iter.next() {
282-
Some(cmd) => cmd,
283-
None => return obfuscated_cmd,
276+
let Some(cmd) = redis_cmd_iter.next() else {
277+
return obfuscated_cmd;
284278
};
285279
obfuscated_cmd.push_str(cmd);
286280

libdd-trace-obfuscation/src/replacer.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,10 @@ pub fn replace_span_tags(span: &mut pb::Span, rules: &[ReplaceRule], scratch_spa
109109
/// `parse_rules_from_string` takes an array of rules, represented as an array of length 3 arrays
110110
/// holding the tag name, regex pattern, and replacement string as strings.
111111
/// * returns a vec of `ReplaceRules`
112+
///
113+
/// # Errors
114+
///
115+
/// Returns an error when the input is not valid JSON or a rule pattern is not a valid regex.
112116
pub fn parse_rules_from_string(
113117
// rules: &'a [[&'a str; 3]],
114118
rules: &str,

0 commit comments

Comments
 (0)