clm-kernel 0.0.15

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Reserved MCard Namespace for Auth Configuration (`mcard:auth/*`)
//! Gerunds freezing authentication processes (OAuth 2.0, OIDC, provider configs, blockchain auth, DID methods, session tokens).

use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};

pub const RESERVED_PREFIX: &str = "mcard:auth/";

/// Returns true if the given handle belongs to the reserved auth MCard namespace.
pub fn is_reserved_auth_handle(handle: &str) -> bool {
    handle.starts_with(RESERVED_PREFIX)
}

/// Infers the auth_type category from a reserved handle string.
pub fn infer_auth_type_from_handle(handle: &str) -> Result<String, String> {
    if !is_reserved_auth_handle(handle) {
        return Err(format!("Handle '{}' is not in the reserved auth namespace 'mcard:auth/'", handle));
    }
    let sub = handle.trim_start_matches(RESERVED_PREFIX);
    if sub.starts_with("oauth2/") {
        Ok("oauth2".to_string())
    } else if sub.starts_with("oidc/") {
        Ok("oidc".to_string())
    } else if sub.starts_with("provider/") {
        Ok("provider".to_string())
    } else if sub.starts_with("blockchain/") {
        Ok("blockchain".to_string())
    } else if sub.starts_with("did/method/") {
        Ok("did".to_string())
    } else if sub.starts_with("token/") {
        Ok("token".to_string())
    } else {
        Err(format!("Unknown reserved auth handle pattern: '{}'", handle))
    }
}

/// Validates JSON content schema for a given auth_type category.
pub fn validate_auth_config_schema(auth_type: &str, content_json: &str) -> Result<(), String> {
    let v: Value = serde_json::from_str(content_json)
        .map_err(|e| format!("Invalid JSON for auth config content: {}", e))?;

    match auth_type {
        "oauth2" => {
            if v.get("client_id").is_none() || v.get("redirect_uris").is_none() {
                return Err("OAuth2 config schema requires 'client_id' and 'redirect_uris'".to_string());
            }
        }
        "oidc" => {
            if v.get("issuer_url").is_none() || v.get("jwks_uri").is_none() {
                return Err("OIDC discovery schema requires 'issuer_url' and 'jwks_uri'".to_string());
            }
        }
        "provider" => {
            if v.get("provider_endpoint").is_none() || v.get("token_signing_keys").is_none() {
                return Err("Provider config schema requires 'provider_endpoint' and 'token_signing_keys'".to_string());
            }
        }
        "blockchain" => {
            if v.get("chain_id").is_none() || v.get("contract_addresses").is_none() {
                return Err("Blockchain config schema requires 'chain_id' and 'contract_addresses'".to_string());
            }
        }
        "did" => {
            if v.get("method_name").is_none() || v.get("verification_keys").is_none() {
                return Err("DID method schema requires 'method_name' and 'verification_keys'".to_string());
            }
        }
        "token" => {
            if v.get("bound_did").is_none() || v.get("expiry").is_none() {
                return Err("Token schema requires 'bound_did' and 'expiry'".to_string());
            }
        }
        other => return Err(format!("Unsupported auth_type category: '{}'", other)),
    }

    Ok(())
}

fn resolve_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
    let p = Path::new(db_name_or_path);
    if p.is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
        p.to_path_buf()
    } 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)
    }
}

/// Mints a reserved auth MCard, validating handle reservation & schema, and registering into SQLite.
pub fn mint_auth_mcard(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    handle: &str,
    content_json: &str,
) -> Result<String, String> {
    if !is_reserved_auth_handle(handle) {
        return Err(format!("Handle '{}' does not belong to reserved auth namespace 'mcard:auth/'", handle));
    }

    let auth_type = infer_auth_type_from_handle(handle)?;
    validate_auth_config_schema(&auth_type, content_json)?;

    let hash = crate::hash::raw_hash_bytes(content_json.as_bytes());
    let db_path = resolve_db_path(db_name_or_path, clm_root);

    if let Some(parent) = db_path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    let _ = conn.execute_batch("PRAGMA busy_timeout = 5000;");

    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS card (hash TEXT PRIMARY KEY, content TEXT, g_time TEXT);
         CREATE TABLE IF NOT EXISTS handle_registry (
             handle TEXT PRIMARY KEY,
             current_hash TEXT NOT NULL,
             updated_at TEXT NOT NULL
         );",
    ).map_err(|e| e.to_string())?;

    // Idempotent migration from legacy `hash` column
    let has_hash: bool = conn
        .query_row(
            "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'hash'",
            [],
            |r| r.get(0),
        )
        .unwrap_or(false);
    if has_hash {
        let has_curr: bool = conn
            .query_row(
                "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
                [],
                |r| r.get(0),
            )
            .unwrap_or(false);
        if !has_curr {
            let _ = conn.execute_batch("ALTER TABLE handle_registry RENAME COLUMN hash TO current_hash;");
        }
    }

    let now = chrono::Utc::now().to_rfc3339();

    conn.execute(
        "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
        rusqlite::params![hash, content_json, now],
    ).map_err(|e| e.to_string())?;

    conn.execute(
        "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3);",
        rusqlite::params![handle, hash, now],
    ).map_err(|e| e.to_string())?;

    Ok(hash)
}

/// Lists all registered `mcard:auth/*` handles matching a pattern in the database.
pub fn list_auth_mcards(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    pattern: &str,
) -> Result<Vec<(String, String)>, String> {
    let db_path = resolve_db_path(db_name_or_path, clm_root);
    if !db_path.exists() {
        return Ok(Vec::new());
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    let like_pattern = format!("mcard:auth/%{}%", pattern);

    let query = if conn.query_row(
        "SELECT count(*) > 0 FROM pragma_table_info('handle_registry') WHERE name = 'current_hash'",
        [],
        |r| r.get(0),
    ).unwrap_or(false) {
        "SELECT handle, current_hash FROM handle_registry WHERE handle LIKE ?1;"
    } else {
        "SELECT handle, hash FROM handle_registry WHERE handle LIKE ?1;"
    };
    let mut stmt = conn.prepare(query).map_err(|e| e.to_string())?;
    let rows = stmt.query_map(rusqlite::params![like_pattern], |row| Ok((row.get(0)?, row.get(1)?))).map_err(|e| e.to_string())?;

    let mut result = Vec::new();
    for item in rows.flatten() {
        result.push(item);
    }
    Ok(result)
}

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

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

    #[test]
    fn test_reserved_auth_handle_inference() {
        assert!(is_reserved_auth_handle("mcard:auth/provider/zitadel"));
        assert!(!is_reserved_auth_handle("mcard:user/profile"));

        assert_eq!(infer_auth_type_from_handle("mcard:auth/oauth2/config").unwrap(), "oauth2");
        assert_eq!(infer_auth_type_from_handle("mcard:auth/oidc/discovery").unwrap(), "oidc");
        assert_eq!(infer_auth_type_from_handle("mcard:auth/provider/keycloak").unwrap(), "provider");
        assert_eq!(infer_auth_type_from_handle("mcard:auth/blockchain/eth_mainnet").unwrap(), "blockchain");
        assert_eq!(infer_auth_type_from_handle("mcard:auth/did/method/key").unwrap(), "did");
        assert_eq!(infer_auth_type_from_handle("mcard:auth/token/sess_123").unwrap(), "token");
    }

    #[test]
    fn test_auth_config_schema_validation() {
        let valid_oauth = r#"{"client_id": "app123", "redirect_uris": ["https://app.com/callback"]}"#;
        assert!(validate_auth_config_schema("oauth2", valid_oauth).is_ok());

        let invalid_oauth = r#"{"client_id": "app123"}"#;
        assert!(validate_auth_config_schema("oauth2", invalid_oauth).is_err());
    }

    #[test]
    fn test_mint_auth_mcard_roundtrip() {
        let tmp_db = std::env::temp_dir().join("clm_test_auth_mcard.db");
        let _ = fs::remove_file(&tmp_db);

        let db_str = tmp_db.to_str().unwrap();
        let handle = "mcard:auth/provider/zitadel";
        let content = r#"{"provider_endpoint": "https://auth.zitadel.com", "token_signing_keys": ["key1"]}"#;

        let hash = mint_auth_mcard(db_str, None, handle, content).unwrap();
        assert!(!hash.is_empty());

        let list = list_auth_mcards(db_str, None, "provider").unwrap();
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].0, handle);
        assert_eq!(list[0].1, hash);

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