use serde_json::{Map, Value};
use crate::algorithm::{JweAlgorithm, JweEncryption};
use crate::base64url;
use crate::error::{JoseError, Result};
use crate::header::JoseHeader;
use crate::jwe::internal::{self, ensure_token_size, JweDecryptOptions, JweEncryptOptions};
use crate::jwe::json::{self as json_mod, FlattenedJwe};
use crate::member_map::MemberMap;
pub const MAX_RECIPIENTS: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recipient {
pub header: Option<Map<String, Value>>,
pub encrypted_key: Option<String>,
pub other: Vec<(String, Value)>,
}
impl Recipient {
fn from_value(value: Value) -> Result<Self> {
let Value::Object(object) = value else {
return Err(JoseError::InvalidToken(
"each JWE \"recipients\" element must be a JSON object".into(),
));
};
let mut map = MemberMap::new(object.into_iter().collect::<Vec<_>>())?;
let header = json_mod::object_member(&mut map, "header")?;
let encrypted_key = match map.take("encrypted_key") {
None => None,
Some(Value::String(value)) if value.is_empty() => None,
Some(Value::String(value)) => {
base64url::decode(&value)?;
Some(value)
}
Some(_) => {
return Err(JoseError::InvalidToken(
"JWE \"recipients\" element member \"encrypted_key\" must be a string".into(),
))
}
};
Ok(Self {
header,
encrypted_key,
other: map.drain_leftovers(),
})
}
fn to_value(&self) -> Result<Value> {
let mut object = Map::new();
if let Some(header) = &self.header {
if !header.is_empty() {
object.insert("header".into(), Value::Object(header.clone()));
}
}
if let Some(encrypted_key) = &self.encrypted_key {
if !encrypted_key.is_empty() {
object.insert("encrypted_key".into(), Value::String(encrypted_key.clone()));
}
}
MemberMap::new(self.other.clone())?.write_into(&mut object)?;
Ok(Value::Object(object))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneralJwe {
pub protected: Option<String>,
pub unprotected: Option<Map<String, Value>>,
pub aad: Option<String>,
pub iv: Option<String>,
pub ciphertext: String,
pub tag: Option<String>,
pub recipients: Vec<Recipient>,
pub other: Vec<(String, Value)>,
}
impl GeneralJwe {
pub fn from_json(text: &str) -> Result<Self> {
ensure_token_size(text)?;
let mut map = MemberMap::from_json(text)?;
for name in json_mod::JWS_MEMBERS {
if map.contains(name) {
return Err(JoseError::InvalidToken(format!(
"member {name} belongs to a JWS; this is not a JWE JSON object"
)));
}
}
for name in ["header", "encrypted_key"] {
if map.contains(name) {
return Err(JoseError::InvalidToken(format!(
"JWE general serialization has no top-level \"{name}\" member; it belongs \
to a \"recipients\" element (RFC 7516 §7.2.1)"
)));
}
}
let protected = json_mod::require_protected(&mut map)?;
let unprotected = json_mod::object_member(&mut map, "unprotected")?;
let aad = json_mod::optional_member(&mut map, "aad")?;
let ciphertext = json_mod::require_member(&mut map, "ciphertext")?;
let iv = json_mod::optional_member(&mut map, "iv")?;
let tag = json_mod::optional_member(&mut map, "tag")?;
let raw_recipients = map.take("recipients").ok_or_else(|| {
JoseError::InvalidToken(
"JWE JSON member \"recipients\" is required for the general serialization; \
if the message has one recipient it is the flattened syntax — use \
jose_rs::jwe::json::FlattenedJwe::from_json"
.into(),
)
})?;
let Value::Array(elements) = raw_recipients else {
return Err(JoseError::InvalidToken(
"JWE JSON member \"recipients\" must be an array of JSON objects".into(),
));
};
if elements.is_empty() {
return Err(JoseError::InvalidToken(
"JWE \"recipients\" must hold at least one recipient (RFC 7516 §7.2.1)".into(),
));
}
if elements.len() > MAX_RECIPIENTS {
return Err(JoseError::InvalidToken(format!(
"JWE \"recipients\" names {} recipients, more than this crate's bound of \
{MAX_RECIPIENTS}",
elements.len()
)));
}
let mut recipients = Vec::with_capacity(elements.len());
for element in elements {
recipients.push(Recipient::from_value(element)?);
}
for value in [
Some(protected.as_str()),
aad.as_deref(),
iv.as_deref(),
tag.as_deref(),
Some(ciphertext.as_str()),
]
.into_iter()
.flatten()
{
base64url::decode(value)?;
}
for (index, recipient) in recipients.iter().enumerate() {
json_mod::ensure_header_locations_disjoint(
&protected,
unprotected.as_ref(),
recipient.header.as_ref(),
)
.map_err(|err| match err {
JoseError::InvalidToken(message) => {
JoseError::InvalidToken(format!("{message} (checked for recipient {index})"))
}
other => other,
})?;
}
Ok(Self {
protected: Some(protected),
unprotected,
aad,
iv,
ciphertext,
tag,
recipients,
other: map.drain_leftovers(),
})
}
pub fn to_json(&self) -> Result<String> {
let mut map = Map::new();
if let Some(protected) = &self.protected {
map.insert("protected".into(), Value::String(protected.clone()));
}
if let Some(unprotected) = &self.unprotected {
if !unprotected.is_empty() {
map.insert("unprotected".into(), Value::Object(unprotected.clone()));
}
}
if let Some(aad) = &self.aad {
if !aad.is_empty() {
map.insert("aad".into(), Value::String(aad.clone()));
}
}
if let Some(iv) = &self.iv {
if !iv.is_empty() {
map.insert("iv".into(), Value::String(iv.clone()));
}
}
if let Some(tag) = &self.tag {
if !tag.is_empty() {
map.insert("tag".into(), Value::String(tag.clone()));
}
}
map.insert("ciphertext".into(), Value::String(self.ciphertext.clone()));
let mut elements = Vec::with_capacity(self.recipients.len());
for recipient in &self.recipients {
elements.push(recipient.to_value()?);
}
map.insert("recipients".into(), Value::Array(elements));
MemberMap::new(self.other.clone())?.write_into(&mut map)?;
let text = serde_json::to_string(&map)?;
ensure_token_size(&text)?;
Ok(text)
}
#[must_use]
pub fn recipient_count(&self) -> usize {
self.recipients.len()
}
pub fn flatten_for(&self, recipient: usize) -> Result<FlattenedJwe> {
let entry = self.recipients.get(recipient).ok_or_else(|| {
JoseError::InvalidToken(format!(
"recipient {recipient} is out of range: this message names {} recipient(s)",
self.recipients.len()
))
})?;
for field in [
self.protected.as_deref(),
self.aad.as_deref(),
self.iv.as_deref(),
Some(self.ciphertext.as_str()),
self.tag.as_deref(),
entry.encrypted_key.as_deref(),
]
.into_iter()
.flatten()
{
ensure_token_size(field)?;
}
Ok(FlattenedJwe {
protected: self.protected.clone(),
unprotected: self.unprotected.clone(),
header: entry.header.clone(),
aad: self.aad.clone(),
encrypted_key: entry.encrypted_key.clone(),
iv: self.iv.clone(),
ciphertext: self.ciphertext.clone(),
tag: self.tag.clone(),
other: Vec::new(),
})
}
pub fn peek_jose_header_for(&self, recipient: usize) -> Result<Map<String, Value>> {
self.flatten_for(recipient)?.peek_jose_header()
}
pub fn recipient_kids(&self) -> Vec<Option<&str>> {
self.recipients
.iter()
.map(|entry| {
entry
.header
.as_ref()
.and_then(|header| header.get("kid"))
.and_then(Value::as_str)
.or_else(|| {
self.unprotected
.as_ref()
.and_then(|header| header.get("kid"))
.and_then(Value::as_str)
})
})
.collect()
}
}
#[derive(Debug, Clone)]
pub struct RecipientSpec<'a> {
pub key: &'a [u8],
pub kid: Option<&'a str>,
}
impl<'a> RecipientSpec<'a> {
#[must_use]
pub fn new(key: &'a [u8]) -> Self {
Self { key, kid: None }
}
#[must_use]
pub fn with_kid(key: &'a [u8], kid: &'a str) -> Self {
Self {
key,
kid: Some(kid),
}
}
fn header(&self) -> Option<Map<String, Value>> {
self.kid.map(|kid| {
let mut object = Map::new();
object.insert("kid".into(), Value::String(kid.to_owned()));
object
})
}
}
pub fn encrypt_general(
header: &JoseHeader,
recipients: &[RecipientSpec<'_>],
plaintext: &[u8],
alg: JweAlgorithm,
enc: JweEncryption,
) -> Result<GeneralJwe> {
encrypt_general_options(
header,
recipients,
plaintext,
alg,
enc,
&JweEncryptOptions::new(),
)
}
pub fn encrypt_general_options(
header: &JoseHeader,
recipients: &[RecipientSpec<'_>],
plaintext: &[u8],
alg: JweAlgorithm,
enc: JweEncryption,
opts: &JweEncryptOptions,
) -> Result<GeneralJwe> {
if recipients.is_empty() {
return Err(JoseError::InvalidHeader(
"a general JWE needs at least one recipient".into(),
));
}
if recipients.len() > MAX_RECIPIENTS {
return Err(JoseError::InvalidHeader(format!(
"a general JWE cannot name {} recipients; this crate's bound is {MAX_RECIPIENTS}",
recipients.len()
)));
}
let aad_b64 = match opts.external_aad() {
None => None,
Some(bytes) => {
internal::ensure_external_aad_present(bytes)?;
Some(base64url::encode(bytes))
}
};
if internal::alg_is_agreement(alg) {
return Err(internal::direct_agreement_not_multi(alg));
}
let keys: Vec<internal::KeyMaterial> = recipients
.iter()
.map(|recipient| {
internal::KeyMaterial::Bytes(zeroize::Zeroizing::new(recipient.key.to_vec()))
})
.collect();
let (core, wrapped) =
internal::encrypt_core_multi(header, &keys, plaintext, alg, enc, opts, aad_b64.as_deref())?;
let entries = recipients
.iter()
.zip(wrapped)
.map(|(spec, key)| Recipient {
header: spec.header(),
encrypted_key: (!key.is_empty()).then(|| base64url::encode(&key)),
other: Vec::new(),
})
.collect();
Ok(GeneralJwe {
protected: Some(core.header_b64),
unprotected: None,
aad: aad_b64,
iv: (!core.iv.is_empty()).then(|| base64url::encode(&core.iv)),
ciphertext: base64url::encode(&core.ciphertext),
tag: (!core.tag.is_empty()).then(|| base64url::encode(&core.tag)),
recipients: entries,
other: Vec::new(),
})
}
pub fn encrypt_general_with_jwks(
header: &JoseHeader,
jwks: &[&crate::jwk::Jwk],
plaintext: &[u8],
enc: JweEncryption,
) -> Result<GeneralJwe> {
encrypt_general_with_jwks_options(header, jwks, plaintext, enc, &JweEncryptOptions::new())
}
pub fn encrypt_general_with_jwks_options(
header: &JoseHeader,
jwks: &[&crate::jwk::Jwk],
plaintext: &[u8],
enc: JweEncryption,
opts: &JweEncryptOptions,
) -> Result<GeneralJwe> {
if jwks.is_empty() {
return Err(JoseError::InvalidHeader(
"a general JWE needs at least one recipient".into(),
));
}
let mut materials = Vec::with_capacity(jwks.len());
let mut pinned: Option<JweAlgorithm> = None;
for jwk in jwks {
let alg = json_mod::pinned_alg(jwk)?;
if internal::agreement_kek_len(alg).is_some() {
return Err(internal::per_recipient_epk_unsupported(alg));
}
if internal::alg_is_agreement(alg) {
return Err(internal::direct_agreement_not_multi(alg));
}
jwk.check_op(internal::jwe_alg_encrypt_op(alg))?;
match pinned {
None => pinned = Some(alg),
Some(previous) if previous != alg => {
return Err(JoseError::Key(format!(
"general JWE recipients must pin the same alg; one pins {} and another {}",
previous.as_str(),
alg.as_str()
)));
}
Some(_) => {}
}
materials.push(internal::jwk_to_jwe_key_bytes(jwk, alg, false)?);
}
let alg = pinned.unwrap_or(JweAlgorithm::Dir);
let specs: Vec<RecipientSpec<'_>> = jwks
.iter()
.zip(&materials)
.map(|(jwk, material)| RecipientSpec {
key: material.as_slice(),
kid: jwk.kid.as_deref(),
})
.collect();
encrypt_general_options(header, &specs, plaintext, alg, enc, opts)
}
pub fn encrypt_general_with_passwords(
header: &JoseHeader,
passwords: &[&crate::jwe::password::Password],
plaintext: &[u8],
alg: JweAlgorithm,
enc: JweEncryption,
) -> Result<GeneralJwe> {
encrypt_general_with_passwords_options(
header,
passwords,
plaintext,
alg,
enc,
&JweEncryptOptions::new(),
)
}
pub fn encrypt_general_with_passwords_options(
header: &JoseHeader,
passwords: &[&crate::jwe::password::Password],
plaintext: &[u8],
alg: JweAlgorithm,
enc: JweEncryption,
opts: &JweEncryptOptions,
) -> Result<GeneralJwe> {
match passwords.len() {
0 => Err(JoseError::InvalidHeader(
"a general JWE needs at least one recipient".into(),
)),
1 => {
let flat = json_mod::encrypt_flattened_with_password_header_options(
passwords[0],
header.clone(),
plaintext,
alg,
enc,
opts,
)?;
Ok(GeneralJwe {
protected: flat.protected,
unprotected: flat.unprotected,
aad: flat.aad,
iv: flat.iv,
ciphertext: flat.ciphertext,
tag: flat.tag,
recipients: vec![Recipient {
header: flat.header,
encrypted_key: flat.encrypted_key,
other: Vec::new(),
}],
other: Vec::new(),
})
}
n => {
let _ = n;
Err(internal::per_recipient_member_unsupported(
alg,
"p2s and p2c",
))
}
}
}
pub fn decrypt_general_with_password(
password: &crate::jwe::password::Password,
jwe: &GeneralJwe,
recipient: usize,
) -> Result<Vec<u8>> {
decrypt_general_with_password_options(
password,
jwe,
recipient,
&JweDecryptOptions::new(
crate::jwe::compact::pbes2_algorithms(),
internal::all_enc_algorithms(),
),
)
}
pub fn decrypt_general_with_password_options(
password: &crate::jwe::password::Password,
jwe: &GeneralJwe,
recipient: usize,
options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
json_mod::decrypt_flattened_with_password_options(
password,
&jwe.flatten_for(recipient)?,
options,
)
}
pub fn decrypt_general_with_jwk(
jwk: &crate::jwk::Jwk,
jwe: &GeneralJwe,
recipient: usize,
) -> Result<Vec<u8>> {
json_mod::decrypt_flattened_with_jwk_impl(jwk, &jwe.flatten_for(recipient)?, None)
}
pub fn decrypt_general_with_jwk_authenticated(
jwk: &crate::jwk::Jwk,
jwe: &GeneralJwe,
recipient: usize,
) -> Result<crate::Authenticated<Vec<u8>>> {
let plaintext = decrypt_general_with_jwk(jwk, jwe, recipient)?;
let flattened = jwe.flatten_for(recipient)?;
let (protected, unprotected) = json_mod::split_flattened_metadata_public(&flattened)?;
Ok(crate::Authenticated::new(plaintext, protected, unprotected))
}
pub fn decrypt_general_with_jwk_options(
jwk: &crate::jwk::Jwk,
jwe: &GeneralJwe,
recipient: usize,
options: &JweDecryptOptions,
) -> Result<Vec<u8>> {
json_mod::decrypt_flattened_with_jwk_options(jwk, &jwe.flatten_for(recipient)?, options)
}
pub fn decrypt_general_with_jwk_and_aad(
jwk: &crate::jwk::Jwk,
jwe: &GeneralJwe,
recipient: usize,
external_aad: &[u8],
) -> Result<Vec<u8>> {
json_mod::decrypt_flattened_with_jwk_impl(jwk, &jwe.flatten_for(recipient)?, Some(external_aad))
}
pub fn decrypt_general_with_jwk_by_kid(jwk: &crate::jwk::Jwk, jwe: &GeneralJwe) -> Result<Vec<u8>> {
let (index, _) = select_recipient_by_kid(jwk, jwe)?;
decrypt_general_with_jwk(jwk, jwe, index)
}
pub(crate) fn select_recipient_by_kid(
jwk: &crate::jwk::Jwk,
jwe: &GeneralJwe,
) -> Result<(usize, usize)> {
let kid = jwk
.kid
.as_deref()
.ok_or_else(|| JoseError::Key("JWK kid must be set to select a recipient by kid".into()))?;
let matches: Vec<usize> = jwe
.recipient_kids()
.iter()
.enumerate()
.filter_map(|(index, candidate)| (*candidate == Some(kid)).then_some(index))
.collect();
match matches.len() {
0 => Err(JoseError::InvalidToken(format!(
"no recipient of this JWE carries kid {kid}"
))),
1 => Ok((matches[0], 1)),
count => Err(JoseError::InvalidToken(format!(
"{count} recipients of this JWE carry kid {kid}; the choice cannot be made from an \
unauthenticated header parameter"
))),
}
}
pub fn decode_header(jwe: &GeneralJwe) -> Result<Option<JoseHeader>> {
jwe.flatten_for(0)?.peek_protected_header()
}