npm auditでパッケージの脆弱性に対応する
そもそも脆弱性とは
プログラム上に存在する、セキュリティ上の欠陥のことを言います
脆弱性(ぜいじゃくせい、英: vulnerability)とは、情報セキュリティ・サイバーセキュリティの用語で、コンピュータに存在する情報セキュリティ上の欠陥をいう。セキュリティホールとも呼ばれる。
npm auditとは?
npm audit
とはNode.jsのパッケージマネージャであるnpmが提供するコマンドです。
プロジェクトにインストールされている依存関係のセキュリティ脆弱性をスキャンしてくれて、脆弱性が見つかったらレポートにして一覧してくれます。
npm auditを実行してみる
プロジェクトを使って実際にnpm audit
を実行していきます。
npm audit
脆弱性がない場合はこんな感じになります。
found 0 vulnerabilities
見つかった場合は
# npm audit report
dset <3.1.4
Severity: high
dset Prototype Pollution vulnerability - https://github.com/advisories/GHSA-f6v4-cf5j-vf3w
fix available via `npm audit fix`
node_modules/dset
micromatch <4.0.8
Severity: moderate
Regular Expression Denial of Service (ReDoS) in micromatch - https://github.com/advisories/GHSA-952p-6rrq-rcjv
fix available via `npm audit fix`
node_modules/micromatch
path-to-regexp 4.0.0 - 6.2.2
Severity: high
path-to-regexp outputs backtracking regular expressions - https://github.com/advisories/GHSA-9wv6-86v2-598j
fix available via `npm audit fix`
node_modules/path-to-regexp
3 vulnerabilities (1 moderate, 2 high)
今回は
- dset
- path-to-regexp
に重要度がhigh、
- micromatch
に重要度がmoderateとなっており
3つともにnpm audit fix
で解決が可能となっています。
脆弱性に対応する
対応方法は大きく以下の3つがあるようです。
- npm audit fix
- npm audit fix --force
- 手動で修正する
npm audit fixを実行する
まずは解決可能となっているnpm audit fix
を実行してみます。
npm audit fix
なんかすごい量のエラーができてきました。
npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: typescript-eslint@7.12.0
npm error Found: eslint@9.4.0
npm error node_modules/eslint
依存関係を解決できない場合に発生するエラーだそうです。
npm audit fix --forceを実行する
npm audit fix --force
found 0 vulnerabilities
今回は無事に解決できたみたいです。
※ただし、npm audit fix --force
を実行しての解決は依存関係の競合を無視して強制的にアップデートするため、プロジェクト自体に不具合が発生する可能性があるので注意が必要です。
手動で修正する
まずはnpm ls [package]
で依存関係を調べます
npm ls micromatch
プロジェクト
├─┬ astro@3.6.5
│ ├─┬ fast-glob@3.3.2
│ │ └── micromatch@4.0.7 deduped
│ └─┬ preferred-pm@3.1.4
│ └─┬ find-yarn-workspace-root2@1.2.16
│ └── micromatch@4.0.7 deduped
└─┬ tailwindcss@3.4.7
└── micromatch@4.0.7
他の2つも調べてみましたが
- astro@3.6.5
- tailwindcss@3.4.7
に依存が依存しているパッケージに問題があることがわかりました。
まずはastroとtailwindをバージョンアップしてみようと思います。
npm view astro
パッケージをインストールし直す
npm uninstall astro tailwindcss
npm install astro tailwindcss
手動でアップデートしてみましたがエラーが全てなくなりませんでした。
# npm audit report
path-to-regexp 4.0.0 - 6.2.2
Severity: high
path-to-regexp outputs backtracking regular expressions - https://github.com/advisories/GHSA-9wv6-86v2-598j
fix available via `npm audit fix --force`
Will install astro@4.15.5, which is a breaking change
node_modules/path-to-regexp
astro >=4.15.6
Depends on vulnerable versions of path-to-regexp
node_modules/astro
2 high severity vulnerabilities
npm audit fix --force
で解決可能ですと出ているので実行して確認したところエラーは出なくなりました。
最後にnpm install
を実行しプロジェクト自体に不具合が出ていないかを確認して終了です。
npm install
まとめ
パッケージの脆弱性は普段あまり気にせずにいるので放置しがちですが
たまに出てくるとドキッとしてしまいますが対処方法を知ってるだけで全然気持ちが違うなと思う次第です。
今回の方法以外にも
package-lock.json
を書き換える(正攻法ではないので注意です。)- 別のパッケージを利用する
- 対応を保留する
などがあるようですので恐れることなくWARN
やERROR
に立ち向かえるようになりたいものです。