Skip to main content

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