Skip to main content

qualia_core_db/bundle/stream/policy/remote/
policy.rs

1//! Versioned whole-source disclosure policy artifact counted in the closure budget.
2use super::PolicyError as E;
3use crate::crypto::network::digest::sha384;
4use crate::crypto::network::object_stream::MAX_OBJECT_BYTES;
5use crate::net::qdnf::types::{OperationId, StrongDigest};
6use crate::semantic_instruments::resolve::bounded_closure::{
7    ClosureCandidate, MAX_CLOSURE_EDGES, MAX_CLOSURE_NODES, MAX_CLOSURE_ORIGINAL_BYTES,
8};
9
10const MAGIC: &[u8] = b"QBDL-WSD-POL-V1\0";
11const VERSION: u8 = 1;
12const FIXED: usize = MAGIC.len() + 1 + 1 + 48 + 8 + 48 + 48 + 48 + 1 + 48 + 48 + 16 + 48 + 48 + 48;
13pub const MAX_DISCLOSURE_POLICY_BYTES: usize = FIXED + 16 * 48;
14pub const MAX_CLOSURE_LABELS: usize = 16;
15
16/// Whole-source coverage bits. This profile admits only the complete set.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct SourceCoverage(u8);
19
20impl SourceCoverage {
21    pub const HEADER: u8 = 1;
22    pub const INDEX: u8 = 2;
23    pub const GAPS: u8 = 4;
24    pub const ENTRIES: u8 = 8;
25    pub const WHOLE: Self = Self(Self::HEADER | Self::INDEX | Self::GAPS | Self::ENTRIES);
26
27    pub const fn from_bits(bits: u8) -> Self {
28        Self(bits)
29    }
30
31    pub const fn bits(self) -> u8 {
32        self.0
33    }
34
35    pub const fn is_whole(self) -> bool {
36        self.0 == Self::WHOLE.0
37    }
38
39    fn admit(self) -> Result<Self, E> {
40        if self.is_whole() {
41            Ok(self)
42        } else {
43            Err(E::Graph)
44        }
45    }
46}
47
48/// Already-counted closure occupancy. Policy bytes/nodes charge this budget.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct ClosureBudget {
51    pub original_bytes: usize,
52    pub nodes: usize,
53    pub edges: usize,
54}
55
56impl ClosureBudget {
57    pub fn from_candidate(candidate: &ClosureCandidate<'_, '_>) -> Self {
58        Self {
59            original_bytes: candidate.original_byte_count(),
60            nodes: candidate.nodes().len(),
61            edges: candidate.edges().len(),
62        }
63    }
64
65    pub fn charge(self, artifact_len: usize) -> Result<Self, E> {
66        if artifact_len == 0 || artifact_len > MAX_DISCLOSURE_POLICY_BYTES {
67            return Err(E::Limit);
68        }
69        let nodes = self.nodes.checked_add(1).ok_or(E::Limit)?;
70        let original_bytes = self
71            .original_bytes
72            .checked_add(artifact_len)
73            .ok_or(E::Limit)?;
74        if nodes > MAX_CLOSURE_NODES
75            || self.edges > MAX_CLOSURE_EDGES
76            || original_bytes > MAX_CLOSURE_ORIGINAL_BYTES
77        {
78            return Err(E::Limit);
79        }
80        Ok(Self {
81            original_bytes,
82            nodes,
83            edges: self.edges,
84        })
85    }
86
87    pub fn admit_counted(&self) -> Result<(), E> {
88        if self.nodes == 0
89            || self.nodes > MAX_CLOSURE_NODES
90            || self.edges > MAX_CLOSURE_EDGES
91            || self.original_bytes > MAX_CLOSURE_ORIGINAL_BYTES
92        {
93            return Err(E::Limit);
94        }
95        Ok(())
96    }
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub struct DisclosurePolicyFields {
101    pub coverage: SourceCoverage,
102    pub source: StrongDigest,
103    pub source_length: u64,
104    pub controller: StrongDigest,
105    pub publisher: StrongDigest,
106    pub source_label: StrongDigest,
107    pub closure_labels: [StrongDigest; MAX_CLOSURE_LABELS],
108    pub closure_label_count: u8,
109    pub recipient: StrongDigest,
110    pub purpose: StrongDigest,
111    pub operation: OperationId,
112    pub consumer: StrongDigest,
113    pub rule: StrongDigest,
114    pub graph: StrongDigest,
115}
116
117#[derive(Clone, Copy, Debug)]
118pub struct DisclosurePolicyView<'a> {
119    encoded: &'a [u8],
120    fields: DisclosurePolicyFields,
121}
122
123impl<'a> DisclosurePolicyView<'a> {
124    pub const fn fields(&self) -> DisclosurePolicyFields {
125        self.fields
126    }
127    pub const fn encoded_bytes(&self) -> &'a [u8] {
128        self.encoded
129    }
130    pub fn digest(&self) -> StrongDigest {
131        sha384(self.encoded)
132    }
133}
134
135pub fn encode_disclosure_policy_into(
136    fields: DisclosurePolicyFields,
137    budget: ClosureBudget,
138    out: &mut [u8],
139) -> Result<usize, E> {
140    fields_valid(fields)?;
141    let n = FIXED + fields.closure_label_count as usize * 48;
142    budget.charge(n)?;
143    let out = out.get_mut(..n).ok_or(E::Capacity)?;
144    let mut pos = 0;
145    put(out, &mut pos, MAGIC);
146    put(out, &mut pos, &[VERSION, fields.coverage.bits()]);
147    put(out, &mut pos, &fields.source.0);
148    put(out, &mut pos, &fields.source_length.to_be_bytes());
149    for d in [fields.controller, fields.publisher, fields.source_label] {
150        put(out, &mut pos, &d.0);
151    }
152    put(out, &mut pos, &[fields.closure_label_count]);
153    for i in 0..fields.closure_label_count as usize {
154        put(out, &mut pos, &fields.closure_labels[i].0);
155    }
156    for d in [fields.recipient, fields.purpose] {
157        put(out, &mut pos, &d.0);
158    }
159    put(out, &mut pos, &fields.operation.0);
160    for d in [fields.consumer, fields.rule, fields.graph] {
161        put(out, &mut pos, &d.0);
162    }
163    debug_assert_eq!(pos, n);
164    Ok(n)
165}
166
167pub fn decode_disclosure_policy(bytes: &[u8]) -> Result<DisclosurePolicyView<'_>, E> {
168    if bytes.len() > MAX_DISCLOSURE_POLICY_BYTES {
169        return Err(E::Limit);
170    }
171    if bytes.len() < FIXED || !bytes.starts_with(MAGIC) {
172        return Err(E::Encoding);
173    }
174    let mut pos = MAGIC.len();
175    if bytes[pos] != VERSION {
176        return Err(E::Encoding);
177    }
178    pos += 1;
179    let coverage = SourceCoverage::from_bits(bytes[pos]).admit()?;
180    pos += 1;
181    let source = digest(&bytes[pos..pos + 48]);
182    pos += 48;
183    let source_length = u64::from_be_bytes(bytes[pos..pos + 8].try_into().unwrap());
184    pos += 8;
185    let controller = digest(&bytes[pos..pos + 48]);
186    pos += 48;
187    let publisher = digest(&bytes[pos..pos + 48]);
188    pos += 48;
189    let source_label = digest(&bytes[pos..pos + 48]);
190    pos += 48;
191    let label_count = bytes[pos] as usize;
192    pos += 1;
193    if label_count > MAX_CLOSURE_LABELS {
194        return Err(E::Limit);
195    }
196    if bytes.len() != FIXED + label_count * 48 {
197        return Err(E::Encoding);
198    }
199    let mut closure_labels = [StrongDigest::ZERO; MAX_CLOSURE_LABELS];
200    for i in 0..label_count {
201        closure_labels[i] = digest(&bytes[pos..pos + 48]);
202        pos += 48;
203    }
204    let recipient = digest(&bytes[pos..pos + 48]);
205    pos += 48;
206    let purpose = digest(&bytes[pos..pos + 48]);
207    pos += 48;
208    let operation = OperationId(bytes[pos..pos + 16].try_into().unwrap());
209    pos += 16;
210    let consumer = digest(&bytes[pos..pos + 48]);
211    pos += 48;
212    let rule = digest(&bytes[pos..pos + 48]);
213    pos += 48;
214    let graph = digest(&bytes[pos..pos + 48]);
215    let fields = DisclosurePolicyFields {
216        coverage,
217        source,
218        source_length,
219        controller,
220        publisher,
221        source_label,
222        closure_labels,
223        closure_label_count: label_count as u8,
224        recipient,
225        purpose,
226        operation,
227        consumer,
228        rule,
229        graph,
230    };
231    fields_valid(fields)?;
232    Ok(DisclosurePolicyView {
233        encoded: bytes,
234        fields,
235    })
236}
237
238/// Policy original must already be a counted closure node inside existing limits.
239pub fn bind_policy_to_closure<'a>(
240    encoded: &'a [u8],
241    candidate: &ClosureCandidate<'_, 'a>,
242) -> Result<DisclosurePolicyView<'a>, E> {
243    let view = decode_disclosure_policy(encoded)?;
244    ClosureBudget::from_candidate(candidate).admit_counted()?;
245    let digest = view.digest();
246    let node = candidate
247        .nodes()
248        .iter()
249        .find(|n| n.digest == digest)
250        .ok_or(E::Graph)?;
251    if node.original_bytes != encoded {
252        return Err(E::Graph);
253    }
254    Ok(view)
255}
256
257fn fields_valid(f: DisclosurePolicyFields) -> Result<(), E> {
258    f.coverage.admit()?;
259    if f.source_length < 64 || f.source_length > MAX_OBJECT_BYTES {
260        return Err(E::Reference);
261    }
262    if f.closure_label_count as usize > MAX_CLOSURE_LABELS {
263        return Err(E::Limit);
264    }
265    for d in [
266        f.source,
267        f.controller,
268        f.publisher,
269        f.source_label,
270        f.recipient,
271        f.purpose,
272        f.consumer,
273        f.rule,
274        f.graph,
275    ] {
276        if d.is_zero() {
277            return Err(E::Reference);
278        }
279    }
280    if f.operation.is_zero() {
281        return Err(E::Reference);
282    }
283    let n = f.closure_label_count as usize;
284    for i in 0..n {
285        if f.closure_labels[i].is_zero() {
286            return Err(E::Reference);
287        }
288        if i != 0 && f.closure_labels[i - 1].0 >= f.closure_labels[i].0 {
289            return Err(E::Encoding);
290        }
291    }
292    for i in n..MAX_CLOSURE_LABELS {
293        if !f.closure_labels[i].is_zero() {
294            return Err(E::Encoding);
295        }
296    }
297    Ok(())
298}
299
300fn digest(bytes: &[u8]) -> StrongDigest {
301    StrongDigest(bytes.try_into().expect("validated fixed-width digest"))
302}
303
304fn put(out: &mut [u8], pos: &mut usize, bytes: &[u8]) {
305    out[*pos..*pos + bytes.len()].copy_from_slice(bytes);
306    *pos += bytes.len();
307}