identity_kit/status_list/
check.rs1use 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
15pub 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 pub const MAX_REDIRECTS: usize = 3;
57}
58
59impl<C: HttpClient, R: KeyResolver, V: JwsVerifier> StatusListCheck<C, R, V> {
60 pub fn new(client: C, resolver: R, verifier: V) -> Self {
63 Self {
64 client,
65 resolver,
66 verifier,
67 }
68 }
69
70 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 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 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}