1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Registry HTTP transport seam.
//!
//! [`RegistryHttp`] is the test seam; [`ReqwestRegistryHttp`] is the production
//! transport for package registries and deps.dev. The retry helpers use the
//! reference-side policy: four attempts, sleeping 1s/2s/4s between retryable
//! responses (429 and 5xx gateway/service errors) and transport failures.
//!
//! `download_limited` additionally enforces a byte cap while streaming, so a
//! registry cannot exhaust memory. A cap rejection is a typed
//! [`DownloadTooLarge`] error and is never retried.
//!
//! Non-success statuses surface as [`HttpStatusError`], which preserves the
//! `Retry-After` and rate-limit headers so per-host governors (`host`) can
//! back off. Error text never includes URL userinfo, query strings, or
//! fragments.
use std::fmt;
use std::time::{Duration, UNIX_EPOCH};
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
use futures::StreamExt;
use serde_json::Value;
pub const USER_AGENT: &str = "vuln-notif/1.0 (+https://github.com/scanoss/purl2cpe)";
pub const HTTP_TIMEOUT: Duration = Duration::from_secs(60);
pub const RETRY_DELAYS: [Duration; 3] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
];
/// A byte-cap rejection. Match with `anyhow::Error::downcast_ref`; size-cap
/// failures are never retried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DownloadTooLarge {
pub url: String,
pub limit: u64,
/// Known size: the declared Content-Length, or the downloaded byte count
/// for the defaulted `download` fallback.
pub size: Option<u64>,
}
impl fmt::Display for DownloadTooLarge {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.size {
Some(size) => write!(
formatter,
"artifact {} is {size} bytes, over the {}-byte limit",
redact_url(&self.url),
self.limit
),
None => write!(
formatter,
"artifact {} exceeds the {}-byte limit",
redact_url(&self.url),
self.limit
),
}
}
}
impl std::error::Error for DownloadTooLarge {}
/// A non-success HTTP status with the rate-limit headers that came with it.
///
/// `url` is already redacted: userinfo, query, and fragment are removed before
/// the value is stored, so the error can be logged safely.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpStatusError {
pub status: u16,
pub url: String,
pub retry_after: Option<String>,
pub rate_limit_remaining: Option<u64>,
pub rate_limit_reset: Option<u64>,
}
impl HttpStatusError {
pub fn new(status: u16, url: &str) -> Self {
Self {
status,
url: redact_url(url),
retry_after: None,
rate_limit_remaining: None,
rate_limit_reset: None,
}
}
/// Delay implied by rate-limit signals, or `None` when this response is
/// not a rate-limit response.
///
/// A 429 always backs off (one second without `Retry-After`). A 403 backs
/// off only when it carries `Retry-After` or exhausted/`reset` rate-limit
/// headers; a plain authorization 403 returns `None`.
pub fn rate_limit_delay(&self, now_unix: f64) -> Option<Duration> {
let seconds = match self.status {
429 => self
.retry_after
.as_deref()
.and_then(|value| parse_retry_after(value, now_unix))
.unwrap_or(1.0),
403 => {
if let Some(seconds) = self
.retry_after
.as_deref()
.and_then(|value| parse_retry_after(value, now_unix))
{
seconds
} else if self.rate_limit_remaining == Some(0) || self.rate_limit_reset.is_some() {
self.rate_limit_reset.map_or(1.0, |reset| {
let reset = reset as f64;
if reset > now_unix {
reset - now_unix
} else {
reset
}
})
} else {
return None;
}
}
_ => return None,
};
Some(Duration::from_secs_f64(seconds.max(0.0)))
}
}
impl fmt::Display for HttpStatusError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "HTTP {} for {}", self.status, self.url)
}
}
impl std::error::Error for HttpStatusError {}
/// Parse `Retry-After`: a numeric number of seconds first, else an HTTP date.
pub fn parse_retry_after(value: &str, now_unix: f64) -> Option<f64> {
let value = value.trim();
if let Ok(seconds) = value.parse::<f64>() {
return Some(seconds.max(0.0));
}
let retry_at = httpdate::parse_http_date(value).ok()?;
let retry_at = retry_at
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0);
Some((retry_at - now_unix).max(0.0))
}
/// Strip URL userinfo, query, and fragment before a URL is shown in an error.
///
/// Scheme, host, port, and path are kept; nothing else is needed to identify
/// the failing request and everything else can carry credentials.
pub fn redact_url(url: &str) -> String {
let url = url.split('#').next().unwrap_or(url);
let url = url.split('?').next().unwrap_or(url);
match url.split_once("://") {
Some((scheme, rest)) => {
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..end];
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
format!("{scheme}://{host}{}", &rest[end..])
}
None => url.to_owned(),
}
}
#[async_trait]
pub trait RegistryHttp: Send + Sync {
async fn get_json(&self, url: &str) -> Result<Value>;
/// GET with request headers. Defaulted so existing fakes keep compiling;
/// the default ignores the headers. [`ReqwestRegistryHttp`] sends them.
///
/// Headers carry credentials (for example a Gitee bearer token); this
/// method never logs them and callers must not either.
async fn get_json_with_headers(
&self,
url: &str,
_headers: &[(String, String)],
) -> Result<Value> {
self.get_json(url).await
}
async fn get_text(&self, url: &str) -> Result<String>;
async fn head_size(&self, url: &str) -> Result<u64>;
/// Fetch the whole artifact. Only used for hashing and size.
async fn download(&self, url: &str) -> Result<Vec<u8>>;
/// Fetch an artifact with a hard byte cap.
///
/// Defaulted so existing fakes keep compiling: the fallback downloads in
/// full and then checks the size. [`ReqwestRegistryHttp`] streams instead
/// and rejects from `Content-Length` before reading any body.
async fn download_limited(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>> {
let bytes = self.download(url).await?;
if bytes.len() as u64 > max_bytes {
return Err(DownloadTooLarge {
url: url.to_owned(),
limit: max_bytes,
size: Some(bytes.len() as u64),
}
.into());
}
Ok(bytes)
}
/// POST a JSON body and decode a JSON response.
///
/// Unsupported by default so fakes that only serve GET requests keep
/// compiling; [`ReqwestRegistryHttp`] implements it with the same retry
/// policy as [`RegistryHttp::get_json`].
async fn post_json(&self, url: &str, _body: &Value) -> Result<Value> {
Err(anyhow!("POST {url} is not supported by this transport"))
}
}
pub struct ReqwestRegistryHttp {
client: reqwest::Client,
}
impl ReqwestRegistryHttp {
pub fn new() -> Result<Self> {
let client = reqwest::Client::builder()
.timeout(HTTP_TIMEOUT)
.user_agent(USER_AGENT)
.redirect(reqwest::redirect::Policy::limited(10))
.build()
.context("build registry HTTP client")?;
Ok(Self { client })
}
pub fn with_client(client: reqwest::Client) -> Self {
Self { client }
}
async fn get_response(&self, url: &str) -> Result<reqwest::Response> {
self.send_with_retry(url, || self.client.get(url)).await
}
async fn get_response_with_headers(
&self,
url: &str,
headers: &[(String, String)],
) -> Result<reqwest::Response> {
self.send_with_retry(url, || {
let mut request = self.client.get(url);
for (name, value) in headers {
request = request.header(name.as_str(), value.as_str());
}
request
})
.await
}
async fn post_response(&self, url: &str, body: &Value) -> Result<reqwest::Response> {
self.send_with_retry(url, || self.client.post(url).json(body))
.await
}
async fn send_with_retry<F>(&self, url: &str, build: F) -> Result<reqwest::Response>
where
F: Fn() -> reqwest::RequestBuilder,
{
let mut last_error: Option<anyhow::Error> = None;
for attempt in 0..=RETRY_DELAYS.len() {
if attempt > 0 {
tokio::time::sleep(RETRY_DELAYS[attempt - 1]).await;
}
match build().send().await {
Ok(response) => {
let status = response.status();
if status == reqwest::StatusCode::OK {
return Ok(response);
}
let error = status_error(status, url, response.headers());
if retryable(status) {
last_error = Some(error);
continue;
}
return Err(error);
}
Err(error) => {
last_error = Some(anyhow!(
"request failed for {}: {}",
redact_url(url),
error.without_url()
));
}
}
}
Err(last_error.unwrap_or_else(|| anyhow!("request failed for {}", redact_url(url))))
}
/// Download with retries, an early `Content-Length` rejection, and a
/// streaming cap. Size-cap rejections return immediately.
async fn fetch_bytes(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>> {
let mut last_error: Option<anyhow::Error> = None;
for attempt in 0..=RETRY_DELAYS.len() {
if attempt > 0 {
tokio::time::sleep(RETRY_DELAYS[attempt - 1]).await;
}
match self.client.get(url).send().await {
Ok(response) => {
let status = response.status();
if status != reqwest::StatusCode::OK {
let error = status_error(status, url, response.headers());
if retryable(status) {
last_error = Some(error);
continue;
}
return Err(error);
}
if let Some(size) = response
.content_length()
.or_else(|| header_content_length(&response))
&& size > max_bytes
{
return Err(DownloadTooLarge {
url: url.to_owned(),
limit: max_bytes,
size: Some(size),
}
.into());
}
match read_capped(response, url, max_bytes).await {
Ok(bytes) => return Ok(bytes),
Err(error) if error.downcast_ref::<DownloadTooLarge>().is_some() => {
return Err(error);
}
Err(error) => last_error = Some(error),
}
}
Err(error) => {
last_error = Some(anyhow!(
"request failed for {}: {}",
redact_url(url),
error.without_url()
))
}
}
}
Err(last_error.unwrap_or_else(|| anyhow!("request failed for {}", redact_url(url))))
}
}
fn retryable(status: reqwest::StatusCode) -> bool {
matches!(status.as_u16(), 429 | 500 | 502 | 503 | 504)
}
fn status_error(
status: reqwest::StatusCode,
url: &str,
headers: &reqwest::header::HeaderMap,
) -> anyhow::Error {
let mut error = HttpStatusError::new(status.as_u16(), url);
error.retry_after = header_value(headers, &["retry-after"]);
error.rate_limit_remaining =
header_value(headers, &["x-ratelimit-remaining", "ratelimit-remaining"])
.and_then(|value| value.parse().ok());
error.rate_limit_reset = header_value(headers, &["x-ratelimit-reset", "ratelimit-reset"])
.and_then(|value| value.parse().ok());
error.into()
}
fn header_value(headers: &reqwest::header::HeaderMap, names: &[&str]) -> Option<String> {
names.iter().find_map(|name| {
headers
.get(*name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
})
}
fn header_content_length(response: &reqwest::Response) -> Option<u64> {
response
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok())
}
async fn read_capped(response: reqwest::Response, url: &str, max_bytes: u64) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|error| {
anyhow!(
"read body from {}: {}",
redact_url(url),
error.without_url()
)
})?;
if bytes.len() as u64 + chunk.len() as u64 > max_bytes {
return Err(DownloadTooLarge {
url: url.to_owned(),
limit: max_bytes,
size: None,
}
.into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
#[async_trait]
impl RegistryHttp for ReqwestRegistryHttp {
async fn get_json(&self, url: &str) -> Result<Value> {
let response = self.get_response(url).await?;
response.json::<Value>().await.map_err(|error| {
anyhow!(
"decode JSON from {}: {}",
redact_url(url),
error.without_url()
)
})
}
async fn get_json_with_headers(
&self,
url: &str,
headers: &[(String, String)],
) -> Result<Value> {
let response = self.get_response_with_headers(url, headers).await?;
response.json::<Value>().await.map_err(|error| {
anyhow!(
"decode JSON from {}: {}",
redact_url(url),
error.without_url()
)
})
}
async fn get_text(&self, url: &str) -> Result<String> {
let response = self.get_response(url).await?;
response.text().await.map_err(|error| {
anyhow!(
"read text from {}: {}",
redact_url(url),
error.without_url()
)
})
}
async fn head_size(&self, url: &str) -> Result<u64> {
let response = self.send_with_retry(url, || self.client.head(url)).await?;
let raw = response
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.unwrap_or("0");
raw.parse::<u64>()
.with_context(|| format!("invalid Content-Length {raw:?} from {}", redact_url(url)))
}
async fn download(&self, url: &str) -> Result<Vec<u8>> {
self.fetch_bytes(url, u64::MAX).await
}
async fn download_limited(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>> {
self.fetch_bytes(url, max_bytes).await
}
async fn post_json(&self, url: &str, body: &Value) -> Result<Value> {
let response = self.post_response(url, body).await?;
response.json::<Value>().await.map_err(|error| {
anyhow!(
"decode JSON from {}: {}",
redact_url(url),
error.without_url()
)
})
}
}