Skip to main content

adk_vision/egress/
gate.rs

1//! [`EgressGate`]: destination, minimise, redact, decide, record, release.
2
3use std::borrow::Cow;
4use std::collections::BTreeMap;
5use std::sync::Arc;
6
7use adk_core::egress::{EgressPolicy, EgressTarget};
8use chrono::Utc;
9
10use super::{
11    DataClass, EgressAction, EgressConfig, EgressDecision, EgressEvidence, EgressReceipt,
12    EgressRecord, EgressRecorder, EgressRefusal, RedactionClass, Redactor, ReleasedImage,
13};
14use crate::backend::{BackendDescriptor, Locality, Oversize};
15use crate::cx::VisionCx;
16use crate::digest::Digest;
17use crate::edit::{Rgba, ops};
18use crate::error::{Result, VisionError};
19use crate::geometry::{
20    BBox, CoordFrame, Region, RegionOrigin, RegionSet, Shape, Transform, TransformChain,
21};
22use crate::media::{DecodedImage, ImageRef, MediaStore, Provenance, SourceImage};
23use crate::sent::SentImage;
24
25/// One request to release an image to a remote backend.
26///
27/// # Example
28///
29/// ```
30/// use adk_vision::{BBox, BackendDescriptor, CoordFrame, DataClass, Locality, ReleaseRequest};
31/// # let source = adk_vision::SourceImage::from_pixels(adk_vision::DecodedImage::filled(64, 64, [255; 4])).unwrap();
32///
33/// let gemini = BackendDescriptor::new(
34///     "gemini",
35///     Locality::Remote { hosts: vec!["generativelanguage.googleapis.com".into()] },
36///     CoordFrame::SentPixels,
37/// );
38/// let request = ReleaseRequest::new(&source, &gemini, DataClass::new("document_crop"))
39///     .with_crop(BBox::new(8.0, 8.0, 40.0, 24.0));
40/// assert!(request.crop.is_some());
41/// ```
42#[derive(Clone, Debug)]
43#[non_exhaustive]
44pub struct ReleaseRequest<'a> {
45    /// The source image.
46    pub source: &'a SourceImage,
47    /// The backend the image is for.
48    pub backend: &'a BackendDescriptor,
49    /// The data class the egress rules are written per.
50    pub data_class: DataClass,
51    /// Only this part of the source is sent, in source pixels: a field and its margin, not
52    /// the page.
53    pub crop: Option<BBox>,
54    /// Regions to fill before release, in source pixels.
55    pub marked: Vec<BBox>,
56    /// Egress digests a person approved, for a rule that asks.
57    pub approved: Vec<Digest>,
58}
59
60impl<'a> ReleaseRequest<'a> {
61    /// A request to release the whole source image.
62    pub fn new(
63        source: &'a SourceImage,
64        backend: &'a BackendDescriptor,
65        data_class: DataClass,
66    ) -> Self {
67        Self { source, backend, data_class, crop: None, marked: Vec::new(), approved: Vec::new() }
68    }
69
70    /// Sends only `crop` of the source.
71    pub fn with_crop(mut self, crop: BBox) -> Self {
72        self.crop = Some(crop);
73        self
74    }
75
76    /// Fills `regions` before release.
77    pub fn with_marked(mut self, regions: Vec<BBox>) -> Self {
78        self.marked = regions;
79        self
80    }
81
82    /// Releases the image if its egress digest is one a person approved.
83    pub fn approved(mut self, digest: Digest) -> Self {
84        self.approved.push(digest);
85        self
86    }
87}
88
89/// The minimised, redacted image the gate would release, before the rule decides.
90#[derive(Clone, Debug)]
91pub struct EgressPreview {
92    image: SentImage,
93    bytes: Arc<[u8]>,
94    egress: Digest,
95    redactions: BTreeMap<RedactionClass, u32>,
96    filled: Vec<(RedactionClass, BBox)>,
97}
98
99impl EgressPreview {
100    /// The digest of the exact bytes that would leave.
101    pub fn digest(&self) -> Digest {
102        self.egress
103    }
104
105    /// The pixels that would leave.
106    pub fn pixels(&self) -> &DecodedImage {
107        self.image.pixels()
108    }
109
110    /// The PNG bytes that would leave.
111    pub fn bytes(&self) -> &[u8] {
112        &self.bytes
113    }
114
115    /// The transforms from the source, redaction included.
116    pub fn chain(&self) -> &TransformChain {
117        self.image.chain()
118    }
119
120    /// Boxes filled, by the redaction class the rules require: a face covered as the whole
121    /// person counts under `faces`.
122    pub fn redactions(&self) -> &BTreeMap<RedactionClass, u32> {
123        &self.redactions
124    }
125
126    /// The boxes filled, in the egress image's pixels, each with the class it is drawn as:
127    /// `people` for a face covered as the whole person.
128    pub fn filled(&self) -> &[(RedactionClass, BBox)] {
129        &self.filled
130    }
131
132    /// The filled boxes as a [`RegionSet`] over the egress image, each labelled with its
133    /// redaction class, for an approval card to outline (board choice A3).
134    pub fn overlay(&self) -> RegionSet {
135        let (width, height) = self.image.size();
136        let origin = RegionOrigin {
137            backend: crate::backend::BackendId::new(EGRESS_GATE_BACKEND),
138            manifest: None,
139            frame: CoordFrame::SentPixels,
140            chain: TransformChain::new(width, height),
141            escalated_from: None,
142        };
143        let regions = self
144            .filled
145            .iter()
146            .map(|(class, bbox)| Region {
147                image: self.egress,
148                shape: Shape::Box(bbox.clamped(width, height)),
149                label: Some(class.to_string()),
150                score: None,
151                track: None,
152                origin: origin.clone(),
153            })
154            .collect();
155        RegionSet::new(self.egress, width, height, regions)
156    }
157
158    /// The approval evidence for this image.
159    pub fn evidence(&self, caption: impl Into<String>) -> EgressEvidence {
160        let (width, height) = self.image.size();
161        EgressEvidence {
162            digest: self.egress,
163            mime_type: "image/png".into(),
164            width,
165            height,
166            overlay: (!self.filled.is_empty()).then(|| self.overlay()),
167            caption: caption.into(),
168        }
169    }
170}
171
172/// The backend id regions the gate itself produced carry: the redaction overlay.
173pub(crate) const EGRESS_GATE_BACKEND: &str = "egress-gate";
174
175/// What would leave for one call, staged before anyone decides: the redacted copy, stored
176/// as an artifact when the gate has a media store, and the rule that applies to it.
177///
178/// [`EgressGate::stage`] makes one; an approval card shows
179/// [`image_evidence`](Self::image_evidence), and a person's approval names
180/// [`digest`](Self::digest), the only image [`EgressGate::release`] then lets leave.
181#[derive(Clone, Debug)]
182pub struct StagedEgress {
183    preview: EgressPreview,
184    stored: Option<ImageRef>,
185    action: EgressAction,
186    rule: Option<usize>,
187    hosts: Vec<String>,
188    data_class: DataClass,
189}
190
191impl StagedEgress {
192    /// The digest of the exact bytes that would leave.
193    pub fn digest(&self) -> Digest {
194        self.preview.egress
195    }
196
197    /// The minimised, redacted image.
198    pub fn preview(&self) -> &EgressPreview {
199        &self.preview
200    }
201
202    /// The stored egress copy, when the gate has a media store and the call a media scope.
203    pub fn stored(&self) -> Option<&ImageRef> {
204        self.stored.as_ref()
205    }
206
207    /// What the rule for the destination and data class says: `allow`, `ask` or `deny`.
208    pub fn action(&self) -> EgressAction {
209        self.action
210    }
211
212    /// The index of the rule that decided, or `None` for the default.
213    pub fn rule(&self) -> Option<usize> {
214        self.rule
215    }
216
217    /// The destination hosts.
218    pub fn hosts(&self) -> &[String] {
219        &self.hosts
220    }
221
222    /// A one-line caption: destination, data class and what was covered, in the board's
223    /// wording: "1 face covered" for a face the face detector placed, "1 face · the whole
224    /// person is covered" for a person covered whole.
225    pub fn caption(&self) -> String {
226        let mut drawn: BTreeMap<&str, u32> = BTreeMap::new();
227        for (class, _) in &self.preview.filled {
228            *drawn.entry(class.as_str()).or_default() += 1;
229        }
230        let plural = |count: u32| if count == 1 { "" } else { "s" };
231        let mut covered = Vec::new();
232        let faces = drawn.remove("faces").unwrap_or(0);
233        let people = drawn.remove("people").unwrap_or(0);
234        match (faces, people) {
235            (0, 0) => {}
236            (faces, 0) => covered.push(format!("{faces} face{} covered", plural(faces))),
237            (0, people) => covered
238                .push(format!("{people} face{} · the whole person is covered", plural(people))),
239            (faces, people) => covered
240                .push(format!("{} faces covered, {people} as the whole person", faces + people)),
241        }
242        for (class, count) in drawn {
243            let plural = plural(count);
244            covered.push(match class {
245                "personal_text" => format!("{count} personal detail{plural} covered"),
246                "schema_personal_fields" => format!("{count} personal field{plural} covered"),
247                "marked" => format!("{count} marked region{plural} covered"),
248                other => format!("{count} {other} covered"),
249            });
250        }
251        let covered =
252            if covered.is_empty() { "nothing covered".to_string() } else { covered.join(", ") };
253        format!("to {} as {} · {covered}", self.hosts.join(", "), self.data_class)
254    }
255
256    /// The approval evidence for the stored egress copy: its digest, artifact, size, the
257    /// redactions as a region overlay, and the caption. `None` when the copy is not stored,
258    /// since a card loads evidence from its artifact.
259    pub fn image_evidence(&self) -> Option<adk_core::ImageEvidence> {
260        let stored = self.stored.as_ref()?;
261        let mut evidence = adk_core::ImageEvidence::new(
262            stored.digest.to_string(),
263            stored.artifact.clone(),
264            stored.mime_type.clone(),
265            stored.width,
266            stored.height,
267        )
268        .with_caption(self.caption());
269        if !self.preview.filled.is_empty() {
270            evidence = evidence.with_regions(
271                serde_json::to_value(self.preview.overlay()).unwrap_or(serde_json::Value::Null),
272            );
273        }
274        Some(evidence)
275    }
276}
277
278/// The only code that releases an image to a remote backend.
279///
280/// [`release`](Self::release) runs six steps:
281///
282/// 1. **Destination.** Under the on-device profile ([`EgressConfig::on_device`]) every host
283///    is refused here; otherwise the adk-core [`EgressPolicy`] decides each of the backend's
284///    hosts, and an unlisted host is refused here. `private_networks = false`
285///    ([`EgressConfig::private_networks`]) narrows that policy to public addresses.
286/// 2. **Minimise.** The image is cropped to the request's crop and downscaled to the
287///    backend's limit; both are recorded in the transform chain.
288/// 3. **Redact.** Every class the configuration lists, none by default, is found by its
289///    [`Redactor`] and filled with solid colour, then the caller's marked regions. A listed
290///    class with no redactor refuses the release.
291/// 4. **Decide.** The rule for the host or provider and the data class, else the default
292///    `allow`, says `deny`, `ask` or `allow`. `ask` holds the release unless a person
293///    approved this exact egress digest.
294/// 5. **Record.** The receipt goes to the [`EgressRecorder`] before the image is returned;
295///    a recorder failure refuses the release.
296/// 6. **Release.** The gate constructs the [`ReleasedImage`].
297///
298/// Every refusal is recorded too. A frozen kill switch or a cancelled call refuses at the
299/// first step and again right before release.
300pub struct EgressGate {
301    pub(super) policy: EgressPolicy,
302    pub(super) config: EgressConfig,
303    redactors: Vec<Arc<dyn Redactor>>,
304    pub(super) recorder: Arc<dyn EgressRecorder>,
305    store: Option<MediaStore>,
306    pub(super) released: std::sync::Mutex<std::collections::HashSet<Digest>>,
307}
308
309impl std::fmt::Debug for EgressGate {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        f.debug_struct("EgressGate")
312            .field("policy", &self.policy)
313            .field("config", &self.config)
314            .field("redactors", &self.redactors.iter().map(|r| r.class()).collect::<Vec<_>>())
315            .finish_non_exhaustive()
316    }
317}
318
319impl EgressGate {
320    /// A gate with a destination policy, egress rules and a recorder.
321    pub fn new(
322        policy: EgressPolicy,
323        config: EgressConfig,
324        recorder: Arc<dyn EgressRecorder>,
325    ) -> Self {
326        Self {
327            policy,
328            config,
329            redactors: Vec::new(),
330            recorder,
331            store: None,
332            released: std::sync::Mutex::new(std::collections::HashSet::new()),
333        }
334    }
335
336    /// Stores every egress copy as an artifact, under the call's media scope, before it is
337    /// released (spec 3.7 §7.8 step 5); the receipt and the audit record name it.
338    pub fn with_media_store(mut self, store: MediaStore) -> Self {
339        self.store = Some(store);
340        self
341    }
342
343    /// Whether this gate released an image with egress digest `digest`: a part carrying a
344    /// release annotation is trusted only when its bytes hash to a digest the gate released.
345    pub fn has_released(&self, digest: &Digest) -> bool {
346        self.released.lock().unwrap_or_else(|e| e.into_inner()).contains(digest)
347    }
348
349    /// The redaction classes the installed redactors find.
350    pub fn redaction_classes(&self) -> Vec<RedactionClass> {
351        let mut classes: Vec<RedactionClass> = self.redactors.iter().map(|r| r.class()).collect();
352        classes.sort();
353        classes.dedup();
354        classes
355    }
356
357    /// The action and rule for an image of `class` bound for `backend`: the strictest over
358    /// its hosts, `deny` over `ask` over `allow`, a `provider` rule matching each host of a
359    /// backend that names that provider. The default for a backend on the device.
360    ///
361    /// # Example
362    ///
363    /// ```
364    /// use std::sync::Arc;
365    /// use adk_core::egress::EgressPolicy;
366    /// use adk_vision::{
367    ///     BackendDescriptor, CoordFrame, DataClass, EgressAction, EgressConfig, EgressGate,
368    ///     InMemoryEgressRecorder, Locality,
369    /// };
370    ///
371    /// let config = EgressConfig::default().with_provider_rule("anthropic", &[], EgressAction::Ask);
372    /// let gate = EgressGate::new(EgressPolicy::allow_private_networks(), config, Arc::new(InMemoryEgressRecorder::new()));
373    /// let claude = BackendDescriptor::new(
374    ///     "claude",
375    ///     Locality::Remote { hosts: vec!["gateway.example.com".into()] },
376    ///     CoordFrame::SentPixels,
377    /// );
378    /// let photo = DataClass::new("photo");
379    /// assert_eq!(gate.decide(&claude, &photo), (EgressAction::Allow, None));
380    /// assert_eq!(gate.decide(&claude.with_provider("anthropic"), &photo), (EgressAction::Ask, Some(0)));
381    /// ```
382    pub fn decide(
383        &self,
384        backend: &BackendDescriptor,
385        class: &DataClass,
386    ) -> (EgressAction, Option<usize>) {
387        let hosts = match &backend.locality {
388            Locality::Remote { hosts } => hosts.as_slice(),
389            Locality::InProcess | Locality::Loopback => &[],
390        };
391        hosts
392            .iter()
393            .map(|host| self.config.decide(host, &backend.providers, class))
394            .max_by_key(|(action, _)| *action)
395            .unwrap_or((self.config.default, None))
396    }
397
398    /// Installs a redactor.
399    pub fn with_redactor(mut self, redactor: Arc<dyn Redactor>) -> Self {
400        self.redactors.push(redactor);
401        self
402    }
403
404    /// The egress rules.
405    pub fn config(&self) -> &EgressConfig {
406        &self.config
407    }
408
409    /// The network policy the destination step applies: the gate's policy, narrowed to
410    /// public addresses under `private_networks = false`.
411    pub(super) fn destination_policy(&self) -> Cow<'_, EgressPolicy> {
412        if self.config.private_networks {
413            Cow::Borrowed(&self.policy)
414        } else {
415            Cow::Owned(self.policy.narrow(&EgressPolicy::public_only()))
416        }
417    }
418
419    /// Runs the destination, minimise and redact steps and returns what would leave, for an
420    /// approval card. Records nothing unless it refuses.
421    ///
422    /// # Errors
423    ///
424    /// The refusals of [`release`](Self::release)'s first three steps.
425    pub async fn preview(
426        &self,
427        cx: &VisionCx,
428        request: &ReleaseRequest<'_>,
429    ) -> Result<EgressPreview> {
430        let hosts = remote_hosts(request.backend)?;
431        self.prepare(cx, request, &hosts).await
432    }
433
434    /// Runs the destination, minimise and redact steps, stores the egress copy, and returns
435    /// what would leave with the rule that applies, for an approval card (spec 3.7 S4).
436    ///
437    /// Releases nothing. A rule that denies is refused here, and recorded, so nobody is
438    /// asked about an image that can never leave.
439    ///
440    /// # Errors
441    ///
442    /// The refusals of [`release`](Self::release)'s first three steps,
443    /// [`VisionError::EgressRefused`] for a rule that denies, and the media store's error.
444    pub async fn stage(&self, cx: &VisionCx, request: &ReleaseRequest<'_>) -> Result<StagedEgress> {
445        let hosts = remote_hosts(request.backend)?;
446        let preview = self.prepare(cx, request, &hosts).await?;
447        let (action, rule) = self.decide(request.backend, &request.data_class);
448        if action == EgressAction::Deny {
449            let reason = deny_reason(rule, &request.data_class);
450            self.refuse(cx, request, &hosts, Some(preview.egress), "decide", &reason).await?;
451            return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
452        }
453        let stored = self.store_copy(cx, request, &preview).await?;
454        Ok(StagedEgress {
455            preview,
456            stored,
457            action,
458            rule,
459            hosts,
460            data_class: request.data_class.clone(),
461        })
462    }
463
464    async fn store_copy(
465        &self,
466        cx: &VisionCx,
467        request: &ReleaseRequest<'_>,
468        preview: &EgressPreview,
469    ) -> Result<Option<ImageRef>> {
470        let (Some(store), Some(scope)) = (&self.store, cx.media_scope()) else {
471            return Ok(None);
472        };
473        let provenance = Provenance::Derived {
474            from: request.source.digest(),
475            operation: Digest::of_json(&serde_json::json!({
476                "op": "egress",
477                "chain": preview.image.chain(),
478            })),
479        };
480        let (image, _) = store.put_image(scope, preview.bytes.to_vec(), provenance).await?;
481        Ok(Some(image))
482    }
483
484    /// Releases an image to a remote backend, or refuses.
485    ///
486    /// # Errors
487    ///
488    /// [`VisionError::EgressRefused`] at the destination or decide step,
489    /// [`VisionError::InputTooLarge`] for an oversized image a backend refuses to have
490    /// resized, [`VisionError::RedactionUnavailable`], [`VisionError::EgressHeld`] for a
491    /// rule that asks, [`VisionError::Cancelled`] or the kill switch's error, and the
492    /// recorder's error.
493    pub async fn release(
494        &self,
495        cx: &VisionCx,
496        request: ReleaseRequest<'_>,
497    ) -> Result<ReleasedImage> {
498        let hosts = remote_hosts(request.backend)?;
499        let preview = self.prepare(cx, &request, &hosts).await?;
500        let (action, rule) = self.decide(request.backend, &request.data_class);
501        let decision = match action {
502            EgressAction::Allow => EgressDecision::Allowed { rule },
503            EgressAction::Ask if request.approved.contains(&preview.egress) => {
504                EgressDecision::Approved { rule }
505            }
506            EgressAction::Ask => {
507                let reason = format!("held for a person's approval of {}", preview.egress);
508                self.refuse(cx, &request, &hosts, Some(preview.egress), "decide", &reason).await?;
509                return Err(VisionError::EgressHeld {
510                    host: hosts.join(", "),
511                    data_class: request.data_class.to_string(),
512                    egress: preview.egress,
513                });
514            }
515            EgressAction::Deny => {
516                let reason = deny_reason(rule, &request.data_class);
517                self.refuse(cx, &request, &hosts, Some(preview.egress), "decide", &reason).await?;
518                return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
519            }
520        };
521        if let Err(err) = cx.check() {
522            self.refuse(cx, &request, &hosts, Some(preview.egress), "release", &err.to_string())
523                .await?;
524            return Err(err);
525        }
526        let artifact = match self.store_copy(cx, &request, &preview).await {
527            Ok(stored) => stored.map(|image| image.artifact),
528            Err(err) => {
529                let reason = format!("the egress copy could not be stored: {err}");
530                self.refuse(cx, &request, &hosts, Some(preview.egress), "record", &reason).await?;
531                return Err(err);
532            }
533        };
534        let receipt = EgressReceipt {
535            id: uuid::Uuid::new_v4().to_string(),
536            source: request.source.digest(),
537            egress: preview.egress,
538            backend: request.backend.id.clone(),
539            hosts: hosts.clone(),
540            data_class: request.data_class.clone(),
541            chain: preview.image.chain().clone(),
542            redactions: preview.redactions.clone(),
543            decision,
544            estimated_cost_micro_usd: request
545                .backend
546                .price
547                .as_ref()
548                .and_then(|p| p.request_cost(1)),
549            artifact,
550            released_at: Utc::now(),
551        };
552        let record = EgressRecord::Released(receipt.clone());
553        self.recorder.record(record.clone()).await?;
554        cx.audit(crate::audit::egress_draft(&record)).await?;
555        self.released.lock().unwrap_or_else(|e| e.into_inner()).insert(receipt.egress);
556        tracing::info!(
557            egress.backend = %receipt.backend,
558            egress.source = %receipt.source,
559            egress.digest = %receipt.egress,
560            egress.data_class = %receipt.data_class,
561            "image released"
562        );
563        Ok(ReleasedImage::from_gate(preview.image, preview.bytes, receipt))
564    }
565
566    async fn prepare(
567        &self,
568        cx: &VisionCx,
569        request: &ReleaseRequest<'_>,
570        hosts: &[String],
571    ) -> Result<EgressPreview> {
572        if let Err(err) = cx.check() {
573            self.refuse(cx, request, hosts, None, "destination", &err.to_string()).await?;
574            return Err(err);
575        }
576        if self.config.on_device {
577            let reason = on_device_reason(hosts);
578            self.refuse(cx, request, hosts, None, "destination", &reason).await?;
579            return Err(VisionError::EgressRefused { host: hosts.join(", "), reason });
580        }
581        let policy = self.destination_policy();
582        for host in hosts {
583            let (name, port) = split_host_port(host);
584            if let Err(denial) = policy.decide(&EgressTarget::Name { host: name, port }) {
585                let reason = denial.to_string();
586                self.refuse(cx, request, hosts, None, "destination", &reason).await?;
587                return Err(VisionError::EgressRefused { host: host.clone(), reason });
588            }
589        }
590
591        let source = request.source;
592        let (w, h) = source.size();
593        let mut chain = TransformChain::new(w, h);
594        let mut pixels = source.shared_pixels();
595        if let Some(crop) = request.crop {
596            let (x, y, cw, ch) = crop.pixel_bounds(w, h);
597            if cw == 0 || ch == 0 {
598                let reason = format!("crop {crop:?} leaves no pixels of the {w}x{h} image");
599                self.refuse(cx, request, hosts, None, "minimise", &reason).await?;
600                return Err(VisionError::InvalidInput(reason));
601            }
602            chain.push(Transform::Crop { x, y, width: cw, height: ch })?;
603            pixels = Arc::new(ops::crop(&pixels, x, y, cw, ch));
604        }
605        let limits = request.backend.limits;
606        if let Some((fw, fh)) = limits.fit(pixels.size()) {
607            if limits.oversize == Oversize::Refuse {
608                let (pw, ph) = pixels.size();
609                let err = VisionError::InputTooLarge {
610                    backend: request.backend.id.to_string(),
611                    limit: limits.describe(),
612                    actual: format!("{pw}x{ph}"),
613                };
614                self.refuse(cx, request, hosts, None, "minimise", &err.to_string()).await?;
615                return Err(err);
616            }
617            chain.push(Transform::Resize { width: fw, height: fh })?;
618            pixels = Arc::new(ops::resize(&pixels, fw, fh));
619        }
620
621        let minimised = SentImage::new(source.digest(), Arc::clone(&pixels), chain.clone());
622        // Each required class with the boxes found for it, each box with the class it is drawn as.
623        let mut boxes: Vec<(RedactionClass, Vec<(RedactionClass, BBox)>)> = Vec::new();
624        let mut required: Vec<&RedactionClass> = Vec::new();
625        for class in &self.config.redact {
626            if !required.contains(&class) {
627                required.push(class);
628            }
629        }
630        for class in required {
631            let redactors: Vec<&Arc<dyn Redactor>> =
632                self.redactors.iter().filter(|r| &r.class() == class).collect();
633            if redactors.is_empty() {
634                let err = VisionError::RedactionUnavailable { class: class.to_string() };
635                self.refuse(cx, request, hosts, None, "redact", &err.to_string()).await?;
636                return Err(err);
637            }
638            let mut found = Vec::new();
639            for redactor in redactors {
640                match redactor.find_classified(cx, &minimised).await {
641                    Ok(regions) => found.extend(regions),
642                    Err(err) => {
643                        let reason = format!("the `{class}` redactor failed: {err}");
644                        self.refuse(cx, request, hosts, None, "redact", &reason).await?;
645                        return Err(err);
646                    }
647                }
648            }
649            boxes.push((class.clone(), found));
650        }
651        if !request.marked.is_empty() {
652            let marked = request
653                .marked
654                .iter()
655                .map(|b| (RedactionClass::marked(), chain.bbox_to_target(b)))
656                .collect();
657            boxes.push((RedactionClass::marked(), marked));
658        }
659
660        let mut redacted = (*pixels).clone();
661        let mut redactions = BTreeMap::new();
662        let mut filled = Vec::new();
663        for (class, regions) in boxes {
664            let mut count = 0u32;
665            for (drawn, region) in regions {
666                if ops::fill(&mut redacted, &region, Rgba::BLACK) {
667                    count += 1;
668                    filled.push((drawn, region));
669                }
670            }
671            redactions.insert(class, count);
672        }
673        if redactions.values().any(|&n| n > 0) {
674            chain.push(Transform::Redact)?;
675        }
676        let bytes: Arc<[u8]> = redacted.encode_png()?.into();
677        let egress = Digest::of(&bytes);
678        Ok(EgressPreview {
679            image: SentImage::new(source.digest(), Arc::new(redacted), chain),
680            bytes,
681            egress,
682            redactions,
683            filled,
684        })
685    }
686
687    async fn refuse(
688        &self,
689        cx: &VisionCx,
690        request: &ReleaseRequest<'_>,
691        hosts: &[String],
692        egress: Option<Digest>,
693        step: &str,
694        reason: &str,
695    ) -> Result<()> {
696        tracing::warn!(
697            egress.backend = %request.backend.id,
698            egress.step = step,
699            egress.reason = reason,
700            "image not released"
701        );
702        let record = EgressRecord::Refused(EgressRefusal {
703            source: request.source.digest(),
704            egress,
705            backend: request.backend.id.clone(),
706            hosts: hosts.to_vec(),
707            data_class: request.data_class.clone(),
708            step: step.to_string(),
709            reason: reason.to_string(),
710            refused_at: Utc::now(),
711        });
712        self.recorder.record(record.clone()).await?;
713        cx.audit(crate::audit::egress_draft(&record)).await
714    }
715}
716
717/// Why the on-device profile refuses a release to `hosts`.
718pub(super) fn on_device_reason(hosts: &[String]) -> String {
719    format!(
720        "the on-device profile keeps every image on this machine, and `{}` is off it \
721         (`on_device = true` in the [egress] table of .adk/vision.toml)",
722        hosts.join(", ")
723    )
724}
725
726pub(super) fn deny_reason(rule: Option<usize>, class: &DataClass) -> String {
727    match rule {
728        Some(index) => format!("egress rule {index} denies `{class}`"),
729        None => format!("the default egress action denies `{class}`"),
730    }
731}
732
733/// `host`, `host:port` or `[v6]:port`; HTTPS's port when none is given.
734pub(super) fn split_host_port(host: &str) -> (&str, u16) {
735    match host.rsplit_once(':') {
736        Some((name, port)) if !name.contains(':') || name.ends_with(']') => {
737            port.parse().map_or((host, 443), |port| (name, port))
738        }
739        _ => (host, 443),
740    }
741}
742
743pub(super) fn remote_hosts(backend: &BackendDescriptor) -> Result<Vec<String>> {
744    match &backend.locality {
745        Locality::Remote { hosts } if !hosts.is_empty() => Ok(hosts.clone()),
746        Locality::Remote { .. } => Err(VisionError::InvalidInput(format!(
747            "remote backend `{}` declares no hosts, so no egress rule can apply to it",
748            backend.id
749        ))),
750        Locality::InProcess | Locality::Loopback => Err(VisionError::InvalidInput(format!(
751            "backend `{}` runs on the device; only remote backends need a release",
752            backend.id
753        ))),
754    }
755}