oxabl-cache-crypto 0.4.0

Client-side cryptography for the oxabl-cache remote compile cache: key hierarchy, seal and open, signatures.
Documentation
//! Verifying an OIDC ID token on the client: an owner's client checks, by itself, the
//! sign-in a join request rests on, without trusting the cache server.

#[cfg(feature = "seal")]
use aws_lc_rs::rsa::PublicKeyComponents;
#[cfg(feature = "seal")]
use aws_lc_rs::signature::{
    ECDSA_P256_SHA256_FIXED, ED25519, RSA_PKCS1_2048_8192_SHA256, UnparsedPublicKey,
};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use oxabl_cache_format::audience::{Claim, issued_to};
use serde_json::{Map, Value};

/// Largest token accepted.
pub const MAX_TOKEN_BYTES: usize = 16 * 1024;
/// Keys read from one key set at most.
const MAX_KEYS: usize = 64;
/// Array members read from one token at most.
const MAX_MEMBERS: usize = 256;
/// Allowed clock difference in seconds.
const SKEW_SECS: i64 = 60;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Algorithm {
    Rs256,
    Es256,
    EdDsa,
}

impl Algorithm {
    fn parse(name: &str) -> Option<Self> {
        match name {
            "RS256" => Some(Self::Rs256),
            "ES256" => Some(Self::Es256),
            "EdDSA" => Some(Self::EdDsa),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
enum Material {
    Rsa { n: Vec<u8>, e: Vec<u8> },
    Ec { point: Vec<u8> },
    Ed { key: Vec<u8> },
}

#[derive(Debug, Clone)]
struct Jwk {
    kid: Option<String>,
    alg: Option<String>,
    material: Material,
}

/// The usable signing keys of an issuer's JWKS document.
#[derive(Debug, Clone)]
pub struct KeySet(Vec<Jwk>);

/// What a verified ID token says about the person.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedIn {
    pub issuer: String,
    pub subject: String,
    /// Scalar claims (strings, whole numbers, booleans) as name and value.
    pub claims: Vec<(String, String)>,
    /// String members of array claims, such as `groups`, as name and value.
    pub members: Vec<(String, String)>,
}

impl SignedIn {
    /// The value of a scalar claim.
    pub fn claim(&self, name: &str) -> Option<&str> {
        self.claims
            .iter()
            .find(|(claim, _)| claim == name)
            .map(|(_, value)| value.as_str())
    }

    /// Whether `claim` holds `value`, as a scalar or as a member of an array.
    pub fn holds(&self, claim: &str, value: &str) -> bool {
        self.claims
            .iter()
            .chain(&self.members)
            .any(|(name, held)| name == claim && held == value)
    }
}

fn b64(value: &Value, field: &str) -> Option<Vec<u8>> {
    URL_SAFE_NO_PAD.decode(value.get(field)?.as_str()?).ok()
}

fn padded(bytes: Vec<u8>, width: usize) -> Option<Vec<u8>> {
    (bytes.len() <= width).then(|| {
        let mut out = vec![0u8; width - bytes.len()];
        out.extend(bytes);
        out
    })
}

impl Jwk {
    fn parse(value: &Value) -> Option<Self> {
        if value.get("use").is_some_and(|usage| usage != "sig") {
            return None;
        }
        let material = match value.get("kty")?.as_str()? {
            "RSA" => {
                let n = b64(value, "n")?;
                let bits = n.iter().skip_while(|b| **b == 0).count() * 8;
                if !(2048..=8192).contains(&bits) {
                    return None;
                }
                Material::Rsa {
                    n,
                    e: b64(value, "e")?,
                }
            }
            "EC" if value.get("crv")? == "P-256" => {
                let x = padded(b64(value, "x")?, 32)?;
                let y = padded(b64(value, "y")?, 32)?;
                Material::Ec {
                    point: [&[4u8][..], &x, &y].concat(),
                }
            }
            "OKP" if value.get("crv")? == "Ed25519" => {
                let key = b64(value, "x")?;
                (key.len() == 32).then_some(Material::Ed { key })?
            }
            _ => return None,
        };
        Some(Self {
            kid: value.get("kid").and_then(Value::as_str).map(str::to_owned),
            alg: value.get("alg").and_then(Value::as_str).map(str::to_owned),
            material,
        })
    }

    fn fits(&self, algorithm: Algorithm) -> bool {
        let family = matches!(
            (&self.material, algorithm),
            (Material::Rsa { .. }, Algorithm::Rs256)
                | (Material::Ec { .. }, Algorithm::Es256)
                | (Material::Ed { .. }, Algorithm::EdDsa)
        );
        let named = match &self.alg {
            None => true,
            Some(name) => Algorithm::parse(name) == Some(algorithm),
        };
        family && named
    }

    #[cfg(feature = "seal")]
    fn verify(&self, message: &[u8], signature: &[u8]) -> bool {
        match &self.material {
            Material::Rsa { n, e } => PublicKeyComponents {
                n: n.as_slice(),
                e: e.as_slice(),
            }
            .verify(&RSA_PKCS1_2048_8192_SHA256, message, signature)
            .is_ok(),
            Material::Ec { point } => UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, point)
                .verify(message, signature)
                .is_ok(),
            Material::Ed { key } => UnparsedPublicKey::new(&ED25519, key)
                .verify(message, signature)
                .is_ok(),
        }
    }

    /// The pure Rust twin of the aws-lc-rs check above, with the same key size rules.
    #[cfg(not(feature = "seal"))]
    fn verify(&self, message: &[u8], signature: &[u8]) -> bool {
        match &self.material {
            Material::Rsa { n, e } => {
                use rsa::pkcs1v15::{Signature, VerifyingKey};
                use rsa::signature::Verifier;
                let Ok(key) = rsa::RsaPublicKey::new_with_max_size(
                    rsa::BigUint::from_bytes_be(n),
                    rsa::BigUint::from_bytes_be(e),
                    8192,
                ) else {
                    return false;
                };
                let Ok(signature) = Signature::try_from(signature) else {
                    return false;
                };
                VerifyingKey::<rsa::sha2::Sha256>::new(key)
                    .verify(message, &signature)
                    .is_ok()
            }
            Material::Ec { point } => {
                use p256::ecdsa::signature::Verifier;
                use p256::ecdsa::{Signature, VerifyingKey};
                let Ok(key) = VerifyingKey::from_sec1_bytes(point) else {
                    return false;
                };
                let Ok(signature) = Signature::from_slice(signature) else {
                    return false;
                };
                key.verify(message, &signature).is_ok()
            }
            Material::Ed { key } => {
                let Ok(key) = <[u8; 32]>::try_from(key.as_slice()) else {
                    return false;
                };
                let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(&key) else {
                    return false;
                };
                let Ok(signature) = ed25519_dalek::Signature::from_slice(signature) else {
                    return false;
                };
                key.verify_strict(message, &signature).is_ok()
            }
        }
    }
}

impl KeySet {
    /// The usable keys of a JWKS document; unusable entries are dropped. `None` when the
    /// document is not a key set.
    pub fn parse(bytes: &[u8]) -> Option<Self> {
        let document: Value = serde_json::from_slice(bytes).ok()?;
        let keys = document.get("keys")?.as_array()?;
        Some(Self(
            keys.iter().take(MAX_KEYS).filter_map(Jwk::parse).collect(),
        ))
    }
}

fn object(segment: &str) -> Option<Map<String, Value>> {
    match serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).ok()?).ok()? {
        Value::Object(map) => Some(map),
        _ => None,
    }
}

fn seconds(claims: &Map<String, Value>, name: &str) -> Option<Option<i64>> {
    match claims.get(name) {
        None => Some(None),
        Some(value) => value.as_i64().map(Some),
    }
}

fn claim(value: Option<&Value>) -> Claim<'_> {
    match value {
        None => Claim::Absent,
        Some(Value::String(text)) => Claim::String(text),
        Some(Value::Array(list)) => list
            .iter()
            .map(Value::as_str)
            .collect::<Option<Vec<_>>>()
            .map_or(Claim::Other, Claim::Strings),
        Some(_) => Claim::Other,
    }
}

/// Whether the token was issued to `audience`, by the rule of
/// [`oxabl_cache_format::audience`].
fn audience_is(claims: &Map<String, Value>, audience: &str) -> bool {
    issued_to(&claim(claims.get("aud")), &claim(claims.get("azp")), |id| {
        id == audience
    })
    .is_some()
}

fn scalars(claims: &Map<String, Value>) -> Vec<(String, String)> {
    claims
        .iter()
        .filter(|(name, _)| !matches!(name.as_str(), "exp" | "nbf" | "iat" | "aud"))
        .filter_map(|(name, value)| {
            let text = match value {
                Value::String(text) => text.clone(),
                Value::Bool(flag) => flag.to_string(),
                Value::Number(number) if number.is_i64() || number.is_u64() => number.to_string(),
                _ => return None,
            };
            Some((name.clone(), text))
        })
        .collect()
}

fn members(claims: &Map<String, Value>) -> Vec<(String, String)> {
    claims
        .iter()
        .filter(|(name, _)| name.as_str() != "aud")
        .filter_map(|(name, value)| value.as_array().map(|list| (name, list)))
        .flat_map(|(name, list)| {
            list.iter()
                .filter_map(Value::as_str)
                .map(move |member| (name.clone(), member.to_owned()))
        })
        .take(MAX_MEMBERS)
        .collect()
}

/// Verifies `token`: an RS256, ES256 or EdDSA signature by one of `keys`, `iss` exactly
/// `issuer`, issued to `audience` (`aud` holds it, and `azp` is it when `aud` has several
/// members or `azp` is present), and `iat` at most `max_age_secs` before `now`. An
/// expired token passes: the question is what the person signed then, not whether the
/// token still opens a session. Every refusal is a short reason.
pub fn verify(
    token: &str,
    keys: &KeySet,
    issuer: &str,
    audience: &str,
    now: i64,
    max_age_secs: i64,
) -> Result<SignedIn, &'static str> {
    if token.len() > MAX_TOKEN_BYTES {
        return Err("the token is too large");
    }
    let mut parts = token.split('.');
    let (Some(header), Some(payload), Some(signature), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err("not a signed token");
    };
    let header = object(header).ok_or("the header does not parse")?;
    if header.contains_key("crit") {
        return Err("the header has critical extensions");
    }
    let algorithm = header
        .get("alg")
        .and_then(Value::as_str)
        .and_then(Algorithm::parse)
        .ok_or("the algorithm is not RS256, ES256 or EdDSA")?;
    let kid = match header.get("kid") {
        None => None,
        Some(Value::String(kid)) => Some(kid.as_str()),
        Some(_) => return Err("the key id is not a string"),
    };
    let claims = object(payload).ok_or("the claims do not parse")?;
    let signature = URL_SAFE_NO_PAD
        .decode(signature)
        .map_err(|_| "the signature does not parse")?;
    let signed = &token[..token.len() - token.rsplit('.').next().map_or(0, str::len) - 1];
    let fitting: Vec<&Jwk> = keys.0.iter().filter(|key| key.fits(algorithm)).collect();
    let chosen: Vec<&Jwk> = match kid {
        Some(kid) => fitting
            .into_iter()
            .filter(|key| key.kid.as_deref() == Some(kid))
            .collect(),
        None if fitting.len() == 1 => fitting,
        None => Vec::new(),
    };
    if !chosen
        .iter()
        .any(|key| key.verify(signed.as_bytes(), &signature))
    {
        return Err("no key of the issuer signed it");
    }
    if claims.get("iss").and_then(Value::as_str) != Some(issuer) {
        return Err("another issuer");
    }
    if !audience_is(&claims, audience) {
        return Err("another audience");
    }
    let (Some(Some(iat)), Some(nbf)) = (seconds(&claims, "iat"), seconds(&claims, "nbf")) else {
        return Err("the times do not parse");
    };
    let fresh = iat <= now + SKEW_SECS
        && iat >= now.saturating_sub(max_age_secs)
        && nbf.is_none_or(|nbf| nbf <= now + SKEW_SECS);
    if !fresh {
        return Err("signed too long ago, or in the future");
    }
    let subject = claims
        .get("sub")
        .and_then(Value::as_str)
        .filter(|sub| !sub.is_empty())
        .ok_or("no subject")?
        .to_owned();
    Ok(SignedIn {
        issuer: issuer.to_owned(),
        subject,
        claims: scalars(&claims),
        members: members(&claims),
    })
}