use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{JoseError, Result};
const TYPED_MEMBERS: &[&str] = &[
"alg", "enc", "kid", "typ", "cty", "jku", "jwk", "x5u", "x5c", "x5t", "x5t#S256", "crit",
];
pub const KEY_REFERENCE_MEMBERS: &[&str] = &["jku", "jwk", "x5u", "x5c"];
pub const JWE_ONLY_MEMBERS: &[&str] =
&["enc", "zip", "epk", "apu", "apv", "iv", "tag", "p2s", "p2c"];
pub(crate) fn is_registered_member(name: &str) -> bool {
TYPED_MEMBERS.contains(&name) || JWE_ONLY_MEMBERS.contains(&name)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JoseHeader {
#[serde(default)]
pub alg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub enc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub typ: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cty: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub jku: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub jwk: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x5u: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x5c: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x5t: Option<String>,
#[serde(rename = "x5t#S256", skip_serializing_if = "Option::is_none")]
pub x5t_s256: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub crit: Option<Vec<String>>,
#[serde(flatten)]
pub extra: std::collections::BTreeMap<String, Value>,
}
impl JoseHeader {
pub fn new(alg: &str) -> Self {
Self {
alg: alg.to_string(),
enc: None,
kid: None,
typ: None,
cty: None,
jku: None,
jwk: None,
x5u: None,
x5c: None,
x5t: None,
x5t_s256: None,
crit: None,
extra: std::collections::BTreeMap::new(),
}
}
pub fn jwt(alg: &str) -> Self {
let mut h = Self::new(alg);
h.typ = Some("JWT".to_string());
h
}
pub fn for_alg(alg: crate::algorithm::JwsAlgorithm) -> Self {
Self::new(alg.as_str())
}
pub fn jwt_for_alg(alg: crate::algorithm::JwsAlgorithm) -> Self {
let mut h = Self::for_alg(alg);
h.typ = Some("JWT".to_string());
h
}
pub fn for_jwe(
alg: crate::algorithm::JweAlgorithm,
enc: crate::algorithm::JweEncryption,
) -> Self {
let mut h = Self::new(alg.as_str());
h.enc = Some(enc.as_str().to_string());
h
}
pub(crate) fn ensure_no_duplicate_members(&self) -> Result<()> {
match TYPED_MEMBERS
.iter()
.find(|name| self.extra.contains_key(**name))
{
Some(name) => Err(JoseError::InvalidHeader(format!(
"extra header member {name} duplicates a typed header field"
))),
None => Ok(()),
}
}
pub(crate) fn key_reference_member(&self) -> Option<&'static str> {
[
("jku", self.jku.is_some()),
("jwk", self.jwk.is_some()),
("x5u", self.x5u.is_some()),
("x5c", self.x5c.is_some()),
]
.into_iter()
.find_map(|(name, present)| present.then_some(name))
}
pub(crate) fn jwe_only_member(&self) -> Option<&'static str> {
if self.enc.is_some() {
return Some("enc");
}
JWE_ONLY_MEMBERS
.iter()
.copied()
.find(|name| self.extra.contains_key(*name))
}
pub(crate) fn to_protected_b64(&self, allow_key_references: bool) -> Result<String> {
self.ensure_no_duplicate_members()?;
if !allow_key_references {
if let Some(name) = self.key_reference_member() {
return Err(JoseError::InvalidHeader(format!(
"{name} in protected header requires allow_key_reference_headers \
(key-reference members may be dereferenced by peers)"
)));
}
}
let encoded = crate::base64url::encode(&serde_json::to_vec(self)?);
if encoded.len() > crate::MAX_TOKEN_BYTES {
return Err(JoseError::InvalidHeader(format!(
"encoded protected header is {} bytes, exceeding MAX_TOKEN_BYTES ({})",
encoded.len(),
crate::MAX_TOKEN_BYTES
)));
}
Ok(encoded)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algorithm::{JweAlgorithm, JweEncryption, JwsAlgorithm};
#[test]
fn typed_members_match_serialized_fields() {
let header = JoseHeader {
alg: "HS256".into(),
enc: Some("A128GCM".into()),
kid: Some("k".into()),
typ: Some("JWT".into()),
cty: Some("JWT".into()),
jku: Some("https://example.com".into()),
jwk: Some(serde_json::json!({})),
x5u: Some("https://example.com".into()),
x5c: Some(vec!["AA".into()]),
x5t: Some("AA".into()),
x5t_s256: Some("AA".into()),
crit: Some(vec!["b64".into()]),
extra: Default::default(),
};
let value = serde_json::to_value(&header).unwrap();
let mut serialized: Vec<&str> = value
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
let mut expected = TYPED_MEMBERS.to_vec();
serialized.sort_unstable();
expected.sort_unstable();
assert_eq!(serialized, expected);
}
#[test]
fn ensure_no_duplicate_members_rejects_only_typed_names() {
for name in TYPED_MEMBERS {
let mut header = JoseHeader::new("HS256");
header.extra.insert((*name).into(), Value::Null);
assert!(matches!(
header.ensure_no_duplicate_members(),
Err(JoseError::InvalidHeader(_))
));
}
let mut header = JoseHeader::new("HS256");
header.extra.insert("b64".into(), Value::Bool(false));
header.extra.insert("tenant".into(), Value::Null);
assert!(header.ensure_no_duplicate_members().is_ok());
}
#[test]
fn registered_members_cover_jose_rfcs_but_not_extensions() {
for name in TYPED_MEMBERS.iter().chain(JWE_ONLY_MEMBERS) {
assert!(is_registered_member(name), "{name} not registered");
}
for name in ["b64", "etsiU", "sigT", "tenant"] {
assert!(!is_registered_member(name), "{name} treated as registered");
}
}
#[test]
fn jwe_only_member_detects_typed_and_extra_members() {
assert_eq!(JoseHeader::new("HS256").jwe_only_member(), None);
let jwe = JoseHeader::for_jwe(JweAlgorithm::Dir, JweEncryption::A128GCM);
assert_eq!(jwe.jwe_only_member(), Some("enc"));
for name in JWE_ONLY_MEMBERS.iter().filter(|n| **n != "enc") {
let mut header = JoseHeader::new("HS256");
header.extra.insert((*name).into(), Value::Null);
assert_eq!(header.jwe_only_member(), Some(*name));
}
}
#[test]
fn for_alg_matches_as_str() {
let h = JoseHeader::for_alg(JwsAlgorithm::ES256);
assert_eq!(h.alg, "ES256");
assert!(h.typ.is_none());
}
#[test]
fn jwt_for_alg_sets_typ() {
let h = JoseHeader::jwt_for_alg(JwsAlgorithm::HS256);
assert_eq!(h.alg, "HS256");
assert_eq!(h.typ.as_deref(), Some("JWT"));
}
#[test]
fn for_jwe_sets_alg_and_enc() {
let h = JoseHeader::for_jwe(JweAlgorithm::A256KW, JweEncryption::A256GCM);
assert_eq!(h.alg, "A256KW");
assert_eq!(h.enc.as_deref(), Some("A256GCM"));
}
}