use std::ffi::OsStr;
use anyhow::{Context as _, Result};
use openmoat_proxy::Requests;
pub const ENV: &str = "OPENMOAT_ADR062_POC";
const HOST: &str = "api.github.com";
const DENY: &[&str] = &["POST /gists", "POST /gists/**"];
pub fn enabled() -> bool {
is_on(std::env::var_os(ENV).as_deref())
}
fn is_on(value: Option<&OsStr>) -> bool {
value == Some(OsStr::new("1"))
}
pub fn hosts() -> Vec<String> {
hosts_for(enabled())
}
fn hosts_for(on: bool) -> Vec<String> {
if on {
vec![HOST.to_owned()]
} else {
Vec::new()
}
}
pub fn requests() -> Result<Requests> {
requests_for(enabled())
}
fn requests_for(on: bool) -> Result<Requests> {
if !on {
return Ok(Requests::default());
}
Requests::default()
.deny(HOST, DENY)
.context("the ADR-062 proof-of-concept rule")
}
pub fn notice() -> Option<String> {
enabled().then(|| {
format!(
"moat run: {ENV}=1: HTTPS to {HOST} is terminated and {} refused there; a temporary \
proof of concept (ADR-062 step 0), not a feature",
DENY.join(" and ")
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_value_1_turns_it_on() {
assert!(is_on(Some(OsStr::new("1"))));
for value in [None, Some(""), Some("0"), Some("true"), Some("1 ")] {
assert!(!is_on(value.map(OsStr::new)), "{value:?}");
}
}
#[test]
fn off_it_adds_no_host_and_no_rule() {
assert_eq!(hosts_for(false), Vec::<String>::new());
assert_eq!(requests_for(false).unwrap().hosts().count(), 0);
}
#[test]
fn on_it_terminates_the_one_host_its_rule_names() {
assert_eq!(hosts_for(true), [HOST]);
let rules: Vec<String> = requests_for(true)
.unwrap()
.hosts()
.map(str::to_owned)
.collect();
assert_eq!(rules, hosts_for(true));
}
}