Skip to content

Commit f7b4930

Browse files
terrikoimsahil007
andauthored
feat: retry if NVD API Key is invalid (#1574)
Co-authored-by: Sahil <[email protected]>
1 parent 9c73442 commit f7b4930

File tree

4 files changed

+38
-1
lines changed

4 files changed

+38
-1
lines changed

.github/workflows/testing.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ on:
1313
env:
1414
ACTIONS: 1
1515
LONG_TESTS: 0
16+
nvd_api_key: ${{ secrets.NVD_API_KEY }}
1617

1718
jobs:
1819
docs:

cve_bin_tool/cli.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,10 @@ def main(argv=None):
351351
if not args["nvd_api_key"] and os.getenv("nvd_api_key"):
352352
args["nvd_api_key"] = os.getenv("nvd_api_key")
353353

354+
# Also try the uppercase env variable, in case people prefer those
355+
if not args["nvd_api_key"] and os.getenv("NVD_API_KEY"):
356+
args["nvd_api_key"] = os.getenv("NVD_API_KEY")
357+
354358
# If you're not using an NVD key, let you know how to get one
355359
if not args["nvd_api_key"] and not args["offline"]:
356360
LOGGER.info("Not using an NVD API key. Your access may be rate limited by NVD.")

cve_bin_tool/error_handler.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,12 @@ class NVDServiceError(Exception):
8888
"""
8989

9090

91+
class NVDKeyError(Exception):
92+
"""
93+
Raised if the NVD API key is invalid.
94+
"""
95+
96+
9197
class SHAMismatch(Exception):
9298
"""
9399
Raised if the sha of a file in the cache was not what it should be.

cve_bin_tool/nvd_api.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from rich.progress import Progress, track
2020

2121
from cve_bin_tool.async_utils import RateLimiter
22-
from cve_bin_tool.error_handler import ErrorMode, NVDServiceError
22+
from cve_bin_tool.error_handler import ErrorMode, NVDKeyError, NVDServiceError
2323
from cve_bin_tool.log import LOGGER
2424

2525
FEED = "https://services.nvd.nist.gov/rest/json/cves/1.0"
@@ -102,6 +102,9 @@ async def get_nvd_params(
102102
self.logger.debug("Fetching metadata from NVD...")
103103
cve_count = await self.nvd_count_metadata(self.session)
104104

105+
if "apiKey" in self.params:
106+
await self.validate_nvd_api()
107+
105108
if time_of_last_update:
106109
# Fetch all the updated CVE entries from the modified date. Subtracting 2-minute offset for updating cve entries
107110
self.params["modStartDate"] = self.convert_date_to_nvd_date(
@@ -125,6 +128,28 @@ async def get_nvd_params(
125128
self.total_results = cve_count["Total"] - cve_count["Rejected"]
126129
self.logger.info(f"Adding {self.total_results} CVE entries")
127130

131+
async def validate_nvd_api(self):
132+
"""
133+
Validate NVD API
134+
"""
135+
param_dict = self.params.copy()
136+
param_dict["startIndex"] = 0
137+
param_dict["resultsPerPage"] = 1
138+
try:
139+
self.logger.debug("Validating NVD API...")
140+
async with await self.session.get(
141+
self.feed, params=param_dict, raise_for_status=True
142+
) as response:
143+
data = await response.json()
144+
if data.get("error", False):
145+
self.logger.error(f"NVD API error: {data['error']}")
146+
raise NVDKeyError(self.params["apiKey"])
147+
except NVDKeyError:
148+
# If the API key provided is invalid, delete from params
149+
# list and try the request again.
150+
self.logger.error("unset api key, retrying")
151+
del self.params["apiKey"]
152+
128153
async def load_nvd_request(self, start_index):
129154
"""Get single NVD request and update year_wise_data list which contains list of all CVEs"""
130155

@@ -141,6 +166,7 @@ async def load_nvd_request(self, start_index):
141166
) as response:
142167
if response.status == 200:
143168
fetched_data = await response.json()
169+
144170
if start_index == 0:
145171
# Update total results in case there is discrepancy between NVD dashboard and API
146172
self.total_results = fetched_data["totalResults"]

0 commit comments

Comments
 (0)