Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Set last_update_date to the time reported by the REST endpoint #2672

Merged
merged 6 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 25 additions & 17 deletions docker/importer/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,35 +704,44 @@ def _process_updates_rest(self, source_repo: osv.SourceRepository):
"""Process updates from REST API."""
andrewpollock marked this conversation as resolved.
Show resolved Hide resolved
logging.info('Begin processing REST: %s', source_repo.name)

ignore_last_import_time = (
source_repo.ignore_last_import_time or not source_repo.last_update_date)
if ignore_last_import_time:
last_update_date = source_repo.last_update_date or datetime.datetime.min
if source_repo.ignore_last_import_time:
last_update_date = datetime.datetime.min
source_repo.ignore_last_import_time = False
source_repo.put()
import_time_now = utcnow()

request = requests.head(source_repo.rest_api_url, timeout=_TIMEOUT_SECONDS)
if request.status_code != 200:
logging.error('Failed to fetch REST API: %s', request.status_code)
return

if 'Last-Modified' in request.headers:
last_modified = datetime.datetime.strptime(
request.headers['Last-Modified'], _HTTP_LAST_MODIFIED_FORMAT)
# Check whether endpoint has been modified since last update
if not ignore_last_import_time and (last_modified
< source_repo.last_update_date):
logging.info('No changes since last update.')
return
request_last_modified = None
if last_modified := request.headers.get('Last-Modified'):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try:
request_last_modified = datetime.datetime.strptime(
last_modified, _HTTP_LAST_MODIFIED_FORMAT)
# Check whether endpoint has been modified since last update
if request_last_modified <= last_update_date:
logging.info('No changes since last update.')
return
except ValueError:
logging.error('Invalid Last-Modified header: "%s"', last_modified)

request = requests.get(source_repo.rest_api_url, timeout=_TIMEOUT_SECONDS)
andrewpollock marked this conversation as resolved.
Show resolved Hide resolved
# Parse vulns into Vulnerability objects from the REST API request.
vulns = osv.parse_vulnerabilities_from_data(
request.text, source_repo.extension, strict=self._strict_validation)

vulns_last_modified = last_update_date
# Create tasks for changed files.
for vuln in vulns:
import_failure_logs = []
if not ignore_last_import_time and vuln.modified.ToDatetime(
) < source_repo.last_update_date:
vuln_modified = vuln.modified.ToDatetime()
if request_last_modified and vuln_modified > request_last_modified:
logging.warning('%s was modified (%s) after Last-Modified header (%s)',
vuln.id, vuln_modified, request_last_modified)
vulns_last_modified = max(vulns_last_modified, vuln_modified)
if vuln_modified <= last_update_date:
continue
try:
# TODO(jesslowe): Use a ThreadPoolExecutor to parallelize this
Expand All @@ -754,14 +763,13 @@ def _process_updates_rest(self, source_repo: osv.SourceRepository):
except Exception as e:
logging.exception('Failed to parse %s: error type: %s, details: %s',
vuln.id, e.__class__.__name__, e)
import_failure_logs.append('Failed to parse vulnerability "' + vuln.id +
'"')
import_failure_logs.append(f'Failed to parse vulnerability "{vuln.id}"')
continue

replace_importer_log(storage.Client(), source_repo.name,
self._public_log_bucket, import_failure_logs)

source_repo.last_update_date = import_time_now
source_repo.last_update_date = request_last_modified or vulns_last_modified
another-rex marked this conversation as resolved.
Show resolved Hide resolved
source_repo.put()

logging.info('Finished processing REST: %s', source_repo.name)
Expand Down
17 changes: 12 additions & 5 deletions docker/importer/importer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,36 +849,40 @@ def test_all_updated(self, unused_mock_time: mock.MagicMock,
mock_publish: mock.MagicMock):
"""Testing basic rest endpoint import"""
data_handler = MockDataHandler
data_handler.last_modified = 'Mon, 01 Jan 2024 00:00:00 GMT'
data_handler.load_file(data_handler, 'rest_test.json')
self.httpd = http.server.HTTPServer(SERVER_ADDRESS, data_handler)
thread = threading.Thread(target=self.httpd.serve_forever)
thread.start()
self.source_repo.last_update_date = datetime.datetime(2020, 1, 1)
self.source_repo.put()
repo = self.source_repo.put()
imp = importer.Importer('fake_public_key', 'fake_private_key', self.tmp_dir,
importer.DEFAULT_PUBLIC_LOGGING_BUCKET, 'bucket',
False, False)
imp.run()
self.assertEqual(mock_publish.call_count, data_handler.cve_count)
self.assertEqual(repo.get().last_update_date, datetime.datetime(2024, 1, 1))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a msg attribute to this with a human-friendly string explaining the nature of the assertion failure to help with debugging test failures?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 9ce7a86


@mock.patch('google.cloud.pubsub_v1.PublisherClient.publish')
@mock.patch('time.time', return_value=12345.0)
def test_last_update_ignored(self, unused_mock_time: mock.MagicMock,
mock_publish: mock.MagicMock):
"""Testing last update ignored"""
data_handler = MockDataHandler
data_handler.last_modified = 'Mon, 01 Jan 2024 00:00:00 GMT'
data_handler.load_file(data_handler, 'rest_test.json')
self.httpd = http.server.HTTPServer(SERVER_ADDRESS, data_handler)
thread = threading.Thread(target=self.httpd.serve_forever)
thread.start()
self.source_repo.last_update_date = datetime.datetime(2023, 6, 6)
self.source_repo.ignore_last_import_time = True
self.source_repo.put()
repo = self.source_repo.put()
imp = importer.Importer('fake_public_key', 'fake_private_key', self.tmp_dir,
importer.DEFAULT_PUBLIC_LOGGING_BUCKET, 'bucket',
False, False)
imp.run()
self.assertEqual(mock_publish.call_count, data_handler.cve_count)
self.assertEqual(repo.get().last_update_date, datetime.datetime(2024, 1, 1))
michaelkedar marked this conversation as resolved.
Show resolved Hide resolved

@mock.patch('google.cloud.pubsub_v1.PublisherClient.publish')
@mock.patch('time.time', return_value=12345.0)
Expand All @@ -889,27 +893,29 @@ def test_no_updates(self, unused_mock_time: mock.MagicMock,
self.httpd = http.server.HTTPServer(SERVER_ADDRESS, MockDataHandler)
thread = threading.Thread(target=self.httpd.serve_forever)
thread.start()
self.source_repo.last_update_date = datetime.datetime(2024, 1, 1)
self.source_repo.put()
self.source_repo.last_update_date = datetime.datetime(2024, 2, 1)
repo = self.source_repo.put()
imp = importer.Importer('fake_public_key', 'fake_private_key', self.tmp_dir,
importer.DEFAULT_PUBLIC_LOGGING_BUCKET, 'bucket',
True, False)
with self.assertLogs() as logs:
imp.run()
mock_publish.assert_not_called()
self.assertIn('INFO:root:No changes since last update.', logs.output[1])
self.assertEqual(repo.get().last_update_date, datetime.datetime(2024, 2, 1))
michaelkedar marked this conversation as resolved.
Show resolved Hide resolved

@mock.patch('google.cloud.pubsub_v1.PublisherClient.publish')
@mock.patch('time.time', return_value=12345.0)
def test_few_updates(self, unused_mock_time: mock.MagicMock,
mock_publish: mock.MagicMock):
"""Testing from date between entries -
only entries after 6/6/2023 should be called"""
MockDataHandler.last_modified = 'Mon, 01 Jan 2024 00:00:00 GMT'
self.httpd = http.server.HTTPServer(SERVER_ADDRESS, MockDataHandler)
thread = threading.Thread(target=self.httpd.serve_forever)
thread.start()
self.source_repo.last_update_date = datetime.datetime(2023, 6, 6)
self.source_repo.put()
repo = self.source_repo.put()
imp = importer.Importer('fake_public_key', 'fake_private_key', self.tmp_dir,
importer.DEFAULT_PUBLIC_LOGGING_BUCKET, 'bucket',
False, False)
Expand Down Expand Up @@ -976,6 +982,7 @@ def test_few_updates(self, unused_mock_time: mock.MagicMock,
deleted='false',
req_timestamp='12345')
])
self.assertEqual(repo.get().last_update_date, datetime.datetime(2024, 1, 1))
michaelkedar marked this conversation as resolved.
Show resolved Hide resolved


@mock.patch('importer.utcnow', lambda: datetime.datetime(2024, 1, 1))
Expand Down
2 changes: 1 addition & 1 deletion docker/mock_test/mock_test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class MockDataHandler(http.server.BaseHTTPRequestHandler):
"""Mock data handler for testing."""
last_modified = 'Tue, 13 Jun 2023 00:00:00 GMT'
last_modified = 'Mon, 01 Jan 2024 00:00:00 GMT'
file_path = 'rest_test.json'
cve_count = -1
data = None
Expand Down
Loading