1use 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#[derive(Clone, Debug)]
43#[non_exhaustive]
44pub struct ReleaseRequest<'a> {
45 pub source: &'a SourceImage,
47 pub backend: &'a BackendDescriptor,
49 pub data_class: DataClass,
51 pub crop: Option<BBox>,
54 pub marked: Vec<BBox>,
56 pub approved: Vec<Digest>,
58}
59
60impl<'a> ReleaseRequest<'a> {
61 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 pub fn with_crop(mut self, crop: BBox) -> Self {
72 self.crop = Some(crop);
73 self
74 }
75
76 pub fn with_marked(mut self, regions: Vec<BBox>) -> Self {
78 self.marked = regions;
79 self
80 }
81
82 pub fn approved(mut self, digest: Digest) -> Self {
84 self.approved.push(digest);
85 self
86 }
87}
88
89#[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 pub fn digest(&self) -> Digest {
102 self.egress
103 }
104
105 pub fn pixels(&self) -> &DecodedImage {
107 self.image.pixels()
108 }
109
110 pub fn bytes(&self) -> &[u8] {
112 &self.bytes
113 }
114
115 pub fn chain(&self) -> &TransformChain {
117 self.image.chain()
118 }
119
120 pub fn redactions(&self) -> &BTreeMap<RedactionClass, u32> {
123 &self.redactions
124 }
125
126 pub fn filled(&self) -> &[(RedactionClass, BBox)] {
129 &self.filled
130 }
131
132 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 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
172pub(crate) const EGRESS_GATE_BACKEND: &str = "egress-gate";
174
175#[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 pub fn digest(&self) -> Digest {
194 self.preview.egress
195 }
196
197 pub fn preview(&self) -> &EgressPreview {
199 &self.preview
200 }
201
202 pub fn stored(&self) -> Option<&ImageRef> {
204 self.stored.as_ref()
205 }
206
207 pub fn action(&self) -> EgressAction {
209 self.action
210 }
211
212 pub fn rule(&self) -> Option<usize> {
214 self.rule
215 }
216
217 pub fn hosts(&self) -> &[String] {
219 &self.hosts
220 }
221
222 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 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
278pub 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 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 pub fn with_media_store(mut self, store: MediaStore) -> Self {
339 self.store = Some(store);
340 self
341 }
342
343 pub fn has_released(&self, digest: &Digest) -> bool {
346 self.released.lock().unwrap_or_else(|e| e.into_inner()).contains(digest)
347 }
348
349 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 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 pub fn with_redactor(mut self, redactor: Arc<dyn Redactor>) -> Self {
400 self.redactors.push(redactor);
401 self
402 }
403
404 pub fn config(&self) -> &EgressConfig {
406 &self.config
407 }
408
409 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 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 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 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 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, ®ion, 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
717pub(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
733pub(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}