1use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use adk_core::{
21 AdkError, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApprovalService,
22 ApproverSelector, Clock, Result, SystemClock, ToolConfirmationRequest,
23};
24use adk_site::migrate::probe::CertificateProbe;
25use async_trait::async_trait;
26use awp_types::Urgency;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::json;
30use uuid::Uuid;
31
32use crate::alarms::{Alarm, AlarmRouter};
33
34pub const CERTIFICATE_WARNING_DAYS: i64 = 14;
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub struct Advisory {
41 pub id: String,
43 pub package: String,
45 pub title: String,
47 #[serde(default)]
49 pub patched: Vec<String>,
50 #[serde(default)]
52 pub unaffected: Vec<String>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub url: Option<String>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub informational: Option<String>,
59}
60
61impl Advisory {
62 pub fn affects(&self, version: &semver::Version) -> bool {
64 let covered = |reqs: &[String]| {
65 reqs.iter().any(|req| {
66 semver::VersionReq::parse(req).is_ok_and(|parsed| parsed.matches(version))
67 })
68 };
69 !covered(&self.patched) && !covered(&self.unaffected)
70 }
71}
72
73#[async_trait]
75pub trait AdvisorySource: Send + Sync {
76 async fn advisories(&self, packages: &[String]) -> Result<Vec<Advisory>>;
82}
83
84#[derive(Debug, Clone, Default)]
86pub struct StaticAdvisories(pub Vec<Advisory>);
87
88#[async_trait]
89impl AdvisorySource for StaticAdvisories {
90 async fn advisories(&self, packages: &[String]) -> Result<Vec<Advisory>> {
91 Ok(self.0.iter().filter(|a| packages.contains(&a.package)).cloned().collect())
92 }
93}
94
95#[derive(Debug, Clone)]
98pub struct AdvisoryDatabase {
99 root: PathBuf,
100}
101
102impl AdvisoryDatabase {
103 pub fn new(root: impl Into<PathBuf>) -> Self {
105 Self { root: root.into() }
106 }
107}
108
109#[derive(Deserialize)]
110struct AdvisoryFile {
111 advisory: AdvisoryMeta,
112 #[serde(default)]
113 versions: AdvisoryVersions,
114}
115
116#[derive(Deserialize)]
117struct AdvisoryMeta {
118 id: String,
119 package: String,
120 #[serde(default)]
121 url: Option<String>,
122 #[serde(default)]
123 informational: Option<String>,
124 #[serde(default)]
125 withdrawn: Option<String>,
126}
127
128#[derive(Deserialize, Default)]
129struct AdvisoryVersions {
130 #[serde(default)]
131 patched: Vec<String>,
132 #[serde(default)]
133 unaffected: Vec<String>,
134}
135
136pub fn parse_advisory(text: &str) -> Result<Option<Advisory>> {
143 let invalid = |why: String| AdkError::config(format!("an advisory file {why}"));
144 let start = text.find("```toml").ok_or_else(|| invalid("has no ```toml block".into()))?;
145 let body = &text[start + "```toml".len()..];
146 let end = body.find("```").ok_or_else(|| invalid("leaves its TOML block open".into()))?;
147 let file: AdvisoryFile =
148 toml::from_str(&body[..end]).map_err(|e| invalid(format!("does not parse: {e}")))?;
149 if file.advisory.withdrawn.is_some() {
150 return Ok(None);
151 }
152 let title = body[end + 3..]
153 .lines()
154 .find_map(|line| line.trim().strip_prefix("# "))
155 .unwrap_or(&file.advisory.id)
156 .trim()
157 .to_string();
158 Ok(Some(Advisory {
159 id: file.advisory.id,
160 package: file.advisory.package,
161 title,
162 patched: file.versions.patched,
163 unaffected: file.versions.unaffected,
164 url: file.advisory.url,
165 informational: file.advisory.informational,
166 }))
167}
168
169#[async_trait]
170impl AdvisorySource for AdvisoryDatabase {
171 async fn advisories(&self, packages: &[String]) -> Result<Vec<Advisory>> {
172 let mut found = Vec::new();
173 for package in packages {
174 if !package.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
176 continue;
177 }
178 let dir = self.root.join("crates").join(package);
179 let mut entries = match tokio::fs::read_dir(&dir).await {
180 Ok(entries) => entries,
181 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
182 Err(error) => {
183 return Err(AdkError::config(format!("{}: {error}", dir.display())));
184 }
185 };
186 while let Some(entry) = entries
187 .next_entry()
188 .await
189 .map_err(|e| AdkError::config(format!("{}: {e}", dir.display())))?
190 {
191 let path = entry.path();
192 if path.extension().is_none_or(|ext| ext != "md") {
193 continue;
194 }
195 let text = tokio::fs::read_to_string(&path)
196 .await
197 .map_err(|e| AdkError::config(format!("{}: {e}", path.display())))?;
198 match parse_advisory(&text) {
199 Ok(Some(advisory)) if advisory.package == *package => found.push(advisory),
200 Ok(_) => {}
201 Err(error) => {
202 tracing::warn!(path = %path.display(), error = %error, "an advisory was skipped");
203 }
204 }
205 }
206 }
207 found.sort_by(|a, b| a.id.cmp(&b.id));
208 Ok(found)
209 }
210}
211
212#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct LockedPackage {
215 pub name: String,
217 pub version: semver::Version,
219}
220
221pub fn locked_packages(lockfile: &str) -> Result<Vec<LockedPackage>> {
227 #[derive(Deserialize)]
228 struct Lock {
229 #[serde(default)]
230 package: Vec<Package>,
231 }
232 #[derive(Deserialize)]
233 struct Package {
234 name: String,
235 version: String,
236 }
237 let lock: Lock = toml::from_str(lockfile)
238 .map_err(|e| AdkError::config(format!("the lockfile does not parse: {e}")))?;
239 Ok(lock
240 .package
241 .into_iter()
242 .filter_map(|p| {
243 Some(LockedPackage { version: semver::Version::parse(&p.version).ok()?, name: p.name })
244 })
245 .collect())
246}
247
248#[async_trait]
250pub trait CertificateSource: Send + Sync {
251 async fn certificate(&self) -> Result<Option<CertificateProbe>>;
257}
258
259#[derive(Debug, Clone)]
261pub struct StaticCertificate(pub Option<CertificateProbe>);
262
263#[async_trait]
264impl CertificateSource for StaticCertificate {
265 async fn certificate(&self) -> Result<Option<CertificateProbe>> {
266 Ok(self.0.clone())
267 }
268}
269
270pub struct OriginCertificate {
272 http: Arc<adk_site::migrate::http::HttpClient>,
273 origin: url::Url,
274 warning_days: i64,
275}
276
277impl OriginCertificate {
278 pub fn new(http: Arc<adk_site::migrate::http::HttpClient>, origin: url::Url) -> Self {
280 Self { http, origin, warning_days: CERTIFICATE_WARNING_DAYS }
281 }
282}
283
284#[async_trait]
285impl CertificateSource for OriginCertificate {
286 async fn certificate(&self) -> Result<Option<CertificateProbe>> {
287 let fetched = self
288 .http
289 .fetch(&self.origin, &adk_site::migrate::http::FetchOptions::crawler())
290 .await
291 .map_err(|e| AdkError::config(e.to_string()))?;
292 let Some(der) = fetched.peer_certificate else { return Ok(None) };
293 CertificateProbe::from_der(&der, Utc::now(), self.warning_days)
294 .map(Some)
295 .map_err(|e| AdkError::config(e.to_string()))
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(tag = "proposal", rename_all = "snake_case", rename_all_fields = "camelCase")]
302pub enum UpkeepProposal {
303 Upgrade {
305 advisory: String,
307 title: String,
309 package: String,
311 version: String,
313 patched: Vec<String>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
317 url: Option<String>,
318 },
319 RenewCertificate {
321 domain: String,
323 not_after: DateTime<Utc>,
325 days_left: i64,
327 },
328}
329
330impl UpkeepProposal {
331 pub fn key(&self) -> String {
333 match self {
334 Self::Upgrade { advisory, package, version, .. } => {
335 format!("upgrade-{advisory}-{package}-{version}")
336 }
337 Self::RenewCertificate { domain, not_after, .. } => {
338 format!("renew-{domain}-{}", not_after.format("%Y%m%d"))
339 }
340 }
341 }
342
343 pub fn summary(&self) -> String {
345 match self {
346 Self::Upgrade { advisory, title, package, version, patched, .. } => {
347 let fixed = if patched.is_empty() {
348 "no fixed version yet; replace it or accept the risk".to_string()
349 } else {
350 format!("upgrade to {}", patched.join(" or "))
351 };
352 format!(
353 "{advisory} affects the edge's {package} {version} ({title}): {fixed}, then redeploy"
354 )
355 }
356 Self::RenewCertificate { domain, not_after, days_left } => format!(
357 "The certificate of {domain} expires in {days_left} days ({}): renew it",
358 not_after.format("%-d %B")
359 ),
360 }
361 }
362
363 pub fn urgency(&self) -> Urgency {
365 match self {
366 Self::RenewCertificate { days_left, .. } if *days_left <= 3 => Urgency::P1,
367 _ => Urgency::P2,
368 }
369 }
370}
371
372pub fn upgrades(packages: &[LockedPackage], advisories: &[Advisory]) -> Vec<UpkeepProposal> {
375 let mut proposals = Vec::new();
376 for advisory in advisories.iter().filter(|a| a.informational.is_none()) {
377 for package in packages.iter().filter(|p| p.name == advisory.package) {
378 if advisory.affects(&package.version) {
379 proposals.push(UpkeepProposal::Upgrade {
380 advisory: advisory.id.clone(),
381 title: advisory.title.clone(),
382 package: package.name.clone(),
383 version: package.version.to_string(),
384 patched: advisory.patched.clone(),
385 url: advisory.url.clone(),
386 });
387 }
388 }
389 }
390 proposals
391}
392
393#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
395#[serde(rename_all = "camelCase")]
396pub struct UpkeepReport {
397 pub proposals: Vec<UpkeepProposal>,
399 pub filed: Vec<String>,
401 pub problems: Vec<String>,
403}
404
405pub struct UpkeepCheck {
409 site: Uuid,
410 domain: String,
411 app: String,
412 owner: String,
413 approvals: Arc<dyn ApprovalService>,
414 alarms: Option<Arc<AlarmRouter>>,
415 lockfile: Option<PathBuf>,
416 advisories: Option<Arc<dyn AdvisorySource>>,
417 certificate: Option<Arc<dyn CertificateSource>>,
418 clock: Arc<dyn Clock>,
419}
420
421impl std::fmt::Debug for UpkeepCheck {
422 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423 f.debug_struct("UpkeepCheck").field("domain", &self.domain).finish_non_exhaustive()
424 }
425}
426
427impl UpkeepCheck {
428 pub fn new(
430 site: Uuid,
431 domain: impl Into<String>,
432 app: impl Into<String>,
433 owner: impl Into<String>,
434 approvals: Arc<dyn ApprovalService>,
435 ) -> Self {
436 Self {
437 site,
438 domain: domain.into(),
439 app: app.into(),
440 owner: owner.into(),
441 approvals,
442 alarms: None,
443 lockfile: None,
444 advisories: None,
445 certificate: None,
446 clock: Arc::new(SystemClock),
447 }
448 }
449
450 #[must_use]
452 pub fn with_advisories(
453 mut self,
454 lockfile: impl AsRef<Path>,
455 source: Arc<dyn AdvisorySource>,
456 ) -> Self {
457 self.lockfile = Some(lockfile.as_ref().to_path_buf());
458 self.advisories = Some(source);
459 self
460 }
461
462 #[must_use]
464 pub fn with_certificate(mut self, source: Arc<dyn CertificateSource>) -> Self {
465 self.certificate = Some(source);
466 self
467 }
468
469 #[must_use]
471 pub fn with_alarms(mut self, router: Arc<AlarmRouter>) -> Self {
472 self.alarms = Some(router);
473 self
474 }
475
476 #[must_use]
478 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
479 self.clock = clock;
480 self
481 }
482
483 #[tracing::instrument(skip_all, name = "website.job.hosting", fields(site.domain = %self.domain))]
489 pub async fn run(&self) -> Result<UpkeepReport> {
490 let mut proposals = Vec::new();
491 let mut problems = Vec::new();
492 if let (Some(path), Some(source)) = (&self.lockfile, &self.advisories) {
493 let read = async {
494 let text = tokio::fs::read_to_string(path)
495 .await
496 .map_err(|e| AdkError::config(format!("{}: {e}", path.display())))?;
497 let packages = locked_packages(&text)?;
498 let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect();
499 let advisories = source.advisories(&names).await?;
500 Ok::<_, AdkError>(upgrades(&packages, &advisories))
501 };
502 match read.await {
503 Ok(found) => proposals.extend(found),
504 Err(error) => problems.push(format!("advisories: {error}")),
505 }
506 }
507 if let Some(source) = &self.certificate {
508 match source.certificate().await {
509 Ok(Some(certificate)) if certificate.expiring => {
510 proposals.push(UpkeepProposal::RenewCertificate {
511 domain: self.domain.clone(),
512 not_after: certificate.not_after,
513 days_left: certificate.days_left,
514 });
515 }
516 Ok(_) => {}
517 Err(error) => problems.push(format!("certificate: {error}")),
518 }
519 }
520 let mut filed = Vec::new();
521 for proposal in &proposals {
522 let id = format!("site-upkeep-{}-{}", self.site, proposal.key());
523 if self.approvals.get(&id).await?.is_some() {
524 continue;
525 }
526 let call = ToolConfirmationRequest::new("upkeep_proposal", json!(proposal));
527 let scope = ApprovalScope::new(self.app.clone(), self.owner.clone(), "site-upkeep");
528 let policy = ApprovalPolicy::new([ApproverSelector::human(self.owner.clone())]);
529 let request = ApprovalRequest::new(id.clone(), scope, &call, policy)
530 .with_summary(proposal.summary())
531 .with_risk(ApprovalRisk::Medium);
532 self.approvals.submit(request).await?;
533 if let Some(alarms) = &self.alarms {
534 alarms
535 .raise(Alarm::new(
536 self.site,
537 proposal.urgency(),
538 "upkeep_proposal",
539 proposal.summary(),
540 self.clock.now(),
541 ))
542 .await;
543 }
544 tracing::info!(website.site = %self.site, proposal = %proposal.key(), "website.upkeep.proposed");
545 filed.push(id);
546 }
547 Ok(UpkeepReport { proposals, filed, problems })
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use super::*;
554
555 const ADVISORY: &str = r#"```toml
556[advisory]
557id = "RUSTSEC-2020-0071"
558package = "time"
559date = "2020-11-18"
560url = "https://github.com/time-rs/time/issues/293"
561
562[versions]
563patched = [">= 0.2.23"]
564unaffected = ["= 0.2.0", "= 0.2.1", "= 0.2.2"]
565```
566
567# Potential segfault in the time crate
568
569Unix-like operating systems may segfault.
570"#;
571
572 #[test]
573 fn an_advisory_parses_and_names_the_versions_it_affects() {
574 let advisory = parse_advisory(ADVISORY).unwrap().unwrap();
575 assert_eq!(advisory.id, "RUSTSEC-2020-0071");
576 assert_eq!(advisory.title, "Potential segfault in the time crate");
577 let affected = |v: &str| advisory.affects(&semver::Version::parse(v).unwrap());
578 assert!(affected("0.1.45"));
579 assert!(!affected("0.2.1"), "unaffected");
580 assert!(!affected("0.3.36"), "patched");
581 let withdrawn = ADVISORY.replace("[versions]", "withdrawn = \"2021-01-01\"\n[versions]");
582 assert!(parse_advisory(&withdrawn).unwrap().is_none());
583 }
584
585 #[test]
586 fn a_locked_vulnerable_version_becomes_one_upgrade_proposal() {
587 let lock = r#"
588version = 4
589
590[[package]]
591name = "time"
592version = "0.1.45"
593
594[[package]]
595name = "serde"
596version = "1.0.228"
597"#;
598 let packages = locked_packages(lock).unwrap();
599 let advisory = parse_advisory(ADVISORY).unwrap().unwrap();
600 let proposals = upgrades(&packages, std::slice::from_ref(&advisory));
601 assert_eq!(proposals.len(), 1);
602 assert!(proposals[0].summary().contains("upgrade to >= 0.2.23"), "{proposals:?}");
603 let mut note = advisory;
604 note.informational = Some("unmaintained".into());
605 assert!(upgrades(&packages, &[note]).is_empty(), "informational advisories wait");
606 }
607}