use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Claims {
pub sub: String,
pub iat: Option<u64>,
pub exp: Option<u64>,
pub tenant_cid: Option<String>,
pub entitlements: Option<Vec<String>>,
}
fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
(0..s.len())
.step_by(2)
.map(|i| {
u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| format!("Failed to parse hex: {}", e))
})
.collect()
}
pub fn verify_token_signature(jwt_string: &str, root_ca_key: &str) -> Result<Value, String> {
let _ = jsonwebtoken::crypto::rust_crypto::DEFAULT_PROVIDER.install_default();
let root_ca_key = root_ca_key.trim();
if root_ca_key.is_empty() {
return Err("Public key is empty".to_string());
}
let decoding_key = if root_ca_key.contains("-----BEGIN PUBLIC KEY-----") {
DecodingKey::from_ed_pem(root_ca_key.as_bytes())
.map_err(|e| format!("Invalid PEM public key: {}", e))?
} else if root_ca_key.len() == 64 && root_ca_key.chars().all(|c| c.is_ascii_hexdigit()) {
let raw_bytes = decode_hex(root_ca_key)?;
if raw_bytes.len() != 32 {
return Err("Hex public key must be exactly 32 bytes".to_string());
}
let mut der_key = vec![
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
];
der_key.extend_from_slice(&raw_bytes);
DecodingKey::from_ed_der(&der_key)
} else {
return Err("Failed to parse public key as PEM or hex".to_string());
};
let mut validation = Validation::new(Algorithm::EdDSA);
validation.validate_aud = false;
validation.required_spec_claims.remove("exp");
let token_data = decode::<Value>(jwt_string, &decoding_key, &validation)
.map_err(|e| format!("Malformed or invalid token: {}", e))?;
Ok(token_data.claims)
}
pub fn compute_epistemic_root(project_path: &str, version: &str) -> Result<String, String> {
Ok(format!("epistemic-root-{}-{}", project_path, version))
}