1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//! Generator for the https://rustsec.org web site
//!
//! Creates markdown versions of each advisory, which are rendered into a final
//! template using markdown.

use crate::prelude::*;
use handlebars::Handlebars;
use serde::Serialize;
use std::{fs::File, io::Write, path::PathBuf};

/// Filename of the advisory template
pub const ADVISORY_TEMPLATE_NAME: &str = "advisory.md.hbs";

/// Advisory template file (Handlebars)
///
/// These are rendered into Markdown, which is parsed by Jekyll and rendered
/// into HTML. The latter step is performed by GitHub Pages itself.
const ADVISORY_TEMPLATE_STRING: &str = r#"---
title:       "{{id}}: {{package}}: {{title}}"
description: "{{summary}}"
date:        {{date}}
tags:        {{tags}}
permalink:   /advisories/{{id}}:output_ext
---

### Description

{{{description}}}

{{#if url ~}}
### More Info

<{{{url}}}>

{{/if~}}

### Patched Versions

{{#if patched_versions~}}
{{#each patched_versions ~}}
- `{{{this}}}`
{{/each~}}
{{~else~}}
- None!
{{~/if}}

{{#if unaffected_versions}}
### Unaffected Versions

{{#each unaffected_versions ~}}
- `{{{this}}}`
{{/each ~}}
{{/if ~}}
"#;

/// Render all advisories using the Markdown template
pub fn render_advisories() {
    let mut handlebars = Handlebars::new();
    handlebars.set_strict_mode(true);
    handlebars.register_escape_fn(handlebars::no_escape);

    handlebars
        .register_template_string(ADVISORY_TEMPLATE_NAME, ADVISORY_TEMPLATE_STRING)
        .unwrap();

    let advisories: Vec<AdvisoryParams> = rustsec::Database::fetch()
        .unwrap()
        .iter()
        .map(AdvisoryParams::from)
        .collect();

    for advisory in &advisories {
        let output_path =
            PathBuf::from("_posts").join(format!("{}-{}.md", advisory.date, advisory.id));

        let mut rendered = handlebars.render(ADVISORY_TEMPLATE_NAME, advisory).unwrap();

        // TODO: escaping bug? Find a better solution for (not) escaping these
        // These are getting escaped by handlebars and are double-escaped in the HTML
        // unless removed using the hax below
        rendered = rendered.replace("&lt;", "<").replace("&gt;", ">");

        let mut output_file = File::create(&output_path).unwrap();
        output_file.write_all(rendered.as_bytes()).unwrap();

        status_ok!("Rendered", "{}", output_path.display());
    }

    status_ok!(
        "Completed",
        "{} advisories rendered as Markdown",
        advisories.len()
    );
}

/// Parameters to pass to the `advisory.md.hbs` Handlebars template
#[derive(Debug, Serialize)]
pub struct AdvisoryParams {
    /// Advisory ID (i.e. `RUSTSEC-20YY-NNNN`)
    pub id: String,

    /// Package name (i.e. crate name)
    pub package: String,

    /// Title of advisory
    pub title: String,

    /// One-liner summary of the advisory
    pub summary: String,

    /// Full description
    pub description: String,

    /// Advisory date
    pub date: String,

    /// Tags to associate with this advisory
    pub tags: String,

    /// URL for more information
    pub url: Option<String>,

    /// Patched versions
    pub patched_versions: Vec<String>,

    /// Unaffected versions
    pub unaffected_versions: Option<Vec<String>>,
}

impl<'a> From<&'a rustsec::Advisory> for AdvisoryParams {
    fn from(advisory: &rustsec::Advisory) -> AdvisoryParams {
        let patched_versions = advisory
            .versions
            .patched
            .iter()
            .map(|req| req.to_string())
            .collect();

        let unaffected_versions = if advisory.versions.unaffected.is_empty() {
            None
        } else {
            Some(
                advisory
                    .versions
                    .unaffected
                    .iter()
                    .map(|req| req.to_string())
                    .collect(),
            )
        };

        let mut summary = advisory.description.replace('\n', " ").replace("  ", " ");

        summary.retain(|c| matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | ' ' | ',' | '.'));

        let mut tags = vec![advisory.metadata.package.to_string()];

        tags.extend(
            advisory
                .metadata
                .keywords
                .iter()
                .map(|kw| kw.as_str().to_owned()),
        );

        Self {
            id: advisory.metadata.id.to_string(),
            package: advisory.metadata.package.to_string(),
            title: advisory.title.clone(),
            summary: summary.trim().to_owned(),
            description: advisory.description.trim().to_owned(),
            date: advisory.metadata.date.as_str().to_owned(),
            tags: tags.join(" "),
            url: advisory.metadata.url.clone(),
            patched_versions,
            unaffected_versions,
        }
    }
}