Snyk CLI
The `snyk` npm package provides the Snyk Command Line Interface (CLI), a developer-first, cloud-native security tool designed to integrate vulnerability scanning and monitoring into the software development workflow. It identifies and helps fix security issues across various content types, including open-source dependencies (Snyk Open Source), proprietary application code (Snyk Code), container images (Snyk Container), and Infrastructure as Code (Snyk IaC). The CLI is currently at version 1.1304.0 and is updated very frequently, often with multiple releases per month, sometimes weekly, to deliver new features, bug fixes, and security enhancements. Its key differentiators include broad scanning capabilities for diverse project types, seamless integration into local development environments and CI/CD pipelines, and comprehensive reporting with actionable fix guidance. While the package itself contains internal library components, its primary public interface and intended use are via the command line.
Common errors
-
snyk: command not found
cause The Snyk CLI is not installed globally or is not in the system's PATH, or `npx` is not available.fixInstall Snyk globally using `npm install -g snyk` or `yarn global add snyk`. Alternatively, run Snyk commands using `npx snyk <command>`. -
Authentication failed. Please check the API token on https://snyk.io
cause The Snyk API token is missing, invalid, or expired, or the user is not a member of a Snyk organization.fixAuthenticate your machine with `snyk auth` and provide your Snyk API token. Ensure the token is valid and belongs to a user who is a member of an organization in Snyk.io. For CI/CD, ensure `SNYK_TOKEN` environment variable is correctly set. -
Failed to get vulns
cause This generic error can indicate several issues, including authentication problems, a project being too large for scanning, or internal CLI errors.fixFirst, verify authentication with `snyk auth`. If persistent, try scanning a smaller, simpler project. Consider adding `--debug` (`-d`) flag for more detailed logs. For very large projects, 'pruning' the dependency tree might help. -
No supported projects detected
cause Snyk CLI could not find any recognizable manifest files (e.g., `package.json`, `pom.xml`, `Dockerfile`) in the current directory or specified path, or the project was not built (dependencies not installed).fixEnsure you are running Snyk in a directory containing supported project files. For Open Source projects, run your package manager's install command (`npm install`, `yarn install`, `mvn install`) beforehand. Use `--file=<FILE_PATH>` to specify a manifest, or `--all-projects` for monorepos. -
JSON output was incorrectly printed to stdout when only --json-file-output was specified
cause A bug in older Snyk CLI versions caused JSON output to be incorrectly printed to stdout even when directed to a file.fixUpgrade Snyk CLI to version 1.1303.1 or later, which includes a fix for this bug.
Warnings
- breaking Snyk CLI versions prior to 1.1191.0 had an issue where authentication in certain environments (e.g., containers/pipelines) might fail due to incorrect reliance on a `TOKEN` environment variable.
- breaking The Snyk CLI is closed to external contributions as of July 22, 2024. While the project remains open-source for transparency, direct pull requests are no longer accepted.
- breaking Older versions of the `snyk` package (before 1.1064.0) were vulnerable to Command Injection (CVE-2022-22984). An incomplete fix for CVE-2022-40764 allowed attackers to run arbitrary commands by crafting command line flags, potentially in CI/CD pipelines.
- gotcha The Snyk CLI may automatically execute code (e.g., invoke package managers like npm, Gradle, Maven) as part of examining a codebase for vulnerabilities. Running `snyk test` on untrusted code with malicious configurations can expose your system to malicious code execution and exploits.
- gotcha For Snyk Open Source scanning, you must have the relevant package manager (e.g., npm, yarn, pip, Gradle, Maven) installed and available in your system's PATH. Snyk CLI cannot resolve dependencies without these third-party tools.
- gotcha Before testing an Open Source project for vulnerabilities, with limited exceptions, you must first build your project (e.g., `npm install`, `mvn install`). This ensures the dependency tree is fully resolved for Snyk to scan.
- gotcha The Snyk CLI's behavior can be influenced by different deployment channels, which users can select for varying stability levels. This could lead to inconsistencies or unexpected behavior if not managed properly.
Install
-
npm install snyk -
yarn add snyk -
pnpm add snyk
Imports
- Snyk CLI execution
import { exec } from 'child_process'; exec('snyk test --json', (err, stdout) => { /* handle output */ }); - Snyk API (via HTTP client)
import axios from 'axios'; axios.post('https://api.snyk.io/rest/orgs/{orgId}/test', { /* ... */ }, { headers: { 'Authorization': `token ${process.env.SNYK_TOKEN}` } }); - SnykCliArgs (Type Definition)
import type { SnykCliArgs } from 'snyk/dist/cli/commands/types';
Quickstart
import { exec } from 'child_process';
import path from 'path';
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
// Create a dummy package.json for demonstration purposes
const projectPath = path.join(process.cwd(), 'snyk-quickstart-project');
mkdirSync(projectPath, { recursive: true });
writeFileSync(path.join(projectPath, 'package.json'), JSON.stringify({
name: 'my-vulnerable-app',
version: '1.0.0',
dependencies: {
'lodash': '4.17.15', // A version known to have vulnerabilities
'express': '4.17.1' // A common dependency
}
}, null, 2));
console.log('Running Snyk CLI test on a dummy project...');
// Important: Ensure SNYK_TOKEN is set as an environment variable (e.g., in .env or CI/CD secrets).
// Use `npx snyk auth` to authenticate your machine with Snyk.
const snykCommand = `npx snyk test --json --file=${path.join(projectPath, 'package.json')}`;
exec(snykCommand, { cwd: projectPath, env: { ...process.env, SNYK_TOKEN: process.env.SNYK_TOKEN ?? '' } }, (error, stdout, stderr) => {
if (error) {
// Snyk CLI often exits with a non-zero code (e.g., 1 or 2) even if it successfully finds vulnerabilities,
// but 2 indicates a failure (e.g. CLI couldn't run).
// We should still try to parse stdout if code is 1.
console.error(`Snyk CLI exited with code ${error.code}. Message: ${error.message}`);
if (stderr) console.error('Stderr:', stderr);
if (error.code === 2) return; // True failure, no output to parse.
}
if (stdout) {
try {
const results = JSON.parse(stdout);
if (results.vulnerabilities && results.vulnerabilities.length > 0) {
console.log(`Snyk scan completed. Found ${results.vulnerabilities.length} vulnerabilities.`);
results.vulnerabilities.slice(0, 3).forEach((vuln: any) => {
console.log(`- [${vuln.severity.toUpperCase()}] ${vuln.title} (Package: ${vuln.packageName}@${vuln.version})`);
console.log(` Fix advice: ${vuln.fixedIn ? 'Upgrade to ' + vuln.fixedIn : 'No direct fix available.'}`);
});
} else {
console.log('Snyk scan completed. No vulnerabilities found.');
}
} catch (parseError) {
console.error('Failed to parse Snyk JSON output. Stdout:', stdout);
if (error) console.error('Original CLI Error:', error);
}
} else if (stderr) {
console.error('Snyk CLI outputted only to stderr (likely an error):', stderr);
} else {
console.log('Snyk CLI ran, but produced no direct output to stdout or stderr.');
}
});