code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def display_severity_rating(severity: dict) -> str: """Return base score and rating of the severity.""" severity_base_score, severity_rating = calculate_severity_details(severity) if severity_base_score is None: return 'Invalid Severity Rating' return f"{severity_base_score} ({severity_rating})"
Return base score and rating of the severity.
display_severity_rating
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def cvss_calculator_url(severity): """Generate the FIRST CVSS calculator URL from a CVSS string.""" score = severity.get('score') # Extract CVSS version from the vector string version = score.split('/')[0].split(':')[1] return f"{_FIRST_CVSS_CALCULATOR_BASE_URL}/{version}#{score}"
Generate the FIRST CVSS calculator URL from a CVSS string.
cvss_calculator_url
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def construct_hierarchy_string(target_bug_id: str, root_nodes: set[str], graph: dict[str, set[str]]) -> str: """Constructs a hierarchy string for display. Args: target_bug_id: The ID of the target bug. root_nodes: a list of root_nodes graph: A dictionary representing the ...
Constructs a hierarchy string for display. Args: target_bug_id: The ID of the target bug. root_nodes: a list of root_nodes graph: A dictionary representing the tree to build. Returns: A string representing the hierarchy for display by the frontend.
construct_hierarchy_string
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def print_subtree(vuln_id: str) -> None: """ Recursively formats the subtree starting from the given vuln_id. Args: vuln_id (str): The starting vuln_id for printing the subtree. """ if vuln_id != target_bug_id: if osv_has_vuln(vuln_id): output_lines.append("<li><a href=\"/vuln...
Recursively formats the subtree starting from the given vuln_id. Args: vuln_id (str): The starting vuln_id for printing the subtree.
print_subtree
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def get_upstreams_of_vulnerability(bug) -> str | None: """Gets the upstream hierarchy of a vulnerability. Args: target_bug_id: The ID of the target bug. Returns: A string representing the upstream hierarchy for display by the frontend. """ target_bug_group = osv.UpstreamGroup.query( osv.U...
Gets the upstream hierarchy of a vulnerability. Args: target_bug_id: The ID of the target bug. Returns: A string representing the upstream hierarchy for display by the frontend.
get_upstreams_of_vulnerability
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def has_cycle(graph: dict[str, set[str]]) -> bool: """ Determines whether there are any cycles in a directed graph represented as an adjacency list. Args: graph: A dictionary representing the graph, where keys are nodes and values are sets of their neighbors. Returns: True if...
Determines whether there are any cycles in a directed graph represented as an adjacency list. Args: graph: A dictionary representing the graph, where keys are nodes and values are sets of their neighbors. Returns: True if the graph contains a cycle, False otherwise.
has_cycle
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def dfs(node: str) -> bool: """ Performs Depth-First Search to detect cycles. Args: node: The current node being visited. Returns: True if a cycle is detected, False otherwise. """ visited.add(node) recursion_stack.add(node) for neighbor in grap...
Performs Depth-First Search to detect cycles. Args: node: The current node being visited. Returns: True if a cycle is detected, False otherwise.
dfs
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def _get_downstreams_of_bug_query(bug_id: str) -> dict[str, list[str]]: """Returns a list of all downstream bugs of the given bug ID by querying the database.""" downstreams = {} for bug in osv.UpstreamGroup.query(osv.UpstreamGroup.upstream_ids == bug_id): downstreams[bug.db_id] = bug.upstream_ids return ...
Returns a list of all downstream bugs of the given bug ID by querying the database.
_get_downstreams_of_bug_query
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def _get_downstreams_of_bug(bug_id: str, bugs: dict[str, list[str]]) -> list[str]: """Returns a list of all downstream bugs of the given bug ID given a list of bugs.""" downstreams = [] for bug in bugs: if bug_id in bugs[bug]: downstreams.append(bug...
Returns a list of all downstream bugs of the given bug ID given a list of bugs.
_get_downstreams_of_bug
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def compute_downstream_hierarchy(target_bug_id: str, downstreams: dict[str, list[str]]) -> str: """Computes the hierarchy of all downstream vulnerabilities for the given bug ID. Returns a constructed string of the downstreams formatted for the frontend """ downstream_map: d...
Computes the hierarchy of all downstream vulnerabilities for the given bug ID. Returns a constructed string of the downstreams formatted for the frontend
compute_downstream_hierarchy
python
google/osv.dev
gcp/website/frontend_handlers.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers.py
Apache-2.0
def test_ecosystem_counts(self): """Test ecosystem counts aggregates correctly updates.""" models.Bug( id='OSV-0', db_id='OSV-0', status=1, public=True, source='test', affected_packages=[{ 'package': { 'ecosystem': 'PyPI', ...
Test ecosystem counts aggregates correctly updates.
test_ecosystem_counts
python
google/osv.dev
gcp/website/frontend_handlers_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/frontend_handlers_test.py
Apache-2.0
def check_request(self, ip_addr): """Check a request. Returns whether or not the request should proceed.""" minute = datetime.datetime.now(datetime.UTC).minute key_name = f'{ip_addr}:{minute}' with self._redis.pipeline(): counter = self._redis.incr(key_name) self._redis.expire(key_name, 59)...
Check a request. Returns whether or not the request should proceed.
check_request
python
google/osv.dev
gcp/website/rate_limiter.py
https://github.com/google/osv.dev/blob/master/gcp/website/rate_limiter.py
Apache-2.0
def api_url() -> str: """ Returns the URL of the OSV API for the current GCP project. Falls back to 'api.test.osv.dev' if URL cannot be determined. """ try: _, project = google.auth.default() except DefaultCredentialsError: project = '<unknown>' # TODO(michaelkedar): Is there a way to avoid hard...
Returns the URL of the OSV API for the current GCP project. Falls back to 'api.test.osv.dev' if URL cannot be determined.
api_url
python
google/osv.dev
gcp/website/utils.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils.py
Apache-2.0
def relative_time(value: datetime | str) -> str: """ Convert a datetime or ISO 8601 string to a human-readable relative time. Args: value: The input datetime as an ISO 8601 string or a datetime object. Returns: str: A human-readable string representing the relative time as: ...
Convert a datetime or ISO 8601 string to a human-readable relative time. Args: value: The input datetime as an ISO 8601 string or a datetime object. Returns: str: A human-readable string representing the relative time as: - < 1 minute: Just now - < 1 hour: x minu...
relative_time
python
google/osv.dev
gcp/website/utils.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils.py
Apache-2.0
def test_minutes_ago(self): """Check when the value is less than one hour""" self.assertEqual( utils.relative_time(self.now - timedelta(minutes=5)), "5 minutes ago")
Check when the value is less than one hour
test_minutes_ago
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def test_hours_ago(self): """Check when the value is less than 24 hours""" self.assertEqual( utils.relative_time(self.now - timedelta(hours=2)), "2 hours ago")
Check when the value is less than 24 hours
test_hours_ago
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def test_yesterday(self): """Check when the value is less than 48 hours""" self.assertEqual( utils.relative_time(self.now - timedelta(days=1)), "yesterday")
Check when the value is less than 48 hours
test_yesterday
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def test_days_ago(self): """Check when the value is less than 7 days""" self.assertEqual( utils.relative_time(self.now - timedelta(days=3)), "3 days ago")
Check when the value is less than 7 days
test_days_ago
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def test_last_week(self, mock_datetime): """Check when the value is 7 days""" now = datetime(2024, 6, 27, tzinfo=UTC) mock_datetime.now.return_value = now last_week = now - timedelta(days=7) self.assertEqual(utils.relative_time(last_week), '20 Jun')
Check when the value is 7 days
test_last_week
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def test_date_without_year(self, mock_datetime): """Check when the value is longer than 7 days but in the same year""" now = datetime(2024, 6, 27, tzinfo=UTC) mock_datetime.now.return_value = now date_within_year = now - timedelta(days=10) self.assertEqual(utils.relative_time(date_within_year), '17 ...
Check when the value is longer than 7 days but in the same year
test_date_without_year
python
google/osv.dev
gcp/website/utils_test.py
https://github.com/google/osv.dev/blob/master/gcp/website/utils_test.py
Apache-2.0
def _update_group(bug_ids, alias_group): """Updates the alias group in the datastore.""" if len(bug_ids) <= 1: logging.info('Deleting alias group due to too few bugs: %s', bug_ids) alias_group.key.delete() return if len(bug_ids) > ALIAS_GROUP_VULN_LIMIT: logging.info('Deleting alias group due to t...
Updates the alias group in the datastore.
_update_group
python
google/osv.dev
gcp/workers/alias/alias_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation.py
Apache-2.0
def _create_alias_group(bug_ids): """Creates a new alias group in the datastore.""" if len(bug_ids) <= 1: logging.info('Skipping alias group creation due to too few bugs: %s', bug_ids) return if len(bug_ids) > ALIAS_GROUP_VULN_LIMIT: logging.info('Skipping alias group creation due to ...
Creates a new alias group in the datastore.
_create_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation.py
Apache-2.0
def _compute_aliases(bug_id, visited, bug_aliases): """Computes all aliases for the given bug ID. The returned list contains the bug ID itself, all the IDs from the bug's raw aliases, all the IDs of bugs that have the current bug as an alias, and repeat for every bug encountered here.""" to_visit = {bug_id} ...
Computes all aliases for the given bug ID. The returned list contains the bug ID itself, all the IDs from the bug's raw aliases, all the IDs of bugs that have the current bug as an alias, and repeat for every bug encountered here.
_compute_aliases
python
google/osv.dev
gcp/workers/alias/alias_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation.py
Apache-2.0
def main(): """Updates all alias groups in the datastore by re-computing existing AliasGroups and creating new AliasGroups for un-computed bugs.""" # Query for all bugs that have aliases. # Use (> '' OR < '') instead of (!= '') / (> '') to de-duplicate results # and avoid datastore emulator problems, see iss...
Updates all alias groups in the datastore by re-computing existing AliasGroups and creating new AliasGroups for un-computed bugs.
main
python
google/osv.dev
gcp/workers/alias/alias_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation.py
Apache-2.0
def test_update_alias_group(self): """Tests updating an existing alias group.""" osv.AliasGroup( bug_ids=['bbb-123', 'bbb-234'], last_modified=datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC), ).put() osv.Bug( id='bbb-123', db_id='bbb-123', aliases=['bbb-345', '...
Tests updating an existing alias group.
test_update_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def test_delete_alias_group(self): """Tests deleting alias groups that only has one vulnerability.""" osv.Bug( id='ccc-123', db_id='ccc-123', status=1, source='test', public=True, import_last_modified=datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC), ).put()...
Tests deleting alias groups that only has one vulnerability.
test_delete_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def test_split_alias_group(self): """Tests split an existing alias group into two. AliasGroup A -> B -> C -> D, remove the B -> C alias to get AliasGroups A -> B and C -> D.""" osv.Bug( id='ddd-123', db_id='ddd-123', aliases=['ddd-124'], status=1, source='test', ...
Tests split an existing alias group into two. AliasGroup A -> B -> C -> D, remove the B -> C alias to get AliasGroups A -> B and C -> D.
test_split_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def test_merge_alias_group(self): """Tests all bugs of one alias group have been merged to other alias group.""" osv.Bug( id='ggg-123', db_id='ggg-123', aliases=['ggg-124', 'ggg-125', 'ggg-126'], status=1, source='test', public=True, import_last_modifi...
Tests all bugs of one alias group have been merged to other alias group.
test_merge_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def test_partial_merge_alias_group(self): """Tests merging some bugs of one alias group to another alias group.""" osv.Bug( id='hhh-123', db_id='hhh-123', aliases=['hhh-124', 'hhh-125'], status=1, source='test', public=True, import_last_modified=datetime.d...
Tests merging some bugs of one alias group to another alias group.
test_partial_merge_alias_group
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def test_to_vulnerability(self): """Tests OSV bug to vulnerability function.""" bug = osv.Bug( id='jjj-123', db_id='jjj-123', related=['jjj-111'], status=1, source='test', public=True, import_last_modified=datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC)...
Tests OSV bug to vulnerability function.
test_to_vulnerability
python
google/osv.dev
gcp/workers/alias/alias_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/alias_computation_test.py
Apache-2.0
def compute_upstream(target_bug, bugs: dict[str, set[str]]) -> list[str]: """Computes all upstream vulnerabilities for the given bug ID. The returned list contains all of the bug IDs that are upstream of the target bug ID, including transitive upstreams.""" visited = set() target_bug_upstream = target_bug ...
Computes all upstream vulnerabilities for the given bug ID. The returned list contains all of the bug IDs that are upstream of the target bug ID, including transitive upstreams.
compute_upstream
python
google/osv.dev
gcp/workers/alias/upstream_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation.py
Apache-2.0
def _create_group(bug_id, upstream_ids) -> osv.UpstreamGroup: """Creates a new upstream group in the datastore.""" new_group = osv.UpstreamGroup( id=bug_id, db_id=bug_id, upstream_ids=upstream_ids, last_modified=datetime.datetime.now(datetime.UTC)) new_group.put() return new_group
Creates a new upstream group in the datastore.
_create_group
python
google/osv.dev
gcp/workers/alias/upstream_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation.py
Apache-2.0
def _update_group(upstream_group: osv.UpstreamGroup, upstream_ids: list) -> osv.UpstreamGroup | None: """Updates the upstream group in the datastore.""" if len(upstream_ids) == 0: logging.info('Deleting upstream group due to too few bugs: %s', upstream_ids) upstream_group....
Updates the upstream group in the datastore.
_update_group
python
google/osv.dev
gcp/workers/alias/upstream_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation.py
Apache-2.0
def compute_upstream_hierarchy( target_upstream_group: osv.UpstreamGroup, all_upstream_groups: dict[str, osv.UpstreamGroup]) -> None: """Computes all upstream vulnerabilities for the given bug ID. The returned list contains all of the bug IDs that are upstream of the target bug ID, including transitive up...
Computes all upstream vulnerabilities for the given bug ID. The returned list contains all of the bug IDs that are upstream of the target bug ID, including transitive upstreams in a map hierarchy. upstream_group: { db_id: bug id upstream_ids: list of upstream bug ids last_modified_date...
compute_upstream_hierarchy
python
google/osv.dev
gcp/workers/alias/upstream_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation.py
Apache-2.0
def main(): """Updates all upstream groups in the datastore by re-computing existing UpstreamGroups and creating new UpstreamGroups for un-computed bugs.""" # Query for all bugs that have upstreams. updated_bugs = [] logging.info('Retrieving bugs...') bugs_query = osv.Bug.query(osv.Bug.upstream_raw > '') ...
Updates all upstream groups in the datastore by re-computing existing UpstreamGroups and creating new UpstreamGroups for un-computed bugs.
main
python
google/osv.dev
gcp/workers/alias/upstream_computation.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation.py
Apache-2.0
def test_compute_upstream_basic(self): """Tests basic case. CVE-1-> CVE-2 -> CVE-3 Upstream of CVE-3 is CVE-2 & CVE-1 """ bugs_query = osv.Bug.query( ndb.OR(osv.Bug.upstream_raw > '', osv.Bug.upstream_raw < '')) bugs = {bug.db_id: bug.upstream_raw for bug in bugs_query.iter()} bug_...
Tests basic case. CVE-1-> CVE-2 -> CVE-3 Upstream of CVE-3 is CVE-2 & CVE-1
test_compute_upstream_basic
python
google/osv.dev
gcp/workers/alias/upstream_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation_test.py
Apache-2.0
def test_compute_upstream_example(self): """Test real world case with multiple levels""" bugs_query = osv.Bug.query( ndb.OR(osv.Bug.upstream_raw > '', osv.Bug.upstream_raw < '')) bugs = {bug.db_id: bug.upstream_raw for bug in bugs_query.iter()} bug_ids = upstream_computation.compute_upstream( ...
Test real world case with multiple levels
test_compute_upstream_example
python
google/osv.dev
gcp/workers/alias/upstream_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation_test.py
Apache-2.0
def test_incomplete_compute_upstream(self): """ Test when incomplete upstream information is given VULN-1 -> VULN-2, VULN-3 -> VULN-4 """ osv.Bug( id='VULN-1', db_id='VULN-1', status=1, upstream_raw=[], source='test', public=True, import_last...
Test when incomplete upstream information is given VULN-1 -> VULN-2, VULN-3 -> VULN-4
test_incomplete_compute_upstream
python
google/osv.dev
gcp/workers/alias/upstream_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation_test.py
Apache-2.0
def test_upstream_group_basic(self): """Test the upstream group get by db_id""" upstream_computation.main() osv.UpstreamGroup( db_id='CVE-3', upstream_ids=['CVE-1', 'CVE-2'], last_modified=datetime.datetime(2024, 1, 1, tzinfo=datetime.UTC), ).put() bug_ids = osv.UpstreamGroup...
Test the upstream group get by db_id
test_upstream_group_basic
python
google/osv.dev
gcp/workers/alias/upstream_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation_test.py
Apache-2.0
def test_upstream_hierarchy_computation_complex(self): """Testing hierarchy computation for more complex, realworld case""" upstream_computation.main() bug_ids = osv.UpstreamGroup.query( osv.UpstreamGroup.db_id == 'USN-7234-3').get().upstream_hierarchy bug_ids = json.loads(bug_ids) expecte...
Testing hierarchy computation for more complex, realworld case
test_upstream_hierarchy_computation_complex
python
google/osv.dev
gcp/workers/alias/upstream_computation_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/alias/upstream_computation_test.py
Apache-2.0
def fetch_vulnerabilities_and_dates( ecosystem: str) -> list[tuple[str, datetime.datetime]]: """Fetch vulnerabilities' id for the given ecosystem.""" # Query with projection to reduce data returned # Order does not matter, other than to keep things consistent bugs = osv.Bug.query( osv.Bug.status == os...
Fetch vulnerabilities' id for the given ecosystem.
fetch_vulnerabilities_and_dates
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap.py
Apache-2.0
def generate_sitemap_for_ecosystem(ecosystem: str, base_url: str) -> datetime.datetime: """ Generate a sitemap for the give n ecosystem. Returns the latest modified date of it's entries. """ logging.info('Generating sitemap for ecosystem "%s".', ecosystem) vulnerability...
Generate a sitemap for the give n ecosystem. Returns the latest modified date of it's entries.
generate_sitemap_for_ecosystem
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap.py
Apache-2.0
def generate_sitemaps(base_url: str) -> None: """Generate sitemaps including all vulnerabilities, split by ecosystem.""" logging.info("Begin generating sitemaps.") # Go over the base ecosystems index. Otherwise we'll have duplicated # vulnerabilities in the sitemap. base_ecosystems = { ecosystem for eco...
Generate sitemaps including all vulnerabilities, split by ecosystem.
generate_sitemaps
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap.py
Apache-2.0
def preload_alias_groups(): """Fetch all alias groups, as we will be querying all of them anyway""" logging.info("Preloading alias groups into memory.") aliases = osv.AliasGroup.query() for al in aliases: al: osv.AliasGroup for bug_id in al.bug_ids: # type: ignore alias_to_last_modified[bug_id] =...
Fetch all alias groups, as we will be querying all of them anyway
preload_alias_groups
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap.py
Apache-2.0
def test_fetch_vulnerabilities_and_dates(self, mock_query): """Test it returns the vulnerability ids for ecosystem""" # Mock the returned query mock_query.return_value.order.return_value = [ MagicMock( last_modified=datetime.fromtimestamp(10, tz=UTC), key=MagicMock(id=MagicMo...
Test it returns the vulnerability ids for ecosystem
test_fetch_vulnerabilities_and_dates
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def test_generate_sitemap_for_ecosystem(self, mock_element_tree, mock_fetch_vulns): """Check it generates the sitemap for ecosystem""" mock_fetch_vulns.return_value = [ ('vuln1', datetime.fromtimestamp(10, tz=UTC)), ('vuln2', datetime.fromtimestamp(20, t...
Check it generates the sitemap for ecosystem
test_generate_sitemap_for_ecosystem
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def test_generate_sitemap_for_ecosystem_with_space(self, mock_element_tree, mock_fetch_vulns): """" Check it creates the sitemap correctly where there is a space in the ecosystem name. """ mock_fetch_vulns.return_value = [ ('vuln1', dateti...
" Check it creates the sitemap correctly where there is a space in the ecosystem name.
test_generate_sitemap_for_ecosystem_with_space
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def test_generate_sitemap_for_ecosystem_with_period(self, mock_element_tree, mock_fetch_vulns): """" Check it creates the sitemap correctly where there is a period in the ecosystem name. """ mock_fetch_vulns.return_value = [ ('vuln1', dat...
" Check it creates the sitemap correctly where there is a period in the ecosystem name.
test_generate_sitemap_for_ecosystem_with_period
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def test_generate_sitemap_index(self, mock_element_tree): """Check it generates the sitemap index as expected""" mock_tree = MagicMock() mock_element_tree.return_value = mock_tree generate_sitemap.generate_sitemap_index( {'Go', 'UVI'}, 'http://example.com', { 'Go': datetime.fromtime...
Check it generates the sitemap index as expected
test_generate_sitemap_index
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def test_generate_sitemap(self, mock_get_ecosystems, mock_generate_index, mock_generate_sitemap): """ Check the outer wrapper generates the ecosystems' sitemaps as well as sitemap index. """ mock_get_ecosystems.return_value = ['Go', 'UVI:Library', 'Android'] mock_gene...
Check the outer wrapper generates the ecosystems' sitemaps as well as sitemap index.
test_generate_sitemap
python
google/osv.dev
gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/cron/generate_sitemap/generate_sitemap_test.py
Apache-2.0
def modify_storage_client_adapters(storage_client: storage.Client, pool_connections: int = 128, max_retries: int = 3, pool_block: bool = True) -> storage.Client: """Returns a modified google.cloud.storage.Client o...
Returns a modified google.cloud.storage.Client object. Due to many concurrent GCS connections, the default connection pool can become overwhelmed, introducing delays. Solution described in https://github.com/googleapis/python-storage/issues/253 These affect the urllib3.HTTPConnectionPool underpinning the sto...
modify_storage_client_adapters
python
google/osv.dev
gcp/workers/exporter/exporter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/exporter.py
Apache-2.0
def _export_ecosystem_list_to_bucket(self, ecosystems: List[str], tmp_dir: str): """Export an ecosystems.txt file with all of the ecosystem names. See https://github.com/google/osv.dev/issues/619 Args: ecosystems: the list of ecosystem names tmp_dir: temp...
Export an ecosystems.txt file with all of the ecosystem names. See https://github.com/google/osv.dev/issues/619 Args: ecosystems: the list of ecosystem names tmp_dir: temporary directory for scratch
_export_ecosystem_list_to_bucket
python
google/osv.dev
gcp/workers/exporter/exporter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/exporter.py
Apache-2.0
def _export_ecosystem_to_bucket(self, ecosystem: str, work_dir: str): """Export the vulnerabilities in an ecosystem to GCS. Args: ecosystem: the ecosystem name work_dir: working directory for scratch This simultaneously exports every Bug for the given ecosystem to individual files in the s...
Export the vulnerabilities in an ecosystem to GCS. Args: ecosystem: the ecosystem name work_dir: working directory for scratch This simultaneously exports every Bug for the given ecosystem to individual files in the scratch filesystem, and a zip file in the scratch filesystem. At the conc...
_export_ecosystem_to_bucket
python
google/osv.dev
gcp/workers/exporter/exporter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/exporter.py
Apache-2.0
def _export_to_file_and_zipfile(bug: osv.Bug): """Write out a bug record to both a single file and the zip file.""" if not bug.public or bug.status == osv.BugStatus.UNPROCESSED: return try: file_path = os.path.join(ecosystem_dir, bug.id() + '.json') vulnerability =...
Write out a bug record to both a single file and the zip file.
_export_to_file_and_zipfile
python
google/osv.dev
gcp/workers/exporter/exporter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/exporter.py
Apache-2.0
def upload_single(bucket: Bucket, source_path: str, target_path: str): """Upload a single file to a GCS bucket.""" logging.info('Uploading %s', target_path) try: blob = bucket.blob(target_path) blob.upload_from_filename(source_path, retry=retry.DEFAULT_RETRY) except Exception as e: logging.exception...
Upload a single file to a GCS bucket.
upload_single
python
google/osv.dev
gcp/workers/exporter/exporter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/exporter.py
Apache-2.0
def aggregate_all_vulnerabilities(work_dir: str, export_bucket: str): """ Aggregates vulnerability records from each ecosystem into a single zip file and uploads it to the export bucket. """ logging.info('Generating unified all.zip archive.') zip_file_name = 'all.zip' output_zip = os.path.join(work_dir, z...
Aggregates vulnerability records from each ecosystem into a single zip file and uploads it to the export bucket.
aggregate_all_vulnerabilities
python
google/osv.dev
gcp/workers/exporter/export_runner.py
https://github.com/google/osv.dev/blob/master/gcp/workers/exporter/export_runner.py
Apache-2.0
def _is_vulnerability_file(source_repo, file_path): """Return whether or not the file is a Vulnerability entry.""" if (source_repo.directory_path and not file_path.startswith(source_repo.directory_path.rstrip('/') + '/')): return False if source_repo.ignore_file(file_path): return False return f...
Return whether or not the file is a Vulnerability entry.
_is_vulnerability_file
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def replace_importer_log(client: storage.Client, source_name: str, bucket_name: str, import_failure_logs: List[str]): """Replace the public importer logs with the new one.""" bucket: storage.Bucket = client.bucket(bucket_name) upload_string = f'--- {datetime.datetime.now(datetime.UTC).iso...
Replace the public importer logs with the new one.
replace_importer_log
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def log_run_duration(start: float): """Log the elapsed wallclock duration at the end of the program. This enables a log-based metric to be created. Args: start: the time the program started. """ elapsed = time.time() - start logging.info('Importer run duration: %d', elapsed)
Log the elapsed wallclock duration at the end of the program. This enables a log-based metric to be created. Args: start: the time the program started.
log_run_duration
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _infer_id_from_invalid_data(self, name: str, content: bytes) -> str: """Best effort infer the bug ID for data that failed to parse. First try and extract something that looks like an "id" field, and failing that, try to infer from the filename. Args: name: the name associated with the data ...
Best effort infer the bug ID for data that failed to parse. First try and extract something that looks like an "id" field, and failing that, try to infer from the filename. Args: name: the name associated with the data content: the data itself Returns: str: the inferred identifer ...
_infer_id_from_invalid_data
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _record_quality_finding( self, source: osv.SourceRepository.name, bug_id: str, maybe_new_finding: osv.ImportFindings = osv.ImportFindings.INVALID_JSON): """Record the quality finding about a record in Datastore. Args: source: the name of the source of the vulnerability record ...
Record the quality finding about a record in Datastore. Args: source: the name of the source of the vulnerability record bug_id: the ID of the vulnerability maybe_new_finding: the finding to record Sets the finding's last_attempt to now, and adds the finding to the list of findings for t...
_record_quality_finding
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _vuln_ids_from_gcs_blob(self, client: storage.Client, source_repo: osv.SourceRepository, blob: storage.Blob) -> Optional[Tuple[str]]: """Returns a list of the vulnerability IDs from a parsable OSV file in GCS. Usually an OSV file has a single vuln...
Returns a list of the vulnerability IDs from a parsable OSV file in GCS. Usually an OSV file has a single vulnerability in it, but it is permissible to have more than one, hence it returns a list. This is runnable in parallel using concurrent.futures.ThreadPoolExecutor Args: client: a storage.C...
_vuln_ids_from_gcs_blob
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _convert_blob_to_vuln( self, storage_client: storage.Client, ndb_client: ndb.Client, source_repo: osv.SourceRepository, blob: storage.Blob, ignore_last_import_time: bool) -> Optional[Tuple[str]]: """Parse a GCS blob into a tuple of hash and Vulnerability Criteria for returning a tuple: ...
Parse a GCS blob into a tuple of hash and Vulnerability Criteria for returning a tuple: - any record in the blob is new (i.e. a new ID) or modified since last run, and the hash for the blob has changed - the importer is reimporting the entire source - ignore_last_import_time is True - the r...
_convert_blob_to_vuln
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _process_deletions_bucket(self, source_repo: osv.SourceRepository, threshold: float = 10.0): """Process deletions from a GCS bucket source. This validates the continued existence of every Bug in Datastore (for the given source) against eve...
Process deletions from a GCS bucket source. This validates the continued existence of every Bug in Datastore (for the given source) against every bug currently in that source's GCS bucket, calculating the delta. The bugs determined to have been deleted from GCS are then flagged for treatment by the wor...
_process_deletions_bucket
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def _process_updates_rest(self, source_repo: osv.SourceRepository): """Process updates from REST API. To find new updates, first makes a HEAD request to check the 'Last-Modified' header, and skips processing if it's before the source's last_modified_date (and ignore_last_import_time isn't set). ...
Process updates from REST API. To find new updates, first makes a HEAD request to check the 'Last-Modified' header, and skips processing if it's before the source's last_modified_date (and ignore_last_import_time isn't set). Otherwise, GETs the list of vulnerabilities and requests updates for ...
_process_updates_rest
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def process_updates(self, source_repo: osv.SourceRepository): """Process source record changes and updates.""" if source_repo.type == osv.SourceRepositoryType.GIT: self._process_updates_git(source_repo) return if source_repo.type == osv.SourceRepositoryType.BUCKET: self._process_updates_b...
Process source record changes and updates.
process_updates
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def process_deletions(self, source_repo: osv.SourceRepository): """Process source record deletions by withdrawing them.""" if source_repo.type == osv.SourceRepositoryType.GIT: # TODO: To be implemented. # NOTE: this may require reintroducing special node GKE node treatment # see discussion on ...
Process source record deletions by withdrawing them.
process_deletions
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def export_oss_fuzz_to_bucket(self): """Export OSS-Fuzz vulns to bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(self._oss_fuzz_export_bucket) def export_oss_fuzz(vulnerability, testcase_id, issue_id): """Export a single vulnerability.""" try: blob = ...
Export OSS-Fuzz vulns to bucket.
export_oss_fuzz_to_bucket
python
google/osv.dev
gcp/workers/importer/importer.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer.py
Apache-2.0
def test_blob_parsing(self): """Test conditional GCS blob parsing works correctly.""" imp = importer.Importer( 'fake_public_key', 'fake_private_key', self.tmp_dir, importer.DEFAULT_PUBLIC_LOGGING_BUCKET, 'bucket', True, False, deletion_safety_thre...
Test conditional GCS blob parsing works correctly.
test_blob_parsing
python
google/osv.dev
gcp/workers/importer/importer_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer_test.py
Apache-2.0
def test_deletions_in_staging(self, mock_publish: mock.MagicMock, unused_upload_from_str: mock.MagicMock): """Load test against staging bucket and (non-emulated) staging Datastore.""" imp = importer.Importer( 'fake_public_key', 'fake_private_key', self.tmp...
Load test against staging bucket and (non-emulated) staging Datastore.
test_deletions_in_staging
python
google/osv.dev
gcp/workers/importer/importer_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer_test.py
Apache-2.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.source_repo.last_update_date = d...
Testing from date between entries - only entries after 6/6/2023 should be called
test_few_updates
python
google/osv.dev
gcp/workers/importer/importer_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer_test.py
Apache-2.0
def test_invalid(self, unused_mock_time: mock.MagicMock, mock_publish: mock.MagicMock): """Test invalid records are treated correctly.""" # TODO(apollock): implement
Test invalid records are treated correctly.
test_invalid
python
google/osv.dev
gcp/workers/importer/importer_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer_test.py
Apache-2.0
def test_add_finding(self): """Test that creating an import finding works.""" expected = osv.ImportFinding( bug_id='CVE-2024-1234', source='cve-osv', findings=[ osv.ImportFindings.INVALID_VERSION, ], first_seen=importer.utcnow(), last_attempt=importer....
Test that creating an import finding works.
test_add_finding
python
google/osv.dev
gcp/workers/importer/importer_test.py
https://github.com/google/osv.dev/blob/master/gcp/workers/importer/importer_test.py
Apache-2.0
def download_file(source: str, destination: str): """Downloads the required file from bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(VULN_BUCKET) try: blob = bucket.blob(source) blob.download_to_filename(destination) except Exception as e: logging.exception('Failed...
Downloads the required file from bucket.
download_file
python
google/osv.dev
gcp/workers/linter/linter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/linter/linter.py
Apache-2.0
def download_osv_data(tmp_dir: str): """download osv data from all.zip to a temp directory""" logging.info('Starts to download %s from bucket %s.', ZIP_FILE_PATH, VULN_BUCKET) all_zip = os.path.join(tmp_dir, ZIP_FILE_PATH) download_file(ZIP_FILE_PATH, all_zip) logging.info('Unzipping %s into %s...
download osv data from all.zip to a temp directory
download_osv_data
python
google/osv.dev
gcp/workers/linter/linter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/linter/linter.py
Apache-2.0
def process_linter_result(output: Any, bugs: set): """process the linter results and update/add findings into db.""" time = utcnow() total_findings = 0 for filename, findings_list in output.items(): bug_id = os.path.splitext(os.path.basename(filename))[0] bugs.add(bug_id) findings_already_added = s...
process the linter results and update/add findings into db.
process_linter_result
python
google/osv.dev
gcp/workers/linter/linter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/linter/linter.py
Apache-2.0
def record_quality_finding(bug_id: str, source: str, new_findings: list[osv.ImportFindings], findingtimenow: datetime): """Record or update the linter finding about a record in Datastore.""" existing_finding = osv.ImportFinding.get_by_id(bug_id) if existing_f...
Record or update the linter finding about a record in Datastore.
record_quality_finding
python
google/osv.dev
gcp/workers/linter/linter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/linter/linter.py
Apache-2.0
def parse_and_record_linter_output(json_output_str: str): """ Parses the JSON output from the OSV linter and records findings. Manages create, update, and delete findings in the Datastore. """ try: linter_output_json = json.loads(json_output_str) logging.info('Successfully parsed OSV Linter JSON outpu...
Parses the JSON output from the OSV linter and records findings. Manages create, update, and delete findings in the Datastore.
parse_and_record_linter_output
python
google/osv.dev
gcp/workers/linter/linter.py
https://github.com/google/osv.dev/blob/master/gcp/workers/linter/linter.py
Apache-2.0
def read_from_json(filename: str, ecosystem_map: defaultdict, bug_map: dict, package_map: defaultdict) -> None: """Loads bugs from one JSON file into bug dicts. Args: filename: the JSON filename. ecosystem_map: A defaultdict mapping ecosystem names to their bugs. For example: ...
Loads bugs from one JSON file into bug dicts. Args: filename: the JSON filename. ecosystem_map: A defaultdict mapping ecosystem names to their bugs. For example: {'Maven': (CVE-XXXX-XXXX, CVE-XXXX-XXXX), 'PyPI': ()} bug_map: A dict mapping bug ID to its `SimpleBug` object. For example...
read_from_json
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def load_all_bugs() -> tuple[defaultdict, dict, defaultdict]: """Loads bugs from JSON directory Returns: A defaultdict mapping ecosystem names to their bugs. For example: {'Maven': (CVE-XXXX-XXXX, CVE-XXXX-XXXX), 'PyPI': ()} A dict mapping bug ID to its `SimpleBug` object. For example: {'CVE-XXXX-...
Loads bugs from JSON directory Returns: A defaultdict mapping ecosystem names to their bugs. For example: {'Maven': (CVE-XXXX-XXXX, CVE-XXXX-XXXX), 'PyPI': ()} A dict mapping bug ID to its `SimpleBug` object. For example: {'CVE-XXXX-XXXX,': SimpleBug{}} A defaultdict mapping package names to th...
load_all_bugs
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def make_http_request(session: aiohttp.ClientSession, request_url: str, request_type: str, request_body: dict) -> None: """Makes one HTTP request Args: session: The HTTP ClientSession request_url: The HTTP request URL request_type: The HTTP request ty...
Makes one HTTP request Args: session: The HTTP ClientSession request_url: The HTTP request URL request_type: The HTTP request type: `GET` or `POST` request_body: The HTTP request body in JSON format
make_http_request
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def make_http_requests_async(request_ids: list, bug_map: dict, url: str, batch_size: int, payload_func: Callable) -> None: """Makes the required number of HTTP requests per second async. Args: request_ids: A list of bug IDs b...
Makes the required number of HTTP requests per second async. Args: request_ids: A list of bug IDs bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects url: The request URL batch_size: The number of requests to make per second payload_func: The pay...
make_http_requests_async
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def build_package_payload(request_id: str, bug_map: dict) -> dict[str, any]: """Builds a package query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package query payload, example: '"package": ...
Builds a package query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package query payload, example: '"package": {"name": "mruby","ecosystem": "OSS-Fuzz"}}'
build_package_payload
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def build_version_payload(request_id: str, bug_map: dict) -> dict: """Builds a version query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package version query payload, example: '{"package": {...
Builds a version query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package version query payload, example: '{"package": { "name": "mruby","ecosystem": "OSS-Fuzz"}, "version": "2.1.2rc"}' ...
build_version_payload
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def build_purl_payload(request_id: str, bug_map: dict) -> dict: """Builds a purl query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package version query payload, example: '{"package": {"purl"...
Builds a purl query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing package version query payload, example: '{"package": {"purl": "pkg:golang/github.com/golang-jwt/jwt/v4@4.5.1"}}'
build_purl_payload
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def build_batch_payload(request_ids: list, bug_map: dict) -> dict[str, list[dict[str, any]]]: """Builds a batch query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing OSV batch...
Builds a batch query payload Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing OSV batch query payload, example: '{ "queries": [ { "package": { ... }, ...
build_batch_payload
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def get_large_batch_query(package_map: defaultdict) -> list[str]: """Gets a list of bug IDs for large batch queries. This list contains bug IDs from the packages with the high number of vulnerabilities. Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `Simp...
Gets a list of bug IDs for large batch queries. This list contains bug IDs from the packages with the high number of vulnerabilities. Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects Returns: A dict containing OSV batch query payloa...
get_large_batch_query
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def send_version_requests(request_ids: list, bug_map: dict) -> None: """Sends version query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects """ url = f'{BASE_URL}/query' batch_size = VERSION_QUERY_BATCH_SIZE await mak...
Sends version query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects
send_version_requests
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def send_package_requests(request_ids: list, bug_map: dict) -> None: """Sends package query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects """ url = f'{BASE_URL}/query' batch_size = PACKAGE_QUERY_BATCH_SIZE await make...
Sends package query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects
send_package_requests
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def send_purl_requests(request_ids: list, bug_map: dict) -> None: """Sends purl query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects """ url = f'{BASE_URL}/query' batch_size = PURL_QUERY_BATCH_SIZE await make_http_req...
Sends purl query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects
send_purl_requests
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def send_vuln_requests(request_ids: list, bug_map: dict) -> None: """Sends vulnerability get requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects """ url = f'{BASE_URL}/vulns' batch_size = VULN_QUERY_BATCH_SIZE await make_h...
Sends vulnerability get requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects
send_vuln_requests
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
async def send_batch_requests(request_ids: list, bug_map: dict, batch_size: int) -> None: """Sends batch query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects batch_size: The batch query size ...
Sends batch query requests Args: request_id: The bug ID bug_map: A dict mapping bug IDs to the corresponding `SimpleBug` objects batch_size: The batch query size
send_batch_requests
python
google/osv.dev
gcp/workers/staging_api_test/perform_api_calls.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/perform_api_calls.py
Apache-2.0
def format_bug_for_output(bug: dict[str, any]) -> dict[str, any]: """Extracts relevant information from a vulnerability record. This function processes a vulnerability record and extracts specific fields needed for further api query usage. Args: bug: a vulnerability record. Returns: A dict storing ...
Extracts relevant information from a vulnerability record. This function processes a vulnerability record and extracts specific fields needed for further api query usage. Args: bug: a vulnerability record. Returns: A dict storing all the important `Bug` fields that we want to use later
format_bug_for_output
python
google/osv.dev
gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
Apache-2.0
def download_vuln_zip(tmp_dir: str) -> None: """Downloads all.zip file from bucket.""" zip_full_path = os.path.join(VULN_BUCKET, ZIP_FILE_PATH) logging.info('Start to download %s.', zip_full_path) storage_client = storage.Client() bucket = storage_client.get_bucket(VULN_BUCKET) try: blob = bucket.blob(Z...
Downloads all.zip file from bucket.
download_vuln_zip
python
google/osv.dev
gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
Apache-2.0
def get_bugs_from_export() -> None: """Gets all bugs from the exported all.zip and writes to `BUG_DIR`.""" tmp_dir = os.path.join(BUG_DIR, 'tmp') os.makedirs(tmp_dir, exist_ok=True) os.environ['TMPDIR'] = tmp_dir logging.info('Start to process %s.', ZIP_FILE_PATH) with tempfile.TemporaryDirectory() as tmp_...
Gets all bugs from the exported all.zip and writes to `BUG_DIR`.
get_bugs_from_export
python
google/osv.dev
gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
https://github.com/google/osv.dev/blob/master/gcp/workers/staging_api_test/retrieve_bugs_from_bucket.py
Apache-2.0
def set_bug_attributes(bug, regress_result, fix_result): """Set bug attributes from bisection results.""" issue_id = fix_result.issue_id or regress_result.issue_id project = fix_result.project or regress_result.project ecosystem = fix_result.ecosystem or regress_result.ecosystem summary = fix_result.summary o...
Set bug attributes from bisection results.
set_bug_attributes
python
google/osv.dev
gcp/workers/worker/oss_fuzz.py
https://github.com/google/osv.dev/blob/master/gcp/workers/worker/oss_fuzz.py
Apache-2.0
def _set_result_attributes(oss_fuzz_dir, message, entity): """Set necessary fields from bisection message.""" project_name = message.attributes['project_name'] issue_id = message.attributes['issue_id'] or None crash_type = message.attributes['crash_type'] crash_state = message.attributes['crash_state'] seve...
Set necessary fields from bisection message.
_set_result_attributes
python
google/osv.dev
gcp/workers/worker/oss_fuzz.py
https://github.com/google/osv.dev/blob/master/gcp/workers/worker/oss_fuzz.py
Apache-2.0
def get_oss_fuzz_summary(crash_type, crash_state): """Generate a summary from OSS-Fuzz crash type and crash state.""" crash_type = crash_type.splitlines()[0] state_lines = crash_state.splitlines() if crash_type in ('ASSERT', 'CHECK failure', 'Security CHECK failure', 'Security DCHECK failure...
Generate a summary from OSS-Fuzz crash type and crash state.
get_oss_fuzz_summary
python
google/osv.dev
gcp/workers/worker/oss_fuzz.py
https://github.com/google/osv.dev/blob/master/gcp/workers/worker/oss_fuzz.py
Apache-2.0
def get_oss_fuzz_details(issue_id, crash_type, crash_state): """Generate details from OSS-Fuzz crash type and crash state.""" details = '' if issue_id: oss_fuzz_link = OSS_FUZZ_ISSUE_URL + issue_id details = f'OSS-Fuzz report: {oss_fuzz_link}\n\n' crash_type = crash_type.replace('\n', ' ') return det...
Generate details from OSS-Fuzz crash type and crash state.
get_oss_fuzz_details
python
google/osv.dev
gcp/workers/worker/oss_fuzz.py
https://github.com/google/osv.dev/blob/master/gcp/workers/worker/oss_fuzz.py
Apache-2.0
def _setup_logging_extra_info(): """Set up extra GCP logging information.""" old_factory = logging.getLogRecordFactory() def record_factory(*args, **kwargs): """Insert jsonPayload fields to all logs.""" record = old_factory(*args, **kwargs) if not hasattr(record, 'json_fields'): record.json_f...
Set up extra GCP logging information.
_setup_logging_extra_info
python
google/osv.dev
gcp/workers/worker/worker.py
https://github.com/google/osv.dev/blob/master/gcp/workers/worker/worker.py
Apache-2.0