use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub const TCB_SCHEMA: &str = "vela.tcb_policy.v0.1";
pub const DEFAULT_ALLOWED_AXIOMS: &[&str] = &["propext", "Classical.choice", "Quot.sound"];
pub const FORBIDDEN_AXIOMS: &[&str] = &[
"sorryAx",
"Lean.ofReduceBool",
"Lean.trustCompiler",
"Lean.reduceBool",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AxiomVerdict {
KernelClean,
ForbiddenAxiom,
UnlistedAxiom,
}
impl AxiomVerdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::KernelClean => "kernel_clean",
Self::ForbiddenAxiom => "forbidden_axiom",
Self::UnlistedAxiom => "unlisted_axiom",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TcbPolicy {
pub schema: String,
pub tcb_id: String,
pub allowed_axioms: Vec<String>,
pub forbidden_axioms: Vec<String>,
pub kernel_checker: String,
pub kernel_checker_version: String,
pub lean_toolchain: String,
pub mathlib_revision: String,
}
#[derive(Debug, Clone)]
pub struct TcbDraft {
pub allowed_axioms: Vec<String>,
pub forbidden_axioms: Vec<String>,
pub kernel_checker: String,
pub kernel_checker_version: String,
pub lean_toolchain: String,
pub mathlib_revision: String,
}
fn sorted_deduped(mut v: Vec<String>) -> Vec<String> {
v.sort();
v.dedup();
v
}
impl TcbPolicy {
pub fn build(draft: TcbDraft) -> Result<Self, String> {
let mut policy = TcbPolicy {
schema: TCB_SCHEMA.to_string(),
tcb_id: String::new(),
allowed_axioms: sorted_deduped(draft.allowed_axioms),
forbidden_axioms: sorted_deduped(draft.forbidden_axioms),
kernel_checker: draft.kernel_checker,
kernel_checker_version: draft.kernel_checker_version,
lean_toolchain: draft.lean_toolchain,
mathlib_revision: draft.mathlib_revision,
};
policy.tcb_id = policy.derive_id()?;
Ok(policy)
}
pub fn default_for(
lean_toolchain: &str,
mathlib_revision: &str,
kernel_checker: &str,
kernel_checker_version: &str,
) -> Result<Self, String> {
Self::build(TcbDraft {
allowed_axioms: DEFAULT_ALLOWED_AXIOMS
.iter()
.map(|s| (*s).to_string())
.collect(),
forbidden_axioms: FORBIDDEN_AXIOMS.iter().map(|s| (*s).to_string()).collect(),
kernel_checker: kernel_checker.to_string(),
kernel_checker_version: kernel_checker_version.to_string(),
lean_toolchain: lean_toolchain.to_string(),
mathlib_revision: mathlib_revision.to_string(),
})
}
pub fn derive_id(&self) -> Result<String, String> {
let mut preimage = self.clone();
preimage.tcb_id = String::new();
let bytes = crate::canonical::to_canonical_bytes(&preimage)
.map_err(|e| format!("canonicalize tcb policy preimage: {e}"))?;
let digest = Sha256::digest(&bytes);
Ok(format!("vtcb_{}", &hex::encode(digest)[..16]))
}
pub fn verify(&self) -> Result<(), String> {
if self.schema != TCB_SCHEMA {
return Err(format!(
"tcb.schema must be `{TCB_SCHEMA}`, got `{}`",
self.schema
));
}
if !self.tcb_id.starts_with("vtcb_") {
return Err(format!(
"tcb id must start with `vtcb_`, got `{}`",
self.tcb_id
));
}
let derived = self.derive_id()?;
if derived != self.tcb_id {
return Err(format!(
"tcb id mismatch: stored `{}`, derived `{}`",
self.tcb_id, derived
));
}
Ok(())
}
#[must_use]
pub fn classify(&self, observed_axioms: &[String]) -> AxiomVerdict {
if observed_axioms
.iter()
.any(|a| self.forbidden_axioms.iter().any(|f| f == a))
{
return AxiomVerdict::ForbiddenAxiom;
}
if observed_axioms
.iter()
.any(|a| !self.allowed_axioms.iter().any(|allowed| allowed == a))
{
return AxiomVerdict::UnlistedAxiom;
}
AxiomVerdict::KernelClean
}
}
#[cfg(test)]
mod tests {
use super::*;
fn default_policy() -> TcbPolicy {
TcbPolicy::default_for(
"leanprover/lean4:v4.29.1",
"v4.29.1",
"lean4checker",
"lean4checker@v4.29.1",
)
.expect("build default policy")
}
#[test]
fn allowlist_parse_roundtrips_and_sorts() {
let p = TcbPolicy::build(TcbDraft {
allowed_axioms: vec!["Quot.sound".into(), "propext".into(), "propext".into()],
forbidden_axioms: vec!["sorryAx".into()],
kernel_checker: "none".into(),
kernel_checker_version: String::new(),
lean_toolchain: "leanprover/lean4:v4.29.1".into(),
mathlib_revision: "v4.29.1".into(),
})
.unwrap();
assert_eq!(p.allowed_axioms, vec!["Quot.sound", "propext"]); }
#[test]
fn classify_kernel_clean() {
let p = default_policy();
let observed = vec!["propext".to_string(), "Classical.choice".to_string()];
assert_eq!(p.classify(&observed), AxiomVerdict::KernelClean);
}
#[test]
fn classify_empty_is_kernel_clean() {
let p = default_policy();
assert_eq!(p.classify(&[]), AxiomVerdict::KernelClean);
}
#[test]
fn classify_rejects_native_decide() {
let p = default_policy();
let observed = vec![
"Lean.ofReduceBool".to_string(),
"Lean.trustCompiler".to_string(),
];
assert_eq!(p.classify(&observed), AxiomVerdict::ForbiddenAxiom);
}
#[test]
fn classify_rejects_sorry() {
let p = default_policy();
assert_eq!(
p.classify(&["sorryAx".to_string()]),
AxiomVerdict::ForbiddenAxiom
);
}
#[test]
fn classify_forbidden_beats_allowed() {
let p = default_policy();
let observed = vec!["propext".to_string(), "sorryAx".to_string()];
assert_eq!(p.classify(&observed), AxiomVerdict::ForbiddenAxiom);
}
#[test]
fn classify_unlisted() {
let p = default_policy();
assert_eq!(
p.classify(&["MyDev.customAxiom".to_string()]),
AxiomVerdict::UnlistedAxiom
);
}
#[test]
fn tcb_id_is_content_addressed_and_verifies() {
let p = default_policy();
assert!(p.tcb_id.starts_with("vtcb_"));
p.verify().unwrap();
}
#[test]
fn tcb_id_changes_with_allowlist() {
let p1 = default_policy();
let p2 = TcbPolicy::build(TcbDraft {
allowed_axioms: vec!["propext".into()], forbidden_axioms: FORBIDDEN_AXIOMS.iter().map(|s| (*s).to_string()).collect(),
kernel_checker: "lean4checker".into(),
kernel_checker_version: "lean4checker@v4.29.1".into(),
lean_toolchain: "leanprover/lean4:v4.29.1".into(),
mathlib_revision: "v4.29.1".into(),
})
.unwrap();
assert_ne!(p1.tcb_id, p2.tcb_id);
}
#[test]
fn tampered_policy_fails_verify() {
let mut p = default_policy();
p.allowed_axioms.push("sorryAx".to_string());
assert!(p.verify().is_err());
}
}