Skip to main content

identity_kit/status_list/
mod.rs

1//! The IETF Token Status List ([draft-ietf-oauth-status-list-21]): the `status` claim of a
2//! referenced token, the status list and the status list token.
3//!
4//! Section numbers below are those of draft 21. The module implements its JSON and JWT
5//! formats. It does not implement the CBOR and CWT formats (§4.3, §5.2, §6.3), historical
6//! resolution (§8.4), following an `aggregation_uri` (§9, though [`StatusList`] carries
7//! one), caching by `ttl` (§13.7, though [`StatusListToken`] carries it) or the X.509
8//! extended key usage (§10).
9//!
10//! The draft defines the `status` claim for any JWT (§6.1), so the module serves every
11//! credential format of the crate: SD-JWT VCs and VCDM 2.0 credentials secured with SD-JWT
12//! ([`sd_jwt_vc`](crate::sd_jwt_vc), feature `sd-jwt`) as much as JWT credentials of either
13//! profile ([`vc`](crate::vc)). The validators of both hand the claim to a
14//! [`StatusCheck`](crate::vc::validation::StatusCheck) as
15//! [`CredentialStatus::StatusClaim`](crate::vc::validation::CredentialStatus::StatusClaim).
16//!
17//! - [`Status`] is the claim, [`StatusListRef`] its `status_list` mechanism and
18//!   [`StatusMechanism`] one mechanism of it.
19//! - [`StatusList`] is the list (§4): one [`StatusType`] of 1, 2, 4 or 8 bits per referenced
20//!   token, ZLIB-compressed in its `lst` member.
21//! - [`StatusListToken`] is the signed list (§5.1), issued with
22//!   [`sign`](StatusListToken::sign) and read with [`status_of`](StatusListToken::status_of).
23//! - `StatusListCheck` (feature `did-web` as well) is the [`StatusCheck`] that fetches the
24//!   token a reference names over an `HttpClient` and verifies it (§8).
25//!
26//! [`StatusCheck`]: crate::vc::validation::StatusCheck
27//! [draft-ietf-oauth-status-list-21]: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-status-list-21
28
29use core::fmt;
30use core::str::FromStr;
31
32use chrono::{DateTime, Utc};
33use indexmap::IndexMap;
34use serde::{Deserialize, Deserializer, Serialize, Serializer};
35use serde_json::Value;
36
37use crate::cause::cause;
38use crate::jose::{JwsError, JwsHeader, Signer, base64url};
39use crate::vc::validation::TimeOptions;
40use crate::vc::{Jwt, JwtClaims};
41
42#[cfg(feature = "did-web")]
43mod check;
44
45#[cfg(feature = "did-web")]
46#[cfg_attr(docsrs, doc(cfg(feature = "did-web")))]
47pub use check::StatusListCheck;
48
49/// The `status` claim of a referenced token: at least one status mechanism, `status_list`
50/// being the one this crate implements.
51///
52/// # Examples
53///
54/// ```
55/// use identity_kit::status_list::{Status, StatusListRef};
56/// use serde_json::json;
57///
58/// // Token Status List §6.2.
59/// let status: Status = serde_json::from_value(json!({
60///   "status_list": { "idx": 0, "uri": "https://example.com/statuslists/1" }
61/// }))?;
62/// let reference = status.status_list.as_ref().unwrap();
63/// assert_eq!(reference.idx, 0);
64/// assert_eq!(reference.uri, "https://example.com/statuslists/1");
65/// assert_eq!(status, Status::status_list(StatusListRef::new("https://example.com/statuslists/1", 0)));
66/// # Ok::<(), serde_json::Error>(())
67/// ```
68#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
69#[non_exhaustive]
70pub struct Status {
71    /// The `status_list` mechanism.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub status_list: Option<StatusListRef>,
74    /// Every other mechanism, by name.
75    #[serde(flatten)]
76    pub additional: IndexMap<String, Value>,
77}
78
79impl Status {
80    /// A `status` claim with no mechanism yet.
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    /// A `status` claim referencing a status list.
86    pub fn status_list(reference: StatusListRef) -> Self {
87        Self {
88            status_list: Some(reference),
89            additional: IndexMap::new(),
90        }
91    }
92
93    /// This claim with the mechanism `name` set to `value`.
94    #[must_use]
95    pub fn with_mechanism(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
96        self.additional.insert(name.into(), value.into());
97        self
98    }
99
100    /// Whether no mechanism is given.
101    pub fn is_empty(&self) -> bool {
102        self.status_list.is_none() && self.additional.is_empty()
103    }
104
105    /// The mechanisms, the status list first.
106    pub fn mechanisms(&self) -> impl Iterator<Item = StatusMechanism<'_>> {
107        self.status_list
108            .iter()
109            .map(StatusMechanism::StatusList)
110            .chain(
111                self.additional
112                    .iter()
113                    .map(|(name, value)| StatusMechanism::Other { name, value }),
114            )
115    }
116}
117
118/// One mechanism of a [`Status`] claim.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum StatusMechanism<'a> {
122    /// A Token Status List reference.
123    StatusList(&'a StatusListRef),
124    /// A mechanism this crate does not implement.
125    Other {
126        /// Its name, the member of `status` it is given under.
127        name: &'a str,
128        /// Its value.
129        value: &'a Value,
130    },
131}
132
133/// A reference to a status list token (`status.status_list`): the token's URI and the index
134/// of the referenced token in its list.
135#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[non_exhaustive]
137pub struct StatusListRef {
138    /// `idx`: the index in the status list.
139    pub idx: u64,
140    /// `uri`: where the status list token is.
141    pub uri: String,
142}
143
144impl StatusListRef {
145    /// A reference to index `idx` of the status list token at `uri`.
146    pub fn new(uri: impl Into<String>, idx: u64) -> Self {
147        Self {
148            idx,
149            uri: uri.into(),
150        }
151    }
152}
153
154/// A status type value (Token Status List §7): a number in `0..=255`, with the registered
155/// meanings as constants.
156///
157/// It serializes as its registered name when it has one of its own (`"VALID"`, `"INVALID"`,
158/// `"SUSPENDED"`) and as a number otherwise. `APPLICATION_SPECIFIC` names `0x03` and
159/// `0x0C`-`0x0F` alike, so those serialize as numbers too. It deserializes from a registered
160/// name, a number in `0..=255`, or that number as a decimal string; [`parse`](Self::parse) and
161/// [`FromStr`] accept the same strings. Names are case-sensitive. Since the form depends on the
162/// value, deserializing needs a self-describing format such as JSON or CBOR.
163///
164/// # Examples
165///
166/// ```
167/// use identity_kit::status_list::StatusType;
168/// use serde_json::json;
169///
170/// assert_eq!(serde_json::to_value(StatusType::SUSPENDED)?, json!("SUSPENDED"));
171/// assert_eq!(serde_json::to_value(StatusType(3))?, json!(3));
172/// assert_eq!(serde_json::from_value::<StatusType>(json!("INVALID"))?, StatusType::INVALID);
173/// assert_eq!(serde_json::from_value::<StatusType>(json!(12))?, StatusType(0x0C));
174/// assert_eq!("VALID".parse::<StatusType>()?, StatusType::VALID);
175/// assert!("APPLICATION_SPECIFIC".parse::<StatusType>().is_err());
176/// # Ok::<(), Box<dyn std::error::Error>>(())
177/// ```
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
179pub struct StatusType(pub u8);
180
181impl StatusType {
182    /// `0x00`: the referenced token is valid.
183    pub const VALID: Self = Self(0);
184    /// `0x01`: the referenced token is revoked.
185    pub const INVALID: Self = Self(1);
186    /// `0x02`: the referenced token is suspended.
187    pub const SUSPENDED: Self = Self(2);
188
189    /// The value.
190    pub const fn value(self) -> u8 {
191        self.0
192    }
193
194    /// Whether this is [`VALID`](Self::VALID).
195    pub const fn is_valid(self) -> bool {
196        self.0 == 0
197    }
198
199    /// The registered name of the value, if it has one.
200    pub const fn name(self) -> Option<&'static str> {
201        match self.0 {
202            0 => Some("VALID"),
203            1 => Some("INVALID"),
204            2 => Some("SUSPENDED"),
205            _ => None,
206        }
207    }
208
209    /// The value named `s`: `VALID`, `INVALID`, `SUSPENDED`, or a decimal number in
210    /// `0..=255`.
211    ///
212    /// # Errors
213    ///
214    /// [`StatusListError::UnknownStatusType`] for anything else, `APPLICATION_SPECIFIC`
215    /// included: it names several values.
216    pub fn parse(s: &str) -> Result<Self, StatusListError> {
217        match s {
218            "VALID" => Ok(Self::VALID),
219            "INVALID" => Ok(Self::INVALID),
220            "SUSPENDED" => Ok(Self::SUSPENDED),
221            digits if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) => digits
222                .parse()
223                .map(Self)
224                .map_err(|_| StatusListError::UnknownStatusType(s.to_owned())),
225            _ => Err(StatusListError::UnknownStatusType(s.to_owned())),
226        }
227    }
228}
229
230impl fmt::Display for StatusType {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        match self.name() {
233            Some(name) => write!(f, "{name} ({:#04x})", self.0),
234            None => write!(f, "{:#04x}", self.0),
235        }
236    }
237}
238
239impl From<u8> for StatusType {
240    fn from(value: u8) -> Self {
241        Self(value)
242    }
243}
244
245impl FromStr for StatusType {
246    type Err = StatusListError;
247
248    fn from_str(s: &str) -> Result<Self, Self::Err> {
249        Self::parse(s)
250    }
251}
252
253impl Serialize for StatusType {
254    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
255        match self.name() {
256            Some(name) => serializer.serialize_str(name),
257            None => serializer.serialize_u8(self.0),
258        }
259    }
260}
261
262impl<'de> Deserialize<'de> for StatusType {
263    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
264        struct StatusTypeVisitor;
265
266        impl serde::de::Visitor<'_> for StatusTypeVisitor {
267            type Value = StatusType;
268
269            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270                f.write_str("VALID, INVALID, SUSPENDED or a number in 0..=255")
271            }
272
273            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<StatusType, E> {
274                StatusType::parse(s).map_err(E::custom)
275            }
276
277            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<StatusType, E> {
278                u8::try_from(value)
279                    .map(StatusType)
280                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(value), &self))
281            }
282
283            fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<StatusType, E> {
284                u8::try_from(value)
285                    .map(StatusType)
286                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(value), &self))
287            }
288        }
289
290        deserializer.deserialize_any(StatusTypeVisitor)
291    }
292}
293
294/// Why a status list or status list token could not be used.
295#[derive(Debug, thiserror::Error)]
296#[non_exhaustive]
297pub enum StatusListError {
298    /// `bits` is not 1, 2, 4 or 8.
299    #[error("`bits` is {0}, not 1, 2, 4 or 8")]
300    InvalidBits(u8),
301    /// A status value does not fit in `bits`.
302    #[error("status value {value} does not fit in {bits} bits")]
303    InvalidStatusValue {
304        /// The value.
305        value: u8,
306        /// The bits per status.
307        bits: u8,
308    },
309    /// The index is beyond the end of the list.
310    #[error("index {idx} is out of range of a status list of {len} entries")]
311    IndexOutOfRange {
312        /// The index.
313        idx: u64,
314        /// The number of entries in the list.
315        len: usize,
316    },
317    /// `lst` is not base64url, or not a ZLIB-compressed byte array. The source is the base64url
318    /// error, when that is the cause.
319    #[error("invalid status list: {reason}{}", cause(.source.as_ref()))]
320    Compression {
321        /// What is wrong with `lst`.
322        reason: String,
323        /// The underlying error.
324        source: Option<Box<dyn std::error::Error + Send + Sync>>,
325    },
326    /// The decompressed list is larger than the limit.
327    #[error("the status list decompresses to more than {limit} bytes")]
328    TooLarge {
329        /// The limit.
330        limit: usize,
331    },
332    /// The status list token is not a compact JWS this crate decodes.
333    #[error("invalid JWS: {0}")]
334    Jws(#[from] JwsError),
335    /// A string that is neither a registered status type name of its own nor a number in
336    /// `0..=255`.
337    #[error("{0:?} is not VALID, INVALID, SUSPENDED or a number in 0..=255")]
338    UnknownStatusType(String),
339    /// The status list token's `typ` is not `statuslist+jwt`.
340    #[error("header `typ` is {0:?}, not `statuslist+jwt`")]
341    UnexpectedTyp(Option<String>),
342    /// The status list token's payload is not a status list token claims set; the source is
343    /// the JSON error.
344    #[error("the payload is not a status list token: {0}")]
345    Payload(#[source] serde_json::Error),
346    /// The token's `sub` is not the `uri` of the reference.
347    #[error("status list token `sub` {sub:?} is not the referenced {uri:?}")]
348    SubjectMismatch {
349        /// The token's `sub`.
350        sub: String,
351        /// The reference's `uri`.
352        uri: String,
353    },
354    /// The status list token has expired.
355    #[error("status list token expired at {} (now is {})", expired_at.to_rfc3339(), now.to_rfc3339())]
356    Expired {
357        /// Its `exp`.
358        expired_at: DateTime<Utc>,
359        /// The validation time.
360        now: DateTime<Utc>,
361    },
362    /// The status list token was issued after the validation time, beyond the leeway.
363    #[error("status list token issued at {}, after now ({})", issued_at.to_rfc3339(), now.to_rfc3339())]
364    NotYetIssued {
365        /// Its `iat`.
366        issued_at: DateTime<Utc>,
367        /// The validation time.
368        now: DateTime<Utc>,
369    },
370}
371
372/// A status list (Token Status List §4): one status of `bits` bits per referenced token,
373/// packed into a byte array from the least significant bit up, ZLIB-compressed and
374/// base64url-encoded as `lst` in JSON.
375///
376/// # Examples
377///
378/// ```
379/// use identity_kit::status_list::{StatusList, StatusType};
380/// use serde_json::json;
381///
382/// // Token Status List §4.1: 16 statuses of 1 bit.
383/// let list: StatusList = serde_json::from_value(json!({ "bits": 1, "lst": "eNrbuRgAAhcBXQ" }))?;
384/// assert_eq!(list.as_bytes(), &[0xb9, 0xa3]);
385/// assert_eq!(list.get(0), Some(StatusType::INVALID));
386/// assert_eq!(list.get(1), Some(StatusType::VALID));
387/// assert_eq!(list.get(15), Some(StatusType::INVALID));
388/// assert_eq!(list.get(16), None);
389///
390/// let mut rebuilt = StatusList::new(1, 16)?;
391/// for index in [0, 3, 4, 5, 7, 8, 9, 13, 15] {
392///     rebuilt.set(index, StatusType::INVALID)?;
393/// }
394/// assert_eq!(rebuilt.as_bytes(), list.as_bytes());
395/// # Ok::<(), Box<dyn std::error::Error>>(())
396/// ```
397#[derive(Debug, Clone, PartialEq, Eq)]
398pub struct StatusList {
399    bits: u8,
400    bytes: Vec<u8>,
401    aggregation_uri: Option<String>,
402}
403
404impl StatusList {
405    /// The largest decompressed list [`Deserialize`] accepts: 16 MiB, room for 16 million
406    /// 8-bit statuses.
407    pub const MAX_BYTES: usize = 1 << 24;
408
409    /// An all-`VALID` list of `size` statuses of `bits` bits each.
410    ///
411    /// # Errors
412    ///
413    /// [`StatusListError::InvalidBits`] unless `bits` is 1, 2, 4 or 8.
414    pub fn new(bits: u8, size: usize) -> Result<Self, StatusListError> {
415        check_bits(bits)?;
416        let bytes = vec![0; (size * usize::from(bits)).div_ceil(8)];
417        Ok(Self {
418            bits,
419            bytes,
420            aggregation_uri: None,
421        })
422    }
423
424    /// A list over the uncompressed byte array `bytes`.
425    ///
426    /// # Errors
427    ///
428    /// [`StatusListError::InvalidBits`] unless `bits` is 1, 2, 4 or 8.
429    pub fn from_bytes(bits: u8, bytes: Vec<u8>) -> Result<Self, StatusListError> {
430        check_bits(bits)?;
431        Ok(Self {
432            bits,
433            bytes,
434            aggregation_uri: None,
435        })
436    }
437
438    /// This list with `aggregation_uri`.
439    #[must_use]
440    pub fn with_aggregation_uri(mut self, uri: impl Into<String>) -> Self {
441        self.aggregation_uri = Some(uri.into());
442        self
443    }
444
445    /// The bits per status: 1, 2, 4 or 8.
446    pub const fn bits(&self) -> u8 {
447        self.bits
448    }
449
450    /// The uncompressed byte array.
451    pub fn as_bytes(&self) -> &[u8] {
452        &self.bytes
453    }
454
455    /// The `aggregation_uri`, if any.
456    pub fn aggregation_uri(&self) -> Option<&str> {
457        self.aggregation_uri.as_deref()
458    }
459
460    /// The number of statuses the list holds.
461    pub fn len(&self) -> usize {
462        self.bytes.len() * 8 / usize::from(self.bits)
463    }
464
465    /// Whether the list holds no status.
466    pub fn is_empty(&self) -> bool {
467        self.bytes.is_empty()
468    }
469
470    /// The status at `index`, or `None` beyond the end of the list.
471    pub fn get(&self, index: u64) -> Option<StatusType> {
472        let (byte, shift) = self.position(index)?;
473        let mask = self.mask();
474        Some(StatusType((self.bytes.get(byte)? >> shift) & mask))
475    }
476
477    /// Sets the status at `index`.
478    ///
479    /// # Errors
480    ///
481    /// [`StatusListError::IndexOutOfRange`] or [`StatusListError::InvalidStatusValue`] when
482    /// the value does not fit in `bits`.
483    pub fn set(&mut self, index: u64, status: StatusType) -> Result<(), StatusListError> {
484        let mask = self.mask();
485        if status.0 & !mask != 0 {
486            return Err(StatusListError::InvalidStatusValue {
487                value: status.0,
488                bits: self.bits,
489            });
490        }
491        let len = self.len();
492        let out_of_range = || StatusListError::IndexOutOfRange { idx: index, len };
493        let (byte, shift) = self.position(index).ok_or_else(out_of_range)?;
494        let slot = self.bytes.get_mut(byte).ok_or_else(out_of_range)?;
495        *slot = (*slot & !(mask << shift)) | (status.0 << shift);
496        Ok(())
497    }
498
499    /// The byte and the bit offset of `index`.
500    fn position(&self, index: u64) -> Option<(usize, u8)> {
501        let bits = u64::from(self.bits);
502        let bit = index.checked_mul(bits)?;
503        let byte = usize::try_from(bit / 8).ok()?;
504        let shift = u8::try_from(bit % 8).ok()?;
505        (byte < self.bytes.len()).then_some((byte, shift))
506    }
507
508    /// The mask of one status.
509    const fn mask(&self) -> u8 {
510        if self.bits == 8 {
511            0xff
512        } else {
513            (1 << self.bits) - 1
514        }
515    }
516
517    /// The ZLIB-compressed byte array, base64url-encoded: the `lst` member.
518    pub fn to_lst(&self) -> String {
519        let compressed = miniz_oxide::deflate::compress_to_vec_zlib(&self.bytes, 10);
520        base64url::encode(&compressed)
521    }
522
523    /// Decodes `lst`, refusing a list that decompresses to more than `max_bytes`.
524    ///
525    /// # Errors
526    ///
527    /// [`StatusListError::InvalidBits`], [`StatusListError::Compression`] or
528    /// [`StatusListError::TooLarge`].
529    pub fn from_lst(bits: u8, lst: &str, max_bytes: usize) -> Result<Self, StatusListError> {
530        check_bits(bits)?;
531        let compressed = base64url::decode(lst).map_err(|e| StatusListError::Compression {
532            reason: "`lst` is not base64url".to_owned(),
533            source: Some(Box::new(e)),
534        })?;
535        let bytes = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&compressed, max_bytes)
536            .map_err(|e| match e.status {
537                miniz_oxide::inflate::TINFLStatus::HasMoreOutput => {
538                    StatusListError::TooLarge { limit: max_bytes }
539                }
540                status => StatusListError::Compression {
541                    reason: format!("`lst` is not ZLIB data: {status:?}"),
542                    source: None,
543                },
544            })?;
545        Ok(Self {
546            bits,
547            bytes,
548            aggregation_uri: None,
549        })
550    }
551}
552
553/// Checks `bits` is 1, 2, 4 or 8.
554fn check_bits(bits: u8) -> Result<(), StatusListError> {
555    match bits {
556        1 | 2 | 4 | 8 => Ok(()),
557        _ => Err(StatusListError::InvalidBits(bits)),
558    }
559}
560
561/// The JSON form of a [`StatusList`].
562#[derive(Serialize, Deserialize)]
563struct StatusListJson {
564    bits: u8,
565    lst: String,
566    #[serde(default, skip_serializing_if = "Option::is_none")]
567    aggregation_uri: Option<String>,
568}
569
570impl Serialize for StatusList {
571    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
572        StatusListJson {
573            bits: self.bits,
574            lst: self.to_lst(),
575            aggregation_uri: self.aggregation_uri.clone(),
576        }
577        .serialize(serializer)
578    }
579}
580
581impl<'de> Deserialize<'de> for StatusList {
582    /// Decodes `lst` with [`StatusList::MAX_BYTES`] as the limit.
583    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
584        let json = StatusListJson::deserialize(deserializer)?;
585        let mut list = Self::from_lst(json.bits, &json.lst, Self::MAX_BYTES)
586            .map_err(serde::de::Error::custom)?;
587        list.aggregation_uri = json.aggregation_uri;
588        Ok(list)
589    }
590}
591
592/// The claims of a status list token in JWT format (Token Status List §5.1).
593///
594/// # Examples
595///
596/// ```
597/// use chrono::{TimeZone as _, Utc};
598/// use identity_kit::status_list::{StatusListRef, StatusListToken, StatusType};
599/// use identity_kit::vc::Jwt;
600/// use identity_kit::vc::validation::TimeOptions;
601///
602/// // Token Status List §8.2.
603/// let jwt: Jwt = "eyJhbGciOiJFUzI1NiIsImtpZCI6IjEyIiwidHlwIjoic3RhdHVzbGlzdCtqd3QifQ.e\
604///     yJleHAiOjIyOTE3MjAxNzAsImlhdCI6MTY4NjkyMDE3MCwiaXNzIjoiaHR0cHM6Ly9leGFtcGxlLmNvbSIsInN0YXR1\
605///     c19saXN0Ijp7ImJpdHMiOjEsImxzdCI6ImVOcmJ1UmdBQWhjQlhRIn0sInN1YiI6Imh0dHBzOi8vZXhhbXBsZS5jb20\
606///     vc3RhdHVzbGlzdHMvMSIsInR0bCI6NDMyMDB9.2lKUUNG503R9htu4aHAYi7vjmr3sgApbfoDvPrl65N3URUO1EYqq\
607///     Ql45Jfzd-Av4QzlKa3oVALpLwOEUOq-U_g".parse()?;
608/// let (header, token) = StatusListToken::decode(&jwt)?;
609/// assert_eq!(header.kid.as_deref(), Some("12"));
610/// assert_eq!(token.sub, "https://example.com/statuslists/1");
611/// assert_eq!(token.ttl, Some(43200));
612///
613/// let now = TimeOptions::at(Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap());
614/// let reference = StatusListRef::new("https://example.com/statuslists/1", 0);
615/// assert_eq!(token.status_of(&reference, now)?, StatusType::INVALID);
616/// assert_eq!(token.status_of(&StatusListRef::new(&reference.uri, 1), now)?, StatusType::VALID);
617/// assert!(token.status_of(&StatusListRef::new(&reference.uri, 16), now).is_err());
618/// # Ok::<(), Box<dyn std::error::Error>>(())
619/// ```
620#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
621#[non_exhaustive]
622pub struct StatusListToken {
623    /// `sub`: the URI of the token, the `uri` referenced tokens use.
624    pub sub: String,
625    /// `iat`: when the token was issued. A `NumericDate` with a fraction is floored.
626    #[serde(deserialize_with = "crate::vc::required_numeric_date")]
627    pub iat: i64,
628    /// `exp`: when the token expires. A `NumericDate` with a fraction is floored.
629    #[serde(
630        default,
631        skip_serializing_if = "Option::is_none",
632        deserialize_with = "crate::vc::numeric_date"
633    )]
634    pub exp: Option<i64>,
635    /// `ttl`: how many seconds the token may be cached.
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub ttl: Option<u64>,
638    /// `status_list`: the list.
639    pub status_list: StatusList,
640    /// Every other claim, in insertion order.
641    #[serde(flatten)]
642    pub additional: IndexMap<String, Value>,
643}
644
645impl StatusListToken {
646    /// The `typ` of a status list token, `statuslist+jwt`.
647    pub const TYP: &'static str = "statuslist+jwt";
648
649    /// The media type of a status list token, `application/statuslist+jwt`.
650    pub const MEDIA_TYPE: &'static str = "application/statuslist+jwt";
651
652    /// A token for the list at `sub`, issued at `iat`.
653    pub fn new(sub: impl Into<String>, iat: DateTime<Utc>, status_list: StatusList) -> Self {
654        Self {
655            sub: sub.into(),
656            iat: JwtClaims::numeric_date(iat),
657            exp: None,
658            ttl: None,
659            status_list,
660            additional: IndexMap::new(),
661        }
662    }
663
664    /// This token with `exp`.
665    #[must_use]
666    pub fn with_expires_at(mut self, time: DateTime<Utc>) -> Self {
667        self.exp = Some(JwtClaims::numeric_date(time));
668        self
669    }
670
671    /// This token with `ttl`.
672    #[must_use]
673    pub fn with_ttl(mut self, seconds: u64) -> Self {
674        self.ttl = Some(seconds);
675        self
676    }
677
678    /// This token with the claim `name` set to `value`.
679    #[must_use]
680    pub fn with_claim(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
681        self.additional.insert(name.into(), value.into());
682        self
683    }
684
685    /// Decodes `jwt` without verifying it: the header, whose `typ` must be
686    /// `statuslist+jwt`, and the claims.
687    ///
688    /// # Errors
689    ///
690    /// [`StatusListError::Jws`], [`StatusListError::UnexpectedTyp`] or
691    /// [`StatusListError::Payload`].
692    pub fn decode(jwt: &Jwt) -> Result<(JwsHeader, Self), StatusListError> {
693        let jws = jwt.decode()?;
694        if jws.header().typ.as_deref() != Some(Self::TYP) {
695            return Err(StatusListError::UnexpectedTyp(jws.header().typ.clone()));
696        }
697        let token = serde_json::from_slice(jws.payload()).map_err(StatusListError::Payload)?;
698        Ok((jws.header().clone(), token))
699    }
700
701    /// Signs this token with `signer`, `typ: statuslist+jwt` and what names the signer's key
702    /// ([`JwsHeader::for_signer`]): its certificate chain in `x5c`, or else its `kid`.
703    ///
704    /// # Errors
705    ///
706    /// [`StatusListError::Jws`] when signing fails.
707    ///
708    /// # Panics
709    ///
710    /// Never: the token always serializes to JSON, and the JWS is one this function has just
711    /// encoded.
712    pub async fn sign(&self, signer: &dyn Signer) -> Result<Jwt, StatusListError> {
713        let header = JwsHeader::for_signer(signer).with_typ(Self::TYP);
714        let payload = serde_json::to_vec(self).expect("a token serializes");
715        let jwt = crate::jose::encode_compact(&header, &payload, signer).await?;
716        Ok(Jwt::new(jwt).expect("a freshly encoded JWS decodes"))
717    }
718
719    /// The status of the token `reference` points at (Token Status List §8.3, steps 4 to 6):
720    /// `sub` must be the referenced URI, the token must not have been issued after `time` nor
721    /// have expired at it, each with its leeway, and the index must be in range.
722    ///
723    /// # Errors
724    ///
725    /// [`StatusListError::SubjectMismatch`], [`StatusListError::NotYetIssued`],
726    /// [`StatusListError::Expired`] or [`StatusListError::IndexOutOfRange`].
727    pub fn status_of(
728        &self,
729        reference: &StatusListRef,
730        time: TimeOptions,
731    ) -> Result<StatusType, StatusListError> {
732        if self.sub != reference.uri {
733            return Err(StatusListError::SubjectMismatch {
734                sub: self.sub.clone(),
735                uri: reference.uri.clone(),
736            });
737        }
738        let (now, earliest, latest) = time.window();
739        // An `iat` past the range `chrono` represents is as far in the future or past as its sign.
740        let issued_at = JwtClaims::timestamp(self.iat).unwrap_or(if self.iat > 0 {
741            DateTime::<Utc>::MAX_UTC
742        } else {
743            DateTime::<Utc>::MIN_UTC
744        });
745        if issued_at > latest {
746            return Err(StatusListError::NotYetIssued { issued_at, now });
747        }
748        if let Some(exp) = self.exp {
749            let expired_at = JwtClaims::timestamp(exp).unwrap_or(DateTime::<Utc>::MIN_UTC);
750            if expired_at <= earliest {
751                return Err(StatusListError::Expired { expired_at, now });
752            }
753        }
754        self.status_list
755            .get(reference.idx)
756            .ok_or(StatusListError::IndexOutOfRange {
757                idx: reference.idx,
758                len: self.status_list.len(),
759            })
760    }
761}