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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Handlebars helpers
#![allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]

use bytecount::count;
use handlebars::{Context, Handlebars as Registry, Helper, Output, RenderContext, RenderError};
use serde_json::Value;

use super::utils::{html_escape, split_indent};

/// Generates a list of line numbers for the given vulnerability.
///
/// An optional line separator can be added that will be used at the end of each line. By default,
/// this separator will be `<br>`.
pub fn line_numbers(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let vulnerability = h
        .param(0)
        .and_then(|v| v.value().as_object())
        .ok_or_else(|| {
            RenderError::new(
                "to generate the vulnerability index, the first parameter must be a \
                 vulnerability",
            )
        })?;
    let line_separator = if let Some(s) = h.param(1) {
        if let Value::String(ref s) = *s.value() {
            s
        } else {
            return Err(RenderError::new(
                "the provided line separator for the code lines was \
                 not a string",
            ));
        }
    } else {
        "<br>"
    };
    let (start_line, end_line) = if let Some(l) = vulnerability.get("line") {
        let line = l.as_i64().unwrap();
        (line, line)
    } else {
        let start_line = vulnerability.get("start_line").unwrap().as_i64().unwrap();
        let end_line = vulnerability.get("end_line").unwrap().as_i64().unwrap();
        (start_line, end_line)
    };

    let iter_start = if start_line > 5 { start_line - 4 } else { 1 };
    let iter_end = end_line + 5;

    let mut rendered =
        String::with_capacity((line_separator.len() + 1) * (iter_end - iter_start) as usize);
    for l in iter_start..iter_end {
        rendered.push_str(&format!("{}", l));
        rendered.push_str(line_separator);
    }
    out.write(&rendered)?;

    Ok(())
}

/// Generates a list of line numbers for all the given code.
///
/// An optional line separator can be added that will be used at the end of each line. By default,
/// this separator will be `<br>`.
pub fn all_lines(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let code = h
        .param(0)
        .and_then(|v| v.value().as_str())
        .ok_or_else(|| RenderError::new("the code must be a string"))?;
    let line_separator = if let Some(s) = h.param(1) {
        if let Value::String(ref s) = *s.value() {
            s
        } else {
            return Err(RenderError::new(
                "the provided line separator for the code lines was \
                 not a string",
            ));
        }
    } else {
        "<br>"
    };

    let line_count = count(code.as_bytes(), b'\n');
    let mut rendered = String::with_capacity((line_separator.len() + 1) * line_count);
    for l in 1..=line_count {
        rendered.push_str(format!("{}", l).as_str());
        rendered.push_str(line_separator);
    }
    out.write(&rendered)?;

    Ok(())
}

/// Generates all the HTML for the given code.
///
/// An optional line separator can be added that will be used at the end of each line. By default,
/// this separator will be `<br>`.
pub fn all_code(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let code = h
        .param(0)
        .and_then(|v| v.value().as_str())
        .ok_or_else(|| RenderError::new("the code must be a string"))?;
    let line_separator = if let Some(s) = h.param(1) {
        if let Value::String(ref s) = *s.value() {
            s
        } else {
            return Err(RenderError::new(
                "the provided line separator for the code lines was \
                 not a string",
            ));
        }
    } else {
        "<br>"
    };

    for (i, line) in code.lines().enumerate() {
        let (indent, line) = split_indent(line);
        let line = format!(
            "<code id=\"code-line-{}\">{}<span \
             class=\"line_body\">{}</span></code>{}",
            i + 1,
            indent,
            html_escape(line),
            line_separator
        );
        out.write(&line)?;
    }

    Ok(())
}

/// Generates HTML code for affected code in a vulnerability.
///
/// For lines without vulnerable code, only the line plus the optional separator (by default `<br>`)
/// will be rendered. For vulnerable lines, the following code will be generated:
///
/// ```html
/// <code class="vulnerable_line {{ criticality }}">{{ indent }}
/// <span class="line_body">{{ code }}</span></code>{{ line_separator }}
/// ```
///
/// This enables easy styling of the code in templates.
pub fn html_code(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let vulnerability = h
        .param(0)
        .and_then(|v| v.value().as_object())
        .ok_or_else(|| {
            RenderError::new(
                "to generate the vulnerability index, the first parameter must be a \
                 vulnerability",
            )
        })?;

    let line_separator = if let Some(s) = h.param(1) {
        if let Value::String(ref s) = *s.value() {
            s
        } else {
            return Err(RenderError::new(
                "the provided line separator for the code lines was \
                 not a string",
            ));
        }
    } else {
        "<br>"
    };

    let (start_line, end_line) = if let Some(l) = vulnerability.get("line") {
        let line = l.as_i64().unwrap();
        (line, line)
    } else {
        let start_line = vulnerability.get("start_line").unwrap().as_i64().unwrap();
        let end_line = vulnerability.get("end_line").unwrap().as_i64().unwrap();
        (start_line, end_line)
    };

    let iter_start = if start_line > 5 { start_line - 4 } else { 1 };

    for (i, line) in vulnerability
        .get("code")
        .unwrap()
        .as_str()
        .unwrap()
        .lines()
        .enumerate()
    {
        let line_number = i + iter_start as usize;

        let rendered = if line_number >= start_line as usize && line_number <= end_line as usize {
            let (indent, code) = split_indent(line);
            format!(
                "<code class=\"vulnerable_line {}\">{}<span \
                 class=\"line_body\">{}</span></code>{}",
                vulnerability.get("criticality").unwrap().as_str().unwrap(),
                indent,
                html_escape(code),
                line_separator
            )
        } else {
            format!("{}{}", html_escape(line), line_separator)
        };

        out.write(&rendered)?;
    }

    Ok(())
}

/// Generates the report index for the given vulnerability.
///
/// E.g.: for a critical vulnerability in an application with between 100 and 200 vulnerability,
/// for the critical vulnerability number 12 it would produce `C012`.
#[allow(clippy::cast_precision_loss)]
pub fn report_index(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let vulnerability = h
        .param(0)
        .and_then(|v| v.value().as_object())
        .ok_or_else(|| {
            RenderError::new(
                "to generate the vulnerability index, the first parameter must be a vulnerability",
            )
        })?;
    let index = h.param(1).and_then(|v| v.value().as_u64()).ok_or_else(|| {
        RenderError::new(
            "the index of the vulnerability in the current list must be the second parameter",
        )
    })? as usize
        + 1;

    let list_len = h.param(2).unwrap().value().as_u64().unwrap();
    let char_index = vulnerability
        .get("criticality")
        .unwrap()
        .as_str()
        .unwrap()
        .to_uppercase()
        .chars()
        .next()
        .unwrap();

    let mut index_padding = (list_len as f64 + 1_f64).log10().ceil() as usize + 1;
    if index_padding < 2 {
        index_padding = 2;
    }
    let rendered = format!("{}{:#02$}", char_index, index, index_padding);
    out.write(&rendered)?;

    Ok(())
}

/// Generates the menu for the source tree.
///
/// It will generate an unordered HTML list (`<ul>…</ul>`) where all files and folders of the given
/// menu object.
pub fn generate_menu(
    h: &Helper<'_, '_>,
    _: &Registry,
    _: &Context,
    _: &mut RenderContext<'_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let menu = h
        .param(0)
        .and_then(|m| m.value().as_array())
        .ok_or_else(|| {
            RenderError::new("to generate the menu, the first parameter must be a menu array")
        })?;
    out.write("<ul>")?;
    render_menu(menu, out)?;
    out.write("</ul>")?;
    Ok(())
}

fn render_menu(menu: &[Value], renderer: &mut dyn Output) -> Result<(), RenderError> {
    for value in menu {
        if let Value::Object(ref item) = *value {
            renderer.write("<li>")?;
            let name = item
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| RenderError::new("invalid menu object type"))?;
            if let Some(&Value::Array(ref menu)) = item.get("menu") {
                renderer.write(
                    format!(
                        "<a href=\"#\" title=\"{0}\"><img src=\"../img/folder.svg\">{0}</a>",
                        name
                    )
                    .as_str(),
                )?;
                renderer.write("<ul>")?;

                render_menu(menu, renderer)?;
                renderer.write("</ul>")?;
            } else {
                let path = item
                    .get("path")
                    .and_then(Value::as_str)
                    .ok_or_else(|| RenderError::new("invalid menu object type"))?;
                let file_type = item
                    .get("type")
                    .and_then(Value::as_str)
                    .ok_or_else(|| RenderError::new("invalid menu object type"))?;
                renderer.write(
                    format!(
                        "<a href=\"{1}.html\" title=\"{0}\" target=\"code\"><img src=\"../img/{2}.svg\">{0}</a>",
                        name, path, file_type
                    ).as_str()
                )?;
            }
            renderer.write("</li>")?;
        } else {
            return Err(RenderError::new("invalid menu object type"));
        }
    }
    Ok(())
}