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