extern crate alloc;
use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use chio_core_types::capability::{
scope::{ChioScope, Operation, ToolGrant},
token::CapabilityToken,
};
use chio_core_types::crypto::{PublicKey, Signature, SigningAlgorithm, SigningBackend};
use chio_core_types::receipt::{
body::ChioReceiptBody, decision::Decision, decision::ToolCallAction, kinds::TrustLevel,
};
use serde_json::Value;
use crate::capability_verify::CapabilityError;
use crate::clock::FixedClock;
use crate::evaluate::EvaluateInput;
use crate::formal_core::{
composite_quota_authorize, family_binding_preserved, guard_pipeline_allows,
monetary_cap_is_subset_by_parts, optional_u32_cap_is_subset, quota_maximum_compatible,
receipt_fields_coupled, required_true_is_preserved, revocation_snapshot_denies,
threshold_distinct_eligible_signers, time_window_valid, GuardStep,
};
use crate::guard::PortableToolCallRequest;
use crate::normalized::{NormalizedOperation, NormalizedScope, NormalizedToolGrant};
use crate::receipts::ReceiptSigningError;
use crate::scope::resolve_matching_grants;
use crate::{
evaluate, sign_receipt, sign_receipt_relaying_trusted_body, verify_capability, Verdict,
};
fn public_key(seed: u8) -> PublicKey {
let mut bytes = [seed; 65];
bytes[0] = 0x04;
PublicKey::from_p256_sec1(&bytes)
.unwrap_or_else(|_| unreachable!("deterministic P-256 key fixture is well-formed"))
}
fn p384_public_key(seed: u8) -> PublicKey {
let mut bytes = [seed; 97];
bytes[0] = 0x04;
PublicKey::from_p384_sec1(&bytes)
.unwrap_or_else(|_| unreachable!("deterministic P-384 key fixture is well-formed"))
}
fn grant(server: &str, tool: &str) -> ToolGrant {
ToolGrant {
server_id: server.to_string(),
tool_name: tool.to_string(),
operations: vec![Operation::Invoke],
constraints: vec![],
max_invocations: None,
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: None,
}
}
fn unsigned_capability(ttl: u64) -> CapabilityToken {
CapabilityToken {
schema: chio_core_types::capability::token::CHIO_CAPABILITY_SCHEMA.to_string(),
id: "cap-public-kani".to_string(),
issuer: public_key(7),
subject: public_key(9),
scope: ChioScope {
grants: vec![grant("s", "r")],
..ChioScope::default()
},
issued_at: 10,
expires_at: 10 + ttl,
delegation_chain: vec![],
algorithm: None,
caveats: vec![],
scope_attenuations: None,
attenuation_proof: None,
budget_share_bps: None,
aggregate_invocation_budget: None,
signature: Signature::from_bytes(&[0; 64]),
}
}
fn path_arguments(path: &str) -> Value {
Value::String(path.to_string())
}
fn request(_capability: &CapabilityToken, tool: &str) -> PortableToolCallRequest {
PortableToolCallRequest {
request_id: "req-public-kani".to_string(),
tool_name: tool.to_string(),
server_id: "s".to_string(),
agent_id: "agent-public-kani".to_string(),
arguments: path_arguments("/app/src/main.rs"),
}
}
fn assume_single_unconstrained_invoke_grant(scope: &ChioScope) {
kani::assume(scope.grants.len() == 1);
let grant = &scope.grants[0];
kani::assume(grant.constraints.is_empty());
kani::assume(grant.operations.len() == 1);
kani::assume(grant.operations[0] == Operation::Invoke);
}
fn assume_single_normalized_tool_grant(scope: &NormalizedScope) {
kani::assume(scope.grants.len() == 1);
kani::assume(scope.resource_grants.is_empty());
kani::assume(scope.prompt_grants.is_empty());
let grant = &scope.grants[0];
kani::assume(grant.constraints.is_empty());
kani::assume(grant.operations.len() == 1);
kani::assume(grant.max_cost_per_invocation.is_none());
kani::assume(grant.max_total_cost.is_none());
}
#[kani::proof]
pub fn public_verify_capability_rejects_untrusted_issuer_before_signature() {
let capability = unsigned_capability(100);
let clock = FixedClock::new(11);
let result = verify_capability(&capability, &[], &clock);
assert!(matches!(result, Err(CapabilityError::UntrustedIssuer)));
core::mem::forget(capability);
}
#[kani::proof]
pub fn public_normalized_scope_subset_rejects_widened_child() {
let parent = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: Some(1),
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: Some(true),
}],
resource_grants: vec![],
prompt_grants: vec![],
};
let child = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: None,
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: None,
}],
resource_grants: vec![],
prompt_grants: vec![],
};
assume_single_normalized_tool_grant(&child);
assume_single_normalized_tool_grant(&parent);
assert!(!child.is_subset_of(&parent));
core::mem::forget(child);
core::mem::forget(parent);
}
#[kani::proof]
pub fn public_normalized_scope_subset_rejects_value_widened_child() {
let parent = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: Some(1),
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: Some(true),
}],
resource_grants: vec![],
prompt_grants: vec![],
};
let child = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: Some(100),
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: Some(false),
}],
resource_grants: vec![],
prompt_grants: vec![],
};
assume_single_normalized_tool_grant(&child);
assume_single_normalized_tool_grant(&parent);
assert!(!child.is_subset_of(&parent));
core::mem::forget(child);
core::mem::forget(parent);
}
#[kani::proof]
pub fn public_normalized_scope_subset_rejects_identity_mismatch() {
let parent = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: None,
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: None,
}],
resource_grants: vec![],
prompt_grants: vec![],
};
let child = NormalizedScope {
grants: vec![NormalizedToolGrant {
server_id: "other".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: None,
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: None,
}],
resource_grants: vec![],
prompt_grants: vec![],
};
assume_single_normalized_tool_grant(&child);
assume_single_normalized_tool_grant(&parent);
assert!(!child.is_subset_of(&parent));
core::mem::forget(child);
core::mem::forget(parent);
}
#[kani::proof]
pub fn public_resolve_matching_grants_rejects_out_of_scope_request() {
let scope = ChioScope {
grants: vec![grant("s", "r")],
..ChioScope::default()
};
assume_single_unconstrained_invoke_grant(&scope);
let arguments = Value::Null;
let matches = match resolve_matching_grants(&scope, "w", "s", &arguments) {
Ok(matches) => matches,
Err(_) => {
core::mem::forget(arguments);
core::mem::forget(scope);
kani::assume(false);
unreachable!("unconstrained grants do not fail during matching");
}
};
assert!(matches.is_empty());
core::mem::forget(matches);
core::mem::forget(arguments);
core::mem::forget(scope);
}
#[kani::proof]
pub fn public_resolve_matching_grants_preserves_wildcard_matching() {
let scope = ChioScope {
grants: vec![grant("*", "*")],
..ChioScope::default()
};
assume_single_unconstrained_invoke_grant(&scope);
let arguments = Value::Null;
let matches = match resolve_matching_grants(&scope, "w", "s", &arguments) {
Ok(matches) => matches,
Err(_) => {
core::mem::forget(arguments);
core::mem::forget(scope);
kani::assume(false);
unreachable!("unconstrained wildcard grants do not fail");
}
};
assert_eq!(matches.len(), 1);
assert_eq!(matches[0].specificity, (0, 0, 0));
core::mem::forget(matches);
core::mem::forget(arguments);
core::mem::forget(scope);
}
#[kani::proof]
pub fn public_evaluate_rejects_untrusted_issuer_before_dispatch() {
let capability = unsigned_capability(100);
let request = request(&capability, "r");
let clock = FixedClock::new(11);
let guards: [&dyn crate::Guard; 0] = [];
let verdict = evaluate(EvaluateInput {
request: &request,
capability: &capability,
trusted_issuers: &[],
clock: &clock,
guards: &guards,
session_filesystem_roots: None,
});
assert_eq!(verdict.verdict, Verdict::Deny);
core::mem::forget(request);
core::mem::forget(capability);
}
struct DeterministicBackend {
public_key: PublicKey,
}
impl SigningBackend for DeterministicBackend {
fn algorithm(&self) -> SigningAlgorithm {
SigningAlgorithm::Ed25519
}
fn public_key(&self) -> PublicKey {
self.public_key.clone()
}
fn sign_bytes(&self, message: &[u8]) -> chio_core_types::Result<Signature> {
let _ = message;
Ok(Signature::from_bytes(&[0; 64]))
}
}
fn receipt_body(kernel_key: PublicKey) -> ChioReceiptBody {
let action = ToolCallAction {
parameters: Value::Null,
parameter_hash: "h".to_string(),
};
ChioReceiptBody {
id: "rcpt-public-kani".to_string(),
timestamp: 1,
capability_id: "cap-public-kani".to_string(),
tool_server: "s".to_string(),
tool_name: "r".to_string(),
action,
decision: Some(Decision::Deny {
reason: "test".to_string(),
guard: "kani".to_string(),
}),
receipt_kind: Default::default(),
boundary_class: Default::default(),
observation_outcome: None,
tool_origin: Default::default(),
redaction_mode: Default::default(),
actor_chain: Vec::new(),
content_hash: "h".to_string(),
policy_hash: "policy".to_string(),
evidence: vec![],
metadata: None,
trust_level: TrustLevel::Mediated,
tenant_id: None,
kernel_key,
bbs_projection_version: None,
}
}
#[kani::proof]
pub fn public_sign_receipt_rejects_kernel_key_mismatch_before_signing() {
let backend = DeterministicBackend {
public_key: public_key(12),
};
let body = receipt_body(p384_public_key(11));
let result = sign_receipt_relaying_trusted_body(body, &backend);
let rejected = matches!(&result, Err(ReceiptSigningError::KernelKeyMismatch));
core::mem::forget(result);
core::mem::forget(backend);
assert!(rejected);
}
#[kani::proof]
pub fn public_sign_receipt_accepts_matching_kernel_key() {
let key = public_key(12);
let backend = DeterministicBackend {
public_key: key.clone(),
};
let body = receipt_body(key);
let receipt = sign_receipt_relaying_trusted_body(body, &backend)
.unwrap_or_else(|_| unreachable!("matching key signs"));
assert_eq!(receipt.id, "rcpt-public-kani");
assert_eq!(receipt.algorithm, Some(SigningAlgorithm::Ed25519));
assert_eq!(receipt.signature, Signature::from_bytes(&[0; 64]));
core::mem::forget(receipt);
core::mem::forget(backend);
}
#[kani::proof]
pub fn public_sign_receipt_refuses_content_hash_mismatch() {
let key = public_key(12);
let backend = DeterministicBackend {
public_key: key.clone(),
};
let body = receipt_body(key);
let canonical_content = b"kani-content-preimage-not-h";
let result = sign_receipt(body, &backend, canonical_content);
let refused = matches!(
&result,
Err(ReceiptSigningError::ContentHashMismatch { .. })
);
core::mem::forget(result);
core::mem::forget(backend);
assert!(refused);
}
#[kani::proof]
pub fn public_sign_receipt_accepts_matching_content_hash() {
let key = public_key(12);
let backend = DeterministicBackend {
public_key: key.clone(),
};
let canonical_content = b"kani-content-preimage";
let mut body = receipt_body(key);
body.content_hash = chio_core_types::crypto::sha256_hex(canonical_content);
let receipt = sign_receipt(body, &backend, canonical_content)
.unwrap_or_else(|_| unreachable!("matching content hash and key signs"));
assert_eq!(receipt.id, "rcpt-public-kani");
assert_eq!(receipt.algorithm, Some(SigningAlgorithm::Ed25519));
assert_eq!(receipt.signature, Signature::from_bytes(&[0; 64]));
core::mem::forget(receipt);
core::mem::forget(backend);
}
#[kani::proof]
pub fn verify_scope_intersection_associative() {
let a_has = kani::any::<bool>();
let b_has = kani::any::<bool>();
let c_has = kani::any::<bool>();
let a_value = u32::from(kani::any::<u8>());
let b_value = u32::from(kani::any::<u8>());
let c_value = u32::from(kani::any::<u8>());
let a_le_b = optional_u32_cap_is_subset(a_has, a_value, b_has, b_value);
let b_le_c = optional_u32_cap_is_subset(b_has, b_value, c_has, c_value);
let a_le_c = optional_u32_cap_is_subset(a_has, a_value, c_has, c_value);
if a_le_b && b_le_c {
assert!(a_le_c);
}
let a_le_a = optional_u32_cap_is_subset(a_has, a_value, a_has, a_value);
assert!(a_le_a);
}
#[kani::proof]
pub fn verify_revocation_predicate_idempotent() {
let token_revoked = kani::any::<bool>();
let ancestor_revoked = kani::any::<bool>();
let first = revocation_snapshot_denies(token_revoked, ancestor_revoked);
let second = revocation_snapshot_denies(token_revoked, ancestor_revoked);
assert_eq!(first, second);
let mirrored_first = revocation_snapshot_denies(token_revoked, token_revoked);
let mirrored_second = revocation_snapshot_denies(token_revoked, token_revoked);
assert_eq!(mirrored_first, mirrored_second);
assert_eq!(mirrored_first, token_revoked);
}
fn one_step_attenuation_predicate(
server_parent_is_wildcard: bool,
server_parent_equals_child: bool,
tool_parent_is_wildcard: bool,
tool_parent_equals_child: bool,
operations_child_subset: bool,
constraints_child_superset: bool,
parent_has_inv_cap: bool,
parent_inv_cap: u32,
child_has_inv_cap: bool,
child_inv_cap: u32,
parent_has_per_call_cost: bool,
parent_per_call_units: u64,
child_has_per_call_cost: bool,
child_per_call_units: u64,
per_call_currency_matches: bool,
parent_has_total_cost: bool,
parent_total_units: u64,
child_has_total_cost: bool,
child_total_units: u64,
total_currency_matches: bool,
parent_dpop_required: bool,
child_dpop_required: bool,
) -> bool {
let server_covers = server_parent_is_wildcard || server_parent_equals_child;
let tool_covers = tool_parent_is_wildcard || tool_parent_equals_child;
let inv_ok = optional_u32_cap_is_subset(
child_has_inv_cap,
child_inv_cap,
parent_has_inv_cap,
parent_inv_cap,
);
let per_call_ok = monetary_cap_is_subset_by_parts(
child_has_per_call_cost,
child_per_call_units,
parent_has_per_call_cost,
parent_per_call_units,
per_call_currency_matches,
);
let total_ok = monetary_cap_is_subset_by_parts(
child_has_total_cost,
child_total_units,
parent_has_total_cost,
parent_total_units,
total_currency_matches,
);
let dpop_ok = required_true_is_preserved(parent_dpop_required, child_dpop_required);
server_covers
&& tool_covers
&& operations_child_subset
&& constraints_child_superset
&& inv_ok
&& per_call_ok
&& total_ok
&& dpop_ok
}
#[kani::proof]
pub fn verify_delegation_chain_step() {
let server_parent_is_wildcard = kani::any::<bool>();
let server_parent_equals_child = kani::any::<bool>();
let tool_parent_is_wildcard = kani::any::<bool>();
let tool_parent_equals_child = kani::any::<bool>();
let operations_child_subset = kani::any::<bool>();
let constraints_child_superset = kani::any::<bool>();
let parent_has_inv_cap = kani::any::<bool>();
let parent_inv_cap = u32::from(kani::any::<u8>());
let child_has_inv_cap = kani::any::<bool>();
let child_inv_cap = u32::from(kani::any::<u8>());
let parent_has_per_call_cost = kani::any::<bool>();
let parent_per_call_units = u64::from(kani::any::<u8>());
let child_has_per_call_cost = kani::any::<bool>();
let child_per_call_units = u64::from(kani::any::<u8>());
let per_call_currency_matches = kani::any::<bool>();
let parent_has_total_cost = kani::any::<bool>();
let parent_total_units = u64::from(kani::any::<u8>());
let child_has_total_cost = kani::any::<bool>();
let child_total_units = u64::from(kani::any::<u8>());
let total_currency_matches = kani::any::<bool>();
let parent_dpop_required = kani::any::<bool>();
let child_dpop_required = kani::any::<bool>();
let attenuates = one_step_attenuation_predicate(
server_parent_is_wildcard,
server_parent_equals_child,
tool_parent_is_wildcard,
tool_parent_equals_child,
operations_child_subset,
constraints_child_superset,
parent_has_inv_cap,
parent_inv_cap,
child_has_inv_cap,
child_inv_cap,
parent_has_per_call_cost,
parent_per_call_units,
child_has_per_call_cost,
child_per_call_units,
per_call_currency_matches,
parent_has_total_cost,
parent_total_units,
child_has_total_cost,
child_total_units,
total_currency_matches,
parent_dpop_required,
child_dpop_required,
);
let reflexive = one_step_attenuation_predicate(
false,
true,
false,
true,
true,
true,
parent_has_inv_cap,
parent_inv_cap,
parent_has_inv_cap,
parent_inv_cap,
parent_has_per_call_cost,
parent_per_call_units,
parent_has_per_call_cost,
parent_per_call_units,
true,
parent_has_total_cost,
parent_total_units,
parent_has_total_cost,
parent_total_units,
true,
parent_dpop_required,
parent_dpop_required,
);
assert!(reflexive);
if attenuates {
assert!(server_parent_is_wildcard || server_parent_equals_child);
assert!(tool_parent_is_wildcard || tool_parent_equals_child);
assert!(operations_child_subset);
assert!(constraints_child_superset);
assert!(!parent_has_inv_cap || (child_has_inv_cap && child_inv_cap <= parent_inv_cap));
assert!(
!parent_has_per_call_cost
|| (child_has_per_call_cost
&& per_call_currency_matches
&& child_per_call_units <= parent_per_call_units)
);
assert!(
!parent_has_total_cost
|| (child_has_total_cost
&& total_currency_matches
&& child_total_units <= parent_total_units)
);
assert!(!parent_dpop_required || child_dpop_required);
}
let widen_inv_unbounded = one_step_attenuation_predicate(
false,
true,
false,
true,
true,
true,
true, parent_inv_cap, false, 0,
false,
0,
false,
0,
true,
false,
0,
false,
0,
true,
false,
false,
);
assert!(!widen_inv_unbounded);
let widen_dpop = one_step_attenuation_predicate(
false, true, false, true, true, true, false, 0, false, 0, false, 0, false, 0, true, false,
0, false, 0, true, true, false, );
assert!(!widen_dpop);
let now = u64::from(kani::any::<u8>());
let issued_at = u64::from(kani::any::<u8>());
let parent_expires_at = u64::from(kani::any::<u8>());
let child_expires_at = u64::from(kani::any::<u8>());
kani::assume(child_expires_at <= parent_expires_at);
let parent_valid = time_window_valid(now, issued_at, parent_expires_at);
let child_valid = time_window_valid(now, issued_at, child_expires_at);
if child_valid {
assert!(parent_valid);
}
let parent_grant = NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: if parent_has_inv_cap {
Some(parent_inv_cap)
} else {
None
},
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: if parent_dpop_required {
Some(true)
} else {
None
},
};
let child_grant = NormalizedToolGrant {
server_id: "s".to_string(),
tool_name: "r".to_string(),
operations: vec![NormalizedOperation::Invoke],
constraints: vec![],
max_invocations: if child_has_inv_cap {
Some(child_inv_cap)
} else {
None
},
max_cost_per_invocation: None,
max_total_cost: None,
dpop_required: if child_dpop_required {
Some(true)
} else {
None
},
};
let runtime_subset = child_grant.is_subset_of(&parent_grant);
let predicate_under_identity =
optional_u32_cap_is_subset(
child_has_inv_cap,
child_inv_cap,
parent_has_inv_cap,
parent_inv_cap,
) && required_true_is_preserved(parent_dpop_required, child_dpop_required);
assert_eq!(runtime_subset, predicate_under_identity);
core::mem::forget(parent_grant);
core::mem::forget(child_grant);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ModelSignature {
signer_id: u8,
message_class: u8,
}
fn model_sign(signer_id: u8, message_class: u8) -> ModelSignature {
ModelSignature {
signer_id,
message_class,
}
}
fn model_verify(verifier_id: u8, message_class: u8, signature: ModelSignature) -> bool {
verifier_id == signature.signer_id && message_class == signature.message_class
}
#[kani::proof]
pub fn verify_receipt_roundtrip() {
let signer_id = kani::any::<u8>();
let message_class = kani::any::<u8>();
let honest = model_sign(signer_id, message_class);
assert!(model_verify(signer_id, message_class, honest));
let tampered_class = kani::any::<u8>();
kani::assume(tampered_class != message_class);
assert!(!model_verify(signer_id, tampered_class, honest));
let tampered_signer = kani::any::<u8>();
kani::assume(tampered_signer != signer_id);
assert!(!model_verify(tampered_signer, message_class, honest));
let forged_signer_part = kani::any::<u8>();
kani::assume(forged_signer_part != signer_id);
let forged_signature_a = ModelSignature {
signer_id: forged_signer_part,
message_class,
};
assert!(!model_verify(signer_id, message_class, forged_signature_a));
let forged_message_part = kani::any::<u8>();
kani::assume(forged_message_part != message_class);
let forged_signature_b = ModelSignature {
signer_id,
message_class: forged_message_part,
};
assert!(!model_verify(signer_id, message_class, forged_signature_b));
let resigned = model_sign(signer_id, message_class);
assert!(model_verify(signer_id, message_class, resigned));
assert_eq!(honest, resigned);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModelBudgetError {
Overflow,
CapExceeded,
}
fn model_budget_checked_add(current: u64, delta: u64, cap: u64) -> Result<u64, ModelBudgetError> {
match current.checked_add(delta) {
None => Err(ModelBudgetError::Overflow),
Some(new) if new > cap => Err(ModelBudgetError::CapExceeded),
Some(new) => Ok(new),
}
}
fn model_budget_apply(state: u64, delta: u64, cap: u64) -> (Result<u64, ModelBudgetError>, u64) {
match model_budget_checked_add(state, delta, cap) {
Ok(new) => (Ok(new), new),
Err(err) => (Err(err), state),
}
}
#[kani::proof]
pub fn verify_budget_checked_add_no_overflow() {
let current = u64::from(kani::any::<u8>());
let delta = u64::from(kani::any::<u8>());
let cap = u64::from(kani::any::<u8>());
let (result, post) = model_budget_apply(current, delta, cap);
match result {
Ok(new) => {
assert!(new <= cap);
assert_eq!(post, new);
assert!(current.checked_add(delta).is_some());
assert_eq!(current.checked_add(delta), Some(new));
}
Err(ModelBudgetError::CapExceeded) => {
assert_eq!(post, current);
let sum = current
.checked_add(delta)
.unwrap_or_else(|| unreachable!("cap-exceeded arm only fires on Some(_)"));
assert!(sum > cap);
}
Err(ModelBudgetError::Overflow) => {
assert_eq!(post, current);
assert!(current.checked_add(delta).is_none());
}
}
let tail = u64::from(kani::any::<u8>());
let overflow_current = u64::MAX - tail;
let overflow_delta = u64::from(kani::any::<u8>());
let overflow_cap = u64::from(kani::any::<u8>());
let (overflow_result, overflow_post) =
model_budget_apply(overflow_current, overflow_delta, overflow_cap);
match overflow_result {
Ok(new) => {
assert!(new <= overflow_cap);
assert_eq!(overflow_post, new);
assert!(overflow_delta <= tail);
}
Err(ModelBudgetError::Overflow) => {
assert_eq!(overflow_post, overflow_current);
assert!(overflow_delta > tail);
assert_eq!(overflow_post, overflow_current);
}
Err(ModelBudgetError::CapExceeded) => {
assert_eq!(overflow_post, overflow_current);
assert!(overflow_delta <= tail);
let sum = overflow_current
.checked_add(overflow_delta)
.unwrap_or_else(|| unreachable!("cap-exceeded arm only fires on Some(_)"));
assert!(sum > overflow_cap);
}
}
let (retry_result, retry_post) =
model_budget_apply(overflow_post, overflow_delta, overflow_cap);
if matches!(overflow_result, Err(_)) {
assert_eq!(retry_post, overflow_post);
assert_eq!(retry_result.is_err(), overflow_result.is_err());
}
}
#[kani::proof]
pub fn verify_composite_quota_all_or_nothing() {
let before = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
let maximum = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
let applicable = [
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
];
let result = composite_quota_authorize(before, maximum, applicable);
if result.accepted {
for index in 0..3 {
if applicable[index] {
assert_eq!(result.captured[index], before[index] + 1);
assert!(result.captured[index] <= maximum[index]);
} else {
assert_eq!(result.captured[index], before[index]);
}
}
} else {
assert_eq!(result.captured, before);
}
}
#[kani::proof]
pub fn verify_quota_maximum_immutable() {
let initialized = kani::any::<bool>();
let existing = kani::any::<u8>();
let presented = kani::any::<u8>();
let compatible = quota_maximum_compatible(initialized, existing, presented);
assert_eq!(compatible, !initialized || existing == presented);
if initialized && existing != presented {
assert!(!compatible);
}
}
#[kani::proof]
pub fn verify_family_binding_preservation() {
let fields = [
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
];
let root_maximum = kani::any::<u8>();
let descendant_maximum = kani::any::<u8>();
let preserved = family_binding_preserved(fields, root_maximum, descendant_maximum);
assert_eq!(
preserved,
fields.iter().all(|matches| *matches) && root_maximum == descendant_maximum
);
if fields.iter().any(|matches| !*matches) || root_maximum != descendant_maximum {
assert!(!preserved);
}
}
#[kani::proof]
pub fn verify_threshold_distinct_signers() {
let signer_ids = [kani::any::<u8>(), kani::any::<u8>(), kani::any::<u8>()];
let present = [
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
];
let eligible = [
kani::any::<bool>(),
kani::any::<bool>(),
kani::any::<bool>(),
];
let count = threshold_distinct_eligible_signers(signer_ids, present, eligible);
assert!(count <= 3);
for signer in 0..3_u8 {
let occurrences = (0..3)
.filter(|index| present[*index] && signer_ids[*index] == signer)
.count();
if occurrences > 1 {
let mut without_duplicate = present;
let mut retained = false;
for index in 0..3 {
if signer_ids[index] == signer && without_duplicate[index] {
if retained {
without_duplicate[index] = false;
} else {
retained = true;
}
}
}
assert_eq!(
count,
threshold_distinct_eligible_signers(signer_ids, without_duplicate, eligible)
);
}
}
}
#[kani::proof]
pub fn verify_delegate_no_widen() {
let parent_cap = u32::from(kani::any::<u8>()).saturating_add(1);
let mid_cap = u32::from(kani::any::<u8>());
let child_cap = u32::from(kani::any::<u8>());
kani::assume(mid_cap <= parent_cap);
kani::assume(child_cap <= mid_cap);
let parent_to_mid = optional_u32_cap_is_subset(true, mid_cap, true, parent_cap);
let mid_to_child = optional_u32_cap_is_subset(true, child_cap, true, mid_cap);
let parent_to_child = optional_u32_cap_is_subset(true, child_cap, true, parent_cap);
assert!(parent_to_mid);
assert!(mid_to_child);
assert!(parent_to_child);
let transitive_step = one_step_attenuation_predicate(
false, true, false, true, true, true, true, parent_cap, true, child_cap, false, 0, false,
0, true, false, 0, false, 0, true, true, true,
);
assert!(transitive_step);
let widened_child_cap = parent_cap + 1;
let widened_step = one_step_attenuation_predicate(
false,
true,
false,
true,
true,
true,
true,
parent_cap,
true,
widened_child_cap,
false,
0,
false,
0,
true,
false,
0,
false,
0,
true,
true,
true,
);
assert!(!widened_step);
}
#[kani::proof]
pub fn verify_delegation_receipt_canonical() {
let parent_chain_len = u8::from(kani::any::<u8>());
let attenuation_axis = kani::any::<bool>();
let signed_at = u8::from(kani::any::<u8>());
let nonce_byte = kani::any::<u8>();
let receipt_like =
model_delegation_receipt(parent_chain_len, attenuation_axis, signed_at, nonce_byte);
let bytes_a = receipt_like.canonical_class();
let bytes_b = receipt_like.canonical_class();
assert_eq!(bytes_a, bytes_b);
let mutated_receipt_like = model_delegation_receipt(
parent_chain_len,
attenuation_axis,
signed_at,
nonce_byte ^ 1,
);
assert_ne!(bytes_a, mutated_receipt_like.canonical_class());
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ModelDelegationReceipt {
parent_chain_len: u8,
attenuation_axis: bool,
signed_at: u8,
nonce_byte: u8,
}
fn model_delegation_receipt(
parent_chain_len: u8,
attenuation_axis: bool,
signed_at: u8,
nonce_byte: u8,
) -> ModelDelegationReceipt {
ModelDelegationReceipt {
parent_chain_len,
attenuation_axis,
signed_at,
nonce_byte,
}
}
impl ModelDelegationReceipt {
fn canonical_class(self) -> [u8; 4] {
[
self.parent_chain_len,
u8::from(self.attenuation_axis),
self.signed_at,
self.nonce_byte,
]
}
}
#[kani::proof]
pub fn verify_revocation_view_freshness() {
let token_revoked = kani::any::<bool>();
let ancestor_revoked = kani::any::<bool>();
let denied = revocation_snapshot_denies(token_revoked, ancestor_revoked);
assert_eq!(denied, token_revoked || ancestor_revoked);
let retry = revocation_snapshot_denies(token_revoked, ancestor_revoked);
assert_eq!(retry, denied);
}
#[kani::proof]
pub fn verify_oracle_inclusion_soundness() {
let leaf_present = kani::any::<bool>();
let chain_hashes_to_root = kani::any::<bool>();
let verifier_accepts = guard_pipeline_allows(
leaf_present,
&[if chain_hashes_to_root {
GuardStep::Allow
} else {
GuardStep::Deny
}],
);
assert_eq!(verifier_accepts, leaf_present && chain_hashes_to_root);
assert!(
receipt_fields_coupled(
leaf_present,
chain_hashes_to_root,
verifier_accepts,
true,
true
) || !verifier_accepts
);
let retry = guard_pipeline_allows(
leaf_present,
&[if chain_hashes_to_root {
GuardStep::Allow
} else {
GuardStep::Deny
}],
);
assert_eq!(retry, verifier_accepts);
}