rustev-contract 0.3.0

Rustev's versioned wire contract: documents, bounded parsing, canonical form and identities.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Authored screening and its plan bindings (spec 035, 3.4 and 3.5.8).
//! Only document-local shape is checked here; compilation owns semantic checks.
use serde::{Deserialize, Serialize};

use crate::actionability::Address;
use crate::ids::{ArtifactId, DescriptorId};

/// The canonical definition screening block.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Screening {
    #[serde(deserialize_with = "positive")]
    #[schemars(range(min = 1))]
    pub max_text_units: u64,
    #[serde(deserialize_with = "bounded_list")]
    #[schemars(length(min = 1, max = 32))]
    pub entries: Vec<ScreeningEntry>,
}

/// An authored entry. Every member is required, including explicit policies.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreeningEntry {
    #[serde(deserialize_with = "name")]
    pub id: String,
    #[serde(deserialize_with = "fields")]
    #[schemars(length(min = 1, max = 32))]
    pub fields: Vec<String>,
    pub item_id: ScreeningItemId,
    #[serde(deserialize_with = "name")]
    pub screener: String,
    pub on_block: OnBlock,
    #[serde(deserialize_with = "address")]
    pub address: Address,
    pub on_unavailable: OnUnavailable,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ScreeningItemId {
    None,
    // Variant-level `untagged` (serde 1.0.181 and later): `"none"` or the
    // bare `{"field": ...}` object, as 3.4.1 writes it; the wire tests
    // round-trip both forms byte for byte.
    #[serde(untagged)]
    Field(ScreeningItemField),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreeningItemField {
    #[serde(deserialize_with = "name")]
    pub field: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnBlock {
    Refuse,
    DropField,
    DropText,
    DropItem,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnUnavailable {
    FailClosed,
    SkipGeneration,
    FailOpen,
}

/// Plan 3 retains the canonical block and each lowered step's binding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlanScreening {
    pub screening: Screening,
    #[serde(deserialize_with = "nonempty_steps")]
    #[schemars(length(min = 1))]
    pub steps: Vec<ScreeningStep>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreeningStep {
    #[serde(deserialize_with = "nonempty")]
    pub step: String,
    #[serde(deserialize_with = "name")]
    pub entry: String,
    #[serde(deserialize_with = "field_reference")]
    pub field: String,
    pub binding: ScreenerBinding,
    pub consequence: OnBlock,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenerBinding {
    #[serde(deserialize_with = "name")]
    pub backend_id: String,
    pub artifact: ArtifactId,
    pub descriptor: DescriptorId,
}

// Optional members may be absent, never explicitly null (descriptor precedent).
pub(crate) fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    deserializer: D,
) -> Result<Option<T>, D::Error> {
    T::deserialize(deserializer).map(Some)
}

fn positive<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
    let n = u64::deserialize(d)?;
    if n == 0 {
        return Err(serde::de::Error::custom("max_text_units must be positive"));
    }
    Ok(n)
}

fn bounded_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    d: D,
) -> Result<Vec<T>, D::Error> {
    let values = Vec::<T>::deserialize(d)?;
    if !(1..=32).contains(&values.len()) {
        return Err(serde::de::Error::custom("expected 1 to 32 elements"));
    }
    Ok(values)
}

// The authored name rule used by core's structure check (spec 002).
fn valid_name(s: &str) -> bool {
    !s.is_empty() && !s.contains(':') && !s.chars().any(char::is_whitespace)
}

fn name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    let s = String::deserialize(d)?;
    if !valid_name(&s) {
        return Err(serde::de::Error::custom("invalid screening name"));
    }
    Ok(s)
}

fn reference(s: &str) -> bool {
    let Some(path) = s.strip_prefix("input:") else {
        return false;
    };
    let (input, field) = match path.split_once('/') {
        Some((input, field)) => (input.strip_suffix("[]").unwrap_or(input), Some(field)),
        None => (path, None),
    };
    let component = |s: &str| valid_name(s) && !s.contains(['/', '[', ']']);
    component(input) && field.is_none_or(component)
}

fn fields<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
    let values: Vec<String> = bounded_list(d)?;
    if !values.iter().all(|s| reference(s)) {
        return Err(serde::de::Error::custom(
            "invalid screening field reference",
        ));
    }
    Ok(values)
}

fn address<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Address, D::Error> {
    let value = Address::deserialize(d)?;
    // An override naming `caller` parses: compilation refuses it as spec
    // 033's `caller_cannot_act` (category 17, spec 035 3.5.7).
    if let Address::Override(a) = &value
        && a.reason.is_empty()
    {
        return Err(serde::de::Error::custom(
            "invalid screening address override",
        ));
    }
    Ok(value)
}

fn nonempty_steps<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<ScreeningStep>, D::Error> {
    let steps = Vec::<ScreeningStep>::deserialize(d)?;
    if steps.is_empty() {
        return Err(serde::de::Error::custom("screening steps must be nonempty"));
    }
    Ok(steps)
}

fn nonempty<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    let s = String::deserialize(d)?;
    if s.is_empty() {
        return Err(serde::de::Error::custom(
            "screening string must be nonempty",
        ));
    }
    Ok(s)
}

fn optional_nonempty<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
    let s = Option::<String>::deserialize(d)?;
    if s.as_ref().is_some_and(String::is_empty) {
        return Err(serde::de::Error::custom(
            "screening string must be nonempty",
        ));
    }
    Ok(s)
}

fn field_reference<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    let s = String::deserialize(d)?;
    if !reference(&s) {
        return Err(serde::de::Error::custom(
            "invalid screening field reference",
        ));
    }
    Ok(s)
}

/// The domain of a digest of screened UTF-8 bytes (spec 035, 3.13.1).
pub const SCREEN_TEXT_TAG: &str = "rustev.screen-text/1";

pub fn screen_text_digest(text: &str) -> crate::ids::ContentDigest {
    crate::ids::ContentDigest::from_digest(crate::canonical::tagged_digest(
        SCREEN_TEXT_TAG,
        text.as_bytes(),
    ))
}

/// Projection members are JSON values, not a contract value enum.
pub fn withheld_screen_blocked() -> serde_json::Value {
    serde_json::json!({"withheld": "screen_blocked"})
}

/// Details of a screening notice. Never includes screened text.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct ScreeningNotice {
    #[serde(deserialize_with = "name")]
    pub entry: String,
    #[serde(deserialize_with = "field_reference")]
    pub field: String,
    pub consequence: ScreenConsequence,
    pub items: Vec<String>,
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ScreenConsequence {
    None,
    Refuse,
    DropField,
    DropText,
    DropItem,
    FailClosed,
    SkipGeneration,
    FailOpen,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum ScreenVerdict {
    Pass,
    Blocked,
    Unavailable { reason: crate::judgment::Unresolved },
    Empty,
}

/// One screened value's evidence, in lowered-step and item order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreeningEvidence {
    #[serde(deserialize_with = "name")]
    pub entry: String,
    #[serde(deserialize_with = "evidence_field_reference")]
    pub field: String,
    /// Null means this field is not a list item.
    #[serde(default, deserialize_with = "optional_nonempty")]
    pub item: Option<String>,
    pub text_digest: crate::ids::ContentDigest,
    pub verdict: ScreenVerdict,
    pub categories: Vec<String>,
    pub consequence: ScreenConsequence,
    #[serde(deserialize_with = "name")]
    pub backend_id: String,
    pub artifact: ArtifactId,
    pub descriptor: DescriptorId,
    #[serde(deserialize_with = "nonempty")]
    pub step: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenRequest {
    pub cache: ScreenCache,
    pub units: ScreenChargedUnits,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum ScreenCache {
    Hit {
        #[serde(deserialize_with = "nonempty")]
        source_attempt: String,
    },
    Miss,
    Disabled,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenChargedUnits {
    /// Sum of computed bounds for dispatched attempts. Absent when no
    /// attempt was dispatched (including cache hits and withdrawal).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "present"
    )]
    #[schemars(with = "u64")]
    pub computed: Option<u64>,
    /// Sum of reported units, when any attempt reported units. Charges for
    /// attempts without a report still use their computed bound.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "present"
    )]
    #[schemars(with = "u64")]
    pub reported: Option<u64>,
    pub charged: u64,
    pub basis: ScreenUnitBasis,
    /// Present only for a reported charge above its computed bound.
    /// Mirrors the cost ledger's bound-violation observation (3.12.3).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "present"
    )]
    #[schemars(with = "ScreenUnitBoundViolation")]
    pub bound_violation: Option<ScreenUnitBoundViolation>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ScreenUnitBasis {
    Reported,
    Computed,
    CacheHit,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScreenUnitBoundViolation {
    pub computed: u64,
    pub reported: u64,
}

impl<'de> Deserialize<'de> for ScreenUnitBoundViolation {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            computed: u64,
            reported: u64,
        }

        let wire = Wire::deserialize(d)?;
        if wire.reported <= wire.computed {
            return Err(serde::de::Error::custom(
                "reported screening units must exceed the computed bound",
            ));
        }
        Ok(Self {
            computed: wire.computed,
            reported: wire.reported,
        })
    }
}

pub(crate) fn unavailable_fields<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Vec<String>, D::Error> {
    let fields = Vec::<String>::deserialize(d)?;
    if fields.is_empty()
        || !fields.iter().all(|s| reference(s))
        || fields
            .windows(2)
            .any(|w| w[0].as_bytes() >= w[1].as_bytes())
    {
        return Err(serde::de::Error::custom(
            "screen_unavailable fields must be nonempty, valid, sorted and unique",
        ));
    }
    Ok(fields)
}

pub(crate) fn evidence_list<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<Vec<ScreeningEvidence>>, D::Error> {
    let entries = Vec::<ScreeningEvidence>::deserialize(d)?;
    if entries.is_empty() {
        return Err(serde::de::Error::custom(
            "screening evidence must be nonempty",
        ));
    }
    Ok(Some(entries))
}

fn evidence_field_reference<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    let s = String::deserialize(d)?;
    let output = s
        .strip_prefix("output:")
        .and_then(|p| p.split_once('/'))
        .is_some_and(|(step, field)| valid_name(step) && valid_name(field));
    if reference(&s) || output {
        Ok(s)
    } else {
        Err(serde::de::Error::custom("invalid screening evidence field"))
    }
}