Skip to main content

adk_vision/egress/
mod.rs

1//! The egress boundary (spec 3.7 §7.8): [`ReleasedImage`], the only image a remote backend
2//! accepts, and the [`EgressGate`], the only code that constructs one.
3//!
4//! The gate runs six steps — destination, minimise, redact, decide, record, release. With
5//! no rules an image leaves as it is; a class the rules list is always redacted before the
6//! decision, so no configuration releases an image before its listed classes are covered
7//! (V-I2). A `ReleasedImage` has no public constructor (V-I1), and neither has
8//! a [`ReleasedClip`], the video counterpart a remote video analyzer takes.
9
10mod clip;
11mod config;
12mod gate;
13
14use std::collections::BTreeMap;
15use std::fmt;
16use std::sync::{Arc, Mutex};
17
18use async_trait::async_trait;
19use chrono::{DateTime, Utc};
20use serde::{Deserialize, Serialize};
21
22pub use clip::{ClipReleaseRequest, ReleasedClip};
23pub use config::{EgressAction, EgressConfig, EgressRuleConfig, RuleTarget, VisionConfig};
24pub use gate::{EgressGate, EgressPreview, ReleaseRequest, StagedEgress};
25
26use crate::backend::BackendId;
27use crate::cx::VisionCx;
28use crate::digest::Digest;
29use crate::error::Result;
30use crate::geometry::{BBox, RegionSet, TransformChain};
31use crate::media::DecodedImage;
32use crate::sent::SentImage;
33
34/// The kind of data an image is, which egress rules are written per: `document_crop`,
35/// `photo`, `screen`.
36#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
37#[serde(transparent)]
38pub struct DataClass(String);
39
40impl DataClass {
41    /// A data class.
42    pub fn new(class: impl Into<String>) -> Self {
43        Self(class.into())
44    }
45
46    /// The class as text.
47    pub fn as_str(&self) -> &str {
48        &self.0
49    }
50}
51
52impl fmt::Display for DataClass {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.write_str(&self.0)
55    }
56}
57
58impl From<&str> for DataClass {
59    fn from(class: &str) -> Self {
60        Self::new(class)
61    }
62}
63
64/// A class of content the gate redacts before release: `faces`, `personal_text`,
65/// `schema_personal_fields`, or `marked` for regions the caller names.
66#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
67#[serde(transparent)]
68pub struct RedactionClass(String);
69
70impl RedactionClass {
71    /// A redaction class.
72    pub fn new(class: impl Into<String>) -> Self {
73        Self(class.into())
74    }
75
76    /// Faces: the class an egress rule requires. `FaceRedactor` covers each face a face
77    /// detector finds, and each person it finds no face for as the whole person;
78    /// `PersonRedactor` covers every detected person's whole box (spec 3.7 Q3).
79    pub fn faces() -> Self {
80        Self::new("faces")
81    }
82
83    /// A person's whole box, covering a face that a redactor of [`faces`](Self::faces) could
84    /// not place: no face detector runs, or the person shows no face it can find. Boxes are
85    /// drawn and counted on captions as this class; receipts count them under `faces`.
86    pub fn people() -> Self {
87        Self::new("people")
88    }
89
90    /// Personal text found by local OCR and the PII patterns.
91    pub fn personal_text() -> Self {
92        Self::new("personal_text")
93    }
94
95    /// Fields a document schema marks personal.
96    pub fn schema_personal_fields() -> Self {
97        Self::new("schema_personal_fields")
98    }
99
100    /// Regions the caller marked for redaction.
101    pub fn marked() -> Self {
102        Self::new("marked")
103    }
104
105    /// The class as text.
106    pub fn as_str(&self) -> &str {
107        &self.0
108    }
109}
110
111impl fmt::Display for RedactionClass {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.write_str(&self.0)
114    }
115}
116
117/// Finds the regions of one [`RedactionClass`] in an image, on the device.
118///
119/// A redactor sees the minimised image the gate is about to release and answers in its
120/// pixels; the gate fills every box with solid colour, because blur and pixelation of text
121/// can be reversed.
122#[async_trait]
123pub trait Redactor: Send + Sync {
124    /// The class this redactor finds.
125    fn class(&self) -> RedactionClass;
126
127    /// The boxes to fill, in `image`'s pixels.
128    async fn find(&self, cx: &VisionCx, image: &SentImage) -> Result<Vec<BBox>>;
129
130    /// The boxes to fill, each with the class it is drawn as on an approval card's overlay
131    /// and named as on its caption: by default every box of [`find`](Self::find) as
132    /// [`class`](Self::class). A faces redactor names the whole-person boxes it falls back to
133    /// [`RedactionClass::people`], so a card says which faces were covered as the whole
134    /// person. The receipt counts every box under [`class`](Self::class).
135    ///
136    /// # Errors
137    ///
138    /// As [`find`](Self::find).
139    async fn find_classified(
140        &self,
141        cx: &VisionCx,
142        image: &SentImage,
143    ) -> Result<Vec<(RedactionClass, BBox)>> {
144        let class = self.class();
145        Ok(self.find(cx, image).await?.into_iter().map(|bbox| (class.clone(), bbox)).collect())
146    }
147}
148
149/// How a release was decided.
150#[non_exhaustive]
151#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase", tag = "kind")]
153pub enum EgressDecision {
154    /// A rule, or the default, allows this destination and data class.
155    Allowed {
156        /// The index of the matching `[[egress.rule]]`, or `None` for the default.
157        #[serde(default, skip_serializing_if = "Option::is_none")]
158        rule: Option<usize>,
159    },
160    /// The rule asks a person, and a person approved this exact egress digest.
161    Approved {
162        /// The index of the matching rule, or `None` for the default.
163        #[serde(default, skip_serializing_if = "Option::is_none")]
164        rule: Option<usize>,
165    },
166}
167
168/// What left the machine: written before the request is sent (V-I3).
169#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct EgressReceipt {
172    /// A unique identifier for this release.
173    pub id: String,
174    /// The source image's digest.
175    pub source: Digest,
176    /// The digest of the exact bytes released.
177    pub egress: Digest,
178    /// The backend the image is released to.
179    pub backend: BackendId,
180    /// The destination hosts.
181    pub hosts: Vec<String>,
182    /// The data class.
183    pub data_class: DataClass,
184    /// The transforms from the source to the released image, redaction included.
185    pub chain: TransformChain,
186    /// Boxes filled, by redaction class.
187    pub redactions: BTreeMap<RedactionClass, u32>,
188    /// How the release was decided.
189    pub decision: EgressDecision,
190    /// The estimated cost of the call, when the backend is priced per unit.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub estimated_cost_micro_usd: Option<u64>,
193    /// The artifact the egress copy is stored in, when the gate has a media store and the
194    /// call a media scope.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub artifact: Option<crate::media::ArtifactLocator>,
197    /// When the image was released.
198    pub released_at: DateTime<Utc>,
199}
200
201/// Why an image was not released.
202#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
203#[serde(rename_all = "camelCase")]
204pub struct EgressRefusal {
205    /// The source image's digest.
206    pub source: Digest,
207    /// The digest of the redacted image, when the gate got that far.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub egress: Option<Digest>,
210    /// The backend.
211    pub backend: BackendId,
212    /// The destination hosts.
213    pub hosts: Vec<String>,
214    /// The data class.
215    pub data_class: DataClass,
216    /// The step that refused: `destination`, `minimise`, `redact`, `decide`.
217    pub step: String,
218    /// Why.
219    pub reason: String,
220    /// When.
221    pub refused_at: DateTime<Utc>,
222}
223
224/// One entry in the egress record: `vision.egress.released` or `vision.egress.refused`.
225#[non_exhaustive]
226#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase", tag = "kind")]
228pub enum EgressRecord {
229    /// An image was released.
230    Released(EgressReceipt),
231    /// An image was not released.
232    Refused(EgressRefusal),
233}
234
235impl EgressRecord {
236    /// The audit action: `vision.egress.released` or `vision.egress.refused`.
237    pub fn action(&self) -> &'static str {
238        match self {
239            Self::Released(_) => "vision.egress.released",
240            Self::Refused(_) => "vision.egress.refused",
241        }
242    }
243}
244
245/// Where the gate writes what left the machine and what did not.
246///
247/// The gate writes a release before it returns the [`ReleasedImage`]; a recorder that
248/// fails refuses the release.
249#[async_trait]
250pub trait EgressRecorder: Send + Sync {
251    /// Records one entry.
252    async fn record(&self, record: EgressRecord) -> Result<()>;
253}
254
255/// An [`EgressRecorder`] that keeps entries in memory, for tests and for proving that a
256/// run sent nothing off the machine.
257#[derive(Debug, Default)]
258pub struct InMemoryEgressRecorder {
259    records: Mutex<Vec<EgressRecord>>,
260}
261
262impl InMemoryEgressRecorder {
263    /// An empty recorder.
264    pub fn new() -> Self {
265        Self::default()
266    }
267
268    /// Every entry, in order.
269    pub fn records(&self) -> Vec<EgressRecord> {
270        self.records.lock().unwrap_or_else(|e| e.into_inner()).clone()
271    }
272
273    /// The releases, in order.
274    pub fn released(&self) -> Vec<EgressReceipt> {
275        self.records()
276            .into_iter()
277            .filter_map(|r| match r {
278                EgressRecord::Released(receipt) => Some(receipt),
279                EgressRecord::Refused(_) => None,
280            })
281            .collect()
282    }
283
284    /// `true` when nothing was recorded.
285    pub fn is_empty(&self) -> bool {
286        self.records.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
287    }
288}
289
290#[async_trait]
291impl EgressRecorder for InMemoryEgressRecorder {
292    async fn record(&self, record: EgressRecord) -> Result<()> {
293        self.records.lock().unwrap_or_else(|e| e.into_inner()).push(record);
294        Ok(())
295    }
296}
297
298/// An image the egress gate released to one backend: the minimised, redacted pixels, the
299/// exact bytes sent, and the receipt the gate recorded.
300///
301/// The only input a remote backend accepts; only [`EgressGate`] constructs one (V-I1):
302///
303/// ```compile_fail,E0599
304/// use adk_vision::ReleasedImage;
305///
306/// let forged = ReleasedImage::new();
307/// ```
308#[derive(Debug)]
309pub struct ReleasedImage {
310    image: SentImage,
311    bytes: Arc<[u8]>,
312    receipt: EgressReceipt,
313}
314
315impl ReleasedImage {
316    pub(crate) fn from_gate(image: SentImage, bytes: Arc<[u8]>, receipt: EgressReceipt) -> Self {
317        Self { image, bytes, receipt }
318    }
319
320    /// The released pixels and their transform chain from the source.
321    pub fn image(&self) -> &SentImage {
322        &self.image
323    }
324
325    /// The released pixels.
326    pub fn pixels(&self) -> &DecodedImage {
327        self.image.pixels()
328    }
329
330    /// The exact PNG bytes released; their digest is the receipt's `egress`.
331    pub fn bytes(&self) -> &[u8] {
332        &self.bytes
333    }
334
335    /// `image/png`.
336    pub fn mime_type(&self) -> &'static str {
337        "image/png"
338    }
339
340    /// The receipt the gate recorded.
341    pub fn receipt(&self) -> &EgressReceipt {
342        &self.receipt
343    }
344
345    /// `true` when this image was released to `backend`.
346    pub fn is_for(&self, backend: &BackendId) -> bool {
347        &self.receipt.backend == backend
348    }
349
350    /// A model part for the released bytes, annotated with the release so the privacy
351    /// guardrail knows it already passed the gate.
352    pub fn to_part(&self) -> adk_core::Part {
353        adk_core::Part::InlineData {
354            mime_type: self.mime_type().to_string(),
355            data: self.bytes.to_vec(),
356            uri: None,
357            annotations: Some(serde_json::json!({
358                "adkVision": {
359                    "digest": self.receipt.egress,
360                    "release": { "id": self.receipt.id, "source": self.receipt.source },
361                }
362            })),
363        }
364    }
365}
366
367/// What an approval card shows for a held release: the exact image that would leave,
368/// after redaction, with its digest, destination and what was redacted.
369///
370/// Maps to `adk_core::evidence::ImageEvidence` once approvals carry evidence (spec 3.7 X4):
371/// the gate stores the egress copy as an artifact, and the evidence names its locator,
372/// with this overlay as `with_regions` and this caption as `with_caption`.
373#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
374#[serde(rename_all = "camelCase")]
375pub struct EgressEvidence {
376    /// The digest of the image that would leave.
377    pub digest: Digest,
378    /// `image/png`.
379    pub mime_type: String,
380    /// Width in pixels.
381    pub width: u32,
382    /// Height in pixels.
383    pub height: u32,
384    /// Regions to draw over the image.
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub overlay: Option<RegionSet>,
387    /// A one-line caption: destination, data class, redactions.
388    pub caption: String,
389}