use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JoseHeader {
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::HashMap<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::HashMap::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
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algorithm::{JweAlgorithm, JweEncryption, JwsAlgorithm};
#[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"));
}
}