perimeterx-fastly-enforcer 2.2.2

PerimeterX Fastly Compute@Edge Rust Enforcer
Documentation
use crate::modules::{pxconstants::*, pxutils};
use crate::pxconfig::PXConfig;
use fastly::{
    Request,
    http::{HeaderValue, header::COOKIE},
};

pub fn req_redirect_client(req: &mut Request, conf: &PXConfig) {
    if let Ok(host_value) = HeaderValue::from_str(&conf.human_client_host) {
        req.set_header("Host", host_value);
    }
    req.set_header(
        FIRST_PARTY_MODE_HEADER,
        HeaderValue::from_static(FIRST_PARTY_HEADER_VALUE),
    );
    req.set_path(format!("/bd/client/{}/main.min.js", conf.app_id).as_str());
}

pub fn req_redirect_captcha(req: &mut Request, conf: &PXConfig) {
    if let Ok(host_value) = HeaderValue::from_str(&conf.human_captcha_host) {
        req.set_header("Host", host_value);
    }

    req.set_header(
        FIRST_PARTY_MODE_HEADER,
        HeaderValue::from_static(FIRST_PARTY_HEADER_VALUE),
    );

    let query = req.get_query_str().unwrap_or_default().to_string();

    req.set_path(format!("/{}/captcha.js", conf.app_id).as_str());
    req.set_query_str(query);
}

pub fn req_redirect_xhr(req: &mut Request, conf: &PXConfig) {
    // handle vid
    let cookie_header_value = req
        .get_header_str_lossy(COOKIE)
        .map(|v| v.into_owned())
        .unwrap_or_default();
    let cookies = pxutils::parse_cookie_header(cookie_header_value.as_str());
    let pxvid = pxutils::extract_cookie_value(&cookies, "_pxvid");

    // filter sensitive headers
    pxutils::filter_headers(req, &conf.sensitive_headers);

    if !pxvid.is_empty() {
        let cookie = format!("pxvid={pxvid}");
        if let Ok(header_value) = HeaderValue::from_str(&cookie) {
            req.set_header(COOKIE, header_value);
        }
    }
    if let Ok(host_value) = HeaderValue::from_str(&conf.human_collector_host) {
        req.set_header("Host", host_value);
    }

    req.set_header(
        FIRST_PARTY_MODE_HEADER,
        HeaderValue::from_static(FIRST_PARTY_HEADER_VALUE),
    );

    if let Some(client_ip) = req.get_client_ip_addr() {
        req.set_header(ENFORCER_TRUE_IP_HEADER, client_ip.to_string());
    }

    let px_fp_appid = match conf.app_id.get(..2) {
        Some(prefix) if prefix.eq_ignore_ascii_case("px") => {
            conf.app_id.get(2..).unwrap_or(&conf.app_id)
        }
        _ => &conf.app_id,
    };
    let path = req.get_path().replace(&format!("/{px_fp_appid}/xhr"), "");

    req.set_path(&path);
}