use crate::layer0::gtime::{DEFAULT_G_TIME_LOCALE, LEGACY_G_TIME_PREFIX};
#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub const CLM_SCHEMA_PCARD_DESCRIPTOR_V1: &str =
crate::layer0::vocabulary::HANDLE_CLM_LAYER1_PCARD_DESCRIPTOR_V1;
pub const CLM_SCHEMA_DIRECTORY_MANIFEST_V1: &str =
crate::layer0::vocabulary::HANDLE_CLM_LAYER2_DIRECTORY_MANIFEST_V1;
pub const CLM_SCHEMA_CHUNK_MANIFEST_V1: &str =
crate::layer0::vocabulary::HANDLE_CLM_LAYER2_CHUNK_MANIFEST_V1;
pub const CLM_SCHEMA_PRUNING_ANCHOR_V1: &str =
crate::layer0::vocabulary::HANDLE_CLM_LAYER2_PRUNING_ANCHOR_V1;
pub const CLM_SCHEMA_CONVERSATIONAL_TURN_V1: &str =
crate::layer0::vocabulary::HANDLE_CLM_LAYER4_CONVERSATIONAL_TURN_V1;
pub fn normalize_schema_uri(uri: &str) -> String {
match uri {
crate::layer0::vocabulary::HANDLE_MCARD_SCHEMAS_CONVERSATIONAL_TURN_V1 => {
CLM_SCHEMA_CONVERSATIONAL_TURN_V1.to_string()
}
_ => uri.to_string(),
}
}
pub fn is_valid_clm_schema_uri(uri: &str) -> bool {
let Some(rest) = uri.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_LAYER) else {
return false;
};
let Some((layer, rest)) = rest.split_once('/') else {
return false;
};
if layer.len() != 1 || !layer.as_bytes()[0].is_ascii_digit() || layer.as_bytes()[0] > b'5' {
return false;
}
let Some((artifact, version)) = rest.rsplit_once("/v") else {
return false;
};
!artifact.is_empty()
&& artifact
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
&& !version.is_empty()
&& version.chars().all(|c| c.is_ascii_digit())
}
pub fn validate_schema_fields(
schema: Option<&str>,
schema_uri: Option<&str>,
) -> Result<(), String> {
if let (Some(schema), Some(schema_uri)) = (schema, schema_uri) {
if normalize_schema_uri(schema) != normalize_schema_uri(schema_uri) {
return Err(format!("Schema mismatch: {schema} vs {schema_uri}"));
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct MCardRecord {
pub hash: String,
pub content: Vec<u8>,
#[serde(alias = "gTime")]
pub g_time: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordVerification {
DeclaredOk {
algorithm: String,
},
DeclaredMismatch {
algorithm: String,
computed_hash: String,
},
LegacyClassified {
algorithm: String,
},
LegacyUnclassified,
LegacyAmbiguous,
Malformed {
reason: String,
},
}
fn valid_timestamp(timestamp: &str) -> bool {
timestamp == timestamp.trim()
&& crate::layer0::gtime::normalize_g_time_timestamp(timestamp).is_ok()
}
impl MCardRecord {
pub fn create(content: &[u8], algorithm: Option<&str>) -> Result<Self, String> {
Self::create_at(content, algorithm, None, DEFAULT_G_TIME_LOCALE)
}
pub fn create_at(
content: &[u8],
algorithm: Option<&str>,
timestamp: Option<&str>,
locale: &str,
) -> Result<Self, String> {
let selected = algorithm
.unwrap_or(crate::hash::config().active_algorithm)
.trim()
.trim_end_matches(':')
.to_lowercase();
let hash = crate::hash::raw_hash_bytes_for(&selected, content)?;
let g_time = match timestamp {
Some(value) => {
crate::layer0::gtime::format_canonical_g_time(&selected, value, locale, None)
}
None => crate::layer0::gtime::stamp_g_time(&selected, None, Some(locale), None),
};
Ok(Self {
hash,
content: content.to_vec(),
g_time,
})
}
}
pub fn create_record(content: &[u8], algorithm: Option<&str>) -> Result<MCardRecord, String> {
MCardRecord::create(content, algorithm)
}
pub fn verify_record(record: &MCardRecord) -> RecordVerification {
if record.hash.trim().is_empty() || record.g_time.trim().is_empty() {
return RecordVerification::Malformed {
reason: "empty hash or g_time".to_string(),
};
}
let (hash_prefix, target_hash) = match record.hash.split_once(':') {
Some((prefix, raw)) if prefix == prefix.trim() => (
Some(crate::layer0::gtime::canonical_algorithm_name(prefix)),
raw.to_lowercase(),
),
Some(_) => {
return RecordVerification::Malformed {
reason: "invalid hash prefix".to_string(),
};
}
None => (None, record.hash.to_lowercase()),
};
let is_pipe = record.g_time.contains('|');
if is_pipe || record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
if let crate::layer0::gtime::ParsedGTime::Malformed(error) =
crate::layer0::gtime::parse_g_time(&record.g_time)
{
return RecordVerification::Malformed {
reason: error.reason,
};
}
}
if is_pipe {
let mut parts = record.g_time.split('|');
let algorithm =
crate::layer0::gtime::canonical_algorithm_name(parts.next().unwrap_or_default());
let timestamp = parts.next().unwrap_or_default().trim();
let locale = parts.next();
if algorithm.is_empty() || locale.is_none() || !valid_timestamp(timestamp) {
return RecordVerification::Malformed {
reason: "invalid canonical pipe g_time".to_string(),
};
}
if hash_prefix
.as_deref()
.is_some_and(|prefix| prefix != algorithm)
{
return RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: String::new(),
};
}
let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
Ok(value) => value,
Err(reason) => return RecordVerification::Malformed { reason },
};
return if computed == target_hash {
RecordVerification::DeclaredOk { algorithm }
} else {
RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: computed,
}
};
}
if record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
let mut fields = HashMap::new();
for segment in record.g_time.split(';') {
let Some((key, value)) = segment.split_once(':') else {
return RecordVerification::Malformed {
reason: "invalid legacy TypeScript g_time segment".to_string(),
};
};
if fields.insert(key, value).is_some() {
return RecordVerification::Malformed {
reason: "duplicate legacy TypeScript g_time key".to_string(),
};
}
}
let algorithm = crate::layer0::gtime::canonical_algorithm_name(
fields.get("a").copied().unwrap_or_default(),
);
let timestamp = fields.get("t").copied().unwrap_or_default();
if algorithm.is_empty() || !valid_timestamp(timestamp) {
return RecordVerification::Malformed {
reason: "invalid legacy TypeScript g_time coordinates".to_string(),
};
}
if hash_prefix
.as_deref()
.is_some_and(|prefix| prefix != algorithm)
{
return RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: String::new(),
};
}
let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
Ok(value) => value,
Err(reason) => return RecordVerification::Malformed { reason },
};
return if computed == target_hash {
RecordVerification::DeclaredOk { algorithm }
} else {
RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: computed,
}
};
}
if !valid_timestamp(record.g_time.trim()) {
return RecordVerification::Malformed {
reason: "unrecognized g_time shape".to_string(),
};
}
let mut matches = Vec::new();
for prefix in crate::hash::list_algorithms() {
let algorithm = prefix.trim_end_matches(':');
if let Ok(computed) = crate::hash::raw_hash_bytes_for(algorithm, &record.content) {
if computed == target_hash {
matches.push(algorithm.to_string());
}
}
}
match matches.len() {
1 => RecordVerification::LegacyClassified {
algorithm: matches.remove(0),
},
n if n > 1 => RecordVerification::LegacyAmbiguous,
_ => RecordVerification::LegacyUnclassified,
}
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn write_record(
connection: &Connection,
content: &[u8],
algorithm: Option<&str>,
) -> Result<MCardRecord, String> {
let record = create_record(content, algorithm)?;
if !matches!(
verify_record(&record),
RecordVerification::DeclaredOk { .. }
) {
return Err("new Rust record did not verify before persistence".to_string());
}
let persisted_hash = crate::tape::put(connection, &record.content, &record.g_time)?;
if persisted_hash != record.hash {
return Err("tape writer changed the selected MCardRecord digest".to_string());
}
let read_back = connection
.query_row(
"SELECT hash, content, g_time FROM card WHERE hash = ?1",
[&record.hash],
|row| {
Ok(MCardRecord {
hash: row.get(0)?,
content: row.get(1)?,
g_time: row.get(2)?,
})
},
)
.map_err(|error| format!("failed to read back MCardRecord: {error}"))?;
match verify_record(&read_back) {
RecordVerification::DeclaredOk { .. } => Ok(read_back),
verdict => Err(format!(
"persisted MCardRecord failed verification: {verdict:?}"
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
fn decode_b64url(input: &str) -> Vec<u8> {
let mut buf: u32 = 0;
let mut bits: u32 = 0;
let mut out = Vec::with_capacity((input.len() * 3) / 4);
for b in input.bytes() {
let val: u32 = match b {
b'A'..=b'Z' => (b - b'A') as u32,
b'a'..=b'z' => (b - b'a' + 26) as u32,
b'0'..=b'9' => (b - b'0' + 52) as u32,
b'-' => 62,
b'_' => 63,
_ => panic!("invalid base64url byte {b}"),
};
buf = (buf << 6) | val;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(((buf >> bits) & 0xff) as u8);
}
}
out
}
fn encode_vcard_signing_bytes(
expression: &str,
subject_uri: &str,
subject_hash: &str,
snapshot_digest: &str,
signer: &str,
) -> Vec<u8> {
let mut out = Vec::from(&b"CLM-VCARD-1\0"[..]);
for field in [
expression,
subject_uri,
subject_hash,
snapshot_digest,
signer,
] {
let bytes = field.as_bytes();
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
out.extend_from_slice(bytes);
}
out
}
fn verification_status_label(verdict: &RecordVerification) -> &'static str {
match verdict {
RecordVerification::DeclaredOk { .. } => "declared-ok",
RecordVerification::DeclaredMismatch { .. } => "declared-mismatch",
RecordVerification::LegacyClassified { .. } => "legacy-classified",
RecordVerification::LegacyUnclassified => "legacy-unclassified",
RecordVerification::LegacyAmbiguous => "legacy-ambiguous",
RecordVerification::Malformed { .. } => "malformed",
}
}
#[test]
fn verifies_cross_runtime_inv609_golden_vectors_fail_closed() {
let raw = include_str!("../../../../tests/golden/vcard_signature_and_snapshot_v1.json");
let doc: serde_json::Value = serde_json::from_str(raw).expect("parse golden json");
for vec in doc["snapshot_vectors"]
.as_array()
.expect("snapshot_vectors")
{
let snap_b64 = vec["snapshot_base64url"].as_str().unwrap();
let wire = decode_b64url(snap_b64);
assert_eq!(hex::encode(&wire), vec["wire_hex"].as_str().unwrap());
assert!(wire.len() >= 2 && wire[0] == 1);
let digest = format!("sha256:{}", hex::encode(Sha256::digest(&wire)));
assert_eq!(digest, vec["snapshot_digest"].as_str().unwrap());
}
assert_ne!(
doc["map_collision_pair"]["digest_ba"].as_str().unwrap(),
doc["map_collision_pair"]["digest_ab"].as_str().unwrap(),
);
let sv = &doc["vcard_signing_vector"];
let signing_bytes = encode_vcard_signing_bytes(
sv["expression"].as_str().unwrap(),
sv["subject_uri"].as_str().unwrap(),
sv["subject_hash"].as_str().unwrap(),
sv["snapshot_digest"].as_str().unwrap(),
sv["signer_did_key"].as_str().unwrap(),
);
assert_eq!(
hex::encode(&signing_bytes),
sv["signing_bytes_hex"].as_str().unwrap()
);
let pub_bytes: [u8; 32] = hex::decode(sv["signer_pubkey_hex"].as_str().unwrap())
.unwrap()
.try_into()
.unwrap();
let sig_bytes: [u8; 64] = decode_b64url(sv["signature_base64url"].as_str().unwrap())
.try_into()
.unwrap();
let verifying_key = VerifyingKey::from_bytes(&pub_bytes).expect("valid ed25519 pubkey");
let sig = Signature::from_bytes(&sig_bytes);
verifying_key
.verify(&signing_bytes, &sig)
.expect("signature verifies");
let mut tampered = signing_bytes.clone();
tampered.push(0);
assert!(verifying_key.verify(&tampered, &sig).is_err());
for cas_vec in doc["content_address_vectors"]
.as_array()
.expect("cas vectors")
{
let record = MCardRecord {
hash: cas_vec["hash"].as_str().unwrap().to_string(),
content: hex::decode(cas_vec["content_hex"].as_str().unwrap()).unwrap(),
g_time: cas_vec["g_time"].as_str().unwrap().to_string(),
};
let verdict = verify_record(&record);
let label = verification_status_label(&verdict);
assert_eq!(label, cas_vec["expected_status"].as_str().unwrap());
let authoritative = matches!(verdict, RecordVerification::DeclaredOk { .. });
assert_eq!(
authoritative,
cas_vec["authoritative_for_commit"].as_bool().unwrap()
);
}
}
}