Skip to main content

active_infinity/
protobuf.rs

1//! Protobuf-wire interop projection.
2//!
3//! Active Infinity is the canonical form, and it is the form peers should
4//! exchange. The rest of the world, however, speaks Protobuf: dashboards,
5//! queues, analytics, tracing pipelines and every language with a generated
6//! client. This module renders a module into protobuf wire format so those
7//! consumers can read Active data without implementing the AINF layout, and so
8//! an Active producer can feed existing infrastructure directly.
9//!
10//! The projection is **redacted by construction**: it is built from the same
11//! [`crate::interop::Projected`] tree as the JSON projection, so secrets are
12//! replaced by [`crate::interop::SECRET_MARKER`] before a single byte is
13//! written. Blob payloads never leave the module; only their identity does.
14//!
15//! # Schema
16//!
17//! ```proto
18//! syntax = "proto3";
19//! package active.infinity.v1;
20//!
21//! message Module {
22//!   bytes content_hash = 1;   // Blake3-256 of the canonical AINF image
23//!   uint64 total_size = 2;    // canonical AINF image size in bytes
24//!   Value root = 3;           // omitted when the module has no root
25//!   repeated Binding bindings = 4;
26//!   Provenance provenance = 5; // omitted when absent
27//!   repeated Annotation annotations = 6;
28//!   repeated Extension extensions = 7;
29//! }
30//!
31//! message Binding { string name = 1; Value value = 2; }
32//!
33//! message Annotation {
34//!   uint32 subject = 1;      // node id
35//!   oneof kind {
36//!     string intent = 2;     // documentation only
37//!     Constraint constraint = 3;
38//!     bool ai_immutable = 4;
39//!   }
40//! }
41//! message Constraint { string source = 1; uint32 expr = 2; }
42//!
43//! message Provenance {
44//!   string producer = 1;
45//!   uint64 timestamp_ms = 2;
46//!   string model = 3;
47//!   string tool = 4;
48//!   bytes parent = 5;        // omitted when absent (32 bytes when present)
49//!   repeated Entry entries = 6;
50//!   message Entry {
51//!     string key = 1;
52//!     oneof value {
53//!       string text = 2;
54//!       sint64 integer = 3;
55//!       bool flag = 4;
56//!       bytes hash = 5;      // 32 bytes
57//!     }
58//!   }
59//! }
60//!
61//! message Extension { uint64 tag = 1; bytes payload = 2; }
62//!
63//! message Value {
64//!   oneof kind {
65//!     Null null_value = 1;
66//!     bool boolean = 2;
67//!     sint64 integer = 3;
68//!     double float = 4;
69//!     string text = 5;
70//!     Ms duration_ms = 6;
71//!     Quantity quantity = 7;
72//!     List list = 8;
73//!     Record record = 9;
74//!     Blob blob = 10;
75//!     Env env = 11;
76//!     Expr expr = 12;
77//!   }
78//! }
79//! message Null {}
80//! message Ms { uint64 ms = 1; }
81//! message Quantity { Value value = 1; string unit = 2; }
82//! message List { repeated Value items = 1; }
83//! message Record { repeated Field fields = 1; }
84//! message Field { string name = 1; Value value = 2; }
85//! message Blob {
86//!   bytes blake3 = 1;        // 32 bytes
87//!   uint64 size = 2;
88//!   string media_type = 3;
89//!   bool tainted = 4;
90//! }
91//! message Env { string name = 1; }
92//! message Expr { string kind = 1; }
93//! ```
94//!
95//! # Encoding rules
96//!
97//! Rewriting a module always produces identical bytes, which lets consumers
98//! hash, cache and diff the projection:
99//!
100//! - fields are emitted in ascending field-number order (`#[prost]`-generated
101//!   structs parse it, and so does every conformant reader);
102//! - scalar fields are emitted even when they equal the proto3 default, so the
103//!   encoding is injective for the projected tree;
104//! - absent optional messages (`root`, `provenance`) and empty repeated fields
105//!   are omitted;
106//! - varints are minimal, `sint64` uses zig-zag, `double` is little-endian
107//!   IEEE-754, and every length prefix is exact;
108//! - the projection is built from the *canonical* module (the decode of its own
109//!   encoded image), so logically equal modules project to identical bytes and
110//!   bindings, annotations and extensions come out in canonical order;
111//! - a module whose opaque extension payload contains a secret literal is
112//!   refused: the projection must not copy secret material it cannot redact
113//!   without corrupting an opaque payload.
114
115use crate::encode::{encode, hash_image};
116use crate::error::{Error, Result};
117use crate::interop::{project_node_with, redacted_key, redacted_value, secret_table, Projected};
118use crate::ir::{AnnotationKind, InfinityModule, ProvValue};
119
120// ---------------------------------------------------------------------------
121// wire primitives
122// ---------------------------------------------------------------------------
123
124const WIRE_VARINT: u8 = 0;
125const WIRE_DOUBLE: u8 = 1;
126const WIRE_LEN: u8 = 2;
127
128fn varint(out: &mut Vec<u8>, mut value: u64) {
129    while value >= 0x80 {
130        out.push((value as u8) | 0x80);
131        value >>= 7;
132    }
133    out.push(value as u8);
134}
135
136fn tag(out: &mut Vec<u8>, field: u32, wire: u8) {
137    varint(out, (u64::from(field) << 3) | u64::from(wire));
138}
139
140fn uint(out: &mut Vec<u8>, field: u32, value: u64) {
141    tag(out, field, WIRE_VARINT);
142    varint(out, value);
143}
144
145fn sint(out: &mut Vec<u8>, field: u32, value: i64) {
146    tag(out, field, WIRE_VARINT);
147    varint(out, ((value << 1) ^ (value >> 63)) as u64);
148}
149
150fn boolean(out: &mut Vec<u8>, field: u32, value: bool) {
151    tag(out, field, WIRE_VARINT);
152    varint(out, u64::from(value));
153}
154
155fn double(out: &mut Vec<u8>, field: u32, value: f64) {
156    tag(out, field, WIRE_DOUBLE);
157    out.extend_from_slice(&value.to_bits().to_le_bytes());
158}
159
160fn bytes(out: &mut Vec<u8>, field: u32, value: &[u8]) {
161    tag(out, field, WIRE_LEN);
162    varint(out, value.len() as u64);
163    out.extend_from_slice(value);
164}
165
166fn string(out: &mut Vec<u8>, field: u32, value: &str) {
167    bytes(out, field, value.as_bytes());
168}
169
170fn message(out: &mut Vec<u8>, field: u32, body: &[u8]) {
171    bytes(out, field, body);
172}
173
174// ---------------------------------------------------------------------------
175// value tree
176// ---------------------------------------------------------------------------
177
178fn encode_value(value: &Projected, out: &mut Vec<u8>) {
179    match value {
180        Projected::Null => message(out, 1, &[]),
181        Projected::Bool(flag) => boolean(out, 2, *flag),
182        Projected::Int(number) => sint(out, 3, *number),
183        Projected::Float(number) => double(out, 4, *number),
184        Projected::Text(text) => string(out, 5, text),
185        Projected::DurationMs(ms) => {
186            let mut body = Vec::new();
187            uint(&mut body, 1, *ms);
188            message(out, 6, &body);
189        }
190        Projected::Quantity(value, unit) => {
191            let mut body = Vec::new();
192            let mut inner = Vec::new();
193            encode_value(value, &mut inner);
194            message(&mut body, 1, &inner);
195            string(&mut body, 2, unit);
196            message(out, 7, &body);
197        }
198        Projected::Array(items) => {
199            let mut body = Vec::new();
200            for item in items {
201                let mut encoded = Vec::new();
202                encode_value(item, &mut encoded);
203                message(&mut body, 1, &encoded);
204            }
205            message(out, 8, &body);
206        }
207        Projected::Record(fields) => {
208            let mut body = Vec::new();
209            for (name, value) in fields {
210                let mut field = Vec::new();
211                string(&mut field, 1, name);
212                let mut encoded = Vec::new();
213                encode_value(value, &mut encoded);
214                message(&mut field, 2, &encoded);
215                message(&mut body, 1, &field);
216            }
217            message(out, 9, &body);
218        }
219        Projected::Blob {
220            hash,
221            size,
222            media_type,
223            tainted,
224        } => {
225            let mut body = Vec::new();
226            bytes(&mut body, 1, hash);
227            uint(&mut body, 2, *size);
228            string(&mut body, 3, media_type);
229            boolean(&mut body, 4, *tainted);
230            message(out, 10, &body);
231        }
232        Projected::Env(name) => {
233            let mut body = Vec::new();
234            string(&mut body, 1, name);
235            message(out, 11, &body);
236        }
237        Projected::Expr(kind) => {
238            let mut body = Vec::new();
239            string(&mut body, 1, kind);
240            message(out, 12, &body);
241        }
242    }
243}
244
245// ---------------------------------------------------------------------------
246// module
247// ---------------------------------------------------------------------------
248
249/// Project `module` into protobuf wire format.
250///
251/// The result is deterministic and redacted. The `content_hash` field is the
252/// Blake3-256 of the canonical AINF image, so a consumer can request or verify
253/// the authoritative bytes with [`crate::validate`] and the usual content
254/// addressing.
255///
256/// The projection is built from the *canonical* module (the decode of its own
257/// encoded image), so two logically equal modules — which share their AINF
258/// bytes and hash — also share their projection bytes. Bindings, annotations and
259/// extensions therefore come out in canonical order.
260///
261/// A module that cannot be encoded canonically (a cycle, a dangling reference,
262/// a duplicate binding) is refused instead of being projected approximately, and
263/// so is a module whose opaque extension payload contains a copy of a secret
264/// literal: that copy would otherwise leave through the projection.
265pub fn to_protobuf(module: &InfinityModule) -> Result<Vec<u8>> {
266    let image = encode(module)?;
267    let hash = hash_image(&image)?;
268    let canonical = crate::decode::decode(&image)?;
269    let module = &canonical;
270    let secrets = secret_table(module);
271
272    let mut out = Vec::new();
273    bytes(&mut out, 1, &hash);
274    uint(&mut out, 2, image.len() as u64);
275
276    if let Some(root) = module.root() {
277        let value = project_node_with(module, root, &secrets)?;
278        let mut body = Vec::new();
279        encode_value(&value, &mut body);
280        message(&mut out, 3, &body);
281    }
282
283    for (name, id) in module.bindings() {
284        let value = project_node_with(module, *id, &secrets)?;
285        let mut binding = Vec::new();
286        string(&mut binding, 1, &redacted_key(name, &secrets));
287        let mut encoded = Vec::new();
288        encode_value(&value, &mut encoded);
289        message(&mut binding, 2, &encoded);
290        message(&mut out, 4, &binding);
291    }
292
293    if let Some(prov) = module.provenance() {
294        message(&mut out, 5, &encode_provenance(prov, &secrets));
295    }
296
297    for annotation in module.annotations() {
298        message(&mut out, 6, &encode_annotation(annotation, &secrets));
299    }
300
301    for (tag, payload) in module.extensions() {
302        if carries_secret(payload, &secrets) {
303            return Err(Error::Encode(
304                "extension payload carries secret material; a projection must not copy it",
305            ));
306        }
307        let mut extension = Vec::new();
308        uint(&mut extension, 1, *tag);
309        bytes(&mut extension, 2, payload);
310        message(&mut out, 7, &extension);
311    }
312
313    Ok(out)
314}
315
316/// Whether an opaque payload contains a secret literal.
317fn carries_secret(payload: &[u8], secrets: &[String]) -> bool {
318    secrets.iter().any(|secret| {
319        let bytes = secret.as_bytes();
320        !bytes.is_empty()
321            && bytes.len() <= payload.len()
322            && payload.windows(bytes.len()).any(|window| window == bytes)
323    })
324}
325
326fn encode_annotation(annotation: &crate::ir::Annotation, secrets: &[String]) -> Vec<u8> {
327    let mut body = Vec::new();
328    uint(&mut body, 1, annotation.node.index() as u64);
329    match &annotation.kind {
330        AnnotationKind::Intent(text) => string(&mut body, 2, &redacted_value(text, secrets)),
331        AnnotationKind::Constraint { source, expr } => {
332            let mut constraint = Vec::new();
333            string(&mut constraint, 1, &redacted_value(source, secrets));
334            uint(&mut constraint, 2, expr.index() as u64);
335            message(&mut body, 3, &constraint);
336        }
337        AnnotationKind::AiImmutable(flag) => boolean(&mut body, 4, *flag),
338    }
339    body
340}
341
342fn encode_provenance(prov: &crate::ir::Provenance, secrets: &[String]) -> Vec<u8> {
343    let mut body = Vec::new();
344    string(
345        &mut body,
346        1,
347        &redacted_value(prov.producer.as_deref().unwrap_or(""), secrets),
348    );
349    uint(&mut body, 2, prov.timestamp_ms);
350    string(
351        &mut body,
352        3,
353        &redacted_value(prov.model.as_deref().unwrap_or(""), secrets),
354    );
355    string(
356        &mut body,
357        4,
358        &redacted_value(prov.tool.as_deref().unwrap_or(""), secrets),
359    );
360    if let Some(parent) = &prov.parent {
361        bytes(&mut body, 5, parent);
362    }
363    for entry in &prov.entries {
364        let mut encoded = Vec::new();
365        string(&mut encoded, 1, &redacted_key(&entry.key, secrets));
366        match &entry.value {
367            ProvValue::Text(text) => string(&mut encoded, 2, &redacted_value(text, secrets)),
368            ProvValue::Int(number) => sint(&mut encoded, 3, *number),
369            ProvValue::Flag(flag) => boolean(&mut encoded, 4, *flag),
370            ProvValue::Hash(hash) => bytes(&mut encoded, 5, hash),
371        }
372        message(&mut body, 6, &encoded);
373    }
374    body
375}