clm-kernel 0.0.9

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Native DID Auth — Ed25519 Challenge-Response with VCard Authorization Tokens
//! Offline O(1) signature verification and VCard authorization token minting.

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChallengeRecord {
    pub did: String,
    pub nonce: String,
    pub challenge: String,
    pub timestamp: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthTokenRecord {
    pub session_id: String,
    pub handle: String,
    pub bound_did: String,
    pub expiry: String,
    pub content_hash: String,
}

/// Generates a cryptographic nonce and challenge for a given DID.
pub fn generate_auth_challenge(did: &str) -> ChallengeRecord {
    let mut nonce_bytes = [0u8; 32];
    rand::thread_rng().fill_bytes(&mut nonce_bytes);
    let nonce = hex::encode(nonce_bytes);
    let now = chrono::Utc::now().to_rfc3339();
    let challenge = format!("clm_challenge:{}:{}", did, nonce);

    ChallengeRecord {
        did: did.to_string(),
        nonce,
        challenge,
        timestamp: now,
    }
}

/// Signs a challenge string using an Ed25519 private key hex string.
pub fn sign_auth_challenge(challenge_text: &str, private_key_hex: &str) -> Result<String, String> {
    let priv_bytes = hex::decode(private_key_hex).map_err(|e| format!("Invalid hex private key: {}", e))?;
    let key_arr: [u8; 32] = priv_bytes.try_into().map_err(|_| "Private key must be exactly 32 bytes".to_string())?;

    let signing_key = SigningKey::from_bytes(&key_arr);
    let sig = signing_key.sign(challenge_text.as_bytes());

    Ok(hex::encode(sig.to_bytes()))
}

/// Verifies an Ed25519 challenge signature against a Base58btc public key in O(1) time.
pub fn verify_auth_challenge(
    _did: &str,
    public_key_bs58: &str,
    challenge_text: &str,
    signature_hex: &str,
) -> Result<bool, String> {
    let pub_bytes = bs58::decode(public_key_bs58).into_vec().map_err(|e| format!("Invalid base58 public key: {}", e))?;
    let pub_arr: [u8; 32] = pub_bytes.try_into().map_err(|_| "Public key must be exactly 32 bytes".to_string())?;

    let verifying_key = VerifyingKey::from_bytes(&pub_arr).map_err(|e| format!("Invalid Ed25519 public key bytes: {}", e))?;

    let sig_bytes = hex::decode(signature_hex).map_err(|e| format!("Invalid hex signature: {}", e))?;
    let sig_arr: [u8; 64] = sig_bytes.try_into().map_err(|_| "Signature must be exactly 64 bytes".to_string())?;

    let signature = Signature::from_bytes(&sig_arr);

    match verifying_key.verify(challenge_text.as_bytes(), &signature) {
        Ok(_) => Ok(true),
        Err(_) => Ok(false),
    }
}

/// Mints a VCard authorization token stored under `mcard:auth/token/{session_id}` upon successful auth.
pub fn mint_vcard_auth_token(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    did: &str,
    expiry_secs: u64,
) -> Result<AuthTokenRecord, String> {
    let mut sess_bytes = [0u8; 16];
    rand::thread_rng().fill_bytes(&mut sess_bytes);
    let session_id = format!("sess_{}", hex::encode(sess_bytes));

    let expiry_dt = chrono::Utc::now() + chrono::Duration::seconds(expiry_secs as i64);
    let expiry_iso = expiry_dt.to_rfc3339();

    let handle = format!("mcard:auth/token/{}", session_id);
    let content_json = serde_json::json!({
        "bound_did": did,
        "expiry": expiry_iso,
        "session_id": session_id,
    }).to_string();

    let content_hash = crate::auth_namespace::mint_auth_mcard(db_name_or_path, clm_root, &handle, &content_json)?;

    Ok(AuthTokenRecord {
        session_id,
        handle,
        bound_did: did.to_string(),
        expiry: expiry_iso,
        content_hash,
    })
}

/// Verifies if a session token under `mcard:auth/token/{session_id}` is active and unexpired.
pub fn verify_vcard_auth_token(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    session_id: &str,
) -> Result<bool, String> {
    let handle = format!("mcard:auth/token/{}", session_id);
    let db_path = if Path::new(db_name_or_path).is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
        PathBuf::from(db_name_or_path)
    } else {
        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
            std::env::var("CLM_ROOT").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
        });
        root.join("db").join(db_name_or_path)
    };

    if !db_path.exists() {
        return Ok(false);
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    let content: String = match conn.query_row(
        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;",
        rusqlite::params![handle],
        |row| row.get(0),
    ) {
        Ok(c) => c,
        Err(_) => return Ok(false),
    };

    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
    let expiry_str = v.get("expiry").and_then(|x| x.as_str()).ok_or("Missing expiry in token")?;

    let expiry_dt = chrono::DateTime::parse_from_rfc3339(expiry_str).map_err(|e| e.to_string())?;
    let now = chrono::Utc::now();

    Ok(expiry_dt > now)
}

// ── Unit Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_challenge_sign_verify_roundtrip() {
        let identity = crate::identity::generate_ed25519_keypair().unwrap();
        let challenge = generate_auth_challenge(&identity.did);

        let signature = sign_auth_challenge(&challenge.challenge, &identity.private_key_hex).unwrap();
        assert!(!signature.is_empty());

        let is_valid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, &challenge.challenge, &signature).unwrap();
        assert!(is_valid);

        let is_invalid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, "corrupted_challenge", &signature).unwrap();
        assert!(!is_invalid);
    }

    #[test]
    fn test_vcard_token_mint_and_verify() {
        let tmp_db = std::env::temp_dir().join("clm_test_vcard_token.db");
        let _ = std::fs::remove_file(&tmp_db);
        let db_str = tmp_db.to_str().unwrap();

        let identity = crate::identity::generate_ed25519_keypair().unwrap();
        let token = mint_vcard_auth_token(db_str, None, &identity.did, 3600).unwrap();

        assert!(token.handle.starts_with("mcard:auth/token/sess_"));

        let is_valid = verify_vcard_auth_token(db_str, None, &token.session_id).unwrap();
        assert!(is_valid);

        let _ = std::fs::remove_file(&tmp_db);
    }
}