rustev-contract 0.4.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Provenance-conditional checks and actionable outcomes (spec 033): the
//! definition 2 `actionability` member and the wire types of judgment 2's
//! actions, causes, remediations and questions.
//!
//! Who can act on an outcome is computed from its causes; an author may move
//! it away from the caller, never toward it (spec 033, I-2). Nothing here is
//! a permission: `addressed_to` and a remediation say who can act and how,
//! and a caller-addressed outcome authorizes nothing (spec 001, 3.2).

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::decimal::Decimal;
use crate::definition::{ParamSource, Predicate, ProvenanceClass, TypeDecl};
use crate::grade::Grade;
use crate::ids::ContentDigest;
use crate::time::{DurationMs, Timestamp};

/// The definition 2 member (spec 033, 3.1.1). Each list may be empty.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Actionability {
    /// Sorted, duplicate-free; only `user-supplied`,
    /// `authenticated-app-field` and `attributed-claim` (3.2.1).
    pub caller_controlled: Vec<ProvenanceClass>,
    pub remediations: Vec<RemediationDecl>,
    pub questions: Vec<QuestionDecl>,
    pub constraint_groups: Vec<ConstraintGroup>,
    pub checks: Vec<CheckDecl>,
}

/// Who can act on an outcome (3.5.2), ordered from most to least able to
/// act on it themselves: the combination of parties is the greatest.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Party {
    None,
    Caller,
    Host,
    Upstream,
}

impl Party {
    /// The combination of 3.5.2: `upstream` over `host` over `caller` over
    /// `none`.
    pub fn combine<I: IntoIterator<Item = Party>>(parties: I) -> Party {
        parties.into_iter().max().unwrap_or(Party::None)
    }
}

/// A declared remediation (3.6.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RemediationDecl {
    /// `[a-z][a-z0-9_]{0,63}`; never a built-in code.
    pub code: String,
    /// `caller`, `host` or `upstream`.
    #[serde(rename = "for")]
    pub for_party: Party,
    pub params: Vec<RemediationParam>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RemediationParam {
    pub name: String,
    /// A scalar type of spec 002, 3.7.2.
    #[serde(rename = "type")]
    pub ty: TypeDecl,
}

/// A declared, literal question template (3.7.3).
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct QuestionDecl {
    pub id: String,
    /// A non-empty subset of the outcome's fields.
    pub fields: Vec<String>,
    /// 1 to 1024 bytes of UTF-8, carried byte-identical; no interpolation.
    pub text: String,
}

/// A named group of checks a `relax` consequence switches off (3.3.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ConstraintGroup {
    pub name: String,
    /// Non-empty check ids.
    pub checks: Vec<String>,
}

/// A provenance-conditional check (3.2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CheckDecl {
    pub id: String,
    /// The declared input whose provenance the check branches on.
    pub subject: String,
    /// A `bool` predicate over inputs, `now` and literals.
    pub test: Predicate,
    pub on_fail: OnFail,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OnFail {
    pub by_provenance: BTreeMap<ProvenanceClass, Consequence>,
    pub default: DefaultConsequence,
}

/// A check's `default`: the string `none`, or a consequence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DefaultConsequence {
    None,
    #[serde(untagged)]
    Consequence(Consequence),
}

/// What a failed check does (3.3). `refuse`, `abstain` and `escalate` are
/// terminal; the others are field-level.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Consequence {
    Refuse {
        remediation: RemediationUse,
        #[serde(default, skip_serializing_if = "Address::is_computed")]
        address: Address,
    },
    DropField {
        notice: String,
        #[serde(default, skip_serializing_if = "Address::is_computed")]
        address: Address,
    },
    Relax {
        group: String,
        notice: String,
        #[serde(default, skip_serializing_if = "Address::is_computed")]
        address: Address,
    },
    DowngradeGrade {
        /// Below `authoritative`.
        to: Grade,
        notice: String,
        #[serde(default, skip_serializing_if = "Address::is_computed")]
        address: Address,
    },
    Abstain,
    Escalate {
        reason: String,
    },
    ContinueWithNotice {
        notice: String,
        #[serde(default, skip_serializing_if = "Address::is_computed")]
        address: Address,
    },
}

impl Consequence {
    /// `refuse`, `abstain` and `escalate` (3.3).
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Consequence::Refuse { .. } | Consequence::Abstain | Consequence::Escalate { .. }
        )
    }

    /// The kind as `plan show` prints it.
    pub fn kind(&self) -> &'static str {
        match self {
            Consequence::Refuse { .. } => "refuse",
            Consequence::DropField { .. } => "drop_field",
            Consequence::Relax { .. } => "relax",
            Consequence::DowngradeGrade { .. } => "downgrade_grade",
            Consequence::Abstain => "abstain",
            Consequence::Escalate { .. } => "escalate",
            Consequence::ContinueWithNotice { .. } => "continue_with_notice",
        }
    }
}

/// Where an outcome is addressed: computed from its causes (when omitted),
/// or an override toward a party less able to act (3.5.3).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Address {
    #[default]
    Computed,
    #[serde(untagged)]
    Override(AddressOverride),
}

impl Address {
    pub fn is_computed(&self) -> bool {
        matches!(self, Address::Computed)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AddressOverride {
    /// `host`, `upstream` or `none`; never `caller`.
    pub to: Party,
    /// `[a-z][a-z0-9_]{0,63}`.
    pub reason: String,
}

/// A use of a declared or built-in remediation: its code alone, or its
/// code with parameters (3.6.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum RemediationUse {
    Code(String),
    WithParams(RemediationCall),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RemediationCall {
    pub code: String,
    pub params: BTreeMap<String, ParamSource>,
}

impl RemediationUse {
    pub fn code(&self) -> &str {
        match self {
            RemediationUse::Code(c) => c,
            RemediationUse::WithParams(c) => &c.code,
        }
    }
}

/// Built-in remediation codes, never redeclared (3.6.2).
pub const BUILTIN_REMEDIATIONS: &[&str] = &[
    "provide_fields",
    "refresh_fields",
    "correct_fields",
    "resolve_conflict",
    "improve_evidence",
    "retry",
    "report_backend",
    "raise_budget",
    "provide_capability",
    "retry_after",
];

/// A scalar or list value in a remediation's parameters: the subset of
/// `OutValue` (spec 002) a remediation can carry, in the same wire form.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum RemediationValue {
    Bool(bool),
    Integer(i64),
    Decimal(Decimal),
    Text(String),
    Enum(String),
    Timestamp(Timestamp),
    Duration(DurationMs),
    List(Vec<RemediationValue>),
}

/// A remediation as an action carries it: `none`, or a code and its
/// canonical parameters (3.6.1).
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Remediation {
    None,
    #[serde(untagged)]
    Some {
        code: String,
        params: BTreeMap<String, RemediationValue>,
    },
}

impl Remediation {
    pub fn code(code: &str) -> Remediation {
        Remediation::Some {
            code: code.into(),
            params: BTreeMap::new(),
        }
    }

    pub fn with(
        code: &str,
        params: impl IntoIterator<Item = (String, RemediationValue)>,
    ) -> Remediation {
        Remediation::Some {
            code: code.into(),
            params: params.into_iter().collect(),
        }
    }

    /// A `fields`-style list parameter of text values.
    pub fn texts<I: IntoIterator<Item = String>>(items: I) -> RemediationValue {
        RemediationValue::List(items.into_iter().map(RemediationValue::Text).collect())
    }
}

/// The provenance an input cause records (3.5.2).
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum CauseProvenance {
    /// An accepted entry existed (including a dropped or invalid one).
    Observed { class: ProvenanceClass },
    /// No entry did: the classes the input accepts.
    Accepted { classes: Vec<ProvenanceClass> },
}

/// Who registered a backend (3.9): `upstream` unless the host implements it.
#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
    #[default]
    Upstream,
    Host,
}

/// One cause of an outcome or notice (3.5.2).
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Cause {
    Input {
        field: String,
        provenance: CauseProvenance,
    },
    Backend {
        step: String,
        origin: Origin,
    },
    Budget {
        resource: String,
    },
    Deadline,
    Capability {
        name: String,
    },
    /// `check:<id>`, `rule:<id>` or `handler:<n>`.
    Policy {
        site: String,
    },
    #[serde(untagged)]
    CapabilityStep {
        capability: CapabilityStep,
    },
}

/// A fallback field identifies the extraction step (spec 038, 3.12.3).
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct CapabilityStep {
    pub step: String,
}

/// How an override came about (3.5.2).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum OverrideBasis {
    Declared,
    Remediation,
}

/// `none`, or the party an author moved the outcome to and why.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Override {
    None,
    #[serde(untagged)]
    Applied {
        to: Party,
        basis: OverrideBasis,
        reason: String,
    },
}

/// Who can act on an outcome or notice, how, why, and whether retrying the
/// same request can succeed (3.5.2). Every member is always written.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct Action {
    pub addressed_to: Party,
    pub computed: Party,
    #[serde(rename = "override")]
    pub override_: Override,
    pub remediation: Remediation,
    /// Duplicate-free, sorted by each cause's canonical JSON bytes.
    pub caused_by: Vec<Cause>,
    pub transient: bool,
}

/// One refusing check of a `refused` outcome (3.5.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Refusal {
    pub check: String,
    pub subject: String,
    pub action: Action,
}

/// A question as a `needs_input` outcome carries it: the declared template,
/// byte-identical (3.7.3).
pub type Question = QuestionDecl;

/// The `needs_input` outcome (3.7).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NeedsInput {
    pub fields: Vec<String>,
    pub questions: Vec<Question>,
    /// `tagged_digest("rustev.continuation/1", ...)` (3.7.4).
    pub continuation: ContentDigest,
    pub action: Action,
}

/// The canonical inputs of a continuation digest (3.7.4), in field order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ContinuationInputs<'a> {
    pub plan_id: &'a str,
    pub snapshot_id: &'a str,
    pub evaluation_time_ms: i64,
    pub site: &'a str,
    pub fields: &'a [String],
    pub questions: &'a [String],
}

/// The tag of a continuation digest.
pub const CONTINUATION_TAG: &str = "rustev.continuation/1";

/// A check's status in evidence 2 (3.4.8).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum CheckStatus {
    Passed,
    Failed {
        class: ProvenanceClass,
        /// The consequence kind applied.
        consequence: String,
    },
    NotEvaluated {
        reason: crate::judgment::Unresolved,
    },
    Unevaluable {
        reason: crate::judgment::Unresolved,
    },
    Relaxed {
        by: String,
    },
}

/// One check's evidence record (3.4.8).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CheckRecord {
    pub check: String,
    pub subject: String,
    pub status: CheckStatus,
}

/// The plan 3 member: the static causes and party of every check branch
/// and policy site (3.8.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlanActionability {
    pub checks: Vec<StaticCheck>,
    pub sites: Vec<StaticSite>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StaticCheck {
    pub check: String,
    pub subject: String,
    /// One per `by_provenance` key, then the `default` (when not `none`)
    /// with every class it covers.
    pub branches: Vec<StaticBranch>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StaticBranch {
    pub classes: Vec<ProvenanceClass>,
    pub consequence: String,
    pub causes: Vec<Cause>,
    pub party: Party,
}

/// A policy site that can produce an action (`rule:<id>`, `handler:<n>`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StaticSite {
    pub site: String,
    pub causes: Vec<Cause>,
    pub party: Party,
}

/// The classes a host may declare caller-controlled (3.2.1).
pub const CALLER_CONTROLLABLE: [ProvenanceClass; 3] = [
    ProvenanceClass::UserSupplied,
    ProvenanceClass::AuthenticatedAppField,
    ProvenanceClass::AttributedClaim,
];

/// A code of `[a-z][a-z0-9_]{0,63}` (3.3.1, 3.5.3, 3.6.1).
pub fn is_code(s: &str) -> bool {
    let b = s.as_bytes();
    !b.is_empty()
        && b.len() <= 64
        && b[0].is_ascii_lowercase()
        && b.iter()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_')
}