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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
use super::pxconfig::{PXConfig, PXCustomParams};
pub use crate::handlers::pxagentic_trust::AgenticTrustData;
pub use crate::handlers::pxcredentials_intelligence::PXCredentialIntelligenceData;
use crate::handlers::pxcrypto;
use crate::handlers::pxgraphql::PXGraphQLExtractedItem;
use crate::modules::{pxconstants::*, pxutils};
use crate::px_debug;
use base64::{Engine as _, engine::general_purpose};
use fastly::Request;
use fastly::http::header::COOKIE;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use strum_macros::{AsRefStr, Display, EnumString};
use uuid::Uuid;

#[derive(Debug, PartialEq, Default)]
pub enum CallReason {
    #[default]
    None,
    NoCookie,
    NoCookieWVid,
    CookieDecryptionFailed,
    CookieValidationFailed,
    CookieExpired,
    SensitiveRoute,
    MobileSdkConnectionError,
    MobileError1,
    MobileError2,
    MobileError3,
    MobileError4,
}
impl fmt::Display for CallReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CallReason::None => {
                write!(f, "none")
            }
            CallReason::NoCookie => {
                write!(f, "no_cookie")
            }
            CallReason::NoCookieWVid => {
                write!(f, "no_cookie_w_vid")
            }
            CallReason::CookieDecryptionFailed => {
                write!(f, "cookie_decryption_failed")
            }
            CallReason::CookieValidationFailed => {
                write!(f, "cookie_validation_failed")
            }
            CallReason::CookieExpired => {
                write!(f, "cookie_expired")
            }
            CallReason::SensitiveRoute => {
                write!(f, "sensitive_route")
            }
            CallReason::MobileSdkConnectionError => {
                write!(f, "mobile_sdk_connection_error")
            }
            CallReason::MobileError1 => {
                write!(f, "mobile_error_1")
            }
            CallReason::MobileError2 => {
                write!(f, "mobile_error_2")
            }
            CallReason::MobileError3 => {
                write!(f, "mobile_error_3")
            }
            CallReason::MobileError4 => {
                write!(f, "mobile_error_4")
            }
        }
    }
}

impl CallReason {
    pub(crate) fn is_mobile_sdk_error(&self) -> bool {
        matches!(
            self,
            CallReason::MobileError1
                | CallReason::MobileError2
                | CallReason::MobileError3
                | CallReason::MobileError4
                | CallReason::MobileSdkConnectionError
        )
    }
}

#[derive(PartialEq, Default)]
pub enum PassReason {
    #[default]
    None,
    Cookie,
    Error,
    S2s,
}

impl fmt::Display for PassReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PassReason::None => {
                write!(f, "none")
            }
            PassReason::Cookie => {
                write!(f, "cookie")
            }
            PassReason::Error => {
                write!(f, "s2s_error")
            }
            PassReason::S2s => {
                write!(f, "s2s")
            }
        }
    }
}

#[derive(PartialEq, Default)]
pub enum BlockReason {
    #[default]
    None,
    CookieScore,
    ServerScore,
    Challenge,
}
impl fmt::Display for BlockReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            BlockReason::None => {
                write!(f, "none")
            }
            BlockReason::CookieScore => {
                write!(f, "cookie_high_score")
            }
            BlockReason::ServerScore => {
                write!(f, "s2s_high_score")
            }
            BlockReason::Challenge => {
                write!(f, "challenge")
            }
        }
    }
}

#[derive(Default, PartialEq)]
pub enum S2sErrorReason {
    #[default]
    None,
    FailedOnServer,
    InvalidResponse,
    BadRequest,
    ServerError,
    Unknown,
}
impl fmt::Display for S2sErrorReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            S2sErrorReason::None => {
                write!(f, "none")
            }
            S2sErrorReason::FailedOnServer => {
                write!(f, "request_failed_on_server")
            }
            S2sErrorReason::InvalidResponse => {
                write!(f, "invalid_response")
            }
            S2sErrorReason::BadRequest => {
                write!(f, "bad_request")
            }
            S2sErrorReason::ServerError => {
                write!(f, "server_error")
            }
            S2sErrorReason::Unknown => {
                write!(f, "unknown_error")
            }
        }
    }
}

/// Working mode of the Enforcer
#[derive(Debug, Default, PartialEq, Clone, Copy, AsRefStr, Display, EnumString)]
pub enum PXModuleMode {
    #[default]
    #[strum(serialize = "monitor")]
    Monitor,
    #[strum(
        serialize = "active_blocking",
        serialize = "blocking",
        serialize = "blocked"
    )]
    Blocking,
}

#[derive(Debug, Default, PartialEq, Clone, Copy, AsRefStr, Display, EnumString)]
pub enum TokenVersion {
    #[strum(serialize = "2")]
    V2,
    #[default]
    #[strum(serialize = "3")]
    V3,
}

#[derive(Debug, Default, PartialEq)]
pub enum CookieOrigin {
    #[default]
    Cookie,
    Header,
}

#[derive(Default, PartialEq)]
pub enum CookieVersion {
    V2,
    #[default]
    V3,
}

/// How the visitor ID (`vid`) was obtained for Risk API / activity payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRefStr, Display, EnumString)]
pub enum VidSource {
    #[strum(serialize = "vid_cookie")]
    VidCookie,
    #[strum(serialize = "risk_cookie")]
    RiskCookie,
}

#[derive(Debug, Serialize)]
pub(crate) struct RiskHeader {
    pub name: String,
    pub value: serde_json::Value,
}

/// Data Enrichment, available after calling `PXEnforcer::enforce()`
#[derive(Deserialize, Debug, Default)]
pub struct PXDataEnrichment {
    pub(crate) timestamp: Option<i64>,
    pub(crate) f_kb: Option<i8>,
    pub(crate) f_type: Option<String>,
    pub(crate) f_id: Option<String>,
    pub(crate) f_origin: Option<String>,
    pub(crate) ipc_id: Option<Vec<i32>>,
    pub(crate) breached_account: Option<i8>,
    pub(crate) f_access_token: Option<String>,
    pub(crate) inc_id: Option<Vec<i32>>,
}

/// Enforcer context for the current request.
/// Some fields are available after calling `PXEnforcer::enforce()`
/// use corresponding getter methods to access the fields
#[allow(dead_code)]
#[derive(Default)]
pub struct PXContext {
    pub(crate) http_method: String,
    /// Inbound HTTP version string sent on Risk API and async activities
    pub(crate) http_version: String,
    /// Client request headers (sensitive headers stripped) for Risk API and activities
    pub(crate) headers: serde_json::value::Value,
    /// Parsed request cookies merged from `Cookie` and the custom cookie header
    pub(crate) cookies: HashMap<String, String>,
    /// Names of all cookies on the request, sent on Risk API and async activities
    pub(crate) request_cookie_names: Vec<String>,
    /// Specially forwarded access cookies (e.g. `_pxac`) included on Risk API when present
    pub(crate) access_cookies: HashMap<String, String>,
    /// Request hostname derived from the HTTP Host header
    pub(crate) hostname: String,
    /// Full request URL after decoding/normalization for Risk API context
    pub(crate) full_url: String,
    /// Client User-Agent string, subject to max-length alignment with cookie signing rules
    pub(crate) user_agent: String,
    /// Real client IP from configured trusted headers or the platform's direct peer address
    pub(crate) ip: String,
    /// Unique ID for this request, carried on Risk API and telemetry
    pub(crate) request_id: Uuid,

    /// Whether this request targets a sensitive route requiring a Risk API call even with a valid cookie
    pub(crate) is_sensitive_route: bool,
    /// Whether this request is enforced (full blocking workflow even in monitor mode)
    pub(crate) is_enforced_request: bool,
    /// Whether this request is monitored (simulated blocks in active-blocking mode)
    pub(crate) is_monitored_request: bool,
    /// Effective risk mode sent on Risk API and async activities (`monitor` or `active_blocking`)
    pub(crate) risk_mode: PXModuleMode,
    /// Whether a Block activity represents a simulated block (monitor mode or monitored route)
    pub(crate) is_simulated_block: bool,

    /// Visitor ID: from the risk cookie `v` field, or from the `_pxvid` cookie
    pub(crate) vid: Option<String>,
    /// HUMAN user UUID from Risk API or cookie-derived identity, used in enforcement and templates
    pub(crate) uuid: Option<String>,
    /// Client-supplied `_pxhd` cookie linking early risk traffic to later sensor activity
    pub(crate) pxhd_cookie: Option<String>,
    /// PXHD value returned by the Risk API response to refresh client `_pxhd` tracking
    pub(crate) pxhd_risk: Option<String>,
    /// Optional cookie `Domain` attribute from Risk API `pxhdDomain`
    pub(crate) pxhd_domain: Option<String>,
    /// How `vid` was obtained; `None` if unknown
    pub(crate) vid_source: Option<VidSource>,
    /// Raw `_pxvid` cookie value when present but failing UUID validation
    pub(crate) orig_cookie_vid: Option<String>,

    /// HTTP status code from a failed Risk API transport/response; `None` when there was no HTTP error
    pub(crate) s2s_error_http_status: Option<u16>,
    /// Human-readable error detail for a failed Risk API outcome
    pub(crate) s2s_error_message: Option<String>,
    /// Milliseconds spent on the synchronous Risk API round-trip (only set when a call was made)
    pub(crate) risk_rtt: Option<i64>,
    /// Single-character enforcement action from Risk API or cookie (`c`=captcha, `b`=block, `r`=ratelimit)
    pub(crate) block_action: Option<String>,
    /// Numeric bot-likelihood score (0–100) compared to `px_blocking_score` to decide pass vs block
    pub(crate) score: Option<u8>,
    /// Customer-defined `custom_param1`…`custom_param10` merged into Risk API and async activity payloads
    pub(crate) custom_params: PXCustomParams,
    /// Timestamp when the enforcer process started, included on Risk API and async activities
    pub(crate) enforcer_start_time: Option<std::time::SystemTime>,
    /// Opaque string from Risk API `additional_risk_info`, forwarded into async activities
    pub(crate) additional_risk_info: Option<String>,
    /// Extra token payload fragment from advanced cookie/mobile token parsing (cookie `add` field)
    pub(crate) additional_token_info: Option<String>,
    /// UTF-8 JSON string of the decrypted v3 risk cookie, sent as `px_cookie` on Risk API
    pub(crate) cookie_json: Option<String>,

    /// Risk-cookie wire format for this request (`_px2` = V2, `_px3` = V3); `None` until cookie verification runs
    pub(crate) cookie_version: Option<CookieVersion>,
    /// Whether the risk token came from browser cookies or a mobile SDK header; `None` if unknown
    pub(crate) cookie_origin: Option<CookieOrigin>,
    /// Inbound HTTP method sent on Risk API and async activities

    /// Raw `x-px-original-token` value from the Mobile SDK when `x-px-authorization` reports an error
    pub(crate) original_token: Option<String>,
    /// Reason the original mobile token could not be decrypted/validated; `None` when not applicable
    pub(crate) original_token_error: Option<CallReason>,

    /// HMAC integrity material from the decrypted v2 risk cookie
    pub(crate) v2_cookie_hash: Option<String>,
    /// Decrypted/decoded v2 risk-cookie JSON payload used for validation before trusting cookie-based scoring
    pub(crate) decoded_v2_cookie: Option<String>,

    /// Reason the Risk API was invoked (e.g. `no_cookie`, `cookie_expired`, `sensitive_route`); `None` when unset
    pub(crate) s2s_call_reason: Option<CallReason>,
    /// Taxonomy for a failed Risk API outcome; `None` when there was no S2S error classification
    pub(crate) s2s_error_reason: Option<S2sErrorReason>,
    /// Why the request was allowed; `None` when unset
    pub(crate) pass_reason: Option<PassReason>,
    /// Why the request was blocked; `None` when unset
    pub(crate) block_reason: Option<BlockReason>,

    /// Parsed GraphQL operations (type, name, sensitivity) sent as `graphql_operations` on activities
    pub(crate) graphql_extracted_items: Vec<PXGraphQLExtractedItem>,

    /// MCP request metadata captured by Agentic Trust enrichment; `None` when the request
    /// did not match the configured MCP endpoint.
    pub(crate) agentic_trust_data: Option<AgenticTrustData>,

    /// Risk API `data_enrichment` object with collector-side enrichment fields
    pub(crate) data_enrichment: Option<PXDataEnrichment>,
    /// Parsed PXDE JSON from `_pxde` cookie or Risk API `data_enrichment`, after base64/HMAC handling
    pub(crate) pxde: Option<String>,
    /// Whether PXDE was HMAC-verified or trusted from an authenticated Risk API response
    pub(crate) pxde_verified: bool,

    /// Raw `pxcts` Cross Tab Session token for `cross_tab_session` on Risk/activity payloads
    pub(crate) pxcts_cookie: Option<String>,
    /// App user ID extracted from a configured JWT cookie/header payload field
    pub(crate) app_user_id: Option<String>,
    /// Additional JWT payload fields keyed by their configured dot-notated paths
    pub(crate) jwt_additional_fields: Option<serde_json::Map<String, serde_json::Value>>,

    /// Risk response flag requesting the enforcer to send an `enforcer_telemetry` activity
    pub(crate) telemetry_requested: bool,

    /// Whether to postpone sending the async activity until a later point in the request lifecycle (e.g. after the response is sent)
    pub(crate) postpone_activities: bool,

    /// Credentials Intelligence extraction/hashing result for this login request.
    pub(crate) credential_intelligence: Option<PXCredentialIntelligenceData>,
}

impl PXContext {
    pub fn new(req: &Request, conf: &PXConfig) -> Self {
        let mut cookie_origin = CookieOrigin::Cookie;
        let mut cookies = HashMap::new();
        let mut access_cookies = HashMap::new();
        let mut request_cookie_names: Vec<String> = vec![];
        let mut original_token = String::new();
        let mut s2s_call_reason = None;
        let mut risk_mode = conf.module_mode;

        // check if the request has the bypass monitor header set to "1" and the module mode is monitor
        let should_bypass_monitor = conf.module_mode == PXModuleMode::Monitor
            && !conf.bypass_monitor_header.is_empty()
            && req
                .get_header_str_lossy(&conf.bypass_monitor_header)
                .map(|v| v.into_owned())
                .unwrap_or_default()
                == "1";

        if conf.module_mode == PXModuleMode::Monitor && should_bypass_monitor {
            risk_mode = PXModuleMode::Blocking;
            px_debug!("Bypass monitor header set in monitor mode, forcing risk mode to blocking");
        }

        let is_enforced_request = risk_mode == PXModuleMode::Monitor
            && (pxutils::verify_route(&conf.enforced_routes, req.get_path())
                || conf
                    .is_enforced_request_fn
                    .map(|f| f(req, conf))
                    .unwrap_or(false));

        if conf.module_mode == PXModuleMode::Monitor && is_enforced_request {
            px_debug!("Enforced request detected in monitor mode, forcing risk mode to blocking");
        }

        let is_monitored_request = risk_mode == PXModuleMode::Blocking
            && (pxutils::verify_route(&conf.monitored_routes, req.get_path())
                || conf
                    .is_monitored_request_fn
                    .map(|f| f(req, conf))
                    .unwrap_or(false));

        let risk_mode = if (risk_mode == PXModuleMode::Monitor && !is_enforced_request)
            || is_monitored_request
        {
            PXModuleMode::Monitor
        } else {
            PXModuleMode::Blocking
        };

        if let Some(mobile_sdk_header) = req.get_header_str_lossy(MOBILE_SDK_HEADER) {
            px_debug!("Mobile SDK token detected");
            cookie_origin = CookieOrigin::Header;
            let orig_token_header = req
                .get_header_str_lossy(MOBILE_SDK_ORIGINAL_TOKEN_HEADER)
                .map(|v| v.into_owned())
                .unwrap_or_default();

            let authorization_header = mobile_sdk_header.trim();

            if pxutils::is_mobile_sdk_error_code(authorization_header) {
                match authorization_header {
                    "1" => s2s_call_reason = Some(CallReason::MobileError1),
                    "2" => s2s_call_reason = Some(CallReason::MobileError2),
                    "3" => s2s_call_reason = Some(CallReason::MobileError3),
                    "4" => s2s_call_reason = Some(CallReason::MobileError4),
                    _ => {
                        s2s_call_reason = Some(CallReason::MobileSdkConnectionError);
                    }
                }
            } else {
                if let Some((cookie_name, cookie_contents)) =
                    pxutils::parse_versioned_mobile_token(authorization_header)
                {
                    cookies.insert(cookie_name, cookie_contents);
                }
            }

            original_token = orig_token_header.trim().to_owned();
        } else {
            let cookie_header_value = req
                .get_header_str_lossy(COOKIE)
                .map(|v| v.into_owned())
                .unwrap_or_default();

            let custom_cookie_header_value = {
                let custom_header_name = conf.custom_cookie_header.as_str();
                if custom_header_name.is_empty() {
                    String::new()
                } else {
                    req.get_header_str_lossy(custom_header_name)
                        .map(|v| v.into_owned())
                        .unwrap_or_default()
                }
            };

            cookies = pxutils::build_merged_request_cookies(
                cookie_header_value.as_str(),
                custom_cookie_header_value.as_str(),
            );
        }
        request_cookie_names = cookies.keys().cloned().collect();

        let pxvid = pxutils::extract_cookie_value(&cookies, "_pxvid");
        let (vid, vid_source, orig_cookie_vid) = if pxutils::is_valid_uuid(&pxvid) {
            (Some(pxvid), Some(VidSource::VidCookie), None)
        } else if !pxvid.is_empty() {
            (None, None, Some(pxvid))
        } else {
            (None, None, None)
        };
        let pxhd_cookie = pxutils::extract_cookie_value(&cookies, "_pxhd");
        let pxcts_cookie = pxutils::extract_cookie_value(&cookies, "pxcts");

        let access_cookie = pxutils::extract_cookie_value(&cookies, "_pxac");
        if !access_cookie.is_empty() {
            access_cookies.insert("access_cookie".to_string(), access_cookie);
        }
        for key in &conf.extracted_cookies {
            let value = pxutils::extract_cookie_value(&cookies, key);
            if !value.is_empty() {
                access_cookies.insert(key.clone(), value);
            }
        }

        PXContext {
            cookie_origin: Some(cookie_origin),
            user_agent: req
                .get_header_str_lossy("user-agent")
                .map(|v| v.into_owned())
                .unwrap_or_default(),
            http_method: req.get_method_str().to_string(),
            http_version: pxutils::get_fastly_version_str(req).into(),
            cookies,
            access_cookies,
            headers: pxutils::get_headers_as_json(req),
            hostname: req.get_url().host_str().unwrap_or_default().to_string(),
            full_url: req.get_url_str().to_string(),
            is_sensitive_route: pxutils::verify_route(&conf.sensitive_routes, req.get_path()),
            is_enforced_request,
            is_monitored_request,
            risk_mode,
            original_token: if original_token.is_empty() {
                None
            } else {
                Some(original_token)
            },
            s2s_call_reason,
            request_cookie_names,
            vid_source,
            vid,
            orig_cookie_vid,
            pxhd_cookie: if pxhd_cookie.is_empty() {
                None
            } else {
                Some(pxhd_cookie)
            },
            ip: pxutils::extract_ip_from_configured_headers(req, &conf.ip_headers)
                .or_else(|| req.get_client_ip_addr().map(|ip| ip.to_string()))
                .unwrap_or_default(),
            block_action: Some("c".to_string()),
            request_id: Uuid::new_v4(),
            pxde_verified: false,
            pxcts_cookie: if pxcts_cookie.is_empty() {
                None
            } else {
                Some(pxcts_cookie)
            },
            enforcer_start_time: Some(std::time::SystemTime::now()),
            postpone_activities: false,
            ..Default::default()
        }
    }

    pub fn extract_pxde_cookie(&mut self, conf: &PXConfig) {
        if let Some(pxde) = self.cookies.get("_pxde") {
            let fields = pxde.split(':').collect::<Vec<&str>>();
            if fields.len() != 2 {
                px_debug!("_pxde cookie validation failed");
                return;
            }

            let ehmac = match fields.first() {
                Some(h) => h,
                None => {
                    px_debug!("_pxde cookie validation failed");
                    return;
                }
            };
            let pxde_val = fields.get(1..).map(|s| s.join(":")).unwrap_or_default();
            let expected_hmac = pxcrypto::create_hmac(&pxde_val, &conf.cookie_secret);

            if ehmac.to_lowercase() != expected_hmac.unwrap_or_default().to_lowercase() {
                px_debug!("_pxde cookie HMAC validation failed");
                return;
            }

            let pxde_val = match general_purpose::STANDARD.decode(pxde_val) {
                Ok(s) => s,
                Err(e) => {
                    px_debug!("_pxde cookie validation failed: {}", e);
                    return;
                }
            };
            let pxde_val = match std::str::from_utf8(&pxde_val) {
                Ok(s) => s,
                Err(_) => {
                    px_debug!("_pxde cookie validation failed: invalid UTF-8");
                    return;
                }
            };

            let data_enrichment: PXDataEnrichment =
                serde_json::from_str::<PXDataEnrichment>(pxde_val).unwrap_or_default();
            self.data_enrichment = Some(data_enrichment);
            self.pxde = Some(pxde_val.to_string());
            self.pxde_verified = true;
        }
    }

    // Public API

    /// Whether this request targets a sensitive route requiring a Risk API call even with a valid cookie.
    pub fn get_is_sensitive_route(&self) -> bool {
        self.is_sensitive_route
    }

    /// Names of all cookies on the request, sent on Risk API and async activity payloads.
    pub fn get_request_cookie_names(&self) -> &Vec<String> {
        &self.request_cookie_names
    }

    /// Visitor ID from the risk cookie `v` field or from the `_pxvid` cookie, when available.
    pub fn get_vid(&self) -> Option<&str> {
        self.vid.as_deref()
    }

    /// HUMAN user UUID from Risk API or cookie-derived identity, used in enforcement and templates.
    pub fn get_uuid(&self) -> Option<&str> {
        self.uuid.as_deref()
    }

    /// Client-supplied `_pxhd` cookie linking early risk traffic to later sensor activity.
    pub fn get_pxhd_cookie(&self) -> Option<&str> {
        self.pxhd_cookie.as_deref()
    }

    /// PXHD value returned by the Risk API response to refresh client `_pxhd` tracking.
    pub fn get_pxhd_risk(&self) -> Option<&str> {
        self.pxhd_risk.as_deref()
    }

    /// Cookie `Domain` attribute from Risk API `pxhdDomain`, when present.
    pub fn get_pxhd_domain(&self) -> Option<&str> {
        self.pxhd_domain.as_deref()
    }

    /// PXHD value for outbound payloads: Risk API pxhd value, else client `_pxhd` cookie.
    pub fn get_pxhd(&self) -> Option<&str> {
        if let Some(pxhd) = self.pxhd_risk.as_deref() {
            return Some(pxhd);
        }
        if let Some(pxhd) = self.pxhd_cookie.as_deref() {
            return Some(pxhd);
        }
        None
    }

    /// How `vid` was obtained; `None` if unknown.
    pub fn get_vid_source(&self) -> Option<&VidSource> {
        self.vid_source.as_ref()
    }

    /// Client User-Agent string, subject to max-length alignment with cookie signing rules.
    pub fn get_user_agent(&self) -> &str {
        &self.user_agent
    }

    /// HTTP status code from a failed Risk API transport or response.
    pub fn get_s2s_error_http_status(&self) -> Option<u16> {
        self.s2s_error_http_status
    }

    /// Human-readable error detail for a failed Risk API outcome.
    pub fn get_s2s_error_message(&self) -> Option<&str> {
        self.s2s_error_message.as_deref()
    }

    /// Real client IP from configured trusted headers or the platform's direct peer address.
    pub fn get_ip(&self) -> &str {
        &self.ip
    }

    /// HMAC integrity material from the decrypted v2 risk cookie.
    pub fn get_v2_cookie_hash(&self) -> Option<&str> {
        self.v2_cookie_hash.as_deref()
    }

    /// Decrypted and decoded v2 risk-cookie JSON payload used for validation before trusting cookie-based scoring.
    pub fn get_decoded_v2_cookie(&self) -> Option<&str> {
        self.decoded_v2_cookie.as_deref()
    }

    /// Milliseconds spent on the synchronous Risk API round-trip, if a call was made.
    pub fn get_risk_rtt(&self) -> Option<i64> {
        self.risk_rtt
    }

    /// Single-character enforcement action from Risk API or cookie (`c` = captcha, `b` = block, `r` = ratelimit).
    pub fn get_block_action(&self) -> Option<&str> {
        self.block_action.as_deref()
    }

    /// Numeric bot-likelihood score (0-100) compared to `px_blocking_score` to decide pass vs block.
    pub fn get_score(&self) -> Option<u8> {
        self.score
    }

    /// Reason the Risk API was invoked, such as `no_cookie`, `cookie_expired`, or `sensitive_route`.
    pub fn get_s2s_call_reason(&self) -> Option<&CallReason> {
        self.s2s_call_reason.as_ref()
    }

    /// Taxonomy for a failed Risk API outcome.
    pub fn get_s2s_error_reason(&self) -> Option<&S2sErrorReason> {
        self.s2s_error_reason.as_ref()
    }

    /// Why the request was allowed.
    pub fn get_pass_reason(&self) -> Option<&PassReason> {
        self.pass_reason.as_ref()
    }

    /// Why the request was blocked.
    pub fn get_block_reason(&self) -> Option<&BlockReason> {
        self.block_reason.as_ref()
    }

    /// Unique ID for this request, carried on Risk API and telemetry.
    pub fn get_request_id(&self) -> &Uuid {
        &self.request_id
    }

    /// Risk API `data_enrichment` object with collector-side enrichment fields.
    pub fn get_data_enrichment(&self) -> Option<&PXDataEnrichment> {
        self.data_enrichment.as_ref()
    }

    /// Raw `pxcts` Cross Tab Session token for `cross_tab_session` on Risk and activity payloads.
    pub fn get_pxcts_cookie(&self) -> Option<&str> {
        self.pxcts_cookie.as_deref()
    }

    /// MCP metadata extracted for Agentic Trust when the request matched the configured endpoint.
    pub fn get_agentic_trust_data(&self) -> Option<&AgenticTrustData> {
        self.agentic_trust_data.as_ref()
    }
}

static EMPTY_VEC: Vec<i32> = Vec::new();
impl PXDataEnrichment {
    /// the creation time
    pub fn get_timestamp(&self) -> i64 {
        self.timestamp.unwrap_or_default()
    }

    /// specifies if the request is made by a known bot or not (0: other, 1: known bot)
    pub fn get_f_kb(&self) -> i8 {
        self.f_kb.unwrap_or_default()
    }

    /// the access control rule type (w: whitelist, b: blacklist)
    pub fn get_f_type(&self) -> &str {
        self.f_type.as_deref().unwrap_or("")
    }

    /// the access control rule ID
    pub fn get_f_id(&self) -> &str {
        self.f_id.as_deref().unwrap_or("")
    }

    /// the data is defined either as a Custom Rule or as a HUMAN rule
    pub fn get_f_origin(&self) -> &str {
        self.f_origin.as_deref().unwrap_or("")
    }

    /// an array of IP Categorization IDs
    pub fn get_ipc_id(&self) -> &Vec<i32> {
        self.ipc_id.as_ref().unwrap_or(&EMPTY_VEC)
    }

    /// Indicates if the credentials on the activity are identified as compromised (1: breached)
    pub fn get_breached_account(&self) -> i8 {
        self.breached_account.unwrap_or_default()
    }

    /// the access token name
    pub fn get_f_access_token(&self) -> &str {
        self.f_access_token.as_deref().unwrap_or("")
    }

    /// an array of incident types
    pub fn get_inc_id(&self) -> &Vec<i32> {
        self.inc_id.as_ref().unwrap_or(&EMPTY_VEC)
    }
}