🔥 remove: security advisories (OSV downloads, lockfile scans, repo Security tab, advisory notifications)
Browse files at this commit1537db23a94466ad13688e7dab4d616ebcf145daParent: d75b65d47 changed files +10 -2766
- Cargo.lock +0 -2
- Cargo.toml +1 -1
- config/forge.example.toml +0 -9
- crates/forge-core/Cargo.toml +0 -1
- crates/forge-core/src/advisories.rs +0 -552
- crates/forge-core/src/audit.rs +0 -2
- crates/forge-core/src/config.rs +0 -36
- crates/forge-core/src/lib.rs +0 -1
- crates/forge-core/src/server_settings.rs +0 -42
- crates/forge-core/src/store/advisories.rs +0 -766
- crates/forge-core/src/store/mod.rs +0 -4
- crates/forge-core/src/store/notifications.rs +1 -3
- crates/forge-core/src/store/user_delete.rs +0 -5
- crates/forge-e2e/tests/e2e/advisories_e2e.rs +0 -161
- crates/forge-e2e/tests/e2e/main.rs +0 -1
- crates/forge-web-account/src/pages/admin_server.rs +0 -3
- crates/forge-web-app/Cargo.toml +0 -1
- crates/forge-web-app/src/advisories/mod.rs +0 -2
- crates/forge-web-app/src/advisories/scan.rs +0 -135
- crates/forge-web-app/src/advisories/worker.rs +0 -218
- crates/forge-web-app/src/layers.rs +1 -1
- crates/forge-web-app/src/lib.rs +0 -1
- crates/forge-web-app/src/notify.rs +0 -126
- crates/forge-web-app/src/post_update.rs +0 -3
- crates/forge-web-app/src/prune.rs +1 -1
- crates/forge-web-app/src/test_support/mod.rs +0 -1
- crates/forge-web-app/src/views/mod.rs +1 -9
- crates/forge-web-app/src/web_push/mod.rs +0 -18
- crates/forge-web-base/src/i18n/audit_names.rs +0 -8
- crates/forge-web-base/src/i18n/misc.rs +0 -31
- crates/forge-web-base/src/i18n/push.rs +0 -7
- crates/forge-web-base/src/i18n/server_settings.rs +0 -9
- crates/forge-web-pages/src/pages/mod.rs +0 -1
- crates/forge-web-pages/src/pages/notifications.rs +1 -99
- crates/forge-web-pages/src/pages/repo.rs +1 -2
- crates/forge-web-pages/src/pages/repo_ctx.rs +0 -3
- crates/forge-web-pages/src/pages/repo_security.rs +0 -248
- crates/forge-web-pages/src/pages/repo_settings_live.rs +0 -13
- crates/forge-web-repo/src/pages/mod.rs +0 -2
- crates/forge-web-repo/src/pages/repo_settings_live_tests.rs +0 -7
- crates/forge-web-repo/src/pages/security_tab_tests.rs +0 -140
- crates/forge-web/src/boot.rs +0 -1
- crates/forge-web/src/page_route_tests/notifications.rs +0 -80
- crates/forge-web/src/routes.snap +0 -6
- docs/architecture.md +1 -1
- docs/backlog.md +0 -1
- docs/notifications.md +2 -2
Cargo.lockmodified+0 -2
| @@ -2012,7 +2012,6 @@ dependencies = [ | |||
| 2012 | "turso", | 2012 | "turso", |
| 2013 | "ulid", | 2013 | "ulid", |
| 2014 | "unicode-normalization", | 2014 | "unicode-normalization", |
| 2015 | - "zip", | ||
| 2016 | ] | 2015 | ] |
| 2017 | 2016 | ||
| 2018 | [[package]] | 2017 | [[package]] |
| @@ -2213,7 +2212,6 @@ dependencies = [ | |||
| 2213 | "topcoat", | 2212 | "topcoat", |
| 2214 | "tracing", | 2213 | "tracing", |
| 2215 | "ulid", | 2214 | "ulid", |
| 2216 | - "zip", | ||
| 2217 | ] | 2215 | ] |
| 2218 | 2216 | ||
| 2219 | [[package]] | 2217 | [[package]] |
Cargo.tomlmodified+1 -1
| @@ -127,7 +127,7 @@ reqwest = { version = "0.13.5", default-features = false, features = ["rustls", | |||
| 127 | scraper = "0.29.0" | 127 | scraper = "0.29.0" |
| 128 | similar = "3.2.1" | 128 | similar = "3.2.1" |
| 129 | 129 | ||
| 130 | -# security advisories (forge-core): semver matching and OSV zip dumps | 130 | +# semver (forge-core) and zip (CI archives) |
| 131 | semver = "1.0.28" | 131 | semver = "1.0.28" |
| 132 | zip = { version = "9.8.2", default-features = false, features = ["deflate"] } | 132 | zip = { version = "9.8.2", default-features = false, features = ["deflate"] } |
| 133 | 133 | ||
config/forge.example.tomlmodified+0 -9
| @@ -138,15 +138,6 @@ trusted_proxies = [] | |||
| 138 | # Hours a runner registration token stays valid. | 138 | # Hours a runner registration token stays valid. |
| 139 | # registration_token_hours = 24 | 139 | # registration_token_hours = 24 |
| 140 | 140 | ||
| 141 | -# Security advisories (opt-in). When enabled, the forge downloads the OSV dumps for ecosystems and scans each repo's lockfiles. | ||
| 142 | -# [advisories] | ||
| 143 | -# Whether the advisory download and the lockfile scans run at all. | ||
| 144 | -# enabled = false | ||
| 145 | -# OSV ecosystems to download and scan: any of "crates.io", "npm", "Go". | ||
| 146 | -# ecosystems = ["crates.io", "npm", "Go"] | ||
| 147 | -# Hours before a downloaded dump is fetched again. | ||
| 148 | -# refresh_hours = 24 | ||
| 149 | - | ||
| 150 | # Outgoing mail transport. The SMTP server, sender and password are set on /admin/mail and stored in the database. | 141 | # Outgoing mail transport. The SMTP server, sender and password are set on /admin/mail and stored in the database. |
| 151 | # [mail] | 142 | # [mail] |
| 152 | # smtp sends through the configured server. log writes each message to <data_dir>/mail-log/ instead, for development and tests. | 143 | # smtp sends through the configured server. log writes each message to <data_dir>/mail-log/ instead, for development and tests. |
crates/forge-core/Cargo.tomlmodified+0 -1
| @@ -31,7 +31,6 @@ tokio = { workspace = true, features = ["sync"] } | |||
| 31 | tracing.workspace = true | 31 | tracing.workspace = true |
| 32 | serde_json.workspace = true | 32 | serde_json.workspace = true |
| 33 | semver = { workspace = true } | 33 | semver = { workspace = true } |
| 34 | -zip = { workspace = true } | ||
| 35 | flate2.workspace = true | 34 | flate2.workspace = true |
| 36 | tar.workspace = true | 35 | tar.workspace = true |
| 37 | 36 | ||
crates/forge-core/src/advisories.rsdeleted+0 -552
| @@ -1,552 +0,0 @@ | |||
| 1 | -use std::collections::{BTreeMap, BTreeSet}; | ||
| 2 | -use std::io::{Read, Seek}; | ||
| 3 | - | ||
| 4 | -use serde::{Deserialize, Serialize}; | ||
| 5 | -use serde_json::Value; | ||
| 6 | - | ||
| 7 | -use crate::error::{Error, Result}; | ||
| 8 | - | ||
| 9 | -pub const KNOWN_ECOSYSTEMS: [&str; 3] = ["crates.io", "npm", "Go"]; | ||
| 10 | - | ||
| 11 | -const MAX_RECORD_BYTES: u64 = 4 * 1024 * 1024; | ||
| 12 | - | ||
| 13 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 14 | -#[serde(rename_all = "snake_case")] | ||
| 15 | -pub enum Event { | ||
| 16 | - Introduced(String), | ||
| 17 | - Fixed(String), | ||
| 18 | - LastAffected(String), | ||
| 19 | - Limit(String), | ||
| 20 | -} | ||
| 21 | - | ||
| 22 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 23 | -pub struct Range { | ||
| 24 | - pub events: Vec<Event>, | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 28 | -pub struct Advisory { | ||
| 29 | - pub id: String, | ||
| 30 | - pub ecosystem: String, | ||
| 31 | - pub package: String, | ||
| 32 | - pub summary: String, | ||
| 33 | - pub severity: String, | ||
| 34 | - pub modified: String, | ||
| 35 | - #[serde(default)] | ||
| 36 | - pub aliases: Vec<String>, | ||
| 37 | - pub ranges: Vec<Range>, | ||
| 38 | - pub versions: Vec<String>, | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] | ||
| 42 | -pub struct Dependency { | ||
| 43 | - pub ecosystem: String, | ||
| 44 | - pub package: String, | ||
| 45 | - pub version: String, | ||
| 46 | - pub manifest_path: String, | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -#[derive(Deserialize)] | ||
| 50 | -struct Record { | ||
| 51 | - id: String, | ||
| 52 | - #[serde(default)] | ||
| 53 | - summary: String, | ||
| 54 | - #[serde(default)] | ||
| 55 | - aliases: Vec<String>, | ||
| 56 | - #[serde(default)] | ||
| 57 | - modified: String, | ||
| 58 | - #[serde(default)] | ||
| 59 | - severity: Vec<SeverityEntry>, | ||
| 60 | - #[serde(default)] | ||
| 61 | - database_specific: Value, | ||
| 62 | - #[serde(default)] | ||
| 63 | - affected: Vec<Affected>, | ||
| 64 | -} | ||
| 65 | - | ||
| 66 | -#[derive(Deserialize)] | ||
| 67 | -struct SeverityEntry { | ||
| 68 | - #[serde(default)] | ||
| 69 | - score: String, | ||
| 70 | -} | ||
| 71 | - | ||
| 72 | -#[derive(Deserialize)] | ||
| 73 | -struct Affected { | ||
| 74 | - #[serde(default)] | ||
| 75 | - package: Option<PackageRef>, | ||
| 76 | - #[serde(default)] | ||
| 77 | - ranges: Vec<RawRange>, | ||
| 78 | - #[serde(default)] | ||
| 79 | - versions: Vec<String>, | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | -#[derive(Deserialize)] | ||
| 83 | -struct PackageRef { | ||
| 84 | - #[serde(default)] | ||
| 85 | - ecosystem: String, | ||
| 86 | - #[serde(default)] | ||
| 87 | - name: String, | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -#[derive(Deserialize)] | ||
| 91 | -struct RawRange { | ||
| 92 | - #[serde(rename = "type", default)] | ||
| 93 | - kind: String, | ||
| 94 | - #[serde(default)] | ||
| 95 | - events: Vec<RawEvent>, | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -#[derive(Deserialize)] | ||
| 99 | -struct RawEvent { | ||
| 100 | - introduced: Option<String>, | ||
| 101 | - fixed: Option<String>, | ||
| 102 | - last_affected: Option<String>, | ||
| 103 | - limit: Option<String>, | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -pub fn parse_record(json: &[u8], ecosystem: &str) -> Result<Vec<Advisory>> { | ||
| 107 | - let record: Record = serde_json::from_slice(json) | ||
| 108 | - .map_err(|e| Error::Invalid(format!("advisory record is not valid OSV: {e}")))?; | ||
| 109 | - if record.id.is_empty() { | ||
| 110 | - return Err(Error::Invalid("advisory record has no id".into())); | ||
| 111 | - } | ||
| 112 | - let severity = record | ||
| 113 | - .database_specific | ||
| 114 | - .get("severity") | ||
| 115 | - .and_then(Value::as_str) | ||
| 116 | - .map(str::to_owned) | ||
| 117 | - .or_else(|| record.severity.first().map(|s| s.score.clone())) | ||
| 118 | - .unwrap_or_default(); | ||
| 119 | - let mut merged: BTreeMap<String, Advisory> = BTreeMap::new(); | ||
| 120 | - for affected in record.affected { | ||
| 121 | - let Some(package) = affected.package else { | ||
| 122 | - continue; | ||
| 123 | - }; | ||
| 124 | - if package.ecosystem != ecosystem || package.name.is_empty() { | ||
| 125 | - continue; | ||
| 126 | - } | ||
| 127 | - let entry = merged | ||
| 128 | - .entry(package.name.clone()) | ||
| 129 | - .or_insert_with(|| Advisory { | ||
| 130 | - id: record.id.clone(), | ||
| 131 | - ecosystem: ecosystem.to_owned(), | ||
| 132 | - package: package.name.clone(), | ||
| 133 | - summary: record.summary.clone(), | ||
| 134 | - severity: severity.clone(), | ||
| 135 | - modified: record.modified.clone(), | ||
| 136 | - aliases: record.aliases.clone(), | ||
| 137 | - ranges: Vec::new(), | ||
| 138 | - versions: Vec::new(), | ||
| 139 | - }); | ||
| 140 | - for raw in affected.ranges { | ||
| 141 | - if !raw.kind.eq_ignore_ascii_case("SEMVER") | ||
| 142 | - && !raw.kind.eq_ignore_ascii_case("ECOSYSTEM") | ||
| 143 | - { | ||
| 144 | - continue; | ||
| 145 | - } | ||
| 146 | - let events = raw | ||
| 147 | - .events | ||
| 148 | - .into_iter() | ||
| 149 | - .filter_map(|e| { | ||
| 150 | - if let Some(v) = e.introduced { | ||
| 151 | - Some(Event::Introduced(v)) | ||
| 152 | - } else if let Some(v) = e.fixed { | ||
| 153 | - Some(Event::Fixed(v)) | ||
| 154 | - } else if let Some(v) = e.last_affected { | ||
| 155 | - Some(Event::LastAffected(v)) | ||
| 156 | - } else { | ||
| 157 | - e.limit.map(Event::Limit) | ||
| 158 | - } | ||
| 159 | - }) | ||
| 160 | - .collect(); | ||
| 161 | - entry.ranges.push(Range { events }); | ||
| 162 | - } | ||
| 163 | - entry.versions.extend(affected.versions); | ||
| 164 | - } | ||
| 165 | - Ok(merged.into_values().collect()) | ||
| 166 | -} | ||
| 167 | - | ||
| 168 | -const IMPORT_BATCH: usize = 500; | ||
| 169 | - | ||
| 170 | -pub fn read_dump<R, F>(reader: R, ecosystem: &str, mut sink: F) -> Result<usize> | ||
| 171 | -where | ||
| 172 | - R: Read + Seek, | ||
| 173 | - F: FnMut(Vec<Advisory>) -> Result<()>, | ||
| 174 | -{ | ||
| 175 | - let mut zip = zip::ZipArchive::new(reader) | ||
| 176 | - .map_err(|e| Error::Invalid(format!("advisory dump is not a zip file: {e}")))?; | ||
| 177 | - let mut pending = Vec::new(); | ||
| 178 | - let mut skipped = 0; | ||
| 179 | - for index in 0..zip.len() { | ||
| 180 | - let mut file = zip | ||
| 181 | - .by_index(index) | ||
| 182 | - .map_err(|e| Error::Invalid(format!("advisory dump entry unreadable: {e}")))?; | ||
| 183 | - if file.is_dir() || !file.name().is_ok_and(|name| name.ends_with(".json")) { | ||
| 184 | - continue; | ||
| 185 | - } | ||
| 186 | - let mut buf = Vec::new(); | ||
| 187 | - file.by_ref() | ||
| 188 | - .take(MAX_RECORD_BYTES + 1) | ||
| 189 | - .read_to_end(&mut buf)?; | ||
| 190 | - if buf.len() as u64 > MAX_RECORD_BYTES { | ||
| 191 | - skipped += 1; | ||
| 192 | - continue; | ||
| 193 | - } | ||
| 194 | - match parse_record(&buf, ecosystem) { | ||
| 195 | - Ok(found) => pending.extend(found), | ||
| 196 | - Err(_) => skipped += 1, | ||
| 197 | - } | ||
| 198 | - if pending.len() >= IMPORT_BATCH { | ||
| 199 | - sink(std::mem::take(&mut pending))?; | ||
| 200 | - } | ||
| 201 | - } | ||
| 202 | - if !pending.is_empty() { | ||
| 203 | - sink(pending)?; | ||
| 204 | - } | ||
| 205 | - Ok(skipped) | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -pub fn parse_version(raw: &str) -> Option<semver::Version> { | ||
| 209 | - semver::Version::parse(raw.trim().trim_start_matches('v')).ok() | ||
| 210 | -} | ||
| 211 | - | ||
| 212 | -pub fn affects(advisory: &Advisory, version: &str) -> bool { | ||
| 213 | - let wanted = version.trim().trim_start_matches('v'); | ||
| 214 | - if advisory | ||
| 215 | - .versions | ||
| 216 | - .iter() | ||
| 217 | - .any(|v| v.trim().trim_start_matches('v') == wanted) | ||
| 218 | - { | ||
| 219 | - return true; | ||
| 220 | - } | ||
| 221 | - let Some(parsed) = parse_version(version) else { | ||
| 222 | - return false; | ||
| 223 | - }; | ||
| 224 | - advisory | ||
| 225 | - .ranges | ||
| 226 | - .iter() | ||
| 227 | - .any(|range| range_affects(range, &parsed)) | ||
| 228 | -} | ||
| 229 | - | ||
| 230 | -fn range_affects(range: &Range, version: &semver::Version) -> bool { | ||
| 231 | - let mut open: Option<Option<semver::Version>> = None; | ||
| 232 | - for event in &range.events { | ||
| 233 | - match event { | ||
| 234 | - Event::Introduced(raw) => { | ||
| 235 | - open = Some(if raw == "0" { None } else { parse_version(raw) }); | ||
| 236 | - } | ||
| 237 | - Event::Fixed(raw) => { | ||
| 238 | - if let Some(start) = open.take() | ||
| 239 | - && starts_before(&start, version) | ||
| 240 | - && parse_version(raw).is_some_and(|fixed| *version < fixed) | ||
| 241 | - { | ||
| 242 | - return true; | ||
| 243 | - } | ||
| 244 | - } | ||
| 245 | - Event::LastAffected(raw) => { | ||
| 246 | - if let Some(start) = open.take() | ||
| 247 | - && starts_before(&start, version) | ||
| 248 | - && parse_version(raw).is_some_and(|last| *version <= last) | ||
| 249 | - { | ||
| 250 | - return true; | ||
| 251 | - } | ||
| 252 | - } | ||
| 253 | - Event::Limit(_) => {} | ||
| 254 | - } | ||
| 255 | - } | ||
| 256 | - open.is_some_and(|start| starts_before(&start, version)) | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -fn starts_before(start: &Option<semver::Version>, version: &semver::Version) -> bool { | ||
| 260 | - start.as_ref().is_none_or(|s| version >= s) | ||
| 261 | -} | ||
| 262 | - | ||
| 263 | -pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> { | ||
| 264 | - #[derive(Deserialize)] | ||
| 265 | - struct Lock { | ||
| 266 | - #[serde(default)] | ||
| 267 | - package: Vec<Package>, | ||
| 268 | - } | ||
| 269 | - #[derive(Deserialize)] | ||
| 270 | - struct Package { | ||
| 271 | - name: String, | ||
| 272 | - version: String, | ||
| 273 | - #[serde(default)] | ||
| 274 | - source: Option<String>, | ||
| 275 | - } | ||
| 276 | - let lock: Lock = toml::from_str(text) | ||
| 277 | - .map_err(|e| Error::Invalid(format!("Cargo.lock is not valid TOML: {e}")))?; | ||
| 278 | - Ok(lock | ||
| 279 | - .package | ||
| 280 | - .into_iter() | ||
| 281 | - .filter(|p| { | ||
| 282 | - p.source | ||
| 283 | - .as_deref() | ||
| 284 | - .is_some_and(|s| s.starts_with("registry+")) | ||
| 285 | - }) | ||
| 286 | - .map(|p| dependency("crates.io", p.name, p.version, manifest_path)) | ||
| 287 | - .collect()) | ||
| 288 | -} | ||
| 289 | - | ||
| 290 | -pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> { | ||
| 291 | - let doc: Value = serde_json::from_str(text) | ||
| 292 | - .map_err(|e| Error::Invalid(format!("package-lock.json is not valid JSON: {e}")))?; | ||
| 293 | - let Some(packages) = doc.get("packages").and_then(Value::as_object) else { | ||
| 294 | - return Ok(Vec::new()); | ||
| 295 | - }; | ||
| 296 | - let mut out = Vec::new(); | ||
| 297 | - for (key, entry) in packages { | ||
| 298 | - if key.is_empty() || entry.get("link").and_then(Value::as_bool) == Some(true) { | ||
| 299 | - continue; | ||
| 300 | - } | ||
| 301 | - let Some(version) = entry.get("version").and_then(Value::as_str) else { | ||
| 302 | - continue; | ||
| 303 | - }; | ||
| 304 | - let name = match key.rsplit_once("node_modules/") { | ||
| 305 | - Some((_, name)) => name, | ||
| 306 | - None => continue, | ||
| 307 | - }; | ||
| 308 | - out.push(dependency( | ||
| 309 | - "npm", | ||
| 310 | - name.to_owned(), | ||
| 311 | - version.to_owned(), | ||
| 312 | - manifest_path, | ||
| 313 | - )); | ||
| 314 | - } | ||
| 315 | - Ok(out) | ||
| 316 | -} | ||
| 317 | - | ||
| 318 | -pub fn parse_go_sum(text: &str, manifest_path: &str) -> Vec<Dependency> { | ||
| 319 | - let mut seen = BTreeSet::new(); | ||
| 320 | - for line in text.lines() { | ||
| 321 | - let mut fields = line.split_whitespace(); | ||
| 322 | - let (Some(module), Some(version)) = (fields.next(), fields.next()) else { | ||
| 323 | - continue; | ||
| 324 | - }; | ||
| 325 | - if version.ends_with("/go.mod") { | ||
| 326 | - continue; | ||
| 327 | - } | ||
| 328 | - seen.insert((module.to_owned(), version.to_owned())); | ||
| 329 | - } | ||
| 330 | - seen.into_iter() | ||
| 331 | - .map(|(module, version)| dependency("Go", module, version, manifest_path)) | ||
| 332 | - .collect() | ||
| 333 | -} | ||
| 334 | - | ||
| 335 | -fn dependency( | ||
| 336 | - ecosystem: &str, | ||
| 337 | - package: String, | ||
| 338 | - version: String, | ||
| 339 | - manifest_path: &str, | ||
| 340 | -) -> Dependency { | ||
| 341 | - Dependency { | ||
| 342 | - ecosystem: ecosystem.to_owned(), | ||
| 343 | - package, | ||
| 344 | - version, | ||
| 345 | - manifest_path: manifest_path.to_owned(), | ||
| 346 | - } | ||
| 347 | -} | ||
| 348 | - | ||
| 349 | -#[cfg(test)] | ||
| 350 | -mod tests { | ||
| 351 | - use super::*; | ||
| 352 | - | ||
| 353 | - fn adv(ranges: Vec<Range>, versions: Vec<&str>) -> Advisory { | ||
| 354 | - Advisory { | ||
| 355 | - id: "GHSA-test".into(), | ||
| 356 | - ecosystem: "crates.io".into(), | ||
| 357 | - package: "demo".into(), | ||
| 358 | - summary: String::new(), | ||
| 359 | - severity: String::new(), | ||
| 360 | - modified: String::new(), | ||
| 361 | - aliases: Vec::new(), | ||
| 362 | - ranges, | ||
| 363 | - versions: versions.into_iter().map(str::to_owned).collect(), | ||
| 364 | - } | ||
| 365 | - } | ||
| 366 | - | ||
| 367 | - fn range(events: Vec<Event>) -> Range { | ||
| 368 | - Range { events } | ||
| 369 | - } | ||
| 370 | - | ||
| 371 | - #[test] | ||
| 372 | - fn range_events_match_by_table() { | ||
| 373 | - type Case<'a> = (&'a str, Vec<Event>, Vec<(&'a str, bool)>); | ||
| 374 | - let cases: Vec<Case> = vec![ | ||
| 375 | - ( | ||
| 376 | - "introduced 1.0.0 fixed 1.2.0 is half open", | ||
| 377 | - vec![ | ||
| 378 | - Event::Introduced("1.0.0".into()), | ||
| 379 | - Event::Fixed("1.2.0".into()), | ||
| 380 | - ], | ||
| 381 | - vec![ | ||
| 382 | - ("0.9.9", false), | ||
| 383 | - ("1.0.0", true), | ||
| 384 | - ("1.1.5", true), | ||
| 385 | - ("1.2.0", false), | ||
| 386 | - ("2.0.0", false), | ||
| 387 | - ], | ||
| 388 | - ), | ||
| 389 | - ( | ||
| 390 | - "introduced 0 last affected 0.4.7 is inclusive", | ||
| 391 | - vec![ | ||
| 392 | - Event::Introduced("0".into()), | ||
| 393 | - Event::LastAffected("0.4.7".into()), | ||
| 394 | - ], | ||
| 395 | - vec![("0.0.1", true), ("0.4.7", true), ("0.4.8", false)], | ||
| 396 | - ), | ||
| 397 | - ( | ||
| 398 | - "a later introduced event reopens the range forever", | ||
| 399 | - vec![ | ||
| 400 | - Event::Introduced("1.0.0".into()), | ||
| 401 | - Event::Fixed("1.1.0".into()), | ||
| 402 | - Event::Introduced("2.0.0".into()), | ||
| 403 | - ], | ||
| 404 | - vec![("1.0.5", true), ("1.5.0", false), ("9.9.9", true)], | ||
| 405 | - ), | ||
| 406 | - ( | ||
| 407 | - "go v prefix and pseudo versions compare as semver", | ||
| 408 | - vec![Event::Introduced("0".into()), Event::Fixed("1.9.1".into())], | ||
| 409 | - vec![ | ||
| 410 | - ("v1.9.0", true), | ||
| 411 | - ("v1.9.1", false), | ||
| 412 | - ("v0.0.0-20210101000000-abcdef123456", true), | ||
| 413 | - ], | ||
| 414 | - ), | ||
| 415 | - ( | ||
| 416 | - "unparsable version matches nothing by range", | ||
| 417 | - vec![Event::Introduced("0".into())], | ||
| 418 | - vec![("not-a-version", false)], | ||
| 419 | - ), | ||
| 420 | - ]; | ||
| 421 | - for (name, events, checks) in cases { | ||
| 422 | - let a = adv(vec![range(events)], vec![]); | ||
| 423 | - for (version, want) in checks { | ||
| 424 | - assert_eq!(affects(&a, version), want, "case {name}: {version}"); | ||
| 425 | - } | ||
| 426 | - } | ||
| 427 | - } | ||
| 428 | - | ||
| 429 | - #[test] | ||
| 430 | - fn parses_an_osv_record_and_merges_entries_for_one_package() { | ||
| 431 | - let json = br#"{ | ||
| 432 | - "id": "GHSA-xxxx", | ||
| 433 | - "summary": "bad things", | ||
| 434 | - "modified": "2026-01-01T00:00:00Z", | ||
| 435 | - "database_specific": {"severity": "HIGH"}, | ||
| 436 | - "affected": [ | ||
| 437 | - {"package": {"ecosystem": "crates.io", "name": "demo"}, | ||
| 438 | - "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "1.0.1"}]}]}, | ||
| 439 | - {"package": {"ecosystem": "crates.io", "name": "demo"}, | ||
| 440 | - "ranges": [{"type": "GIT", "events": [{"introduced": "0"}]}, | ||
| 441 | - {"type": "ECOSYSTEM", "events": [{"introduced": "3.0.0"}, {"last_affected": "3.0.5"}]}], | ||
| 442 | - "versions": ["0.9.0"]}, | ||
| 443 | - {"package": {"ecosystem": "npm", "name": "other"}, | ||
| 444 | - "ranges": []} | ||
| 445 | - ] | ||
| 446 | - }"#; | ||
| 447 | - let found = parse_record(json, "crates.io").expect("record parses"); | ||
| 448 | - assert_eq!(found.len(), 1); | ||
| 449 | - let a = &found[0]; | ||
| 450 | - assert_eq!(a.id, "GHSA-xxxx"); | ||
| 451 | - assert_eq!(a.severity, "HIGH"); | ||
| 452 | - assert_eq!(a.ranges.len(), 2, "the GIT range is skipped"); | ||
| 453 | - assert!(affects(a, "0.5.0")); | ||
| 454 | - assert!(!affects(a, "1.0.1")); | ||
| 455 | - assert!(affects(a, "3.0.2")); | ||
| 456 | - assert!(affects(a, "0.9.0")); | ||
| 457 | - } | ||
| 458 | - | ||
| 459 | - #[test] | ||
| 460 | - fn reads_a_zip_dump_and_skips_bad_records() { | ||
| 461 | - use std::io::{Cursor, Write}; | ||
| 462 | - let mut buf = Cursor::new(Vec::new()); | ||
| 463 | - { | ||
| 464 | - let mut zip = zip::ZipWriter::new(&mut buf); | ||
| 465 | - let opts = zip::write::SimpleFileOptions::default(); | ||
| 466 | - zip.start_file("GHSA-a.json", opts).expect("start"); | ||
| 467 | - zip.write_all( | ||
| 468 | - br#"{"id":"GHSA-a","affected":[{"package":{"ecosystem":"npm","name":"left"}, | ||
| 469 | - "ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"2.0.0"}]}]}]}"#, | ||
| 470 | - ) | ||
| 471 | - .expect("write"); | ||
| 472 | - zip.start_file("broken.json", opts).expect("start"); | ||
| 473 | - zip.write_all(b"{ nope").expect("write"); | ||
| 474 | - zip.start_file("readme.txt", opts).expect("start"); | ||
| 475 | - zip.write_all(b"ignored").expect("write"); | ||
| 476 | - zip.finish().expect("finish"); | ||
| 477 | - } | ||
| 478 | - buf.set_position(0); | ||
| 479 | - let mut found = Vec::new(); | ||
| 480 | - let skipped = read_dump(buf, "npm", |batch| { | ||
| 481 | - found.extend(batch); | ||
| 482 | - Ok(()) | ||
| 483 | - }) | ||
| 484 | - .expect("dump reads"); | ||
| 485 | - assert_eq!(skipped, 1); | ||
| 486 | - assert_eq!(found.len(), 1); | ||
| 487 | - assert_eq!(found[0].package, "left"); | ||
| 488 | - } | ||
| 489 | - | ||
| 490 | - #[test] | ||
| 491 | - fn parses_cargo_lock_registry_packages_only() { | ||
| 492 | - let text = r#" | ||
| 493 | -version = 4 | ||
| 494 | - | ||
| 495 | -[[package]] | ||
| 496 | -name = "serde" | ||
| 497 | -version = "1.0.0" | ||
| 498 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 499 | -checksum = "abc" | ||
| 500 | - | ||
| 501 | -[[package]] | ||
| 502 | -name = "local" | ||
| 503 | -version = "0.1.0" | ||
| 504 | -"#; | ||
| 505 | - let deps = parse_cargo_lock(text, "Cargo.lock").expect("parses"); | ||
| 506 | - assert_eq!(deps.len(), 1); | ||
| 507 | - assert_eq!(deps[0].ecosystem, "crates.io"); | ||
| 508 | - assert_eq!(deps[0].package, "serde"); | ||
| 509 | - assert_eq!(deps[0].version, "1.0.0"); | ||
| 510 | - assert_eq!(deps[0].manifest_path, "Cargo.lock"); | ||
| 511 | - } | ||
| 512 | - | ||
| 513 | - #[test] | ||
| 514 | - fn parses_package_lock_v3_packages() { | ||
| 515 | - let text = r#"{ | ||
| 516 | - "lockfileVersion": 3, | ||
| 517 | - "packages": { | ||
| 518 | - "": {"name": "app", "version": "1.0.0"}, | ||
| 519 | - "node_modules/left-pad": {"version": "1.3.0"}, | ||
| 520 | - "node_modules/a/node_modules/@scope/inner": {"version": "2.0.1"}, | ||
| 521 | - "node_modules/linked": {"link": true}, | ||
| 522 | - "packages/ws": {"version": "0.0.1"} | ||
| 523 | - } | ||
| 524 | - }"#; | ||
| 525 | - let mut deps = parse_package_lock(text, "web/package-lock.json").expect("parses"); | ||
| 526 | - deps.sort(); | ||
| 527 | - let names: Vec<(&str, &str)> = deps | ||
| 528 | - .iter() | ||
| 529 | - .map(|d| (d.package.as_str(), d.version.as_str())) | ||
| 530 | - .collect(); | ||
| 531 | - assert_eq!( | ||
| 532 | - names, | ||
| 533 | - vec![("@scope/inner", "2.0.1"), ("left-pad", "1.3.0")] | ||
| 534 | - ); | ||
| 535 | - assert!(deps.iter().all(|d| d.ecosystem == "npm")); | ||
| 536 | - } | ||
| 537 | - | ||
| 538 | - #[test] | ||
| 539 | - fn parses_go_sum_and_drops_go_mod_lines() { | ||
| 540 | - let text = "\ | ||
| 541 | -github.com/a/b v1.2.3 h1:abc= | ||
| 542 | -github.com/a/b v1.2.3/go.mod h1:def= | ||
| 543 | -github.com/c/d v0.0.0-20210101000000-abcdef123456 h1:ghi= | ||
| 544 | -github.com/c/d v0.0.0-20210101000000-abcdef123456/go.mod h1:jkl= | ||
| 545 | -"; | ||
| 546 | - let deps = parse_go_sum(text, "go.sum"); | ||
| 547 | - assert_eq!(deps.len(), 2); | ||
| 548 | - assert_eq!(deps[0].ecosystem, "Go"); | ||
| 549 | - assert_eq!(deps[0].package, "github.com/a/b"); | ||
| 550 | - assert_eq!(deps[0].version, "v1.2.3"); | ||
| 551 | - } | ||
| 552 | -} | ||
crates/forge-core/src/audit.rsmodified+0 -2
| @@ -72,8 +72,6 @@ audit_actions! { | |||
| 72 | CiRunnerRestartRequested => "ci_runner_restart_requested", | 72 | CiRunnerRestartRequested => "ci_runner_restart_requested", |
| 73 | CiRunnerConfigChanged => "ci_runner_config_changed", | 73 | CiRunnerConfigChanged => "ci_runner_config_changed", |
| 74 | CiRegistrationTokenCreated => "ci_registration_token_created", | 74 | CiRegistrationTokenCreated => "ci_registration_token_created", |
| 75 | - AdvisoryAlertDismissed => "advisory_alert_dismissed", | ||
| 76 | - AdvisoryAlertReopened => "advisory_alert_reopened", | ||
| 77 | UiPrefsChanged => "ui_prefs_changed", | 75 | UiPrefsChanged => "ui_prefs_changed", |
| 78 | DiscussionsEnabled => "discussions_enabled", | 76 | DiscussionsEnabled => "discussions_enabled", |
| 79 | DiscussionsDisabled => "discussions_disabled", | 77 | DiscussionsDisabled => "discussions_disabled", |
crates/forge-core/src/config.rsmodified+0 -36
| @@ -91,8 +91,6 @@ pub struct Config { | |||
| 91 | #[serde(default)] | 91 | #[serde(default)] |
| 92 | pub ci: CiConfig, | 92 | pub ci: CiConfig, |
| 93 | #[serde(default)] | 93 | #[serde(default)] |
| 94 | - pub advisories: AdvisoriesConfig, | ||
| 95 | - #[serde(default)] | ||
| 96 | pub mail: MailConfig, | 94 | pub mail: MailConfig, |
| 97 | #[serde(default)] | 95 | #[serde(default)] |
| 98 | pub orgs: OrgsConfig, | 96 | pub orgs: OrgsConfig, |
| @@ -339,39 +337,6 @@ impl Default for CiConfig { | |||
| 339 | } | 337 | } |
| 340 | } | 338 | } |
| 341 | 339 | ||
| 342 | -#[derive(Debug, Clone, Deserialize)] | ||
| 343 | -#[serde(deny_unknown_fields, default)] | ||
| 344 | -pub struct AdvisoriesConfig { | ||
| 345 | - pub enabled: bool, | ||
| 346 | - pub ecosystems: Vec<String>, | ||
| 347 | - pub refresh_hours: u64, | ||
| 348 | -} | ||
| 349 | - | ||
| 350 | -impl Default for AdvisoriesConfig { | ||
| 351 | - fn default() -> Self { | ||
| 352 | - AdvisoriesConfig { | ||
| 353 | - enabled: false, | ||
| 354 | - ecosystems: vec!["crates.io".into(), "npm".into(), "Go".into()], | ||
| 355 | - refresh_hours: 24, | ||
| 356 | - } | ||
| 357 | - } | ||
| 358 | -} | ||
| 359 | - | ||
| 360 | -impl AdvisoriesConfig { | ||
| 361 | - fn validate(&self) -> Result<()> { | ||
| 362 | - match self | ||
| 363 | - .ecosystems | ||
| 364 | - .iter() | ||
| 365 | - .find(|name| !crate::advisories::KNOWN_ECOSYSTEMS.contains(&name.as_str())) | ||
| 366 | - { | ||
| 367 | - Some(name) => Err(Error::Config(format!( | ||
| 368 | - "[advisories] unknown ecosystem `{name}`" | ||
| 369 | - ))), | ||
| 370 | - None => Ok(()), | ||
| 371 | - } | ||
| 372 | - } | ||
| 373 | -} | ||
| 374 | - | ||
| 375 | #[derive(Debug, Clone, Deserialize)] | 340 | #[derive(Debug, Clone, Deserialize)] |
| 376 | #[serde(deny_unknown_fields, default)] | 341 | #[serde(deny_unknown_fields, default)] |
| 377 | pub struct LfsConfig { | 342 | pub struct LfsConfig { |
| @@ -713,7 +678,6 @@ impl Config { | |||
| 713 | self.backup.validate()?; | 678 | self.backup.validate()?; |
| 714 | self.replication.validate()?; | 679 | self.replication.validate()?; |
| 715 | self.self_update.validate()?; | 680 | self.self_update.validate()?; |
| 716 | - self.advisories.validate()?; | ||
| 717 | self.storage.validate()?; | 681 | self.storage.validate()?; |
| 718 | Ok(()) | 682 | Ok(()) |
| 719 | } | 683 | } |
crates/forge-core/src/lib.rsmodified+0 -1
| @@ -24,7 +24,6 @@ macro_rules! string_enum { | |||
| 24 | }; | 24 | }; |
| 25 | } | 25 | } |
| 26 | 26 | ||
| 27 | -pub mod advisories; | ||
| 28 | pub mod alerts; | 27 | pub mod alerts; |
| 29 | pub mod audit; | 28 | pub mod audit; |
| 30 | pub mod authz; | 29 | pub mod authz; |
crates/forge-core/src/server_settings.rsmodified+0 -42
| @@ -4,7 +4,6 @@ use std::sync::{Arc, RwLock}; | |||
| 4 | 4 | ||
| 5 | use ipnet::IpNet; | 5 | use ipnet::IpNet; |
| 6 | 6 | ||
| 7 | -use crate::advisories::KNOWN_ECOSYSTEMS; | ||
| 8 | use crate::config::{ | 7 | use crate::config::{ |
| 9 | BannerLevel, Config, MailTransport, OrgCreation, R2Jurisdiction, Registration, StorageBackend, | 8 | BannerLevel, Config, MailTransport, OrgCreation, R2Jurisdiction, Registration, StorageBackend, |
| 10 | }; | 9 | }; |
| @@ -98,13 +97,6 @@ fn proxies_check(raw: &str) -> Option<String> { | |||
| 98 | .map(|item| format!("invalid trusted proxy `{item}`")) | 97 | .map(|item| format!("invalid trusted proxy `{item}`")) |
| 99 | } | 98 | } |
| 100 | 99 | ||
| 101 | -fn ecosystems_check(raw: &str) -> Option<String> { | ||
| 102 | - split_list(raw) | ||
| 103 | - .into_iter() | ||
| 104 | - .find(|item| !KNOWN_ECOSYSTEMS.contains(&item.as_str())) | ||
| 105 | - .map(|item| format!("unknown ecosystem `{item}`")) | ||
| 106 | -} | ||
| 107 | - | ||
| 108 | #[allow(clippy::too_many_arguments)] | 100 | #[allow(clippy::too_many_arguments)] |
| 109 | const fn f( | 101 | const fn f( |
| 110 | key: &'static str, | 102 | key: &'static str, |
| @@ -765,39 +757,6 @@ pub static FIELDS: &[Field] = &[ | |||
| 765 | |c| c.mail.transport.as_str().into(), | 757 | |c| c.mail.transport.as_str().into(), |
| 766 | |c, v| c.mail.transport = v.parse().unwrap_or_default(), | 758 | |c, v| c.mail.transport = v.parse().unwrap_or_default(), |
| 767 | ), | 759 | ), |
| 768 | - f( | ||
| 769 | - "advisories.enabled", | ||
| 770 | - Integrations, | ||
| 771 | - X, | ||
| 772 | - Ty::Bool, | ||
| 773 | - "Security advisories", | ||
| 774 | - "Download OSV dumps and scan lockfiles.", | ||
| 775 | - |c| c.advisories.enabled.to_string(), | ||
| 776 | - |c, v| c.advisories.enabled = b(v), | ||
| 777 | - ), | ||
| 778 | - Field { | ||
| 779 | - check: ecosystems_check, | ||
| 780 | - ..f( | ||
| 781 | - "advisories.ecosystems", | ||
| 782 | - Integrations, | ||
| 783 | - X, | ||
| 784 | - Ty::List, | ||
| 785 | - "Advisory ecosystems", | ||
| 786 | - "Any of crates.io, npm, Go. Comma separated.", | ||
| 787 | - |c| c.advisories.ecosystems.join(", "), | ||
| 788 | - |c, v| c.advisories.ecosystems = split_list(v), | ||
| 789 | - ) | ||
| 790 | - }, | ||
| 791 | - f( | ||
| 792 | - "advisories.refresh_hours", | ||
| 793 | - Integrations, | ||
| 794 | - X, | ||
| 795 | - Ty::Uint(1, 8_760), | ||
| 796 | - "Advisory refresh (hours)", | ||
| 797 | - "", | ||
| 798 | - |c| c.advisories.refresh_hours.to_string(), | ||
| 799 | - |c, v| c.advisories.refresh_hours = n(v), | ||
| 800 | - ), | ||
| 801 | f( | 760 | f( |
| 802 | "self_update.enabled", | 761 | "self_update.enabled", |
| 803 | Integrations, | 762 | Integrations, |
| @@ -1348,7 +1307,6 @@ max_log_mb = 20 | |||
| 1348 | ("ci.max_log_mb", "lots"), | 1307 | ("ci.max_log_mb", "lots"), |
| 1349 | ("trusted_proxies", "not-an-ip"), | 1308 | ("trusted_proxies", "not-an-ip"), |
| 1350 | ("ssh_public_port", "70000"), | 1309 | ("ssh_public_port", "70000"), |
| 1351 | - ("advisories.ecosystems", "pip"), | ||
| 1352 | ("storage.r2.jurisdiction", "mars"), | 1310 | ("storage.r2.jurisdiction", "mars"), |
| 1353 | ("listen", "0.0.0.0:1"), | 1311 | ("listen", "0.0.0.0:1"), |
| 1354 | ] { | 1312 | ] { |
crates/forge-core/src/store/advisories.rsdeleted+0 -766
| @@ -1,766 +0,0 @@ | |||
| 1 | -use std::collections::{BTreeSet, HashMap}; | ||
| 2 | - | ||
| 3 | -use tokio::sync::mpsc; | ||
| 4 | -use turso::{Row, Value}; | ||
| 5 | - | ||
| 6 | -use super::issues::parse_db; | ||
| 7 | -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; | ||
| 8 | -use crate::advisories::{Advisory, Dependency, Range, affects}; | ||
| 9 | -use crate::error::{Error, Result}; | ||
| 10 | -use crate::time::now_stamp; | ||
| 11 | - | ||
| 12 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 13 | -pub enum AlertState { | ||
| 14 | - Open, | ||
| 15 | - Dismissed, | ||
| 16 | - Fixed, | ||
| 17 | -} | ||
| 18 | - | ||
| 19 | -string_enum!(AlertState { | ||
| 20 | - Open = "open", | ||
| 21 | - Dismissed = "dismissed", | ||
| 22 | - Fixed = "fixed", | ||
| 23 | -}); | ||
| 24 | - | ||
| 25 | -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
| 26 | -pub struct AlertKey { | ||
| 27 | - pub advisory_id: String, | ||
| 28 | - pub ecosystem: String, | ||
| 29 | - pub package: String, | ||
| 30 | - pub version: String, | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 34 | -pub struct Alert { | ||
| 35 | - pub key: AlertKey, | ||
| 36 | - pub state: AlertState, | ||
| 37 | - pub summary: String, | ||
| 38 | - pub severity: String, | ||
| 39 | - pub created_at: String, | ||
| 40 | - pub updated_at: String, | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 44 | -pub struct AdvisoryNotice { | ||
| 45 | - pub repo_id: String, | ||
| 46 | - pub repo_owner: String, | ||
| 47 | - pub repo_name: String, | ||
| 48 | - pub new_alerts: u64, | ||
| 49 | - pub unread: bool, | ||
| 50 | - pub updated_at: String, | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] | ||
| 54 | -pub struct ScanOutcome { | ||
| 55 | - pub opened: usize, | ||
| 56 | - pub fixed: usize, | ||
| 57 | -} | ||
| 58 | - | ||
| 59 | -fn json_err(e: serde_json::Error) -> Error { | ||
| 60 | - Error::Database(format!("advisory JSON: {e}")) | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -fn map_advisory(row: &Row) -> Result<Advisory> { | ||
| 64 | - let ranges_json = col_text(row, 5)?; | ||
| 65 | - let versions_json = col_text(row, 6)?; | ||
| 66 | - Ok(Advisory { | ||
| 67 | - id: col_text(row, 0)?, | ||
| 68 | - ecosystem: col_text(row, 1)?, | ||
| 69 | - package: col_text(row, 2)?, | ||
| 70 | - summary: col_text(row, 3)?, | ||
| 71 | - severity: col_text(row, 4)?, | ||
| 72 | - ranges: serde_json::from_str::<Vec<Range>>(&ranges_json).map_err(json_err)?, | ||
| 73 | - versions: serde_json::from_str::<Vec<String>>(&versions_json).map_err(json_err)?, | ||
| 74 | - modified: col_text(row, 7)?, | ||
| 75 | - aliases: Vec::new(), | ||
| 76 | - }) | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -fn key_of(row: &Row, offset: usize) -> Result<AlertKey> { | ||
| 80 | - Ok(AlertKey { | ||
| 81 | - advisory_id: col_text(row, offset)?, | ||
| 82 | - ecosystem: col_text(row, offset + 1)?, | ||
| 83 | - package: col_text(row, offset + 2)?, | ||
| 84 | - version: col_text(row, offset + 3)?, | ||
| 85 | - }) | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -fn map_alert(row: &Row) -> Result<Alert> { | ||
| 89 | - Ok(Alert { | ||
| 90 | - key: key_of(row, 0)?, | ||
| 91 | - state: parse_db(&col_text(row, 4)?)?, | ||
| 92 | - summary: col_text(row, 5)?, | ||
| 93 | - severity: col_text(row, 6)?, | ||
| 94 | - created_at: col_text(row, 7)?, | ||
| 95 | - updated_at: col_text(row, 8)?, | ||
| 96 | - }) | ||
| 97 | -} | ||
| 98 | - | ||
| 99 | -fn key_params(repo_id: &str, key: &AlertKey) -> Vec<Value> { | ||
| 100 | - vec![ | ||
| 101 | - Value::Text(repo_id.to_string()), | ||
| 102 | - Value::Text(key.advisory_id.clone()), | ||
| 103 | - Value::Text(key.ecosystem.clone()), | ||
| 104 | - Value::Text(key.package.clone()), | ||
| 105 | - Value::Text(key.version.clone()), | ||
| 106 | - ] | ||
| 107 | -} | ||
| 108 | - | ||
| 109 | -impl Store { | ||
| 110 | - pub async fn replace_advisories( | ||
| 111 | - &self, | ||
| 112 | - ecosystem: &str, | ||
| 113 | - mut batches: mpsc::Receiver<Result<Option<Vec<Advisory>>>>, | ||
| 114 | - ) -> Result<usize> { | ||
| 115 | - let conn = self.inner.conn.lock().await; | ||
| 116 | - let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 117 | - let outcome: Result<usize> = async { | ||
| 118 | - tx.execute( | ||
| 119 | - "DELETE FROM advisories WHERE ecosystem = ?1", | ||
| 120 | - (ecosystem.to_string(),), | ||
| 121 | - ) | ||
| 122 | - .await | ||
| 123 | - .map_err(db_err)?; | ||
| 124 | - let mut stored = 0; | ||
| 125 | - loop { | ||
| 126 | - let Some(batch) = batches.recv().await else { | ||
| 127 | - return Err(Error::Invalid("advisory import ended without finishing".into())); | ||
| 128 | - }; | ||
| 129 | - let Some(batch) = batch? else { | ||
| 130 | - break; | ||
| 131 | - }; | ||
| 132 | - for advisory in batch { | ||
| 133 | - if advisory.ecosystem != ecosystem { | ||
| 134 | - continue; | ||
| 135 | - } | ||
| 136 | - let params = vec![ | ||
| 137 | - Value::Text(advisory.id.clone()), | ||
| 138 | - Value::Text(advisory.ecosystem.clone()), | ||
| 139 | - Value::Text(advisory.package.clone()), | ||
| 140 | - Value::Text(advisory.summary.clone()), | ||
| 141 | - Value::Text(advisory.severity.clone()), | ||
| 142 | - Value::Text(serde_json::to_string(&advisory.ranges).map_err(json_err)?), | ||
| 143 | - Value::Text(serde_json::to_string(&advisory.versions).map_err(json_err)?), | ||
| 144 | - Value::Text(advisory.modified.clone()), | ||
| 145 | - ]; | ||
| 146 | - tx.execute( | ||
| 147 | - "INSERT OR REPLACE INTO advisories (id, ecosystem, package, summary, severity, \ | ||
| 148 | - ranges_json, versions_json, modified) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | ||
| 149 | - params, | ||
| 150 | - ) | ||
| 151 | - .await | ||
| 152 | - .map_err(db_err)?; | ||
| 153 | - stored += 1; | ||
| 154 | - } | ||
| 155 | - } | ||
| 156 | - Ok(stored) | ||
| 157 | - } | ||
| 158 | - .await; | ||
| 159 | - finish(tx, outcome).await | ||
| 160 | - } | ||
| 161 | - | ||
| 162 | - pub async fn advisories_for_package( | ||
| 163 | - &self, | ||
| 164 | - ecosystem: &str, | ||
| 165 | - package: &str, | ||
| 166 | - ) -> Result<Vec<Advisory>> { | ||
| 167 | - let conn = self.read_conn().await; | ||
| 168 | - fetch_all( | ||
| 169 | - &conn, | ||
| 170 | - "SELECT id, ecosystem, package, summary, severity, ranges_json, versions_json, modified \ | ||
| 171 | - FROM advisories WHERE ecosystem = ?1 AND package = ?2 ORDER BY id", | ||
| 172 | - (ecosystem.to_string(), package.to_string()), | ||
| 173 | - map_advisory, | ||
| 174 | - ) | ||
| 175 | - .await | ||
| 176 | - } | ||
| 177 | - | ||
| 178 | - pub async fn all_repo_ids(&self) -> Result<Vec<String>> { | ||
| 179 | - let conn = self.read_conn().await; | ||
| 180 | - fetch_all(&conn, "SELECT id FROM repos ORDER BY id", (), |row| { | ||
| 181 | - col_text(row, 0) | ||
| 182 | - }) | ||
| 183 | - .await | ||
| 184 | - } | ||
| 185 | - | ||
| 186 | - pub async fn scan_repo(&self, repo_id: &str, deps: &[Dependency]) -> Result<ScanOutcome> { | ||
| 187 | - let unique: BTreeSet<&Dependency> = deps.iter().collect(); | ||
| 188 | - let mut by_package: HashMap<(String, String), Vec<Advisory>> = HashMap::new(); | ||
| 189 | - let mut matched: BTreeSet<AlertKey> = BTreeSet::new(); | ||
| 190 | - for dep in &unique { | ||
| 191 | - let pair = (dep.ecosystem.clone(), dep.package.clone()); | ||
| 192 | - if !by_package.contains_key(&pair) { | ||
| 193 | - let found = self | ||
| 194 | - .advisories_for_package(&dep.ecosystem, &dep.package) | ||
| 195 | - .await?; | ||
| 196 | - by_package.insert(pair.clone(), found); | ||
| 197 | - } | ||
| 198 | - for advisory in by_package.get(&pair).into_iter().flatten() { | ||
| 199 | - if affects(advisory, &dep.version) { | ||
| 200 | - matched.insert(AlertKey { | ||
| 201 | - advisory_id: advisory.id.clone(), | ||
| 202 | - ecosystem: advisory.ecosystem.clone(), | ||
| 203 | - package: advisory.package.clone(), | ||
| 204 | - version: dep.version.clone(), | ||
| 205 | - }); | ||
| 206 | - } | ||
| 207 | - } | ||
| 208 | - } | ||
| 209 | - | ||
| 210 | - let conn = self.inner.conn.lock().await; | ||
| 211 | - let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 212 | - let rid = repo_id.to_string(); | ||
| 213 | - let outcome: Result<ScanOutcome> = async { | ||
| 214 | - tx.execute( | ||
| 215 | - "DELETE FROM repo_dependencies WHERE repo_id = ?1", | ||
| 216 | - (rid.clone(),), | ||
| 217 | - ) | ||
| 218 | - .await | ||
| 219 | - .map_err(db_err)?; | ||
| 220 | - for dep in &unique { | ||
| 221 | - tx.execute( | ||
| 222 | - "INSERT OR IGNORE INTO repo_dependencies (repo_id, ecosystem, package, version, \ | ||
| 223 | - manifest_path) VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 224 | - ( | ||
| 225 | - rid.clone(), | ||
| 226 | - dep.ecosystem.clone(), | ||
| 227 | - dep.package.clone(), | ||
| 228 | - dep.version.clone(), | ||
| 229 | - dep.manifest_path.clone(), | ||
| 230 | - ), | ||
| 231 | - ) | ||
| 232 | - .await | ||
| 233 | - .map_err(db_err)?; | ||
| 234 | - } | ||
| 235 | - | ||
| 236 | - let existing: HashMap<AlertKey, AlertState> = fetch_all( | ||
| 237 | - &tx, | ||
| 238 | - "SELECT advisory_id, ecosystem, package, version, state FROM repo_alerts \ | ||
| 239 | - WHERE repo_id = ?1", | ||
| 240 | - (rid.clone(),), | ||
| 241 | - |row| Ok((key_of(row, 0)?, parse_db(&col_text(row, 4)?)?)), | ||
| 242 | - ) | ||
| 243 | - .await? | ||
| 244 | - .into_iter() | ||
| 245 | - .collect(); | ||
| 246 | - | ||
| 247 | - let now = now_stamp(); | ||
| 248 | - let mut outcome = ScanOutcome::default(); | ||
| 249 | - for key in &matched { | ||
| 250 | - let mut params = key_params(&rid, key); | ||
| 251 | - match existing.get(key) { | ||
| 252 | - None => { | ||
| 253 | - params.extend([ | ||
| 254 | - Value::Text(AlertState::Open.as_str().to_string()), | ||
| 255 | - Value::Text(now.clone()), | ||
| 256 | - Value::Text(now.clone()), | ||
| 257 | - ]); | ||
| 258 | - tx.execute( | ||
| 259 | - "INSERT INTO repo_alerts (repo_id, advisory_id, ecosystem, package, \ | ||
| 260 | - version, state, created_at, updated_at) \ | ||
| 261 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | ||
| 262 | - params, | ||
| 263 | - ) | ||
| 264 | - .await | ||
| 265 | - .map_err(db_err)?; | ||
| 266 | - outcome.opened += 1; | ||
| 267 | - } | ||
| 268 | - Some(AlertState::Fixed) => { | ||
| 269 | - set_state(&tx, &rid, key, AlertState::Fixed, AlertState::Open, &now).await?; | ||
| 270 | - outcome.opened += 1; | ||
| 271 | - } | ||
| 272 | - Some(AlertState::Open | AlertState::Dismissed) => {} | ||
| 273 | - } | ||
| 274 | - } | ||
| 275 | - for (key, state) in &existing { | ||
| 276 | - if *state == AlertState::Open && !matched.contains(key) { | ||
| 277 | - set_state(&tx, &rid, key, AlertState::Open, AlertState::Fixed, &now).await?; | ||
| 278 | - outcome.fixed += 1; | ||
| 279 | - } | ||
| 280 | - } | ||
| 281 | - Ok(outcome) | ||
| 282 | - } | ||
| 283 | - .await; | ||
| 284 | - finish(tx, outcome).await | ||
| 285 | - } | ||
| 286 | - | ||
| 287 | - pub async fn set_alert_state( | ||
| 288 | - &self, | ||
| 289 | - repo_id: &str, | ||
| 290 | - key: &AlertKey, | ||
| 291 | - from: AlertState, | ||
| 292 | - to: AlertState, | ||
| 293 | - ) -> Result<bool> { | ||
| 294 | - let conn = self.inner.conn.lock().await; | ||
| 295 | - let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 296 | - let rid = repo_id.to_string(); | ||
| 297 | - let now = now_stamp(); | ||
| 298 | - let outcome: Result<bool> = async { | ||
| 299 | - let changed = set_state(&tx, &rid, key, from, to, &now).await?; | ||
| 300 | - Ok(changed > 0) | ||
| 301 | - } | ||
| 302 | - .await; | ||
| 303 | - finish(tx, outcome).await | ||
| 304 | - } | ||
| 305 | - | ||
| 306 | - pub async fn list_alerts(&self, repo_id: &str) -> Result<Vec<Alert>> { | ||
| 307 | - let conn = self.read_conn().await; | ||
| 308 | - fetch_all( | ||
| 309 | - &conn, | ||
| 310 | - "SELECT a.advisory_id, a.ecosystem, a.package, a.version, a.state, \ | ||
| 311 | - COALESCE(v.summary, ''), COALESCE(v.severity, ''), a.created_at, a.updated_at \ | ||
| 312 | - FROM repo_alerts a \ | ||
| 313 | - LEFT JOIN advisories v ON v.id = a.advisory_id AND v.ecosystem = a.ecosystem \ | ||
| 314 | - AND v.package = a.package \ | ||
| 315 | - WHERE a.repo_id = ?1 \ | ||
| 316 | - ORDER BY CASE a.state WHEN 'open' THEN 0 WHEN 'dismissed' THEN 1 ELSE 2 END, \ | ||
| 317 | - a.created_at, a.advisory_id, a.package", | ||
| 318 | - (repo_id.to_string(),), | ||
| 319 | - map_alert, | ||
| 320 | - ) | ||
| 321 | - .await | ||
| 322 | - } | ||
| 323 | - | ||
| 324 | - pub async fn dependency_count(&self, repo_id: &str) -> Result<u64> { | ||
| 325 | - let conn = self.read_conn().await; | ||
| 326 | - let mut rows = conn | ||
| 327 | - .query( | ||
| 328 | - "SELECT COUNT(*) FROM repo_dependencies WHERE repo_id = ?1", | ||
| 329 | - (repo_id.to_string(),), | ||
| 330 | - ) | ||
| 331 | - .await | ||
| 332 | - .map_err(db_err)?; | ||
| 333 | - let row = rows | ||
| 334 | - .next() | ||
| 335 | - .await | ||
| 336 | - .map_err(db_err)? | ||
| 337 | - .ok_or_else(super::missing_row)?; | ||
| 338 | - u64::try_from(col_int(&row, 0)?).map_err(|_| Error::Database("negative count".into())) | ||
| 339 | - } | ||
| 340 | -} | ||
| 341 | - | ||
| 342 | -impl Store { | ||
| 343 | - pub async fn notify_new_alerts( | ||
| 344 | - &self, | ||
| 345 | - user_id: &str, | ||
| 346 | - repo_id: &str, | ||
| 347 | - new_alerts: u64, | ||
| 348 | - ) -> Result<()> { | ||
| 349 | - let count = i64::try_from(new_alerts) | ||
| 350 | - .map_err(|_| Error::Database("alert count too large".into()))?; | ||
| 351 | - let conn = self.inner.conn.lock().await; | ||
| 352 | - conn.execute( | ||
| 353 | - "INSERT INTO advisory_notifications (user_id, repo_id, new_alerts, unread, updated_at) \ | ||
| 354 | - VALUES (?1, ?2, ?3, 1, ?4) \ | ||
| 355 | - ON CONFLICT (user_id, repo_id) DO UPDATE SET \ | ||
| 356 | - new_alerts = CASE WHEN advisory_notifications.unread = 1 \ | ||
| 357 | - THEN advisory_notifications.new_alerts + excluded.new_alerts \ | ||
| 358 | - ELSE excluded.new_alerts END, \ | ||
| 359 | - unread = 1, updated_at = excluded.updated_at", | ||
| 360 | - vec![ | ||
| 361 | - Value::Text(user_id.to_string()), | ||
| 362 | - Value::Text(repo_id.to_string()), | ||
| 363 | - Value::Integer(count), | ||
| 364 | - Value::Text(now_stamp()), | ||
| 365 | - ], | ||
| 366 | - ) | ||
| 367 | - .await | ||
| 368 | - .map_err(db_err)?; | ||
| 369 | - Ok(()) | ||
| 370 | - } | ||
| 371 | - | ||
| 372 | - pub async fn list_advisory_notifications( | ||
| 373 | - &self, | ||
| 374 | - user_id: &str, | ||
| 375 | - unread_only: bool, | ||
| 376 | - before: Option<&str>, | ||
| 377 | - limit: u32, | ||
| 378 | - ) -> Result<Vec<AdvisoryNotice>> { | ||
| 379 | - let mut sql = format!("{ADVISORY_NOTICE_SELECT} WHERE n.user_id = ?"); | ||
| 380 | - let mut params = vec![Value::Text(user_id.to_string())]; | ||
| 381 | - if unread_only { | ||
| 382 | - sql.push_str(" AND n.unread = 1"); | ||
| 383 | - } | ||
| 384 | - if let Some(stamp) = before { | ||
| 385 | - sql.push_str(" AND n.updated_at < ?"); | ||
| 386 | - params.push(Value::Text(stamp.to_string())); | ||
| 387 | - } | ||
| 388 | - sql.push_str(" ORDER BY n.updated_at DESC, n.repo_id DESC LIMIT ?"); | ||
| 389 | - params.push(Value::Integer(i64::from(limit.clamp(1, 200)))); | ||
| 390 | - let conn = self.read_conn().await; | ||
| 391 | - fetch_all(&conn, &sql, params, map_advisory_notice).await | ||
| 392 | - } | ||
| 393 | - | ||
| 394 | - pub async fn advisory_notification( | ||
| 395 | - &self, | ||
| 396 | - user_id: &str, | ||
| 397 | - repo_id: &str, | ||
| 398 | - ) -> Result<Option<AdvisoryNotice>> { | ||
| 399 | - let conn = self.read_conn().await; | ||
| 400 | - fetch_opt( | ||
| 401 | - &conn, | ||
| 402 | - &format!("{ADVISORY_NOTICE_SELECT} WHERE n.user_id = ?1 AND n.repo_id = ?2 LIMIT 1"), | ||
| 403 | - (user_id.to_string(), repo_id.to_string()), | ||
| 404 | - map_advisory_notice, | ||
| 405 | - ) | ||
| 406 | - .await | ||
| 407 | - } | ||
| 408 | - | ||
| 409 | - pub async fn mark_advisory_notification_read( | ||
| 410 | - &self, | ||
| 411 | - user_id: &str, | ||
| 412 | - repo_id: &str, | ||
| 413 | - ) -> Result<()> { | ||
| 414 | - let conn = self.inner.conn.lock().await; | ||
| 415 | - conn.execute( | ||
| 416 | - "UPDATE advisory_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2", | ||
| 417 | - (user_id.to_string(), repo_id.to_string()), | ||
| 418 | - ) | ||
| 419 | - .await | ||
| 420 | - .map_err(db_err)?; | ||
| 421 | - Ok(()) | ||
| 422 | - } | ||
| 423 | - | ||
| 424 | - pub async fn mark_all_advisory_notifications_read( | ||
| 425 | - &self, | ||
| 426 | - user_id: &str, | ||
| 427 | - repo_id: Option<&str>, | ||
| 428 | - ) -> Result<()> { | ||
| 429 | - let conn = self.inner.conn.lock().await; | ||
| 430 | - let result = match repo_id { | ||
| 431 | - Some(repo) => { | ||
| 432 | - conn.execute( | ||
| 433 | - "UPDATE advisory_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1", | ||
| 434 | - (user_id.to_string(), repo.to_string()), | ||
| 435 | - ) | ||
| 436 | - .await | ||
| 437 | - } | ||
| 438 | - None => { | ||
| 439 | - conn.execute( | ||
| 440 | - "UPDATE advisory_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1", | ||
| 441 | - (user_id.to_string(),), | ||
| 442 | - ) | ||
| 443 | - .await | ||
| 444 | - } | ||
| 445 | - }; | ||
| 446 | - result.map_err(db_err)?; | ||
| 447 | - Ok(()) | ||
| 448 | - } | ||
| 449 | -} | ||
| 450 | - | ||
| 451 | -const ADVISORY_NOTICE_SELECT: &str = "SELECT n.repo_id, o.username, r.name, n.new_alerts, \ | ||
| 452 | - n.unread, n.updated_at FROM advisory_notifications n \ | ||
| 453 | - JOIN repos r ON r.id = n.repo_id \ | ||
| 454 | - JOIN users o ON o.id = r.owner_id"; | ||
| 455 | - | ||
| 456 | -fn map_advisory_notice(row: &Row) -> Result<AdvisoryNotice> { | ||
| 457 | - Ok(AdvisoryNotice { | ||
| 458 | - repo_id: col_text(row, 0)?, | ||
| 459 | - repo_owner: col_text(row, 1)?, | ||
| 460 | - repo_name: col_text(row, 2)?, | ||
| 461 | - new_alerts: u64::try_from(col_int(row, 3)?) | ||
| 462 | - .map_err(|_| Error::Database("negative count".into()))?, | ||
| 463 | - unread: col_int(row, 4)? != 0, | ||
| 464 | - updated_at: col_text(row, 5)?, | ||
| 465 | - }) | ||
| 466 | -} | ||
| 467 | - | ||
| 468 | -async fn set_state( | ||
| 469 | - tx: &turso::transaction::Transaction<'_>, | ||
| 470 | - repo_id: &str, | ||
| 471 | - key: &AlertKey, | ||
| 472 | - from: AlertState, | ||
| 473 | - to: AlertState, | ||
| 474 | - now: &str, | ||
| 475 | -) -> Result<u64> { | ||
| 476 | - let mut params = key_params(repo_id, key); | ||
| 477 | - params.extend([ | ||
| 478 | - Value::Text(to.as_str().to_string()), | ||
| 479 | - Value::Text(now.to_string()), | ||
| 480 | - Value::Text(from.as_str().to_string()), | ||
| 481 | - ]); | ||
| 482 | - tx.execute( | ||
| 483 | - "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND advisory_id = ?2 \ | ||
| 484 | - AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND state = ?8", | ||
| 485 | - params, | ||
| 486 | - ) | ||
| 487 | - .await | ||
| 488 | - .map_err(db_err) | ||
| 489 | -} | ||
| 490 | - | ||
| 491 | -#[cfg(test)] | ||
| 492 | -mod tests { | ||
| 493 | - use super::*; | ||
| 494 | - use crate::advisories::{Event, Range}; | ||
| 495 | - use crate::store::Store; | ||
| 496 | - | ||
| 497 | - impl Store { | ||
| 498 | - async fn replace_in_one_batch( | ||
| 499 | - &self, | ||
| 500 | - ecosystem: &str, | ||
| 501 | - advisories: &[Advisory], | ||
| 502 | - ) -> Result<usize> { | ||
| 503 | - let (tx, rx) = mpsc::channel(2); | ||
| 504 | - tx.send(Ok(Some(advisories.to_vec()))).await.unwrap(); | ||
| 505 | - tx.send(Ok(None)).await.unwrap(); | ||
| 506 | - self.replace_advisories(ecosystem, rx).await | ||
| 507 | - } | ||
| 508 | - } | ||
| 509 | - | ||
| 510 | - fn advisory(id: &str, package: &str, fixed: &str) -> Advisory { | ||
| 511 | - Advisory { | ||
| 512 | - id: id.into(), | ||
| 513 | - ecosystem: "crates.io".into(), | ||
| 514 | - package: package.into(), | ||
| 515 | - summary: format!("{id} summary"), | ||
| 516 | - severity: "HIGH".into(), | ||
| 517 | - modified: String::new(), | ||
| 518 | - aliases: Vec::new(), | ||
| 519 | - ranges: vec![Range { | ||
| 520 | - events: vec![Event::Introduced("0".into()), Event::Fixed(fixed.into())], | ||
| 521 | - }], | ||
| 522 | - versions: Vec::new(), | ||
| 523 | - } | ||
| 524 | - } | ||
| 525 | - | ||
| 526 | - fn dep(package: &str, version: &str) -> Dependency { | ||
| 527 | - Dependency { | ||
| 528 | - ecosystem: "crates.io".into(), | ||
| 529 | - package: package.into(), | ||
| 530 | - version: version.into(), | ||
| 531 | - manifest_path: "Cargo.lock".into(), | ||
| 532 | - } | ||
| 533 | - } | ||
| 534 | - | ||
| 535 | - async fn store_with_repo(dir: &tempfile::TempDir) -> (Store, String) { | ||
| 536 | - let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); | ||
| 537 | - let tahinli = store | ||
| 538 | - .create_user("Tahinli", None, "hash", false) | ||
| 539 | - .await | ||
| 540 | - .unwrap(); | ||
| 541 | - let repo = store | ||
| 542 | - .create_repo(&tahinli.id, "demo", "", crate::Visibility::Private, "main") | ||
| 543 | - .await | ||
| 544 | - .unwrap(); | ||
| 545 | - (store, repo.id) | ||
| 546 | - } | ||
| 547 | - | ||
| 548 | - #[tokio::test] | ||
| 549 | - async fn scans_reconcile_alerts_and_replace_per_ecosystem() { | ||
| 550 | - let dir = tempfile::tempdir().unwrap(); | ||
| 551 | - let (store, repo) = store_with_repo(&dir).await; | ||
| 552 | - | ||
| 553 | - store | ||
| 554 | - .replace_in_one_batch( | ||
| 555 | - "crates.io", | ||
| 556 | - &[ | ||
| 557 | - advisory("RUSTSEC-1", "old", "2.0.0"), | ||
| 558 | - advisory("RUSTSEC-2", "other", "2.0.0"), | ||
| 559 | - ], | ||
| 560 | - ) | ||
| 561 | - .await | ||
| 562 | - .unwrap(); | ||
| 563 | - | ||
| 564 | - let first = store | ||
| 565 | - .scan_repo(&repo, &[dep("old", "1.0.0"), dep("other", "1.5.0")]) | ||
| 566 | - .await | ||
| 567 | - .unwrap(); | ||
| 568 | - assert_eq!( | ||
| 569 | - first, | ||
| 570 | - ScanOutcome { | ||
| 571 | - opened: 2, | ||
| 572 | - fixed: 0 | ||
| 573 | - }, | ||
| 574 | - "first scan opens both" | ||
| 575 | - ); | ||
| 576 | - assert_eq!( | ||
| 577 | - store.dependency_count(&repo).await.unwrap(), | ||
| 578 | - 2, | ||
| 579 | - "two dependencies" | ||
| 580 | - ); | ||
| 581 | - | ||
| 582 | - let second = store | ||
| 583 | - .scan_repo(&repo, &[dep("old", "1.0.0"), dep("other", "2.0.0")]) | ||
| 584 | - .await | ||
| 585 | - .unwrap(); | ||
| 586 | - assert_eq!( | ||
| 587 | - second, | ||
| 588 | - ScanOutcome { | ||
| 589 | - opened: 0, | ||
| 590 | - fixed: 1 | ||
| 591 | - }, | ||
| 592 | - "upgrade closes one" | ||
| 593 | - ); | ||
| 594 | - let third = store | ||
| 595 | - .scan_repo(&repo, &[dep("old", "1.0.0")]) | ||
| 596 | - .await | ||
| 597 | - .unwrap(); | ||
| 598 | - assert_eq!( | ||
| 599 | - third, | ||
| 600 | - ScanOutcome { | ||
| 601 | - opened: 0, | ||
| 602 | - fixed: 0 | ||
| 603 | - }, | ||
| 604 | - "nothing changes" | ||
| 605 | - ); | ||
| 606 | - | ||
| 607 | - let alerts = store.list_alerts(&repo).await.unwrap(); | ||
| 608 | - assert_eq!(alerts.len(), 2, "two alerts on the repo"); | ||
| 609 | - let open = alerts | ||
| 610 | - .iter() | ||
| 611 | - .find(|a| a.key.advisory_id == "RUSTSEC-1") | ||
| 612 | - .unwrap(); | ||
| 613 | - assert_eq!(open.state, AlertState::Open, "open alert"); | ||
| 614 | - assert_eq!(open.summary, "RUSTSEC-1 summary", "summary copied"); | ||
| 615 | - assert_eq!(open.severity, "HIGH", "severity copied"); | ||
| 616 | - let fixed = alerts | ||
| 617 | - .iter() | ||
| 618 | - .find(|a| a.key.advisory_id == "RUSTSEC-2") | ||
| 619 | - .unwrap(); | ||
| 620 | - assert_eq!(fixed.state, AlertState::Fixed, "fixed alert"); | ||
| 621 | - | ||
| 622 | - assert!( | ||
| 623 | - store | ||
| 624 | - .set_alert_state(&repo, &open.key, AlertState::Open, AlertState::Dismissed) | ||
| 625 | - .await | ||
| 626 | - .unwrap(), | ||
| 627 | - "dismiss applied" | ||
| 628 | - ); | ||
| 629 | - assert!( | ||
| 630 | - !store | ||
| 631 | - .set_alert_state(&repo, &open.key, AlertState::Open, AlertState::Dismissed) | ||
| 632 | - .await | ||
| 633 | - .unwrap(), | ||
| 634 | - "second dismiss is a no-op" | ||
| 635 | - ); | ||
| 636 | - let kept = store | ||
| 637 | - .scan_repo(&repo, &[dep("old", "1.0.0")]) | ||
| 638 | - .await | ||
| 639 | - .unwrap(); | ||
| 640 | - assert_eq!( | ||
| 641 | - kept, | ||
| 642 | - ScanOutcome { | ||
| 643 | - opened: 0, | ||
| 644 | - fixed: 0 | ||
| 645 | - }, | ||
| 646 | - "dismissed alert stays put" | ||
| 647 | - ); | ||
| 648 | - assert!( | ||
| 649 | - store | ||
| 650 | - .set_alert_state(&repo, &open.key, AlertState::Dismissed, AlertState::Open) | ||
| 651 | - .await | ||
| 652 | - .unwrap(), | ||
| 653 | - "reopen applied" | ||
| 654 | - ); | ||
| 655 | - | ||
| 656 | - let owner = store.repo_by_id(&repo).await.unwrap().unwrap().owner_id; | ||
| 657 | - let back = store | ||
| 658 | - .create_repo(&owner, "back", "", crate::Visibility::Private, "main") | ||
| 659 | - .await | ||
| 660 | - .unwrap() | ||
| 661 | - .id; | ||
| 662 | - store | ||
| 663 | - .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-3", "back", "2.0.0")]) | ||
| 664 | - .await | ||
| 665 | - .unwrap(); | ||
| 666 | - store | ||
| 667 | - .scan_repo(&back, &[dep("back", "1.0.0")]) | ||
| 668 | - .await | ||
| 669 | - .unwrap(); | ||
| 670 | - store | ||
| 671 | - .scan_repo(&back, &[dep("back", "2.0.0")]) | ||
| 672 | - .await | ||
| 673 | - .unwrap(); | ||
| 674 | - let again = store | ||
| 675 | - .scan_repo(&back, &[dep("back", "1.0.1")]) | ||
| 676 | - .await | ||
| 677 | - .unwrap(); | ||
| 678 | - assert_eq!( | ||
| 679 | - again, | ||
| 680 | - ScanOutcome { | ||
| 681 | - opened: 1, | ||
| 682 | - fixed: 0 | ||
| 683 | - }, | ||
| 684 | - "the match returns and reopens" | ||
| 685 | - ); | ||
| 686 | - let alerts = store.list_alerts(&back).await.unwrap(); | ||
| 687 | - assert_eq!(alerts.len(), 2, "alert count on the back repo"); | ||
| 688 | - assert_eq!(alerts[0].state, AlertState::Open, "reopened alert is open"); | ||
| 689 | - | ||
| 690 | - store | ||
| 691 | - .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")]) | ||
| 692 | - .await | ||
| 693 | - .unwrap(); | ||
| 694 | - store.replace_in_one_batch("npm", &[]).await.unwrap(); | ||
| 695 | - assert_eq!( | ||
| 696 | - store | ||
| 697 | - .advisories_for_package("crates.io", "a") | ||
| 698 | - .await | ||
| 699 | - .unwrap() | ||
| 700 | - .len(), | ||
| 701 | - 1, | ||
| 702 | - "crates.io advisory kept" | ||
| 703 | - ); | ||
| 704 | - store | ||
| 705 | - .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-5", "a", "3.0.0")]) | ||
| 706 | - .await | ||
| 707 | - .unwrap(); | ||
| 708 | - let rows = store | ||
| 709 | - .advisories_for_package("crates.io", "a") | ||
| 710 | - .await | ||
| 711 | - .unwrap(); | ||
| 712 | - assert_eq!(rows.len(), 1, "replaced in place"); | ||
| 713 | - assert_eq!(rows[0].id, "RUSTSEC-5", "the new advisory"); | ||
| 714 | - } | ||
| 715 | - | ||
| 716 | - #[tokio::test] | ||
| 717 | - async fn new_alert_notices_add_up_while_unread_and_stay_per_user() { | ||
| 718 | - let dir = tempfile::tempdir().unwrap(); | ||
| 719 | - let (store, repo) = store_with_repo(&dir).await; | ||
| 720 | - let bob = store.create_user("Bob", None, "hash", false).await.unwrap(); | ||
| 721 | - let owner = store.repo_by_id(&repo).await.unwrap().unwrap().owner_id; | ||
| 722 | - store.notify_new_alerts(&owner, &repo, 2).await.unwrap(); | ||
| 723 | - store.notify_new_alerts(&owner, &repo, 3).await.unwrap(); | ||
| 724 | - let notices = store | ||
| 725 | - .list_advisory_notifications(&owner, false, None, 50) | ||
| 726 | - .await | ||
| 727 | - .unwrap(); | ||
| 728 | - assert_eq!(notices.len(), 1); | ||
| 729 | - assert_eq!(notices[0].repo_id, repo); | ||
| 730 | - assert!(notices[0].repo_owner.eq_ignore_ascii_case("tahinli")); | ||
| 731 | - assert_eq!(notices[0].repo_name, "demo"); | ||
| 732 | - assert_eq!(notices[0].new_alerts, 5); | ||
| 733 | - assert!(notices[0].unread); | ||
| 734 | - assert!( | ||
| 735 | - store | ||
| 736 | - .list_advisory_notifications(&bob.id, false, None, 50) | ||
| 737 | - .await | ||
| 738 | - .unwrap() | ||
| 739 | - .is_empty() | ||
| 740 | - ); | ||
| 741 | - } | ||
| 742 | - | ||
| 743 | - #[tokio::test] | ||
| 744 | - async fn alert_notices_are_marked_read_by_repo_or_all() { | ||
| 745 | - let dir = tempfile::tempdir().unwrap(); | ||
| 746 | - let (store, repo) = store_with_repo(&dir).await; | ||
| 747 | - let owner = store.repo_by_id(&repo).await.unwrap().unwrap().owner_id; | ||
| 748 | - store.notify_new_alerts(&owner, &repo, 1).await.unwrap(); | ||
| 749 | - store | ||
| 750 | - .mark_advisory_notification_read(&owner, &repo) | ||
| 751 | - .await | ||
| 752 | - .unwrap(); | ||
| 753 | - let read = store.advisory_notification(&owner, &repo).await.unwrap(); | ||
| 754 | - assert!(!read.expect("row").unread); | ||
| 755 | - store.notify_new_alerts(&owner, &repo, 4).await.unwrap(); | ||
| 756 | - store | ||
| 757 | - .mark_all_advisory_notifications_read(&owner, Some(&repo)) | ||
| 758 | - .await | ||
| 759 | - .unwrap(); | ||
| 760 | - let unread = store | ||
| 761 | - .list_advisory_notifications(&owner, true, None, 50) | ||
| 762 | - .await | ||
| 763 | - .unwrap(); | ||
| 764 | - assert!(unread.is_empty()); | ||
| 765 | - } | ||
| 766 | -} | ||
crates/forge-core/src/store/mod.rsmodified+0 -4
| @@ -1,6 +1,5 @@ | |||
| 1 | pub mod account_tokens; | 1 | pub mod account_tokens; |
| 2 | pub mod admin_alerts; | 2 | pub mod admin_alerts; |
| 3 | -pub mod advisories; | ||
| 4 | pub mod attachments; | 3 | pub mod attachments; |
| 5 | pub mod audit; | 4 | pub mod audit; |
| 6 | pub mod backup_runs; | 5 | pub mod backup_runs; |
| @@ -1195,9 +1194,6 @@ impl Store { | |||
| 1195 | "DELETE FROM commit_statuses WHERE repo_id = ?1", | 1194 | "DELETE FROM commit_statuses WHERE repo_id = ?1", |
| 1196 | "DELETE FROM lfs_objects WHERE repo_id = ?1", | 1195 | "DELETE FROM lfs_objects WHERE repo_id = ?1", |
| 1197 | "DELETE FROM commit_signatures WHERE repo_id = ?1", | 1196 | "DELETE FROM commit_signatures WHERE repo_id = ?1", |
| 1198 | - "DELETE FROM advisory_notifications WHERE repo_id = ?1", | ||
| 1199 | - "DELETE FROM repo_alerts WHERE repo_id = ?1", | ||
| 1200 | - "DELETE FROM repo_dependencies WHERE repo_id = ?1", | ||
| 1201 | "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \ | 1197 | "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \ |
| 1202 | JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)", | 1198 | JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)", |
| 1203 | "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)", | 1199 | "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)", |
crates/forge-core/src/store/notifications.rsmodified+1 -3
| @@ -350,12 +350,10 @@ impl Store { | |||
| 350 | WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ | 350 | WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ |
| 351 | (SELECT COUNT(*) FROM discussion_notifications n JOIN repos r ON r.id = n.repo_id \ | 351 | (SELECT COUNT(*) FROM discussion_notifications n JOIN repos r ON r.id = n.repo_id \ |
| 352 | WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ | 352 | WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ |
| 353 | - (SELECT COUNT(*) FROM advisory_notifications n JOIN repos r ON r.id = n.repo_id \ | ||
| 354 | - WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ | ||
| 355 | (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ? AND unread = 1)" | 353 | (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ? AND unread = 1)" |
| 356 | ); | 354 | ); |
| 357 | let mut params = Vec::new(); | 355 | let mut params = Vec::new(); |
| 358 | - for _ in 0..3 { | 356 | + for _ in 0..2 { |
| 359 | params.push(Value::Text(user_id.to_string())); | 357 | params.push(Value::Text(user_id.to_string())); |
| 360 | params.extend(readable_params(user_id)); | 358 | params.extend(readable_params(user_id)); |
| 361 | } | 359 | } |
crates/forge-core/src/store/user_delete.rsmodified+0 -5
| @@ -113,11 +113,6 @@ const REMOVED: &[(&str, &str, &str)] = &[ | |||
| 113 | "discussion_notifications", | 113 | "discussion_notifications", |
| 114 | "user_id", | 114 | "user_id", |
| 115 | ), | 115 | ), |
| 116 | - ( | ||
| 117 | - "advisory notifications", | ||
| 118 | - "advisory_notifications", | ||
| 119 | - "user_id", | ||
| 120 | - ), | ||
| 121 | ("admin notifications", "admin_notifications", "user_id"), | 116 | ("admin notifications", "admin_notifications", "user_id"), |
| 122 | ("reactions", "reactions", "user_id"), | 117 | ("reactions", "reactions", "user_id"), |
| 123 | ("preferences", "user_prefs", "user_id"), | 118 | ("preferences", "user_prefs", "user_id"), |
crates/forge-e2e/tests/e2e/advisories_e2e.rsdeleted+0 -161
| @@ -1,161 +0,0 @@ | |||
| 1 | -use crate::common::{ | ||
| 2 | - BOB_CMD, Http, PW, Resp, Server, TAHINLI_CMD, boot_forge, commit_file, create_token, csrf_for, | ||
| 3 | - git_text, login, temp_dir, tool_on_path, | ||
| 4 | -}; | ||
| 5 | -use std::fs; | ||
| 6 | -use std::io::{Cursor, Write}; | ||
| 7 | -use std::path::PathBuf; | ||
| 8 | -use std::time::{Duration, Instant}; | ||
| 9 | - | ||
| 10 | -const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n"; | ||
| 11 | -const SCAN_TIMEOUT: Duration = Duration::from_secs(30); | ||
| 12 | - | ||
| 13 | -const OSV_RECORD: &str = r#"{ | ||
| 14 | - "id": "RUSTSEC-TEST-0001", | ||
| 15 | - "summary": "demo is vulnerable before 2.0.0", | ||
| 16 | - "modified": "2026-01-01T00:00:00Z", | ||
| 17 | - "database_specific": {"severity": "HIGH"}, | ||
| 18 | - "affected": [{ | ||
| 19 | - "package": {"ecosystem": "crates.io", "name": "demo"}, | ||
| 20 | - "ranges": [{"type": "SEMVER", "events": [{"introduced": "0"}, {"fixed": "2.0.0"}]}] | ||
| 21 | - }] | ||
| 22 | -}"#; | ||
| 23 | - | ||
| 24 | -const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; | ||
| 25 | -const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n"; | ||
| 26 | - | ||
| 27 | -fn dump_zip() -> Vec<u8> { | ||
| 28 | - let mut buf = Cursor::new(Vec::new()); | ||
| 29 | - { | ||
| 30 | - let mut zip = zip::ZipWriter::new(&mut buf); | ||
| 31 | - let options = zip::write::SimpleFileOptions::default(); | ||
| 32 | - zip.start_file("RUSTSEC-TEST-0001.json", options) | ||
| 33 | - .expect("start zip entry"); | ||
| 34 | - zip.write_all(OSV_RECORD.as_bytes()).expect("write record"); | ||
| 35 | - zip.finish().expect("finish zip"); | ||
| 36 | - } | ||
| 37 | - buf.into_inner() | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -struct Booted { | ||
| 41 | - _server: Server, | ||
| 42 | - _root: tempfile::TempDir, | ||
| 43 | - dir: PathBuf, | ||
| 44 | - http: Http, | ||
| 45 | - port: u16, | ||
| 46 | -} | ||
| 47 | - | ||
| 48 | -async fn boot() -> Booted { | ||
| 49 | - if !tool_on_path("git") { | ||
| 50 | - panic!("`git` was not found on PATH"); | ||
| 51 | - } | ||
| 52 | - let root = temp_dir("adv2e"); | ||
| 53 | - let dir = root.path().to_path_buf(); | ||
| 54 | - let dump_dir = dir.join("advisories").join("crates.io"); | ||
| 55 | - fs::create_dir_all(&dump_dir).expect("dump dir"); | ||
| 56 | - fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump"); | ||
| 57 | - | ||
| 58 | - let (server, ports) = boot_forge(&dir, ADVISORIES_TOML, &[TAHINLI_CMD, BOB_CMD]).await; | ||
| 59 | - Booted { | ||
| 60 | - _server: server, | ||
| 61 | - _root: root, | ||
| 62 | - dir, | ||
| 63 | - http: Http::new(ports.http), | ||
| 64 | - port: ports.http, | ||
| 65 | - } | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -async fn new_repo(http: &Http, session: &str, name: &str) { | ||
| 69 | - let csrf = csrf_for(http, "/new", session).await; | ||
| 70 | - let res = http | ||
| 71 | - .post_form( | ||
| 72 | - "/new", | ||
| 73 | - &[ | ||
| 74 | - ("csrf", &csrf), | ||
| 75 | - ("name", name), | ||
| 76 | - ("description", ""), | ||
| 77 | - ("visibility", "public"), | ||
| 78 | - ("default_branch", "main"), | ||
| 79 | - ], | ||
| 80 | - Some(session), | ||
| 81 | - ) | ||
| 82 | - .await; | ||
| 83 | - assert_eq!(res.status, 303, "create repo {name}: {}", res.body); | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -async fn security_page(http: &Http, session: &str) -> Resp { | ||
| 87 | - http.get_cookie("/tahinli/app/security", session).await | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -async fn wait_for_text(http: &Http, session: &str, text: &str) -> String { | ||
| 91 | - let deadline = Instant::now() + SCAN_TIMEOUT; | ||
| 92 | - loop { | ||
| 93 | - let page = security_page(http, session).await; | ||
| 94 | - if page.status == 200 && page.body.contains(text) { | ||
| 95 | - return page.body; | ||
| 96 | - } | ||
| 97 | - assert!( | ||
| 98 | - Instant::now() < deadline, | ||
| 99 | - "timed out waiting for {text:?} on the security page (last status {})", | ||
| 100 | - page.status | ||
| 101 | - ); | ||
| 102 | - tokio::time::sleep(Duration::from_millis(200)).await; | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp { | ||
| 107 | - let csrf = csrf_for(http, "/tahinli/app/security", session).await; | ||
| 108 | - http.post_form( | ||
| 109 | - &format!("/tahinli/app/security/{action}"), | ||
| 110 | - &[ | ||
| 111 | - ("csrf", &csrf), | ||
| 112 | - ("advisory", "RUSTSEC-TEST-0001"), | ||
| 113 | - ("ecosystem", "crates.io"), | ||
| 114 | - ("package", "demo"), | ||
| 115 | - ("version", "1.0.0"), | ||
| 116 | - ], | ||
| 117 | - Some(session), | ||
| 118 | - ) | ||
| 119 | - .await | ||
| 120 | -} | ||
| 121 | - | ||
| 122 | -#[tokio::test] | ||
| 123 | -async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() { | ||
| 124 | - let b = boot().await; | ||
| 125 | - let tahinli = login(&b.http, "tahinli", PW).await; | ||
| 126 | - let token = create_token(&b.http, &tahinli, "advisory-token").await; | ||
| 127 | - new_repo(&b.http, &tahinli, "app").await; | ||
| 128 | - | ||
| 129 | - let work = b.dir.join("app-work"); | ||
| 130 | - let remote = format!( | ||
| 131 | - "http://tahinli:{token}@127.0.0.1:{}/tahinli/app.git", | ||
| 132 | - b.port | ||
| 133 | - ); | ||
| 134 | - git_text( | ||
| 135 | - &b.dir, | ||
| 136 | - &["clone", "-q", &remote, work.to_str().expect("utf-8 path")], | ||
| 137 | - ); | ||
| 138 | - commit_file(&work, "Cargo.lock", LOCK_OLD, "lock demo 1.0.0"); | ||
| 139 | - git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | ||
| 140 | - | ||
| 141 | - let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await; | ||
| 142 | - assert!(page.contains(">Open</span>"), "the alert is open"); | ||
| 143 | - assert!(page.contains("demo"), "the vulnerable package is listed"); | ||
| 144 | - | ||
| 145 | - let dismissed = post_alert_action(&b.http, &tahinli, "dismiss").await; | ||
| 146 | - assert_eq!(dismissed.status, 303, "dismiss: {}", dismissed.body); | ||
| 147 | - let page = wait_for_text(&b.http, &tahinli, ">Dismissed</span>").await; | ||
| 148 | - assert!(page.contains("Reopen")); | ||
| 149 | - | ||
| 150 | - let reopened = post_alert_action(&b.http, &tahinli, "reopen").await; | ||
| 151 | - assert_eq!(reopened.status, 303, "reopen: {}", reopened.body); | ||
| 152 | - wait_for_text(&b.http, &tahinli, ">Open</span>").await; | ||
| 153 | - | ||
| 154 | - let bob = login(&b.http, "bob", PW).await; | ||
| 155 | - let refused = security_page(&b.http, &bob).await; | ||
| 156 | - assert_eq!(refused.status, 404, "a reader without Write gets 404"); | ||
| 157 | - | ||
| 158 | - commit_file(&work, "Cargo.lock", LOCK_FIXED, "lock demo 2.0.0"); | ||
| 159 | - git_text(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]); | ||
| 160 | - wait_for_text(&b.http, &tahinli, ">Fixed</span>").await; | ||
| 161 | -} | ||
crates/forge-e2e/tests/e2e/main.rsmodified+0 -1
| @@ -1,7 +1,6 @@ | |||
| 1 | mod common; | 1 | mod common; |
| 2 | 2 | ||
| 3 | mod account_mail_e2e; | 3 | mod account_mail_e2e; |
| 4 | -mod advisories_e2e; | ||
| 5 | mod branch_protection_e2e; | 4 | mod branch_protection_e2e; |
| 6 | mod browse_e2e; | 5 | mod browse_e2e; |
| 7 | mod ci_e2e; | 6 | mod ci_e2e; |
crates/forge-web-account/src/pages/admin_server.rsmodified+0 -3
| @@ -179,9 +179,6 @@ pub(crate) const PAGES: &[SrvPage] = &[ | |||
| 179 | keys: &[ | 179 | keys: &[ |
| 180 | "webhooks.allow_http", | 180 | "webhooks.allow_http", |
| 181 | "webhooks.allowed_hosts", | 181 | "webhooks.allowed_hosts", |
| 182 | - "advisories.enabled", | ||
| 183 | - "advisories.ecosystems", | ||
| 184 | - "advisories.refresh_hours", | ||
| 185 | ], | 182 | ], |
| 186 | }, | 183 | }, |
| 187 | SrvPage { | 184 | SrvPage { |
crates/forge-web-app/Cargo.tomlmodified+0 -1
| @@ -41,7 +41,6 @@ hmac.workspace = true | |||
| 41 | similar = { workspace = true } | 41 | similar = { workspace = true } |
| 42 | ulid.workspace = true | 42 | ulid.workspace = true |
| 43 | lettre.workspace = true | 43 | lettre.workspace = true |
| 44 | -zip = { workspace = true } | ||
| 45 | tar.workspace = true | 44 | tar.workspace = true |
| 46 | flate2.workspace = true | 45 | flate2.workspace = true |
| 47 | p256.workspace = true | 46 | p256.workspace = true |
crates/forge-web-app/src/advisories/mod.rsdeleted+0 -2
| @@ -1,2 +0,0 @@ | |||
| 1 | -pub mod scan; | ||
| 2 | -pub mod worker; | ||
crates/forge-web-app/src/advisories/scan.rsdeleted+0 -135
| @@ -1,135 +0,0 @@ | |||
| 1 | -use std::collections::VecDeque; | ||
| 2 | -use std::path::Path; | ||
| 3 | - | ||
| 4 | -use forge_core::advisories::{Dependency, parse_cargo_lock, parse_go_sum, parse_package_lock}; | ||
| 5 | -use forge_core::store::advisories::ScanOutcome; | ||
| 6 | -use forge_core::{Error, Repo, Result}; | ||
| 7 | -use forge_git::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree}; | ||
| 8 | - | ||
| 9 | -use crate::live::bump_settings; | ||
| 10 | -use crate::state::AppState; | ||
| 11 | - | ||
| 12 | -const MAX_DEPTH: usize = 3; | ||
| 13 | -const MAX_DIRS: usize = 500; | ||
| 14 | -const MAX_LOCKFILE_BYTES: usize = 32 * 1024 * 1024; | ||
| 15 | - | ||
| 16 | -pub fn spawn_repo_scan(state: &AppState, repo: &Repo) { | ||
| 17 | - if !state.config.advisories.enabled { | ||
| 18 | - return; | ||
| 19 | - } | ||
| 20 | - let state = state.clone(); | ||
| 21 | - let repo = repo.clone(); | ||
| 22 | - tokio::spawn(async move { | ||
| 23 | - if let Err(e) = scan_repo(&state, &repo).await { | ||
| 24 | - tracing::error!(error = %e, repo_id = %repo.id, "advisories: scan failed"); | ||
| 25 | - } | ||
| 26 | - }); | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | -pub async fn scan_all(state: &AppState) { | ||
| 30 | - let ids = match state.store.all_repo_ids().await { | ||
| 31 | - Ok(ids) => ids, | ||
| 32 | - Err(e) => { | ||
| 33 | - tracing::error!(error = %e, "advisories: could not list repos"); | ||
| 34 | - return; | ||
| 35 | - } | ||
| 36 | - }; | ||
| 37 | - for id in ids { | ||
| 38 | - match state.store.repo_by_id(&id).await { | ||
| 39 | - Ok(Some(repo)) => { | ||
| 40 | - if let Err(e) = scan_repo(state, &repo).await { | ||
| 41 | - tracing::error!(error = %e, repo_id = %id, "advisories: scan failed"); | ||
| 42 | - } | ||
| 43 | - } | ||
| 44 | - Ok(None) => {} | ||
| 45 | - Err(e) => tracing::error!(error = %e, repo_id = %id, "advisories: could not load repo"), | ||
| 46 | - } | ||
| 47 | - } | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -pub async fn scan_repo(state: &AppState, repo: &Repo) -> Result<ScanOutcome> { | ||
| 51 | - let dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) | ||
| 52 | - .map_err(|e| Error::Git(e.to_string()))?; | ||
| 53 | - let branch = repo.default_branch.clone(); | ||
| 54 | - let deps = | ||
| 55 | - tokio::task::spawn_blocking(move || -> std::result::Result<Vec<Dependency>, String> { | ||
| 56 | - match default_branch_commit(&dir, &branch).map_err(|e| e.to_string())? { | ||
| 57 | - Some(commit) => collect_dependencies(&dir, &commit), | ||
| 58 | - None => Ok(Vec::new()), | ||
| 59 | - } | ||
| 60 | - }) | ||
| 61 | - .await | ||
| 62 | - .map_err(|e| Error::Git(format!("scan task failed: {e}")))? | ||
| 63 | - .map_err(Error::Git)?; | ||
| 64 | - let outcome = state.store.scan_repo(&repo.id, &deps).await?; | ||
| 65 | - if outcome.opened > 0 || outcome.fixed > 0 { | ||
| 66 | - bump_settings(&state.live, &repo.id); | ||
| 67 | - } | ||
| 68 | - if outcome.opened > 0 { | ||
| 69 | - tracing::info!( | ||
| 70 | - repo_id = %repo.id, | ||
| 71 | - opened = outcome.opened, | ||
| 72 | - fixed = outcome.fixed, | ||
| 73 | - "advisories: new alerts" | ||
| 74 | - ); | ||
| 75 | - crate::notify::advisories_opened(state, repo, outcome.opened).await; | ||
| 76 | - } | ||
| 77 | - Ok(outcome) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -pub fn collect_dependencies( | ||
| 81 | - repo: &Path, | ||
| 82 | - commit: &str, | ||
| 83 | -) -> std::result::Result<Vec<Dependency>, String> { | ||
| 84 | - let mut found = Vec::new(); | ||
| 85 | - let mut queue: VecDeque<(String, usize)> = VecDeque::from([(String::new(), 0)]); | ||
| 86 | - let mut visited = 0; | ||
| 87 | - while let Some((dir, depth)) = queue.pop_front() { | ||
| 88 | - if visited >= MAX_DIRS { | ||
| 89 | - break; | ||
| 90 | - } | ||
| 91 | - visited += 1; | ||
| 92 | - let Some(entries) = read_tree(repo, commit, &dir).map_err(|e| e.to_string())? else { | ||
| 93 | - continue; | ||
| 94 | - }; | ||
| 95 | - for entry in entries { | ||
| 96 | - let path = if dir.is_empty() { | ||
| 97 | - entry.name.clone() | ||
| 98 | - } else { | ||
| 99 | - format!("{dir}/{}", entry.name) | ||
| 100 | - }; | ||
| 101 | - match entry.kind { | ||
| 102 | - EntryKind::Tree => { | ||
| 103 | - if depth < MAX_DEPTH { | ||
| 104 | - queue.push_back((path, depth + 1)); | ||
| 105 | - } | ||
| 106 | - } | ||
| 107 | - EntryKind::Blob | EntryKind::Executable => { | ||
| 108 | - if !matches!( | ||
| 109 | - entry.name.as_str(), | ||
| 110 | - "Cargo.lock" | "package-lock.json" | "go.sum" | ||
| 111 | - ) { | ||
| 112 | - continue; | ||
| 113 | - } | ||
| 114 | - let text = match read_text_blob(repo, commit, &path, MAX_LOCKFILE_BYTES) { | ||
| 115 | - Ok(Some(text)) => text, | ||
| 116 | - Ok(None) => { | ||
| 117 | - return Err(format!("{path}: not UTF-8 text or over the size limit")); | ||
| 118 | - } | ||
| 119 | - Err(e) => return Err(format!("{path}: {e}")), | ||
| 120 | - }; | ||
| 121 | - let parsed = match entry.name.as_str() { | ||
| 122 | - "Cargo.lock" => parse_cargo_lock(&text, &path), | ||
| 123 | - "package-lock.json" => parse_package_lock(&text, &path), | ||
| 124 | - _ => Ok(parse_go_sum(&text, &path)), | ||
| 125 | - }; | ||
| 126 | - found.extend(parsed.map_err(|e| format!("{path}: {e}"))?); | ||
| 127 | - } | ||
| 128 | - EntryKind::Symlink | EntryKind::Submodule => {} | ||
| 129 | - } | ||
| 130 | - } | ||
| 131 | - } | ||
| 132 | - found.sort(); | ||
| 133 | - found.dedup(); | ||
| 134 | - Ok(found) | ||
| 135 | -} | ||
crates/forge-web-app/src/advisories/worker.rsdeleted+0 -218
| @@ -1,218 +0,0 @@ | |||
| 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 | -} | ||
crates/forge-web-app/src/layers.rsmodified+1 -1
| @@ -457,7 +457,7 @@ mod repo_settings_write { | |||
| 457 | fn written(cx: &Cx) -> Option<(String, String)> { | 457 | fn written(cx: &Cx) -> Option<(String, String)> { |
| 458 | let parts = post_segments(cx)?; | 458 | let parts = post_segments(cx)?; |
| 459 | match parts.as_slice() { | 459 | match parts.as_slice() { |
| 460 | - [owner, name, "settings" | "security", ..] => { | 460 | + [owner, name, "settings", ..] => { |
| 461 | Some(((*owner).to_owned(), (*name).to_owned())) | 461 | Some(((*owner).to_owned(), (*name).to_owned())) |
| 462 | } | 462 | } |
| 463 | _ => None, | 463 | _ => None, |
crates/forge-web-app/src/lib.rsmodified+0 -1
| @@ -7,7 +7,6 @@ pub use forge_web_base::{ | |||
| 7 | 7 | ||
| 8 | pub mod access; | 8 | pub mod access; |
| 9 | pub mod admin_client; | 9 | pub mod admin_client; |
| 10 | -pub mod advisories; | ||
| 11 | pub mod alerts; | 10 | pub mod alerts; |
| 12 | pub mod api; | 11 | pub mod api; |
| 13 | pub mod audit; | 12 | pub mod audit; |
crates/forge-web-app/src/notify.rsmodified+0 -126
| @@ -140,54 +140,6 @@ pub async fn dispatch_review_requested( | |||
| 140 | dispatch(state, repo, issue, actor_id, activity, None).await; | 140 | dispatch(state, repo, issue, actor_id, activity, None).await; |
| 141 | } | 141 | } |
| 142 | 142 | ||
| 143 | -pub async fn advisories_opened(state: &AppState, repo: &Repo, opened: usize) { | ||
| 144 | - if let Err(e) = notify_advisory_admins(state, repo, opened).await { | ||
| 145 | - tracing::error!(error = %e, repo_id = %repo.id, "notify: advisory alert notice failed"); | ||
| 146 | - } | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -async fn advisory_admins(state: &AppState, repo: &Repo) -> Result<Vec<String>> { | ||
| 150 | - let mut admins: BTreeSet<String> = BTreeSet::new(); | ||
| 151 | - if let Some(owner) = state.store.user_by_id(&repo.owner_id).await? { | ||
| 152 | - if owner.is_org() { | ||
| 153 | - for (member, role) in state.store.org_members(&owner.id).await? { | ||
| 154 | - if role == OrgMemberRole::Owner { | ||
| 155 | - admins.insert(member.id); | ||
| 156 | - } | ||
| 157 | - } | ||
| 158 | - } else { | ||
| 159 | - admins.insert(owner.id); | ||
| 160 | - } | ||
| 161 | - } | ||
| 162 | - for (user, role) in state.store.list_collaborators(&repo.id).await? { | ||
| 163 | - if role == forge_core::Role::Admin { | ||
| 164 | - admins.insert(user.id); | ||
| 165 | - } | ||
| 166 | - } | ||
| 167 | - Ok(admins.into_iter().collect()) | ||
| 168 | -} | ||
| 169 | - | ||
| 170 | -async fn notify_advisory_admins(state: &AppState, repo: &Repo, opened: usize) -> Result<()> { | ||
| 171 | - let count = u64::try_from(opened).unwrap_or(u64::MAX); | ||
| 172 | - for admin in advisory_admins(state, repo).await? { | ||
| 173 | - state | ||
| 174 | - .store | ||
| 175 | - .notify_new_alerts(&admin, &repo.id, count) | ||
| 176 | - .await?; | ||
| 177 | - publish_unread(state, &admin).await; | ||
| 178 | - web_push::queue( | ||
| 179 | - state, | ||
| 180 | - &admin, | ||
| 181 | - Alert::Advisories { | ||
| 182 | - repo: format!("{}/{}", repo.owner_name, repo.name), | ||
| 183 | - count, | ||
| 184 | - url: format!("/{}/{}/security", repo.owner_name, repo.name), | ||
| 185 | - }, | ||
| 186 | - ); | ||
| 187 | - } | ||
| 188 | - Ok(()) | ||
| 189 | -} | ||
| 190 | - | ||
| 191 | async fn fan_out( | 143 | async fn fan_out( |
| 192 | state: &AppState, | 144 | state: &AppState, |
| 193 | repo: &Repo, | 145 | repo: &Repo, |
| @@ -986,84 +938,6 @@ mod tests { | |||
| 986 | assert_eq!(carol_inbox[0].last_activity, "edited"); | 938 | assert_eq!(carol_inbox[0].last_activity, "edited"); |
| 987 | } | 939 | } |
| 988 | 940 | ||
| 989 | - #[tokio::test] | ||
| 990 | - async fn advisory_alerts_reach_owner_admin_collaborators_and_org_owners_only() { | ||
| 991 | - let dir = tempfile::tempdir().expect("tempdir"); | ||
| 992 | - let state = test_state(dir.path()).await; | ||
| 993 | - let store = &state.store; | ||
| 994 | - let owner = store | ||
| 995 | - .create_user("owner", None, "unused", false) | ||
| 996 | - .await | ||
| 997 | - .unwrap(); | ||
| 998 | - let admin = store | ||
| 999 | - .create_user("admin", None, "unused", false) | ||
| 1000 | - .await | ||
| 1001 | - .unwrap(); | ||
| 1002 | - let writer = store | ||
| 1003 | - .create_user("writer", None, "unused", false) | ||
| 1004 | - .await | ||
| 1005 | - .unwrap(); | ||
| 1006 | - let repo = store | ||
| 1007 | - .create_repo(&owner.id, "proj", "", Visibility::Private, "main") | ||
| 1008 | - .await | ||
| 1009 | - .unwrap(); | ||
| 1010 | - store | ||
| 1011 | - .set_collaborator(&repo.id, &admin.id, Role::Admin) | ||
| 1012 | - .await | ||
| 1013 | - .unwrap(); | ||
| 1014 | - store | ||
| 1015 | - .set_collaborator(&repo.id, &writer.id, Role::Write) | ||
| 1016 | - .await | ||
| 1017 | - .unwrap(); | ||
| 1018 | - | ||
| 1019 | - advisories_opened(&state, &repo, 2).await; | ||
| 1020 | - | ||
| 1021 | - assert_eq!(advisory_rows(store, &owner.id).await, vec![2]); | ||
| 1022 | - assert_eq!(advisory_rows(store, &admin.id).await, vec![2]); | ||
| 1023 | - assert!(advisory_rows(store, &writer.id).await.is_empty()); | ||
| 1024 | - | ||
| 1025 | - let org = store.create_org("acme", &owner.id).await.unwrap(); | ||
| 1026 | - let org_member = store | ||
| 1027 | - .create_user("member", None, "unused", false) | ||
| 1028 | - .await | ||
| 1029 | - .unwrap(); | ||
| 1030 | - let org_owner = store | ||
| 1031 | - .create_user("orgowner", None, "unused", false) | ||
| 1032 | - .await | ||
| 1033 | - .unwrap(); | ||
| 1034 | - store | ||
| 1035 | - .add_org_member(&org.id, &org_member.id, OrgMemberRole::Member) | ||
| 1036 | - .await | ||
| 1037 | - .unwrap(); | ||
| 1038 | - store | ||
| 1039 | - .add_org_member(&org.id, &org_owner.id, OrgMemberRole::Owner) | ||
| 1040 | - .await | ||
| 1041 | - .unwrap(); | ||
| 1042 | - let org_repo = store | ||
| 1043 | - .create_repo(&org.id, "shared", "", Visibility::Private, "main") | ||
| 1044 | - .await | ||
| 1045 | - .unwrap(); | ||
| 1046 | - | ||
| 1047 | - advisories_opened(&state, &org_repo, 1).await; | ||
| 1048 | - | ||
| 1049 | - assert_eq!(advisory_rows(store, &owner.id).await, vec![1, 2]); | ||
| 1050 | - assert_eq!(advisory_rows(store, &org_owner.id).await, vec![1]); | ||
| 1051 | - assert!(advisory_rows(store, &org_member.id).await.is_empty()); | ||
| 1052 | - assert!(advisory_rows(store, &org.id).await.is_empty()); | ||
| 1053 | - } | ||
| 1054 | - | ||
| 1055 | - async fn advisory_rows(store: &forge_core::store::Store, user_id: &str) -> Vec<u64> { | ||
| 1056 | - let mut counts: Vec<u64> = store | ||
| 1057 | - .list_advisory_notifications(user_id, false, None, 50) | ||
| 1058 | - .await | ||
| 1059 | - .unwrap() | ||
| 1060 | - .iter() | ||
| 1061 | - .map(|notice| notice.new_alerts) | ||
| 1062 | - .collect(); | ||
| 1063 | - counts.sort_unstable(); | ||
| 1064 | - counts | ||
| 1065 | - } | ||
| 1066 | - | ||
| 1067 | async fn mail_fixture(enabled: bool) -> Fixture { | 941 | async fn mail_fixture(enabled: bool) -> Fixture { |
| 1068 | let fx = fixture(Visibility::Public).await; | 942 | let fx = fixture(Visibility::Public).await; |
| 1069 | let store = &fx.state.store; | 943 | let store = &fx.state.store; |
crates/forge-web-app/src/post_update.rsmodified+0 -3
| @@ -49,9 +49,6 @@ pub async fn after_ref_update( | |||
| 49 | } | 49 | } |
| 50 | let branch = refname.starts_with("refs/heads/") && !is_zero_oid(new); | 50 | let branch = refname.starts_with("refs/heads/") && !is_zero_oid(new); |
| 51 | let default = branch && refname == format!("refs/heads/{}", repo.default_branch); | 51 | let default = branch && refname == format!("refs/heads/{}", repo.default_branch); |
| 52 | - if default { | ||
| 53 | - crate::advisories::scan::spawn_repo_scan(state, repo); | ||
| 54 | - } | ||
| 55 | crate::replication::enqueue_repo(state, &repo.id); | 52 | crate::replication::enqueue_repo(state, &repo.id); |
| 56 | if branch { | 53 | if branch { |
| 57 | match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { | 54 | match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { |
crates/forge-web-app/src/prune.rsmodified+1 -1
| @@ -23,7 +23,7 @@ async fn run(state: AppState) { | |||
| 23 | } | 23 | } |
| 24 | 24 | ||
| 25 | async fn sweep(state: &AppState) { | 25 | async fn sweep(state: &AppState) { |
| 26 | - let ids = match state.store.all_repo_ids().await { | 26 | + let ids = match state.store.repo_ids().await { |
| 27 | Ok(ids) => ids, | 27 | Ok(ids) => ids, |
| 28 | Err(e) => { | 28 | Err(e) => { |
| 29 | tracing::error!(error = %e, "prune: listing repos failed"); | 29 | tracing::error!(error = %e, "prune: listing repos failed"); |
crates/forge-web-app/src/test_support/mod.rsmodified+0 -1
| @@ -46,7 +46,6 @@ pub fn test_config(dir: &Path) -> Config { | |||
| 46 | claim_wait_ms: 50, | 46 | claim_wait_ms: 50, |
| 47 | ..Default::default() | 47 | ..Default::default() |
| 48 | }, | 48 | }, |
| 49 | - advisories: Default::default(), | ||
| 50 | mail: Default::default(), | 49 | mail: Default::default(), |
| 51 | orgs: Default::default(), | 50 | orgs: Default::default(), |
| 52 | self_update: Default::default(), | 51 | self_update: Default::default(), |
crates/forge-web-app/src/views/mod.rsmodified+1 -9
| @@ -156,7 +156,7 @@ fn step_label(lang: Lang, word: &str) -> String { | |||
| 156 | fn repo_section_label(lang: Lang, kind: &str) -> Option<String> { | 156 | fn repo_section_label(lang: Lang, kind: &str) -> Option<String> { |
| 157 | match kind { | 157 | match kind { |
| 158 | "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" | 158 | "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" |
| 159 | - | "discussions" | "wiki" | "security" | "settings" => Some(tab_title(lang, kind, "")), | 159 | + | "discussions" | "wiki" | "settings" => Some(tab_title(lang, kind, "")), |
| 160 | "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()), | 160 | "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()), |
| 161 | "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()), | 161 | "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()), |
| 162 | _ => None, | 162 | _ => None, |
| @@ -1293,7 +1293,6 @@ pub async fn repo_tabs( | |||
| 1293 | #[default] open_pulls: Option<u64>, | 1293 | #[default] open_pulls: Option<u64>, |
| 1294 | #[default] discussions: bool, | 1294 | #[default] discussions: bool, |
| 1295 | #[default] wiki: bool, | 1295 | #[default] wiki: bool, |
| 1296 | - #[default] security: bool, | ||
| 1297 | ) -> Result<impl View> { | 1296 | ) -> Result<impl View> { |
| 1298 | let home = repo_href(&owner, &repo, "", ""); | 1297 | let home = repo_href(&owner, &repo, "", ""); |
| 1299 | let issues = repo_href(&owner, &repo, "issues", ""); | 1298 | let issues = repo_href(&owner, &repo, "issues", ""); |
| @@ -1313,7 +1312,6 @@ pub async fn repo_tabs( | |||
| 1313 | let settings = repo_href(&owner, &repo, "settings", ""); | 1312 | let settings = repo_href(&owner, &repo, "settings", ""); |
| 1314 | let discussions_tab = repo_href(&owner, &repo, "discussions", ""); | 1313 | let discussions_tab = repo_href(&owner, &repo, "discussions", ""); |
| 1315 | let wiki_tab = repo_href(&owner, &repo, "wiki", ""); | 1314 | let wiki_tab = repo_href(&owner, &repo, "wiki", ""); |
| 1316 | - let security_tab = repo_href(&owner, &repo, "security", ""); | ||
| 1317 | Ok(view! { | 1315 | Ok(view! { |
| 1318 | <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))> | 1316 | <nav class="repo-tabs" aria-label=(g::t(lang, K::RepositoryNav))> |
| 1319 | <a class=(tab_class(code_on)) href=(home)> | 1317 | <a class=(tab_class(code_on)) href=(home)> |
| @@ -1355,11 +1353,6 @@ pub async fn repo_tabs( | |||
| 1355 | (g::t(lang, K::TabWiki)) | 1353 | (g::t(lang, K::TabWiki)) |
| 1356 | </a> | 1354 | </a> |
| 1357 | } | 1355 | } |
| 1358 | - if security { | ||
| 1359 | - <a class=(tab_class(active == "security")) href=(security_tab)> | ||
| 1360 | - (t(lang, Key::Security)) | ||
| 1361 | - </a> | ||
| 1362 | - } | ||
| 1363 | if can_admin { | 1356 | if can_admin { |
| 1364 | <a class=(tab_class(active == "settings")) href=(settings)> | 1357 | <a class=(tab_class(active == "settings")) href=(settings)> |
| 1365 | (g::t(lang, K::TabSettings)) | 1358 | (g::t(lang, K::TabSettings)) |
| @@ -1616,7 +1609,6 @@ pub fn tab_title(lang: Lang, active: &str, repo: &str) -> String { | |||
| 1616 | "releases" => g::t(lang, K::TabReleases).to_owned(), | 1609 | "releases" => g::t(lang, K::TabReleases).to_owned(), |
| 1617 | "discussions" => g::t(lang, K::TabDiscussions).to_owned(), | 1610 | "discussions" => g::t(lang, K::TabDiscussions).to_owned(), |
| 1618 | "wiki" => g::t(lang, K::TabWiki).to_owned(), | 1611 | "wiki" => g::t(lang, K::TabWiki).to_owned(), |
| 1619 | - "security" => i18n::t(lang, i18n::Key::Security).to_owned(), | ||
| 1620 | "settings" => g::t(lang, K::TabSettings).to_owned(), | 1612 | "settings" => g::t(lang, K::TabSettings).to_owned(), |
| 1621 | _ => repo.to_owned(), | 1613 | _ => repo.to_owned(), |
| 1622 | } | 1614 | } |
crates/forge-web-app/src/web_push/mod.rsmodified+0 -18
| @@ -49,11 +49,6 @@ pub enum Alert { | |||
| 49 | url: String, | 49 | url: String, |
| 50 | thread: String, | 50 | thread: String, |
| 51 | }, | 51 | }, |
| 52 | - Advisories { | ||
| 53 | - repo: String, | ||
| 54 | - count: u64, | ||
| 55 | - url: String, | ||
| 56 | - }, | ||
| 57 | Admin { | 52 | Admin { |
| 58 | subject: String, | 53 | subject: String, |
| 59 | detail: String, | 54 | detail: String, |
| @@ -89,12 +84,6 @@ impl Alert { | |||
| 89 | tag: format!("thread-{thread}"), | 84 | tag: format!("thread-{thread}"), |
| 90 | } | 85 | } |
| 91 | } | 86 | } |
| 92 | - Alert::Advisories { repo, count, url } => Message { | ||
| 93 | - title: clip(repo), | ||
| 94 | - body: text::advisory_alerts(lang, *count), | ||
| 95 | - url: safe_url(url), | ||
| 96 | - tag: format!("advisories-{repo}"), | ||
| 97 | - }, | ||
| 98 | Alert::Admin { subject, detail } => Message { | 87 | Alert::Admin { subject, detail } => Message { |
| 99 | title: clip(subject), | 88 | title: clip(subject), |
| 100 | body: clip(detail), | 89 | body: clip(detail), |
| @@ -374,13 +363,6 @@ mod tests { | |||
| 374 | fn the_payload_follows_the_recipient_language() { | 363 | fn the_payload_follows_the_recipient_language() { |
| 375 | let msg = activity(None).message(Lang::Tr); | 364 | let msg = activity(None).message(Lang::Tr); |
| 376 | assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body); | 365 | assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body); |
| 377 | - let advisories = Alert::Advisories { | ||
| 378 | - repo: "tahinli/forge".into(), | ||
| 379 | - count: 3, | ||
| 380 | - url: "/tahinli/forge/security".into(), | ||
| 381 | - }; | ||
| 382 | - assert_eq!(advisories.message(Lang::En).body, "3 new security alerts"); | ||
| 383 | - assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı"); | ||
| 384 | } | 366 | } |
| 385 | 367 | ||
| 386 | #[test] | 368 | #[test] |
crates/forge-web-base/src/i18n/audit_names.rsmodified+0 -8
| @@ -112,10 +112,6 @@ pub fn action_name(lang: Lang, action: &str) -> Option<&'static str> { | |||
| 112 | ("ci_runner_config_changed", Lang::Tr) => Some("CI çalıştırıcısı ayarları değiştirildi"), | 112 | ("ci_runner_config_changed", Lang::Tr) => Some("CI çalıştırıcısı ayarları değiştirildi"), |
| 113 | ("ci_registration_token_created", Lang::En) => Some("CI registration token created"), | 113 | ("ci_registration_token_created", Lang::En) => Some("CI registration token created"), |
| 114 | ("ci_registration_token_created", Lang::Tr) => Some("CI kayıt belirteci oluşturuldu"), | 114 | ("ci_registration_token_created", Lang::Tr) => Some("CI kayıt belirteci oluşturuldu"), |
| 115 | - ("advisory_alert_dismissed", Lang::En) => Some("Advisory alert dismissed"), | ||
| 116 | - ("advisory_alert_dismissed", Lang::Tr) => Some("Güvenlik uyarısı kapatıldı"), | ||
| 117 | - ("advisory_alert_reopened", Lang::En) => Some("Advisory alert reopened"), | ||
| 118 | - ("advisory_alert_reopened", Lang::Tr) => Some("Güvenlik uyarısı yeniden açıldı"), | ||
| 119 | ("ui_prefs_changed", Lang::En) => Some("Display preferences changed"), | 115 | ("ui_prefs_changed", Lang::En) => Some("Display preferences changed"), |
| 120 | ("ui_prefs_changed", Lang::Tr) => Some("Görünüm tercihleri değiştirildi"), | 116 | ("ui_prefs_changed", Lang::Tr) => Some("Görünüm tercihleri değiştirildi"), |
| 121 | ("discussions_enabled", Lang::En) => Some("Discussions turned on"), | 117 | ("discussions_enabled", Lang::En) => Some("Discussions turned on"), |
| @@ -370,8 +366,6 @@ pub fn detail_key_name(lang: Lang, key: &str) -> Option<&'static str> { | |||
| 370 | ("boot_id", Lang::Tr) => Some("açılış kimliği"), | 366 | ("boot_id", Lang::Tr) => Some("açılış kimliği"), |
| 371 | ("all_repos", Lang::En) => Some("all repositories"), | 367 | ("all_repos", Lang::En) => Some("all repositories"), |
| 372 | ("all_repos", Lang::Tr) => Some("tüm depolar"), | 368 | ("all_repos", Lang::Tr) => Some("tüm depolar"), |
| 373 | - ("advisory", Lang::En) => Some("advisory"), | ||
| 374 | - ("advisory", Lang::Tr) => Some("güvenlik uyarısı"), | ||
| 375 | ("version", Lang::En) => Some("version"), | 369 | ("version", Lang::En) => Some("version"), |
| 376 | ("version", Lang::Tr) => Some("sürüm"), | 370 | ("version", Lang::Tr) => Some("sürüm"), |
| 377 | ("security", Lang::En) => Some("security"), | 371 | ("security", Lang::En) => Some("security"), |
| @@ -463,8 +457,6 @@ mod tests { | |||
| 463 | "ci_runner_restart_requested", | 457 | "ci_runner_restart_requested", |
| 464 | "ci_runner_config_changed", | 458 | "ci_runner_config_changed", |
| 465 | "ci_registration_token_created", | 459 | "ci_registration_token_created", |
| 466 | - "advisory_alert_dismissed", | ||
| 467 | - "advisory_alert_reopened", | ||
| 468 | "ui_prefs_changed", | 460 | "ui_prefs_changed", |
| 469 | "discussions_enabled", | 461 | "discussions_enabled", |
| 470 | "discussions_disabled", | 462 | "discussions_disabled", |
crates/forge-web-base/src/i18n/misc.rsmodified+0 -31
| @@ -37,7 +37,6 @@ strings! { | |||
| 37 | KindOpenPull => "Open pull request", "Açık çekme isteği"; | 37 | KindOpenPull => "Open pull request", "Açık çekme isteği"; |
| 38 | KindClosedPull => "Closed pull request", "Kapalı çekme isteği"; | 38 | KindClosedPull => "Closed pull request", "Kapalı çekme isteği"; |
| 39 | KindDiscussion => "Discussion", "Tartışma"; | 39 | KindDiscussion => "Discussion", "Tartışma"; |
| 40 | - KindSecurityAlerts => "Security alerts", "Güvenlik uyarıları"; | ||
| 41 | KindAdminAlert => "Admin alert", "Yönetici uyarısı"; | 40 | KindAdminAlert => "Admin alert", "Yönetici uyarısı"; |
| 42 | ReasonMentioned => "mentioned", "bahsedildi"; | 41 | ReasonMentioned => "mentioned", "bahsedildi"; |
| 43 | ReasonAssigned => "assigned", "atandı"; | 42 | ReasonAssigned => "assigned", "atandı"; |
| @@ -48,7 +47,6 @@ strings! { | |||
| 48 | ReasonSubscribed => "subscribed", "abone"; | 47 | ReasonSubscribed => "subscribed", "abone"; |
| 49 | ReasonWatching => "watching", "izleniyor"; | 48 | ReasonWatching => "watching", "izleniyor"; |
| 50 | ReasonReplied => "replied", "yanıtladı"; | 49 | ReasonReplied => "replied", "yanıtladı"; |
| 51 | - ReasonSecurity => "security", "güvenlik"; | ||
| 52 | ReasonAdmin => "admin", "yönetici"; | 50 | ReasonAdmin => "admin", "yönetici"; |
| 53 | VerbOpened => "opened", "açıldı"; | 51 | VerbOpened => "opened", "açıldı"; |
| 54 | VerbCommented => "commented", "yorumlandı"; | 52 | VerbCommented => "commented", "yorumlandı"; |
| @@ -75,9 +73,6 @@ strings! { | |||
| 75 | OptParticipating => "Participating", "Katılımcı"; | 73 | OptParticipating => "Participating", "Katılımcı"; |
| 76 | OptWatching => "Watching", "İzleniyor"; | 74 | OptWatching => "Watching", "İzleniyor"; |
| 77 | OptIgnoring => "Ignoring", "Yok sayılıyor"; | 75 | OptIgnoring => "Ignoring", "Yok sayılıyor"; |
| 78 | - SecurityOff => "Security advisories are off on this instance, so no lockfile is scanned. An administrator can turn them on with the [advisories] section of the config.", "Bu sunucuda güvenlik tavsiyeleri kapalı, bu yüzden hiçbir kilit dosyası taranmıyor. Bir yönetici bunları yapılandırma dosyasındaki [advisories] bölümünden açabilir."; | ||
| 79 | - NoAlerts => "No alerts.", "Uyarı yok."; | ||
| 80 | - StateDismissed => "Dismissed", "Yoksayıldı"; | ||
| 81 | StateFixed => "Fixed", "Düzeltildi"; | 76 | StateFixed => "Fixed", "Düzeltildi"; |
| 82 | Dismiss => "Dismiss", "Yoksay"; | 77 | Dismiss => "Dismiss", "Yoksay"; |
| 83 | Reopen => "Reopen", "Yeniden aç"; | 78 | Reopen => "Reopen", "Yeniden aç"; |
| @@ -315,25 +310,6 @@ pub fn watchers_count(lang: Lang, watchers: u64) -> String { | |||
| 315 | } | 310 | } |
| 316 | } | 311 | } |
| 317 | 312 | ||
| 318 | -pub fn new_alerts(lang: Lang, count: u64) -> String { | ||
| 319 | - match lang { | ||
| 320 | - Lang::En if count == 1 => format!("{count} new alert"), | ||
| 321 | - Lang::En => format!("{count} new alerts"), | ||
| 322 | - Lang::Tr => format!("{count} yeni uyarı"), | ||
| 323 | - } | ||
| 324 | -} | ||
| 325 | - | ||
| 326 | -pub fn dependencies_summary(lang: Lang, dependencies: u64, open: usize) -> String { | ||
| 327 | - match lang { | ||
| 328 | - Lang::En => format!( | ||
| 329 | - "{dependencies} dependencies were read from the lockfiles on the default branch. {open} open alerts." | ||
| 330 | - ), | ||
| 331 | - Lang::Tr => format!( | ||
| 332 | - "Varsayılan daldaki kilit dosyalarından {dependencies} bağımlılık okundu. {open} açık uyarı var." | ||
| 333 | - ), | ||
| 334 | - } | ||
| 335 | -} | ||
| 336 | - | ||
| 337 | pub fn description_too_long(lang: Lang, max: usize) -> String { | 313 | pub fn description_too_long(lang: Lang, max: usize) -> String { |
| 338 | match lang { | 314 | match lang { |
| 339 | Lang::En => format!("description must be at most {max} characters"), | 315 | Lang::En => format!("description must be at most {max} characters"), |
| @@ -399,11 +375,4 @@ mod tests { | |||
| 399 | "tahinli tarafından inceleme istendi" | 375 | "tahinli tarafından inceleme istendi" |
| 400 | ); | 376 | ); |
| 401 | } | 377 | } |
| 402 | - | ||
| 403 | - #[test] | ||
| 404 | - fn plural_helpers_match_english() { | ||
| 405 | - assert_eq!(new_alerts(Lang::En, 1), "1 new alert"); | ||
| 406 | - assert_eq!(new_alerts(Lang::En, 2), "2 new alerts"); | ||
| 407 | - assert_eq!(new_alerts(Lang::Tr, 3), "3 yeni uyarı"); | ||
| 408 | - } | ||
| 409 | } | 378 | } |
crates/forge-web-base/src/i18n/push.rsmodified+0 -7
| @@ -44,10 +44,3 @@ pub fn last_delivered_label(lang: Lang) -> &'static str { | |||
| 44 | } | 44 | } |
| 45 | } | 45 | } |
| 46 | 46 | ||
| 47 | -pub fn advisory_alerts(lang: Lang, count: u64) -> String { | ||
| 48 | - match lang { | ||
| 49 | - Lang::En if count == 1 => "1 new security alert".to_owned(), | ||
| 50 | - Lang::En => format!("{count} new security alerts"), | ||
| 51 | - Lang::Tr => format!("{count} yeni güvenlik uyarısı"), | ||
| 52 | - } | ||
| 53 | -} | ||
crates/forge-web-base/src/i18n/server_settings.rsmodified+0 -9
| @@ -138,15 +138,6 @@ pub fn field_tr(key: &str) -> Option<(&'static str, &'static str)> { | |||
| 138 | "E-posta taşıma yöntemi", | 138 | "E-posta taşıma yöntemi", |
| 139 | "smtp e-postayı gönderir, log ise bir dizine yazar. SMTP hesabı E-posta sayfasındadır.", | 139 | "smtp e-postayı gönderir, log ise bir dizine yazar. SMTP hesabı E-posta sayfasındadır.", |
| 140 | ), | 140 | ), |
| 141 | - "advisories.enabled" => ( | ||
| 142 | - "Güvenlik tavsiyeleri", | ||
| 143 | - "OSV dökümlerini indirir ve kilit dosyalarını tarar.", | ||
| 144 | - ), | ||
| 145 | - "advisories.ecosystems" => ( | ||
| 146 | - "Tavsiye ekosistemleri", | ||
| 147 | - "crates.io, npm, Go: bunlardan herhangi biri. Virgülle ayrılmış.", | ||
| 148 | - ), | ||
| 149 | - "advisories.refresh_hours" => ("Tavsiye yenileme (saat)", ""), | ||
| 150 | "self_update.enabled" => ( | 141 | "self_update.enabled" => ( |
| 151 | "Kendini güncelleme", | 142 | "Kendini güncelleme", |
| 152 | "Forge'un kendi deposunda başarılı biten bir çalıştırmanın yapıtını dağıtır.", | 143 | "Forge'un kendi deposunda başarılı biten bir çalıştırmanın yapıtını dağıtır.", |
crates/forge-web-pages/src/pages/mod.rsmodified+0 -1
| @@ -30,7 +30,6 @@ pub mod repo; | |||
| 30 | pub mod repo_ctx; | 30 | pub mod repo_ctx; |
| 31 | pub mod repo_mirrors; | 31 | pub mod repo_mirrors; |
| 32 | pub mod repo_rename; | 32 | pub mod repo_rename; |
| 33 | -pub mod repo_security; | ||
| 34 | pub mod repo_settings; | 33 | pub mod repo_settings; |
| 35 | pub mod repo_settings_live; | 34 | pub mod repo_settings_live; |
| 36 | pub mod repo_side; | 35 | pub mod repo_side; |
crates/forge-web-pages/src/pages/notifications.rsmodified+1 -99
| @@ -3,7 +3,6 @@ use std::collections::HashMap; | |||
| 3 | use forge_core::authz::{Action, authorize}; | 3 | use forge_core::authz::{Action, authorize}; |
| 4 | use forge_core::discussions::{DiscussionNotification, DiscussionReason}; | 4 | use forge_core::discussions::{DiscussionNotification, DiscussionReason}; |
| 5 | use forge_core::store::admin_alerts::AdminNotice; | 5 | use forge_core::store::admin_alerts::AdminNotice; |
| 6 | -use forge_core::store::advisories::AdvisoryNotice; | ||
| 7 | use forge_core::store::transfers::PendingTransfer; | 6 | use forge_core::store::transfers::PendingTransfer; |
| 8 | use forge_core::{IssueState, Notification, Reason, Role, SubState, User, WatchLevel}; | 7 | use forge_core::{IssueState, Notification, Reason, Role, SubState, User, WatchLevel}; |
| 9 | use futures_util::{Stream, StreamExt, future, stream}; | 8 | use futures_util::{Stream, StreamExt, future, stream}; |
| @@ -40,7 +39,6 @@ path_param!(repo); | |||
| 40 | path_param!(number); | 39 | path_param!(number); |
| 41 | path_param!(note); | 40 | path_param!(note); |
| 42 | path_param!(discussion_id); | 41 | path_param!(discussion_id); |
| 43 | -path_param!(advisory_repo_id); | ||
| 44 | path_param!(admin_note); | 42 | path_param!(admin_note); |
| 45 | 43 | ||
| 46 | const ADMIN_GROUP: &str = "admin"; | 44 | const ADMIN_GROUP: &str = "admin"; |
| @@ -97,7 +95,6 @@ pub struct RepoGroup { | |||
| 97 | enum Entry { | 95 | enum Entry { |
| 98 | Issue(Notification), | 96 | Issue(Notification), |
| 99 | Discussion(DiscussionNotification), | 97 | Discussion(DiscussionNotification), |
| 100 | - Advisory(AdvisoryNotice), | ||
| 101 | Admin(AdminNotice), | 98 | Admin(AdminNotice), |
| 102 | } | 99 | } |
| 103 | 100 | ||
| @@ -106,7 +103,6 @@ impl Entry { | |||
| 106 | match self { | 103 | match self { |
| 107 | Entry::Issue(note) => ¬e.repo_id, | 104 | Entry::Issue(note) => ¬e.repo_id, |
| 108 | Entry::Discussion(note) => ¬e.repo_id, | 105 | Entry::Discussion(note) => ¬e.repo_id, |
| 109 | - Entry::Advisory(note) => ¬e.repo_id, | ||
| 110 | Entry::Admin(_) => ADMIN_GROUP, | 106 | Entry::Admin(_) => ADMIN_GROUP, |
| 111 | } | 107 | } |
| 112 | } | 108 | } |
| @@ -115,7 +111,6 @@ impl Entry { | |||
| 115 | match self { | 111 | match self { |
| 116 | Entry::Issue(note) => ¬e.repo_owner, | 112 | Entry::Issue(note) => ¬e.repo_owner, |
| 117 | Entry::Discussion(note) => ¬e.repo_owner, | 113 | Entry::Discussion(note) => ¬e.repo_owner, |
| 118 | - Entry::Advisory(note) => ¬e.repo_owner, | ||
| 119 | Entry::Admin(_) => "", | 114 | Entry::Admin(_) => "", |
| 120 | } | 115 | } |
| 121 | } | 116 | } |
| @@ -124,7 +119,6 @@ impl Entry { | |||
| 124 | match self { | 119 | match self { |
| 125 | Entry::Issue(note) => ¬e.repo_name, | 120 | Entry::Issue(note) => ¬e.repo_name, |
| 126 | Entry::Discussion(note) => ¬e.repo_name, | 121 | Entry::Discussion(note) => ¬e.repo_name, |
| 127 | - Entry::Advisory(note) => ¬e.repo_name, | ||
| 128 | Entry::Admin(_) => "", | 122 | Entry::Admin(_) => "", |
| 129 | } | 123 | } |
| 130 | } | 124 | } |
| @@ -133,7 +127,6 @@ impl Entry { | |||
| 133 | match self { | 127 | match self { |
| 134 | Entry::Issue(note) => ¬e.updated_at, | 128 | Entry::Issue(note) => ¬e.updated_at, |
| 135 | Entry::Discussion(note) => ¬e.updated_at, | 129 | Entry::Discussion(note) => ¬e.updated_at, |
| 136 | - Entry::Advisory(note) => ¬e.updated_at, | ||
| 137 | Entry::Admin(note) => ¬e.updated_at, | 130 | Entry::Admin(note) => ¬e.updated_at, |
| 138 | } | 131 | } |
| 139 | } | 132 | } |
| @@ -222,31 +215,6 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64) | |||
| 222 | } | 215 | } |
| 223 | } | 216 | } |
| 224 | 217 | ||
| 225 | -fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowView { | ||
| 226 | - let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | ||
| 227 | - let count = note.new_alerts; | ||
| 228 | - RowView { | ||
| 229 | - item_class: item_class(note.unread), | ||
| 230 | - icon_class: "notif-icon advisory", | ||
| 231 | - kind_label: g::t(lang, K::KindSecurityAlerts), | ||
| 232 | - open_href: format!( | ||
| 233 | - "/notifications/advisories/{}/open", | ||
| 234 | - percent_encode(¬e.repo_id) | ||
| 235 | - ), | ||
| 236 | - read_action: format!( | ||
| 237 | - "/notifications/advisories/{}/read", | ||
| 238 | - percent_encode(¬e.repo_id) | ||
| 239 | - ), | ||
| 240 | - title_line: format!("{}/{}", note.repo_owner, note.repo_name), | ||
| 241 | - reason: g::t(lang, K::ReasonSecurity), | ||
| 242 | - activity: g::new_alerts(lang, count), | ||
| 243 | - iso, | ||
| 244 | - absolute, | ||
| 245 | - relative, | ||
| 246 | - unread: note.unread, | ||
| 247 | - } | ||
| 248 | -} | ||
| 249 | - | ||
| 250 | fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView { | 218 | fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView { |
| 251 | let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | 219 | let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); |
| 252 | RowView { | 220 | RowView { |
| @@ -303,9 +271,7 @@ async fn entry_visible( | |||
| 303 | visible | 271 | visible |
| 304 | } | 272 | } |
| 305 | }; | 273 | }; |
| 306 | - Ok(visible | 274 | + Ok(visible) |
| 307 | - && (!matches!(entry, Entry::Advisory(_)) | ||
| 308 | - || repo_allows(state, user, repo_id, Action::Write).await?)) | ||
| 309 | } | 275 | } |
| 310 | #[page("/notifications")] | 276 | #[page("/notifications")] |
| 311 | async fn inbox(cx: &Cx) -> Result<impl View> { | 277 | async fn inbox(cx: &Cx) -> Result<impl View> { |
| @@ -327,10 +293,6 @@ async fn inbox(cx: &Cx) -> Result<impl View> { | |||
| 327 | .store | 293 | .store |
| 328 | .list_discussion_notifications(&user.id, !all, before.as_deref(), PAGE_SIZE) | 294 | .list_discussion_notifications(&user.id, !all, before.as_deref(), PAGE_SIZE) |
| 329 | .await?; | 295 | .await?; |
| 330 | - let advisory_rows = state | ||
| 331 | - .store | ||
| 332 | - .list_advisory_notifications(&user.id, !all, before.as_deref(), PAGE_SIZE) | ||
| 333 | - .await?; | ||
| 334 | let admin_rows = if user.is_admin { | 296 | let admin_rows = if user.is_admin { |
| 335 | state | 297 | state |
| 336 | .store | 298 | .store |
| @@ -341,13 +303,11 @@ async fn inbox(cx: &Cx) -> Result<impl View> { | |||
| 341 | }; | 303 | }; |
| 342 | let lists_full = rows.len() == PAGE_SIZE as usize | 304 | let lists_full = rows.len() == PAGE_SIZE as usize |
| 343 | || discussion_rows.len() == PAGE_SIZE as usize | 305 | || discussion_rows.len() == PAGE_SIZE as usize |
| 344 | - || advisory_rows.len() == PAGE_SIZE as usize | ||
| 345 | || admin_rows.len() == PAGE_SIZE as usize; | 306 | || admin_rows.len() == PAGE_SIZE as usize; |
| 346 | let mut merged: Vec<Entry> = rows | 307 | let mut merged: Vec<Entry> = rows |
| 347 | .into_iter() | 308 | .into_iter() |
| 348 | .map(Entry::Issue) | 309 | .map(Entry::Issue) |
| 349 | .chain(discussion_rows.into_iter().map(Entry::Discussion)) | 310 | .chain(discussion_rows.into_iter().map(Entry::Discussion)) |
| 350 | - .chain(advisory_rows.into_iter().map(Entry::Advisory)) | ||
| 351 | .chain(admin_rows.into_iter().map(Entry::Admin)) | 311 | .chain(admin_rows.into_iter().map(Entry::Admin)) |
| 352 | .collect(); | 312 | .collect(); |
| 353 | merged.sort_by(|a, b| b.updated_at().cmp(a.updated_at())); | 313 | merged.sort_by(|a, b| b.updated_at().cmp(a.updated_at())); |
| @@ -400,7 +360,6 @@ async fn inbox(cx: &Cx) -> Result<impl View> { | |||
| 400 | let row = match entry { | 360 | let row = match entry { |
| 401 | Entry::Issue(note) => issue_row(lang, ¬e, &tz, now), | 361 | Entry::Issue(note) => issue_row(lang, ¬e, &tz, now), |
| 402 | Entry::Discussion(note) => discussion_row(lang, ¬e, &tz, now), | 362 | Entry::Discussion(note) => discussion_row(lang, ¬e, &tz, now), |
| 403 | - Entry::Advisory(note) => advisory_row(lang, ¬e, &tz, now), | ||
| 404 | Entry::Admin(note) => admin_row(lang, ¬e, &tz, now), | 363 | Entry::Admin(note) => admin_row(lang, ¬e, &tz, now), |
| 405 | }; | 364 | }; |
| 406 | groups[slot].rows.push(row); | 365 | groups[slot].rows.push(row); |
| @@ -414,12 +373,6 @@ async fn inbox(cx: &Cx) -> Result<impl View> { | |||
| 414 | .mark_discussion_notification_read(&user.id, ¬e.discussion_id) | 373 | .mark_discussion_notification_read(&user.id, ¬e.discussion_id) |
| 415 | .await?; | 374 | .await?; |
| 416 | } | 375 | } |
| 417 | - Entry::Advisory(note) => { | ||
| 418 | - state | ||
| 419 | - .store | ||
| 420 | - .mark_advisory_notification_read(&user.id, ¬e.repo_id) | ||
| 421 | - .await?; | ||
| 422 | - } | ||
| 423 | Entry::Admin(note) => { | 376 | Entry::Admin(note) => { |
| 424 | state | 377 | state |
| 425 | .store | 378 | .store |
| @@ -479,16 +432,6 @@ async fn inbox_fingerprint(state: &AppState, user: &User, all: bool) -> Result<S | |||
| 479 | note.discussion_id, note.unread, note.updated_at, note.title | 432 | note.discussion_id, note.unread, note.updated_at, note.title |
| 480 | )); | 433 | )); |
| 481 | } | 434 | } |
| 482 | - for note in state | ||
| 483 | - .store | ||
| 484 | - .list_advisory_notifications(&user.id, unread_only, before, PAGE_SIZE) | ||
| 485 | - .await? | ||
| 486 | - { | ||
| 487 | - lines.push(format!( | ||
| 488 | - "advisory {} {} {}", | ||
| 489 | - note.repo_id, note.unread, note.updated_at | ||
| 490 | - )); | ||
| 491 | - } | ||
| 492 | if user.is_admin { | 435 | if user.is_admin { |
| 493 | for note in state | 436 | for note in state |
| 494 | .store | 437 | .store |
| @@ -583,43 +526,6 @@ async fn read_discussion_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Re | |||
| 583 | Ok(see_other(back(cx))) | 526 | Ok(see_other(back(cx))) |
| 584 | } | 527 | } |
| 585 | 528 | ||
| 586 | -#[route(GET "/notifications/advisories/{advisory_repo_id}/open")] | ||
| 587 | -async fn open_advisory_notification(cx: &Cx) -> Result<SeeOther> { | ||
| 588 | - let (user, _) = require_user(cx).await?; | ||
| 589 | - let state = context::<AppState>(cx); | ||
| 590 | - let repo_id = advisory_repo_id(cx); | ||
| 591 | - let Some(notice) = state.store.advisory_notification(&user.id, repo_id).await? else { | ||
| 592 | - return Err(not_found().into()); | ||
| 593 | - }; | ||
| 594 | - state | ||
| 595 | - .store | ||
| 596 | - .mark_advisory_notification_read(&user.id, repo_id) | ||
| 597 | - .await?; | ||
| 598 | - publish_unread(state, &user.id).await; | ||
| 599 | - if !repo_allows(state, &user, repo_id, Action::Write).await? { | ||
| 600 | - return Err(not_found().into()); | ||
| 601 | - } | ||
| 602 | - Ok(see_other(repo_href( | ||
| 603 | - ¬ice.repo_owner, | ||
| 604 | - ¬ice.repo_name, | ||
| 605 | - "security", | ||
| 606 | - "", | ||
| 607 | - ))) | ||
| 608 | -} | ||
| 609 | - | ||
| 610 | -#[route(POST "/notifications/advisories/{advisory_repo_id}/read")] | ||
| 611 | -async fn read_advisory_notification(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 612 | - let (user, _) = require_csrf(cx, &form.csrf).await?; | ||
| 613 | - let state = context::<AppState>(cx); | ||
| 614 | - let repo_id = advisory_repo_id(cx); | ||
| 615 | - state | ||
| 616 | - .store | ||
| 617 | - .mark_advisory_notification_read(&user.id, repo_id) | ||
| 618 | - .await?; | ||
| 619 | - publish_unread(state, &user.id).await; | ||
| 620 | - Ok(see_other(back(cx))) | ||
| 621 | -} | ||
| 622 | - | ||
| 623 | #[route(GET "/notifications/admin/{admin_note}/open")] | 529 | #[route(GET "/notifications/admin/{admin_note}/open")] |
| 624 | async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> { | 530 | async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> { |
| 625 | let (user, _) = require_user(cx).await?; | 531 | let (user, _) = require_user(cx).await?; |
| @@ -672,10 +578,6 @@ async fn mark_all_read(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> | |||
| 672 | .store | 578 | .store |
| 673 | .mark_all_discussion_notifications_read(&user.id, repo_id) | 579 | .mark_all_discussion_notifications_read(&user.id, repo_id) |
| 674 | .await?; | 580 | .await?; |
| 675 | - state | ||
| 676 | - .store | ||
| 677 | - .mark_all_advisory_notifications_read(&user.id, repo_id) | ||
| 678 | - .await?; | ||
| 679 | publish_unread(state, &user.id).await; | 581 | publish_unread(state, &user.id).await; |
| 680 | Ok(see_other(back(cx))) | 582 | Ok(see_other(back(cx))) |
| 681 | } | 583 | } |
crates/forge-web-pages/src/pages/repo.rsmodified+1 -2
| @@ -67,7 +67,6 @@ pub async fn repo_head( | |||
| 67 | mirror, | 67 | mirror, |
| 68 | discussions, | 68 | discussions, |
| 69 | wiki, | 69 | wiki, |
| 70 | - security, | ||
| 71 | lang, | 70 | lang, |
| 72 | clone, | 71 | clone, |
| 73 | .. | 72 | .. |
| @@ -164,7 +163,7 @@ pub async fn repo_head( | |||
| 164 | (child) | 163 | (child) |
| 165 | </div> | 164 | </div> |
| 166 | head_sub(parts: parts, pips: pips, keep: true) | 165 | head_sub(parts: parts, pips: pips, keep: true) |
| 167 | - repo_tabs(owner: owner.clone(), repo: name.clone(), default_branch: default_branch.clone(), active: active.clone(), can_admin: can_admin, lang: lang, open_issues: Some(open_issues), open_pulls: Some(open_pulls), discussions: discussions, wiki: wiki, security: security) | 166 | + repo_tabs(owner: owner.clone(), repo: name.clone(), default_branch: default_branch.clone(), active: active.clone(), can_admin: can_admin, lang: lang, open_issues: Some(open_issues), open_pulls: Some(open_pulls), discussions: discussions, wiki: wiki) |
| 168 | </section> | 167 | </section> |
| 169 | if archived { | 168 | if archived { |
| 170 | <p class="state" role="status">(g::t(lang, K::ArchivedNotice))</p> | 169 | <p class="state" role="status">(g::t(lang, K::ArchivedNotice))</p> |
crates/forge-web-pages/src/pages/repo_ctx.rsmodified+0 -3
| @@ -55,7 +55,6 @@ pub struct RepoHead { | |||
| 55 | pub mirror: Option<MirrorSource>, | 55 | pub mirror: Option<MirrorSource>, |
| 56 | pub discussions: bool, | 56 | pub discussions: bool, |
| 57 | pub wiki: bool, | 57 | pub wiki: bool, |
| 58 | - pub security: bool, | ||
| 59 | pub clone: CloneLinks, | 58 | pub clone: CloneLinks, |
| 60 | } | 59 | } |
| 61 | 60 | ||
| @@ -168,7 +167,6 @@ impl RepoCtx { | |||
| 168 | let forks = fork_count(state, &self.repo.id).await?; | 167 | let forks = fork_count(state, &self.repo.id).await?; |
| 169 | let discussions = state.store.discussions_enabled(&self.repo.id).await?; | 168 | let discussions = state.store.discussions_enabled(&self.repo.id).await?; |
| 170 | let wiki = state.store.wiki_enabled(&self.repo.id).await?; | 169 | let wiki = state.store.wiki_enabled(&self.repo.id).await?; |
| 171 | - let security = state.config.advisories.enabled && self.can_write(); | ||
| 172 | let mirror = state | 170 | let mirror = state |
| 173 | .store | 171 | .store |
| 174 | .pull_mirror(&self.repo.id) | 172 | .pull_mirror(&self.repo.id) |
| @@ -219,7 +217,6 @@ impl RepoCtx { | |||
| 219 | }, | 217 | }, |
| 220 | discussions, | 218 | discussions, |
| 221 | wiki, | 219 | wiki, |
| 222 | - security, | ||
| 223 | }) | 220 | }) |
| 224 | } | 221 | } |
| 225 | 222 | ||
crates/forge-web-pages/src/pages/repo_security.rsdeleted+0 -248
| @@ -1,248 +0,0 @@ | |||
| 1 | -use forge_core::AuditAction; | ||
| 2 | -use forge_core::store::advisories::{Alert, AlertKey, AlertState}; | ||
| 3 | -use serde::Deserialize; | ||
| 4 | -use serde_json::json; | ||
| 5 | -use topcoat::Result; | ||
| 6 | -use topcoat::context::{Cx, context}; | ||
| 7 | -use topcoat::router::content::Form; | ||
| 8 | -use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; | ||
| 9 | -use topcoat::router::{page, path_param, route}; | ||
| 10 | -use topcoat::view::{View, component, view}; | ||
| 11 | - | ||
| 12 | -use crate::audit::{self, Actor, Target}; | ||
| 13 | -use crate::auth::{require_csrf, require_user}; | ||
| 14 | -use crate::i18n::misc::{self as g, K}; | ||
| 15 | -use crate::i18n::{self, Key, Lang}; | ||
| 16 | -use crate::pages::repo::repo_head; | ||
| 17 | -use crate::pages::repo_ctx::{RepoHead, load_repo}; | ||
| 18 | -use crate::pages::repo_settings_live::security_live_url; | ||
| 19 | -use crate::state::AppState; | ||
| 20 | -use crate::views::parts::post_act; | ||
| 21 | -use crate::views::{rel_time, shell}; | ||
| 22 | - | ||
| 23 | -path_param!(owner); | ||
| 24 | -path_param!(repo); | ||
| 25 | - | ||
| 26 | -#[derive(Deserialize)] | ||
| 27 | -struct AlertForm { | ||
| 28 | - #[serde(default)] | ||
| 29 | - csrf: String, | ||
| 30 | - #[serde(default)] | ||
| 31 | - advisory: String, | ||
| 32 | - #[serde(default)] | ||
| 33 | - ecosystem: String, | ||
| 34 | - #[serde(default)] | ||
| 35 | - package: String, | ||
| 36 | - #[serde(default)] | ||
| 37 | - version: String, | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -struct AlertRow { | ||
| 41 | - advisory: String, | ||
| 42 | - osv_href: String, | ||
| 43 | - package: String, | ||
| 44 | - version: String, | ||
| 45 | - severity: String, | ||
| 46 | - summary: String, | ||
| 47 | - state_text: &'static str, | ||
| 48 | - state_class: &'static str, | ||
| 49 | - created_at: String, | ||
| 50 | - open: bool, | ||
| 51 | - dismissed: bool, | ||
| 52 | - dismiss_action: String, | ||
| 53 | - reopen_action: String, | ||
| 54 | - fields: Vec<(String, String)>, | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -fn security_href(title: &str) -> String { | ||
| 58 | - format!("/{title}/security") | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -fn row_of(alert: &Alert, title: &str, lang: Lang) -> AlertRow { | ||
| 62 | - let (state_text, state_class) = match alert.state { | ||
| 63 | - AlertState::Open => ( | ||
| 64 | - crate::i18n::t(lang, crate::i18n::Key::StateOpen), | ||
| 65 | - "hook-state fail", | ||
| 66 | - ), | ||
| 67 | - AlertState::Dismissed => (g::t(lang, K::StateDismissed), "hook-state"), | ||
| 68 | - AlertState::Fixed => (g::t(lang, K::StateFixed), "hook-state ok"), | ||
| 69 | - }; | ||
| 70 | - let key = &alert.key; | ||
| 71 | - let base = security_href(title); | ||
| 72 | - AlertRow { | ||
| 73 | - advisory: key.advisory_id.clone(), | ||
| 74 | - osv_href: format!( | ||
| 75 | - "https://osv.dev/vulnerability/{}", | ||
| 76 | - key.advisory_id.replace(['/', '?', '#'], "") | ||
| 77 | - ), | ||
| 78 | - package: key.package.clone(), | ||
| 79 | - version: key.version.clone(), | ||
| 80 | - severity: alert.severity.clone(), | ||
| 81 | - summary: alert.summary.clone(), | ||
| 82 | - state_text, | ||
| 83 | - state_class, | ||
| 84 | - created_at: alert.created_at.clone(), | ||
| 85 | - open: alert.state == AlertState::Open, | ||
| 86 | - dismissed: alert.state == AlertState::Dismissed, | ||
| 87 | - dismiss_action: format!("{base}/dismiss"), | ||
| 88 | - reopen_action: format!("{base}/reopen"), | ||
| 89 | - fields: vec![ | ||
| 90 | - ("advisory".to_owned(), key.advisory_id.clone()), | ||
| 91 | - ("ecosystem".to_owned(), key.ecosystem.clone()), | ||
| 92 | - ("package".to_owned(), key.package.clone()), | ||
| 93 | - ("version".to_owned(), key.version.clone()), | ||
| 94 | - ], | ||
| 95 | - } | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -#[component] | ||
| 99 | -async fn security_body( | ||
| 100 | - cx: &Cx, | ||
| 101 | - lang: Lang, | ||
| 102 | - head: RepoHead, | ||
| 103 | - enabled: bool, | ||
| 104 | - dependencies: u64, | ||
| 105 | - csrf: String, | ||
| 106 | - rows: Vec<AlertRow>, | ||
| 107 | -) -> Result<impl View> { | ||
| 108 | - let open_count = rows.iter().filter(|r| r.open).count(); | ||
| 109 | - Ok(view! { | ||
| 110 | - repo_head(head: head, title: Some(i18n::t(lang, Key::Security).to_owned())) | ||
| 111 | - <div class="sheet"> | ||
| 112 | - <section class="sec"> | ||
| 113 | - <h2>(i18n::t(lang, Key::Security))</h2> | ||
| 114 | - if !enabled { | ||
| 115 | - <p class="state">(g::t(lang, K::SecurityOff))</p> | ||
| 116 | - } else { | ||
| 117 | - <p class="state">(g::dependencies_summary(lang, dependencies, open_count))</p> | ||
| 118 | - } | ||
| 119 | - if rows.is_empty() { | ||
| 120 | - <p class="state">(g::t(lang, K::NoAlerts))</p> | ||
| 121 | - } | ||
| 122 | - <div> | ||
| 123 | - for row in rows.iter() { | ||
| 124 | - <div class="line" data-kb-row=""> | ||
| 125 | - <span class="name" title=(row.summary.as_str())>(row.advisory.as_str())</span> | ||
| 126 | - <span class="val"><code>(row.package.as_str())</code> " " <code>(row.version.as_str())</code> " · " (row.severity.as_str()) " · " <span class=(row.state_class)>(row.state_text)</span> " · " rel_time(lang: lang, stamp: row.created_at.as_str())</span> | ||
| 127 | - <a class="act" href=(row.osv_href.as_str()) rel="noopener noreferrer">(crate::i18n::s(lang, "osv.dev", "osv.dev"))</a> | ||
| 128 | - if row.open { | ||
| 129 | - post_act(label: g::t(lang, K::Dismiss), action: row.dismiss_action.as_str(), csrf: csrf.as_str(), fields: row.fields.clone()) | ||
| 130 | - } | ||
| 131 | - if row.dismissed { | ||
| 132 | - post_act(label: g::t(lang, K::Reopen), action: row.reopen_action.as_str(), csrf: csrf.as_str(), fields: row.fields.clone()) | ||
| 133 | - } | ||
| 134 | - </div> | ||
| 135 | - } | ||
| 136 | - </div> | ||
| 137 | - </section> | ||
| 138 | - </div> | ||
| 139 | - }) | ||
| 140 | -} | ||
| 141 | - | ||
| 142 | -#[page("/{owner}/{repo}/security")] | ||
| 143 | -async fn security_page(cx: &Cx) -> Result<impl View> { | ||
| 144 | - let owner = owner(cx); | ||
| 145 | - let name = repo(cx); | ||
| 146 | - let ctx = load_repo(cx, owner, name).await?; | ||
| 147 | - let (user, session) = require_user(cx).await?; | ||
| 148 | - if !ctx.can_write() { | ||
| 149 | - return Err(not_found().into()); | ||
| 150 | - } | ||
| 151 | - let lang = i18n::lang(cx, Some(&user)); | ||
| 152 | - let state = context::<AppState>(cx); | ||
| 153 | - let title = ctx.title(); | ||
| 154 | - let mut head = ctx.head(state, "security").await?; | ||
| 155 | - head.live = security_live_url(&ctx.repo.owner_name, &ctx.repo.name); | ||
| 156 | - let dependencies = state.store.dependency_count(&ctx.repo.id).await?; | ||
| 157 | - let rows: Vec<AlertRow> = state | ||
| 158 | - .store | ||
| 159 | - .list_alerts(&ctx.repo.id) | ||
| 160 | - .await? | ||
| 161 | - .iter() | ||
| 162 | - .map(|alert| row_of(alert, &title, lang)) | ||
| 163 | - .collect(); | ||
| 164 | - let csrf = session.csrf_token.clone(); | ||
| 165 | - let enabled = state.config.advisories.enabled; | ||
| 166 | - let page_title = format!("{title} \u{b7} {}", i18n::t(lang, Key::Security)); | ||
| 167 | - Ok(view! { | ||
| 168 | - shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | ||
| 169 | - security_body(lang: lang, head: head, enabled: enabled, dependencies: dependencies, | ||
| 170 | - csrf: csrf, rows: rows)) | ||
| 171 | - }) | ||
| 172 | -} | ||
| 173 | - | ||
| 174 | -async fn change_alert( | ||
| 175 | - cx: &Cx, | ||
| 176 | - form: AlertForm, | ||
| 177 | - from: AlertState, | ||
| 178 | - to: AlertState, | ||
| 179 | - action: AuditAction, | ||
| 180 | -) -> Result<SeeOther> { | ||
| 181 | - let owner = owner(cx); | ||
| 182 | - let name = repo(cx); | ||
| 183 | - let ctx = load_repo(cx, owner, name).await?; | ||
| 184 | - let (user, _) = require_csrf(cx, &form.csrf).await?; | ||
| 185 | - if !ctx.can_write() { | ||
| 186 | - return Err(not_found().into()); | ||
| 187 | - } | ||
| 188 | - if ctx.repo.archived { | ||
| 189 | - return Err(forbidden().into()); | ||
| 190 | - } | ||
| 191 | - let state = context::<AppState>(cx); | ||
| 192 | - let key = AlertKey { | ||
| 193 | - advisory_id: form.advisory.clone(), | ||
| 194 | - ecosystem: form.ecosystem.clone(), | ||
| 195 | - package: form.package.clone(), | ||
| 196 | - version: form.version.clone(), | ||
| 197 | - }; | ||
| 198 | - let title = ctx.title(); | ||
| 199 | - let changed = state | ||
| 200 | - .store | ||
| 201 | - .set_alert_state(&ctx.repo.id, &key, from, to) | ||
| 202 | - .await?; | ||
| 203 | - if changed { | ||
| 204 | - audit::record( | ||
| 205 | - &state.store, | ||
| 206 | - Some(cx), | ||
| 207 | - Actor::User(&user), | ||
| 208 | - action, | ||
| 209 | - Target { | ||
| 210 | - kind: "repo", | ||
| 211 | - id: &ctx.repo.id, | ||
| 212 | - name: &title, | ||
| 213 | - }, | ||
| 214 | - json!({ | ||
| 215 | - "advisory": key.advisory_id, | ||
| 216 | - "ecosystem": key.ecosystem, | ||
| 217 | - "package": key.package, | ||
| 218 | - "version": key.version, | ||
| 219 | - }), | ||
| 220 | - ) | ||
| 221 | - .await; | ||
| 222 | - } | ||
| 223 | - Ok(see_other(security_href(&title))) | ||
| 224 | -} | ||
| 225 | - | ||
| 226 | -#[route(POST "/{owner}/{repo}/security/dismiss")] | ||
| 227 | -async fn alert_dismiss(cx: &Cx, Form(form): Form<AlertForm>) -> Result<SeeOther> { | ||
| 228 | - change_alert( | ||
| 229 | - cx, | ||
| 230 | - form, | ||
| 231 | - AlertState::Open, | ||
| 232 | - AlertState::Dismissed, | ||
| 233 | - AuditAction::AdvisoryAlertDismissed, | ||
| 234 | - ) | ||
| 235 | - .await | ||
| 236 | -} | ||
| 237 | - | ||
| 238 | -#[route(POST "/{owner}/{repo}/security/reopen")] | ||
| 239 | -async fn alert_reopen(cx: &Cx, Form(form): Form<AlertForm>) -> Result<SeeOther> { | ||
| 240 | - change_alert( | ||
| 241 | - cx, | ||
| 242 | - form, | ||
| 243 | - AlertState::Dismissed, | ||
| 244 | - AlertState::Open, | ||
| 245 | - AuditAction::AdvisoryAlertReopened, | ||
| 246 | - ) | ||
| 247 | - .await | ||
| 248 | -} | ||
crates/forge-web-pages/src/pages/repo_settings_live.rsmodified+0 -13
| @@ -4,7 +4,6 @@ use topcoat::router::error::forbidden; | |||
| 4 | use topcoat::router::response::Response; | 4 | use topcoat::router::response::Response; |
| 5 | use topcoat::router::{path_param, route}; | 5 | use topcoat::router::{path_param, route}; |
| 6 | 6 | ||
| 7 | -use crate::auth::require_user; | ||
| 8 | use crate::live::{Topic, stream_wakes}; | 7 | use crate::live::{Topic, stream_wakes}; |
| 9 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 8 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| 10 | use crate::state::AppState; | 9 | use crate::state::AppState; |
| @@ -16,10 +15,6 @@ pub fn settings_live_url(owner: &str, repo: &str) -> String { | |||
| 16 | format!("/{owner}/{repo}/settings/live") | 15 | format!("/{owner}/{repo}/settings/live") |
| 17 | } | 16 | } |
| 18 | 17 | ||
| 19 | -pub fn security_live_url(owner: &str, repo: &str) -> String { | ||
| 20 | - format!("/{owner}/{repo}/security/live") | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | pub async fn settings_head(ctx: &RepoCtx, state: &AppState) -> Result<RepoHead> { | 18 | pub async fn settings_head(ctx: &RepoCtx, state: &AppState) -> Result<RepoHead> { |
| 24 | let mut head = ctx.head(state, "settings").await?; | 19 | let mut head = ctx.head(state, "settings").await?; |
| 25 | head.live = settings_live_url(&ctx.repo.owner_name, &ctx.repo.name); | 20 | head.live = settings_live_url(&ctx.repo.owner_name, &ctx.repo.name); |
| @@ -39,11 +34,3 @@ async fn settings_live(cx: &Cx) -> Result<Response> { | |||
| 39 | ]; | 34 | ]; |
| 40 | stream_wakes(cx, &state.live, &topics) | 35 | stream_wakes(cx, &state.live, &topics) |
| 41 | } | 36 | } |
| 42 | - | ||
| 43 | -#[route(GET "/{owner}/{repo}/security/live")] | ||
| 44 | -async fn security_live(cx: &Cx) -> Result<Response> { | ||
| 45 | - let ctx = load_repo(cx, owner(cx), repo(cx)).await?; | ||
| 46 | - require_user(cx).await?; | ||
| 47 | - let state = context::<AppState>(cx); | ||
| 48 | - stream_wakes(cx, &state.live, &[Topic::RepoSettings(ctx.repo.id.clone())]) | ||
| 49 | -} | ||
crates/forge-web-repo/src/pages/mod.rsmodified+0 -2
| @@ -50,5 +50,3 @@ pub mod repo_secrets; | |||
| 50 | mod repo_settings_live_tests; | 50 | mod repo_settings_live_tests; |
| 51 | pub mod repo_webhooks; | 51 | pub mod repo_webhooks; |
| 52 | pub mod review_requests; | 52 | pub mod review_requests; |
| 53 | -#[cfg(test)] | ||
| 54 | -mod security_tab_tests; | ||
crates/forge-web-repo/src/pages/repo_settings_live_tests.rsmodified+0 -7
| @@ -95,13 +95,6 @@ async fn the_streams_check_who_may_open_them() { | |||
| 95 | assert_eq!(reader.status().as_u16(), 403, "settings: reader"); | 95 | assert_eq!(reader.status().as_u16(), 403, "settings: reader"); |
| 96 | let anonymous = get(&site, "/owner/proj/settings/live", None).await; | 96 | let anonymous = get(&site, "/owner/proj/settings/live", None).await; |
| 97 | assert_ne!(anonymous.status().as_u16(), 200, "settings: anonymous"); | 97 | assert_ne!(anonymous.status().as_u16(), 200, "settings: anonymous"); |
| 98 | - | ||
| 99 | - for path in ["/owner/proj/security/live"] { | ||
| 100 | - let reader = get(&site, path, Some(&reader_cookie)).await; | ||
| 101 | - assert_eq!(reader.status().as_u16(), 200, "{path}: reader"); | ||
| 102 | - let anonymous = get(&site, path, None).await; | ||
| 103 | - assert_ne!(anonymous.status().as_u16(), 200, "{path}: anonymous"); | ||
| 104 | - } | ||
| 105 | } | 98 | } |
| 106 | 99 | ||
| 107 | #[tokio::test] | 100 | #[tokio::test] |
crates/forge-web-repo/src/pages/security_tab_tests.rsdeleted+0 -140
| @@ -1,140 +0,0 @@ | |||
| 1 | -use std::sync::Arc; | ||
| 2 | - | ||
| 3 | -use forge_core::{Role, Store, Visibility}; | ||
| 4 | -use topcoat::router::Router; | ||
| 5 | - | ||
| 6 | -use crate::auth::SESSION_COOKIE; | ||
| 7 | -use crate::test_support::fixture::{Reply, send}; | ||
| 8 | - | ||
| 9 | -const SECURITY_TAB: &str = "href=\"/owner/proj/security\""; | ||
| 10 | -const CSRF: &str = "security-tab-test-csrf"; | ||
| 11 | - | ||
| 12 | -struct Site { | ||
| 13 | - router: Router, | ||
| 14 | - store: Store, | ||
| 15 | - _dir: tempfile::TempDir, | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -async fn site(advisories: bool) -> Site { | ||
| 19 | - let dir = tempfile::tempdir().expect("tempdir"); | ||
| 20 | - let mut state = crate::test_support::test_state(dir.path()).await; | ||
| 21 | - let mut config = crate::test_support::test_config(dir.path()); | ||
| 22 | - config.advisories.enabled = advisories; | ||
| 23 | - state.config = Arc::new(config); | ||
| 24 | - let store = state.store.clone(); | ||
| 25 | - let router = crate::test_support::app_router(state); | ||
| 26 | - Site { | ||
| 27 | - router, | ||
| 28 | - store, | ||
| 29 | - _dir: dir, | ||
| 30 | - } | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { | ||
| 34 | - crate::test_support::create_session(store, user_id, token, CSRF).await; | ||
| 35 | - format!("__Host-{SESSION_COOKIE}={token}") | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -async fn fixture(site: &Site) -> (String, String) { | ||
| 39 | - let owner = site | ||
| 40 | - .store | ||
| 41 | - .create_user("owner", None, "unused", false) | ||
| 42 | - .await | ||
| 43 | - .unwrap(); | ||
| 44 | - site.store | ||
| 45 | - .create_repo(&owner.id, "proj", "", Visibility::Public, "main") | ||
| 46 | - .await | ||
| 47 | - .unwrap(); | ||
| 48 | - let owner_cookie = sign_in(&site.store, &owner.id, "owner-token").await; | ||
| 49 | - let reader = site | ||
| 50 | - .store | ||
| 51 | - .create_user("reader", None, "unused", false) | ||
| 52 | - .await | ||
| 53 | - .unwrap(); | ||
| 54 | - let reader_cookie = sign_in(&site.store, &reader.id, "reader-token").await; | ||
| 55 | - (owner_cookie, reader_cookie) | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -#[tokio::test] | ||
| 59 | -async fn security_tab_follows_the_role_while_advisories_are_on() { | ||
| 60 | - let site = site(true).await; | ||
| 61 | - let (owner_cookie, reader_cookie) = fixture(&site).await; | ||
| 62 | - | ||
| 63 | - let Reply { status, body, .. } = send( | ||
| 64 | - &site.router, | ||
| 65 | - "GET", | ||
| 66 | - "/owner/proj/issues", | ||
| 67 | - Some(&owner_cookie), | ||
| 68 | - None, | ||
| 69 | - ) | ||
| 70 | - .await; | ||
| 71 | - assert_eq!(status, 200, "owner page"); | ||
| 72 | - assert!( | ||
| 73 | - body.contains(SECURITY_TAB), | ||
| 74 | - "owner should see the Security tab" | ||
| 75 | - ); | ||
| 76 | - assert!(body.contains("/owner/proj/security")); | ||
| 77 | - | ||
| 78 | - let writer = site | ||
| 79 | - .store | ||
| 80 | - .create_user("writer", None, "unused", false) | ||
| 81 | - .await | ||
| 82 | - .unwrap(); | ||
| 83 | - let repo = site | ||
| 84 | - .store | ||
| 85 | - .repo_by_owner_and_name("owner", "proj") | ||
| 86 | - .await | ||
| 87 | - .unwrap() | ||
| 88 | - .expect("repo"); | ||
| 89 | - site.store | ||
| 90 | - .set_collaborator(&repo.id, &writer.id, Role::Write) | ||
| 91 | - .await | ||
| 92 | - .unwrap(); | ||
| 93 | - let writer_cookie = sign_in(&site.store, &writer.id, "writer-token").await; | ||
| 94 | - let Reply { status, body, .. } = send( | ||
| 95 | - &site.router, | ||
| 96 | - "GET", | ||
| 97 | - "/owner/proj/issues", | ||
| 98 | - Some(&writer_cookie), | ||
| 99 | - None, | ||
| 100 | - ) | ||
| 101 | - .await; | ||
| 102 | - assert_eq!(status, 200, "writer page"); | ||
| 103 | - assert!( | ||
| 104 | - body.contains(SECURITY_TAB), | ||
| 105 | - "a Write collaborator should see the tab" | ||
| 106 | - ); | ||
| 107 | - | ||
| 108 | - let Reply { status, body, .. } = send( | ||
| 109 | - &site.router, | ||
| 110 | - "GET", | ||
| 111 | - "/owner/proj/issues", | ||
| 112 | - Some(&reader_cookie), | ||
| 113 | - None, | ||
| 114 | - ) | ||
| 115 | - .await; | ||
| 116 | - assert_eq!(status, 200, "reader page"); | ||
| 117 | - assert!( | ||
| 118 | - !body.contains(SECURITY_TAB), | ||
| 119 | - "a reader must not see the tab" | ||
| 120 | - ); | ||
| 121 | -} | ||
| 122 | - | ||
| 123 | -#[tokio::test] | ||
| 124 | -async fn security_tab_is_hidden_when_advisories_are_off() { | ||
| 125 | - let site = site(false).await; | ||
| 126 | - let (owner_cookie, _) = fixture(&site).await; | ||
| 127 | - let Reply { status, body, .. } = send( | ||
| 128 | - &site.router, | ||
| 129 | - "GET", | ||
| 130 | - "/owner/proj/issues", | ||
| 131 | - Some(&owner_cookie), | ||
| 132 | - None, | ||
| 133 | - ) | ||
| 134 | - .await; | ||
| 135 | - assert_eq!(status, 200); | ||
| 136 | - assert!( | ||
| 137 | - !body.contains(SECURITY_TAB), | ||
| 138 | - "no tab while advisories are off" | ||
| 139 | - ); | ||
| 140 | -} | ||
crates/forge-web/src/boot.rsmodified+0 -1
| @@ -139,7 +139,6 @@ pub async fn serve( | |||
| 139 | forge_web_app::exporter::on_boot(&state).await; | 139 | forge_web_app::exporter::on_boot(&state).await; |
| 140 | forge_web_app::webhooks::worker::spawn(state.clone()); | 140 | forge_web_app::webhooks::worker::spawn(state.clone()); |
| 141 | forge_web_app::mirrors::worker::spawn(state.clone()); | 141 | forge_web_app::mirrors::worker::spawn(state.clone()); |
| 142 | - forge_web_app::advisories::worker::spawn(state.clone()); | ||
| 143 | forge_web_app::mail::worker::spawn(state.clone()); | 142 | forge_web_app::mail::worker::spawn(state.clone()); |
| 144 | if state.config.backup.enabled() { | 143 | if state.config.backup.enabled() { |
| 145 | forge_web_app::backup::scheduler::spawn(state.clone()); | 144 | forge_web_app::backup::scheduler::spawn(state.clone()); |
crates/forge-web/src/page_route_tests/notifications.rsmodified+0 -80
| @@ -443,83 +443,3 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() { | |||
| 443 | 0 | 443 | 0 |
| 444 | ); | 444 | ); |
| 445 | } | 445 | } |
| 446 | - | ||
| 447 | -#[tokio::test] | ||
| 448 | -async fn advisory_alerts_show_for_managers_and_open_marks_read() { | ||
| 449 | - let site = site().await; | ||
| 450 | - let w = world(&site, Visibility::Public).await; | ||
| 451 | - site.store | ||
| 452 | - .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2) | ||
| 453 | - .await | ||
| 454 | - .expect("alerts"); | ||
| 455 | - site.store | ||
| 456 | - .notify_new_alerts(&w.bob.id, &w.repo.id, 1) | ||
| 457 | - .await | ||
| 458 | - .expect("alerts"); | ||
| 459 | - let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await; | ||
| 460 | - let bob = sign_in(&site.store, &w.bob.id, "bob-token").await; | ||
| 461 | - let open = format!("/notifications/advisories/{}/open", w.repo.id); | ||
| 462 | - | ||
| 463 | - let page = get(&site, "/notifications", Some(&tahinli)).await; | ||
| 464 | - assert_eq!(page.status, 200); | ||
| 465 | - assert!(page.body.contains("Security alerts")); | ||
| 466 | - assert!(page.body.contains("2 new alerts")); | ||
| 467 | - assert!(page.body.contains(&open)); | ||
| 468 | - assert_eq!( | ||
| 469 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 470 | - 1 | ||
| 471 | - ); | ||
| 472 | - | ||
| 473 | - let bob_page = get(&site, "/notifications", Some(&bob)).await; | ||
| 474 | - assert_eq!(bob_page.status, 200); | ||
| 475 | - assert!(!bob_page.body.contains(&open)); | ||
| 476 | - assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0); | ||
| 477 | - let bob_open = get(&site, &open, Some(&bob)).await; | ||
| 478 | - assert_eq!(bob_open.status, 404); | ||
| 479 | - | ||
| 480 | - let res = get(&site, &open, Some(&tahinli)).await; | ||
| 481 | - assert_eq!(res.status, 303); | ||
| 482 | - assert_eq!(res.location.as_deref(), Some("/tahinli/demo/security")); | ||
| 483 | - assert_eq!( | ||
| 484 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 485 | - 0 | ||
| 486 | - ); | ||
| 487 | -} | ||
| 488 | - | ||
| 489 | -#[tokio::test] | ||
| 490 | -async fn advisory_rows_are_marked_read_by_mark_read_and_mark_all() { | ||
| 491 | - let site = site().await; | ||
| 492 | - let w = world(&site, Visibility::Public).await; | ||
| 493 | - let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await; | ||
| 494 | - let read = format!("/notifications/advisories/{}/read", w.repo.id); | ||
| 495 | - | ||
| 496 | - site.store | ||
| 497 | - .notify_new_alerts(&w.tahinli.id, &w.repo.id, 1) | ||
| 498 | - .await | ||
| 499 | - .expect("alerts"); | ||
| 500 | - assert_eq!( | ||
| 501 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 502 | - 1 | ||
| 503 | - ); | ||
| 504 | - let res = post(&site, &read, &tahinli, "").await; | ||
| 505 | - assert_eq!(res.status, 303); | ||
| 506 | - assert_eq!( | ||
| 507 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 508 | - 0 | ||
| 509 | - ); | ||
| 510 | - | ||
| 511 | - site.store | ||
| 512 | - .notify_new_alerts(&w.tahinli.id, &w.repo.id, 3) | ||
| 513 | - .await | ||
| 514 | - .expect("alerts"); | ||
| 515 | - assert_eq!( | ||
| 516 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 517 | - 1 | ||
| 518 | - ); | ||
| 519 | - let res = post(&site, "/notifications/mark_all_read", &tahinli, "").await; | ||
| 520 | - assert_eq!(res.status, 303); | ||
| 521 | - assert_eq!( | ||
| 522 | - site.store.unread_count(&w.tahinli.id).await.expect("count"), | ||
| 523 | - 0 | ||
| 524 | - ); | ||
| 525 | -} | ||
crates/forge-web/src/routes.snapmodified+0 -6
| @@ -155,7 +155,6 @@ page /{owner}/{repo}/releases/{release_id}/edit Only([GET]) | |||
| 155 | page /{owner}/{repo}/releases/{release_id}/edit Only([POST]) | 155 | page /{owner}/{repo}/releases/{release_id}/edit Only([POST]) |
| 156 | page /{owner}/{repo}/scrub/{oid} Only([GET]) | 156 | page /{owner}/{repo}/scrub/{oid} Only([GET]) |
| 157 | page /{owner}/{repo}/search Only([GET]) | 157 | page /{owner}/{repo}/search Only([GET]) |
| 158 | -page /{owner}/{repo}/security Only([GET]) | ||
| 159 | page /{owner}/{repo}/settings Only([GET]) | 158 | page /{owner}/{repo}/settings Only([GET]) |
| 160 | page /{owner}/{repo}/settings/branches Only([POST]) | 159 | page /{owner}/{repo}/settings/branches Only([POST]) |
| 161 | page /{owner}/{repo}/settings/collaborators Only([GET]) | 160 | page /{owner}/{repo}/settings/collaborators Only([GET]) |
| @@ -309,8 +308,6 @@ route /needs-you/events Only([GET]) | |||
| 309 | route /needs-you/runs/dismiss Only([POST]) | 308 | route /needs-you/runs/dismiss Only([POST]) |
| 310 | route /notifications/admin/{admin_note}/open Only([GET]) | 309 | route /notifications/admin/{admin_note}/open Only([GET]) |
| 311 | route /notifications/admin/{admin_note}/read Only([POST]) | 310 | route /notifications/admin/{admin_note}/read Only([POST]) |
| 312 | -route /notifications/advisories/{advisory_repo_id}/open Only([GET]) | ||
| 313 | -route /notifications/advisories/{advisory_repo_id}/read Only([POST]) | ||
| 314 | route /notifications/discussions/{discussion_id}/open Only([GET]) | 311 | route /notifications/discussions/{discussion_id}/open Only([GET]) |
| 315 | route /notifications/discussions/{discussion_id}/read Only([POST]) | 312 | route /notifications/discussions/{discussion_id}/read Only([POST]) |
| 316 | route /notifications/events Only([GET]) | 313 | route /notifications/events Only([GET]) |
| @@ -459,9 +456,6 @@ route /{owner}/{repo}/releases/tag/{tag}/events Only([GET]) | |||
| 459 | route /{owner}/{repo}/releases/{release_id}/assets Only([POST]) | 456 | route /{owner}/{repo}/releases/{release_id}/assets Only([POST]) |
| 460 | route /{owner}/{repo}/releases/{release_id}/assets/{asset_id}/delete Only([POST]) | 457 | route /{owner}/{repo}/releases/{release_id}/assets/{asset_id}/delete Only([POST]) |
| 461 | route /{owner}/{repo}/releases/{release_id}/delete Only([POST]) | 458 | route /{owner}/{repo}/releases/{release_id}/delete Only([POST]) |
| 462 | -route /{owner}/{repo}/security/dismiss Only([POST]) | ||
| 463 | -route /{owner}/{repo}/security/live Only([GET]) | ||
| 464 | -route /{owner}/{repo}/security/reopen Only([POST]) | ||
| 465 | route /{owner}/{repo}/settings/archive Only([POST]) | 459 | route /{owner}/{repo}/settings/archive Only([POST]) |
| 466 | route /{owner}/{repo}/settings/branches/delete Only([POST]) | 460 | route /{owner}/{repo}/settings/branches/delete Only([POST]) |
| 467 | route /{owner}/{repo}/settings/collaborators/add Only([POST]) | 461 | route /{owner}/{repo}/settings/collaborators/add Only([POST]) |
docs/architecture.mdmodified+1 -1
| @@ -281,7 +281,7 @@ Pages update without a reload. A write that changes what a page shows calls `Liv | |||
| 281 | | Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers | | 281 | | Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers | |
| 282 | | Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar) | the viewer's own account topic: a setting, key, token, passkey or session changed, a sign-in or key use happened, or a suspension or account deletion. A revoked current session leaves for the login page on the next re-read | | 282 | | Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar) | the viewer's own account topic: a setting, key, token, passkey or session changed, a sign-in or key use happened, or a suspension or account deletion. A revoked current session leaves for the login page on the next re-read | |
| 283 | | Every signed-in page (`/-/alive`, the stream every page holds) | the viewer's account topic. A `theme` event carries the appearance attributes (theme, accents, base, sidebar side) when they change, and `nav.js` applies them with no reload. The stream is one connection, shared with the restart check | | 283 | | Every signed-in page (`/-/alive`, the stream every page holds) | the viewer's account topic. A `theme` event carries the appearance attributes (theme, accents, base, sidebar side) when they change, and `nav.js` applies them with no reload. The stream is one connection, shared with the restart check | |
| 284 | -| Repo settings `/{owner}/{repo}/settings/...`, security `/{owner}/{repo}/security`, transfer `/{owner}/{repo}/transfer` | `/{owner}/{repo}/settings/live` (admins only), `/{owner}/{repo}/security/live`, `/{owner}/{repo}/transfer/live` | the repo settings topic: a settings POST, a webhook delivery queued or sent, a mirror sync that finished, a security scan that opened or fixed an alert, a transfer accepted, declined or cancelled. The settings stream also follows the repo refs for the branch picker | | 284 | +| Repo settings `/{owner}/{repo}/settings/...`, transfer `/{owner}/{repo}/transfer` | `/{owner}/{repo}/settings/live` (admins only), `/{owner}/{repo}/transfer/live` | the repo settings topic: a settings POST, a webhook delivery queued or sent, a mirror sync that finished, a transfer accepted, declined or cancelled. The settings stream also follows the repo refs for the branch picker | |
| 285 | 285 | ||
| 286 | The org streams follow the same access as their pages: a non-member gets 404, and a member who is not an owner gets 403 on the settings stream. A team page names only the linked repos the viewer may read. Each org write (a POST under `/org/{org}/members`, `teams` or `settings`) wakes the org's streams. The org notices (for example "Member added.") are carried in the redirect's `?notice=` query, not a cookie, so a live refresh of the page shows the same notice again. | 286 | The org streams follow the same access as their pages: a non-member gets 404, and a member who is not an owner gets 403 on the settings stream. A team page names only the linked repos the viewer may read. Each org write (a POST under `/org/{org}/members`, `teams` or `settings`) wakes the org's streams. The org notices (for example "Member added.") are carried in the redirect's `?notice=` query, not a cookie, so a live refresh of the page shows the same notice again. |
| 287 | 287 | ||
docs/backlog.mdmodified+0 -1
| @@ -93,6 +93,5 @@ Status: `[ ]` todo, `[~]` in progress, `[x]` done. | |||
| 93 | - [x] I18 i18n infrastructure (En/Tr) and the shell, auth and settings pages | 93 | - [x] I18 i18n infrastructure (En/Tr) and the shell, auth and settings pages |
| 94 | - [x] I18b remaining pages translated (11 per-group key modules in i18n/, Turkish review pass done) | 94 | - [x] I18b remaining pages translated (11 per-group key modules in i18n/, Turkish review pass done) |
| 95 | - [x] I18c shared time/size/visibility helpers localised | 95 | - [x] I18c shared time/size/visibility helpers localised |
| 96 | -- [x] A1 security advisories (OSV, opt-in) | ||
| 97 | - [x] P1 repo transfer acceptance | 96 | - [x] P1 repo transfer acceptance |
| 98 | - [x] LFS media route moved to `/-/media/` (branch named `media` no longer shadowed) | 97 | - [x] LFS media route moved to `/-/media/` (branch named `media` no longer shadowed) |
docs/notifications.mdmodified+2 -2
| @@ -40,8 +40,8 @@ your device, as with any push service. | |||
| 40 | 40 | ||
| 41 | Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity | 41 | Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity |
| 42 | on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a | 42 | on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a |
| 43 | -repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Security alerts | 43 | +repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Site admin alerts |
| 44 | -and site admin alerts are pushed the same way. | 44 | +are pushed the same way. |
| 45 | 45 | ||
| 46 | Notifications on a lock screen can show the title of a private repository. Turn push off for a | 46 | Notifications on a lock screen can show the title of a private repository. Turn push off for a |
| 47 | device you share. | 47 | device you share. |