coreason_engine/
governance.rs1use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13#[derive(Debug, Deserialize, Serialize, Clone)]
14pub struct Claims {
15 pub sub: String,
16 pub iat: Option<u64>,
17 pub exp: Option<u64>,
18 pub tenant_cid: Option<String>,
19 pub entitlements: Option<Vec<String>>,
20}
21
22fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
23 (0..s.len())
24 .step_by(2)
25 .map(|i| {
26 u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| format!("Failed to parse hex: {}", e))
27 })
28 .collect()
29}
30
31pub fn verify_token_signature(jwt_string: &str, root_ca_key: &str) -> Result<Value, String> {
33 let _ = jsonwebtoken::crypto::rust_crypto::DEFAULT_PROVIDER.install_default();
34 let root_ca_key = root_ca_key.trim();
35 if root_ca_key.is_empty() {
36 return Err("Public key is empty".to_string());
37 }
38
39 let decoding_key = if root_ca_key.contains("-----BEGIN PUBLIC KEY-----") {
40 DecodingKey::from_ed_pem(root_ca_key.as_bytes())
41 .map_err(|e| format!("Invalid PEM public key: {}", e))?
42 } else if root_ca_key.len() == 64 && root_ca_key.chars().all(|c| c.is_ascii_hexdigit()) {
43 let raw_bytes = decode_hex(root_ca_key)?;
44 if raw_bytes.len() != 32 {
45 return Err("Hex public key must be exactly 32 bytes".to_string());
46 }
47 let mut der_key = vec![
48 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
49 ];
50 der_key.extend_from_slice(&raw_bytes);
51 DecodingKey::from_ed_der(&der_key)
52 } else {
53 return Err("Failed to parse public key as PEM or hex".to_string());
54 };
55
56 let mut validation = Validation::new(Algorithm::EdDSA);
57 validation.validate_aud = false;
58 validation.required_spec_claims.remove("exp");
59
60 let token_data = decode::<Value>(jwt_string, &decoding_key, &validation)
61 .map_err(|e| format!("Malformed or invalid token: {}", e))?;
62
63 Ok(token_data.claims)
64}
65
66pub fn compute_epistemic_root(project_path: &str, version: &str) -> Result<String, String> {
67 Ok(format!("epistemic-root-{}-{}", project_path, version))
68}