use crate::error::{GarrisonError, GarrisonResult};
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::time::{SystemTime, UNIX_EPOCH};
use super::{GarrisonJwtClaims, JwtHandler};
const MIN_SECRET_BYTES: usize = 32;
pub(crate) enum KeyMaterial {
Hs,
RsaPkcs1Pem(String),
EcPem(String),
EdPem(String),
}
impl KeyMaterial {
pub(crate) fn allowed_algorithms(&self) -> &'static [Algorithm] {
match self {
KeyMaterial::Hs => &[Algorithm::HS256, Algorithm::HS384, Algorithm::HS512],
KeyMaterial::RsaPkcs1Pem(_) => &[Algorithm::RS256, Algorithm::RS384, Algorithm::RS512],
KeyMaterial::EcPem(_) => &[Algorithm::ES256, Algorithm::ES384],
KeyMaterial::EdPem(_) => &[Algorithm::EdDSA],
}
}
}
impl std::fmt::Debug for KeyMaterial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KeyMaterial::Hs => write!(f, "KeyMaterial::Hs"),
KeyMaterial::RsaPkcs1Pem(_) => write!(f, "KeyMaterial::RsaPkcs1Pem(<redacted>"),
KeyMaterial::EcPem(_) => write!(f, "KeyMaterial::EcPem(<redacted>"),
KeyMaterial::EdPem(_) => write!(f, "KeyMaterial::EdPem(<redacted>"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JwkPublicKey {
Rsa {
n: String,
e: String,
},
Ec {
crv: &'static str,
x: String,
y: String,
},
Okp {
x: String,
},
}
pub(crate) fn validate_algorithm_match(
key_material: &KeyMaterial,
algorithm: Algorithm,
) -> GarrisonResult<()> {
if key_material.allowed_algorithms().contains(&algorithm) {
Ok(())
} else {
Err(GarrisonError::Config(format!(
"jwt-key-algorithm-mismatch::key={:?}::alg={:?}",
key_material, algorithm
)))
}
}
fn pem_to_der(pem: &str) -> GarrisonResult<Vec<u8>> {
use base64::Engine;
let body: String = pem
.lines()
.filter(|line| !line.starts_with("-----"))
.collect::<Vec<_>>()
.join("");
base64::engine::general_purpose::STANDARD
.decode(body.trim())
.map_err(|e| GarrisonError::Internal(format!("jwt-rsa-pem-invalid::{}", e)))
}
fn extract_rsa_public_components(pem: &str) -> GarrisonResult<(String, String)> {
use base64::Engine;
use pkcs8::der::Decode;
let der = pem_to_der(pem)?;
let key = if pem.contains("BEGIN RSA PRIVATE KEY") {
pkcs1::RsaPrivateKey::from_der(&der)
} else {
let pki = pkcs8::PrivateKeyInfo::from_der(&der)
.map_err(|e| GarrisonError::Internal(format!("jwt-rsa-pem-invalid::{}", e)))?;
pkcs1::RsaPrivateKey::from_der(pki.private_key)
}
.map_err(|e| GarrisonError::Internal(format!("jwt-rsa-pem-invalid::{}", e)))?;
let b64 = |data: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data);
Ok((
b64(key.modulus.as_bytes()),
b64(key.public_exponent.as_bytes()),
))
}
fn extract_ec_public_sec1(pem: &str) -> GarrisonResult<Vec<u8>> {
use pkcs8::der::asn1::ObjectIdentifier;
use pkcs8::der::Decode;
const OID_P256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
const OID_P384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
let der = pem_to_der(pem)?;
let pki = pkcs8::PrivateKeyInfo::from_der(&der)
.map_err(|e| GarrisonError::Internal(format!("jwt-ec-pem-invalid::{}", e)))?;
let ec = sec1::EcPrivateKey::from_der(pki.private_key)
.map_err(|e| GarrisonError::Internal(format!("jwt-ec-pem-invalid::{}", e)))?;
if let Some(pub_bytes) = ec.public_key {
return Ok(pub_bytes.to_vec());
}
let oid = pki
.algorithm
.parameters
.and_then(|any| any.decode_as::<ObjectIdentifier>().ok())
.ok_or_else(|| GarrisonError::Internal("jwt-ec-curve-missing::".to_string()))?;
if oid == OID_P256 {
let secret = p256::SecretKey::from_slice(ec.private_key)
.map_err(|e| GarrisonError::Internal(format!("jwt-ec-pem-invalid::{}", e)))?;
Ok(secret.public_key().to_sec1_bytes().to_vec())
} else if oid == OID_P384 {
let secret = p384::SecretKey::from_slice(ec.private_key)
.map_err(|e| GarrisonError::Internal(format!("jwt-ec-pem-invalid::{}", e)))?;
Ok(secret.public_key().to_sec1_bytes().to_vec())
} else {
Err(GarrisonError::Internal(format!(
"jwt-ec-curve-unsupported::{oid}"
)))
}
}
fn extract_ed25519_seed(pem: &str) -> GarrisonResult<[u8; 32]> {
use pkcs8::der::Decode;
let der = pem_to_der(pem)?;
let pki = pkcs8::PrivateKeyInfo::from_der(&der)
.map_err(|e| GarrisonError::Internal(format!("jwt-ed-pem-invalid::{}", e)))?;
let inner = pkcs8::der::asn1::OctetStringRef::from_der(pki.private_key)
.map_err(|e| GarrisonError::Internal(format!("jwt-ed-pem-invalid::{}", e)))?;
inner
.as_bytes()
.try_into()
.map_err(|_| GarrisonError::Internal("jwt-ed-seed-len::".to_string()))
}
fn rsa_decoding_key(pem: &str) -> GarrisonResult<DecodingKey> {
let (n, e) = extract_rsa_public_components(pem)?;
DecodingKey::from_rsa_components(&n, &e)
.map_err(|e| GarrisonError::Internal(format!("jwt-rsa-key::{}", e)))
}
fn ec_decoding_key(pem: &str) -> GarrisonResult<DecodingKey> {
let sec1 = extract_ec_public_sec1(pem)?;
Ok(DecodingKey::from_ec_der(&sec1))
}
fn ed_decoding_key(pem: &str) -> GarrisonResult<DecodingKey> {
use base64::Engine;
let seed = extract_ed25519_seed(pem)?;
let signing = ed25519_dalek::SigningKey::from_bytes(&seed);
let b64 = |data: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data);
DecodingKey::from_ed_components(&b64(signing.verifying_key().as_bytes()))
.map_err(|e| GarrisonError::Internal(format!("jwt-ed-key::{}", e)))
}
fn map_verify_error(e: jsonwebtoken::errors::Error) -> GarrisonError {
let msg = e.to_string();
if msg.contains("ExpiredSignature") {
GarrisonError::ExpiredToken(format!("jwt-expired::{}", e))
} else if msg.contains("ImmatureSignature") || msg.contains("nbf") {
GarrisonError::InvalidToken(format!("jwt-not-yet-valid::{}", e))
} else {
GarrisonError::InvalidToken(format!("jwt-invalid::{}", e))
}
}
fn ed_jwk_from_seed(seed: &[u8; 32]) -> JwkPublicKey {
use base64::Engine;
let signing = ed25519_dalek::SigningKey::from_bytes(seed);
JwkPublicKey::Okp {
x: base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(signing.verifying_key().as_bytes()),
}
}
fn ec_jwk_from_sec1(sec1: &[u8]) -> GarrisonResult<JwkPublicKey> {
use base64::Engine;
if sec1.first() != Some(&0x04) || sec1.len() < 3 || sec1.len().is_multiple_of(2) {
return Err(GarrisonError::Internal("jwt-ec-sec1-format::".to_string()));
}
let coord = (sec1.len() - 1) / 2;
let b64 = |data: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data);
let crv = match coord {
32 => "P-256",
48 => "P-384",
_ => {
return Err(GarrisonError::Internal(
"jwt-ec-curve-unsupported::".to_string(),
))
},
};
Ok(JwkPublicKey::Ec {
crv,
x: b64(&sec1[1..1 + coord]),
y: b64(&sec1[1 + coord..]),
})
}
impl JwtHandler {
pub fn new(secret: impl Into<String>) -> Self {
Self {
secret: secret.into(),
algorithm: Algorithm::HS256,
device: None,
key_material: KeyMaterial::Hs,
amr: None,
auth_time: None,
tid: None,
}
}
#[must_use]
pub(crate) fn with_tid(mut self, tid: i64) -> Self {
self.tid = Some(tid);
self
}
pub fn export_public_jwk_parts(&self) -> GarrisonResult<Option<JwkPublicKey>> {
match &self.key_material {
KeyMaterial::Hs => Ok(None),
KeyMaterial::RsaPkcs1Pem(pem) => {
let (n, e) = extract_rsa_public_components(pem)?;
Ok(Some(JwkPublicKey::Rsa { n, e }))
},
KeyMaterial::EcPem(pem) => {
let sec1 = extract_ec_public_sec1(pem)?;
ec_jwk_from_sec1(&sec1).map(Some)
},
KeyMaterial::EdPem(pem) => {
let seed = extract_ed25519_seed(pem)?;
Ok(Some(ed_jwk_from_seed(&seed)))
},
}
}
pub(crate) fn from_algorithm_parts(
algorithm: &str,
jwt_secret: &str,
rsa_pem: Option<&str>,
ec_pem: Option<&str>,
ed_pem: Option<&str>,
) -> GarrisonResult<Self> {
let base = JwtHandler::new(jwt_secret);
match algorithm {
"HS256" => base.try_with_algorithm(Algorithm::HS256),
"HS384" => base.try_with_algorithm(Algorithm::HS384),
"HS512" => base.try_with_algorithm(Algorithm::HS512),
"RS256" => base
.with_rsa_private_pem(rsa_pem.unwrap_or(""))
.and_then(|h| h.try_with_algorithm(Algorithm::RS256)),
"ES256" => base
.with_ec_pem(ec_pem.unwrap_or(""))
.and_then(|h| h.try_with_algorithm(Algorithm::ES256)),
"EdDSA" => base
.with_ed_pem(ed_pem.unwrap_or(""))
.and_then(|h| h.try_with_algorithm(Algorithm::EdDSA)),
other => Err(GarrisonError::Config(format!(
"config-jwt-algorithm-unsupported::{other}"
))),
}
}
pub fn try_with_algorithm(mut self, algorithm: Algorithm) -> GarrisonResult<Self> {
validate_algorithm_match(&self.key_material, algorithm)?;
self.algorithm = algorithm;
Ok(self)
}
pub fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
self.algorithm = algorithm;
self
}
pub fn with_device(mut self, device: impl Into<String>) -> Self {
self.device = Some(device.into());
self
}
pub fn with_rsa_private_pem(mut self, pem: impl Into<String>) -> GarrisonResult<Self> {
let pem = pem.into();
EncodingKey::from_rsa_pem(pem.as_bytes())
.map_err(|e| GarrisonError::Config(format!("jwt-rsa-pem-invalid::{}", e)))?;
self.key_material = KeyMaterial::RsaPkcs1Pem(pem);
Ok(self)
}
pub fn with_ec_pem(mut self, pem: impl Into<String>) -> GarrisonResult<Self> {
let pem = pem.into();
EncodingKey::from_ec_pem(pem.as_bytes())
.map_err(|e| GarrisonError::Config(format!("jwt-ec-pem-invalid::{}", e)))?;
self.key_material = KeyMaterial::EcPem(pem);
Ok(self)
}
pub fn with_ed_pem(mut self, pem: impl Into<String>) -> GarrisonResult<Self> {
let pem = pem.into();
let _parsed_ok = extract_ed25519_seed(&pem)?;
self.key_material = KeyMaterial::EdPem(pem);
Ok(self)
}
pub fn sign_with_amr(
&self,
login_id: impl Into<String>,
timeout: i64,
amr: &[String],
auth_time: Option<i64>,
) -> GarrisonResult<String> {
let handler = JwtHandler {
secret: self.secret.clone(),
algorithm: self.algorithm,
device: self.device.clone(),
key_material: match &self.key_material {
KeyMaterial::Hs => KeyMaterial::Hs,
KeyMaterial::RsaPkcs1Pem(pem) => KeyMaterial::RsaPkcs1Pem(pem.clone()),
KeyMaterial::EcPem(pem) => KeyMaterial::EcPem(pem.clone()),
KeyMaterial::EdPem(pem) => KeyMaterial::EdPem(pem.clone()),
},
amr: if amr.is_empty() {
None
} else {
Some(amr.to_vec())
},
auth_time,
tid: self.tid,
};
handler.sign(login_id, timeout)
}
pub fn sign(&self, login_id: impl Into<String>, timeout: i64) -> GarrisonResult<String> {
self.sign_with_kid(login_id, timeout, None)
}
pub fn sign_with_kid(
&self,
login_id: impl Into<String>,
timeout: i64,
kid: Option<String>,
) -> GarrisonResult<String> {
let login_id: String = login_id.into();
self.validate_hs_secret()?;
if timeout < 0 {
return Err(GarrisonError::Config(format!(
"jwt-timeout-negative::{}",
timeout
)));
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| GarrisonError::Internal(format!("system-clock-error::{}", e)))?
.as_secs() as i64;
validate_algorithm_match(&self.key_material, self.algorithm)?;
let exp = now.checked_add(timeout).ok_or_else(|| {
GarrisonError::InvalidParam(format!("jwt-timeout-overflow::{}", timeout))
})?;
let claims = GarrisonJwtClaims {
sub: login_id.clone(),
iat: now,
exp,
login_id,
device: self.device.clone(),
jti: Some(uuid::Uuid::new_v4().to_string()),
nbf: Some(now), amr: self.amr.clone(),
auth_time: self.auth_time,
tid: self.tid,
};
let header = Header {
kid,
..Header::new(self.algorithm)
};
let key = self.encoding_key()?;
encode(&header, &claims, &key)
.map_err(|e| GarrisonError::Internal(format!("jwt-sign::{}", e)))
}
fn validate_hs_secret(&self) -> GarrisonResult<()> {
if matches!(self.key_material, KeyMaterial::Hs) && self.secret.is_empty() {
return Err(GarrisonError::Config("jwt-secret-empty::".to_string()));
}
if matches!(self.key_material, KeyMaterial::Hs) && self.secret.len() < MIN_SECRET_BYTES {
return Err(GarrisonError::Config(format!(
"jwt-secret-too-short::{}::{}",
self.secret.len(),
MIN_SECRET_BYTES
)));
}
Ok(())
}
#[cfg_attr(not(any(test, feature = "backchannel-logout")), allow(dead_code))]
pub(crate) fn sign_claims<T: Serialize>(&self, claims: &T) -> GarrisonResult<String> {
self.validate_hs_secret()?;
validate_algorithm_match(&self.key_material, self.algorithm)?;
let header = Header::new(self.algorithm);
let key = self.encoding_key()?;
encode(&header, claims, &key)
.map_err(|e| GarrisonError::Internal(format!("jwt-sign-claims::{}", e)))
}
fn encoding_key(&self) -> GarrisonResult<EncodingKey> {
Ok(match &self.key_material {
KeyMaterial::Hs => EncodingKey::from_secret(self.secret.as_bytes()),
KeyMaterial::RsaPkcs1Pem(pem) => EncodingKey::from_rsa_pem(pem.as_bytes())
.map_err(|e| GarrisonError::Internal(format!("jwt-rsa-key::{}", e)))?,
KeyMaterial::EcPem(pem) => EncodingKey::from_ec_pem(pem.as_bytes())
.map_err(|e| GarrisonError::Internal(format!("jwt-ec-key::{}", e)))?,
KeyMaterial::EdPem(pem) => EncodingKey::from_ed_pem(pem.as_bytes())
.map_err(|e| GarrisonError::Internal(format!("jwt-ed-key::{}", e)))?,
})
}
fn decoding_key(&self) -> GarrisonResult<DecodingKey> {
match &self.key_material {
KeyMaterial::Hs => Ok(DecodingKey::from_secret(self.secret.as_bytes())),
KeyMaterial::RsaPkcs1Pem(pem) => rsa_decoding_key(pem),
KeyMaterial::EcPem(pem) => ec_decoding_key(pem),
KeyMaterial::EdPem(pem) => ed_decoding_key(pem),
}
}
pub(crate) fn private_pem(&self) -> Option<&str> {
match &self.key_material {
KeyMaterial::Hs => None,
KeyMaterial::RsaPkcs1Pem(pem) => Some(pem),
KeyMaterial::EcPem(pem) => Some(pem),
KeyMaterial::EdPem(pem) => Some(pem),
}
}
pub fn verify(&self, token: &str) -> GarrisonResult<GarrisonJwtClaims> {
self.validate_hs_secret()?;
validate_algorithm_match(&self.key_material, self.algorithm)?;
let key = self.decoding_key()?;
let mut validation = Validation::new(self.algorithm);
validation.validate_exp = true;
validation.validate_nbf = true;
validation.leeway = 0;
let decoded: jsonwebtoken::TokenData<GarrisonJwtClaims> =
decode(token, &key, &validation).map_err(map_verify_error)?;
Ok(decoded.claims)
}
pub fn refresh(&self, token: &str, new_timeout: i64) -> GarrisonResult<String> {
let claims = self.verify(token)?;
self.sign(claims.login_id, new_timeout)
}
pub fn sign_custom<T: serde::Serialize>(&self, claims: &T) -> GarrisonResult<String> {
self.ensure_symmetric_secret_usable()?;
validate_algorithm_match(&self.key_material, self.algorithm)?;
let header = Header::new(self.algorithm);
let key = self.encoding_key()?;
encode(&header, claims, &key)
.map_err(|e| GarrisonError::Internal(format!("jwt-sign::{}", e)))
}
pub fn verify_custom<T: DeserializeOwned>(&self, token: &str) -> GarrisonResult<T> {
self.ensure_symmetric_secret_usable()?;
validate_algorithm_match(&self.key_material, self.algorithm)?;
let key = self.decoding_key()?;
let mut validation = Validation::new(self.algorithm);
validation.validate_exp = true;
validation.leeway = 0;
let decoded: jsonwebtoken::TokenData<T> =
decode(token, &key, &validation).map_err(map_verify_error)?;
Ok(decoded.claims)
}
fn ensure_symmetric_secret_usable(&self) -> GarrisonResult<()> {
if matches!(self.key_material, KeyMaterial::Hs) {
if self.secret.is_empty() {
return Err(GarrisonError::Config("jwt-secret-empty::".to_string()));
}
if self.secret.len() < MIN_SECRET_BYTES {
return Err(GarrisonError::Config(format!(
"jwt-secret-too-short::{}::{}",
self.secret.len(),
MIN_SECRET_BYTES
)));
}
}
Ok(())
}
}
#[cfg(feature = "protocol-zeroize")]
impl Drop for JwtHandler {
fn drop(&mut self) {
use zeroize::Zeroize;
self.secret.zeroize();
}
}