Skip to main content

adk_website/
upkeep.rs

1//! Upkeep proposals: dependency upgrades for security advisories and certificate renewals
2//! (spec 3.5 §5 S10, §7.19 "Guardian … advisories daily", §7.20 "Hosting, domains,
3//! certificates, backups — Propose; renewals within budget").
4//!
5//! The hosting job's daily watch ([`crate::jobs::WATCH_WORKFLOW`]) runs [`UpkeepCheck`]
6//! without a model: it reads the edge's `Cargo.lock` against an [`AdvisorySource`] — such as
7//! a local clone of the RustSec advisory database ([`AdvisoryDatabase`]) — and the origin's
8//! certificate through a [`CertificateSource`], and proposes each upgrade or renewal to the
9//! owner as one decision card, filed once. A proposal changes nothing: the owner decides, and
10//! the upgrade is a redeploy and the renewal the registrar's or the host's.
11//!
12//! | Proposal | When | Urgency |
13//! |---|---|---|
14//! | [`UpkeepProposal::Upgrade`] | A locked package is in a version an advisory names and no patched or unaffected range covers | P2 |
15//! | [`UpkeepProposal::RenewCertificate`] | The certificate expires within the warning window (14 days) | P2; P1 within 3 days |
16
17use 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
34/// Days before expiry a certificate renewal is proposed (spec 3.5 §5 S10).
35pub const CERTIFICATE_WARNING_DAYS: i64 = 14;
36
37/// A security advisory against a crate (the RustSec advisory format).
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub struct Advisory {
41    /// Its id, such as `RUSTSEC-2020-0071`.
42    pub id: String,
43    /// The crate.
44    pub package: String,
45    /// Its title.
46    pub title: String,
47    /// Version requirements that carry the fix, such as `>= 0.2.23`.
48    #[serde(default)]
49    pub patched: Vec<String>,
50    /// Version requirements never affected.
51    #[serde(default)]
52    pub unaffected: Vec<String>,
53    /// Where it is described.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub url: Option<String>,
56    /// Whether it is informational (unmaintained, unsound) rather than a vulnerability.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub informational: Option<String>,
59}
60
61impl Advisory {
62    /// Whether `version` is affected: no patched or unaffected requirement covers it.
63    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/// Where advisories come from.
74#[async_trait]
75pub trait AdvisorySource: Send + Sync {
76    /// The advisories against any of `packages`.
77    ///
78    /// # Errors
79    ///
80    /// The source's error.
81    async fn advisories(&self, packages: &[String]) -> Result<Vec<Advisory>>;
82}
83
84/// Advisories held in memory, such as a fixture or a feed already fetched.
85#[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/// A local clone of the RustSec advisory database (`github.com/rustsec/advisory-db`): one
96/// Markdown file per advisory under `crates/<crate>/`, its metadata in a TOML block.
97#[derive(Debug, Clone)]
98pub struct AdvisoryDatabase {
99    root: PathBuf,
100}
101
102impl AdvisoryDatabase {
103    /// The database cloned at `root`.
104    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
136/// Parses one advisory file: a fenced TOML block, then a `# Title` line. `None` for a
137/// withdrawn advisory.
138///
139/// # Errors
140///
141/// A file with no TOML block or one that does not parse.
142pub 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            // Crate names are path-safe, and a name that is not is not read.
175            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/// A package a lockfile pins.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct LockedPackage {
215    /// The crate.
216    pub name: String,
217    /// Its version.
218    pub version: semver::Version,
219}
220
221/// The packages `lockfile` (a `Cargo.lock`) pins.
222///
223/// # Errors
224///
225/// A lockfile that does not parse.
226pub 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/// The origin's certificate, as the probe reads it.
249#[async_trait]
250pub trait CertificateSource: Send + Sync {
251    /// The certificate's expiry, or `None` when the origin serves no certificate.
252    ///
253    /// # Errors
254    ///
255    /// The source's error.
256    async fn certificate(&self) -> Result<Option<CertificateProbe>>;
257}
258
259/// A certificate already read, such as the last probe's.
260#[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
270/// The certificate the public origin presents, read through the site's signed HTTP client.
271pub struct OriginCertificate {
272    http: Arc<adk_site::migrate::http::HttpClient>,
273    origin: url::Url,
274    warning_days: i64,
275}
276
277impl OriginCertificate {
278    /// The certificate of `origin`, warning [`CERTIFICATE_WARNING_DAYS`] ahead.
279    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/// An upkeep proposal for the owner (spec 3.5 §7.20).
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(tag = "proposal", rename_all = "snake_case", rename_all_fields = "camelCase")]
302pub enum UpkeepProposal {
303    /// Upgrade a package an advisory names.
304    Upgrade {
305        /// The advisory.
306        advisory: String,
307        /// Its title.
308        title: String,
309        /// The crate.
310        package: String,
311        /// The locked version.
312        version: String,
313        /// The versions that carry the fix.
314        patched: Vec<String>,
315        /// Where it is described.
316        #[serde(default, skip_serializing_if = "Option::is_none")]
317        url: Option<String>,
318    },
319    /// Renew the site's certificate.
320    RenewCertificate {
321        /// The site's domain.
322        domain: String,
323        /// When it expires.
324        not_after: DateTime<Utc>,
325        /// Whole days left.
326        days_left: i64,
327    },
328}
329
330impl UpkeepProposal {
331    /// A stable key: one card per advisory and package, one per certificate expiry.
332    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    /// The proposal in a sentence for the owner.
344    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    /// How soon the owner hears of it.
364    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
372/// The proposals for `packages` under `advisories`: every vulnerability that affects a
373/// locked version, informational advisories left out.
374pub 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/// What one upkeep check found and filed.
394#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
395#[serde(rename_all = "camelCase")]
396pub struct UpkeepReport {
397    /// Every proposal the check found, filed now or earlier.
398    pub proposals: Vec<UpkeepProposal>,
399    /// The decision cards filed now.
400    pub filed: Vec<String>,
401    /// What the check could not read.
402    pub problems: Vec<String>,
403}
404
405/// The hosting job's daily upkeep check (spec 3.5 §7.20): advisories against the edge's
406/// lockfile and the certificate's expiry, each found proposal filed once as a decision card
407/// to the owner, with an alarm by its urgency.
408pub 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    /// A check for `site` at `domain` of app `app`, filing cards for `owner` in `approvals`.
429    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    /// Reads `lockfile` against `source` (spec 3.5 §7.19 "advisories daily").
451    #[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    /// Reads the certificate's expiry from `source`.
463    #[must_use]
464    pub fn with_certificate(mut self, source: Arc<dyn CertificateSource>) -> Self {
465        self.certificate = Some(source);
466        self
467    }
468
469    /// Raises each new proposal's alarm on `router`.
470    #[must_use]
471    pub fn with_alarms(mut self, router: Arc<AlarmRouter>) -> Self {
472        self.alarms = Some(router);
473        self
474    }
475
476    /// The clock.
477    #[must_use]
478    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
479        self.clock = clock;
480        self
481    }
482
483    /// Finds the proposals and files the new ones (spec 3.5 §7.20).
484    ///
485    /// # Errors
486    ///
487    /// The approval service's error; what cannot be read is reported, not raised.
488    #[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}