use crate::header::JoseHeader;
use serde_json::Value;
#[derive(Debug, Clone)]
pub struct Authenticated<T> {
pub value: T,
pub protected: JoseHeader,
pub unprotected: Vec<Value>,
verified_key_index: Option<usize>,
}
impl<T> Authenticated<T> {
pub(crate) fn new(value: T, protected: JoseHeader, unprotected: Vec<Value>) -> Self {
Self {
value,
protected,
unprotected,
verified_key_index: None,
}
}
pub fn verified_key_index(&self) -> Option<usize> {
self.verified_key_index
}
pub(crate) fn with_verified_key_index(mut self, index: usize) -> Self {
self.verified_key_index = Some(index);
self
}
pub fn into_value(self) -> T {
self.value
}
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Authenticated<U> {
Authenticated {
value: f(self.value),
protected: self.protected,
unprotected: self.unprotected,
verified_key_index: self.verified_key_index,
}
}
pub fn algorithm(&self) -> &str {
&self.protected.alg
}
pub fn kid(&self) -> Option<&str> {
self.protected.kid.as_deref()
}
pub fn has_unprotected(&self) -> bool {
!self.unprotected.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn outcome() -> Authenticated<Vec<u8>> {
let mut protected = JoseHeader::new("ES256");
protected.kid = Some("signed-kid".into());
Authenticated::new(
b"payload".to_vec(),
protected,
vec![serde_json::json!({"kid": "unsigned-kid"})],
)
}
#[test]
fn the_kid_accessor_reads_the_authenticated_header_only() {
let outcome = outcome();
assert_eq!(outcome.kid(), Some("signed-kid"));
assert_eq!(
outcome.unprotected[0].get("kid").and_then(Value::as_str),
Some("unsigned-kid"),
"the unauthenticated value is still *reported*, it is simply not authoritative"
);
assert!(outcome.has_unprotected());
}
#[test]
fn mapping_keeps_the_header_context() {
let parsed = outcome().map(|bytes| String::from_utf8(bytes).unwrap());
assert_eq!(parsed.value, "payload");
assert_eq!(parsed.algorithm(), "ES256");
assert_eq!(parsed.kid(), Some("signed-kid"));
assert_eq!(parsed.unprotected.len(), 1);
}
#[test]
fn a_compact_style_document_has_no_unprotected_metadata() {
let outcome = Authenticated::new(b"x".to_vec(), JoseHeader::new("EdDSA"), Vec::new());
assert!(!outcome.has_unprotected());
assert_eq!(outcome.clone().into_value(), b"x".to_vec());
}
}