use proxy_wasm::traits::*;
use proxy_wasm::types::*;
proxy_wasm::main! {{
proxy_wasm::set_log_level(LogLevel::Trace);
proxy_wasm::set_root_context(|_| -> Box<dyn RootContext> { Box::new(Root) });
}}
struct Root;
impl Context for Root {}
impl RootContext for Root {
fn get_type(&self) -> Option<ContextType> {
Some(ContextType::HttpContext)
}
fn create_http_context(&self, _: u32) -> Option<Box<dyn HttpContext>> {
Some(Box::new(Filter))
}
}
struct Filter;
const BLOCKED_COUNTRIES: &[&str] = &["ZZ"];
impl Filter {
fn reject(&self, status: u32, body: &'static str, country: &str) -> Action {
self.send_http_response(
status,
vec![
("content-type", "text/plain"),
("cache-control", "no-store"),
("x-client-country", country),
],
Some(body.as_bytes()),
);
Action::Pause
}
}
impl Context for Filter {}
impl HttpContext for Filter {
fn on_http_request_headers(&mut self, _: usize, _: bool) -> Action {
let country = self
.get_property(vec!["request.country"])
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
.unwrap_or_default();
if country.is_empty() || BLOCKED_COUNTRIES.iter().any(|code| *code == country) {
return self.reject(403, "country-rejected", &country);
}
let user_agent = self
.get_http_request_header("user-agent")
.unwrap_or_default();
if user_agent.to_ascii_lowercase().contains("bot") {
return self.reject(403, "bot-rejected", &country);
}
let query = self
.get_property(vec!["request.query"])
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
.unwrap_or_default();
let token = query_value(&query, "token");
if token.is_empty() {
return self.reject(401, "token-rejected", &country);
}
let authorization = format!("Bearer {token}");
self.add_http_request_header("authorization", &authorization);
self.add_http_request_header("x-client-country", &country);
Action::Continue
}
}
fn query_value(query: &str, name: &str) -> String {
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
if key == name {
return value.to_string();
}
}
String::new()
}