Skip to main content

adk_vision/egress/
config.rs

1//! `.adk/vision.toml`: egress after redaction.
2
3use serde::{Deserialize, Serialize};
4
5use super::{DataClass, RedactionClass};
6use crate::error::{Result, VisionError};
7
8/// What happens to an image bound for a destination, always after redaction.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum EgressAction {
12    /// Release it.
13    Allow,
14    /// Hold it until a person approves the exact image.
15    Ask,
16    /// Never release it.
17    Deny,
18}
19
20/// What an `[[egress.rule]]` matches: a host, or every host of one provider.
21#[non_exhaustive]
22#[derive(Clone, Debug, PartialEq, Eq, Hash)]
23pub enum RuleTarget {
24    /// A host name, or `*.example.com` for its subdomains.
25    Host(String),
26    /// A provider id, as a backend names it in
27    /// [`BackendDescriptor::providers`](crate::BackendDescriptor::providers): the id its
28    /// model's responses carry in `LlmResponse::provider`, such as `anthropic`, `gemini`,
29    /// `bedrock` or `nvidia`.
30    Provider(String),
31}
32
33/// One `[[egress.rule]]`: the action for a host or a provider and, optionally, some data
34/// classes.
35///
36/// A rule names exactly one of `host` and `provider`; a rule with both or neither is
37/// refused.
38///
39/// # Example
40///
41/// ```
42/// use adk_vision::{EgressAction, RuleTarget, VisionConfig};
43///
44/// let config = VisionConfig::from_toml_str(r#"
45///     [[egress.rule]]
46///     provider = "anthropic"
47///     action = "ask"
48/// "#).unwrap();
49/// assert_eq!(config.egress.rules[0].target, RuleTarget::Provider("anthropic".into()));
50/// assert_eq!(config.egress.rules[0].action, EgressAction::Ask);
51///
52/// let both = r#"
53///     [[egress.rule]]
54///     host = "api.anthropic.com"
55///     provider = "anthropic"
56///     action = "ask"
57/// "#;
58/// assert!(VisionConfig::from_toml_str(both).is_err());
59/// ```
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(try_from = "RuleToml", into = "RuleToml")]
62pub struct EgressRuleConfig {
63    /// The host or provider the rule matches.
64    pub target: RuleTarget,
65    /// The data classes the rule covers; empty covers every class.
66    pub classes: Vec<DataClass>,
67    /// The action.
68    pub action: EgressAction,
69}
70
71/// The TOML form of a rule: exactly one of `host` and `provider`.
72#[derive(Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74struct RuleToml {
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    host: Option<String>,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    provider: Option<String>,
79    #[serde(default)]
80    classes: Vec<DataClass>,
81    action: EgressAction,
82}
83
84impl TryFrom<RuleToml> for EgressRuleConfig {
85    type Error = String;
86
87    fn try_from(rule: RuleToml) -> std::result::Result<Self, Self::Error> {
88        let target = match (rule.host, rule.provider) {
89            (Some(host), None) => RuleTarget::Host(host),
90            (None, Some(provider)) => RuleTarget::Provider(provider),
91            (Some(_), Some(_)) => {
92                return Err("an egress rule names `host` or `provider`, not both".into());
93            }
94            (None, None) => {
95                return Err("an egress rule names the `host` or the `provider` it covers".into());
96            }
97        };
98        Ok(Self { target, classes: rule.classes, action: rule.action })
99    }
100}
101
102impl From<EgressRuleConfig> for RuleToml {
103    fn from(rule: EgressRuleConfig) -> Self {
104        let (host, provider) = match rule.target {
105            RuleTarget::Host(host) => (Some(host), None),
106            RuleTarget::Provider(provider) => (None, Some(provider)),
107        };
108        Self { host, provider, classes: rule.classes, action: rule.action }
109    }
110}
111
112impl EgressRuleConfig {
113    fn matches(&self, host: &str, providers: &[String], class: &DataClass) -> bool {
114        let target_matches = match &self.target {
115            RuleTarget::Host(pattern) => match pattern.strip_prefix("*.") {
116                Some(suffix) => {
117                    host.len() > suffix.len()
118                        && host.ends_with(suffix)
119                        && host.as_bytes()[host.len() - suffix.len() - 1] == b'.'
120                }
121                None => pattern.eq_ignore_ascii_case(host),
122            },
123            RuleTarget::Provider(provider) => {
124                providers.iter().any(|p| p.eq_ignore_ascii_case(provider))
125            }
126        };
127        target_matches && (self.classes.is_empty() || self.classes.contains(class))
128    }
129}
130
131/// The `[egress]` table: the default action, the redaction classes every release passes
132/// through, and the rules per host or provider and data class.
133///
134/// With no table, every image a remote backend is called with leaves unredacted and
135/// unasked, to a public or a private-network host. Each restriction is an opt-in:
136/// `default = "ask"` or `"deny"`, a rule that asks or denies for a host or provider, a
137/// `redact` class, `private_networks = false`, or `on_device = true`. A chosen
138/// restriction fails closed: a listed class no redactor covers refuses the release
139/// ([`VisionError::RedactionUnavailable`]), and redaction runs before the decision, so an
140/// approval names the redacted image. Unknown keys are refused rather than ignored (V-I2).
141///
142/// # Example
143///
144/// ```
145/// use adk_vision::{DataClass, EgressAction, VisionConfig};
146///
147/// let open = VisionConfig::default();
148/// assert_eq!(open.egress.decide("api.anthropic.com", &[], &DataClass::new("photo")).0, EgressAction::Allow);
149/// assert!(open.egress.redact.is_empty());
150///
151/// let config = VisionConfig::from_toml_str(r#"
152///     [egress]
153///     default = "ask"
154///     redact = ["faces", "personal_text"]
155///
156///     [[egress.rule]]
157///     host = "generativelanguage.googleapis.com"
158///     classes = ["document_crop"]
159///     action = "allow"
160///
161///     [[egress.rule]]
162///     provider = "openrouter"
163///     action = "deny"
164/// "#).unwrap();
165/// let (action, rule) = config
166///     .egress
167///     .decide("generativelanguage.googleapis.com", &[], &DataClass::new("document_crop"));
168/// assert_eq!((action, rule), (EgressAction::Allow, Some(0)));
169/// let photo = DataClass::new("photo");
170/// assert_eq!(config.egress.decide("api.anthropic.com", &[], &photo).0, EgressAction::Ask);
171/// let openrouter = ["openrouter".to_string()];
172/// assert_eq!(config.egress.decide("openrouter.ai", &openrouter, &photo), (EgressAction::Deny, Some(1)));
173/// assert!(VisionConfig::from_toml_str("[egress]\nallow_before_redaction = true").is_err());
174/// ```
175#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(deny_unknown_fields)]
177pub struct EgressConfig {
178    /// The action when no rule matches. `allow` by default; `ask` or `deny` opt in to a
179    /// restriction.
180    #[serde(default = "allow")]
181    pub default: EgressAction,
182    /// The redaction classes every release passes through; none by default.
183    #[serde(default)]
184    pub redact: Vec<RedactionClass>,
185    /// The rules, first match wins.
186    #[serde(default, rename = "rule")]
187    pub rules: Vec<EgressRuleConfig>,
188    /// The on-device profile: every remote destination is refused at the gate's first step,
189    /// whatever the rules say, so no image leaves the machine. `false` by default.
190    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
191    pub on_device: bool,
192    /// Whether images may go to a host on a loopback, private or link-local address, such as
193    /// a self-hosted model on this machine or the local network. `true` by default;
194    /// `private_networks = false` keeps image egress to public addresses. Cloud metadata
195    /// endpoints are refused either way, and the gate's [`EgressPolicy`](adk_core::egress::EgressPolicy)
196    /// stays the ceiling: this switch only narrows it.
197    #[serde(default = "yes", skip_serializing_if = "is_true")]
198    pub private_networks: bool,
199}
200
201fn allow() -> EgressAction {
202    EgressAction::Allow
203}
204
205fn yes() -> bool {
206    true
207}
208
209fn is_true(value: &bool) -> bool {
210    *value
211}
212
213impl Default for EgressConfig {
214    fn default() -> Self {
215        Self {
216            default: EgressAction::Allow,
217            redact: Vec::new(),
218            rules: Vec::new(),
219            on_device: false,
220            private_networks: true,
221        }
222    }
223}
224
225impl EgressConfig {
226    /// Keeps image egress to public addresses: a host on a loopback, private or link-local
227    /// address is refused at the destination step.
228    ///
229    /// # Example
230    ///
231    /// ```
232    /// use adk_vision::{EgressConfig, VisionConfig};
233    ///
234    /// assert!(EgressConfig::default().private_networks);
235    /// let config = VisionConfig::from_toml_str("[egress]\nprivate_networks = false").unwrap();
236    /// assert_eq!(config.egress, EgressConfig::default().public_networks_only());
237    /// ```
238    pub fn public_networks_only(mut self) -> Self {
239        self.private_networks = false;
240        self
241    }
242
243    /// The on-device profile: every release is refused at the destination step with its
244    /// reason, before anything is minimised, redacted or sent.
245    ///
246    /// # Example
247    ///
248    /// ```
249    /// use adk_vision::{EgressConfig, VisionConfig};
250    ///
251    /// let config = VisionConfig::from_toml_str("[egress]\non_device = true").unwrap();
252    /// assert_eq!(config.egress, EgressConfig::default().on_device());
253    /// ```
254    pub fn on_device(mut self) -> Self {
255        self.on_device = true;
256        self
257    }
258
259    /// Sets the default action.
260    pub fn with_default(mut self, action: EgressAction) -> Self {
261        self.default = action;
262        self
263    }
264
265    /// Requires a redaction class on every release.
266    pub fn redacting(mut self, class: RedactionClass) -> Self {
267        if !self.redact.contains(&class) {
268            self.redact.push(class);
269        }
270        self
271    }
272
273    /// Appends a rule for `host`, or `*.example.com` for its subdomains.
274    pub fn with_rule(mut self, host: &str, classes: &[&str], action: EgressAction) -> Self {
275        self.rules.push(EgressRuleConfig {
276            target: RuleTarget::Host(host.to_string()),
277            classes: classes.iter().map(|&c| DataClass::new(c)).collect(),
278            action,
279        });
280        self
281    }
282
283    /// Appends a rule for every host of `provider`, a provider id such as `anthropic`.
284    ///
285    /// # Example
286    ///
287    /// ```
288    /// use adk_vision::{DataClass, EgressAction, EgressConfig};
289    ///
290    /// let config = EgressConfig::default().with_provider_rule("gemini", &[], EgressAction::Ask);
291    /// let gemini = ["gemini".to_string()];
292    /// let photo = DataClass::new("photo");
293    /// assert_eq!(config.decide("us-central1-aiplatform.googleapis.com", &gemini, &photo).0, EgressAction::Ask);
294    /// assert_eq!(config.decide("api.anthropic.com", &[], &photo).0, EgressAction::Allow);
295    /// ```
296    pub fn with_provider_rule(
297        mut self,
298        provider: &str,
299        classes: &[&str],
300        action: EgressAction,
301    ) -> Self {
302        self.rules.push(EgressRuleConfig {
303            target: RuleTarget::Provider(provider.to_string()),
304            classes: classes.iter().map(|&c| DataClass::new(c)).collect(),
305            action,
306        });
307        self
308    }
309
310    /// The action for an image of `class` bound for `host` of a backend that sends to
311    /// `providers`, and the index of the rule that decided it (`None` for the default).
312    pub fn decide(
313        &self,
314        host: &str,
315        providers: &[String],
316        class: &DataClass,
317    ) -> (EgressAction, Option<usize>) {
318        self.rules
319            .iter()
320            .position(|rule| rule.matches(host, providers, class))
321            .map_or((self.default, None), |index| (self.rules[index].action, Some(index)))
322    }
323}
324
325/// The contents of `.adk/vision.toml`.
326#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(deny_unknown_fields)]
328pub struct VisionConfig {
329    /// The `[egress]` table.
330    #[serde(default)]
331    pub egress: EgressConfig,
332    /// The `[sam]` table: which decoder turns `sam-3.1` masks into rasters.
333    #[serde(default)]
334    pub sam: crate::mask_decoder::SamSettings,
335}
336
337impl VisionConfig {
338    /// Parses the TOML text of `.adk/vision.toml`.
339    ///
340    /// # Errors
341    ///
342    /// Returns [`VisionError::InvalidInput`] for invalid TOML, an unknown key, or a rule that
343    /// names both or neither of `host` and `provider`.
344    pub fn from_toml_str(text: &str) -> Result<Self> {
345        toml::from_str(text)
346            .map_err(|e| VisionError::InvalidInput(format!(".adk/vision.toml is invalid: {e}")))
347    }
348}