Skip to main content

sail_api/
attribution.rs

1//! Submitter-supplied requirement attribution for ordinary Verus project jobs.
2//!
3//! An ordinary job proves the submitted Verus source against its own
4//! specifications. A submitter may name requirement identities for exact
5//! functions when submitting the job; this view reports, per requirement, what
6//! the retained job evidence establishes for each attributed function. The
7//! attribution itself is a submitter claim: Sail never checks that a function's
8//! specification states the requirement, and this view is never neutral-contract
9//! assurance (see [`crate::assurance`]). Reading a view never runs a verifier.
10
11use serde::{Deserialize, Serialize};
12use std::collections::BTreeMap;
13
14use crate::assurance::{EvidenceTier, MutationStatus, ProofState};
15use crate::jobs::{Currentness, Lifecycle, Mode, ResultDocument};
16use crate::output::{EstablishmentName, SolverInfo};
17use crate::project::ProjectResult;
18
19/// Attributed assurance view contract version.
20pub const VERSION: u32 = 1;
21/// Most attributions one job may carry.
22pub const MAX_ATTRIBUTIONS: usize = 4096;
23/// Longest requirement identity or function name, in bytes.
24pub const MAX_NAME: usize = 1024;
25
26/// One submitter claim that an exact function serves a requirement.
27#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct RequirementAttribution {
30    /// Stable caller-owned requirement identity.
31    pub requirement_id: String,
32    /// Exact crate-qualified function name as the verifier reports it.
33    pub function: String,
34}
35
36/// Validate and canonically sort attributions before submission or storage.
37///
38/// # Errors
39/// Refuses empty sets, empty, oversized or control-character names and
40/// duplicate pairs.
41pub fn canonical(
42    mut attributions: Vec<RequirementAttribution>,
43) -> Result<Vec<RequirementAttribution>, String> {
44    let invalid = |why: &str| format!("SAIL3160: invalid requirement attribution: {why}");
45    if attributions.is_empty() || attributions.len() > MAX_ATTRIBUTIONS {
46        return Err(invalid("between one and 4096 attributions are required"));
47    }
48    for item in &attributions {
49        for name in [&item.requirement_id, &item.function] {
50            if name.is_empty() || name.len() > MAX_NAME || name.chars().any(char::is_control) {
51                return Err(invalid("names must be non-empty printable text"));
52            }
53        }
54    }
55    attributions.sort();
56    if attributions.windows(2).any(|pair| pair[0] == pair[1]) {
57        return Err(invalid("duplicate requirement and function pair"));
58    }
59    Ok(attributions)
60}
61
62/// Whether a job mode can carry attribution: only stock project and
63/// standalone-file verification, never an engine or repair batch.
64#[must_use]
65pub const fn mode_supported(mode: &Mode) -> bool {
66    matches!(mode, Mode::Stock | Mode::Standalone)
67}
68
69/// The relationship an attributed row checks; distinct from neutral contract-to-code.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "kebab-case")]
72pub enum Relationship {
73    /// The exact function satisfies its own Verus specification in the submitted source.
74    VerusSpecificationToCode,
75}
76
77/// Who asserted the requirement link.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "kebab-case")]
80pub enum AttributionSource {
81    /// Supplied by the submitting client and retained with the job, unchecked.
82    Submitter,
83}
84
85/// Evidence applies to the job's recorded input revision.
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "kebab-case")]
88pub enum Scope {
89    /// The project inputs whose revision the runner recorded.
90    InputRevision,
91}
92
93/// One attributed function and what the retained job evidence establishes for it.
94#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Evidence {
96    /// Content-derived identity over the revision, function, requirement and context.
97    pub obligation_id: String,
98    /// The relationship this evidence checks; never neutral contract-to-code.
99    pub relationship: Relationship,
100    /// The requirement link is a submitter claim.
101    pub attribution: AttributionSource,
102    /// Exact attributed function.
103    pub function: String,
104    /// Whether the verifier reported exactly one requested-target function with this name.
105    pub function_reported: bool,
106    /// Input revision recorded by the runner.
107    pub input_revision: String,
108    /// Original backend report digest.
109    pub backend_sha256: String,
110    /// Conservative outcome: proved only for a complete whole-job proof.
111    pub outcome: ProofState,
112    /// Present only for complete confirmed evidence with actual tool identity.
113    pub establishment: Option<EstablishmentName>,
114    /// Present only when that strength has actually been established.
115    pub tier: Option<EvidenceTier>,
116    /// Scope of the proof.
117    pub scope: Scope,
118    /// All actual distinct solver identities, sorted canonically.
119    pub solvers: Vec<SolverInfo>,
120    /// Explicit assumptions, trust and missing relationships, sorted.
121    pub qualifiers: Vec<String>,
122    /// Mutation establishment is never inferred from a passing proof.
123    pub mutation: MutationStatus,
124    /// Source-named inputs from the solver model of the function's first failed
125    /// or unknown check, with struct fields named by position; absent when proved.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub counterexample: Option<crate::counterexample::Decoded>,
128}
129
130/// Attributed evidence grouped by requirement identity.
131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
132pub struct Requirement {
133    /// Submitter-supplied identity.
134    pub requirement_id: String,
135    /// Rows sorted by function.
136    pub evidence: Vec<Evidence>,
137}
138
139/// Versioned read-only view over one ordinary job and its retained attributions.
140#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
141pub struct View {
142    /// Equals [`VERSION`].
143    pub version: u32,
144    /// Exact retained job identity.
145    pub job_id: String,
146    /// The job's verification arguments, verbatim; Verus arguments follow `--`.
147    pub arguments: Vec<String>,
148    /// Live currentness of the job's inputs, as the job service classifies it.
149    pub currentness: Currentness,
150    /// Requirement groups sorted by identity.
151    pub requirements: Vec<Requirement>,
152}
153
154const QUALIFIER_ATTRIBUTION: &str = "requirement attribution was supplied by the submitter; Sail does not check that the function's specification states the requirement";
155const QUALIFIER_NOT_NEUTRAL: &str =
156    "ordinary Verus evidence: no neutral contract was admitted, lowered or checked";
157const QUALIFIER_SCOPE: &str =
158    "applies to the job's recorded input revision under the function's stated preconditions";
159const QUALIFIER_TRUST: &str = "the submitted Verus specifications and the pinned Verus/SMT toolchain are trusted; Sail does not review assume or admit statements, external_body or assume_specification items, or other trusted code";
160const QUALIFIER_CHEATING: &str = "the job did not pass Verus --no-cheating, so assume, admit, external_body and assume_specification were allowed in the verified crate; no tier is established";
161const QUALIFIER_NO_CHEATING: &str = "the job passed Verus --no-cheating, which refuses assume, admit, external_body and assume_specification in the verified crate";
162const QUALIFIER_UNREVIEWED: &str =
163    "the job passed Verus arguments outside the reviewed set; no tier is established:";
164
165/// Verus arguments that cannot weaken a reported proof: selection, resource
166/// limits, threading, report detail and standalone crate naming. Each pairs its name with whether it
167/// takes a separate value. Anything else after `--` withholds the tier.
168const REVIEWED_VERUS_ARGUMENTS: [(&str, bool); 14] = [
169    ("--crate-name", true),
170    ("--crate-type", true),
171    ("--edition", true),
172    ("--expand-errors", false),
173    ("--multiple-errors", true),
174    ("--no-cheating", false),
175    ("--num-threads", true),
176    ("--rlimit", true),
177    ("--time", false),
178    ("--time-expanded", false),
179    ("--verify-function", true),
180    ("--verify-module", true),
181    ("--verify-only-module", true),
182    ("--verify-root", false),
183];
184
185/// How the job's forwarded Verus arguments bear on attributed trust.
186#[derive(Debug, Default, PartialEq, Eq)]
187struct VerusArguments {
188    no_cheating: bool,
189    unreviewed: Vec<String>,
190}
191
192/// Classify the Verus arguments, those after the first `--`.
193fn verus_arguments(arguments: &[String]) -> VerusArguments {
194    let mut result = VerusArguments::default();
195    let mut forwarded = arguments.iter().skip_while(|a| a.as_str() != "--").skip(1);
196    while let Some(argument) = forwarded.next() {
197        let (name, inline) = argument
198            .split_once('=')
199            .map_or((argument.as_str(), false), |(name, _)| (name, true));
200        match REVIEWED_VERUS_ARGUMENTS.iter().find(|(n, _)| *n == name) {
201            Some((_, takes_value)) if !inline || *takes_value => {
202                if *takes_value && !inline && forwarded.next().is_none() {
203                    result.unreviewed.push(argument.clone());
204                }
205                result.no_cheating |= name == "--no-cheating";
206            }
207            _ => result.unreviewed.push(argument.clone()),
208        }
209    }
210    result
211}
212const QUALIFIER_UNREPORTED: &str =
213    "the verifier reported no unique requested-target function with this exact name";
214const QUALIFIER_NOT_CURRENT: &str =
215    "the job's inputs are not confirmed current; no tier is established";
216
217/// Project an ordinary job result and its retained attributions.
218///
219/// The job service reads the sealed backend output before calling this
220/// function; a caller-built document is not authentication.
221///
222/// # Errors
223/// Refuses neutral, repair, unfinished or malformed jobs and invalid attributions.
224pub fn from_project_result(
225    document: &ResultDocument,
226    attributions: &[RequirementAttribution],
227) -> Result<View, String> {
228    let invalid = || "SAIL3160: invalid or incomplete attributed job evidence".to_owned();
229    let attributions = canonical(attributions.to_vec())?;
230    let backend: ProjectResult =
231        serde_json::from_value(document.result.clone().ok_or_else(invalid)?)
232            .map_err(|_| invalid())?;
233    if document.job.version != crate::jobs::VERSION
234        || document.job.state != Lifecycle::Completed
235        || document.job.id.is_empty()
236        || document.job.error.is_some()
237        || document.repair.is_some()
238        || backend.kind != "sail-project-result"
239        || backend.schema_version != crate::project::SCHEMA_VERSION
240        || backend.engine.is_some()
241        || document.job.exit_code.is_none()
242        || document.job.exit_code != backend.exit_code
243        || backend.input_revision.is_empty()
244    {
245        return Err(invalid());
246    }
247    let backend_sha256 =
248        crate::assurance::digest(&serde_json::to_vec(&backend).map_err(|_| invalid())?);
249    let (checks, _) = crate::assurance::check_counts(&backend);
250    let complete_run = crate::assurance::run_complete(&backend, &checks);
251    let (complete_identity, solvers) =
252        crate::assurance::solver_identities(&backend).map_err(|()| invalid())?;
253    let current = document.job.currentness == Currentness::Current;
254    let verus = verus_arguments(&document.job.args);
255    let reviewed = verus.no_cheating && verus.unreviewed.is_empty();
256    let targets = crate::assurance::requested_targets(&backend);
257    let reported = targets
258        .iter()
259        .flat_map(|t| &t.report.crates)
260        .flat_map(|c| &c.functions)
261        .fold(BTreeMap::<&str, usize>::new(), |mut counts, f| {
262            *counts.entry(f.function.as_str()).or_default() += 1;
263            counts
264        });
265    let mut grouped: BTreeMap<String, Vec<Evidence>> = BTreeMap::new();
266    for item in &attributions {
267        let unique = reported.get(item.function.as_str()) == Some(&1);
268        let proved = complete_run
269            && unique
270            && crate::assurance::exactly_one_proved(&targets, &item.function);
271        let confirmed = proved && complete_identity && current && reviewed;
272        let qualifiers = qualifiers(unique, complete_identity, current, &verus);
273        let identity = serde_json::to_vec(&(
274            &backend.input_revision,
275            &item.function,
276            &item.requirement_id,
277            &backend.context_sha256,
278        ))
279        .map_err(|_| invalid())?;
280        grouped
281            .entry(item.requirement_id.clone())
282            .or_default()
283            .push(Evidence {
284                obligation_id: format!("verus:{}", crate::assurance::digest(&identity)),
285                relationship: Relationship::VerusSpecificationToCode,
286                attribution: AttributionSource::Submitter,
287                function: item.function.clone(),
288                function_reported: unique,
289                input_revision: backend.input_revision.clone(),
290                backend_sha256: backend_sha256.clone(),
291                outcome: if proved {
292                    ProofState::Proved
293                } else {
294                    ProofState::NotProved
295                },
296                establishment: confirmed.then_some(EstablishmentName::Confirmed),
297                tier: confirmed.then_some(EvidenceTier::SmtVerified),
298                scope: Scope::InputRevision,
299                solvers: solvers.clone(),
300                qualifiers,
301                mutation: MutationStatus::NotEstablished,
302                counterexample: (!proved && unique)
303                    .then(|| decoded(&targets, &item.function))
304                    .flatten(),
305            });
306    }
307    Ok(View {
308        version: VERSION,
309        job_id: document.job.id.clone(),
310        arguments: document.job.args.clone(),
311        currentness: document.job.currentness,
312        requirements: grouped
313            .into_iter()
314            .map(|(requirement_id, evidence)| Requirement {
315                requirement_id,
316                evidence,
317            })
318            .collect(),
319    })
320}
321
322/// Model inputs of the one reported function; fields are named by position
323/// because ordinary source is not retained.
324fn decoded(
325    targets: &[&crate::project::TargetResult],
326    function: &str,
327) -> Option<crate::counterexample::Decoded> {
328    targets
329        .iter()
330        .flat_map(|t| &t.report.crates)
331        .flat_map(|c| &c.functions)
332        .find(|f| f.function == function)
333        .and_then(|f| crate::counterexample::decode(f, &crate::counterexample::FieldNames::new()))
334}
335
336fn qualifiers(
337    unique: bool,
338    complete_identity: bool,
339    current: bool,
340    verus: &VerusArguments,
341) -> Vec<String> {
342    let mut qualifiers: Vec<String> = [
343        QUALIFIER_ATTRIBUTION,
344        QUALIFIER_NOT_NEUTRAL,
345        QUALIFIER_SCOPE,
346        QUALIFIER_TRUST,
347    ]
348    .into_iter()
349    .chain(crate::assurance::SHARED_QUALIFIERS)
350    .map(String::from)
351    .collect();
352    if !unique {
353        qualifiers.push(QUALIFIER_UNREPORTED.into());
354    }
355    if !complete_identity {
356        qualifiers.push(crate::assurance::NO_IDENTITY_QUALIFIER.into());
357    }
358    if !current {
359        qualifiers.push(QUALIFIER_NOT_CURRENT.into());
360    }
361    qualifiers.push(
362        if verus.no_cheating {
363            QUALIFIER_NO_CHEATING
364        } else {
365            QUALIFIER_CHEATING
366        }
367        .into(),
368    );
369    if !verus.unreviewed.is_empty() {
370        qualifiers.push(format!(
371            "{QUALIFIER_UNREVIEWED} {}",
372            verus.unreviewed.join(" ")
373        ));
374    }
375    qualifiers.sort();
376    qualifiers
377}