perimeterx-fastly-enforcer 2.2.2

PerimeterX Fastly Compute@Edge Rust Enforcer
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use crate::px_debug;
use crate::pxcontext::RiskHeader;
use base64::{Engine as _, engine::general_purpose};
use fastly::{Request, http::Version};
use regex::Regex;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::OnceLock;

const UUID_PATTERN: &str =
    r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";

static UUID_VALIDATOR: OnceLock<Regex> = OnceLock::new();

fn uuid_validator() -> Option<&'static Regex> {
    if let Some(re) = UUID_VALIDATOR.get() {
        return Some(re);
    }
    let Ok(re) = Regex::new(UUID_PATTERN) else {
        return None;
    };
    let _ = UUID_VALIDATOR.set(re);
    UUID_VALIDATOR.get()
}

/// Returns whether `uuid` matches the lowercase UUID v1-v5 format used by the JS enforcer.
pub fn is_valid_uuid(uuid: &str) -> bool {
    !uuid.is_empty() && uuid_validator().is_some_and(|re| re.is_match(uuid))
}

pub fn get_risk_headers(
    headers_json: &serde_json::value::Value,
    sensitive_headers: &[String],
) -> Vec<RiskHeader> {
    let mut sanitized_headers = vec![];

    if let Some(headers_obj) = headers_json.as_object() {
        for (k, v) in headers_obj {
            // case insensitive check if header is in sensitive headers list, if not add to risk headers
            if !sensitive_headers.iter().any(|h| h.eq_ignore_ascii_case(k)) {
                sanitized_headers.push(RiskHeader {
                    name: k.into(),
                    value: v.to_owned(),
                })
            }
        }
    }
    sanitized_headers
}

pub fn filter_headers(req: &mut Request, sensitive_headers: &Vec<String>) {
    for h in sensitive_headers {
        req.remove_header(h);
    }
}

/// Parse a `Cookie` or custom cookie header value into a name-to-value map.
pub fn parse_cookie_header(cookie_header: &str) -> HashMap<String, String> {
    cookie_header
        .split(";")
        .filter_map(|kv| {
            let kv = kv.trim();
            if kv.is_empty() {
                return None;
            }
            let (key, value) = kv.split_once('=')?;
            let key = key.trim();
            if key.is_empty() {
                return None;
            }
            Some((key.to_string(), value.trim().to_string()))
        })
        .collect()
}

/// Merge cookie maps; entries in `override_cookies` replace those in `base`.
pub fn merge_cookie_headers(
    base: HashMap<String, String>,
    override_cookies: HashMap<String, String>,
) -> HashMap<String, String> {
    let mut merged = base;
    merged.extend(override_cookies);
    merged
}

/// Build the merged request cookie map from `Cookie` and custom cookie header values.
pub fn build_merged_request_cookies(
    cookie_header: &str,
    custom_cookie_header: &str,
) -> HashMap<String, String> {
    merge_cookie_headers(
        parse_cookie_header(cookie_header),
        parse_cookie_header(custom_cookie_header),
    )
}

/// Return the value of a named cookie from a parsed cookie map.
pub fn extract_cookie_value(cookies: &HashMap<String, String>, name: &str) -> String {
    cookies.get(name).cloned().unwrap_or_default()
}

/// First non-empty trimmed IP from a header value (handles comma-separated lists).
pub(crate) fn first_ip_from_header_value(value: &str) -> Option<String> {
    value
        .split(',')
        .map(str::trim)
        .find(|part| !part.is_empty())
        .map(str::to_owned)
}

/// Extract client IP from configured trusted headers, in order.
pub(crate) fn extract_ip_from_configured_headers(
    req: &Request,
    ip_headers: &[String],
) -> Option<String> {
    extract_ip_from_header_values(ip_headers, |name| {
        req.get_header_str_lossy(name).map(|v| v.into_owned())
    })
}

pub(crate) fn extract_ip_from_header_values(
    ip_headers: &[String],
    get_header: impl Fn(&str) -> Option<String>,
) -> Option<String> {
    for header_name in ip_headers {
        if header_name.is_empty() {
            continue;
        }
        if let Some(header_value) = get_header(header_name.as_str()) {
            if let Some(ip) = first_ip_from_header_value(header_value.as_str()) {
                return Some(ip);
            }
        }
    }
    None
}

fn ipv4_cidr_mask(prefix: u8) -> Option<u32> {
    match prefix {
        0 => Some(0),
        8 => Some(0xFF00_0000),
        16 => Some(0xFFFF_0000),
        24 => Some(0xFFFF_FF00),
        32 => Some(0xFFFF_FFFF),
        _ => None,
    }
}

/// Returns true when `client_ip` matches an exact IPv4 or supported CIDR (`/0`, `/8`, `/16`, `/24`, `/32`).
pub(crate) fn ip_matches_filter(client_ip: &str, filter: &str) -> bool {
    let Ok(client) = client_ip.trim().parse::<Ipv4Addr>() else {
        return false;
    };

    let filter = filter.trim();
    if let Some((network_str, prefix_str)) = filter.split_once('/') {
        let Ok(prefix) = prefix_str.trim().parse::<u8>() else {
            return false;
        };
        let Some(mask) = ipv4_cidr_mask(prefix) else {
            return false;
        };
        let Ok(network) = network_str.trim().parse::<Ipv4Addr>() else {
            return false;
        };
        let client_bits = u32::from(client);
        let network_bits = u32::from(network);
        (client_bits & mask) == (network_bits & mask)
    } else {
        filter
            .parse::<Ipv4Addr>()
            .is_ok_and(|expected| client == expected)
    }
}

/// True when `x-px-authorization` carries only a mobile SDK error code.
pub(crate) fn is_mobile_sdk_error_code(value: &str) -> bool {
    !value.is_empty() && value.chars().all(|c| c.is_ascii_digit())
}

/// Parse `<token_version>:<cookie_contents>` into `("_px2"|"_px3", contents)`.
pub(crate) fn parse_versioned_mobile_token(value: &str) -> Option<(String, String)> {
    let value = value.trim();
    let (version, contents) = value.split_once(':')?;
    if contents.is_empty() {
        return None;
    }
    match version {
        "2" => Some(("_px2".to_owned(), contents.to_owned())),
        "3" => Some(("_px3".to_owned(), contents.to_owned())),
        _ => None,
    }
}
pub fn verify_route(routes: &[String], path: &str) -> bool {
    routes
        .iter()
        .any(|prefix| !prefix.is_empty() && path.starts_with(prefix))
}

pub fn get_headers_as_json(req: &Request) -> serde_json::value::Value {
    let mut headers_json = serde_json::Map::new();
    for h in req.get_header_names_str() {
        headers_json.insert(
            h.to_string(),
            serde_json::Value::String(
                req.get_header_str_lossy(h)
                    .map(|v| v.into_owned())
                    .unwrap_or_default(),
            ),
        );
    }

    serde_json::Value::Object(headers_json)
}

/// Decode the middle segment of a JWT into a JSON payload. Signature is not verified.
pub fn decode_jwt_payload(jwt: &str) -> Option<serde_json::Value> {
    let mut segments = jwt.split('.');
    let _header = segments.next()?;
    let encoded_payload = segments.next()?;
    let _signature = segments.next()?;
    if encoded_payload.is_empty() {
        return None;
    }

    let payload_bytes = general_purpose::URL_SAFE_NO_PAD
        .decode(encoded_payload)
        .or_else(|_| {
            let mut normalized = encoded_payload.replace('-', "+").replace('_', "/");
            let rem = normalized.len() % 4;
            if rem > 0 {
                normalized.push_str(&"=".repeat(4 - rem));
            }
            general_purpose::STANDARD.decode(normalized)
        })
        .ok()?;

    serde_json::from_slice(&payload_bytes).ok()
}

/// Resolve a dot-notated path against a JSON value.
pub fn get_value_at_path<'a>(
    value: &'a serde_json::Value,
    path: &str,
) -> Option<&'a serde_json::Value> {
    if path.is_empty() {
        return None;
    }

    let mut current = value;
    for part in path.split('.') {
        if part.is_empty() {
            return None;
        }
        current = current.get(part)?;
    }
    Some(current)
}

/// Match JS `if (value)` checks when deciding whether to copy JWT additional fields.
pub fn is_truthy_json_value(value: &serde_json::Value) -> bool {
    match value {
        serde_json::Value::Null => false,
        serde_json::Value::Bool(b) => *b,
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                i != 0
            } else if let Some(u) = n.as_u64() {
                u != 0
            } else if let Some(f) = n.as_f64() {
                f != 0.0
            } else {
                true
            }
        }
        serde_json::Value::String(s) => !s.is_empty(),
        serde_json::Value::Array(a) => !a.is_empty(),
        serde_json::Value::Object(o) => !o.is_empty(),
    }
}

pub fn get_cookie_json(px_cookie: &str) -> serde_json::Value {
    let default_json = serde_json::json!({});
    let px_cookie_bytes = general_purpose::STANDARD
        .decode(px_cookie)
        .unwrap_or_default();
    let decoded_px_cookie = std::str::from_utf8(&px_cookie_bytes).unwrap_or_default();

    if !decoded_px_cookie.is_empty() {
        let cookie_json: serde_json::Value =
            serde_json::from_str(decoded_px_cookie).unwrap_or_default();

        if !cookie_json.is_object() {
            px_debug!(
                "cookie value is not a valid json, value: {}",
                decoded_px_cookie
            );
            return default_json;
        }

        return cookie_json;
    };

    default_json
}

// translate fastly::http::Version into static str
pub fn get_fastly_version_str(req: &Request) -> &'static str {
    match req.get_version() {
        Version::HTTP_09 => "0.9",
        Version::HTTP_10 => "1.0",
        Version::HTTP_11 => "1.1",
        Version::HTTP_2 => "2.0",
        Version::HTTP_3 => "3.0",
        _ => "unknown",
    }
}

/// Helper function to set a JSON string value at a nested dot-separated path.
/// Creates intermediate objects if they don't exist.
/// Only sets non-empty string values.
pub fn set_json_str_at_path(root: &mut serde_json::Value, path: &str, value: &str) {
    if value.is_empty() {
        return;
    }

    let parts: Vec<&str> = path.split('.').collect();
    let mut current: &mut serde_json::Value = root;

    for (i, part) in parts.iter().enumerate() {
        if i == parts.len() - 1 {
            // Last part: set the value
            current[*part] = serde_json::Value::String(value.to_string());
        } else {
            // Intermediate part: ensure object exists
            if !current.get(*part).is_some_and(|v| v.is_object()) {
                current[*part] = serde_json::json!({});
            }
            current = &mut current[*part];
        }
    }
}

/// Safely set a JSON string value at a nested path.
/// Accepts a mutable reference to the root JSON object, a dot-separated path string, and a value.
/// Creates intermediate objects if they don't exist.
/// Only sets non-empty string values.
///
/// # Usage
/// ```text
/// set_json_str!(&mut root, "field"; value);
/// set_json_str!(&mut root, "level1.level2"; value);
/// set_json_str!(&mut root, "level1.level2.level3"; value);
/// // For already-mutable references:
/// set_json_str!(details, "field"; value);
/// ```
macro_rules! set_json_str {
    ($root:expr, $path:expr; $value:expr) => {{
        use $crate::modules::pxutils::set_json_str_at_path;

        // Get the string value
        let str_value: String = $value.to_string();

        set_json_str_at_path($root, $path, &str_value);
    }};
}
pub(crate) use set_json_str;

/// Helper function to set a JSON integer value at a nested dot-separated path.
/// Creates intermediate objects if they don't exist.
pub fn set_json_int_at_path(root: &mut serde_json::Value, path: &str, value: i64) {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current: &mut serde_json::Value = root;

    for (i, part) in parts.iter().enumerate() {
        if i == parts.len() - 1 {
            // Last part: set the value
            current[*part] = serde_json::Value::Number(serde_json::Number::from(value));
        } else {
            // Intermediate part: ensure object exists
            if !current.get(*part).is_some_and(|v| v.is_object()) {
                current[*part] = serde_json::json!({});
            }
            current = &mut current[*part];
        }
    }
}

/// Safely set a JSON integer value at a nested path.
/// Accepts a mutable reference to the root JSON object, a dot-separated path string, and a value.
/// Creates intermediate objects if they don't exist.
/// Accepts u8, u16, or i64 values.
///
/// # Usage
/// ```text
/// set_json_int!(&mut root, "field"; value);
/// set_json_int!(&mut root, "level1.level2"; value);
/// set_json_int!(&mut root, "level1.level2.level3"; value);
/// // For already-mutable references:
/// set_json_int!(details, "field"; value);
/// ```
macro_rules! set_json_int {
    ($root:expr, $path:expr; $value:expr) => {{
        use $crate::modules::pxutils::set_json_int_at_path;

        // Convert to i64 (works for u8, u16, i64)
        let int_value: i64 = $value as i64;

        set_json_int_at_path($root, $path, int_value);
    }};
}
pub(crate) use set_json_int;