vulnera-advisor 0.1.7

Aggregates security advisories from GHSA, NVD, OSV, CISA KEV, and more
Documentation
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Storage backends for advisory data.
//!
//! This module provides the [`AdvisoryStore`] trait and implementations for
//! persisting and querying vulnerability advisories.

use crate::config::StoreConfig;
use crate::ecosystem::normalize_package_key;
use crate::error::{AdvisoryError, Result};
use crate::models::Advisory;
use async_stream::try_stream;
use async_trait::async_trait;
use futures_util::Stream;
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::pin::Pin;
use std::time::Instant;
use tracing::{info, instrument};

/// Trait for advisory storage backends.
#[async_trait]
pub trait AdvisoryStore: Send + Sync {
    /// Insert or update a batch of advisories.
    async fn upsert_batch(&self, advisories: &[Advisory], source: &str) -> Result<()>;

    /// Get a single advisory by ID.
    async fn get(&self, id: &str) -> Result<Option<Advisory>>;

    /// Get all advisories affecting a specific package.
    async fn get_by_package(&self, ecosystem: &str, package: &str) -> Result<Vec<Advisory>>;

    /// Get the timestamp of the last sync for a source.
    async fn last_sync(&self, source: &str) -> Result<Option<String>>;

    /// Check the health of the store connection.
    async fn health_check(&self) -> Result<HealthStatus>;

    /// Get advisories as a stream for memory-efficient processing.
    async fn get_by_package_stream(
        &self,
        ecosystem: &str,
        package: &str,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Advisory>> + Send + '_>>>;

    /// Get multiple advisories by IDs in a batch.
    async fn get_batch(&self, ids: &[String]) -> Result<Vec<Advisory>>;

    /// Store enrichment data (EPSS/KEV) for a CVE.
    async fn store_enrichment(&self, cve_id: &str, data: &EnrichmentData) -> Result<()>;

    /// Get enrichment data for a CVE.
    async fn get_enrichment(&self, cve_id: &str) -> Result<Option<EnrichmentData>>;

    /// Get enrichment data for multiple CVEs.
    async fn get_enrichment_batch(
        &self,
        cve_ids: &[String],
    ) -> Result<Vec<(String, EnrichmentData)>>;

    /// Update the last sync timestamp for a source.
    async fn update_sync_timestamp(&self, source: &str) -> Result<()>;

    /// Reset (delete) the sync timestamp for a source, forcing a full re-sync.
    async fn reset_sync_timestamp(&self, source: &str) -> Result<()>;

    /// Get the count of stored advisories.
    async fn advisory_count(&self) -> Result<u64>;

    /// Store an OSS Index component report in cache.
    ///
    /// # Arguments
    ///
    /// * `purl` - The Package URL that was queried
    /// * `cache` - The cached component report with metadata
    async fn store_ossindex_cache(&self, purl: &str, cache: &OssIndexCache) -> Result<()>;

    /// Get a cached OSS Index component report.
    ///
    /// Returns `None` if not cached or if the cache has expired.
    async fn get_ossindex_cache(&self, purl: &str) -> Result<Option<OssIndexCache>>;

    /// Invalidate (delete) a cached OSS Index component report.
    async fn invalidate_ossindex_cache(&self, purl: &str) -> Result<()>;

    /// Invalidate all OSS Index cache entries.
    async fn invalidate_all_ossindex_cache(&self) -> Result<u64>;
}

/// Health status of the store.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    /// Whether the connection is working.
    pub connected: bool,
    /// Round-trip latency in milliseconds.
    pub latency_ms: u64,
    /// Number of advisory keys (approximate).
    pub advisory_count: u64,
    /// Redis server info (version, etc.).
    pub server_info: Option<String>,
}

/// Enrichment data stored separately for CVEs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnrichmentData {
    /// EPSS score (0.0 - 1.0).
    pub epss_score: Option<f64>,
    /// EPSS percentile (0.0 - 1.0).
    pub epss_percentile: Option<f64>,
    /// Whether in CISA KEV catalog.
    pub is_kev: bool,
    /// KEV due date (RFC3339).
    pub kev_due_date: Option<String>,
    /// KEV date added (RFC3339).
    pub kev_date_added: Option<String>,
    /// Whether used in ransomware campaigns.
    pub kev_ransomware: Option<bool>,
    /// Last updated timestamp.
    pub updated_at: String,
}

/// Cached OSS Index component report.
///
/// Stores advisories from OSS Index along with
/// cache metadata for TTL management.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OssIndexCache {
    /// The converted advisories from OSS Index.
    pub advisories: Vec<crate::models::Advisory>,
    /// When this was cached.
    pub cached_at: chrono::DateTime<chrono::Utc>,
    /// TTL in seconds from cache time.
    pub ttl_seconds: u64,
}

/// Default cache TTL: 1 hour.
const DEFAULT_OSSINDEX_CACHE_TTL: u64 = 3600;

impl OssIndexCache {
    /// Create a new cache entry with default TTL.
    pub fn new(advisories: Vec<crate::models::Advisory>) -> Self {
        Self {
            advisories,
            cached_at: chrono::Utc::now(),
            ttl_seconds: DEFAULT_OSSINDEX_CACHE_TTL,
        }
    }

    /// Create a new cache entry with custom TTL.
    pub fn with_ttl(advisories: Vec<crate::models::Advisory>, ttl_seconds: u64) -> Self {
        Self {
            advisories,
            cached_at: chrono::Utc::now(),
            ttl_seconds,
        }
    }

    /// Check if this cache entry is still valid (not expired).
    pub fn is_valid(&self) -> bool {
        !self.is_expired()
    }

    /// Check if this cache entry has expired.
    pub fn is_expired(&self) -> bool {
        let age = chrono::Utc::now().signed_duration_since(self.cached_at);
        age.num_seconds() >= self.ttl_seconds as i64
    }

    /// Get the remaining TTL in seconds.
    pub fn remaining_ttl(&self) -> i64 {
        let age = chrono::Utc::now().signed_duration_since(self.cached_at);
        (self.ttl_seconds as i64) - age.num_seconds()
    }
}

/// Redis/DragonflyDB storage implementation.
pub struct DragonflyStore {
    client: redis::Client,
    config: StoreConfig,
}

impl DragonflyStore {
    /// Create a new store with default configuration.
    pub fn new(url: &str) -> Result<Self> {
        Self::with_config(url, StoreConfig::default())
    }

    /// Create a new store with custom configuration.
    pub fn with_config(url: &str, config: StoreConfig) -> Result<Self> {
        let client = redis::Client::open(url)?;
        Ok(Self { client, config })
    }

    /// Get the key prefix for this store.
    pub fn key_prefix(&self) -> &str {
        &self.config.key_prefix
    }

    /// Build a key with the configured prefix.
    fn key(&self, suffix: &str) -> String {
        format!("{}:{}", self.config.key_prefix, suffix)
    }

    fn compress(&self, data: &[u8]) -> Result<Vec<u8>> {
        let mut encoder =
            zstd::stream::write::Encoder::new(Vec::new(), self.config.compression_level)?;
        encoder.write_all(data)?;
        encoder
            .finish()
            .map_err(|e| AdvisoryError::compression(e.to_string()))
    }

    fn decompress(data: &[u8]) -> Result<Vec<u8>> {
        let mut decoder = zstd::stream::read::Decoder::new(data)?;
        let mut decoded = Vec::new();
        std::io::Read::read_to_end(&mut decoder, &mut decoded)?;
        Ok(decoded)
    }

    async fn get_connection(&self) -> Result<redis::aio::MultiplexedConnection> {
        self.client
            .get_multiplexed_async_connection()
            .await
            .map_err(AdvisoryError::from)
    }
}

#[async_trait]
impl AdvisoryStore for DragonflyStore {
    #[instrument(skip(self, advisories), fields(count = advisories.len()))]
    async fn upsert_batch(&self, advisories: &[Advisory], source: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let mut pipe = redis::pipe();

        for advisory in advisories {
            let json = serde_json::to_vec(advisory)?;
            let compressed = self.compress(&json)?;

            let data_key = self.key(&format!("data:{}", advisory.id));

            // Store data with optional TTL
            if let Some(ttl) = self.config.ttl_seconds {
                pipe.cmd("SETEX").arg(&data_key).arg(ttl).arg(compressed);
            } else {
                pipe.set(&data_key, compressed);
            }

            // Update index
            for affected in &advisory.affected {
                let (ecosystem, package) =
                    normalize_package_key(&affected.package.ecosystem, &affected.package.name);
                let idx_key = self.key(&format!("idx:{}:{}", ecosystem, package));
                pipe.sadd(&idx_key, &advisory.id);
            }
        }

        // NOTE: Do NOT update meta timestamp here.
        // The caller (sync_all) will update it explicitly after verifying success.

        pipe.query_async::<()>(&mut conn).await?;
        info!("Upserted {} advisories from {}", advisories.len(), source);
        Ok(())
    }

    async fn get(&self, id: &str) -> Result<Option<Advisory>> {
        let mut conn = self.get_connection().await?;
        let data: Option<Vec<u8>> = conn.get(self.key(&format!("data:{}", id))).await?;

        match data {
            Some(bytes) => {
                let decompressed = Self::decompress(&bytes)?;
                let advisory = serde_json::from_slice(&decompressed)?;
                Ok(Some(advisory))
            }
            None => Ok(None),
        }
    }

    async fn get_by_package(&self, ecosystem: &str, package: &str) -> Result<Vec<Advisory>> {
        let (ecosystem, package) = normalize_package_key(ecosystem, package);
        let mut conn = self.get_connection().await?;
        let ids: Vec<String> = conn
            .smembers(self.key(&format!("idx:{}:{}", ecosystem, package)))
            .await?;

        // Batch fetch to avoid N+1 round trips and repeated decompress calls
        self.get_batch(&ids).await
    }

    async fn last_sync(&self, source: &str) -> Result<Option<String>> {
        let mut conn = self.get_connection().await?;
        Ok(conn.get(self.key(&format!("meta:{}", source))).await?)
    }

    async fn health_check(&self) -> Result<HealthStatus> {
        let start = Instant::now();

        let mut conn = self.get_connection().await?;

        // Ping to check connection
        let pong: String = redis::cmd("PING").query_async(&mut conn).await?;
        let connected = pong == "PONG";

        let latency_ms = start.elapsed().as_millis() as u64;

        // Get approximate key count
        let advisory_count = self.advisory_count().await.unwrap_or(0);

        // Get server info
        let info: std::result::Result<String, _> = redis::cmd("INFO")
            .arg("server")
            .query_async(&mut conn)
            .await;
        let server_info = info.ok().and_then(|s| {
            s.lines()
                .find(|l| l.starts_with("redis_version:"))
                .map(|l| l.to_string())
        });

        Ok(HealthStatus {
            connected,
            latency_ms,
            advisory_count,
            server_info,
        })
    }

    async fn get_by_package_stream(
        &self,
        ecosystem: &str,
        package: &str,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Advisory>> + Send + '_>>> {
        let (ecosystem, package) = normalize_package_key(ecosystem, package);
        let idx_key = self.key(&format!("idx:{}:{}", ecosystem, package));

        let stream = try_stream! {
            let mut conn = self.get_connection().await?;

            // Use SSCAN for memory-efficient iteration
            let mut cursor = 0u64;
            loop {
                let (new_cursor, ids): (u64, Vec<String>) = redis::cmd("SSCAN")
                    .arg(&idx_key)
                    .arg(cursor)
                    .arg("COUNT")
                    .arg(100)
                    .query_async(&mut conn)
                    .await?;

                for id in ids {
                    if let Some(advisory) = self.get(&id).await? {
                        yield advisory;
                    }
                }

                cursor = new_cursor;
                if cursor == 0 {
                    break;
                }
            }
        };

        Ok(Box::pin(stream))
    }

    async fn get_batch(&self, ids: &[String]) -> Result<Vec<Advisory>> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }

        let mut conn = self.get_connection().await?;
        let keys: Vec<String> = ids
            .iter()
            .map(|id| self.key(&format!("data:{}", id)))
            .collect();

        let data: Vec<Option<Vec<u8>>> =
            redis::cmd("MGET").arg(&keys).query_async(&mut conn).await?;

        let mut advisories = Vec::new();
        for bytes in data.into_iter().flatten() {
            let decompressed = Self::decompress(&bytes)?;
            let advisory: Advisory = serde_json::from_slice(&decompressed)?;
            advisories.push(advisory);
        }

        Ok(advisories)
    }

    async fn store_enrichment(&self, cve_id: &str, data: &EnrichmentData) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let key = self.key(&format!("enrich:{}", cve_id));
        let json = serde_json::to_string(data)?;

        if let Some(ttl) = self.config.ttl_seconds {
            redis::cmd("SETEX")
                .arg(&key)
                .arg(ttl)
                .arg(json)
                .query_async::<()>(&mut conn)
                .await?;
        } else {
            let _: () = conn.set(&key, json).await?;
        }

        Ok(())
    }

    async fn get_enrichment(&self, cve_id: &str) -> Result<Option<EnrichmentData>> {
        let mut conn = self.get_connection().await?;
        let key = self.key(&format!("enrich:{}", cve_id));
        let data: Option<String> = conn.get(&key).await?;

        match data {
            Some(json) => Ok(Some(serde_json::from_str(&json)?)),
            None => Ok(None),
        }
    }

    async fn get_enrichment_batch(
        &self,
        cve_ids: &[String],
    ) -> Result<Vec<(String, EnrichmentData)>> {
        if cve_ids.is_empty() {
            return Ok(Vec::new());
        }

        let mut conn = self.get_connection().await?;
        let keys: Vec<String> = cve_ids
            .iter()
            .map(|id| self.key(&format!("enrich:{}", id)))
            .collect();

        let data: Vec<Option<String>> =
            redis::cmd("MGET").arg(&keys).query_async(&mut conn).await?;

        let mut results = Vec::new();
        for (cve_id, json_opt) in cve_ids.iter().zip(data) {
            if let Some(json) = json_opt {
                if let Ok(enrichment) = serde_json::from_str(&json) {
                    results.push((cve_id.clone(), enrichment));
                }
            }
        }

        Ok(results)
    }

    async fn update_sync_timestamp(&self, source: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let _: () = conn
            .set(
                self.key(&format!("meta:{}", source)),
                chrono::Utc::now().to_rfc3339(),
            )
            .await?;
        Ok(())
    }

    async fn reset_sync_timestamp(&self, source: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let _: () = conn.del(self.key(&format!("meta:{}", source))).await?;
        info!("Reset sync timestamp for {}", source);
        Ok(())
    }

    async fn advisory_count(&self) -> Result<u64> {
        let mut conn = self.get_connection().await?;
        let pattern = self.key("data:*");

        // Use SCAN to count keys matching pattern
        let mut count = 0u64;
        let mut cursor = 0u64;

        loop {
            let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(1000)
                .query_async(&mut conn)
                .await?;

            count += keys.len() as u64;
            cursor = new_cursor;

            if cursor == 0 {
                break;
            }
        }

        Ok(count)
    }

    async fn store_ossindex_cache(&self, purl: &str, cache: &OssIndexCache) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let key = self.key(&format!("ossidx:{}", Self::hash_purl(purl)));
        let json = serde_json::to_string(cache)?;

        // Use the remaining TTL or the configured TTL
        let ttl = cache.remaining_ttl().max(1) as u64;
        redis::cmd("SETEX")
            .arg(&key)
            .arg(ttl)
            .arg(json)
            .query_async::<()>(&mut conn)
            .await?;

        Ok(())
    }

    async fn get_ossindex_cache(&self, purl: &str) -> Result<Option<OssIndexCache>> {
        let mut conn = self.get_connection().await?;
        let key = self.key(&format!("ossidx:{}", Self::hash_purl(purl)));
        let data: Option<String> = conn.get(&key).await?;

        match data {
            Some(json) => {
                let cache: OssIndexCache = serde_json::from_str(&json)?;
                // Double-check validity (Redis TTL should handle this, but be safe)
                if cache.is_valid() {
                    Ok(Some(cache))
                } else {
                    // Cache expired, delete it
                    let _: () = conn.del(&key).await?;
                    Ok(None)
                }
            }
            None => Ok(None),
        }
    }

    async fn invalidate_ossindex_cache(&self, purl: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let key = self.key(&format!("ossidx:{}", Self::hash_purl(purl)));
        let _: () = conn.del(&key).await?;
        Ok(())
    }

    async fn invalidate_all_ossindex_cache(&self) -> Result<u64> {
        let mut conn = self.get_connection().await?;
        let pattern = self.key("ossidx:*");

        // Use SCAN to find all OSS Index cache keys
        let mut deleted = 0u64;
        let mut cursor = 0u64;

        loop {
            let (new_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(1000)
                .query_async(&mut conn)
                .await?;

            if !keys.is_empty() {
                let count: u64 = redis::cmd("DEL").arg(&keys).query_async(&mut conn).await?;
                deleted += count;
            }

            cursor = new_cursor;
            if cursor == 0 {
                break;
            }
        }

        Ok(deleted)
    }
}

impl DragonflyStore {
    /// Generate a hash key for a PURL string.
    fn hash_purl(purl: &str) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        purl.hash(&mut hasher);
        format!("{:x}", hasher.finish())
    }
}