use serde::{Deserialize, Serialize};
use super::{DataClass, RedactionClass};
use crate::error::{Result, VisionError};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EgressAction {
Allow,
Ask,
Deny,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum RuleTarget {
Host(String),
Provider(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RuleToml", into = "RuleToml")]
pub struct EgressRuleConfig {
pub target: RuleTarget,
pub classes: Vec<DataClass>,
pub action: EgressAction,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RuleToml {
#[serde(default, skip_serializing_if = "Option::is_none")]
host: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
provider: Option<String>,
#[serde(default)]
classes: Vec<DataClass>,
action: EgressAction,
}
impl TryFrom<RuleToml> for EgressRuleConfig {
type Error = String;
fn try_from(rule: RuleToml) -> std::result::Result<Self, Self::Error> {
let target = match (rule.host, rule.provider) {
(Some(host), None) => RuleTarget::Host(host),
(None, Some(provider)) => RuleTarget::Provider(provider),
(Some(_), Some(_)) => {
return Err("an egress rule names `host` or `provider`, not both".into());
}
(None, None) => {
return Err("an egress rule names the `host` or the `provider` it covers".into());
}
};
Ok(Self { target, classes: rule.classes, action: rule.action })
}
}
impl From<EgressRuleConfig> for RuleToml {
fn from(rule: EgressRuleConfig) -> Self {
let (host, provider) = match rule.target {
RuleTarget::Host(host) => (Some(host), None),
RuleTarget::Provider(provider) => (None, Some(provider)),
};
Self { host, provider, classes: rule.classes, action: rule.action }
}
}
impl EgressRuleConfig {
fn matches(&self, host: &str, providers: &[String], class: &DataClass) -> bool {
let target_matches = match &self.target {
RuleTarget::Host(pattern) => match pattern.strip_prefix("*.") {
Some(suffix) => {
host.len() > suffix.len()
&& host.ends_with(suffix)
&& host.as_bytes()[host.len() - suffix.len() - 1] == b'.'
}
None => pattern.eq_ignore_ascii_case(host),
},
RuleTarget::Provider(provider) => {
providers.iter().any(|p| p.eq_ignore_ascii_case(provider))
}
};
target_matches && (self.classes.is_empty() || self.classes.contains(class))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EgressConfig {
#[serde(default = "allow")]
pub default: EgressAction,
#[serde(default)]
pub redact: Vec<RedactionClass>,
#[serde(default, rename = "rule")]
pub rules: Vec<EgressRuleConfig>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub on_device: bool,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub private_networks: bool,
}
fn allow() -> EgressAction {
EgressAction::Allow
}
fn yes() -> bool {
true
}
fn is_true(value: &bool) -> bool {
*value
}
impl Default for EgressConfig {
fn default() -> Self {
Self {
default: EgressAction::Allow,
redact: Vec::new(),
rules: Vec::new(),
on_device: false,
private_networks: true,
}
}
}
impl EgressConfig {
pub fn public_networks_only(mut self) -> Self {
self.private_networks = false;
self
}
pub fn on_device(mut self) -> Self {
self.on_device = true;
self
}
pub fn with_default(mut self, action: EgressAction) -> Self {
self.default = action;
self
}
pub fn redacting(mut self, class: RedactionClass) -> Self {
if !self.redact.contains(&class) {
self.redact.push(class);
}
self
}
pub fn with_rule(mut self, host: &str, classes: &[&str], action: EgressAction) -> Self {
self.rules.push(EgressRuleConfig {
target: RuleTarget::Host(host.to_string()),
classes: classes.iter().map(|&c| DataClass::new(c)).collect(),
action,
});
self
}
pub fn with_provider_rule(
mut self,
provider: &str,
classes: &[&str],
action: EgressAction,
) -> Self {
self.rules.push(EgressRuleConfig {
target: RuleTarget::Provider(provider.to_string()),
classes: classes.iter().map(|&c| DataClass::new(c)).collect(),
action,
});
self
}
pub fn decide(
&self,
host: &str,
providers: &[String],
class: &DataClass,
) -> (EgressAction, Option<usize>) {
self.rules
.iter()
.position(|rule| rule.matches(host, providers, class))
.map_or((self.default, None), |index| (self.rules[index].action, Some(index)))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VisionConfig {
#[serde(default)]
pub egress: EgressConfig,
#[serde(default)]
pub sam: crate::mask_decoder::SamSettings,
}
impl VisionConfig {
pub fn from_toml_str(text: &str) -> Result<Self> {
toml::from_str(text)
.map_err(|e| VisionError::InvalidInput(format!(".adk/vision.toml is invalid: {e}")))
}
}