id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
2,359
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version The provided code snippet includes necessary dependencies for implementing the `normalize_prisma_url` function. Write a Python function `def normalize_prisma_url(url: str | None) -> str | None` to solve the following problem: Correct common Prisma Cloud API URL misconfigurations Here is the function: def normalize_prisma_url(url: str | None) -> str | None: """ Correct common Prisma Cloud API URL misconfigurations """ if not url: return None return url.lower().replace('//app', '//api').replace('http:', 'https:').strip().rstrip('/')
Correct common Prisma Cloud API URL misconfigurations
2,360
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version PRISMA_PLATFORM = 'Prisma Cloud Code Security' BRIDGECREW_PLATFORM = 'Bridgecrew' def get_auth_error_message(status: int, is_prisma: bool, is_s3_upload: bool) -> str: platform_type = PRISMA_PLATFORM if is_prisma else BRIDGECREW_PLATFORM error_message = f'Received unexpected response from platform (status code {status}). Please verify ' \ f'that your API token is valid and has permissions to call the {platform_type} APIs.' if platform_type == PRISMA_PLATFORM: error_message += 'The key must be associated with a Developer or Sys Admin role / permission group.' elif is_s3_upload: # This part only applies to S3 upload, but not downloading the run config error_message += 'The key must be associated with any role besides Auditor.' return error_message
null
2,361
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def extract_error_message(response: requests.Response | HTTPResponse) -> Optional[str]: if (isinstance(response, requests.Response) and response.content) or ( isinstance(response, HTTPResponse) and response.data): raw = response.content if isinstance(response, requests.Response) else response.data try: content = json.loads(raw) if 'message' in content: return cast(str, content['message']) elif 'Message' in content: return cast(str, content['Message']) except Exception: logging.debug(f'Failed to parse the response content: {raw.decode()}') return response.reason
null
2,362
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def get_auth_header(token: str) -> dict[str, str]: return { 'Authorization': token }
null
2,363
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def get_prisma_auth_header(token: str) -> dict[str, str]: return { 'x-redlock-auth': token }
null
2,364
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def get_version_headers(client: str, client_version: str | None) -> dict[str, str]: return { 'x-api-client': client, 'x-api-version': client_version or "unknown", 'x-api-checkov-version': checkov_version } def get_user_agent_header() -> dict[str, str]: return {'User-Agent': f'checkov/{checkov_version}'} DEV_API_GET_HEADERS = { 'Accept': 'application/json' } def merge_dicts(*dicts: dict[_T, Any]) -> dict[_T, Any]: """ Merges two or more dicts. If there are duplicate keys, later dict arguments take precedence. Null, empty, or non-dict arguments are qiuetly skipped. :param dicts: :return: """ res: dict[Any, Any] = {} for d in dicts: if not d or not isinstance(d, dict): continue res = {**res, **d} return res class SourceType: __slots__ = ("name", "upload_results") def __init__(self, name: str, upload_results: bool): self.name = name self.upload_results = upload_results def get_default_get_headers(client: SourceType, client_version: str | None) -> dict[str, Any]: return merge_dicts(DEV_API_GET_HEADERS, get_version_headers(client.name, client_version), get_user_agent_header())
null
2,365
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def get_version_headers(client: str, client_version: str | None) -> dict[str, str]: return { 'x-api-client': client, 'x-api-version': client_version or "unknown", 'x-api-checkov-version': checkov_version } def get_user_agent_header() -> dict[str, str]: return {'User-Agent': f'checkov/{checkov_version}'} DEV_API_POST_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/json' } def merge_dicts(*dicts: dict[_T, Any]) -> dict[_T, Any]: """ Merges two or more dicts. If there are duplicate keys, later dict arguments take precedence. Null, empty, or non-dict arguments are qiuetly skipped. :param dicts: :return: """ res: dict[Any, Any] = {} for d in dicts: if not d or not isinstance(d, dict): continue res = {**res, **d} return res class SourceType: __slots__ = ("name", "upload_results") def __init__(self, name: str, upload_results: bool): self.name = name self.upload_results = upload_results def get_default_post_headers(client: SourceType, client_version: str | None) -> dict[str, Any]: return merge_dicts(DEV_API_POST_HEADERS, get_version_headers(client.name, client_version), get_user_agent_header())
null
2,366
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version def get_user_agent_header() -> dict[str, str]: return {'User-Agent': f'checkov/{checkov_version}'} PRISMA_API_GET_HEADERS = { 'Accept': 'application/json; charset=UTF-8' } def merge_dicts(*dicts: dict[_T, Any]) -> dict[_T, Any]: """ Merges two or more dicts. If there are duplicate keys, later dict arguments take precedence. Null, empty, or non-dict arguments are qiuetly skipped. :param dicts: :return: """ res: dict[Any, Any] = {} for d in dicts: if not d or not isinstance(d, dict): continue res = {**res, **d} return res def get_prisma_get_headers() -> dict[str, str]: return merge_dicts(PRISMA_API_GET_HEADERS, get_user_agent_header())
null
2,367
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version The provided code snippet includes necessary dependencies for implementing the `valid_url` function. Write a Python function `def valid_url(url: str | None) -> bool` to solve the following problem: Checks for a valid URL, otherwise returns False Here is the function: def valid_url(url: str | None) -> bool: """Checks for a valid URL, otherwise returns False""" if not url: return False try: result = parse_url(url) return all([result.scheme, result.netloc]) except Exception: return False
Checks for a valid URL, otherwise returns False
2,368
from __future__ import annotations import json import uuid import requests import logging import time import os import aiohttp import asyncio from typing import Any, TYPE_CHECKING, cast, Optional, overload from urllib3.response import HTTPResponse from urllib3.util import parse_url from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger from checkov.common.util.consts import DEV_API_GET_HEADERS, DEV_API_POST_HEADERS, PRISMA_API_GET_HEADERS, \ PRISMA_PLATFORM, BRIDGECREW_PLATFORM from checkov.common.util.data_structures_utils import merge_dicts from checkov.common.util.type_forcers import force_int, force_float from checkov.version import version as checkov_version async def aiohttp_client_session_wrapper( url: str, headers: dict[str, Any], payload: dict[str, Any] ) -> int: request_max_tries = int(os.getenv('REQUEST_MAX_TRIES', 3)) sleep_between_request_tries = float(os.getenv('SLEEP_BETWEEN_REQUEST_TRIES', 1)) # adding retry mechanism for avoiding the next repeated unexpected issues: # 1. Gateway Timeout from the server # 2. ClientOSError async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(resolver=aiohttp.AsyncResolver())) as session: for i in range(request_max_tries): logging.info( f"[http_utils](aiohttp_client_session_wrapper) reporting attempt {i + 1} out of {request_max_tries}") try: async with session.post( url=url, headers=headers, json=payload ) as response: content = await response.text() if response.ok: logging.info(f"[http_utils](aiohttp_client_session_wrapper) - done successfully to url: \'{url}\'") return 0 elif i != request_max_tries - 1: await asyncio.sleep(sleep_between_request_tries * (i + 1)) continue else: logging.error(f"[http_utils](aiohttp_client_session_wrapper) - Failed to send report to " f"url \'{url}\'") logging.error(f"Status code: {response.status}, Reason: {response.reason}, Content: {content}") return 1 except aiohttp.ClientOSError: if i != request_max_tries - 1: await asyncio.sleep(sleep_between_request_tries * (i + 1)) continue else: logging.error(f"[http_utils](aiohttp_client_session_wrapper) - ClientOSError when sending report " f"to url: \'{url}\'") raise except Exception as e: logging.error(f"[http_utils](aiohttp_client_session_wrapper) - exception when sending report " f"to url: \'{url}\':\n\'{e}\'") raise else: raise Exception("Unexpected behavior: the method \'aiohttp_client_session_wrapper\' should be terminated " "inside the above for-loop")
null
2,369
from __future__ import annotations import os from pathlib import Path def config_file_paths(dir_path: str | Path) -> list[str]: return [os.path.join(dir_path, '.checkov.yaml'), os.path.join(dir_path, '.checkov.yml')] The provided code snippet includes necessary dependencies for implementing the `get_default_config_paths` function. Write a Python function `def get_default_config_paths(argv: list[str]) -> list[str]` to solve the following problem: Checkov looks for .checkov.yml or .checkov.yaml file in the directory (--directory) against which it is run. If that does not have the config file, the current working directory is checked followed by checking the user's home directory is searched. :param argv: List of CLI args from sys.argv. :return: List of default config file paths. Here is the function: def get_default_config_paths(argv: list[str]) -> list[str]: """ Checkov looks for .checkov.yml or .checkov.yaml file in the directory (--directory) against which it is run. If that does not have the config file, the current working directory is checked followed by checking the user's home directory is searched. :param argv: List of CLI args from sys.argv. :return: List of default config file paths. """ home_paths = config_file_paths(Path.home()) cwd_path = config_file_paths(Path.cwd()) dir_paths = [] for i, v in enumerate(argv): if v in ('-d', '--directory'): dir_paths += config_file_paths(argv[i + 1]) return dir_paths + cwd_path + home_paths
Checkov looks for .checkov.yml or .checkov.yaml file in the directory (--directory) against which it is run. If that does not have the config file, the current working directory is checked followed by checking the user's home directory is searched. :param argv: List of CLI args from sys.argv. :return: List of default config file paths.
2,370
from __future__ import annotations import logging import pickle from typing import Any, TypeVar, cast def get_inner_dict(source_dict: dict[str, Any], path_as_list: list[str]) -> dict[str, Any]: result = source_dict for index in path_as_list: try: result = result[index] except KeyError: # for getting the source context for resources with for_each name - index can be "resource_name[0]" for k in result: if index.startswith(k): result = result[k] return result
null
2,371
from __future__ import annotations import logging import pickle from typing import Any, TypeVar, cast The provided code snippet includes necessary dependencies for implementing the `search_deep_keys` function. Write a Python function `def search_deep_keys( search_text: str, obj: dict[str, Any] | list[dict[str, Any]] | None, path: list[int | str] ) -> list[list[int | str]]` to solve the following problem: Search deep for keys and get their values Here is the function: def search_deep_keys( search_text: str, obj: dict[str, Any] | list[dict[str, Any]] | None, path: list[int | str] ) -> list[list[int | str]]: """Search deep for keys and get their values""" keys: list[list[int | str]] = [] if isinstance(obj, dict): for key in obj: pathprop = path[:] pathprop.append(key) if key == search_text: pathprop.append(obj[key]) keys.append(pathprop) # pop the last element off for nesting of found elements for # dict and list checks pathprop = pathprop[:-1] if isinstance(obj[key], dict): if key != 'parent_metadata': # Don't go back to the parent metadata, it is scanned for the parent keys.extend(search_deep_keys(search_text, obj[key], pathprop)) elif isinstance(obj[key], list): for index, item in enumerate(obj[key]): pathproparr = pathprop[:] pathproparr.append(index) keys.extend(search_deep_keys(search_text, item, pathproparr)) elif isinstance(obj, list): for index, item in enumerate(obj): pathprop = path[:] pathprop.append(index) keys.extend(search_deep_keys(search_text, item, pathprop)) return keys
Search deep for keys and get their values
2,372
from __future__ import annotations import logging import pickle from typing import Any, TypeVar, cast The provided code snippet includes necessary dependencies for implementing the `get_empty_list_str` function. Write a Python function `def get_empty_list_str() -> list[str]` to solve the following problem: Returns an empty list with type 'list[str]' This is needed for using empty lists with a list union type hint ex. foo: list[str] | list[int] = [] more info can be found here https://github.com/python/mypy/issues/6463 Here is the function: def get_empty_list_str() -> list[str]: """Returns an empty list with type 'list[str]' This is needed for using empty lists with a list union type hint ex. foo: list[str] | list[int] = [] more info can be found here https://github.com/python/mypy/issues/6463 """ return []
Returns an empty list with type 'list[str]' This is needed for using empty lists with a list union type hint ex. foo: list[str] | list[int] = [] more info can be found here https://github.com/python/mypy/issues/6463
2,373
from __future__ import annotations from datetime import timedelta import logging from functools import wraps from timeit import default_timer from typing import TypeVar, Callable from typing_extensions import ParamSpec T = TypeVar("T") P = ParamSpec("P") The provided code snippet includes necessary dependencies for implementing the `time_it` function. Write a Python function `def time_it(func: Callable[P, T]) -> Callable[P, T]` to solve the following problem: Prints the time it took to execute the function Here is the function: def time_it(func: Callable[P, T]) -> Callable[P, T]: """Prints the time it took to execute the function""" @wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: start = default_timer() output = func(*args, **kwargs) end = default_timer() func_path = f"{func.__code__.co_filename.replace('.py', '')}.{func.__name__}" logging.info(f"'{func_path}' took: {timedelta(seconds=end - start)}\n") return output return wrapper
Prints the time it took to execute the function
2,374
from __future__ import annotations from typing import Any, TypeVar, Callable, Protocol from typing_extensions import TypeAlias from checkov.common.util.data_structures_utils import pickle_deepcopy _MergeDict = TypeVar("_MergeDict", bound="dict[Any, Any]") _OverwriteFunc: TypeAlias = "Callable[..., Any]" def overwrite(v1: _T, v2: _T, **kwargs: Any) -> _T: """ Completely overwrites one value with another. """ return pickle_deepcopy(v2) The provided code snippet includes necessary dependencies for implementing the `merge_dicts` function. Write a Python function `def merge_dicts( d1: _MergeDict, d2: _MergeDict, merge_lists: _OverwriteFunc = overwrite, merge_ints: _OverwriteFunc = overwrite, merge_floats: _OverwriteFunc = overwrite, merge_strings: _OverwriteFunc = overwrite, merge_other: _OverwriteFunc = overwrite, ) -> _MergeDict` to solve the following problem: Recursively merges values from d2 into d1. Here is the function: def merge_dicts( d1: _MergeDict, d2: _MergeDict, merge_lists: _OverwriteFunc = overwrite, merge_ints: _OverwriteFunc = overwrite, merge_floats: _OverwriteFunc = overwrite, merge_strings: _OverwriteFunc = overwrite, merge_other: _OverwriteFunc = overwrite, ) -> _MergeDict: """ Recursively merges values from d2 into d1. """ kwargs = { "merge_lists": merge_lists, "merge_ints": merge_ints, "merge_floats": merge_floats, "merge_strings": merge_strings, "merge_other": merge_other, } for key in d2: if key in d1: if isinstance(d1[key], dict) and isinstance(d2[key], dict): d1[key] = merge_dicts(d1[key], d2[key], **kwargs) elif isinstance(d1[key], list) and isinstance(d2[key], list): d1[key] = merge_lists(d1[key], d2[key], **kwargs) elif isinstance(d1[key], int) and isinstance(d2[key], int): d1[key] = merge_ints(d1[key], d2[key], **kwargs) elif isinstance(d1[key], float) and isinstance(d2[key], float): d1[key] = merge_ints(d1[key], d2[key], **kwargs) elif isinstance(d1[key], str) and isinstance(d2[key], str): d1[key] = merge_strings(d1[key], d2[key], **kwargs) else: d1[key] = merge_other(d1[key], d2[key], **kwargs) else: d1[key] = overwrite(None, d2[key]) return d1
Recursively merges values from d2 into d1.
2,375
from __future__ import annotations from typing import Any, TypeVar, Callable, Protocol from typing_extensions import TypeAlias from checkov.common.util.data_structures_utils import pickle_deepcopy _MergeDict = TypeVar("_MergeDict", bound="dict[Any, Any]") _OverwriteFunc: TypeAlias = "Callable[..., Any]" class _MergeDictsFunc(Protocol): def __call__( self, d1: _MergeDict, d2: _MergeDict, *, merge_lists: _OverwriteFunc, merge_ints: _OverwriteFunc, merge_floats: _OverwriteFunc, merge_strings: _OverwriteFunc, merge_other: _OverwriteFunc, ) -> _MergeDict: ... def overwrite(v1: _T, v2: _T, **kwargs: Any) -> _T: """ Completely overwrites one value with another. """ return pickle_deepcopy(v2) The provided code snippet includes necessary dependencies for implementing the `pickle_deep_merge` function. Write a Python function `def pickle_deep_merge( *dicts: _MergeDict, merge_dicts: _MergeDictsFunc = merge_dicts, merge_lists: _OverwriteFunc = overwrite, merge_ints: _OverwriteFunc = overwrite, merge_floats: _OverwriteFunc = overwrite, merge_strings: _OverwriteFunc = overwrite, merge_other: _OverwriteFunc = overwrite, ) -> _MergeDict` to solve the following problem: Recursively merges dictionaries and the datastructures they contain. :Parameters: *dicts : `dict` Dictionaries to be merged. Items that appear last will take higher precedence when merging. merge_dicts : `func` The function to apply when merging dictionaries. merge_lists : `func` The function to apply when merging lists. merge_ints : `func` The function to apply when merging integers. merge_floats : `func` The function to apply when merging floats. merge_strings : `func` The function to apply when merging strings. merge_other : `func` The function to apply when merging other types or types that do not match. Here is the function: def pickle_deep_merge( *dicts: _MergeDict, merge_dicts: _MergeDictsFunc = merge_dicts, merge_lists: _OverwriteFunc = overwrite, merge_ints: _OverwriteFunc = overwrite, merge_floats: _OverwriteFunc = overwrite, merge_strings: _OverwriteFunc = overwrite, merge_other: _OverwriteFunc = overwrite, ) -> _MergeDict: """ Recursively merges dictionaries and the datastructures they contain. :Parameters: *dicts : `dict` Dictionaries to be merged. Items that appear last will take higher precedence when merging. merge_dicts : `func` The function to apply when merging dictionaries. merge_lists : `func` The function to apply when merging lists. merge_ints : `func` The function to apply when merging integers. merge_floats : `func` The function to apply when merging floats. merge_strings : `func` The function to apply when merging strings. merge_other : `func` The function to apply when merging other types or types that do not match. """ for param in dicts: if not isinstance(param, dict): raise TypeError("{0} is not a dict".format(param)) d = dicts[0] for d_update in dicts[1:]: d = merge_dicts( d, d_update, merge_lists=merge_lists, merge_ints=merge_ints, merge_floats=merge_floats, merge_strings=merge_strings, merge_other=merge_other, ) return d
Recursively merges dictionaries and the datastructures they contain. :Parameters: *dicts : `dict` Dictionaries to be merged. Items that appear last will take higher precedence when merging. merge_dicts : `func` The function to apply when merging dictionaries. merge_lists : `func` The function to apply when merging lists. merge_ints : `func` The function to apply when merging integers. merge_floats : `func` The function to apply when merging floats. merge_strings : `func` The function to apply when merging strings. merge_other : `func` The function to apply when merging other types or types that do not match.
2,376
import os from contextlib import contextmanager from typing import Any, Generator The provided code snippet includes necessary dependencies for implementing the `temp_environ` function. Write a Python function `def temp_environ(**kwargs: Any) -> Generator[None, None, None]` to solve the following problem: Temporarily set environment variables and restores previous values copy of https://gist.github.com/igniteflow/7267431?permalink_comment_id=2553451#gistcomment-2553451 Here is the function: def temp_environ(**kwargs: Any) -> Generator[None, None, None]: """Temporarily set environment variables and restores previous values copy of https://gist.github.com/igniteflow/7267431?permalink_comment_id=2553451#gistcomment-2553451 """ original_env = {key: os.getenv(key) for key in kwargs} os.environ.update(kwargs) try: yield finally: for key, value in original_env.items(): if value is None: del os.environ[key] else: os.environ[key] = value
Temporarily set environment variables and restores previous values copy of https://gist.github.com/igniteflow/7267431?permalink_comment_id=2553451#gistcomment-2553451
2,377
from __future__ import annotations import json import logging import typing from json import JSONDecodeError from typing import TypeVar, overload, Any, Dict import yaml def force_float(var: Any) -> float | None: try: if not isinstance(var, float): return float(var) return var except Exception: return None
null
2,378
from __future__ import annotations import json import logging import typing from json import JSONDecodeError from typing import TypeVar, overload, Any, Dict import yaml def is_json(data: str) -> bool: try: parsed = json.loads(data) return isinstance(parsed, dict) except (TypeError, ValueError): logging.debug(f"could not parse json data: {data}") return False
null
2,379
from __future__ import annotations import json import logging import typing from json import JSONDecodeError from typing import TypeVar, overload, Any, Dict import yaml def is_yaml(data: str) -> bool: try: parsed = yaml.safe_load(data) return isinstance(parsed, dict) except yaml.YAMLError: logging.debug(f"could not parse yaml data: {data}") return False
null
2,380
from __future__ import annotations import json import logging import typing from json import JSONDecodeError from typing import TypeVar, overload, Any, Dict import yaml The provided code snippet includes necessary dependencies for implementing the `convert_csv_string_arg_to_list` function. Write a Python function `def convert_csv_string_arg_to_list(csv_string_arg: list[str] | str | None) -> list[str]` to solve the following problem: Converts list type arguments that also support comma delimited strings into a list. For instance the --check flag in the CLI: checkov -c CKV_1,CKV2 will translate to ['CKV_1', 'CKV_2'] :param csv_string_arg: Comma delimited string :return: List of strings or empty list Here is the function: def convert_csv_string_arg_to_list(csv_string_arg: list[str] | str | None) -> list[str]: """ Converts list type arguments that also support comma delimited strings into a list. For instance the --check flag in the CLI: checkov -c CKV_1,CKV2 will translate to ['CKV_1', 'CKV_2'] :param csv_string_arg: Comma delimited string :return: List of strings or empty list """ if csv_string_arg is None: return [] if isinstance(csv_string_arg, str): return csv_string_arg.split(',') elif isinstance(csv_string_arg, list) and len(csv_string_arg) == 1: return csv_string_arg[0].split(',') else: return csv_string_arg
Converts list type arguments that also support comma delimited strings into a list. For instance the --check flag in the CLI: checkov -c CKV_1,CKV2 will translate to ['CKV_1', 'CKV_2'] :param csv_string_arg: Comma delimited string :return: List of strings or empty list
2,381
from __future__ import annotations import json import logging import typing from json import JSONDecodeError from typing import TypeVar, overload, Any, Dict import yaml The provided code snippet includes necessary dependencies for implementing the `convert_prisma_policy_filter_to_dict` function. Write a Python function `def convert_prisma_policy_filter_to_dict(filter_string: str) -> Dict[Any, Any]` to solve the following problem: Converts the filter string to a dict. For example: 'policy.label=label,cloud.type=aws' becomes --> {'policy.label': 'label1', 'cloud.type': 'aws'} Note that the API does not accept lists https://prisma.pan.dev/api/cloud/cspm/policy#operation/get-policies-v2 This is not allowed: policy.label=label1,label2 Here is the function: def convert_prisma_policy_filter_to_dict(filter_string: str) -> Dict[Any, Any]: """ Converts the filter string to a dict. For example: 'policy.label=label,cloud.type=aws' becomes --> {'policy.label': 'label1', 'cloud.type': 'aws'} Note that the API does not accept lists https://prisma.pan.dev/api/cloud/cspm/policy#operation/get-policies-v2 This is not allowed: policy.label=label1,label2 """ filter_params = {} if isinstance(filter_string, str) and filter_string: filter_string = "".join(filter_string.split()) try: for f in filter_string.split(','): f_name, f_value = f.split('=') filter_params[f_name] = f_value except (IndexError, ValueError) as e: logging.debug(f"Invalid filter format: {e}") return filter_params
Converts the filter string to a dict. For example: 'policy.label=label,cloud.type=aws' becomes --> {'policy.label': 'label1', 'cloud.type': 'aws'} Note that the API does not accept lists https://prisma.pan.dev/api/cloud/cspm/policy#operation/get-policies-v2 This is not allowed: policy.label=label1,label2
2,382
import re from typing import Any from checkov.common.util.parser_utils import find_var_blocks TF_OPERATOR_PREFIXES = ("lookup(", "list(", "file(") TF_BLOCK_REFS = ("var.", "local.", "module.", "data.") TF_PROVIDER_PREFIXES = ( "aws_", "azurerm_", "azuread_", "digitalocean_", "google_", "github_", "kubernetes_", "linode_", "oci_", "openstack_", "yandex_", ) def find_var_blocks(value: str) -> List[VarBlockMatch]: """ Find and return all the var blocks within a given string. Order is important and may contain portions of one another. """ if "$" not in value: # not relevant, typically just a normal string value return [] to_return: List[VarBlockMatch] = [] mode_stack: List[ParserMode] = [] eval_start_pos_stack: List[int] = [] # location of first char inside brackets param_start_pos_stack: List[int] = [] # location of open parens preceding_dollar = False preceding_string_escape = False # NOTE: function calls can be nested, but since param args are only being inspected for variables, # it's alright to ignore outer calls. param_arg_start = -1 for index, c in enumerate(value): current_mode = ParserMode.BLANK if not mode_stack else mode_stack[-1] # Print statement of power... # print(f"{str(index).ljust(3, ' ')} {c} {'$' if preceding_dollar else ' '} " # f"{'`' if preceding_string_escape else ' '} " # f"{current_mode.ljust(2)} - {mode_stack}") if c == "$": if preceding_dollar: # ignore double $ preceding_dollar = False continue preceding_dollar = True continue if c == "{" and preceding_dollar: mode_stack.append(ParserMode.EVAL) eval_start_pos_stack.append(index + 1) # next char preceding_dollar = False continue elif c == "\\" and ParserMode.is_string(current_mode): preceding_string_escape = True continue preceding_dollar = False if c == "}": if current_mode == ParserMode.EVAL: mode_stack.pop() start_pos = eval_start_pos_stack.pop() eval_string = value[start_pos:index] to_return.append(VarBlockMatch("${" + eval_string + "}", eval_string)) elif current_mode == ParserMode.MAP: mode_stack.pop() elif c == "]" and current_mode == ParserMode.ARRAY: mode_stack.pop() elif c == ")" and current_mode == ParserMode.PARAMS: if param_arg_start > 0: param_arg = value[param_arg_start:index].strip() if _ARG_VAR_PATTERN.match(param_arg): to_return.append(VarBlockMatch(param_arg, param_arg)) param_arg_start = -1 mode_stack.pop() start_pos = param_start_pos_stack.pop() # See if these params are for a function call. Back up from the index to determine if there's # a function preceding. function_name_start_index = start_pos for function_index in range(start_pos - 1, 0, -1): if value[function_index] in _FUNCTION_NAME_CHARS: function_name_start_index = function_index else: break # We know now there's a function call here. But, don't call it out if it's directly wrapped # in eval markers. in_eval_markers = False if function_name_start_index >= 2: in_eval_markers = ( value[function_name_start_index - 2] == "$" and value[function_name_start_index - 1] == "{" ) if function_name_start_index < start_pos and not in_eval_markers: to_return.append( VarBlockMatch( value[function_name_start_index : index + 1], value[function_name_start_index : index + 1] ) ) elif c == '"': if preceding_string_escape: preceding_string_escape = False continue elif current_mode == ParserMode.STRING_DOUBLE_QUOTE: mode_stack.pop() else: mode_stack.append(ParserMode.STRING_DOUBLE_QUOTE) elif c == "'": if preceding_string_escape: preceding_string_escape = False continue elif current_mode == ParserMode.STRING_SINGLE_QUOTE: mode_stack.pop() else: mode_stack.append(ParserMode.STRING_SINGLE_QUOTE) elif c == "{": # NOTE: Can't be preceded by a dollar sign (that was checked earlier) if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.MAP) elif c == "[": # do we care? if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.ARRAY) elif c == "(": # do we care? if not ParserMode.is_string(current_mode): mode_stack.append(ParserMode.PARAMS) param_start_pos_stack.append(index) param_arg_start = index + 1 elif c == ",": if current_mode == ParserMode.PARAMS and param_arg_start > 0: param_arg = value[param_arg_start:index].strip() if _ARG_VAR_PATTERN.match(param_arg): to_return.append(VarBlockMatch(param_arg, param_arg)) param_arg_start = index + 1 elif c == "?" and current_mode == ParserMode.EVAL: # ternary # If what's been processed in the ternary so far is "true" or "false" (boolean or string type) # then nothing special will happen here and only the full expression will be returned. # Anything else will be treated as an unresolved variable block. start_pos = eval_start_pos_stack[-1] # DO NOT pop: there's no separate eval start indicator eval_string = value[start_pos:index].strip() # HACK ALERT: For the cases with the trailing quotes, see: # test_hcl2_load_assumptions.py -> test_weird_ternary_string_clipping if eval_string not in {"true", "false", '"true"', '"false"', 'true"', 'false"'}: # REMINDER: The eval string is not wrapped in a eval markers since they didn't really # appear in the original value. If they're put in, substitution doesn't # work properly. to_return.append(VarBlockMatch(eval_string, eval_string)) preceding_string_escape = False return to_return def is_terraform_variable_dependent(value: Any) -> bool: if not isinstance(value, str): return False if value.startswith(TF_BLOCK_REFS): return True if value.startswith(TF_PROVIDER_PREFIXES): return True if value.startswith(TF_OPERATOR_PREFIXES): return True if "${" not in value: return False if find_var_blocks(value): return True return False
null
2,383
import re from typing import Any from checkov.common.util.parser_utils import find_var_blocks CFN_VARIABLE_DEPENDANT_REGEX = re.compile(r"(?:Ref)\.\S+") def is_cloudformation_variable_dependent(value: Any) -> bool: if isinstance(value, str) and re.match(CFN_VARIABLE_DEPENDANT_REGEX, value): return True return False
null
2,384
from __future__ import annotations import os import pickle import re from collections.abc import Generator, Callable from typing import Any import requests import sys import time from datetime import datetime from functools import wraps from tempfile import gettempdir class UpdateResult: """Contains the information for a package that has an update.""" def __init__(self, package: str, running: str, available: str, release_date: str | None) -> None: """Initialize an UpdateResult instance.""" self.available_version = available self.package_name = package self.running_version = running if release_date: self.release_date: datetime | None = datetime.strptime(release_date, "%Y-%m-%dT%H:%M:%S") else: self.release_date = None def __str__(self) -> str: """Return a printable UpdateResult string.""" retval = f"Version {self.running_version} of {self.package_name} is outdated. Version {self.available_version} " if self.release_date: retval += f"was released {pretty_date(self.release_date)}." else: retval += "is available." return retval class UpdateChecker: """A class to check for package updates.""" def __init__(self, *, bypass_cache: bool = False) -> None: self._bypass_cache = bypass_cache def check(self, package_name: str, package_version: str) -> UpdateResult | None: """Return a UpdateResult object if there is a newer version.""" data = query_pypi(package_name, include_prereleases=not standard_release(package_version)) if not data.get("success") or (parse_version(package_version) >= parse_version(data["data"]["version"])): return None return UpdateResult( package_name, running=package_version, available=data["data"]["version"], release_date=data["data"]["upload_time"], ) The provided code snippet includes necessary dependencies for implementing the `cache_results` function. Write a Python function `def cache_results( function: Callable[[UpdateChecker, str, str], UpdateResult | None] ) -> Callable[[UpdateChecker, str, str], UpdateResult | None]` to solve the following problem: Return decorated function that caches the results. Here is the function: def cache_results( function: Callable[[UpdateChecker, str, str], UpdateResult | None] ) -> Callable[[UpdateChecker, str, str], UpdateResult | None]: """Return decorated function that caches the results.""" def save_to_permacache() -> None: """Save the in-memory cache data to the permacache. There is a race condition here between two processes updating at the same time. It's perfectly acceptable to lose and/or corrupt the permacache information as each process's in-memory cache will remain in-tact. """ update_from_permacache() try: if filename is None: return with open(filename, "wb") as fp: pickle.dump(cache, fp, pickle.HIGHEST_PROTOCOL) except IOError: pass # Ignore permacache saving exceptions def update_from_permacache() -> None: """Attempt to update newer items from the permacache.""" try: if filename is None: return with open(filename, "rb") as fp: permacache = pickle.load(fp) # nosec except Exception: # TODO: Handle specific exceptions return # It's okay if it cannot load for key, value in permacache.items(): if key not in cache or value[0] > cache[key][0]: cache[key] = value cache: dict[tuple[str, str], tuple[float, UpdateResult | None]] = {} cache_expire_time = 3600 try: filename = os.path.join(gettempdir(), "update_checker_cache.pkl") update_from_permacache() except NotImplementedError: filename = None @wraps(function) def wrapped(obj: UpdateChecker, package_name: str, package_version: str, **extra_data: Any) -> UpdateResult | None: """Return cached results if available.""" now = time.time() key = (package_name, package_version) if not obj._bypass_cache and key in cache: # Check the in-memory cache cache_time, retval = cache[key] if now - cache_time < cache_expire_time: return retval retval = function(obj, package_name, package_version, **extra_data) cache[key] = now, retval if filename: save_to_permacache() return retval return wrapped
Return decorated function that caches the results.
2,385
from __future__ import annotations import os import pickle import re from collections.abc import Generator, Callable from typing import Any import requests import sys import time from datetime import datetime from functools import wraps from tempfile import gettempdir def standard_release(version: str) -> bool: return version.replace(".", "").isdigit() def parse_version(s: str) -> tuple[str, ...]: """Convert a version string to a chronologically-sortable key. This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It is *possible* to create pathological version coding schemes that will fool this parser, but they should be very rare in practice. The returned value will be a tuple of strings. Numeric portions of the version are padded to 8 digits so they will compare numerically, but without relying on how numbers compare relative to strings. Dots are dropped, but dashes are retained. Trailing zeros between alpha segments or dashes are suppressed, so that e.g. "2.4.0" is considered the same as "2.4". Alphanumeric parts are lower-cased. The algorithm assumes that strings like "-" and any alpha string that alphabetically follows "final" represents a "patch level". So, "2.4-1" is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is considered newer than "2.4-1", which in turn is newer than "2.4". Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that come before "final" alphabetically) are assumed to be pre-release versions, so that the version "2.4" is considered newer than "2.4a1". Finally, to handle miscellaneous cases, the strings "pre", "preview", and "rc" are treated as if they were "c", i.e. as though they were release candidates, and therefore are not as new as a version string that does not contain them, and "dev" is replaced with an '@' so that it sorts lower than than any other pre-release tag. """ parts: list[str] = [] for part in _parse_version_parts(s.lower()): if part.startswith("*"): if part < "*final": # remove '-' before a prerelease tag while parts and parts[-1] == "*final-": parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == "00000000": parts.pop() parts.append(part) return tuple(parts) The provided code snippet includes necessary dependencies for implementing the `query_pypi` function. Write a Python function `def query_pypi(package: str, include_prereleases: bool) -> dict[str, Any]` to solve the following problem: Return information about the current version of package. Here is the function: def query_pypi(package: str, include_prereleases: bool) -> dict[str, Any]: """Return information about the current version of package.""" try: response = requests.get(f"https://pypi.org/pypi/{package}/json", timeout=1) except requests.exceptions.RequestException: return {"success": False} if response.status_code != 200: return {"success": False} data = response.json() versions = list(data["releases"].keys()) versions.sort(key=parse_version, reverse=True) version = versions[0] for tmp_version in versions: if include_prereleases or standard_release(tmp_version): version = tmp_version break upload_time = None for file_info in data["releases"][version]: if file_info["upload_time"]: upload_time = file_info["upload_time"] break return {"success": True, "data": {"upload_time": upload_time, "version": version}}
Return information about the current version of package.
2,386
from __future__ import annotations import os import pickle import re from collections.abc import Generator, Callable from typing import Any import requests import sys import time from datetime import datetime from functools import wraps from tempfile import gettempdir The provided code snippet includes necessary dependencies for implementing the `pretty_date` function. Write a Python function `def pretty_date(the_datetime: datetime) -> str` to solve the following problem: Attempt to return a human-readable time delta string. Here is the function: def pretty_date(the_datetime: datetime) -> str: """Attempt to return a human-readable time delta string.""" # Source modified from # http://stackoverflow.com/a/5164027/176978 diff = datetime.utcnow() - the_datetime if diff.days > 7 or diff.days < 0: return the_datetime.strftime("%A %B %d, %Y") elif diff.days == 1: return "1 day ago" elif diff.days > 1: return f"{diff.days} days ago" elif diff.seconds <= 1: return "just now" elif diff.seconds < 60: return f"{diff.seconds} seconds ago" elif diff.seconds < 120: return "1 minute ago" elif diff.seconds < 3600: return f"{int(round(diff.seconds / 60))} minutes ago" elif diff.seconds < 7200: return "1 hour ago" else: return f"{int(round(diff.seconds / 3600))} hours ago"
Attempt to return a human-readable time delta string.
2,387
from __future__ import annotations import os import pickle import re from collections.abc import Generator, Callable from typing import Any import requests import sys import time from datetime import datetime from functools import wraps from tempfile import gettempdir class UpdateChecker: """A class to check for package updates.""" def __init__(self, *, bypass_cache: bool = False) -> None: self._bypass_cache = bypass_cache def check(self, package_name: str, package_version: str) -> UpdateResult | None: """Return a UpdateResult object if there is a newer version.""" data = query_pypi(package_name, include_prereleases=not standard_release(package_version)) if not data.get("success") or (parse_version(package_version) >= parse_version(data["data"]["version"])): return None return UpdateResult( package_name, running=package_version, available=data["data"]["version"], release_date=data["data"]["upload_time"], ) The provided code snippet includes necessary dependencies for implementing the `update_check` function. Write a Python function `def update_check(package_name: str, package_version: str, bypass_cache: bool = False) -> None` to solve the following problem: Convenience method that outputs to stderr if an update is available. Here is the function: def update_check(package_name: str, package_version: str, bypass_cache: bool = False) -> None: """Convenience method that outputs to stderr if an update is available.""" checker = UpdateChecker(bypass_cache=bypass_cache) result = checker.check(package_name, package_version) if result: print(result, file=sys.stderr)
Convenience method that outputs to stderr if an update is available.
2,388
from __future__ import annotations import itertools import json import logging import re from typing import Any, TYPE_CHECKING from checkov.common.models.enums import CheckCategories, CheckResult from checkov.common.util.consts import RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK _patterns = {k: [re.compile(p, re.DOTALL) for p in v] for k, v in _secrets_regexes.items()} _patterns['all'] = list(itertools.chain.from_iterable(_patterns.values())) def is_hash(s: str) -> bool: """ Checks whether a string is a MD5 or SHA1 hash :param s: :return: """ return any(pattern.search(s) for pattern in _hash_patterns) The provided code snippet includes necessary dependencies for implementing the `string_has_secrets` function. Write a Python function `def string_has_secrets(s: str, *categories: str) -> bool` to solve the following problem: Check whether the specified string has any matches for the regexes in the specified category(ies). If categories is blank, then this method checks all categories. It is recommended to use the category constants provided. Examples: string_has_secrets(some_string) -> checks all regexes string_has_secrets(some_string, AWS, GENERAL) -> checks only AWS and general regexes. :param s: :param categories: :return: Here is the function: def string_has_secrets(s: str, *categories: str) -> bool: """ Check whether the specified string has any matches for the regexes in the specified category(ies). If categories is blank, then this method checks all categories. It is recommended to use the category constants provided. Examples: string_has_secrets(some_string) -> checks all regexes string_has_secrets(some_string, AWS, GENERAL) -> checks only AWS and general regexes. :param s: :param categories: :return: """ if is_hash(s): return False # set a default if no category is provided; or, if categories were provided and they include 'all', then just set it # explicitly so we don't do any duplication if not categories or "all" in categories: categories = ("all",) for c in categories: if any([pattern.search(s) for pattern in _patterns[c]]): return True return False
Check whether the specified string has any matches for the regexes in the specified category(ies). If categories is blank, then this method checks all categories. It is recommended to use the category constants provided. Examples: string_has_secrets(some_string) -> checks all regexes string_has_secrets(some_string, AWS, GENERAL) -> checks only AWS and general regexes. :param s: :param categories: :return:
2,389
from __future__ import annotations import itertools import json import logging import re from typing import Any, TYPE_CHECKING from checkov.common.models.enums import CheckCategories, CheckResult from checkov.common.util.consts import RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK def omit_multiple_secret_values_from_line(secrets: set[str], line_text: str) -> str: censored_line = line_text for secret in secrets: censored_line = omit_secret_value_from_line(secret, censored_line) return censored_line class CheckResult(str, Enum): PASSED = "PASSED" FAILED = "FAILED" # Unknown should be used when a check does not wish to return a result, generally due to the inability # to resolve a value or similar types of errors. UNKNOWN = "UNKNOWN" # Skipped is used by the framework when a test is suppressed and should not be used directly by checks. SKIPPED = "SKIPPED" class CheckCategories(Enum): LOGGING = 1 ENCRYPTION = 2 GENERAL_SECURITY = 3 NETWORKING = 4 IAM = 5 BACKUP_AND_RECOVERY = 6 CONVENTION = 7 SECRETS = 8 KUBERNETES = 9 APPLICATION_SECURITY = 10 SUPPLY_CHAIN = 11 API_SECURITY = 12 SAST = 13 RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK = '*' class BaseCheck(ABC): def __init__( self, name: str, id: str, categories: Iterable[CheckCategories], supported_entities: Iterable[str], block_type: str, bc_id: Optional[str] = None, guideline: Optional[str] = None, ) -> None: self.name = name self.id = id self.bc_id = bc_id self.categories = categories self.block_type = block_type self.path: str | None = None self.supported_entities = supported_entities self.logger = logging.getLogger("{}".format(self.__module__)) add_resource_code_filter_to_logger(self.logger) self.evaluated_keys: List[str] = [] self.entity_path = "" self.entity_type = "" self.guideline = guideline self.benchmarks: dict[str, list[str]] = {} self.severity = None self.bc_category = None self.graph = None if self.guideline: logging.debug(f'Found custom guideline for check {id}') self.details: List[str] = [] self.check_fail_level = os.environ.get('CHECKOV_CHECK_FAIL_LEVEL', CheckFailLevel.ERROR) def run( self, scanned_file: str, entity_configuration: Dict[str, Any], entity_name: str, entity_type: str, skip_info: _SkippedCheck, ) -> _CheckResult: self.details = [] check_result: _CheckResult = {} if skip_info: check_result["result"] = CheckResult.SKIPPED check_result["suppress_comment"] = skip_info["suppress_comment"] self.logger.debug( f'File {scanned_file}, {self.block_type} "{entity_type}.{entity_name}" check "{self.name}" Result: {check_result}, Suppression comment: {check_result["suppress_comment"]}' ) else: try: self.evaluated_keys = [] self.entity_path = f"{scanned_file}:{entity_type}:{entity_name}" check_result["result"] = self.scan_entity_conf(entity_configuration, entity_type) check_result["evaluated_keys"] = self.get_evaluated_keys() self.logger.debug( f'File {scanned_file}, {self.block_type} "{entity_type}.{entity_name}" check "{self.name}" Result: {check_result}' ) except Exception: self.log_check_error(scanned_file=scanned_file, entity_type=entity_type, entity_name=entity_name, entity_configuration=entity_configuration) raise return check_result def scan_entity_conf(self, conf: dict[str, Any], entity_type: str) -> CheckResult | tuple[CheckResult, dict[str, Any]]: raise NotImplementedError() def get_evaluated_keys(self) -> List[str]: """ Retrieves the evaluated keys for the run's report. Child classes override the function and return the `expected_keys` instead. :return: List of the evaluated keys, as JSONPath syntax paths of the checked attributes """ return force_list(self.evaluated_keys) def get_output_id(self, use_bc_ids: bool) -> str: return self.bc_id if self.bc_id and use_bc_ids else self.id def log_check_error(self, scanned_file: str, entity_type: str, entity_name: str, entity_configuration: Dict[str, Any]) -> None: if self.check_fail_level == CheckFailLevel.ERROR: logging.error(f'Failed to run check {self.id} on {scanned_file}:{entity_type}.{entity_name}', exc_info=True) if self.check_fail_level == CheckFailLevel.WARNING: logging.warning(f'Failed to run check {self.id} on {scanned_file}:{entity_type}.{entity_name}') logging.info(f'Entity configuration: {entity_configuration}') ResourceAttributesToOmit: TypeAlias = Dict[_Resource, _Attributes] class _CheckResult(TypedDict, total=False): result: Union["CheckResult", Tuple["CheckResult", dict[str, Any]]] suppress_comment: str evaluated_keys: list[str] results_configuration: dict[str, Any] | None check: BaseCheck entity: dict[str, Any] # only exists for graph results def omit_secret_value_from_checks( check: BaseCheck, check_result: dict[str, CheckResult] | _CheckResult, entity_code_lines: list[tuple[int, str]], entity_config: dict[str, Any] | ParameterAttributes | ResourceAttributes, resource_attributes_to_omit: ResourceAttributesToOmit | None = None ) -> list[tuple[int, str]]: # a set, to efficiently avoid duplicates in case the same secret is found in the following conditions secrets = set() censored_code_lines = [] if CheckCategories.SECRETS in check.categories and check_result.get('result') == CheckResult.FAILED: secrets.update([str(secret) for key, secret in entity_config.items() if key.startswith(f'{check.id}_secret')]) if resource_attributes_to_omit: universal_mask = resource_attributes_to_omit.get(RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK, set()) resource_masks = resource_attributes_to_omit.get(check.entity_type, set()) resource_masks.update(universal_mask) for key, secret in entity_config.items(): if key not in resource_masks: continue if isinstance(secret, list) and secret: if not isinstance(secret[0], str): logging.debug(f"Secret value can't be masked, has type {type(secret)}") continue secrets.add(secret[0]) if not secrets: logging.debug(f"Secret was not saved in {check.id}, can't omit") return entity_code_lines for idx, line in entity_code_lines: censored_line = omit_multiple_secret_values_from_line(secrets, line) censored_code_lines.append((idx, censored_line)) return censored_code_lines
null
2,390
from __future__ import annotations import itertools import json import logging import re from typing import Any, TYPE_CHECKING from checkov.common.models.enums import CheckCategories, CheckResult from checkov.common.util.consts import RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK def omit_multiple_secret_values_from_line(secrets: set[str], line_text: str) -> str: censored_line = line_text for secret in secrets: censored_line = omit_secret_value_from_line(secret, censored_line) return censored_line class CheckResult(str, Enum): PASSED = "PASSED" FAILED = "FAILED" # Unknown should be used when a check does not wish to return a result, generally due to the inability # to resolve a value or similar types of errors. UNKNOWN = "UNKNOWN" # Skipped is used by the framework when a test is suppressed and should not be used directly by checks. SKIPPED = "SKIPPED" class CheckCategories(Enum): LOGGING = 1 ENCRYPTION = 2 GENERAL_SECURITY = 3 NETWORKING = 4 IAM = 5 BACKUP_AND_RECOVERY = 6 CONVENTION = 7 SECRETS = 8 KUBERNETES = 9 APPLICATION_SECURITY = 10 SUPPLY_CHAIN = 11 API_SECURITY = 12 SAST = 13 RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK = '*' class BaseGraphCheck: def __init__(self) -> None: self.id = "" self.bc_id = None self.name = "" self.category = "" self.resource_types: List[str] = [] self.connected_resources_types: List[str] = [] self.operator = "" self.attribute: Optional[str] = None self.attribute_value: Optional[str] = None self.sub_checks: List["BaseGraphCheck"] = [] self.type: Optional[SolverType] = None self.solver: Optional[BaseSolver] = None self.guideline: Optional[str] = None self.benchmarks: Dict[str, List[str]] = {} self.severity: Optional[Severity] = None self.bc_category: Optional[str] = None self.frameworks: List[str] = [] self.is_jsonpath_check: bool = False self.check_path: str = "" def set_solver(self, solver: BaseSolver) -> None: self.solver = solver def run(self, graph_connector: DiGraph) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]: if not self.solver: raise AttributeError("solver attribute was not set") return self.solver.run(graph_connector=graph_connector) def get_output_id(self, use_bc_ids: bool) -> str: return self.bc_id if self.bc_id and use_bc_ids else self.id def get_evaluated_keys(self) -> List[str]: if self.sub_checks: return list(set(itertools.chain.from_iterable(check.get_evaluated_keys() for check in self.sub_checks))) return ["/".join(self.attribute.split('.'))] if self.attribute else [] ResourceAttributesToOmit: TypeAlias = Dict[_Resource, _Attributes] class _CheckResult(TypedDict, total=False): result: Union["CheckResult", Tuple["CheckResult", dict[str, Any]]] suppress_comment: str evaluated_keys: list[str] results_configuration: dict[str, Any] | None check: BaseCheck entity: dict[str, Any] # only exists for graph results def omit_secret_value_from_graph_checks( check: BaseGraphCheck, check_result: dict[str, CheckResult] | _CheckResult, entity_code_lines: list[tuple[int, str]], entity_config: dict[str, Any] | ParameterAttributes | ResourceAttributes, resource_attributes_to_omit: ResourceAttributesToOmit | None = None ) -> list[tuple[int, str]]: # a set, to efficiently avoid duplicates in case the same secret is found in the following conditions secrets = set() censored_code_lines = [] if check.category == CheckCategories.SECRETS.name and check_result.get('result') == CheckResult.FAILED: secrets = { str(secret) for key, secret in entity_config.items() if key.startswith(f'{check.id}_secret') } if resource_attributes_to_omit: # Universal mask ('*') might exist in resource_attributes_to_omit. If it does exist, we need to mask all the # entities in resource types according to resource_attributes_to_omit.get('*') universal_mask = set(resource_attributes_to_omit.get(RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK, set())) for resource in check.resource_types: resource_masks = set(resource_attributes_to_omit.get(resource, set())) # resource_masks should contain all mask rules that should apply on this resource resource_masks.update(universal_mask) if not resource_masks: continue # If entity is one that should be masked, we add it the value to secrets for attribute, secret in entity_config.items(): if attribute in resource_masks: if isinstance(secret, list) and secret: if not isinstance(secret[0], str): logging.debug(f"Secret value can't be masked, has type {type(secret)}") continue secrets.add(secret[0]) if not secrets: logging.debug(f"Secret was not saved in {check.id}, can't omit") return entity_code_lines for idx, line in entity_code_lines: censored_line = omit_multiple_secret_values_from_line(secrets, line) censored_code_lines.append((idx, censored_line)) return censored_code_lines
null
2,391
from __future__ import annotations import itertools import json import logging import re from typing import Any, TYPE_CHECKING from checkov.common.models.enums import CheckCategories, CheckResult from checkov.common.util.consts import RESOURCE_ATTRIBUTES_TO_OMIT_UNIVERSAL_MASK _patterns = {k: [re.compile(p, re.DOTALL) for p in v] for k, v in _secrets_regexes.items()} _patterns['all'] = list(itertools.chain.from_iterable(_patterns.values())) def is_hash(s: str) -> bool: def get_secrets_from_string(s: str, *categories: str) -> list[str]: # set a default if no category is provided; or, if categories were provided and they include 'all', then just set it # explicitly so we don't do any duplication if is_hash(s): return [] if not categories or "all" in categories: categories = ("all",) secrets: list[str] = [] for c in categories: for pattern in _patterns[c]: secrets.extend(str(match.group()) for match in pattern.finditer(s)) return secrets
null
2,392
from __future__ import annotations import re from typing import Iterator, TYPE_CHECKING from packaging import version as packaging_version LegacyCmpKey: TypeAlias = "tuple[int, tuple[str, ...]]" def _parse_version_parts(s: str) -> Iterator[str]: def _legacy_cmpkey(version: str) -> LegacyCmpKey: # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch # greater than or equal to 0. This will effectively put the LegacyVersion, # which uses the defacto standard originally implemented by setuptools, # as before all PEP 440 versions. epoch = -1 # This scheme is taken from pkg_resources.parse_version setuptools prior to # it's adoption of the packaging library. parts: list[str] = [] for part in _parse_version_parts(version.lower()): if part.startswith("*"): # remove "-" before a prerelease tag if part < "*final": while parts and parts[-1] == "*final-": parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == "00000000": parts.pop() parts.append(part) return epoch, tuple(parts)
null
2,393
import re from typing import Union, List, Dict from checkov.cloudformation.graph_builder.variable_rendering.vertex_reference import CloudformationVertexReference from checkov.cloudformation.parser.cfn_keywords import IntrinsicFunctions FIND_INTERPOLATION_PATTERN = re.compile(r"\${([a-zA-Z0-9.]*?)}") def find_all_interpolations(str_value: str) -> List[str]: return re.findall(FIND_INTERPOLATION_PATTERN, str_value)
null
2,394
import re from typing import Union, List, Dict from checkov.cloudformation.graph_builder.variable_rendering.vertex_reference import CloudformationVertexReference from checkov.cloudformation.parser.cfn_keywords import IntrinsicFunctions def get_vertices_references(str_value: str, vertices_block_name_map: Dict[str, Dict[str, List[int]]]) -> List[CloudformationVertexReference]: vertices_references = [] words_in_str_value = str_value.split() for word in words_in_str_value: word_sub_parts = word.split(".") suspected_block = word_sub_parts[0] for block_type, blocks_dict in vertices_block_name_map.items(): if suspected_block in blocks_dict: vertex_reference = CloudformationVertexReference( block_type=block_type, sub_parts=word_sub_parts, origin_value=suspected_block ) if vertex_reference not in vertices_references: vertices_references.append(vertex_reference) break return vertices_references def remove_interpolation(str_value: str, replace_str: str = " ") -> str: if "${" not in str_value: # otherwise it is not an interpolation return str_value return re.sub(REMOVE_INTERPOLATION_PATTERN, replace_str, str_value) class CloudformationVertexReference(VertexReference): def __init__(self, block_type: str, sub_parts: list[str], origin_value: str) -> None: super().__init__(block_type, sub_parts, origin_value) def block_type_str_to_enum(block_type_str: str) -> str: return BlockType().get(block_type_str) class IntrinsicFunctions: BASE64 = "Fn::Base64" CIDR = "Fn::Cidr" FIND_IN_MAP = "Fn::FindInMap" GET_ATT = "Fn::GetAtt" GET_AZS = "Fn::GetAZs" IMPORT_VALUE = "Fn::ImportValue" JOIN = "Fn::Join" SELECT = "Fn::Select" SPLIT = "Fn::Split" SUB = "Fn::Sub" TRANSFORM = "Fn::Transform" REF = "Ref" CONDITION = "Condition" def get_referenced_vertices_in_value( value: Union[str, List[str], Dict[str, str]], vertices_block_name_map: Dict[str, Dict[str, List[int]]], ) -> List[CloudformationVertexReference]: references_vertices = [] if isinstance(value, list): for sub_value in value: references_vertices += get_referenced_vertices_in_value( sub_value, vertices_block_name_map ) if isinstance(value, dict): for key, sub_value in value.items(): if key == IntrinsicFunctions.GET_ATT: sub_value = '.'.join(sub_value) if \ isinstance(sub_value, list) and all(isinstance(s, str) for s in sub_value) else sub_value references_vertices += get_referenced_vertices_in_value( sub_value, vertices_block_name_map ) if isinstance(value, str): value = remove_interpolation(value) references_vertices = get_vertices_references(value, vertices_block_name_map) return references_vertices
null
2,395
from __future__ import annotations import logging import re from inspect import ismethod from typing import Dict, Any, Optional, List, Union, TYPE_CHECKING, Callable, cast from checkov.cloudformation.graph_builder.graph_components.block_types import BlockType from checkov.cloudformation.graph_builder.graph_components.blocks import CloudformationBlock from checkov.cloudformation.graph_builder.utils import GLOBALS_RESOURCE_TYPE_MAP from checkov.cloudformation.graph_builder.variable_rendering.renderer import CloudformationVariableRenderer from checkov.cloudformation.parser.cfn_keywords import IntrinsicFunctions, ConditionFunctions, ResourceAttributes, \ TemplateSections from checkov.common.graph.graph_builder.consts import GraphSource from checkov.common.parsers.node import DictNode from checkov.common.graph.graph_builder import Edge from checkov.common.graph.graph_builder.local_graph import LocalGraph from checkov.common.util.consts import START_LINE, END_LINE from checkov.common.util.data_structures_utils import search_deep_keys from checkov.cloudformation.graph_builder.graph_components.generic_resource_encryption import ENCRYPTION_BY_RESOURCE_TYPE def get_only_dict_items(origin_dict: Union[Dict[str, Any], Any]) -> Dict[str, Dict[str, Any]]: if not isinstance(origin_dict, dict): return {} return {key: value for key, value in origin_dict.items() if isinstance(value, dict)}
null
2,396
from __future__ import annotations import os from typing import List, Dict, Any, Tuple from checkov.cloudformation.graph_builder.graph_components.block_types import BlockType from checkov.cloudformation.parser import TemplateSections from checkov.cloudformation.graph_builder.graph_components.blocks import CloudformationBlock def add_breadcrumbs(vertex: CloudformationBlock, breadcrumbs: Dict[str, Dict[str, Any]], relative_block_path: str) -> None: vertex_breadcrumbs = vertex.breadcrumbs if vertex_breadcrumbs: breadcrumbs.setdefault(relative_block_path, {})[vertex.name] = vertex_breadcrumbs class BlockType(CommonBlockType): METADATA = "metadata" PARAMETERS = "parameters" RULES = "rules" MAPPINGS = "mappings" CONDITIONS = "conditions" TRANSFORM = "transform" OUTPUTS = "outputs" GLOBALS = "globals" class CloudformationBlock(Block): __slots__ = ("condition", "metadata") def __init__( self, name: str, config: Dict[str, Any], path: str, block_type: str, attributes: Dict[str, Any], id: str = "", source: str = "", condition: bool = True, metadata: Optional[Dict[str, Any]] = None ) -> None: """ :param name: unique name given to the terraform block, for example: 'aws_vpc.example_name' :param config: the section in tf_definitions that belong to this block :param path: the file location of the block :param block_type: str :param attributes: dictionary of the block's original attributes in the terraform file """ super().__init__(name, config, path, block_type, attributes, id, source) self.condition = condition self.metadata = metadata def update_attribute( self, attribute_key: str, attribute_value: Any, change_origin_id: int | None, previous_breadcrumbs: List[BreadcrumbMetadata], attribute_at_dest: str | None, transform_step: bool = False, ) -> None: super().update_attribute( attribute_key=attribute_key, attribute_value=attribute_value, change_origin_id=change_origin_id, previous_breadcrumbs=previous_breadcrumbs, attribute_at_dest=attribute_at_dest, transform_step=transform_step, ) attribute_key_parts = attribute_key.split(".") if attribute_key_parts: obj_to_update = self.attributes key_to_update = attribute_key_parts.pop() for i, key in enumerate(attribute_key_parts): if isinstance(obj_to_update, list): key = int(key) if (isinstance(obj_to_update, dict) and key in obj_to_update) or \ (isinstance(obj_to_update, list) and isinstance(key, int) and 0 <= key < len( obj_to_update)): obj_to_update = obj_to_update[key] else: attribute_key_parts.append(key_to_update) key_to_update = ".".join(attribute_key_parts[i:]) break if isinstance(obj_to_update, list): key_to_update = int(key_to_update) if isinstance(obj_to_update, (dict, list)): obj_to_update[key_to_update] = attribute_value else: logging.info(f"Failed to update an attribute, values: {obj_to_update}, {key_to_update}, {attribute_value}") def update_inner_attribute( self, attribute_key: str, nested_attributes: list[Any] | dict[str, Any], value_to_update: Any ) -> None: # this overrides the parent method, which doesn't work as expected with CloudFormation pass def _should_add_previous_breadcrumbs(change_origin_id: Optional[int], previous_breadcrumbs: List[BreadcrumbMetadata], attribute_at_dest: Optional[str]) -> bool: return ( change_origin_id is not None and attribute_at_dest is not None and (not previous_breadcrumbs or previous_breadcrumbs[-1].vertex_id != change_origin_id) ) def _should_set_changed_attributes(change_origin_id: Optional[int], attribute_at_dest: Optional[str]) -> bool: return change_origin_id is not None and attribute_at_dest is not None def convert_graph_vertices_to_definitions( vertices: List[CloudformationBlock], root_folder: str | None ) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, Dict[str, Any]]]: definitions: Dict[str, Dict[str, Any]] = {} breadcrumbs: Dict[str, Dict[str, Any]] = {} for vertex in vertices: if (vertex.block_type != BlockType.RESOURCE and vertex.block_type != BlockType.PARAMETERS) or \ (vertex.block_type == BlockType.RESOURCE and not vertex.condition): continue block_path = vertex.path block_type = TemplateSections.RESOURCES.value if vertex.block_type == 'resource' else TemplateSections.PARAMETERS.value block_name = vertex.name.split('.')[-1] # vertex.name is "type.name" so type.name -> [type, name] definition = { "Type": vertex.attributes["resource_type"] if vertex.block_type == BlockType.RESOURCE else vertex.block_type, "Properties": vertex.config or {}, } if vertex.metadata: definition["Metadata"] = vertex.metadata definitions.setdefault(block_path, {}).setdefault(block_type, {}).setdefault(block_name, definition) relative_block_path = f"/{os.path.relpath(block_path, root_folder)}" add_breadcrumbs(vertex, breadcrumbs, relative_block_path) return definitions, breadcrumbs
null
2,397
from __future__ import annotations import logging import os from typing import Optional, List, Tuple, Dict, Any, Callable import dpath from checkov.cloudformation.checks.resource.base_registry import Registry from checkov.cloudformation.checks.resource.registry import cfn_registry from checkov.cloudformation.context_parser import ContextParser, ENDLINE, STARTLINE from checkov.cloudformation.parser import parse, TemplateSections from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.parsers.node import DictNode, StrNode from checkov.common.runners.base_runner import filter_ignored_paths from checkov.runner_filter import RunnerFilter from checkov.common.models.consts import YAML_COMMENT_MARK def parse_entity_tags(tags: Any) -> dict[str, str] | None: if isinstance(tags, list): tag_dict = { get_entity_value_as_string(tag["Key"]): get_entity_value_as_string(tag["Value"]) for tag in tags if all(field in tag for field in TAG_FIELD_NAMES) } return tag_dict elif isinstance(tags, dict): tag_dict = { get_entity_value_as_string(key): get_entity_value_as_string(value) for key, value in tags.items() if key not in (STARTLINE, ENDLINE) } return tag_dict return None class Registry(BaseCheckRegistry): def __init__(self) -> None: super().__init__(report_type=CheckType.CLOUDFORMATION) def extract_entity_details(self, entity: dict[str, dict[str, Any]]) -> tuple[str, str, dict[str, Any]]: resource_name, resource = next(iter(entity.items())) resource_type = resource["Type"] return resource_type, resource_name, resource cfn_registry = Registry() def get_resource_tags(entity: dict[str, dict[str, Any]], registry: Registry = cfn_registry) -> Optional[Dict[str, str]]: entity_details = registry.extract_entity_details(entity) if not entity_details: return None entity_config = entity_details[-1] if not isinstance(entity_config, dict): return None try: properties = entity_config.get("Properties") if properties: tags = properties.get("Tags") if tags: return parse_entity_tags(tags) except Exception: logging.warning(f"Failed to parse tags for entity {entity}") return None
null
2,398
from __future__ import annotations import logging import os from typing import Optional, List, Tuple, Dict, Any, Callable import dpath from checkov.cloudformation.checks.resource.base_registry import Registry from checkov.cloudformation.checks.resource.registry import cfn_registry from checkov.cloudformation.context_parser import ContextParser, ENDLINE, STARTLINE from checkov.cloudformation.parser import parse, TemplateSections from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.parsers.node import DictNode, StrNode from checkov.common.runners.base_runner import filter_ignored_paths from checkov.runner_filter import RunnerFilter from checkov.common.models.consts import YAML_COMMENT_MARK class ContextParser: """ CloudFormation template context parser """ def __init__(self, cf_file: str, cf_template: dict[str, Any], cf_template_lines: List[Tuple[int, str]]) -> None: self.cf_file = cf_file self.cf_template = cf_template self.cf_template_lines = cf_template_lines def evaluate_default_refs(self) -> None: # Get Parameter Defaults - Locate Refs in Template refs = self.search_deep_keys("Ref", self.cf_template, []) for ref in refs: refname = ref.pop() ref.pop() # Get rid of the 'Ref' dict key # TODO refactor into evaluations if not isinstance(refname, str): continue default_value = self.cf_template.get("Parameters", {}).get(refname, {}).get("Properties", {}).get("Default") if default_value is not None: logging.debug( "Replacing Ref {} in file {} with default parameter value: {}".format( refname, self.cf_file, default_value ) ) self._set_in_dict(self.cf_template, ref, default_value) # TODO - Add Variable Eval Message for Output # Output in Checkov looks like this: # Variable versioning (of /.) evaluated to value "True" in expression: enabled = ${var.versioning} def extract_cf_resource_id(cf_resource: dict[str, Any], cf_resource_name: str) -> Optional[str]: if cf_resource_name == STARTLINE or cf_resource_name == ENDLINE: return None if "Type" not in cf_resource: # This is not a CloudFormation resource, skip return None return f"{cf_resource['Type']}.{cf_resource_name}" def extract_cf_resource_code_lines( self, cf_resource: dict[str, Any] ) -> Tuple[Optional[List[int]], Optional[List[Tuple[int, str]]]]: find_lines_result_set = set(self.find_lines(cf_resource, STARTLINE)) if len(find_lines_result_set) >= 1: start_line = min(find_lines_result_set) end_line = max(self.find_lines(cf_resource, ENDLINE)) # start_line - 2: -1 to switch to 0-based indexing, and -1 to capture the resource name entity_code_lines = self.cf_template_lines[start_line - 2 : end_line - 1] # if the file did not end in a new line, and this was the last resource in the file, then we # trimmed off the last line if (end_line - 1) < len(self.cf_template_lines) and not self.cf_template_lines[end_line - 1][1].endswith( "\n" ): entity_code_lines.append(self.cf_template_lines[end_line - 1]) entity_code_lines = ContextParser.trim_lines(entity_code_lines) entity_lines_range = [entity_code_lines[0][0], entity_code_lines[-1][0]] return entity_lines_range, entity_code_lines return None, None def trim_lines(code_lines: List[Tuple[int, str]]) -> List[Tuple[int, str]]: # Removes leading and trailing lines that are only whitespace, returning a new value # The passed value should be a list of tuples of line numbers and line strings (entity_code_lines) start = 0 end = len(code_lines) while start < end and not code_lines[start][1].strip(): start += 1 while end > start and not code_lines[end - 1][1].strip(): end -= 1 # if start == end, this will just be empty return code_lines[start:end] def find_lines(node: Any, kv: str) -> Generator[int, None, None]: # Hack to allow running checkov on json templates # CF scripts that are parsed using the yaml mechanism have a magic STARTLINE and ENDLINE property # CF scripts that are parsed using the json mechnism use dicts that have a marker if hasattr(node, "start_mark") and kv == STARTLINE: yield node.start_mark.line + 1 if hasattr(node, "end_mark") and kv == ENDLINE: yield node.end_mark.line + 1 if isinstance(node, list): for i in node: for x in ContextParser.find_lines(i, kv): yield x elif isinstance(node, dict): if kv in node: yield node[kv] def collect_skip_comments( entity_code_lines: List[Tuple[int, str]], resource_config: dict[str, Any] | None = None ) -> List[_SkippedCheck]: skipped_checks = collect_suppressions_for_context(code_lines=entity_code_lines) bc_id_mapping = metadata_integration.bc_to_ckv_id_mapping if resource_config: metadata = resource_config.get("Metadata") if metadata: ckv_skip = metadata.get("checkov", {}).get("skip", []) bc_skip = metadata.get("bridgecrew", {}).get("skip", []) if ckv_skip or bc_skip: for skip in itertools.chain(ckv_skip, bc_skip): skip_id = skip.get("id") skip_comment = skip.get("comment", "No comment provided") if skip_id is None: logging.warning("Check suppression is missing key 'id'") continue skipped_check: "_SkippedCheck" = {"id": skip_id, "suppress_comment": skip_comment} if bc_id_mapping and skipped_check["id"] in bc_id_mapping: skipped_check["bc_id"] = skipped_check["id"] skipped_check["id"] = bc_id_mapping[skipped_check["id"]] elif metadata_integration.check_metadata: skipped_check["bc_id"] = metadata_integration.get_bc_id(skipped_check["id"]) skipped_checks.append(skipped_check) return skipped_checks def search_deep_keys( search_text: str, cfn_dict: str | list[Any] | dict[str, Any], path: list[int | str] ) -> list[list[int | str]]: """Search deep for keys and get their values""" keys: list[list[int | str]] = [] if isinstance(cfn_dict, dict): for key in cfn_dict: pathprop = path[:] pathprop.append(key) if key == search_text: pathprop.append(cfn_dict[key]) keys.append(pathprop) # pop the last element off for nesting of found elements for # dict and list checks pathprop = pathprop[:-1] if isinstance(cfn_dict[key], dict): keys.extend(ContextParser.search_deep_keys(search_text, cfn_dict[key], pathprop)) elif isinstance(cfn_dict[key], list): for index, item in enumerate(cfn_dict[key]): pathproparr = pathprop[:] pathproparr.append(index) keys.extend(ContextParser.search_deep_keys(search_text, item, pathproparr)) elif isinstance(cfn_dict, list): for index, item in enumerate(cfn_dict): pathprop = list(path) pathprop.append(index) keys.extend(ContextParser.search_deep_keys(search_text, item, pathprop)) return keys def _set_in_dict(self, data_dict: dict[str, Any], map_list: list[Any], value: str) -> None: v = self._get_from_dict(data_dict, map_list[:-1]) # save the original marks so that we do not copy in the line numbers of the parameter element # but not all ref types will have these attributes start = None end = None if hasattr(v, "start_mark") and hasattr(v, "end_mark"): start = v.start_mark end = v.end_mark v[map_list[-1]] = value if hasattr(v[map_list[-1]], "start_mark") and start and end: v[map_list[-1]].start_mark = start v[map_list[-1]].end_mark = end def _get_from_dict(data_dict: dict[str, Any], map_list: list[Any]) -> list[Any] | dict[str, Any]: return reduce(operator.getitem, map_list, data_dict) class StrNode(str): """Node class created based on the input class""" def __init__(self, x: str, start_mark: Mark | Any, end_mark: Mark | Any) -> None: try: super().__init__(x) # type:ignore[call-arg] except TypeError: super().__init__() self.start_mark = start_mark self.end_mark = end_mark # pylint: disable=bad-classmethod-argument, unused-argument def __new__(cls, x: str, start_mark: Mark | None = None, end_mark: Mark | None = None) -> StrNode: return str.__new__(cls, x) def __getattr__(self, name: str) -> Any: raise TemplateAttributeError(f'{name} is invalid') def __deepcopy__(self, memo: dict[int, Any]) -> StrNode: result = StrNode(self, self.start_mark, self.end_mark) memo[id(self)] = result return result def __copy__(self) -> StrNode: return self class DictNode(dict): # type:ignore[type-arg] # either typing works or runtime, but not both """Node class created based on the input class""" def __init__(self, x: dict[str, Any], start_mark: Mark | Any, end_mark: Mark | Any): try: super().__init__(x) except TypeError: super().__init__() self.start_mark = start_mark self.end_mark = end_mark self.condition_functions = ['Fn::If'] def __deepcopy__(self, memo: dict[int, Any]) -> DictNode: result = DictNode(self, self.start_mark, self.end_mark) memo[id(self)] = result for k, v in self.items(): result[deepcopy(k)] = deepcopy(v, memo) return result def __copy__(self) -> DictNode: return self def is_function_returning_object(self, _mappings: Any = None) -> bool: """ Check if an object is using a function that could return an object Return True when Fn::Select: - 0 # or any number - !FindInMap [mapname, key, value] # or any mapname, key, value Otherwise False """ if len(self) == 1: for k, v in self.items(): if k in ['Fn::Select']: if isinstance(v, list): if len(v) == 2: p_v = v[1] if isinstance(p_v, dict): if len(p_v) == 1: for l_k in p_v.keys(): if l_k == 'Fn::FindInMap': return True return False def get(self, key: str, default: Any = None) -> Any: """ Override the default get """ if isinstance(default, dict): default = DictNode(default, self.start_mark, self.end_mark) return super().get(key, default) def get_safe( self, key: str, default: Any = None, path: list[str] | None = None, type_t: Type[tuple[Any, ...]] = tuple ) -> list[tuple[tuple[Any, ...], list[str]]]: """Get values in format""" path = path or [] value = self.get(key, default) if not isinstance(value, dict): if isinstance(value, type_t) or not type_t: return [(value, (path[:] + [key]))] results = [] for sub_v, sub_path in value.items_safe(path + [key]): if isinstance(sub_v, type_t) or not type_t: results.append((sub_v, sub_path)) return results def items_safe( self, path: list[int | str] | None = None, type_t: Type[tuple[Any, ...]] = tuple ) -> Generator[tuple[Any, ...], Any, None]: """Get items while handling IFs""" path = path or [] if len(self) == 1: for k, v in self.items(): if k == 'Fn::If': if isinstance(v, list): if len(v) == 3: for i, if_v in enumerate(v[1:]): if isinstance(if_v, DictNode): # yield from if_v.items_safe(path[:] + [k, i - 1]) # Python 2.7 support for items, p in if_v.items_safe(path[:] + [k, i + 1]): if isinstance(items, type_t) or not type_t: yield items, p elif isinstance(if_v, list): if isinstance(if_v, type_t) or not type_t: yield if_v, path[:] + [k, i + 1] else: if isinstance(if_v, type_t) or not type_t: yield if_v, path[:] + [k, i + 1] elif not (k == 'Ref' and v == 'AWS::NoValue'): if isinstance(self, type_t) or not type_t: yield self, path[:] else: if isinstance(self, type_t) or not type_t: yield self, path[:] def __getattr__(self, name: str) -> Any: raise TemplateAttributeError(f'{name} is invalid') YAML_COMMENT_MARK = '#' def build_definitions_context( definitions: dict[str, dict[str, Any]], definitions_raw: Dict[str, List[Tuple[int, str]]] ) -> Dict[str, Dict[str, Any]]: definitions_context: Dict[str, Dict[str, Any]] = {} # iterate on the files for file_path, file_path_definitions in definitions.items(): # iterate on the definitions (Parameters, Resources, Outputs...) for file_path_definition, definition in file_path_definitions.items(): if ( isinstance(file_path_definition, StrNode) and file_path_definition.upper() in TemplateSections.__members__ and isinstance(definition, DictNode) ): # iterate on the actual objects of each definition for attribute, attr_value in definition.items(): if isinstance(attr_value, DictNode): start_line = attr_value.start_mark.line end_line = attr_value.end_mark.line # fix lines number for yaml and json files first_line_index = 0 while not str.strip(definitions_raw[file_path][first_line_index][1]): first_line_index += 1 # check if the file is a json file if str.strip(definitions_raw[file_path][first_line_index][1])[0] == "{": start_line += 1 end_line += 1 else: # add resource comments to definition lines current_line = str.strip(definitions_raw[file_path][start_line - 1][1]) while not current_line or current_line[0] == YAML_COMMENT_MARK: start_line -= 1 current_line = str.strip(definitions_raw[file_path][start_line - 1][1]) # remove next resource comments from definition lines current_line = str.strip(definitions_raw[file_path][end_line - 1][1]) while not current_line or current_line[0] == YAML_COMMENT_MARK: end_line -= 1 current_line = str.strip(definitions_raw[file_path][end_line - 1][1]) code_lines = definitions_raw[file_path][start_line - 1: end_line] dpath.new( definitions_context, [file_path, str(file_path_definition), str(attribute)], {"start_line": start_line, "end_line": end_line, "code_lines": code_lines}, ) if file_path_definition.upper() == TemplateSections.RESOURCES.value.upper(): skipped_checks = ContextParser.collect_skip_comments( entity_code_lines=code_lines, resource_config=attr_value, ) dpath.new( definitions_context, [file_path, str(file_path_definition), str(attribute), "skipped_checks"], skipped_checks, ) return definitions_context
null
2,399
from __future__ import annotations import logging import os from typing import Optional, List, Tuple, Dict, Any, Callable import dpath from checkov.cloudformation.checks.resource.base_registry import Registry from checkov.cloudformation.checks.resource.registry import cfn_registry from checkov.cloudformation.context_parser import ContextParser, ENDLINE, STARTLINE from checkov.cloudformation.parser import parse, TemplateSections from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.parsers.node import DictNode, StrNode from checkov.common.runners.base_runner import filter_ignored_paths from checkov.runner_filter import RunnerFilter from checkov.common.models.consts import YAML_COMMENT_MARK CF_POSSIBLE_ENDINGS = frozenset((".yml", ".yaml", ".json", ".template")) def get_folder_definitions( root_folder: str, excluded_paths: list[str] | None, out_parsing_errors: dict[str, str] | None = None ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]]]: out_parsing_errors = {} if out_parsing_errors is None else out_parsing_errors files_list = [] for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) for file in f_names: file_ending = os.path.splitext(file)[1] if file_ending in CF_POSSIBLE_ENDINGS: files_list.append(os.path.join(root, file)) definitions, definitions_raw = get_files_definitions(files_list, out_parsing_errors) return definitions, definitions_raw def get_files_definitions( files: List[str], out_parsing_errors: Dict[str, str], filepath_fn: Callable[[str], str] | None = None ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]]]: results = parallel_runner.run_function(_parse_file, files) definitions = {} definitions_raw = {} for file, parse_result, parsing_errors in results: out_parsing_errors.update(parsing_errors) path = filepath_fn(file) if filepath_fn else file try: template, template_lines = parse_result if isinstance(template, dict) and isinstance(template.get("Resources"), dict) and isinstance(template_lines, list): if validate_properties_in_resources_are_dict(template): definitions[path] = template definitions_raw[path] = template_lines else: out_parsing_errors.update({file: 'Resource Properties is not a dictionary'}) else: if parsing_errors: logging.debug(f'File {file} had the following parsing errors: {parsing_errors}') logging.debug(f"Parsed file {file} incorrectly {template}") except (TypeError, ValueError): logging.warning(f"CloudFormation skipping {file} as it is not a valid CF template") continue return definitions, definitions_raw class RunnerFilter(object): # NOTE: This needs to be static because different filters may be used at load time versus runtime # (see note in BaseCheckRegistery.register). The concept of which checks are external is # logically a "static" concept anyway, so this makes logical sense. __EXTERNAL_CHECK_IDS: Set[str] = set() def __init__( self, framework: Optional[List[str]] = None, checks: Union[str, List[str], None] = None, skip_checks: Union[str, List[str], None] = None, include_all_checkov_policies: bool = True, download_external_modules: bool = False, external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR, evaluate_variables: bool = True, runners: Optional[List[str]] = None, skip_framework: Optional[List[str]] = None, excluded_paths: Optional[List[str]] = None, all_external: bool = False, var_files: Optional[List[str]] = None, skip_cve_package: Optional[List[str]] = None, use_enforcement_rules: bool = False, filtered_policy_ids: Optional[List[str]] = None, show_progress_bar: Optional[bool] = True, run_image_referencer: bool = False, enable_secret_scan_all_files: bool = False, block_list_secret_scan: Optional[List[str]] = None, deep_analysis: bool = False, repo_root_for_plan_enrichment: Optional[List[str]] = None, resource_attr_to_omit: Optional[Dict[str, Set[str]]] = None, enable_git_history_secret_scan: bool = False, git_history_timeout: str = '12h', git_history_last_commit_scanned: Optional[str] = None, # currently not exposed by a CLI flag report_sast_imports: bool = False, remove_default_sast_policies: bool = False, report_sast_reachability: bool = False ) -> None: checks = convert_csv_string_arg_to_list(checks) skip_checks = convert_csv_string_arg_to_list(skip_checks) self.skip_invalid_secrets = skip_checks and any(skip_check.capitalize() == ValidationStatus.INVALID.value for skip_check in skip_checks) self.use_enforcement_rules = use_enforcement_rules self.enforcement_rule_configs: Dict[str, Severity | Dict[CodeCategoryType, Severity]] = {} # we will store the lowest value severity we find in checks, and the highest value we find in skip-checks # so the logic is "run all checks >= severity" and/or "skip all checks <= severity" self.check_threshold = None self.skip_check_threshold = None self.checks = [] self.bc_cloned_checks: dict[str, list[dict[str, Any]]] = defaultdict(list) self.skip_checks = [] self.skip_checks_regex_patterns = defaultdict(list) self.show_progress_bar = show_progress_bar # split out check/skip thresholds so we can access them easily later for val in (checks or []): if val.upper() in Severities: val = val.upper() if not self.check_threshold or self.check_threshold.level > Severities[val].level: self.check_threshold = Severities[val] else: self.checks.append(val) # Get regex patterns to split checks and remove it from skip checks: updated_skip_checks = set(skip_checks) for val in (skip_checks or []): splitted_check = val.split(":") # In case it's not expected pattern if len(splitted_check) != 2: continue self.skip_checks_regex_patterns[splitted_check[0]].append(splitted_check[1]) updated_skip_checks -= {val} skip_checks = list(updated_skip_checks) for val in (skip_checks or []): if val.upper() in Severities: val = val.upper() if not self.skip_check_threshold or self.skip_check_threshold.level < Severities[val].level: self.skip_check_threshold = Severities[val] else: self.skip_checks.append(val) self.include_all_checkov_policies = include_all_checkov_policies if not framework or "all" in framework: self.framework_flag_values = [] else: self.framework_flag_values = framework self.framework: "Iterable[str]" = framework if framework else ["all"] if skip_framework: if "all" in self.framework: if runners is None: runners = [] self.framework = set(runners) - set(skip_framework) else: self.framework = set(self.framework) - set(skip_framework) logging.debug(f"Resultant set of frameworks (removing skipped frameworks): {','.join(self.framework)}") self.download_external_modules = download_external_modules self.external_modules_download_path = external_modules_download_path self.evaluate_variables = evaluate_variables self.excluded_paths = excluded_paths or [] self.all_external = all_external self.var_files = var_files self.skip_cve_package = skip_cve_package self.filtered_policy_ids = filtered_policy_ids or [] self.run_image_referencer = run_image_referencer self.enable_secret_scan_all_files = enable_secret_scan_all_files self.block_list_secret_scan = block_list_secret_scan self.suppressed_policies: List[str] = [] self.deep_analysis = deep_analysis self.repo_root_for_plan_enrichment = repo_root_for_plan_enrichment self.resource_attr_to_omit: DefaultDict[str, Set[str]] = RunnerFilter._load_resource_attr_to_omit( resource_attr_to_omit ) self.sast_languages: Set[SastLanguages] = RunnerFilter.get_sast_languages(framework, skip_framework) if self.sast_languages and any(item for item in self.framework if item.startswith(CheckType.SAST) or item == 'all'): self.framework = [item for item in self.framework if not item.startswith(CheckType.SAST)] self.framework.append(CheckType.SAST) elif not self.sast_languages: # remove all SAST and CDK frameworks self.framework = [ item for item in self.framework if not item.startswith(CheckType.SAST) and item != CheckType.CDK ] self.enable_git_history_secret_scan: bool = enable_git_history_secret_scan if self.enable_git_history_secret_scan: self.git_history_timeout = convert_to_seconds(git_history_timeout) self.framework = [CheckType.SECRETS] logging.debug("Scan secrets history was enabled ignoring other frameworks") self.git_history_last_commit_scanned = git_history_last_commit_scanned self.report_sast_imports = report_sast_imports self.remove_default_sast_policies = remove_default_sast_policies self.report_sast_reachability = report_sast_reachability def _load_resource_attr_to_omit(resource_attr_to_omit_input: Optional[Dict[str, Set[str]]]) -> DefaultDict[str, Set[str]]: resource_attributes_to_omit: DefaultDict[str, Set[str]] = defaultdict(set) # In order to create new object (and not a reference to the given one) if resource_attr_to_omit_input: resource_attributes_to_omit.update(resource_attr_to_omit_input) return resource_attributes_to_omit def apply_enforcement_rules(self, enforcement_rule_configs: Dict[str, CodeCategoryConfiguration]) -> None: self.enforcement_rule_configs = {} for report_type, code_category in CodeCategoryMapping.items(): if isinstance(code_category, list): self.enforcement_rule_configs[report_type] = {c: enforcement_rule_configs.get(c).soft_fail_threshold for c in code_category} # type:ignore[union-attr] # will not be None else: config = enforcement_rule_configs.get(code_category) if not config: raise Exception(f'Could not find an enforcement rule config for category {code_category} (runner: {report_type})') self.enforcement_rule_configs[report_type] = config.soft_fail_threshold def extract_enforcement_rule_threshold(self, check_id: str, report_type: str) -> Severity: if 'sca_' in report_type and '_LIC_' in check_id: return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.LICENSES] elif 'sca_' in report_type: # vulnerability return cast("dict[CodeCategoryType, Severity]", self.enforcement_rule_configs[report_type])[CodeCategoryType.VULNERABILITIES] else: return cast(Severity, self.enforcement_rule_configs[report_type]) def should_run_check( self, check: BaseCheck | BaseGraphCheck | BaseSastCheck | None = None, check_id: str | None = None, bc_check_id: str | None = None, severity: Severity | None = None, report_type: str | None = None, file_origin_paths: List[str] | None = None, root_folder: str | None = None ) -> bool: if check: check_id = check.id bc_check_id = check.bc_id severity = check.severity assert check_id is not None # nosec (for mypy (and then for bandit)) check_threshold: Optional[Severity] skip_check_threshold: Optional[Severity] # apply enforcement rules if specified, but let --check/--skip-check with a severity take priority if self.use_enforcement_rules and report_type: if not self.check_threshold and not self.skip_check_threshold: check_threshold = self.extract_enforcement_rule_threshold(check_id, report_type) skip_check_threshold = None else: check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold else: if self.use_enforcement_rules: # this is a warning for us (but there is nothing the user can do about it) logging.debug(f'Use enforcement rules is true, but check {check_id} was not passed to the runner filter with a report type') check_threshold = self.check_threshold skip_check_threshold = self.skip_check_threshold run_severity = severity and check_threshold and severity.level >= check_threshold.level explicit_run = self.checks and self.check_matches(check_id, bc_check_id, self.checks) implicit_run = not self.checks and not check_threshold is_external = RunnerFilter.is_external_check(check_id) is_policy_filtered = self.is_policy_filtered(check_id) # True if this check is present in the allow list, or if there is no allow list # this is not necessarily the return value (need to apply other filters) should_run_check = ( run_severity or explicit_run or implicit_run or (is_external and self.all_external) ) if not should_run_check: logging.debug(f'Should run check {check_id}: False') return False # If a policy is not present in the list of filtered policies, it should not be run - implicitly or explicitly. # It can, however, be skipped. if not is_policy_filtered: logging.debug(f'not is_policy_filtered {check_id}: should_run_check = False') should_run_check = False skip_severity = severity and skip_check_threshold and severity.level <= skip_check_threshold.level explicit_skip = self.skip_checks and self.check_matches(check_id, bc_check_id, self.skip_checks) regex_match = self._match_regex_pattern(check_id, file_origin_paths, root_folder) should_skip_check = ( skip_severity or explicit_skip or regex_match or (not bc_check_id and not self.include_all_checkov_policies and not is_external and not explicit_run) or (bc_check_id in self.suppressed_policies and bc_check_id not in self.bc_cloned_checks) ) logging.debug(f'skip_severity = {skip_severity}, explicit_skip = {explicit_skip}, regex_match = {regex_match}, suppressed_policies: {self.suppressed_policies}') logging.debug( f'bc_check_id = {bc_check_id}, include_all_checkov_policies = {self.include_all_checkov_policies}, is_external = {is_external}, explicit_run: {explicit_run}') if should_skip_check: result = False logging.debug(f'should_skip_check {check_id}: {should_skip_check}') elif should_run_check: result = True logging.debug(f'should_run_check {check_id}: {result}') else: result = False logging.debug(f'default {check_id}: {result}') return result def _match_regex_pattern(self, check_id: str, file_origin_paths: List[str] | None, root_folder: str | None) -> bool: """ Check if skip check_id for a certain file_types, according to given path pattern """ if not file_origin_paths: return False regex_patterns = self.skip_checks_regex_patterns.get(check_id, []) # In case skip is generic, for example, CKV_AZURE_*. generic_check_id = f"{'_'.join(i for i in check_id.split('_')[:-1])}_*" generic_check_regex_patterns = self.skip_checks_regex_patterns.get(generic_check_id, []) regex_patterns.extend(generic_check_regex_patterns) if not regex_patterns: return False for pattern in regex_patterns: if not pattern: continue full_regex_pattern = fr"^{root_folder}/{pattern}" if root_folder else pattern try: if any(re.search(full_regex_pattern, path) for path in file_origin_paths): return True except Exception as exc: logging.error( "Invalid regex pattern has been supplied", extra={"regex_pattern": pattern, "exc": str(exc)} ) return False def check_matches(check_id: str, bc_check_id: Optional[str], pattern_list: List[str]) -> bool: return any( (fnmatch.fnmatch(check_id, pattern) or (bc_check_id and fnmatch.fnmatch(bc_check_id, pattern))) for pattern in pattern_list) def within_threshold(self, severity: Severity) -> bool: above_min = (not self.check_threshold) or self.check_threshold.level <= severity.level below_max = self.skip_check_threshold and self.skip_check_threshold.level >= severity.level return above_min and not below_max def secret_validation_status_matches(secret_validation_status: str, statuses_list: list[str]) -> bool: return secret_validation_status in statuses_list def notify_external_check(check_id: str) -> None: RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id) def is_external_check(check_id: str) -> bool: return check_id in RunnerFilter.__EXTERNAL_CHECK_IDS def is_policy_filtered(self, check_id: str) -> bool: if not self.filtered_policy_ids: return True return check_id in self.filtered_policy_ids def to_dict(self) -> Dict[str, Any]: result: Dict[str, Any] = {} for key, value in self.__dict__.items(): result[key] = value return result def from_dict(obj: Dict[str, Any]) -> RunnerFilter: framework = obj.get('framework') checks = obj.get('checks') skip_checks = obj.get('skip_checks') include_all_checkov_policies = obj.get('include_all_checkov_policies') if include_all_checkov_policies is None: include_all_checkov_policies = True download_external_modules = obj.get('download_external_modules') if download_external_modules is None: download_external_modules = False external_modules_download_path = obj.get('external_modules_download_path') if external_modules_download_path is None: external_modules_download_path = DEFAULT_EXTERNAL_MODULES_DIR evaluate_variables = obj.get('evaluate_variables') if evaluate_variables is None: evaluate_variables = True runners = obj.get('runners') skip_framework = obj.get('skip_framework') excluded_paths = obj.get('excluded_paths') all_external = obj.get('all_external') if all_external is None: all_external = False var_files = obj.get('var_files') skip_cve_package = obj.get('skip_cve_package') use_enforcement_rules = obj.get('use_enforcement_rules') if use_enforcement_rules is None: use_enforcement_rules = False filtered_policy_ids = obj.get('filtered_policy_ids') show_progress_bar = obj.get('show_progress_bar') if show_progress_bar is None: show_progress_bar = True run_image_referencer = obj.get('run_image_referencer') if run_image_referencer is None: run_image_referencer = False enable_secret_scan_all_files = bool(obj.get('enable_secret_scan_all_files')) block_list_secret_scan = obj.get('block_list_secret_scan') runner_filter = RunnerFilter(framework, checks, skip_checks, include_all_checkov_policies, download_external_modules, external_modules_download_path, evaluate_variables, runners, skip_framework, excluded_paths, all_external, var_files, skip_cve_package, use_enforcement_rules, filtered_policy_ids, show_progress_bar, run_image_referencer, enable_secret_scan_all_files, block_list_secret_scan) return runner_filter def set_suppressed_policies(self, policy_level_suppressions: List[str]) -> None: logging.debug(f"Received the following policy-level suppressions, that will be skipped from running: {policy_level_suppressions}") self.suppressed_policies = policy_level_suppressions def get_sast_languages(frameworks: Optional[List[str]], skip_framework: Optional[List[str]]) -> Set[SastLanguages]: langs: Set[SastLanguages] = set() if not frameworks or (skip_framework and "sast" in skip_framework): return langs if 'all' in frameworks: sast_languages = SastLanguages.set() skip_framework = [] if not skip_framework else [f.split("sast_")[-1] for f in skip_framework] return set([lang for lang in sast_languages if lang.value not in skip_framework]) for framework in frameworks: if framework in [CheckType.SAST, CheckType.CDK]: for sast_lang in SastLanguages: langs.add(sast_lang) return langs if not framework.startswith(CheckType.SAST): continue lang = '_'.join(framework.split('_')[1:]) langs.add(SastLanguages[lang.upper()]) return langs def create_definitions( root_folder: str | None, files: list[str] | None = None, runner_filter: RunnerFilter | None = None, out_parsing_errors: dict[str, str] | None = None ) -> tuple[dict[str, dict[str, Any]], dict[str, list[tuple[int, str]]]]: runner_filter = runner_filter or RunnerFilter() out_parsing_errors = {} if out_parsing_errors is None else out_parsing_errors definitions: dict[str, dict[str, Any]] = {} definitions_raw: dict[str, list[tuple[int, str]]] = {} if files: files_list = [file for file in files if os.path.splitext(file)[1] in CF_POSSIBLE_ENDINGS] definitions, definitions_raw = get_files_definitions(files_list, out_parsing_errors) if root_folder: definitions, definitions_raw = get_folder_definitions(root_folder, runner_filter.excluded_paths, out_parsing_errors) return definitions, definitions_raw
null
2,400
from checkov.cloudformation.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories from checkov.common.util.type_forcers import force_list import ast class CheckResult(str, Enum): def force_list(var: list[T]) -> list[T]: def force_list(var: T) -> list[T]: def force_list(var: T | list[T]) -> list[T]: def check_policy(policy_block): if policy_block: if isinstance(policy_block, str): policy_block = ast.literal_eval(policy_block) if isinstance(policy_block, dict) and 'Statement' in policy_block.keys(): for statement in force_list(policy_block['Statement']): if 'Action' in statement and statement.get('Effect', ['Allow']) == 'Allow' and '*' in force_list( statement['Action']): return CheckResult.FAILED return CheckResult.PASSED else: return CheckResult.PASSED else: return CheckResult.PASSED
null
2,401
from checkov.cloudformation.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories from checkov.common.util.type_forcers import force_list class CheckResult(str, Enum): PASSED = "PASSED" FAILED = "FAILED" # Unknown should be used when a check does not wish to return a result, generally due to the inability # to resolve a value or similar types of errors. UNKNOWN = "UNKNOWN" # Skipped is used by the framework when a test is suppressed and should not be used directly by checks. SKIPPED = "SKIPPED" def force_list(var: list[T]) -> list[T]: ... def force_list(var: T) -> list[T]: ... def force_list(var: T | list[T]) -> list[T]: if not isinstance(var, list): return [var] return var def check_policy(policy_block): if policy_block and isinstance(policy_block, dict) and 'Statement' in policy_block.keys(): for statement in force_list(policy_block['Statement']): if 'Action' in statement: effect = statement.get('Effect', 'Allow') action = force_list(statement.get('Action', [''])) resource = force_list(statement.get('Resource', [''])) if effect == 'Allow' and '*' in action and '*' in resource: return CheckResult.FAILED return CheckResult.PASSED else: return CheckResult.PASSED
null
2,402
from __future__ import annotations from typing import Any from checkov.common.util.data_structures_utils import pickle_deepcopy def pickle_deepcopy(obj: _T) -> _T: """More performant version of the built-in deepcopy""" return cast("_T", pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))) # nosec The provided code snippet includes necessary dependencies for implementing the `convert_cloudformation_conf_to_iam_policy` function. Write a Python function `def convert_cloudformation_conf_to_iam_policy(conf: dict[str, Any]) -> dict[str, Any]` to solve the following problem: converts terraform parsed configuration to iam policy document Here is the function: def convert_cloudformation_conf_to_iam_policy(conf: dict[str, Any]) -> dict[str, Any]: """ converts terraform parsed configuration to iam policy document """ result = pickle_deepcopy(conf) if "Statement" in result.keys(): result["Statement"] = result.pop("Statement") for statement in map(dict, result["Statement"]): if "Action" in statement: statement["Action"] = str(statement.pop("Action")[0]) if "Resource" in statement: resources = statement.pop("Resource") if isinstance(resources, list): statement["Resource"] = str(resources[0]) else: statement["Resource"] = str(resources) if "NotAction" in statement: statement["NotAction"] = str(statement.pop("NotAction")[0]) if "NotResource" in statement: not_resources = statement.pop("NotResource") if isinstance(not_resources, list): statement["NotResource"] = str(not_resources[0]) else: statement["NotResource"] = str(not_resources) if "Effect" in statement: statement["Effect"] = str(statement.pop("Effect")) if "Effect" not in statement: statement["Effect"] = "Allow" return result
converts terraform parsed configuration to iam policy document
2,403
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.cloudformation.image_referencer.base_provider import BaseCloudFormationProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import extract_json def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_aws_apprunner_service(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] image_repo = find_in_dict(input_dict=resource, key_path="SourceConfiguration/ImageRepository") if isinstance(image_repo, dict): repo_type = image_repo.get("ImageRepositoryType") name = image_repo.get("ImageIdentifier") if name and isinstance(name, str) and repo_type == "ECR_PUBLIC": image_names.append(name) return image_names
null
2,404
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.cloudformation.image_referencer.base_provider import BaseCloudFormationProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import extract_json def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_json(json_str: Any) -> dict[str, Any] | list[dict[str, Any]] | None: """Tries to return a json object from a possible string value""" if isinstance(json_str, list): return json_str return extract_policy_dict(json_str) def extract_images_from_aws_batch_job_definition(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] properties = extract_json(resource.get("ContainerProperties")) if isinstance(properties, dict): name = properties.get("Image") if name and isinstance(name, str): image_names.append(name) node_range = find_in_dict(input_dict=resource, key_path="NodeProperties/NodeRangeProperties") if isinstance(node_range, list): for node in node_range: name = find_in_dict(input_dict=node, key_path="Container/Image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,405
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.cloudformation.image_referencer.base_provider import BaseCloudFormationProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import extract_json def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: def extract_images_from_aws_codebuild_project(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = find_in_dict(input_dict=resource, key_path="Environment/Image") if name and isinstance(name, str): # AWS provided images have an internal identifier if not name.startswith("aws/codebuild/"): image_names.append(name) return image_names
null
2,406
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.cloudformation.image_referencer.base_provider import BaseCloudFormationProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import extract_json def extract_json(json_str: Any) -> dict[str, Any] | list[dict[str, Any]] | None: def extract_images_from_aws_ecs_task_definition(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] definitions = extract_json(resource.get("ContainerDefinitions")) if isinstance(definitions, list): for definition in definitions: name = definition.get("Image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,407
from __future__ import annotations from typing import TYPE_CHECKING, Any from checkov.cloudformation.image_referencer.base_provider import BaseCloudFormationProvider from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import extract_json def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_aws_lightsail_container_service_deployment_version(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] containers = find_in_dict(input_dict=resource, key_path="ContainerServiceDeployment/Containers") if isinstance(containers, list): for container in containers: name = container.get("Image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,408
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING def safe_index(sequence_hopefully: Sequence[Any], index: int) -> Any: try: return sequence_hopefully[index] except IndexError: logging.debug(f'Failed to parse index int ({index}) out of {sequence_hopefully}', exc_info=True) return None
null
2,409
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING RESOLVED_MODULE_PATTERN = re.compile(r"\[.+\#.+\]") The provided code snippet includes necessary dependencies for implementing the `remove_module_dependency_from_path` function. Write a Python function `def remove_module_dependency_from_path(path: str) -> str` to solve the following problem: :param path: path that looks like "dir/main.tf[other_dir/x.tf#0] :return: only the outer path: dir/main.tf Here is the function: def remove_module_dependency_from_path(path: str) -> str: """ :param path: path that looks like "dir/main.tf[other_dir/x.tf#0] :return: only the outer path: dir/main.tf """ if "#" in path: path = re.sub(RESOLVED_MODULE_PATTERN, '', path) return path
:param path: path that looks like "dir/main.tf[other_dir/x.tf#0] :return: only the outer path: dir/main.tf
2,410
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING def get_next_vertices(evaluated_files: list[str], unevaluated_files: list[str]) -> tuple[list[str], list[str]]: """ This function implements a lazy separation of levels for the evaluated files. It receives the evaluated files, and returns 2 lists: 1. The next level of files - files from the unevaluated_files which have no unresolved dependency (either no dependency or all dependencies were evaluated). 2. unevaluated - files which have yet to be evaluated, and still have pending dependencies Let's say we have this dependency tree: a -> b x -> b y -> c z -> b b -> c c -> d The first run will return [a, y, x, z] as the next level since all of them have no dependencies The second run with the evaluated being [a, y, x, z] will return [b] as the next level. Please mind that [c] has some resolved dependencies (from y), but has unresolved dependencies from [b]. The third run will return [c], and the fourth will return [d]. """ next_level, unevaluated, do_not_eval_yet = [], [], [] for key in unevaluated_files: found = False for eval_key in evaluated_files: if eval_key in key: found = True break if not found: do_not_eval_yet.append(key.split(TERRAFORM_NESTED_MODULE_PATH_PREFIX)[0]) unevaluated.append(key) else: next_level.append(key) move_to_uneval = list(filter(lambda k: k.split(TERRAFORM_NESTED_MODULE_PATH_PREFIX)[0] in do_not_eval_yet, next_level)) for k in move_to_uneval: next_level.remove(k) unevaluated.append(k) return next_level, unevaluated def pickle_deepcopy(obj: _T) -> _T: """More performant version of the built-in deepcopy""" return cast("_T", pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))) # nosec def unify_dependency_path(dependency_path: List[str]) -> str: if not dependency_path: return '' return dependency_path[-1] def remove_module_dependency_in_path(path: str) -> Tuple[str, str, str]: """ :param path: path that looks like "dir/main.tf[other_dir/x.tf#0] :return: separated path from module dependency: dir/main.tf, other_dir/x.tf """ module_dependency = re.findall(MODULE_DEPENDENCY_PATTERN_IN_PATH, path) if re.findall(MODULE_DEPENDENCY_PATTERN_IN_PATH, path): path = re.sub(MODULE_DEPENDENCY_PATTERN_IN_PATH, "", path) module_and_num = extract_module_dependency_path(module_dependency) return path, module_and_num[0], module_and_num[1] TERRAFORM_NESTED_MODULE_PATH_ENDING = '}])' The provided code snippet includes necessary dependencies for implementing the `get_module_dependency_map` function. Write a Python function `def get_module_dependency_map( tf_definitions: dict[str, Any] ) -> tuple[dict[str, list[list[str]]], dict[str, Any], dict[tuple[str, str], list[str]]]` to solve the following problem: :param tf_definitions, with paths in format 'dir/main.tf[module_dir/main.tf#0]' :return module_dependency_map: mapping between directories and the location of its module definition: {'dir': 'module_dir/main.tf'} :return tf_definitions: with paths in format 'dir/main.tf' Here is the function: def get_module_dependency_map( tf_definitions: dict[str, Any] ) -> tuple[dict[str, list[list[str]]], dict[str, Any], dict[tuple[str, str], list[str]]]: """ :param tf_definitions, with paths in format 'dir/main.tf[module_dir/main.tf#0]' :return module_dependency_map: mapping between directories and the location of its module definition: {'dir': 'module_dir/main.tf'} :return tf_definitions: with paths in format 'dir/main.tf' """ module_dependency_map: dict[str, list[list[str]]] = {} copy_of_tf_definitions = {} dep_index_mapping: dict[tuple[str, str], list[str]] = {} origin_keys = list(filter(lambda k: not k.endswith(TERRAFORM_NESTED_MODULE_PATH_ENDING), tf_definitions.keys())) unevaluated_keys = list(filter(lambda k: k.endswith(TERRAFORM_NESTED_MODULE_PATH_ENDING), tf_definitions.keys())) for file_path in origin_keys: dir_name = os.path.dirname(file_path) module_dependency_map[dir_name] = [[]] copy_of_tf_definitions[file_path] = pickle_deepcopy(tf_definitions[file_path]) next_level, unevaluated_keys = get_next_vertices(origin_keys, unevaluated_keys) while next_level: for file_path in next_level: path, module_dependency, module_dependency_num = remove_module_dependency_in_path(file_path) dir_name = os.path.dirname(path) current_deps = pickle_deepcopy(module_dependency_map[os.path.dirname(module_dependency)]) for dep in current_deps: dep.append(module_dependency) if dir_name not in module_dependency_map: module_dependency_map[dir_name] = current_deps else: for dep in current_deps: if dep not in module_dependency_map[dir_name]: module_dependency_map[dir_name].append(dep) copy_of_tf_definitions[path] = pickle_deepcopy(tf_definitions[file_path]) origin_keys.append(path) dep_index_mapping.setdefault((path, module_dependency), []).append(module_dependency_num) next_level, unevaluated_keys = get_next_vertices(origin_keys, unevaluated_keys) for key, dep_trails in module_dependency_map.items(): hashes = set() deduped = [] for trail in dep_trails: trail_hash = unify_dependency_path(trail) if trail_hash in hashes: continue hashes.add(trail_hash) deduped.append(trail) module_dependency_map[key] = deduped return module_dependency_map, copy_of_tf_definitions, dep_index_mapping
:param tf_definitions, with paths in format 'dir/main.tf[module_dir/main.tf#0]' :return module_dependency_map: mapping between directories and the location of its module definition: {'dir': 'module_dir/main.tf'} :return tf_definitions: with paths in format 'dir/main.tf'
2,411
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING _Conf = TypeVar("_Conf", bound="dict[Any, Any]") class CustomJSONEncoder(json.JSONEncoder): def default(self, o: Any) -> Any: from checkov.terraform.modules.module_objects import TFModule, TFDefinitionKey if isinstance(o, set): return list(o) elif isinstance(o, Tree): return str(o) elif isinstance(o, datetime.date): return str(o) elif isinstance(o, (Version, LegacyVersion)): return str(o) elif isinstance(o, Severity): return o.name elif isinstance(o, complex): return str(o) elif isinstance(o, ImageDetails): return o.__dict__ elif isinstance(o, type_of_function): return str(o) elif isinstance(o, TFDefinitionKey): return str(o) elif isinstance(o, TFModule): return dict(o) elif isinstance(o, PotentialSecret): return o.json() elif isinstance(o, MatchMetadata): return o.serialize_model() elif isinstance(o, DataFlow): return o.serialize_model() elif isinstance(o, MatchLocation): return o.serialize_model() elif isinstance(o, Point): return o.serialize_model() else: return json.JSONEncoder.default(self, o) def encode(self, obj: Any) -> str: return super().encode(self._encode(obj)) def _encode(self, obj: Any) -> Any: if isinstance(obj, dict): return {self.encode_key(k): v for k, v in obj.items()} else: return obj def encode_key(key: Any) -> Any: from checkov.terraform.modules.module_objects import TFModule, TFDefinitionKey if isinstance(key, TFDefinitionKey): return str(key) if isinstance(key, TFModule): return str(key) else: return key def object_hook(dct: Dict[Any, Any]) -> Any: from checkov.terraform.modules.module_objects import TFModule, TFDefinitionKey from checkov.common.util.consts import RESOLVED_MODULE_ENTRY_NAME try: if dct is None: return None if isinstance(dct, dict): dct_obj = pickle_deepcopy(dct) if 'tf_source_modules' in dct and 'file_path' in dct: return TFDefinitionKey(file_path=dct["file_path"], tf_source_modules=object_hook(dct["tf_source_modules"])) if 'path' in dct and 'name' in dct and 'foreach_idx' in dct and 'nested_tf_module' in dct: return TFModule(path=dct['path'], name=dct['name'], foreach_idx=dct['foreach_idx'], nested_tf_module=object_hook(dct['nested_tf_module'])) for key, value in dct.items(): if key == RESOLVED_MODULE_ENTRY_NAME: resolved_classes = [] for resolved_module in dct[RESOLVED_MODULE_ENTRY_NAME]: if isinstance(resolved_module, str): resolved_classes.append(object_hook(json.loads(resolved_module))) dct_obj[RESOLVED_MODULE_ENTRY_NAME] = resolved_classes if isinstance(key, str) and 'tf_source_modules' in key and 'file_path' in key: tf_definition_key = json.loads(key) tf_definition_key_obj = TFDefinitionKey(file_path=tf_definition_key["file_path"], tf_source_modules=object_hook( tf_definition_key["tf_source_modules"])) dct_obj[tf_definition_key_obj] = value del dct_obj[key] return dct_obj return dct except (KeyError, TypeError, JSONDecodeError): return dct def serialize_definitions(tf_definitions: _Conf) -> _Conf: return cast("_Conf", json.loads(json.dumps(tf_definitions, cls=CustomJSONEncoder), object_hook=object_hook))
null
2,412
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING def is_nested(full_path: TFDefinitionKey | None) -> bool: return full_path.tf_source_modules is not None if full_path is not None else False class TFDefinitionKey: file_path: str tf_source_modules: TFModule | None = None def __lt__(self, other: Any) -> bool: if not isinstance(other, TFDefinitionKey): return False return (self.file_path, self.tf_source_modules) < (other.file_path, other.tf_source_modules) def __repr__(self) -> str: return f'tf_source_modules:{self.tf_source_modules}, file_path:{self.file_path}' def __iter__(self) -> Iterator[tuple[str, Any]]: yield from { "file_path": self.file_path, "tf_source_modules": dict(self.tf_source_modules) if self.tf_source_modules else None }.items() def __str__(self) -> str: from checkov.common.util.json_utils import CustomJSONEncoder return json.dumps(self.to_json(), cls=CustomJSONEncoder) def to_json(self) -> dict[str, Any]: to_return: dict[str, Any] = {"file_path": self.file_path, "tf_source_modules": None} if self.tf_source_modules: to_return["tf_source_modules"] = dict(self.tf_source_modules) return to_return def from_json(json_dct: dict[str, Any]) -> TFDefinitionKey: return TFDefinitionKey(file_path=json_dct['file_path'], tf_source_modules=TFModule.from_json(json_dct['tf_source_modules'])) def get_module_from_full_path(file_path: TFDefinitionKey | None) -> Tuple[TFDefinitionKey | None, None]: if not file_path or not is_nested(file_path): return None, None if file_path.tf_source_modules is None: return None, None return TFDefinitionKey(file_path=file_path.tf_source_modules.path, tf_source_modules=file_path.tf_source_modules.nested_tf_module), None
null
2,413
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING class TFDefinitionKey: file_path: str tf_source_modules: TFModule | None = None def __lt__(self, other: Any) -> bool: if not isinstance(other, TFDefinitionKey): return False return (self.file_path, self.tf_source_modules) < (other.file_path, other.tf_source_modules) def __repr__(self) -> str: return f'tf_source_modules:{self.tf_source_modules}, file_path:{self.file_path}' def __iter__(self) -> Iterator[tuple[str, Any]]: yield from { "file_path": self.file_path, "tf_source_modules": dict(self.tf_source_modules) if self.tf_source_modules else None }.items() def __str__(self) -> str: from checkov.common.util.json_utils import CustomJSONEncoder return json.dumps(self.to_json(), cls=CustomJSONEncoder) def to_json(self) -> dict[str, Any]: to_return: dict[str, Any] = {"file_path": self.file_path, "tf_source_modules": None} if self.tf_source_modules: to_return["tf_source_modules"] = dict(self.tf_source_modules) return to_return def from_json(json_dct: dict[str, Any]) -> TFDefinitionKey: return TFDefinitionKey(file_path=json_dct['file_path'], tf_source_modules=TFModule.from_json(json_dct['tf_source_modules'])) def get_module_name(file_path: TFDefinitionKey) -> str | None: if not file_path.tf_source_modules: return None module_name = file_path.tf_source_modules.name if file_path.tf_source_modules.foreach_idx: foreach_or_count = '"' if isinstance(file_path.tf_source_modules.foreach_idx, str) else '' module_name = f'{module_name}[{foreach_or_count}{file_path.tf_source_modules.foreach_idx}{foreach_or_count}]' return module_name
null
2,414
from __future__ import annotations import json import logging import os from collections.abc import Sequence from typing import Any, TYPE_CHECKING, TypeVar, cast, Tuple from lark import Tree import re from checkov.common.typing import TFDefinitionKeyType from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.json_utils import CustomJSONEncoder, object_hook from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.checks.utils.dependency_path_handler import unify_dependency_path from checkov.terraform.graph_builder.utils import remove_module_dependency_in_path from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_PREFIX, TERRAFORM_NESTED_MODULE_PATH_ENDING TFDefinitionKeyType: TypeAlias = "Union[str, TFDefinitionKey]" def get_abs_path(file_path: TFDefinitionKeyType) -> str: # file_path might be str for terraform-plan return file_path if isinstance(file_path, str) else str(file_path.file_path)
null
2,415
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference def is_local_path(root_dir: str, source: str) -> bool: # https://www.terraform.io/docs/modules/sources.html#local-paths return ( source.startswith(r"./") or source.startswith(r"/./") or source.startswith(r"../") )
null
2,416
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference def get_referenced_vertices_in_str_value( str_value: str, aliases: dict[str, dict[str, str]], resources_types: list[str], ) -> list[TerraformVertexReference]: references_vertices: "list[TerraformVertexReference]" = [] value_len = len(str_value) if CHECKOV_RENDER_MAX_LEN and 0 < CHECKOV_RENDER_MAX_LEN < value_len: logging.debug( f'Rendering was skipped for a {value_len}-character-long string. If you wish to have it ' f'evaluated, please set the environment variable CHECKOV_RENDER_MAX_LEN ' f'to {str(value_len + 1)} or to 0 to allow rendering of any length' ) else: if value_len < 5 or "." not in str_value: # the shortest reference is 'var.a' and references are done via dot notation return references_vertices str_value = remove_function_calls_from_str(str_value=str_value) str_value = remove_index_pattern_from_str(str_value=str_value) str_value = replace_map_attribute_access_with_dot(str_value=str_value) str_value = remove_interpolation(str_value=str_value) references_vertices = get_vertices_references(str_value, aliases, resources_types) return references_vertices class TerraformVertexReference(VertexReference): def __init__(self, block_type: str, sub_parts: list[str], origin_value: str) -> None: super().__init__(block_type, sub_parts, origin_value) def block_type_str_to_enum(block_type_str: str) -> str: if block_type_str == "var": return BlockType.VARIABLE if block_type_str == "local": return BlockType.LOCALS return BlockType().get(block_type_str) def get_referenced_vertices_in_value( value: Union[str, List[str], Dict[str, str]], aliases: Dict[str, Dict[str, str]], resources_types: List[str], ) -> List[TerraformVertexReference]: references_vertices: "list[TerraformVertexReference]" = [] if not value or isinstance(value, (bool, int)): # bool/int values can't have a references to other vertices return references_vertices if isinstance(value, list): for sub_value in value: references_vertices += get_referenced_vertices_in_value( sub_value, aliases, resources_types ) if isinstance(value, dict): for sub_value in value.values(): references_vertices += get_referenced_vertices_in_value( sub_value, aliases, resources_types ) if isinstance(value, str): references_vertices = get_referenced_vertices_in_str_value( str_value=value, aliases=aliases, resources_types=resources_types, ) return references_vertices
null
2,417
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference def generate_possible_strings_from_wildcards(origin_string: str, max_entries: int = 10) -> List[str]: max_entries = int(os.environ.get("MAX_WILDCARD_ARR_SIZE", max_entries)) generated_strings = [origin_string] if not origin_string: return [] if "*" not in origin_string: return generated_strings locations_of_wildcards = [] for i, char in enumerate(origin_string): if char == "*": locations_of_wildcards.append(i) locations_of_wildcards.reverse() for wildcard_index in locations_of_wildcards: new_generated_strings = [] for s in generated_strings: before_wildcard = s[:wildcard_index] after_wildcard = s[wildcard_index + 1:] for i in range(max_entries): new_generated_strings.append(before_wildcard + str(i) + after_wildcard) generated_strings = new_generated_strings # if origin_string == "ingress.*.cidr_blocks", check for "ingress.cidr_blocks" too generated_strings.append("".join(origin_string.split(".*"))) return generated_strings
null
2,418
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference NESTED_ATTRIBUTE_PATTERN = re.compile(r"\.\d+") The provided code snippet includes necessary dependencies for implementing the `attribute_has_nested_attributes` function. Write a Python function `def attribute_has_nested_attributes(attribute_key: str, attributes: Dict[str, Any], attribute_is_leaf: Optional[Dict[str, bool]] = None) -> bool` to solve the following problem: :param attribute_key: key inside the `attributes` dictionary :param attributes: :return: True if attribute_key has inner attributes. Example 1: if attributes.keys == [key1, key.key2], type(attributes[key1]) is dict and return True for key1 Example 2: if attributes.keys == [key1, key1.0], type(attributes[key1]) is list and return True for key1 Here is the function: def attribute_has_nested_attributes(attribute_key: str, attributes: Dict[str, Any], attribute_is_leaf: Optional[Dict[str, bool]] = None) -> bool: """ :param attribute_key: key inside the `attributes` dictionary :param attributes: :return: True if attribute_key has inner attributes. Example 1: if attributes.keys == [key1, key.key2], type(attributes[key1]) is dict and return True for key1 Example 2: if attributes.keys == [key1, key1.0], type(attributes[key1]) is list and return True for key1 """ if attribute_is_leaf is None: attribute_is_leaf = {} if attribute_is_leaf.get(attribute_key): prefixes_with_attribute_key = [] else: prefixes_with_attribute_key = [a for a in attributes if a.startswith(attribute_key) and a != attribute_key] if not any(re.findall(NESTED_ATTRIBUTE_PATTERN, a) for a in prefixes_with_attribute_key): # if there aro no numeric parts in the key such as key1.0.key2 return isinstance(attributes[attribute_key], dict) return isinstance(attributes[attribute_key], list) or isinstance(attributes[attribute_key], dict)
:param attribute_key: key inside the `attributes` dictionary :param attributes: :return: True if attribute_key has inner attributes. Example 1: if attributes.keys == [key1, key.key2], type(attributes[key1]) is dict and return True for key1 Example 2: if attributes.keys == [key1, key1.0], type(attributes[key1]) is list and return True for key1
2,419
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference The provided code snippet includes necessary dependencies for implementing the `attribute_has_dup_with_dynamic_attributes` function. Write a Python function `def attribute_has_dup_with_dynamic_attributes(attribute_key: str, attributes: dict[str, Any] | list[str]) -> bool` to solve the following problem: :param attribute_key: key inside the `attributes` dictionary :param attributes: `attributes` dictionary :return: True if attribute_key has duplicate attribute with dynamic reference. :example: if attributes.keys == [name.rule, dynamic.name.content.rule] -> will return True. Here is the function: def attribute_has_dup_with_dynamic_attributes(attribute_key: str, attributes: dict[str, Any] | list[str]) -> bool: """ :param attribute_key: key inside the `attributes` dictionary :param attributes: `attributes` dictionary :return: True if attribute_key has duplicate attribute with dynamic reference. :example: if attributes.keys == [name.rule, dynamic.name.content.rule] -> will return True. """ attribute_key_paths = attribute_key.split('.') if len(attribute_key_paths) > 1: attar_key_dynamic_ref = f"dynamic.{attribute_key_paths[0]}.content.{attribute_key_paths[1]}" return attar_key_dynamic_ref in attributes else: return False
:param attribute_key: key inside the `attributes` dictionary :param attributes: `attributes` dictionary :return: True if attribute_key has duplicate attribute with dynamic reference. :example: if attributes.keys == [name.rule, dynamic.name.content.rule] -> will return True.
2,420
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference class CustomAttributes: BLOCK_NAME = "block_name_" BLOCK_TYPE = "block_type_" FILE_PATH = "file_path_" CONFIG = "config_" ATTRIBUTES = "attributes_" LABEL = "label_" ID = "id_" HASH = "hash" RENDERING_BREADCRUMBS = "rendering_breadcrumbs_" SOURCE = "source_" RESOURCE_TYPE = "resource_type" RESOURCE_ID = "resource_id" SOURCE_MODULE = "source_module_" MODULE_DEPENDENCY = "module_dependency_" MODULE_DEPENDENCY_NUM = "module_dependency_num_" ENCRYPTION = "encryption_" ENCRYPTION_DETAILS = "encryption_details_" TF_RESOURCE_ADDRESS = "__address__" REFERENCES = "references_" FOREACH_ATTRS = "foreach_attrs_" SOURCE_MODULE_OBJECT = "source_module_object_" def get_related_resource_id(resource: dict[str, Any], file_path_to_referred_id: dict[str, str]) -> str | None: resource_id = resource.get(CustomAttributes.ID) # for external modules resources the id should start with the prefix module.[module_name] if resource.get(CustomAttributes.MODULE_DEPENDENCY): referred_id = file_path_to_referred_id.get( f'{resource.get(CustomAttributes.FILE_PATH)}[{resource.get(CustomAttributes.MODULE_DEPENDENCY)}#{resource.get(CustomAttributes.MODULE_DEPENDENCY_NUM)}]') resource_id = f'{referred_id}.{resource_id}' return resource_id
null
2,421
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference def get_file_path_to_referred_id_networkx(graph_object: DiGraph) -> dict[str, str]: file_path_to_module_id = {} modules = [node for node in graph_object.nodes.values() if node.get(CustomAttributes.BLOCK_TYPE) == BlockType.MODULE] for modules_data in modules: for module_name, module_content in modules_data.get(CustomAttributes.CONFIG, {}).items(): for path in module_content.get("__resolved__", []): file_path_to_module_id[path] = f"module.{module_name}" return file_path_to_module_id def get_file_path_to_referred_id_rustworkx(graph_object: DiGraph) -> dict[str, str]: file_path_to_module_id = {} modules = [node for index, node in graph_object.nodes() if node.get(CustomAttributes.BLOCK_TYPE) == BlockType.MODULE] for modules_data in modules: for module_name, module_content in modules_data.get(CustomAttributes.CONFIG, {}).items(): for path in module_content.get("__resolved__", []): file_path_to_module_id[path] = f"module.{module_name}" return file_path_to_module_id LibraryGraph: TypeAlias = "Union[DiGraph, _RustworkxGraph]" def setup_file_path_to_referred_id(graph_object: LibraryGraph) -> dict[str, str]: if isinstance(graph_object, DiGraph): return get_file_path_to_referred_id_networkx(graph_object) else: return get_file_path_to_referred_id_rustworkx(graph_object)
null
2,422
from __future__ import annotations import logging import os import re from typing import Tuple from typing import Union, List, Any, Dict, Optional, TYPE_CHECKING from checkov.common.typing import LibraryGraph from checkov.common.util.parser_utils import TERRAFORM_NESTED_MODULE_PATH_SEPARATOR_LENGTH, \ TERRAFORM_NESTED_MODULE_INDEX_SEPARATOR from networkx import DiGraph from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference class TerraformBlock(Block): def __init__( self, name: str, config: Dict[str, Any], path: TFDefinitionKeyType, block_type: str, attributes: Dict[str, Any], id: str = "", source: str = "", has_dynamic_block: bool = False, dynamic_attributes: dict[str, Any] | None = None, ) -> None: def __eq__(self, other: object) -> bool: def get_attribute_dict(self, add_hash: bool = True) -> dict[str, Any]: def add_module_connection(self, attribute_key: str, vertex_id: int) -> None: def extract_additional_changed_attributes(self, attribute_key: str) -> List[str]: def _extract_dynamic_changed_attributes(self, dynamic_attribute_key: str, nesting_prefix: str = '') -> List[str]: def _collect_dynamic_dependent_keys(self, dynamic_block_name: str, value: str | list[str] | dict[str, Any], key_path: str, dynamic_content_path: List[str], dynamic_changed_attributes: List[str]) -> None: def find_attribute(self, attribute: Optional[Union[str, List[str]]]) -> Optional[str]: def update_list_attribute(self, attribute_key: str, attribute_value: Any) -> None: def get_inner_attributes( cls, attribute_key: str, attribute_value: Union[str, List[str], Dict[str, Any]], strip_list: bool = True ) -> Dict[str, Any]: def to_dict(self) -> dict[str, Any]: def from_dict(data: dict[str, Any]) -> TerraformBlock: def get_attribute_is_leaf(vertex: TerraformBlock) -> Dict[str, bool]: attribute_is_leaf = {} for attribute in vertex.attributes: attribute_is_leaf[attribute] = True other = '.'.join(attribute.split('.')[:-1]) if other in attribute_is_leaf: attribute_is_leaf[other] = False return attribute_is_leaf
null
2,423
from __future__ import annotations from typing import Optional FOREACH_KEY_SEPERATOR = '["' FOREACH_KEY_ENDER = '"]' COUNT_KEY_SEPERATOR = "[" COUNT_KEY_ENDER = "]" def get_sanitized_terraform_resource_id(resource_id: str) -> str: if FOREACH_KEY_SEPERATOR in resource_id: original_id_parts = resource_id.split(FOREACH_KEY_SEPERATOR, maxsplit=1) original_resource_name = original_id_parts[-2] # As the last item will be the key itself, return original_resource_name # This will be the resource id before the foreach key was added elif COUNT_KEY_SEPERATOR in resource_id: original_id_parts = resource_id.split(COUNT_KEY_SEPERATOR) original_resource_name = original_id_parts[-2] return original_resource_name return resource_id def get_terraform_foreach_or_count_key(resource_id: str) -> Optional[str]: sanitized_id = get_sanitized_terraform_resource_id(resource_id) if sanitized_id == resource_id: return None key = resource_id.split(sanitized_id)[-1] while key.startswith(FOREACH_KEY_SEPERATOR) and key.endswith(FOREACH_KEY_ENDER): key = key[2:-2] while key.startswith(COUNT_KEY_SEPERATOR) and key.endswith(COUNT_KEY_ENDER): key = key[1:-1] return key
null
2,424
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def _find_regex_groups(pattern: str, input_str: str) -> Optional[Union[Dict[str, str], List[str]]]: match = re.match(pattern, input_str) if match: if match.groupdict(): # try to find named capturing groups return match.groupdict() if list(match.groups()): # try to find unnamed capturing groups return list(match.groups()) return None def regex(pattern: str, input_str: str) -> Union[Dict[str, str], List[str], str]: try: groups = _find_regex_groups(pattern, input_str) if groups is not None: return groups results: List[str] = re.findall(pattern, input_str) # return first match if len(results) > 0: return results[0] return "" except TypeError: return f"regex({pattern}, {input_str})"
null
2,425
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def _find_regex_groups(pattern: str, input_str: str) -> Optional[Union[Dict[str, str], List[str]]]: match = re.match(pattern, input_str) if match: if match.groupdict(): # try to find named capturing groups return match.groupdict() if list(match.groups()): # try to find unnamed capturing groups return list(match.groups()) return None def regexall(pattern: str, input_str: str) -> Union[Dict[str, str], List[str], str]: try: groups = _find_regex_groups(pattern, input_str) if groups is not None: return groups results = re.findall(pattern, input_str) return results except TypeError: return f"regexall({pattern}, {input_str})"
null
2,426
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def trim(input_str: str, chars_to_remove: str) -> str: for c in chars_to_remove: input_str = input_str.replace(c, "") return input_str
null
2,427
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def coalesce(*arg: Any) -> Any: return reduce(lambda x, y: x if x not in [None, ""] else y, arg)
null
2,428
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def coalesce_list(*arg: List[Any]) -> List[Any]: return reduce(lambda x, y: x if x not in [None, []] else y, arg)
null
2,429
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def flatten(lst: List[List[Any]]) -> List[Any]: res = [item for sublist in lst for item in sublist] if any(type(elem) is list for elem in res): return flatten(res) else: return res
null
2,430
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def matchkeys(values_list: List[Any], keys_list: List[Any], search_set: List[Any]) -> List[Any]: matching = set() for search in search_set: indices = [i for i, x in enumerate(keys_list) if x == search] for i in indices: matching.add(values_list[i]) return list(matching)
null
2,431
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def sort(lst: List[str]) -> List[str]: lst.sort() return lst
null
2,432
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def merge(*args: Any) -> Dict[str, Any]: res: Dict[str, Any] = {} for d in args: res = {**res, **d} return res
null
2,433
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring FUNCTION_FAILED = "____FUNCTION_FAILED____" def wrap_func(f: Callable[..., Any], *args: Any) -> Any: res = f(*args) if res == FUNCTION_FAILED: raise ValueError return res
null
2,434
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring TIME_DELTA_PATTERN = re.compile(r"(\d*\.*\d+)") def update_datetime(dt: datetime, delta: timedelta, adding: bool) -> datetime: if adding is True: dt = dt + delta else: dt = dt - delta return dt The provided code snippet includes necessary dependencies for implementing the `timeadd` function. Write a Python function `def timeadd(input_str: str, time_delta: str) -> str` to solve the following problem: From docs: duration is a string representation of a time difference, consisting of sequences of number and unit pairs, like "1.5h" or "1h30m". The accepted units are "ns", "us" (or "µs"), "ms", "s", "m", and "h". The first number may be negative to indicate a negative duration, like "-2h5m". Here is the function: def timeadd(input_str: str, time_delta: str) -> str: ''' From docs: duration is a string representation of a time difference, consisting of sequences of number and unit pairs, like "1.5h" or "1h30m". The accepted units are "ns", "us" (or "µs"), "ms", "s", "m", and "h". The first number may be negative to indicate a negative duration, like "-2h5m". ''' # Convert the date to allowing parsing input_str = input_str.replace("Z", "+00:00") dt = datetime.fromisoformat(input_str) adding = True if time_delta[0] == '-': adding = False time_delta = time_delta[1:] # Split out into each of the deltas deltas = re.split(TIME_DELTA_PATTERN, time_delta) # Needed to strip the leading empty element deltas = list(filter(None, deltas)) while len(deltas) > 0: amount = float(deltas[0]) interval = deltas[1] deltas = deltas[2:] delta = timedelta(0) if interval == 'h': delta = timedelta(hours=amount) elif interval == 'm': delta = timedelta(minutes=amount) elif interval == 's': delta = timedelta(seconds=amount) elif interval == 'ms': delta = timedelta(milliseconds=amount) elif interval == 'us' or interval == 'µs': delta = timedelta(microseconds=amount) elif interval == 'ns': # Crude, but timedelta does not deal with nanoseconds delta = timedelta(microseconds=(amount / 1000)) dt = update_datetime(dt, delta, adding) return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
From docs: duration is a string representation of a time difference, consisting of sequences of number and unit pairs, like "1.5h" or "1h30m". The accepted units are "ns", "us" (or "µs"), "ms", "s", "m", and "h". The first number may be negative to indicate a negative duration, like "-2h5m".
2,435
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def process_formatting_codes(format_str: str, dt: datetime) -> str: format_mapping = { "YYYY": "%Y", "YY": "%y", "MMMM": "%B", "MMM": "%b", "MM": "%m", "M": "%-m", "DD" : "%d", "D" : "%-d", "EEEE" : "%A", "EEE" : "%a", "HH" : "%I", "H" : "%-I", "hh" : "%H", "h" : "%-H", "mm" : "%M", "m" : "%-M", "ss" : "%S", "s" : "%-S", "AA" : "%p", # "aa" : "%p", # included for completeness but requires separate handling "ZZZZZ" : "%z", "ZZZZ" : "%z", "ZZZ" : "%z", "Z " : "%z"} if format_str == 'aa': format_str = dt.strftime('%p').lower() elif format_str == 'ZZZZZ': tz = dt.strftime("%z") format_str = tz[:3] + ":" + tz[3:] elif format_str == 'ZZZ': tz = dt.strftime("%z") if tz == '+0000': tz = 'UTC' format_str = tz elif format_str == 'Z': tz = dt.strftime("%z") if tz == '+0000': tz = 'Z' format_str = tz else: format_str = format_mapping.get(format_str, format_str) return format_str The provided code snippet includes necessary dependencies for implementing the `formatdate` function. Write a Python function `def formatdate(format_str: str, input_str: str) -> str` to solve the following problem: From docs: This function is intended for producing common machine-oriented timestamp formats such as those defined in RFC822, RFC850, and RFC1123. It is not suitable for truly human-oriented date formatting because it is not locale-aware. Any non-letter characters, such as punctuation, are reproduced verbatim in the output. To include literal letters in the format string, enclose them in single quotes '. To include a literal quote, escape it by doubling the quotes. Function works through the format string halting on single quotes to process any formatting Here is the function: def formatdate(format_str: str, input_str: str) -> str: ''' From docs: This function is intended for producing common machine-oriented timestamp formats such as those defined in RFC822, RFC850, and RFC1123. It is not suitable for truly human-oriented date formatting because it is not locale-aware. Any non-letter characters, such as punctuation, are reproduced verbatim in the output. To include literal letters in the format string, enclose them in single quotes '. To include a literal quote, escape it by doubling the quotes. Function works through the format string halting on single quotes to process any formatting ''' # Convert the input str to a date input_str = input_str.replace("Z", "+00:00") dt = datetime.fromisoformat(input_str) processed_format_str = "" format_str_segment = "" in_quote = False # Keep track of whether in formatting or quoted text last_ch = "" # Used to identify the '' scenario for ch in format_str: if ch == "'" or in_quote is True: if len(format_str_segment) > 0: processed_format_str += process_formatting_codes(format_str_segment, dt) format_str_segment = "" if ch == "'": if last_ch == "'": processed_format_str += "'" in_quote = not in_quote else: processed_format_str += ch else: if ch != last_ch and last_ch != "": # new format code and the start of the string processed_format_str += process_formatting_codes(format_str_segment, dt) format_str_segment = "" format_str_segment += ch last_ch = ch if len(format_str_segment) > 0: processed_format_str += process_formatting_codes(format_str_segment, dt) return dt.strftime(processed_format_str)
From docs: This function is intended for producing common machine-oriented timestamp formats such as those defined in RFC822, RFC850, and RFC1123. It is not suitable for truly human-oriented date formatting because it is not locale-aware. Any non-letter characters, such as punctuation, are reproduced verbatim in the output. To include literal letters in the format string, enclose them in single quotes '. To include a literal quote, escape it by doubling the quotes. Function works through the format string halting on single quotes to process any formatting
2,436
from __future__ import annotations import itertools import logging import re from datetime import datetime, timedelta from functools import reduce from math import ceil, floor, log from typing import Union, Any, Dict, Callable, List, Optional from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring def evaluate(input_str: str) -> Any: if "__" in input_str: logging.debug(f"got a substring with double underscore, which is not allowed. origin string: {input_str}") return input_str if input_str == "...": # don't create an Ellipsis object return input_str if input_str.startswith("try"): # As `try` is a saved word in python, we can't override it like other functions as `eval` won't accept it. # Instead, we are manually replacing this string with our own custom string, so we can pass it to `eval`. # Don't use str.replace to make sure we replace just the first occurrence input_str = f"{TRY_STR_REPLACEMENT}{input_str[3:]}" evaluated = eval(input_str, {"__builtins__": None}, SAFE_EVAL_DICT) # nosec return evaluated if not isinstance(evaluated, str) else remove_unicode_null(evaluated) The provided code snippet includes necessary dependencies for implementing the `terraform_try` function. Write a Python function `def terraform_try(*args: Any) -> Any` to solve the following problem: From terraform docs: "try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors." Here is the function: def terraform_try(*args: Any) -> Any: """ From terraform docs: "try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors." """ for arg in args: try: return evaluate(arg) if isinstance(arg, str) else arg except Exception as e: logging.warning(f"Error in evaluate_try of argument {arg} - {e}") continue raise Exception(f"No argument can be avaluted for try of {args}")
From terraform docs: "try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors."
2,437
from __future__ import annotations import json from ast import literal_eval import logging import os import re from collections.abc import Hashable, Sequence from json import JSONDecodeError import dpath from typing import TYPE_CHECKING, List, Dict, Any, Tuple, Union, Optional, cast from lark.tree import Tree from checkov.common.graph.graph_builder import Edge from checkov.common.graph.graph_builder.utils import join_trimmed_strings from checkov.common.graph.graph_builder.variable_rendering.renderer import VariableRenderer from checkov.common.util.data_structures_utils import find_in_dict, pickle_deepcopy from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes, reserved_attribute_names from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.utils import ( get_attribute_is_leaf, get_referenced_vertices_in_value, remove_index_pattern_from_str, attribute_has_nested_attributes, attribute_has_dup_with_dynamic_attributes, ) from checkov.terraform.graph_builder.variable_rendering.vertex_reference import VertexReference import checkov.terraform.graph_builder.variable_rendering.evaluate_terraform as evaluator def get_lookup_value(block_content: dict[str, Any], dynamic_argument: str) -> str: lookup_value: str = '' if 'None' in block_content[dynamic_argument]: lookup_value = 'null' elif 'False' in block_content[dynamic_argument]: lookup_value = 'false' elif 'True' in block_content[dynamic_argument]: lookup_value = 'true' return lookup_value
null
2,438
from __future__ import annotations import json from ast import literal_eval import logging import os import re from collections.abc import Hashable, Sequence from json import JSONDecodeError import dpath from typing import TYPE_CHECKING, List, Dict, Any, Tuple, Union, Optional, cast from lark.tree import Tree from checkov.common.graph.graph_builder import Edge from checkov.common.graph.graph_builder.utils import join_trimmed_strings from checkov.common.graph.graph_builder.variable_rendering.renderer import VariableRenderer from checkov.common.util.data_structures_utils import find_in_dict, pickle_deepcopy from checkov.common.util.type_forcers import force_int from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes, reserved_attribute_names from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.utils import ( get_attribute_is_leaf, get_referenced_vertices_in_value, remove_index_pattern_from_str, attribute_has_nested_attributes, attribute_has_dup_with_dynamic_attributes, ) from checkov.terraform.graph_builder.variable_rendering.vertex_reference import VertexReference import checkov.terraform.graph_builder.variable_rendering.evaluate_terraform as evaluator The provided code snippet includes necessary dependencies for implementing the `create_variable_key_path` function. Write a Python function `def create_variable_key_path(key_path: list[str]) -> str` to solve the following problem: Returns the key_path without the var prefix ex. ["var", "properties", "region"] -> "properties/region" Here is the function: def create_variable_key_path(key_path: list[str]) -> str: """Returns the key_path without the var prefix ex. ["var", "properties", "region"] -> "properties/region" """ return "/".join(key_path[1:])
Returns the key_path without the var prefix ex. ["var", "properties", "region"] -> "properties/region"
2,439
from __future__ import annotations import ast import json import logging import os import re from typing import Any, Union, Optional, List, Dict, Callable, TypeVar, Tuple from checkov.common.util.type_forcers import force_int from checkov.common.util.parser_utils import find_var_blocks import checkov.terraform.graph_builder.variable_rendering.renderer as renderer from checkov.terraform.graph_builder.variable_rendering.safe_eval_functions import evaluate def evaluate_terraform(input_str: Any, keep_interpolations: bool = True) -> Any: def remove_interpolation(original_str: str, var_to_clean: Optional[str] = None, escape_unrendered: bool = True) -> str: def replace_string_value(original_str: Any, str_to_replace: str, replaced_value: str, keep_origin: bool = True) -> Any: if original_str is None or type(original_str) not in (str, list): return original_str if type(original_str) is list: for i, item in enumerate(original_str): original_str[i] = replace_string_value(item, str_to_replace, replaced_value, keep_origin) if type(replaced_value) in [int, float, bool]: original_str[i] = evaluate_terraform(original_str[i]) return original_str if str_to_replace not in original_str: return original_str if keep_origin else str_to_replace string_without_interpolation = remove_interpolation(original_str, str_to_replace, escape_unrendered=False) return string_without_interpolation.replace(str_to_replace, str(replaced_value))
null
2,440
from __future__ import annotations import logging import os from collections import defaultdict from functools import partial from pathlib import Path from typing import List, Optional, Union, Any, Dict, overload, TypedDict import checkov.terraform.graph_builder.foreach.consts from checkov.common.graph.graph_builder import Edge from checkov.common.graph.graph_builder import reserved_attribute_names from checkov.common.graph.graph_builder.graph_components.attribute_names import CustomAttributes from checkov.common.graph.graph_builder.local_graph import LocalGraph from checkov.common.graph.graph_builder.utils import calculate_hash, join_trimmed_strings, filter_sub_keys from checkov.common.runners.base_runner import strtobool from checkov.common.util.data_structures_utils import pickle_deepcopy from checkov.common.util.type_forcers import force_int from checkov.terraform.graph_builder.foreach.builder import ForeachBuilder from checkov.terraform.graph_builder.variable_rendering.vertex_reference import TerraformVertexReference from checkov.terraform.modules.module_objects import TFModule from checkov.terraform.context_parsers.registry import parser_registry from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.graph_components.blocks import TerraformBlock from checkov.terraform.graph_builder.graph_components.generic_resource_encryption import ENCRYPTION_BY_RESOURCE_TYPE from checkov.terraform.graph_builder.graph_components.module import Module from checkov.terraform.graph_builder.utils import ( get_attribute_is_leaf, get_referenced_vertices_in_value, attribute_has_nested_attributes, remove_index_pattern_from_str, join_double_quote_surrounded_dot_split, ) from checkov.terraform.graph_builder.foreach.utils import get_terraform_foreach_or_count_key from checkov.terraform.graph_builder.utils import is_local_path from checkov.terraform.graph_builder.variable_rendering.renderer import TerraformVariableRenderer from checkov.common.util.consts import RESOLVED_MODULE_ENTRY_NAME class TFModule: path: str name: str | None nested_tf_module: TFModule | None = None foreach_idx: int | str | None = None def __lt__(self, other: Any) -> bool: if not isinstance(other, TFModule): return False return (self.path, self.name, self.nested_tf_module, self.foreach_idx) < ( other.path, other.name, other.nested_tf_module, other.foreach_idx) def __repr__(self) -> str: return f'path:{self.path}, name:{self.name}, nested_tf_module:{self.nested_tf_module}, foreach_idx:{self.foreach_idx}' def __iter__(self) -> Iterator[tuple[str, Any]]: yield from { "path": self.path, "name": self.name, "foreach_idx": self.foreach_idx, "nested_tf_module": dict(self.nested_tf_module) if self.nested_tf_module else None }.items() def __str__(self) -> str: from checkov.common.util.json_utils import CustomJSONEncoder return json.dumps(dict(self), cls=CustomJSONEncoder) def from_json(json_dct: dict[str, Any] | None) -> TFModule | None: return TFModule(path=json_dct['path'], name=json_dct['name'], foreach_idx=json_dct['foreach_idx'], nested_tf_module=TFModule.from_json(json_dct['nested_tf_module']) if json_dct.get( 'nested_tf_module') else None) if json_dct else None class TerraformBlock(Block): __slots__ = ( "module_connections", "source_module", "has_dynamic_block", "dynamic_attributes", "foreach_attrs", "source_module_object", "for_each_index" ) def __init__( self, name: str, config: Dict[str, Any], path: TFDefinitionKeyType, block_type: str, attributes: Dict[str, Any], id: str = "", source: str = "", has_dynamic_block: bool = False, dynamic_attributes: dict[str, Any] | None = None, ) -> None: """ when adding a new field be sure to add it to the equality function below :param name: unique name given to the terraform block, for example: 'aws_vpc.example_name' :param config: the section in tf_definitions that belong to this block :param path: the file location of the block :param block_type: BlockType :param attributes: dictionary of the block's original attributes in the terraform file """ super().__init__( name=name, config=config, path=path, # type:ignore[arg-type] # Block class would need to be a Generic type to make this pass block_type=str(block_type), attributes=attributes, id=id, source=source, has_dynamic_block=has_dynamic_block, dynamic_attributes=dynamic_attributes, ) if path: self.path = path # type:ignore[assignment] # Block class would need to be a Generic type to make this pass if attributes.get(RESOLVED_MODULE_ENTRY_NAME): del attributes[RESOLVED_MODULE_ENTRY_NAME] self.attributes = attributes self.module_connections: Dict[str, List[int]] = {} self.source_module: Set[int] = set() self.has_dynamic_block = has_dynamic_block self.source_module_object: Optional[TFModule] = None self.for_each_index: Optional[Any] = None self.foreach_attrs: list[str] | None = None def __eq__(self, other: object) -> bool: if not isinstance(other, TerraformBlock): return False return self.name == other.name and self.config == other.config and self.path == other.path and \ self.block_type == other.block_type and self.attributes == other.attributes and \ self.id == other.id and self.has_dynamic_block == other.has_dynamic_block and self.source == other.source def get_attribute_dict(self, add_hash: bool = True) -> dict[str, Any]: """ :return: map of all the block's native attributes (from the source file), combined with the attributes generated by the module builder. If the attributes are not a primitive type, they are converted to strings. """ base_attributes = self.get_base_attributes() self.get_origin_attributes(base_attributes) if hasattr(self, "module_dependency") and hasattr(self, "module_dependency_num"): base_attributes[CustomAttributes.MODULE_DEPENDENCY] = self.module_dependency base_attributes[CustomAttributes.MODULE_DEPENDENCY_NUM] = self.module_dependency_num if self.changed_attributes: # add changed attributes only for calculating the hash base_attributes["changed_attributes"] = sorted(self.changed_attributes.keys()) if self.breadcrumbs: sorted_breadcrumbs = dict(sorted(self.breadcrumbs.items())) base_attributes[CustomAttributes.RENDERING_BREADCRUMBS] = sorted_breadcrumbs if hasattr(self, 'foreach_attrs'): base_attributes[CustomAttributes.FOREACH_ATTRS] = self.foreach_attrs if hasattr(self, 'source_module_object'): base_attributes[CustomAttributes.SOURCE_MODULE_OBJECT] = self.source_module_object if add_hash: base_attributes[CustomAttributes.HASH] = calculate_hash(base_attributes) if self.block_type == BlockType.DATA: base_attributes[CustomAttributes.RESOURCE_TYPE] = f'data.{self.id.split(".")[0]}' if self.block_type == BlockType.MODULE: # since module names are user defined we are just setting 'module' as resource type for easier searching base_attributes[CustomAttributes.RESOURCE_TYPE] = "module" if self.block_type == BlockType.PROVIDER: # provider_name is always a string, base_attributes needs better typing pipenv run mypy provider_name = cast(str, base_attributes[CustomAttributes.BLOCK_NAME]) provider_type = provider_name.split(".")[0] # ex: provider.aws base_attributes[CustomAttributes.RESOURCE_TYPE] = f"provider.{provider_type}" if "changed_attributes" in base_attributes: # removed changed attributes if it was added previously for calculating hash. del base_attributes["changed_attributes"] return base_attributes def add_module_connection(self, attribute_key: str, vertex_id: int) -> None: self.module_connections.setdefault(attribute_key, []).append(vertex_id) def extract_additional_changed_attributes(self, attribute_key: str) -> List[str]: # if the `attribute_key` starts with a `for_each.` we know the attribute can't be a dynamic attribute as it # represents the for_each of the block, so we don't need extract dynamic changed attributes # Fix: https://github.com/bridgecrewio/checkov/issues/4324 if self.has_dynamic_block and not attribute_key.startswith('for_each'): return self._extract_dynamic_changed_attributes(attribute_key) return super().extract_additional_changed_attributes(attribute_key) def _extract_dynamic_changed_attributes(self, dynamic_attribute_key: str, nesting_prefix: str = '') -> List[str]: dynamic_changed_attributes: list[str] = [] dynamic_attribute_key_parts = dynamic_attribute_key.split('.') try: remainder_key_parts = ['start_extract_dynamic_changed_attributes'] # For 1st iteration while remainder_key_parts: dynamic_for_each_index = dynamic_attribute_key_parts.index('for_each') dynamic_content_key_parts, remainder_key_parts = \ dynamic_attribute_key_parts[:dynamic_for_each_index], dynamic_attribute_key_parts[dynamic_for_each_index + 1:] dynamic_block_name = dynamic_content_key_parts[-1] dynamic_content_path = dynamic_content_key_parts + ['content'] if dpath.search(self.attributes, dynamic_content_path): dynamic_block_content = dpath.get(self.attributes, dynamic_content_path) for key, value in dynamic_block_content.items(): key_path = ".".join(filter(None, [nesting_prefix, dynamic_block_name, key])) self._collect_dynamic_dependent_keys(dynamic_block_name, value, key_path, dynamic_content_path, dynamic_changed_attributes) dynamic_attribute_key_parts = remainder_key_parts return dynamic_changed_attributes except ValueError: return dynamic_changed_attributes def _collect_dynamic_dependent_keys(self, dynamic_block_name: str, value: str | list[str] | dict[str, Any], key_path: str, dynamic_content_path: List[str], dynamic_changed_attributes: List[str]) -> None: if isinstance(value, str): dynamic_ref = f'{dynamic_block_name}.value' if "${" in value: interpolation_matches = re.findall(INTERPOLATION_EXPR, value) for match in interpolation_matches: if dynamic_ref in match: dynamic_changed_attributes.append(key_path) elif isinstance(value, list): for idx, sub_value in enumerate(value): self._collect_dynamic_dependent_keys( dynamic_block_name, sub_value, f'{key_path}.{idx}', dynamic_content_path, dynamic_changed_attributes) elif isinstance(value, dict): for sub_key, sub_value in value.items(): if isinstance(sub_value, dict) and 'content' in sub_value.keys() and 'for_each' in sub_value.keys(): nested_dynamic_block_key_path = f'{".".join(dynamic_content_path)}.dynamic.{sub_key}.for_each' dynamic_changed_attributes.extend( self._extract_dynamic_changed_attributes(nested_dynamic_block_key_path, nesting_prefix=dynamic_block_name)) else: self._collect_dynamic_dependent_keys( dynamic_block_name, sub_value, f'{key_path}.{sub_key}', dynamic_content_path, dynamic_changed_attributes) def find_attribute(self, attribute: Optional[Union[str, List[str]]]) -> Optional[str]: """ :param attribute: key to search in self.attributes The function searches for attribute in self.attribute. It might not exist if the block is variable or output, or its search path might be different if its a resource. :return: the actual attribute key or None """ if not attribute: return None if self.attributes.get(attribute[0]): return attribute[0] if self.block_type == BlockType.VARIABLE: return "default" if self.attributes.get("default") else None if self.block_type == BlockType.OUTPUT: return "value" if self.attributes.get("value") else None if self.block_type == BlockType.RESOURCE and len(attribute) > 1: # handle cases where attribute_at_dest == ['aws_s3_bucket.template_bucket', 'acl'] if self.name == attribute[0] and self.attributes.get(attribute[1]): return attribute[1] return None def update_list_attribute(self, attribute_key: str, attribute_value: Any) -> None: """Updates list attributes with their index This needs to be overridden, because of our hcl parser adding a list around any value """ if attribute_key not in self.attributes or isinstance(self.attributes[attribute_key][0], list): # sometimes the attribute_value is a list and replaces the whole value of the key, which makes it a normal value # ex. attribute_value = ["xyz"] and self.attributes[attribute_key][0] = "xyz" for idx, value in enumerate(attribute_value): self.attributes[f"{attribute_key}.{idx}"] = value def get_inner_attributes( cls, attribute_key: str, attribute_value: Union[str, List[str], Dict[str, Any]], strip_list: bool = True ) -> Dict[str, Any]: if strip_list and isinstance(attribute_value, list) and len(attribute_value) == 1: attribute_value = attribute_value[0] return super().get_inner_attributes( attribute_key=attribute_key, attribute_value=attribute_value, ) def to_dict(self) -> dict[str, Any]: return { 'attributes': self.attributes, 'block_type': self.block_type, 'breadcrumbs': self.breadcrumbs, 'config': self.config, 'id': self.id, 'module_connections': self.module_connections, 'name': self.name, 'path': self.path, 'source': self.source, 'source_module': list(self.source_module), 'source_module_object': dict(self.source_module_object) if self.source_module_object else None } def from_dict(data: dict[str, Any]) -> TerraformBlock: tf_block = TerraformBlock(name=data.get('name', ''), block_type=data.get('block_type', ''), config=data.get('config', {}), id=data.get('id', ''), path=data.get('path', ''), source=data.get('source', ''), attributes=data.get('attributes', {}) ) tf_block.breadcrumbs = data.get('breadcrumbs', {}) tf_block.module_connections = data.get('module_connections', {}) tf_block.source_module = data.get('source_module', set()) tf_block.source_module_object = TFModule.from_json(data.get('source_module_object')) return tf_block def get_vertex_as_tf_module(block: TerraformBlock) -> TFModule: return TFModule(block.path, block.name, block.source_module_object)
null
2,441
from __future__ import annotations import os from typing import List, Dict, Any, Tuple from checkov.common.graph.graph_builder import CustomAttributes from checkov.terraform.modules.module_objects import TFDefinitionKey from checkov.terraform.graph_builder.graph_components.block_types import BlockType from checkov.terraform.graph_builder.graph_components.blocks import TerraformBlock def add_breadcrumbs(vertex: TerraformBlock, breadcrumbs: Dict[str, Dict[str, Any]], relative_block_path: str) -> None: vertex_breadcrumbs = vertex.breadcrumbs if vertex_breadcrumbs: vertex_key = vertex.attributes.get(CustomAttributes.TF_RESOURCE_ADDRESS, vertex.name) breadcrumbs.setdefault(relative_block_path, {})[vertex_key] = vertex_breadcrumbs class TFDefinitionKey: file_path: str tf_source_modules: TFModule | None = None def __lt__(self, other: Any) -> bool: if not isinstance(other, TFDefinitionKey): return False return (self.file_path, self.tf_source_modules) < (other.file_path, other.tf_source_modules) def __repr__(self) -> str: return f'tf_source_modules:{self.tf_source_modules}, file_path:{self.file_path}' def __iter__(self) -> Iterator[tuple[str, Any]]: yield from { "file_path": self.file_path, "tf_source_modules": dict(self.tf_source_modules) if self.tf_source_modules else None }.items() def __str__(self) -> str: from checkov.common.util.json_utils import CustomJSONEncoder return json.dumps(self.to_json(), cls=CustomJSONEncoder) def to_json(self) -> dict[str, Any]: to_return: dict[str, Any] = {"file_path": self.file_path, "tf_source_modules": None} if self.tf_source_modules: to_return["tf_source_modules"] = dict(self.tf_source_modules) return to_return def from_json(json_dct: dict[str, Any]) -> TFDefinitionKey: return TFDefinitionKey(file_path=json_dct['file_path'], tf_source_modules=TFModule.from_json(json_dct['tf_source_modules'])) class BlockType(CommonBlockType): DATA = "data" LOCALS = "locals" MODULE = "module" OUTPUT = "output" PROVIDER = "provider" TERRAFORM = "terraform" TF_VARIABLE = "tfvar" VARIABLE = "variable" CUSTOM = "custom" class TerraformBlock(Block): __slots__ = ( "module_connections", "source_module", "has_dynamic_block", "dynamic_attributes", "foreach_attrs", "source_module_object", "for_each_index" ) def __init__( self, name: str, config: Dict[str, Any], path: TFDefinitionKeyType, block_type: str, attributes: Dict[str, Any], id: str = "", source: str = "", has_dynamic_block: bool = False, dynamic_attributes: dict[str, Any] | None = None, ) -> None: """ when adding a new field be sure to add it to the equality function below :param name: unique name given to the terraform block, for example: 'aws_vpc.example_name' :param config: the section in tf_definitions that belong to this block :param path: the file location of the block :param block_type: BlockType :param attributes: dictionary of the block's original attributes in the terraform file """ super().__init__( name=name, config=config, path=path, # type:ignore[arg-type] # Block class would need to be a Generic type to make this pass block_type=str(block_type), attributes=attributes, id=id, source=source, has_dynamic_block=has_dynamic_block, dynamic_attributes=dynamic_attributes, ) if path: self.path = path # type:ignore[assignment] # Block class would need to be a Generic type to make this pass if attributes.get(RESOLVED_MODULE_ENTRY_NAME): del attributes[RESOLVED_MODULE_ENTRY_NAME] self.attributes = attributes self.module_connections: Dict[str, List[int]] = {} self.source_module: Set[int] = set() self.has_dynamic_block = has_dynamic_block self.source_module_object: Optional[TFModule] = None self.for_each_index: Optional[Any] = None self.foreach_attrs: list[str] | None = None def __eq__(self, other: object) -> bool: if not isinstance(other, TerraformBlock): return False return self.name == other.name and self.config == other.config and self.path == other.path and \ self.block_type == other.block_type and self.attributes == other.attributes and \ self.id == other.id and self.has_dynamic_block == other.has_dynamic_block and self.source == other.source def get_attribute_dict(self, add_hash: bool = True) -> dict[str, Any]: """ :return: map of all the block's native attributes (from the source file), combined with the attributes generated by the module builder. If the attributes are not a primitive type, they are converted to strings. """ base_attributes = self.get_base_attributes() self.get_origin_attributes(base_attributes) if hasattr(self, "module_dependency") and hasattr(self, "module_dependency_num"): base_attributes[CustomAttributes.MODULE_DEPENDENCY] = self.module_dependency base_attributes[CustomAttributes.MODULE_DEPENDENCY_NUM] = self.module_dependency_num if self.changed_attributes: # add changed attributes only for calculating the hash base_attributes["changed_attributes"] = sorted(self.changed_attributes.keys()) if self.breadcrumbs: sorted_breadcrumbs = dict(sorted(self.breadcrumbs.items())) base_attributes[CustomAttributes.RENDERING_BREADCRUMBS] = sorted_breadcrumbs if hasattr(self, 'foreach_attrs'): base_attributes[CustomAttributes.FOREACH_ATTRS] = self.foreach_attrs if hasattr(self, 'source_module_object'): base_attributes[CustomAttributes.SOURCE_MODULE_OBJECT] = self.source_module_object if add_hash: base_attributes[CustomAttributes.HASH] = calculate_hash(base_attributes) if self.block_type == BlockType.DATA: base_attributes[CustomAttributes.RESOURCE_TYPE] = f'data.{self.id.split(".")[0]}' if self.block_type == BlockType.MODULE: # since module names are user defined we are just setting 'module' as resource type for easier searching base_attributes[CustomAttributes.RESOURCE_TYPE] = "module" if self.block_type == BlockType.PROVIDER: # provider_name is always a string, base_attributes needs better typing pipenv run mypy provider_name = cast(str, base_attributes[CustomAttributes.BLOCK_NAME]) provider_type = provider_name.split(".")[0] # ex: provider.aws base_attributes[CustomAttributes.RESOURCE_TYPE] = f"provider.{provider_type}" if "changed_attributes" in base_attributes: # removed changed attributes if it was added previously for calculating hash. del base_attributes["changed_attributes"] return base_attributes def add_module_connection(self, attribute_key: str, vertex_id: int) -> None: self.module_connections.setdefault(attribute_key, []).append(vertex_id) def extract_additional_changed_attributes(self, attribute_key: str) -> List[str]: # if the `attribute_key` starts with a `for_each.` we know the attribute can't be a dynamic attribute as it # represents the for_each of the block, so we don't need extract dynamic changed attributes # Fix: https://github.com/bridgecrewio/checkov/issues/4324 if self.has_dynamic_block and not attribute_key.startswith('for_each'): return self._extract_dynamic_changed_attributes(attribute_key) return super().extract_additional_changed_attributes(attribute_key) def _extract_dynamic_changed_attributes(self, dynamic_attribute_key: str, nesting_prefix: str = '') -> List[str]: dynamic_changed_attributes: list[str] = [] dynamic_attribute_key_parts = dynamic_attribute_key.split('.') try: remainder_key_parts = ['start_extract_dynamic_changed_attributes'] # For 1st iteration while remainder_key_parts: dynamic_for_each_index = dynamic_attribute_key_parts.index('for_each') dynamic_content_key_parts, remainder_key_parts = \ dynamic_attribute_key_parts[:dynamic_for_each_index], dynamic_attribute_key_parts[dynamic_for_each_index + 1:] dynamic_block_name = dynamic_content_key_parts[-1] dynamic_content_path = dynamic_content_key_parts + ['content'] if dpath.search(self.attributes, dynamic_content_path): dynamic_block_content = dpath.get(self.attributes, dynamic_content_path) for key, value in dynamic_block_content.items(): key_path = ".".join(filter(None, [nesting_prefix, dynamic_block_name, key])) self._collect_dynamic_dependent_keys(dynamic_block_name, value, key_path, dynamic_content_path, dynamic_changed_attributes) dynamic_attribute_key_parts = remainder_key_parts return dynamic_changed_attributes except ValueError: return dynamic_changed_attributes def _collect_dynamic_dependent_keys(self, dynamic_block_name: str, value: str | list[str] | dict[str, Any], key_path: str, dynamic_content_path: List[str], dynamic_changed_attributes: List[str]) -> None: if isinstance(value, str): dynamic_ref = f'{dynamic_block_name}.value' if "${" in value: interpolation_matches = re.findall(INTERPOLATION_EXPR, value) for match in interpolation_matches: if dynamic_ref in match: dynamic_changed_attributes.append(key_path) elif isinstance(value, list): for idx, sub_value in enumerate(value): self._collect_dynamic_dependent_keys( dynamic_block_name, sub_value, f'{key_path}.{idx}', dynamic_content_path, dynamic_changed_attributes) elif isinstance(value, dict): for sub_key, sub_value in value.items(): if isinstance(sub_value, dict) and 'content' in sub_value.keys() and 'for_each' in sub_value.keys(): nested_dynamic_block_key_path = f'{".".join(dynamic_content_path)}.dynamic.{sub_key}.for_each' dynamic_changed_attributes.extend( self._extract_dynamic_changed_attributes(nested_dynamic_block_key_path, nesting_prefix=dynamic_block_name)) else: self._collect_dynamic_dependent_keys( dynamic_block_name, sub_value, f'{key_path}.{sub_key}', dynamic_content_path, dynamic_changed_attributes) def find_attribute(self, attribute: Optional[Union[str, List[str]]]) -> Optional[str]: """ :param attribute: key to search in self.attributes The function searches for attribute in self.attribute. It might not exist if the block is variable or output, or its search path might be different if its a resource. :return: the actual attribute key or None """ if not attribute: return None if self.attributes.get(attribute[0]): return attribute[0] if self.block_type == BlockType.VARIABLE: return "default" if self.attributes.get("default") else None if self.block_type == BlockType.OUTPUT: return "value" if self.attributes.get("value") else None if self.block_type == BlockType.RESOURCE and len(attribute) > 1: # handle cases where attribute_at_dest == ['aws_s3_bucket.template_bucket', 'acl'] if self.name == attribute[0] and self.attributes.get(attribute[1]): return attribute[1] return None def update_list_attribute(self, attribute_key: str, attribute_value: Any) -> None: """Updates list attributes with their index This needs to be overridden, because of our hcl parser adding a list around any value """ if attribute_key not in self.attributes or isinstance(self.attributes[attribute_key][0], list): # sometimes the attribute_value is a list and replaces the whole value of the key, which makes it a normal value # ex. attribute_value = ["xyz"] and self.attributes[attribute_key][0] = "xyz" for idx, value in enumerate(attribute_value): self.attributes[f"{attribute_key}.{idx}"] = value def get_inner_attributes( cls, attribute_key: str, attribute_value: Union[str, List[str], Dict[str, Any]], strip_list: bool = True ) -> Dict[str, Any]: if strip_list and isinstance(attribute_value, list) and len(attribute_value) == 1: attribute_value = attribute_value[0] return super().get_inner_attributes( attribute_key=attribute_key, attribute_value=attribute_value, ) def to_dict(self) -> dict[str, Any]: return { 'attributes': self.attributes, 'block_type': self.block_type, 'breadcrumbs': self.breadcrumbs, 'config': self.config, 'id': self.id, 'module_connections': self.module_connections, 'name': self.name, 'path': self.path, 'source': self.source, 'source_module': list(self.source_module), 'source_module_object': dict(self.source_module_object) if self.source_module_object else None } def from_dict(data: dict[str, Any]) -> TerraformBlock: tf_block = TerraformBlock(name=data.get('name', ''), block_type=data.get('block_type', ''), config=data.get('config', {}), id=data.get('id', ''), path=data.get('path', ''), source=data.get('source', ''), attributes=data.get('attributes', {}) ) tf_block.breadcrumbs = data.get('breadcrumbs', {}) tf_block.module_connections = data.get('module_connections', {}) tf_block.source_module = data.get('source_module', set()) tf_block.source_module_object = TFModule.from_json(data.get('source_module_object')) return tf_block def convert_graph_vertices_to_tf_definitions( vertices: List[TerraformBlock], root_folder: str ) -> Tuple[Dict[TFDefinitionKey, Dict[str, Any]], Dict[str, Dict[str, Any]]]: tf_definitions: Dict[TFDefinitionKey, Dict[str, Any]] = {} breadcrumbs: Dict[str, Dict[str, Any]] = {} for vertex in vertices: block_path = vertex.path if not os.path.isfile(block_path): print(f"tried to convert vertex to tf_definitions but its path doesnt exist: {vertex}") continue block_type = vertex.block_type if block_type == BlockType.TF_VARIABLE: continue tf_path = TFDefinitionKey(file_path=block_path) if vertex.source_module_object: tf_path = TFDefinitionKey(file_path=block_path, tf_source_modules=vertex.source_module_object) tf_definitions.setdefault(tf_path, {}).setdefault(block_type, []).append(vertex.config) relative_block_path = f"/{os.path.relpath(block_path, root_folder)}" add_breadcrumbs(vertex, breadcrumbs, relative_block_path) return tf_definitions, breadcrumbs
null
2,442
from typing import Dict, List, Any, Optional from checkov.common.util.type_forcers import force_dict def force_dict(obj: Any) -> dict[str, Any] | None: """ If the specified object is a dict, returns the object. If the specified object is a list or a tuple of length 1 or more, force_dict is called recursively on the first element. Else returns None. :param obj: :return: """ if isinstance(obj, dict): return obj if (isinstance(obj, list) or isinstance(obj, tuple)) and len(obj) > 0: return force_dict(obj[0]) return None def get_resource_tags(entity_config: Dict[str, List[Any]]) -> Optional[Dict[str, Any]]: return force_dict(entity_config.get("labels"))
null
2,443
from typing import Dict, List, Any, Optional from checkov.common.util.type_forcers import force_dict def force_dict(obj: Any) -> dict[str, Any] | None: """ If the specified object is a dict, returns the object. If the specified object is a list or a tuple of length 1 or more, force_dict is called recursively on the first element. Else returns None. :param obj: :return: """ if isinstance(obj, dict): return obj if (isinstance(obj, list) or isinstance(obj, tuple)) and len(obj) > 0: return force_dict(obj[0]) return None def get_resource_tags(entity_config: Dict[str, List[Any]]) -> Optional[Dict[str, Any]]: return force_dict(entity_config.get("tags"))
null
2,445
from json import JSONDecodeError import re from checkov.common.models.enums import CheckResult, CheckCategories from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.util.type_forcers import force_list import json from typing import List def check_conditions(statement) -> bool: # Check if 'Condition' key exists if 'Condition' not in statement: return False condition = statement['Condition'] # Pass if they define bad ARNs. Assumes they are not too narrow if any(key in condition for key in ['ArnNotEquals', 'ArnNotLike']): return True # Handling 'ArnEquals' and 'ArnLike' for arn_key in ['ArnEquals', 'ArnLike']: if arn_key in condition: # Pass unless it is for all IAM ARNs for principal_key in ['aws:PrincipalArn', 'aws:SourceArn']: if principal_key in condition[arn_key]: principal_arn = condition[arn_key][principal_key] # Fail if the Condition is for all ARNs of any resource if re.match(r'^arn:aws:[a-z0-9-]+::\*.*$', principal_arn): return False # Passed if 'aws:PrincipalArn' or 'aws:SourceArn' do not match because then they are specific return True # Handle VPC sources. Other sources not specific enough # Leaves out the NOT conditions as too broad ('StringNotEquals', 'StringNotEqualsIgnoreCase', 'StringNotLike') string_conditions = ['StringEquals', 'StringEqualsIgnoreCase', 'StringLike'] if any(condition_type in condition for condition_type in string_conditions): for condition_type in string_conditions: if condition_type in condition: if any(source in condition[condition_type] for source in ['aws:sourceVpce', 'aws:SourceVpc']): return True # Default fail if none of the above conditions are met return False
null
2,446
from __future__ import annotations from typing import Dict, List, Any from checkov.common.util.data_structures_utils import pickle_deepcopy def pickle_deepcopy(obj: _T) -> _T: """More performant version of the built-in deepcopy""" return cast("_T", pickle.loads(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL))) # nosec The provided code snippet includes necessary dependencies for implementing the `convert_terraform_conf_to_iam_policy` function. Write a Python function `def convert_terraform_conf_to_iam_policy(conf: Dict[str, List[Dict[str, Any]]]) -> Dict[str, List[Dict[str, Any]]]` to solve the following problem: converts terraform parsed configuration to iam policy document Here is the function: def convert_terraform_conf_to_iam_policy(conf: Dict[str, List[Dict[str, Any]]]) -> Dict[str, List[Dict[str, Any]]]: """ converts terraform parsed configuration to iam policy document """ result = pickle_deepcopy(conf) if "statement" in result.keys(): result["Statement"] = result.pop("statement") for statement in result["Statement"]: if "actions" in statement: statement["Action"] = statement.pop("actions")[0] if "resources" in statement: statement["Resource"] = statement.pop("resources")[0] if "not_actions" in statement: statement["NotAction"] = statement.pop("not_actions")[0] if "not_resources" in statement: statement["NotResource"] = statement.pop("not_resources")[0] if "effect" in statement: statement["Effect"] = statement.pop("effect")[0] if "effect" not in statement and "Effect" not in statement: statement["Effect"] = "Allow" if "condition" in statement: conditions = statement.pop("condition") if conditions and isinstance(conditions, list): statement["Condition"] = {} for condition in conditions: cond_operator = condition["test"][0] cond_key = condition["variable"][0] cond_value = condition["values"][0] statement["Condition"].setdefault(cond_operator, {})[cond_key] = cond_value return result
converts terraform parsed configuration to iam policy document
2,447
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_google_cloudbuild_trigger(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] steps = find_in_dict(input_dict=resource, key_path="build/step") if isinstance(steps, list): for definition in steps: name = definition.get("name") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,448
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_google_cloud_run_service(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = find_in_dict(input_dict=resource, key_path="template/spec/containers/image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,449
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_google_cloud_run_v2_job(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = find_in_dict(input_dict=resource, key_path="template/template/containers/image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,450
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_google_cloud_run_v2_service(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = find_in_dict(input_dict=resource, key_path="template/containers/image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,451
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_azurerm_batch_pool(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] containers = find_in_dict(input_dict=resource, key_path="container_configuration/container_image_names") if isinstance(containers, list): image_names.extend(container for container in containers if isinstance(container, str)) return image_names
null
2,452
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def force_list(var: list[T]) -> list[T]: ... def force_list(var: T) -> list[T]: ... def force_list(var: T | list[T]) -> list[T]: if not isinstance(var, list): return [var] return var def extract_images_from_azurerm_container_group(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] containers = resource.get("container") if containers: for container in force_list(containers): name = container.get("image") if name and isinstance(name, str): image_names.append(name) containers = resource.get("init_container") if containers: for container in force_list(containers): name = container.get("image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,453
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_azurerm_linux_function_app(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] docker = find_in_dict(input_dict=resource, key_path="site_config/application_stack/docker") if isinstance(docker, dict): name = docker.get("image_name") tag = docker.get("image_tag") if name and isinstance(name, str) and tag and isinstance(tag, str): image_names.append(f"{name}:{tag}") return image_names
null
2,454
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_azurerm_linux_web_app(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] app_stack = find_in_dict(input_dict=resource, key_path="site_config/application_stack") if isinstance(app_stack, dict): name = app_stack.get("docker_image") tag = app_stack.get("docker_image_tag") if name and isinstance(name, str) and tag and isinstance(tag, str): image_names.append(f"{name}:{tag}") return image_names
null
2,455
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def extract_images_from_azurerm_spring_cloud_container_deployment(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = resource.get("image") if name and isinstance(name, str): image_names.append(name) return image_names
null
2,456
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_azurerm_windows_web_app(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] app_stack = find_in_dict(input_dict=resource, key_path="site_config/application_stack") if isinstance(app_stack, dict): name = app_stack.get("docker_container_name") tag = app_stack.get("docker_container_tag") if name and isinstance(name, str) and tag and isinstance(tag, str): image_names.append(f"{name}:{tag}") return image_names
null
2,457
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list, extract_json from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_aws_apprunner_service(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] image_repo = find_in_dict(input_dict=resource, key_path="source_configuration/image_repository") if isinstance(image_repo, dict): repo_type = image_repo.get("image_repository_type") name = image_repo.get("image_identifier") if name and isinstance(name, str) and repo_type == "ECR_PUBLIC": image_names.append(name) return image_names
null
2,458
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list, extract_json from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def extract_json(json_str: Any) -> dict[str, Any] | list[dict[str, Any]] | None: """Tries to return a json object from a possible string value""" if isinstance(json_str, list): return json_str return extract_policy_dict(json_str) def extract_images_from_aws_batch_job_definition(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] properties = extract_json(resource.get("container_properties")) if isinstance(properties, dict): name = properties.get("image") if name and isinstance(name, str): image_names.append(name) # node properties are not supported yet # https://github.com/hashicorp/terraform-provider-aws/issues/20983 return image_names
null
2,459
from __future__ import annotations from typing import Any from checkov.common.typing import LibraryGraph from checkov.common.util.data_structures_utils import find_in_dict from checkov.common.util.type_forcers import force_list, extract_json from checkov.terraform.image_referencer.base_provider import BaseTerraformProvider def find_in_dict(input_dict: dict[str, Any], key_path: str) -> Any: """Tries to retrieve the value under the given 'key_path', otherwise returns None.""" value: Any = input_dict key_list = key_path.split("/") try: for key in key_list: if key.startswith("[") and key.endswith("]"): if isinstance(value, list): idx = int(key[1:-1]) value = value[idx] continue else: return None value = value.get(key) if value is None: return None except (AttributeError, IndexError, KeyError, TypeError, ValueError): logging.debug(f"Could not find {key_path} in dict") return None return value def extract_images_from_aws_codebuild_project(resource: dict[str, Any]) -> list[str]: image_names: list[str] = [] name = find_in_dict(input_dict=resource, key_path="environment/image") if name and isinstance(name, str): # AWS provided images have an internal identifier if not name.startswith("aws/codebuild/"): image_names.append(name) return image_names
null