use crate::analyzer::hadolint::parser::instruction::Instruction;
use crate::analyzer::hadolint::rules::{SimpleRule, simple_rule};
use crate::analyzer::hadolint::shell::ParsedShell;
use crate::analyzer::hadolint::types::Severity;
pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
simple_rule(
"DL3016",
Severity::Warning,
"Pin versions in npm. Instead of `npm install <package>` use `npm install <package>@<version>`.",
|instr, shell| {
match instr {
Instruction::Run(_) => {
if let Some(shell) = shell {
!shell.any_command(|cmd| {
if cmd.name == "npm" && cmd.has_any_arg(&["install", "i"]) {
let packages = get_npm_packages(cmd);
packages.iter().any(|pkg| !is_pinned_npm_package(pkg))
} else {
false
}
})
} else {
true
}
}
_ => true,
}
},
)
}
fn get_npm_packages(cmd: &crate::analyzer::hadolint::shell::Command) -> Vec<&str> {
let mut packages = Vec::new();
let mut found_install = false;
for arg in &cmd.arguments {
if arg == "install" || arg == "i" {
found_install = true;
continue;
}
if found_install && !arg.starts_with('-') {
packages.push(arg.as_str());
}
}
packages
}
fn is_pinned_npm_package(pkg: &str) -> bool {
if pkg.starts_with('-') {
return true;
}
if pkg.starts_with('.') || pkg.starts_with('/') || pkg.starts_with("file:") {
return true;
}
if pkg.starts_with("git") || pkg.contains("github.com") || pkg.contains("gitlab.com") {
return true;
}
if pkg.contains('@') {
let parts: Vec<&str> = pkg.split('@').collect();
if pkg.starts_with('@') {
parts.len() >= 3
} else {
parts.len() >= 2 && !parts[1].is_empty()
}
} else {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analyzer::hadolint::config::HadolintConfig;
use crate::analyzer::hadolint::lint::{LintResult, lint};
fn lint_dockerfile(content: &str) -> LintResult {
lint(content, &HadolintConfig::default())
}
#[test]
fn test_npm_install_unpinned() {
let result = lint_dockerfile("FROM node:18\nRUN npm install express");
assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
#[test]
fn test_npm_install_pinned() {
let result = lint_dockerfile("FROM node:18\nRUN npm install express@4.18.2");
assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
#[test]
fn test_npm_install_pinned_caret() {
let result = lint_dockerfile("FROM node:18\nRUN npm install express@^4.18.0");
assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
#[test]
fn test_npm_ci() {
let result = lint_dockerfile("FROM node:18\nRUN npm ci");
assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
#[test]
fn test_npm_install_global_unpinned() {
let result = lint_dockerfile("FROM node:18\nRUN npm install -g typescript");
assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
#[test]
fn test_npm_install_global_pinned() {
let result = lint_dockerfile("FROM node:18\nRUN npm install -g typescript@5.0.0");
assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3016"));
}
}