Skip to main content

clm_rust_core/
auth_did.rs

1//! Native DID Auth — Ed25519 Challenge-Response with VCard Authorization Tokens
2//! Offline O(1) signature verification and VCard authorization token minting.
3
4use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
5use rand::RngCore;
6use serde::{Deserialize, Serialize};
7use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct ChallengeRecord {
11    pub did: String,
12    pub nonce: String,
13    pub challenge: String,
14    pub timestamp: String,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct AuthTokenRecord {
19    pub session_id: String,
20    pub handle: String,
21    pub bound_did: String,
22    pub expiry: String,
23    pub content_hash: String,
24}
25
26/// Generates a cryptographic nonce and challenge for a given DID.
27pub fn generate_auth_challenge(did: &str) -> ChallengeRecord {
28    let mut nonce_bytes = [0u8; 32];
29    rand::thread_rng().fill_bytes(&mut nonce_bytes);
30    let nonce = hex::encode(nonce_bytes);
31    let now = chrono::Utc::now().to_rfc3339();
32    let challenge = format!("clm_challenge:{}:{}", did, nonce);
33
34    ChallengeRecord {
35        did: did.to_string(),
36        nonce,
37        challenge,
38        timestamp: now,
39    }
40}
41
42/// Signs a challenge string using an Ed25519 private key hex string.
43pub fn sign_auth_challenge(challenge_text: &str, private_key_hex: &str) -> Result<String, String> {
44    let priv_bytes = hex::decode(private_key_hex).map_err(|e| format!("Invalid hex private key: {}", e))?;
45    let key_arr: [u8; 32] = priv_bytes.try_into().map_err(|_| "Private key must be exactly 32 bytes".to_string())?;
46
47    let signing_key = SigningKey::from_bytes(&key_arr);
48    let sig = signing_key.sign(challenge_text.as_bytes());
49
50    Ok(hex::encode(sig.to_bytes()))
51}
52
53/// Verifies an Ed25519 challenge signature against a Base58btc public key in O(1) time.
54pub fn verify_auth_challenge(
55    _did: &str,
56    public_key_bs58: &str,
57    challenge_text: &str,
58    signature_hex: &str,
59) -> Result<bool, String> {
60    let pub_bytes = bs58::decode(public_key_bs58).into_vec().map_err(|e| format!("Invalid base58 public key: {}", e))?;
61    let pub_arr: [u8; 32] = pub_bytes.try_into().map_err(|_| "Public key must be exactly 32 bytes".to_string())?;
62
63    let verifying_key = VerifyingKey::from_bytes(&pub_arr).map_err(|e| format!("Invalid Ed25519 public key bytes: {}", e))?;
64
65    let sig_bytes = hex::decode(signature_hex).map_err(|e| format!("Invalid hex signature: {}", e))?;
66    let sig_arr: [u8; 64] = sig_bytes.try_into().map_err(|_| "Signature must be exactly 64 bytes".to_string())?;
67
68    let signature = Signature::from_bytes(&sig_arr);
69
70    match verifying_key.verify(challenge_text.as_bytes(), &signature) {
71        Ok(_) => Ok(true),
72        Err(_) => Ok(false),
73    }
74}
75
76/// Mints a VCard authorization token stored under `mcard:auth/token/{session_id}` upon successful auth.
77pub fn mint_vcard_auth_token(
78    db_name_or_path: &str,
79    clm_root: Option<&str>,
80    did: &str,
81    expiry_secs: u64,
82) -> Result<AuthTokenRecord, String> {
83    let mut sess_bytes = [0u8; 16];
84    rand::thread_rng().fill_bytes(&mut sess_bytes);
85    let session_id = format!("sess_{}", hex::encode(sess_bytes));
86
87    let expiry_dt = chrono::Utc::now() + chrono::Duration::seconds(expiry_secs as i64);
88    let expiry_iso = expiry_dt.to_rfc3339();
89
90    let handle = format!("mcard:auth/token/{}", session_id);
91    let content_json = serde_json::json!({
92        "bound_did": did,
93        "expiry": expiry_iso,
94        "session_id": session_id,
95    }).to_string();
96
97    let content_hash = crate::auth_namespace::mint_auth_mcard(db_name_or_path, clm_root, &handle, &content_json)?;
98
99    Ok(AuthTokenRecord {
100        session_id,
101        handle,
102        bound_did: did.to_string(),
103        expiry: expiry_iso,
104        content_hash,
105    })
106}
107
108/// Verifies if a session token under `mcard:auth/token/{session_id}` is active and unexpired.
109pub fn verify_vcard_auth_token(
110    db_name_or_path: &str,
111    clm_root: Option<&str>,
112    session_id: &str,
113) -> Result<bool, String> {
114    let handle = format!("mcard:auth/token/{}", session_id);
115    let db_path = if Path::new(db_name_or_path).is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
116        PathBuf::from(db_name_or_path)
117    } else {
118        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
119            std::env::var("CLM_ROOT").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
120        });
121        root.join("db").join(db_name_or_path)
122    };
123
124    if !db_path.exists() {
125        return Ok(false);
126    }
127
128    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
129    let _ = conn.execute_batch("PRAGMA busy_timeout = 5000;");
130    let query = if conn.query_row(
131        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
132        [],
133        |r| r.get(0),
134    ).unwrap_or(false) {
135        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.current_hash WHERE h.handle = ?1;"
136    } else {
137        "SELECT c.content FROM card c JOIN handle_registry h ON c.hash = h.hash WHERE h.handle = ?1;"
138    };
139    let content: String = match conn.query_row(
140        query,
141        rusqlite::params![handle],
142        |row| row.get(0),
143    ) {
144        Ok(c) => c,
145        Err(_) => return Ok(false),
146    };
147
148    let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
149    let expiry_str = v.get("expiry").and_then(|x| x.as_str()).ok_or("Missing expiry in token")?;
150
151    let expiry_dt = chrono::DateTime::parse_from_rfc3339(expiry_str).map_err(|e| e.to_string())?;
152    let now = chrono::Utc::now();
153
154    Ok(expiry_dt > now)
155}
156
157// ── Unit Tests ─────────────────────────────────────────────────────────────────
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn test_challenge_sign_verify_roundtrip() {
165        let identity = crate::identity::generate_ed25519_keypair().unwrap();
166        let challenge = generate_auth_challenge(&identity.did);
167
168        let signature = sign_auth_challenge(&challenge.challenge, &identity.private_key_hex).unwrap();
169        assert!(!signature.is_empty());
170
171        let is_valid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, &challenge.challenge, &signature).unwrap();
172        assert!(is_valid);
173
174        let is_invalid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, "corrupted_challenge", &signature).unwrap();
175        assert!(!is_invalid);
176    }
177
178    #[test]
179    fn test_vcard_token_mint_and_verify() {
180        let tmp_db = std::env::temp_dir().join("clm_test_vcard_token.db");
181        let _ = std::fs::remove_file(&tmp_db);
182        let db_str = tmp_db.to_str().unwrap();
183
184        let identity = crate::identity::generate_ed25519_keypair().unwrap();
185        let token = mint_vcard_auth_token(db_str, None, &identity.did, 3600).unwrap();
186
187        assert!(token.handle.starts_with("mcard:auth/token/sess_"));
188
189        let is_valid = verify_vcard_auth_token(db_str, None, &token.session_id).unwrap();
190        assert!(is_valid);
191
192        let _ = std::fs::remove_file(&tmp_db);
193    }
194}