use hyper::Method;
use serde::{Deserialize, Serialize};
use url::Url;
#[derive(Debug, Clone, Serialize)]
pub struct RequestInfo {
pub url: String,
pub method: String,
pub scheme: String,
pub host: String,
pub path: String,
pub requester_ip: String,
}
impl RequestInfo {
pub fn from_request(method: &Method, url: &str, requester_ip: &str) -> Result<Self, String> {
let parsed_url = Url::parse(url).map_err(|e| format!("Failed to parse URL: {}", e))?;
Ok(RequestInfo {
url: url.to_string(),
method: method.as_str().to_string(),
scheme: parsed_url.scheme().to_string(),
host: parsed_url.host_str().unwrap_or("").to_string(),
path: parsed_url.path().to_string(),
requester_ip: requester_ip.to_string(),
})
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(untagged)]
pub enum AllowPolicy {
Bool(bool),
Limited { max_tx_bytes: u64 },
}
impl<'de> Deserialize<'de> for AllowPolicy {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
use serde_json::Value;
let value = Value::deserialize(deserializer)?;
match value {
Value::Bool(b) => Ok(AllowPolicy::Bool(b)),
Value::Object(mut obj) => {
if let Some(max_tx_bytes) = obj.remove("max_tx_bytes") {
let bytes = max_tx_bytes
.as_u64()
.ok_or_else(|| Error::custom("max_tx_bytes must be a number"))?;
Ok(AllowPolicy::Limited {
max_tx_bytes: bytes,
})
} else {
Err(Error::custom(
"allow object must contain max_tx_bytes field",
))
}
}
_ => Err(Error::custom("allow must be a boolean or object")),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RuleResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub allow: Option<AllowPolicy>,
#[serde(skip_serializing_if = "Option::is_none")]
pub deny_message: Option<String>,
}
impl RuleResponse {
pub fn from_string(s: &str) -> Self {
let trimmed = s.trim();
match trimmed {
"true" => {
return RuleResponse {
allow: Some(AllowPolicy::Bool(true)),
deny_message: None,
};
}
"false" => {
return RuleResponse {
allow: Some(AllowPolicy::Bool(false)),
deny_message: None,
};
}
_ => {}
}
if let Ok(response) = serde_json::from_str::<RuleResponse>(trimmed) {
return response;
}
RuleResponse {
allow: Some(AllowPolicy::Bool(false)),
deny_message: Some(trimmed.to_string()),
}
}
pub fn to_evaluation_result(&self) -> (bool, Option<String>, Option<u64>) {
match &self.allow {
Some(AllowPolicy::Bool(true)) => (true, None, None),
Some(AllowPolicy::Bool(false)) => (false, self.deny_message.clone(), None),
Some(AllowPolicy::Limited { max_tx_bytes }) => (true, None, Some(*max_tx_bytes)),
None => (false, self.deny_message.clone(), None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rule_response_from_string() {
let resp = RuleResponse::from_string("true");
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(true))));
assert_eq!(resp.deny_message, None);
let resp = RuleResponse::from_string("false");
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(false))));
assert_eq!(resp.deny_message, None);
let resp = RuleResponse::from_string(r#"{"allow": true}"#);
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(true))));
assert_eq!(resp.deny_message, None);
let resp = RuleResponse::from_string(r#"{"allow": false, "deny_message": "blocked"}"#);
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(false))));
assert_eq!(resp.deny_message, Some("blocked".to_string()));
let resp = RuleResponse::from_string(r#"{"deny_message": "not allowed"}"#);
assert_eq!(resp.allow, None); assert_eq!(resp.deny_message, Some("not allowed".to_string()));
let resp = RuleResponse::from_string("Access denied for security reasons");
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(false))));
assert_eq!(
resp.deny_message,
Some("Access denied for security reasons".to_string())
);
let resp = RuleResponse::from_string(" true \n");
assert!(matches!(resp.allow, Some(AllowPolicy::Bool(true))));
assert_eq!(resp.deny_message, None);
}
#[test]
fn test_rule_response_to_evaluation_result() {
let resp = RuleResponse {
allow: Some(AllowPolicy::Bool(true)),
deny_message: None,
};
assert_eq!(resp.to_evaluation_result(), (true, None, None));
let resp = RuleResponse {
allow: Some(AllowPolicy::Bool(true)),
deny_message: Some("ignored".to_string()),
};
assert_eq!(resp.to_evaluation_result(), (true, None, None));
let resp = RuleResponse {
allow: Some(AllowPolicy::Bool(false)),
deny_message: Some("denied".to_string()),
};
assert_eq!(
resp.to_evaluation_result(),
(false, Some("denied".to_string()), None)
);
let resp = RuleResponse {
allow: Some(AllowPolicy::Bool(false)),
deny_message: None,
};
assert_eq!(resp.to_evaluation_result(), (false, None, None));
let resp = RuleResponse {
allow: None,
deny_message: Some("blocked".to_string()),
};
assert_eq!(
resp.to_evaluation_result(),
(false, Some("blocked".to_string()), None)
);
let resp = RuleResponse::from_string("{}");
assert_eq!(resp.to_evaluation_result(), (false, None, None));
}
#[test]
fn test_response_parity_examples() {
let resp = RuleResponse::from_string("true");
assert_eq!(resp.to_evaluation_result(), (true, None, None));
let resp = RuleResponse::from_string("false");
assert_eq!(resp.to_evaluation_result(), (false, None, None));
let resp = RuleResponse::from_string(r#"{"allow": true}"#);
assert_eq!(resp.to_evaluation_result(), (true, None, None));
let resp =
RuleResponse::from_string(r#"{"allow": false, "deny_message": "Not authorized"}"#);
assert_eq!(
resp.to_evaluation_result(),
(false, Some("Not authorized".to_string()), None)
);
let resp = RuleResponse::from_string(r#"{"deny_message": "Access restricted"}"#);
assert_eq!(
resp.to_evaluation_result(),
(false, Some("Access restricted".to_string()), None)
);
let resp = RuleResponse::from_string("Invalid request");
assert_eq!(
resp.to_evaluation_result(),
(false, Some("Invalid request".to_string()), None)
);
}
#[test]
fn test_allow_with_max_tx_bytes() {
let resp = RuleResponse::from_string(r#"{"allow": {"max_tx_bytes": 1024}}"#);
assert!(matches!(
resp.allow,
Some(AllowPolicy::Limited { max_tx_bytes: 1024 })
));
assert_eq!(resp.deny_message, None);
assert_eq!(resp.to_evaluation_result(), (true, None, Some(1024)));
let resp = RuleResponse::from_string(r#"{"allow": {"max_tx_bytes": 10485760}}"#);
assert!(matches!(
resp.allow,
Some(AllowPolicy::Limited {
max_tx_bytes: 10485760
})
));
assert_eq!(resp.to_evaluation_result(), (true, None, Some(10485760)));
let resp = RuleResponse::from_string(
r#"{"allow": {"max_tx_bytes": 512}, "deny_message": "ignored"}"#,
);
assert!(matches!(
resp.allow,
Some(AllowPolicy::Limited { max_tx_bytes: 512 })
));
assert_eq!(resp.to_evaluation_result(), (true, None, Some(512)));
}
}