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
//! OSV.dev source: online query endpoints, offline bulk dumps, and the local
//! advisory cache.
//!
//! Advisory payloads keep the wire shape (`aliases`, `affected[].ranges[].
//! events[]`) so planners can evaluate `introduced`/`fixed`/`last_affected`
//! without a second parse. The cache stores the fields `release_osv` has
//! columns for (aliases, affected, modified); `summary` and `severity` are
//! advisory-only metadata and are not persisted.
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::db::DbHandle;
use crate::db::model::ReleaseOsvMark;
use crate::release::http::RegistryHttp;
pub const DEFAULT_OSV_BASE_URL: &str = "https://api.osv.dev";
/// OSV rejects `querybatch` requests with more than 1000 queries.
pub const OSV_QUERYBATCH_LIMIT: usize = 1000;
/// One `querybatch` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsvQuery {
pub purl: String,
pub version: Option<String>,
}
/// An OSV advisory, trimmed to the fields release ingestion uses.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Advisory {
#[serde(default)]
pub id: String,
#[serde(default)]
pub aliases: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modified: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub severity: Vec<Value>,
#[serde(default)]
pub affected: Vec<AffectedPackage>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AffectedPackage {
#[serde(default)]
pub package: OsvPackage,
#[serde(default)]
pub ranges: Vec<AffectedRange>,
#[serde(default)]
pub versions: Vec<String>,
#[serde(default)]
pub ecosystem_specific: Value,
#[serde(default)]
pub database_specific: Value,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct OsvPackage {
#[serde(default)]
pub ecosystem: String,
#[serde(default)]
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purl: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AffectedRange {
/// `SEMVER`, `ECOSYSTEM`, or `GIT`.
#[serde(rename = "type", default)]
pub kind: String,
#[serde(default)]
pub events: Vec<RangeEvent>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct RangeEvent {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub introduced: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fixed: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_affected: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
struct QueryResponse {
#[serde(default)]
vulns: Vec<Advisory>,
}
#[derive(Debug, Default, Deserialize)]
struct BatchResponse {
#[serde(default)]
results: Vec<BatchResult>,
}
#[derive(Debug, Default, Deserialize)]
struct BatchResult {
#[serde(default)]
vulns: Vec<Advisory>,
}
/// OSV API and bulk-dump client.
pub struct OsvClient {
http: Arc<dyn RegistryHttp>,
base_url: String,
}
impl OsvClient {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self::with_base_url(http, DEFAULT_OSV_BASE_URL)
}
pub fn with_base_url(http: Arc<dyn RegistryHttp>, base_url: impl Into<String>) -> Self {
Self {
http,
base_url: base_url.into().trim_end_matches('/').to_owned(),
}
}
pub fn base_url(&self) -> &str {
&self.base_url
}
fn url(&self, path: &str) -> String {
format!("{}{path}", self.base_url)
}
/// `POST /v1/query` for one purl (optionally pinned to a version).
pub async fn query(&self, purl: &str, version: Option<&str>) -> Result<Vec<Advisory>> {
let body = query_body(&OsvQuery {
purl: purl.to_owned(),
version: version.map(str::to_owned),
});
let payload = self.http.post_json(&self.url("/v1/query"), &body).await?;
let response: QueryResponse =
serde_json::from_value(payload).context("decode OSV query response")?;
Ok(response.vulns)
}
/// `POST /v1/querybatch`, split into batches of at most
/// [`OSV_QUERYBATCH_LIMIT`] queries. Results preserve query order.
pub async fn querybatch(&self, queries: &[OsvQuery]) -> Result<Vec<Vec<Advisory>>> {
let mut results = Vec::with_capacity(queries.len());
for batch in queries.chunks(OSV_QUERYBATCH_LIMIT) {
let body = serde_json::json!({
"queries": batch.iter().map(query_body).collect::<Vec<_>>(),
});
let payload = self
.http
.post_json(&self.url("/v1/querybatch"), &body)
.await?;
let mut response: BatchResponse =
serde_json::from_value(payload).context("decode OSV querybatch response")?;
response
.results
.resize_with(batch.len(), BatchResult::default);
results.extend(
response
.results
.into_iter()
.take(batch.len())
.map(|result| result.vulns),
);
}
Ok(results)
}
/// `GET /v1/vulns/{id}`.
pub async fn get_vuln(&self, id: &str) -> Result<Advisory> {
if id.is_empty()
|| !id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
{
return Err(anyhow!("invalid OSV advisory id: {id}"));
}
let payload = self
.http
.get_json(&self.url(&format!("/v1/vulns/{id}")))
.await?;
serde_json::from_value(payload).with_context(|| format!("decode OSV advisory {id}"))
}
/// Load an offline OSV bulk dump: every `*.json` file in `dir` is one
/// advisory. Files are read in sorted order and no network is touched.
pub fn load_bulk_dir(&self, dir: &Path) -> Result<Vec<Advisory>> {
let entries = std::fs::read_dir(dir)
.with_context(|| format!("read OSV bulk dir {}", dir.display()))?;
let mut paths = Vec::new();
for entry in entries {
let path = entry
.with_context(|| format!("read OSV bulk dir {}", dir.display()))?
.path();
if path.is_file()
&& path
.extension()
.is_some_and(|extension| extension == "json")
{
paths.push(path);
}
}
paths.sort();
let mut advisories = Vec::with_capacity(paths.len());
for path in paths {
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("read OSV advisory {}", path.display()))?;
let advisory = serde_json::from_str(&raw)
.with_context(|| format!("decode OSV advisory {}", path.display()))?;
advisories.push(advisory);
}
Ok(advisories)
}
/// Upsert `release_osv` rows for `purl`.
pub async fn hydrate(
&self,
db: &DbHandle,
repo_did: &str,
purl: &str,
advisories: &[Advisory],
) -> Result<()> {
for advisory in advisories {
if advisory.id.is_empty() {
return Err(anyhow!("OSV advisory without an id"));
}
let aliases_json =
serde_json::to_string(&advisory.aliases).context("serialize OSV aliases")?;
let affected_json =
serde_json::to_string(&advisory.affected).context("serialize OSV affected")?;
db.mark_release_osv(ReleaseOsvMark {
repo_did: repo_did.to_owned(),
purl: purl.to_owned(),
osv_id: advisory.id.clone(),
aliases_json: Some(aliases_json),
affected_json: Some(affected_json),
modified: advisory.modified.clone(),
})
.await?;
}
Ok(())
}
/// Read cached advisories for `purl`. `summary` and `severity` are not
/// part of the cache schema and come back empty.
pub async fn cached(&self, db: &DbHandle, repo_did: &str, purl: &str) -> Result<Vec<Advisory>> {
let rows = db.list_release_osv(repo_did, purl).await?;
rows.into_iter()
.map(|row| {
let aliases = row
.aliases_json
.as_deref()
.map(serde_json::from_str::<Vec<String>>)
.transpose()
.context("decode cached OSV aliases")?
.unwrap_or_default();
let affected = row
.affected_json
.as_deref()
.map(serde_json::from_str::<Vec<AffectedPackage>>)
.transpose()
.context("decode cached OSV affected")?
.unwrap_or_default();
Ok(Advisory {
id: row.osv_id,
aliases,
modified: row.modified,
summary: None,
severity: Vec::new(),
affected,
})
})
.collect()
}
}
/// Whether `identifier` (a CVE, GHSA, or OSV id) names this advisory.
/// Matching is case-insensitive across the id and every alias.
pub fn advisory_matches_cve(advisory: &Advisory, identifier: &str) -> bool {
let identifier = identifier.trim();
if identifier.is_empty() {
return false;
}
std::iter::once(advisory.id.as_str())
.chain(advisory.aliases.iter().map(String::as_str))
.any(|candidate| candidate.eq_ignore_ascii_case(identifier))
}
fn query_body(query: &OsvQuery) -> Value {
let mut package = Map::new();
package.insert("purl".to_owned(), Value::String(query.purl.clone()));
let mut body = Map::new();
body.insert("package".to_owned(), Value::Object(package));
if let Some(version) = &query.version {
body.insert("version".to_owned(), Value::String(version.clone()));
}
Value::Object(body)
}