forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.5 MiB·7aca449·Tahinli·1 hour ago·336 commits
| 1 | use std::collections::HashMap; |
| 2 | use std::fs::{self, File}; |
| 3 | use std::io::{BufReader, Write}; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::time::{Duration, SystemTime}; |
| 6 | |
| 7 | use forge_core::advisories::{Advisory, KNOWN_ECOSYSTEMS, read_dump}; |
| 8 | use forge_core::{Error, Result}; |
| 9 | use tokio::sync::mpsc; |
| 10 | |
| 11 | use super::scan::scan_all; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | const IMPORT_QUEUE: usize = 2; |
| 15 | const RETRY_FIRST: Duration = Duration::from_secs(5 * 60); |
| 16 | const RETRY_MAX: Duration = Duration::from_secs(60 * 60); |
| 17 | const MAX_DUMP_BYTES: u64 = 500 * 1024 * 1024; |
| 18 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); |
| 19 | const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(30 * 60); |
| 20 | const USER_AGENT: &str = concat!("forge-advisories/", env!("CARGO_PKG_VERSION")); |
| 21 | |
| 22 | pub fn spawn(state: AppState) { |
| 23 | if !state.config.advisories.enabled { |
| 24 | return; |
| 25 | } |
| 26 | tokio::spawn(run(state)); |
| 27 | } |
| 28 | |
| 29 | pub fn dump_url(ecosystem: &str) -> String { |
| 30 | format!("https://osv-vulnerabilities.storage.googleapis.com/{ecosystem}/all.zip") |
| 31 | } |
| 32 | |
| 33 | pub fn dump_path(data_dir: &Path, ecosystem: &str) -> PathBuf { |
| 34 | data_dir.join("advisories").join(ecosystem).join("all.zip") |
| 35 | } |
| 36 | |
| 37 | async fn run(state: AppState) { |
| 38 | let client = match reqwest::Client::builder() |
| 39 | .redirect(reqwest::redirect::Policy::none()) |
| 40 | .connect_timeout(CONNECT_TIMEOUT) |
| 41 | .timeout(DOWNLOAD_TIMEOUT) |
| 42 | .user_agent(USER_AGENT) |
| 43 | .build() |
| 44 | { |
| 45 | Ok(client) => client, |
| 46 | Err(e) => { |
| 47 | tracing::error!(error = %e, "advisories: could not build the HTTP client"); |
| 48 | return; |
| 49 | } |
| 50 | }; |
| 51 | let refresh_after = Duration::from_secs(state.config.advisories.refresh_hours.max(1) * 3600); |
| 52 | let mut imported: HashMap<String, SystemTime> = HashMap::new(); |
| 53 | let mut due: HashMap<String, SystemTime> = HashMap::new(); |
| 54 | let mut failures: HashMap<String, u32> = HashMap::new(); |
| 55 | loop { |
| 56 | let mut wake_at: Option<SystemTime> = None; |
| 57 | for ecosystem in &state.config.advisories.ecosystems { |
| 58 | if !KNOWN_ECOSYSTEMS.contains(&ecosystem.as_str()) { |
| 59 | tracing::warn!(ecosystem = %ecosystem, "advisories: unknown ecosystem, skipped"); |
| 60 | continue; |
| 61 | } |
| 62 | let path = dump_path(&state.config.data_dir, ecosystem); |
| 63 | let mut refresh_at = *due |
| 64 | .entry(ecosystem.clone()) |
| 65 | .or_insert_with(|| next_refresh_at(&path, refresh_after)); |
| 66 | let now = SystemTime::now(); |
| 67 | if refresh_at <= now { |
| 68 | refresh_at = match download(&client, ecosystem, &path).await { |
| 69 | Ok(()) => { |
| 70 | failures.remove(ecosystem); |
| 71 | next_refresh_at(&path, refresh_after) |
| 72 | } |
| 73 | Err(e) => { |
| 74 | tracing::error!(error = %e, ecosystem = %ecosystem, "advisories: refresh failed"); |
| 75 | let count = failures.entry(ecosystem.clone()).or_insert(0); |
| 76 | *count += 1; |
| 77 | now + retry_delay(*count) |
| 78 | } |
| 79 | }; |
| 80 | due.insert(ecosystem.clone(), refresh_at); |
| 81 | } |
| 82 | if let Err(e) = import_if_changed(&state, ecosystem, &path, &mut imported).await { |
| 83 | tracing::error!(error = %e, ecosystem = %ecosystem, "advisories: import failed"); |
| 84 | } |
| 85 | wake_at = Some(wake_at.map_or(refresh_at, |at| at.min(refresh_at))); |
| 86 | } |
| 87 | let Some(wake_at) = wake_at else { |
| 88 | tracing::info!("advisories: no known ecosystems configured, worker stopped"); |
| 89 | return; |
| 90 | }; |
| 91 | let wait = wake_at |
| 92 | .duration_since(SystemTime::now()) |
| 93 | .unwrap_or(Duration::ZERO); |
| 94 | tokio::time::sleep(wait).await; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | fn next_refresh_at(path: &Path, refresh_after: Duration) -> SystemTime { |
| 99 | match modified_time(path) { |
| 100 | None => SystemTime::now(), |
| 101 | Some(last) => last + refresh_after, |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fn retry_delay(failures: u32) -> Duration { |
| 106 | let shift = failures.saturating_sub(1).min(16); |
| 107 | (RETRY_FIRST * 2u32.pow(shift)).min(RETRY_MAX) |
| 108 | } |
| 109 | |
| 110 | async fn import_if_changed( |
| 111 | state: &AppState, |
| 112 | ecosystem: &str, |
| 113 | path: &Path, |
| 114 | imported: &mut HashMap<String, SystemTime>, |
| 115 | ) -> Result<()> { |
| 116 | let Some(modified) = modified_time(path) else { |
| 117 | return Ok(()); |
| 118 | }; |
| 119 | if imported.get(ecosystem) == Some(&modified) { |
| 120 | return Ok(()); |
| 121 | } |
| 122 | import(state, ecosystem, path).await?; |
| 123 | imported.insert(ecosystem.to_owned(), modified); |
| 124 | scan_all(state).await; |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | fn modified_time(path: &Path) -> Option<SystemTime> { |
| 129 | fs::metadata(path).and_then(|m| m.modified()).ok() |
| 130 | } |
| 131 | |
| 132 | async fn download(client: &reqwest::Client, ecosystem: &str, path: &Path) -> Result<()> { |
| 133 | let url = dump_url(ecosystem); |
| 134 | let dir = path |
| 135 | .parent() |
| 136 | .ok_or_else(|| Error::Config("advisory dump path has no directory".into()))?; |
| 137 | fs::create_dir_all(dir)?; |
| 138 | let part = path.with_extension("zip.part"); |
| 139 | let outcome = fetch_into(client, &url, &part).await; |
| 140 | match outcome { |
| 141 | Ok(bytes) => { |
| 142 | fs::rename(&part, path)?; |
| 143 | tracing::info!(ecosystem, bytes, "advisories: dump downloaded"); |
| 144 | Ok(()) |
| 145 | } |
| 146 | Err(e) => { |
| 147 | let _ = fs::remove_file(&part); |
| 148 | Err(e) |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | async fn fetch_into(client: &reqwest::Client, url: &str, part: &Path) -> Result<u64> { |
| 154 | let mut response = client |
| 155 | .get(url) |
| 156 | .send() |
| 157 | .await |
| 158 | .and_then(reqwest::Response::error_for_status) |
| 159 | .map_err(|e| Error::Invalid(format!("advisory download failed: {e}")))?; |
| 160 | if response |
| 161 | .content_length() |
| 162 | .is_some_and(|len| len > MAX_DUMP_BYTES) |
| 163 | { |
| 164 | return Err(Error::Invalid( |
| 165 | "advisory dump is larger than 500 MiB".into(), |
| 166 | )); |
| 167 | } |
| 168 | let mut file = File::create(part)?; |
| 169 | let mut total: u64 = 0; |
| 170 | while let Some(chunk) = response |
| 171 | .chunk() |
| 172 | .await |
| 173 | .map_err(|e| Error::Invalid(format!("advisory download interrupted: {e}")))? |
| 174 | { |
| 175 | total += chunk.len() as u64; |
| 176 | if total > MAX_DUMP_BYTES { |
| 177 | return Err(Error::Invalid( |
| 178 | "advisory dump is larger than 500 MiB".into(), |
| 179 | )); |
| 180 | } |
| 181 | file.write_all(&chunk)?; |
| 182 | } |
| 183 | file.sync_all()?; |
| 184 | Ok(total) |
| 185 | } |
| 186 | |
| 187 | async fn import(state: &AppState, ecosystem: &str, path: &Path) -> Result<()> { |
| 188 | let (tx, rx) = mpsc::channel::<Result<Option<Vec<Advisory>>>>(IMPORT_QUEUE); |
| 189 | let owned_path = path.to_owned(); |
| 190 | let eco = ecosystem.to_owned(); |
| 191 | let parser = tokio::task::spawn_blocking(move || -> usize { |
| 192 | let parsed = File::open(&owned_path) |
| 193 | .map_err(Error::from) |
| 194 | .and_then(|file| { |
| 195 | read_dump(BufReader::new(file), &eco, |batch| { |
| 196 | tx.blocking_send(Ok(Some(batch))) |
| 197 | .map_err(|_| Error::Invalid("advisory import was stopped".into())) |
| 198 | }) |
| 199 | }); |
| 200 | match parsed { |
| 201 | Ok(skipped) => { |
| 202 | let _ = tx.blocking_send(Ok(None)); |
| 203 | skipped |
| 204 | } |
| 205 | Err(e) => { |
| 206 | let _ = tx.blocking_send(Err(e)); |
| 207 | 0 |
| 208 | } |
| 209 | } |
| 210 | }); |
| 211 | let stored = state.store.replace_advisories(ecosystem, rx).await; |
| 212 | let skipped = parser |
| 213 | .await |
| 214 | .map_err(|e| Error::Invalid(format!("advisory import task failed: {e}")))?; |
| 215 | let imported = stored?; |
| 216 | tracing::info!(ecosystem, imported, skipped, "advisories: dump imported"); |
| 217 | Ok(()) |
| 218 | } |