1use 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
19pub const VERSION: u32 = 1;
21pub const MAX_ATTRIBUTIONS: usize = 4096;
23pub const MAX_NAME: usize = 1024;
25
26#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct RequirementAttribution {
30 pub requirement_id: String,
32 pub function: String,
34}
35
36pub 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#[must_use]
65pub const fn mode_supported(mode: &Mode) -> bool {
66 matches!(mode, Mode::Stock | Mode::Standalone)
67}
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "kebab-case")]
72pub enum Relationship {
73 VerusSpecificationToCode,
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "kebab-case")]
80pub enum AttributionSource {
81 Submitter,
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "kebab-case")]
88pub enum Scope {
89 InputRevision,
91}
92
93#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Evidence {
96 pub obligation_id: String,
98 pub relationship: Relationship,
100 pub attribution: AttributionSource,
102 pub function: String,
104 pub function_reported: bool,
106 pub input_revision: String,
108 pub backend_sha256: String,
110 pub outcome: ProofState,
112 pub establishment: Option<EstablishmentName>,
114 pub tier: Option<EvidenceTier>,
116 pub scope: Scope,
118 pub solvers: Vec<SolverInfo>,
120 pub qualifiers: Vec<String>,
122 pub mutation: MutationStatus,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub counterexample: Option<crate::counterexample::Decoded>,
128}
129
130#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
132pub struct Requirement {
133 pub requirement_id: String,
135 pub evidence: Vec<Evidence>,
137}
138
139#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
141pub struct View {
142 pub version: u32,
144 pub job_id: String,
146 pub arguments: Vec<String>,
148 pub currentness: Currentness,
150 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
165const 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#[derive(Debug, Default, PartialEq, Eq)]
187struct VerusArguments {
188 no_cheating: bool,
189 unreviewed: Vec<String>,
190}
191
192fn 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
217pub 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
322fn 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}