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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! Presenter for `rustsec::Report` information.

use crate::{
    config::{OutputConfig, OutputFormat},
    prelude::*,
};
use abscissa_core::terminal::{
    self,
    Color::{self, Red, Yellow},
};
use rustsec::{
    cargo_lock::{
        dependency::{self, graph::EdgeDirection, Dependency},
        Lockfile, Package,
    },
    Vulnerability, Warning,
};
use std::{collections::BTreeSet as Set, io, path::Path, process::exit};

/// Vulnerability information presenter
#[derive(Clone, Debug)]
pub struct Presenter {
    /// Track packages we've displayed once so we don't show the same dep tree
    // TODO(tarcieri): group advisories about the same package?
    displayed_packages: Set<Dependency>,

    /// Output configuration
    config: OutputConfig,
}

impl Presenter {
    /// Create a new vulnerability information presenter
    pub fn new(config: &OutputConfig) -> Self {
        Self {
            displayed_packages: Set::new(),
            config: config.clone(),
        }
    }

    /// Information to display before a report is generated
    pub fn before_report(&mut self, lockfile_path: &Path, lockfile: &Lockfile) {
        if !self.config.is_quiet() {
            status_ok!(
                "Scanning",
                "{} for vulnerabilities ({} crate dependencies)",
                lockfile_path.display(),
                lockfile.packages.len(),
            );
        }
    }

    /// Print the vulnerability report generated by an audit
    pub fn print_report(
        &mut self,
        report: &rustsec::Report,
        self_advisories: &[rustsec::Advisory],
        lockfile: &Lockfile,
    ) {
        if self.config.format == OutputFormat::Json {
            serde_json::to_writer(io::stdout(), &report).unwrap();
            return;
        }

        if report.vulnerabilities.found {
            status_err!("Vulnerable crates found!");
        } else {
            status_ok!("Success", "No vulnerable packages found");
        }

        let tree = lockfile
            .dependency_tree()
            .expect("invalid Cargo.lock dependency tree");

        for vulnerability in &report.vulnerabilities.list {
            self.print_vulnerability(vulnerability, &tree);
        }

        if !report.warnings.is_empty() {
            println!();

            let advisory_word = if report.warnings.len() != 1 {
                "advisories"
            } else {
                "advisory"
            };

            if self.config.deny_warnings {
                status_err!(
                    "{} informational {} found",
                    report.warnings.len(),
                    advisory_word
                );
            } else {
                status_warn!(
                    "{} informational {} found",
                    report.warnings.len(),
                    advisory_word
                );
            }

            for warning in &report.warnings {
                self.print_warning(warning, &tree)
            }
        }

        if !self_advisories.is_empty() {
            println!();

            let msg = "this copy of cargo-audit has known advisories!";

            if self.config.deny_warnings {
                status_err!(msg);
            } else {
                status_warn!(msg);
            }

            for advisory in self_advisories {
                self.print_advisory_warning(&advisory.metadata);
            }
        }

        if report.vulnerabilities.found {
            println!();

            if report.vulnerabilities.count == 1 {
                status_err!("1 vulnerability found!");
            } else {
                status_err!("{} vulnerabilities found!", report.vulnerabilities.count);
            }
        }

        if !report.warnings.is_empty() {
            if !report.vulnerabilities.found {
                println!();
            }

            let warnings_word = if report.warnings.len() != 1 {
                "warnings"
            } else {
                "warning"
            };

            if self.config.deny_warnings {
                status_err!(
                    "{} {} found and `--deny-warnings` enabled!",
                    report.warnings.len(),
                    warnings_word
                );

                // TODO(tarcieri): better unify this with vulnerabilities handling
                exit(1);
            } else {
                status_warn!("{} {} found!", report.warnings.len(), warnings_word);
            }
        }

        let upgrade_msg = "upgrade cargo-audit to the latest version: \
                           cargo install --force cargo-audit";

        if !self_advisories.is_empty() {
            if self.config.deny_warnings {
                status_err!(upgrade_msg);
                exit(1);
            } else {
                status_warn!(upgrade_msg);
            }
        }
    }

    /// Print information about the given vulnerability
    fn print_vulnerability(&mut self, vulnerability: &Vulnerability, tree: &dependency::Tree) {
        let advisory = &vulnerability.advisory;

        println!();
        self.print_attr(Red, "ID:      ", &advisory.id);
        self.print_attr(Red, "Crate:   ", &vulnerability.package.name);
        self.print_attr(Red, "Version: ", &vulnerability.package.version.to_string());
        self.print_attr(Red, "Date:    ", &advisory.date);

        if let Some(url) = advisory.id.url() {
            self.print_attr(Red, "URL:     ", &url);
        } else if let Some(url) = &advisory.url {
            self.print_attr(Red, "URL:     ", url);
        }

        self.print_attr(Red, "Title:   ", &advisory.title);
        if vulnerability.versions.patched.is_empty() {
            self.print_attr(
                Red,
                "Solution:",
                String::from(" No safe upgrade is available!"),
            );
        } else {
            self.print_attr(
                Red,
                "Solution:",
                String::from(" upgrade to ")
                    + &vulnerability
                        .versions
                        .patched
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .as_slice()
                        .join(" OR "),
            );
        }

        self.print_tree(Red, &vulnerability.package, tree);
    }

    /// Print information about a given warning
    fn print_warning(&mut self, warning: &Warning, tree: &dependency::Tree) {
        self.print_advisory_warning(&warning.advisory);
        self.print_tree(self.warning_color(), &warning.package, tree);
    }

    /// Get the color to use when displaying warnings
    fn warning_color(&self) -> Color {
        if self.config.deny_warnings {
            Red
        } else {
            Yellow
        }
    }

    /// Print a warning about a particular advisory
    fn print_advisory_warning(&mut self, metadata: &rustsec::advisory::Metadata) {
        let color = self.warning_color();

        println!();
        self.print_attr(color, "Crate:   ", &metadata.package);
        self.print_attr(color, "Title:   ", &metadata.title);
        self.print_attr(color, "Date:    ", &metadata.date);

        if let Some(url) = metadata.id.url() {
            self.print_attr(color, "URL:     ", &url);
        } else if let Some(url) = &metadata.url {
            self.print_attr(color, "URL:     ", url);
        }
    }

    /// Display an attribute of a particular vulnerability
    fn print_attr(&self, color: Color, attr: &str, content: impl AsRef<str>) {
        terminal::status::Status::new()
            .bold()
            .color(color)
            .status(attr)
            .print_stdout(content.as_ref())
            .unwrap();
    }

    /// Print the inverse dependency tree to standard output
    fn print_tree(&mut self, color: Color, package: &Package, tree: &dependency::Tree) {
        // Only show the tree once per package
        if !self
            .displayed_packages
            .insert(Dependency::from(package.clone()))
        {
            return;
        }

        if !self.config.show_tree.unwrap_or(true) {
            return;
        }

        terminal::status::Status::new()
            .bold()
            .color(color)
            .status("Dependency tree:")
            .print_stdout("")
            .unwrap();

        let package_node = tree.nodes()[&Dependency::from(package.clone())];
        tree.render(&mut io::stdout(), package_node, EdgeDirection::Incoming)
            .unwrap();
    }
}