Skip to main content

identity_kit/status_list/
check.rs

1//! [`StatusListCheck`]: the Token Status List as a [`StatusCheck`], over an [`HttpClient`].
2
3use url::Url;
4
5use crate::jose::{DefaultVerifier, JwsVerifier};
6use crate::methods::web::{HttpClient, HttpResponse, fetchable};
7use crate::resolver::{JwsKeyError, KeyReference, KeyResolver, KeyRole, resolve_jws_key};
8use crate::vc::Jwt;
9use crate::vc::validation::{CredentialStatus, StatusCheck, StatusError, TimeOptions};
10
11use super::{StatusListError, StatusListToken, StatusMechanism};
12
13type BoxError = Box<dyn std::error::Error + Send + Sync>;
14
15/// A [`StatusCheck`] for the Token Status List: for the `status` claim of an SD-JWT
16/// credential or of a JWT credential ([`CredentialStatus::StatusClaim`]), fetches the status
17/// list token from the referenced URI with an [`HttpClient`], verifies it was signed by
18/// the key its header names ([`KeyReference::candidates`] with the token's `iss`, the first
19/// of them the resolver handles), resolved for [`KeyRole::Issuer`] at the validation time,
20/// checks it was issued by the validation time and has not expired,
21/// each within the validation's leeway ([`StatusListToken::status_of`]), and reads the status
22/// at the referenced index (Token Status List §8).
23///
24/// When the token has an `iss`, the key must belong to it ([`KeyReference::binds_to`]);
25/// without one, only a key named by a DID URL or certified by an `x5c` chain is accepted,
26/// since a key by value or a key set could be anybody's. HAIP 1.0 §6.1 requires the chain:
27/// with the `x509` feature, give the check an `X509Resolver`. Beyond that the check trusts the
28/// key the reference resolves to; whether that key may speak for the list is the
29/// application's policy to enforce around it, by restricting the resolver, say. That matters
30/// most for a token without `iss` under a chain: any certificate under the resolver's trust
31/// anchors signs it, so give the check trust anchors that certify status list issuers only.
32///
33/// # Fetching
34///
35/// Every request asks for `application/statuslist+jwt` ([`StatusListToken::MEDIA_TYPE`])
36/// through [`HttpClient::get_accepting`]. `ReqwestClient` (feature `reqwest`) also
37/// negotiates gzip, which the draft recommends Status Providers use.
38///
39/// A 301, 302, 303, 307 or 308 response is followed, as the draft recommends: its
40/// [`location`](HttpResponse::location) is resolved against the URL
41/// that returned it and fetched with a new request through the same client, so that every
42/// hop passes the client's checks. The check refuses a target that is not `https` (unless the
43/// client [allows plain `http`](HttpClient::allows_plain_http) for it), a URL
44/// already visited (a loop), a redirect without a `Location`, and more than
45/// [`MAX_REDIRECTS`](Self::MAX_REDIRECTS) redirects.
46///
47/// The status list URI comes from the credential, and a redirect target from whoever serves
48/// it, so the client fetches whatever an issuer names: `client` must enforce the protections
49/// `ReqwestClient` does (HTTPS only, no redirects of its own, no non-public addresses after
50/// name resolution, a body limit and a timeout), or the status check becomes a request
51/// forgery primitive.
52pub struct StatusListCheck<C, R, V = DefaultVerifier> {
53    client: C,
54    resolver: R,
55    verifier: V,
56}
57
58impl<C, R, V> StatusListCheck<C, R, V> {
59    /// The most redirects one status list fetch follows.
60    pub const MAX_REDIRECTS: usize = 3;
61}
62
63impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> StatusListCheck<C, R, V> {
64    /// A check fetching with `client`, resolving the status issuer's key with `resolver`
65    /// and verifying with `verifier`.
66    pub fn new(client: C, resolver: R, verifier: V) -> Self {
67        Self {
68            client,
69            resolver,
70            verifier,
71        }
72    }
73
74    /// The response for `uri`, following redirects as the type documentation describes.
75    async fn get(&self, uri: &str) -> Result<HttpResponse, StatusError> {
76        let unavailable = |reason: String, source: Option<BoxError>| StatusError::Unavailable {
77            uri: uri.to_owned(),
78            reason,
79            source,
80        };
81        let mut url = Url::parse(uri).map_err(|e| StatusError::InvalidList {
82            uri: uri.to_owned(),
83            reason: "the URI is not a URL".to_owned(),
84            source: Some(Box::new(e)),
85        })?;
86        let mut visited = vec![url.clone()];
87        loop {
88            let response = self
89                .client
90                .get_accepting(&url, StatusListToken::MEDIA_TYPE)
91                .await
92                .map_err(|e| unavailable(format!("fetching {url}"), Some(Box::new(e))))?;
93            if !matches!(response.status, 301 | 302 | 303 | 307 | 308) {
94                return Ok(response);
95            }
96            if visited.len() > Self::MAX_REDIRECTS {
97                return Err(unavailable(
98                    format!("more than {} redirects", Self::MAX_REDIRECTS),
99                    None,
100                ));
101            }
102            let location = response.location.ok_or_else(|| {
103                unavailable(
104                    format!(
105                        "{url} answered HTTP {} without a `Location`",
106                        response.status
107                    ),
108                    None,
109                )
110            })?;
111            let next = url.join(&location).map_err(|e| {
112                unavailable(
113                    format!("redirect from {url} to {location:?}"),
114                    Some(Box::new(e)),
115                )
116            })?;
117            if !fetchable(&self.client, &next) {
118                return Err(unavailable(
119                    format!("redirect from {url} to {next}, which is not HTTPS"),
120                    None,
121                ));
122            }
123            if visited.contains(&next) {
124                return Err(unavailable(format!("redirect loop at {next}"), None));
125            }
126            visited.push(next.clone());
127            url = next;
128        }
129    }
130
131    /// The status list token at `uri`, fetched and verified at `time`.
132    async fn fetch(&self, uri: &str, time: TimeOptions) -> Result<StatusListToken, StatusError> {
133        let invalid = |reason: &str, source: Option<BoxError>| StatusError::InvalidList {
134            uri: uri.to_owned(),
135            reason: reason.to_owned(),
136            source,
137        };
138        let response = self.get(uri).await?;
139        if !(200..300).contains(&response.status) {
140            return Err(StatusError::Unavailable {
141                uri: uri.to_owned(),
142                reason: format!("HTTP {}", response.status),
143                source: None,
144            });
145        }
146        let body = String::from_utf8(response.body)
147            .map_err(|e| invalid("the body is not UTF-8", Some(Box::new(e))))?;
148        let not_a_token = |e: BoxError| invalid("not a status list token", Some(e));
149        let jwt = Jwt::new(body.trim()).map_err(|e| not_a_token(Box::new(e)))?;
150        let (_, token) = StatusListToken::decode(&jwt).map_err(|e| not_a_token(Box::new(e)))?;
151        let jws = jwt.decode().map_err(|e| not_a_token(Box::new(e)))?;
152        let iss = token.additional.get("iss").and_then(|iss| iss.as_str());
153        let (reference, key) = resolve_jws_key(
154            &self.resolver,
155            &jws,
156            iss,
157            KeyRole::Issuer,
158            time.now().timestamp(),
159        )
160        .await
161        .map_err(|error| match error {
162            JwsKeyError::Reference(e) => invalid("no key to verify it with", Some(Box::new(e))),
163            JwsKeyError::Resolution { key, source } => StatusError::UnresolvedKey {
164                uri: uri.to_owned(),
165                key: key.to_string(),
166                source,
167            },
168        })?;
169        jws.verify(&self.verifier, &key)
170            .map_err(|e| invalid("the signature does not verify", Some(Box::new(e))))?;
171        // Without an `iss`, a key by value or a key set could be anybody's; a DID URL names its
172        // DID, and a certificate chain its subject.
173        let bound = match iss {
174            Some(iss) => reference.binds_to(Some(iss), &key),
175            None => match reference {
176                KeyReference::DidUrl(_) => true,
177                KeyReference::X509Chain(_) => reference.binds_to(None, &key),
178                _ => false,
179            },
180        };
181        if !bound {
182            return Err(invalid(
183                &format!("key {reference} does not belong to the issuer {iss:?}"),
184                None,
185            ));
186        }
187        Ok(token)
188    }
189}
190
191#[async_trait::async_trait]
192impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> StatusCheck for StatusListCheck<C, R, V> {
193    /// Checks the Token Status List reference of a `status` claim; a `credentialStatus`
194    /// entry, or a `status` claim without one, is [`StatusError::Unsupported`].
195    async fn check(
196        &self,
197        status: CredentialStatus<'_>,
198        time: TimeOptions,
199    ) -> Result<(), StatusError> {
200        // One validation time for the token's key and for the token.
201        let time = time.pinned();
202        let CredentialStatus::StatusClaim(status) = status else {
203            return Err(StatusError::Unsupported(status.mechanism()));
204        };
205        let Some(reference) = &status.status_list else {
206            let names: Vec<&str> = status
207                .mechanisms()
208                .filter_map(|m| match m {
209                    StatusMechanism::Other { name, .. } => Some(name),
210                    _ => None,
211                })
212                .collect();
213            return Err(StatusError::Unsupported(names.join(", ")));
214        };
215        let uri = &reference.uri;
216        let token = self.fetch(uri, time).await?;
217        let status_type = token.status_of(reference, time).map_err(|e| match e {
218            StatusListError::Expired { expired_at, now } => StatusError::Expired {
219                uri: uri.clone(),
220                expired_at,
221                now,
222            },
223            StatusListError::IndexOutOfRange { idx, len } => StatusError::IndexOutOfRange {
224                uri: uri.clone(),
225                idx,
226                len,
227            },
228            not_yet_issued @ StatusListError::NotYetIssued { .. } => StatusError::InvalidList {
229                uri: uri.clone(),
230                reason: "it was issued after the validation time".to_owned(),
231                source: Some(Box::new(not_yet_issued)),
232            },
233            other => StatusError::InvalidList {
234                uri: uri.clone(),
235                reason: "it does not cover the reference".to_owned(),
236                source: Some(Box::new(other)),
237            },
238        })?;
239        if status_type.is_valid() {
240            Ok(())
241        } else {
242            Err(StatusError::Invalid(status_type.to_string()))
243        }
244    }
245}
246
247impl<C: core::fmt::Debug, R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug
248    for StatusListCheck<C, R, V>
249{
250    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        f.debug_struct("StatusListCheck")
252            .field("client", &self.client)
253            .field("resolver", &self.resolver)
254            .field("verifier", &self.verifier)
255            .finish()
256    }
257}