identity_kit/status_list/
check.rs1use 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
15pub 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 pub const MAX_REDIRECTS: usize = 3;
61}
62
63impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> StatusListCheck<C, R, V> {
64 pub fn new(client: C, resolver: R, verifier: V) -> Self {
67 Self {
68 client,
69 resolver,
70 verifier,
71 }
72 }
73
74 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 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 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 async fn check(
196 &self,
197 status: CredentialStatus<'_>,
198 time: TimeOptions,
199 ) -> Result<(), StatusError> {
200 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}