To address issues that do not require attention run npm audit fix

To address issues that do not require attention run npm audit fix

How to fix npm vulnerabilities manually?

However, npm audit fix outputs up to date in 11s fixed 0 of 33 vulnerabilities in 24653 scanned packages 33 vulnerabilities required manual review and could not be updated

Does that review mean it is not supposed to be fixed by user?

When I run npm audit it gives me list of tables, similar to this:

and no more lodash dependencies. So it should already be v4.17.5. I also checked /node_modules/lodash/lodash.json which has var VERSION = ‘4.17.10’; line. In /node_modules/lodash/package.json there are these lines:

I believe that version shown in «_id», not in «_from», so versions are correct but vulnerability still appear in audit list.

I’m still new in node.js and those messages confuses me a lot. Is there any way to fix it manually or get rid of those messages, I can’t do anything with?

To address issues that do not require attention run npm audit fix. Смотреть фото To address issues that do not require attention run npm audit fix. Смотреть картинку To address issues that do not require attention run npm audit fix. Картинка про To address issues that do not require attention run npm audit fix. Фото To address issues that do not require attention run npm audit fix

7 Answers 7

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

lodash-cli in devDependencies doesn’t affect how browser-sync works in your project, devDependencies are ignored when a package is installed as a dependency.

What audit report says is that it’s easy-extender that has lodash dependency:

audit report importance should be evaluated manually. Even if nested dependency has security risk, this doesn’t mean that a feature that introduces this risk was used. This also doesn’t mean that even if it’s used, it introduces real risk due to how it’s used.

browser-sync is development tool that isn’t used in production, there are not so many scenarios where its vulnerabilities could be exploited. And Prototype Pollution isn’t a vulnerability at all, just a notice that a package doesn’t follow good practices, it can be ignored.

Generally, this is the way to fix reported vulnerabilities:

Most times it’s expected that you won’t advance beyond a sanity check, and the only problem is that a «vulnerability» clutters audit report and conceals real vulnerabilities.

patch-package can help to patch nested dependencies in-place but this won’t affect the report.

It’s possible to force specific dependency version in nested dependency in Yarn 1 and 2 with resolutions field, this will affect audit report. It may be possible to do this natively in NPM in future. Currently the alternative in NPM is third-party npm-force-resolutions utility that gives less control, currently it forces a resolution for all dependencies, not a specific one.

npm-audit

Table of contents

The audit command submits a description of the dependencies configured in your project to your default registry and asks for a report of known vulnerabilities. If any vulnerabilities are found, then the impact and appropriate remediation will be calculated. If the fix argument is provided, then remediations will be applied to the package tree.

The command will exit with a 0 exit code if no vulnerabilities were found.

To ensure the integrity of packages you download from the public npm registry, or any registry that supports signatures, you can verify the registry signatures of downloaded packages using the npm CLI.

Registry signatures can be verified using the following audit command:

The npm CLI supports registry signatures and signing keys provided by any registry if the following conventions are followed:

See this example of a signed package from the public npm registry.

There are two audit endpoints that npm may use to fetch vulnerability information: the Bulk Advisory endpoint and the Quick Audit endpoint.

Bulk Advisory Endpoint

As of version 7, npm uses the much faster Bulk Advisory endpoint to optimize the speed of calculating audit results.

If the registry responds with an error, or with an invalid response, then npm will attempt to load advisory data from the Quick Audit endpoint.

npm then uses these advisory objects to calculate vulnerabilities and meta-vulnerabilities of the dependencies within the tree.

Quick Audit Endpoint

If the Bulk Advisory endpoint returns an error, or invalid data, npm will attempt to load advisory data from the Quick Audit endpoint, which is considerably slower in most cases.

The full package tree as found in package-lock.json is submitted, along with the following pieces of additional metadata:

All packages in the tree are submitted to the Quick Audit endpoint. Omitted dependency types are skipped when generating the report.

Out of an abundance of caution, npm versions 5 and 6 would «scrub» any packages from the submitted report if their name contained a / character, so as to avoid leaking the names of potentially private packages or git URLs.

However, in practice, this resulted in audits often failing to properly detect meta-vulnerabilities, because the tree would appear to be invalid due to missing dependencies, and prevented the detection of vulnerabilities in package trees that used git dependencies or private modules.

This scrubbing has been removed from npm as of version 7.

Calculating Meta-Vulnerabilities and Remediations

npm uses the @npmcli/metavuln-calculator module to turn a set of security advisories into a set of «vulnerability» objects. A «meta-vulnerability» is a dependency that is vulnerable by virtue of dependence on vulnerable versions of a vulnerable package.

Once metavulnerabilities for a given package are calculated, they are cached in the

/.npm folder and only re-evaluated if the advisory range changes, or a new version of the package is published (in which case, the new version is checked for metavulnerable status as well).

The npm audit command will exit with a 0 exit code if no vulnerabilities were found. The npm audit fix command will exit with 0 exit code if no vulnerabilities are found or if the remediation is able to successfully fix all vulnerabilities.

If vulnerabilities were found the exit code will depend on the audit-level configuration setting.

Scan your project for vulnerabilities and automatically install any compatible updates to vulnerable dependencies:

Skip updating devDependencies :

Have audit fix install SemVer-major updates to toplevel dependencies, not just SemVer-compatible ones:

Do a dry run to get an idea of what audit fix will do, and also output install information in JSON format:

Scan your project for vulnerabilities and just show the details, without fixing anything:

Get the detailed audit report in JSON format:

Fail an audit only if the results include a vulnerability with a level of moderate or higher:

The minimum level of vulnerability for npm audit to exit with a non-zero exit code.

Removes various protections against unfortunate side effects, common mistakes, unnecessary performance degradation, and malicious input.

If you don’t have a clear idea of what you want to do, it is strongly recommended that you do not use this option!

Whether or not to output JSON data, rather than the normal output.

Not supported by all npm commands.

For update this means only the package-lock.json will be updated, instead of checking node_modules and downloading dependencies.

Dependency types to omit from the installation tree on disk.

Note that these dependencies are still resolved and added to the package-lock.json or npm-shrinkwrap.json file. They are just not physically installed on disk.

Note that this will generally make installs run slower, and be much noisier, but can be useful for debugging.

If true, npm does not run scripts specified in package.json files.

Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option.

Valid values for the workspace config are either:

When set for the npm init command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project.

This value is not exported to the environment for child processes.

Set to true to run the command in the context of all configured workspaces.

Explicitly setting this to false will cause commands like install to ignore workspaces altogether. When not set explicitly:

This value is not exported to the environment for child processes.

Include the workspace root when workspaces are enabled for a command.

When false, specifying individual workspaces via the workspace config, or all workspaces via the workspaces flag, will cause npm to operate only on the specified workspaces, and not on the root project.

This value is not exported to the environment for child processes.

When set file: protocol dependencies that exist outside of the project root will be packed and installed as regular dependencies instead of creating a symlink. This option has no effect on workspaces.

npm audit работает неправильно — это настоящий театр безопасности

Думаю, придётся мне.

npm audit работает принципиально неправильно. Проверка по умолчанию на каждый npm install — поспешный, непродуманный и неадекватный подход.

Слышали историю про мальчика, который часто кричал «Волк!»? Спойлер: в результате волк съел овец. Если мы не хотим такого итога, нам нужны лучшие инструменты.

Как работает npm audit?

У приложения Node.js есть дерево зависимостей. Оно может выглядеть следующим образом:

Скорее всего, дерево гораздо глубже.

Теперь предположим, что обнаружена уязвимость в network-utility@1.0.0 :

Вот как должен работать npm audit в теории.

Как сказал кто-то мудрый, в теории нет разницы между теорией и практикой. Но разница есть на практике. И вот тут начинается самое интересное.

Почему это неправильный подход

Посмотрим, что происходит на практике. Для тестирования возьмём Create React App. Этот набор включает множество инструментов, в том числе Babel, webpack, TypeScript, ESLint, PostCSS, Terser и другие. Create React App берёт ваш исходный код JavaScript — и преобразует в статичную папку HTML+JS+CSS. Примечательно, что он не создаёт приложение Node.js.

Итак, делаем новый проект!

Сразу после создания проекта видим следующее:

Чёрт побери! В только что созданном приложении уже уязвимости!

Так говорит npm.

Запустим npm audit и посмотрим, что случилось.

Первая «уязвимость»

Вот первая проблема, о которой сообщает npm audit :

Тогда он уберёт из выдачи устаревшие хаки flexbox. Поскольку множество инструментов полагаются на один и тот же формат конфигурации целевых браузеров, Create React App использует общий пакет browserslist для парсинга файла конфигурации.

Итак, я полагаю, что эта «умеренная» «уязвимость» не является ни умеренной, ни уязвимостью в контексте проекта. Проехали.

Вердикт: эта «уязвимость» абсурдна в данном контексте.

Вторая «уязвимость»

Вот следующая проблема, о которой с готовностью сообщил npm audit :

К сожалению, glob-parent уязвим! Если злоумышленник предоставит специально созданный путь к файлу, он может сделать эту функцию экспоненциально медленной, что приведёт к…

Погодите, что?! Сервер разработки находится на вашем компьютере. Файлы находятся на вашем компьютере. Файл-вотчер использует указанную вами конфигурацию. Ни одна из этих конструкций не покидает ваш компьютер. Если злоумышленник достаточно изощрён, чтобы войти на вашу машину во время локальной разработки, последнее, что он захочет сделать, это создать специальные длинные пути к файлам, чтобы замедлить вашу разработку. Так что эта угроза просто абсурдна.

Похоже, что эта «умеренная» «уязвимость» не является ни умеренной, ни уязвимостью в контексте проекта.

Вердикт: эта «уязвимость» абсурдна в данном контексте.

Третья «уязвимость»

Давайте посмотрим на это:

Подождите, это то же самое, что и выше, но через другой путь зависимости.

Вердикт: эта «уязвимость» абсурдна в данном контексте.

Четвёртая «уязвимость»

Уф, выглядит очень плохо! npm audit осмелился показать её красным цветом:

Что это за проблема «высокой» важности? «Отказ в обслуживании»? Я не хочу, чтобы в обслуживании было отказано! Это будет очень плохо… Если только…

Давайте посмотрим внимательнее на проблему. Очевидно, что парсер для CSS-селекторов css-what может замедлиться при получении специально созданных входных данных. Этот парсер используется плагином, который генерирует компоненты React из SVG-файлов.

Это означает, что если злоумышленник получит контроль над моей машиной разработки или моим исходным кодом, он поместит специальный SVG-файл, в котором будет находиться специально созданный CSS-селектор, что сделает мою сборку медленной. Уязвимость проверена и подтверждена…

Подождите, что?! Если злоумышленник может изменить исходный код моего приложения, то просто добавит туда криптомайнер. Зачем добавлять файлы SVG, если только они не майнят монеро? Опять же, в этом никакого смысла.

Вердикт: «уязвимость» абсурдна в данном контексте.

Вот вам и «высокая» важность.

Пятая «уязвимость»

Вердикт: эта «уязвимость» абсурдна в данном контексте.

Продолжать?

Мальчик уже пять раз прокричал «Волк!». Два предупреждения — это дубли. Остальные абсурдны и не имеют значения в контексте использования этих зависимостей.

Пять ложноположительных срабатываний — не так уж плохо.

К сожалению, их сотни.

To address issues that do not require attention run npm audit fix. Смотреть фото To address issues that do not require attention run npm audit fix. Смотреть картинку To address issues that do not require attention run npm audit fix. Картинка про To address issues that do not require attention run npm audit fix. Фото To address issues that do not require attention run npm audit fix

Я потратил несколько часов, но изучил абсолютно все проблемы, о которых сообщил npm audit за последние несколько месяцев, и похоже, что все они являются ложными срабатываниями в контексте такого инструмента для сборки, как Create React App, в виде «набора зависимостей».

Конечно, их можно исправить. Можно ослабить некоторые зависимости верхнего уровня, расширив «фокус» вместо указания конкретных версий (что приведёт к более частому проскальзыванию багов в патчи). Можно участить релизы, чтобы этот театр безопасности никогда нас не догнал.

Но этого недостаточно. Представьте, если б ваши тесты в 99% случаев не срабатывали по надуманным причинам! Это бесполезная трата многих человеко-лет и совершенно лишние проблемы. Причём страдают все категории:

Что делать?

Я не знаю, как решить проблему. Не я её создал, так что не мне решать. Знаю только то, что нынешняя система не работает.

Есть несколько возможных решений.

Нужно что-то делать.

Сейчас npm audit сломан.

Новички, опытные разработчики, мейнтейнеры, отделы безопасности и, самое главное, наши пользователи — заслуживают лучшего.

npm-audit

Table of contents

The audit command submits a description of the dependencies configured in your project to your default registry and asks for a report of known vulnerabilities. If any vulnerabilities are found, then the impact and appropriate remediation will be calculated. If the fix argument is provided, then remediations will be applied to the package tree.

The command will exit with a 0 exit code if no vulnerabilities were found.

There are two audit endpoints that npm may use to fetch vulnerability information: the Bulk Advisory endpoint and the Quick Audit endpoint.

Bulk Advisory Endpoint

As of version 7, npm uses the much faster Bulk Advisory endpoint to optimize the speed of calculating audit results.

If the registry responds with an error, or with an invalid response, then npm will attempt to load advisory data from the Quick Audit endpoint.

npm then uses these advisory objects to calculate vulnerabilities and meta-vulnerabilities of the dependencies within the tree.

Quick Audit Endpoint

If the Bulk Advisory endpoint returns an error, or invalid data, npm will attempt to load advisory data from the Quick Audit endpoint, which is considerably slower in most cases.

The full package tree as found in package-lock.json is submitted, along with the following pieces of additional metadata:

All packages in the tree are submitted to the Quick Audit endpoint. Omitted dependency types are skipped when generating the report.

Out of an abundance of caution, npm versions 5 and 6 would «scrub» any packages from the submitted report if their name contained a / character, so as to avoid leaking the names of potentially private packages or git URLs.

However, in practice, this resulted in audits often failing to properly detect meta-vulnerabilities, because the tree would appear to be invalid due to missing dependencies, and prevented the detection of vulnerabilities in package trees that used git dependencies or private modules.

This scrubbing has been removed from npm as of version 7.

Calculating Meta-Vulnerabilities and Remediations

npm uses the @npmcli/metavuln-calculator module to turn a set of security advisories into a set of «vulnerability» objects. A «meta-vulnerability» is a dependency that is vulnerable by virtue of dependence on vulnerable versions of a vulnerable package.

Once metavulnerabilities for a given package are calculated, they are cached in the

/.npm folder and only re-evaluated if the advisory range changes, or a new version of the package is published (in which case, the new version is checked for metavulnerable status as well).

The npm audit command will exit with a 0 exit code if no vulnerabilities were found. The npm audit fix command will exit with 0 exit code if no vulnerabilities are found or if the remediation is able to successfully fix all vulnerabilities.

If vulnerabilities were found the exit code will depend on the audit-level configuration setting.

Scan your project for vulnerabilities and automatically install any compatible updates to vulnerable dependencies:

Skip updating devDependencies :

Have audit fix install SemVer-major updates to toplevel dependencies, not just SemVer-compatible ones:

Do a dry run to get an idea of what audit fix will do, and also output install information in JSON format:

Scan your project for vulnerabilities and just show the details, without fixing anything:

Get the detailed audit report in JSON format:

Fail an audit only if the results include a vulnerability with a level of moderate or higher:

The minimum level of vulnerability for npm audit to exit with a non-zero exit code.

Removes various protections against unfortunate side effects, common mistakes, unnecessary performance degradation, and malicious input.

If you don’t have a clear idea of what you want to do, it is strongly recommended that you do not use this option!

Whether or not to output JSON data, rather than the normal output.

Not supported by all npm commands.

For update this means only the package-lock.json will be updated, instead of checking node_modules and downloading dependencies.

Dependency types to omit from the installation tree on disk.

Note that these dependencies are still resolved and added to the package-lock.json or npm-shrinkwrap.json file. They are just not physically installed on disk.

Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option.

Valid values for the workspace config are either:

When set for the npm init command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project.

This value is not exported to the environment for child processes.

Enable running a command in the context of all the configured workspaces.

This value is not exported to the environment for child processes.

6 high severity vulnerabilities #114

Comments

h-enk commented Jun 21, 2021

The text was updated successfully, but these errors were encountered:

XhmikosR commented Jun 22, 2021 •

There’s only one vulnerability which cannot be fixed on our side kevva/download#216

The rest can be fixed by running npm audit fix or regenerating package-lock.json.

h-enk commented Jun 22, 2021

From the audit report: Will install hugo-bin@0.30.0, which is a breaking change — not what I want.

The rest can be fixed by running npm audit fix or regenerating package-lock.json.

No, unfortunately not: running npm audit fix [—force] is only making things worse:

XhmikosR commented Jun 22, 2021

I cannot reproduce. Like I said, there’s only one vulnerability for me using Node.js 14.x/npm 6.x which is the current LTS.

h-enk commented Jun 22, 2021

I think bin-wrapper@4.1.0 really is a problem — see also: https://snyk.io/test/npm/hugo-bin

XhmikosR commented Jun 22, 2021

Either way, there’s nothing we can do at this point. This needs to be fixed upstream.

h-enk commented Jun 22, 2021

Either way, there’s nothing we can do at this point.

Knowing the last commit to bin-wrapper was Nov 7, 2018, would make a case looking for a replacement.

XhmikosR commented Jun 22, 2021

Again, nothing I can do. You are welcome to propose a solid PR, but I’m not going to just replace the package myself.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *