__source_file,cve_ids,cwe_ids,file_path,class,patched_function_source,predicted_cwe_ids,repo,sha,function_code functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/providers/common/io/xcom/backend.py,0,"def serialize_value( value: T, *, key: str | None = None, task_id: str | None = None, dag_id: str | None = None, run_id: str | None = None, map_index: int | None = None, ) -> bytes | str: # we will always serialize ourselves and not by BaseXCom as the deserialize method # from BaseXCom accepts only XCom objects and not the value directly s_val = json.dumps(value, cls=XComEncoder).encode(""utf-8"") if compression := _get_compression(): suffix = f"".{_get_compression_suffix(compression)}"" else: suffix = """" threshold = _get_threshold() if threshold < 0 or len(s_val) < threshold: # Either no threshold or value is small enough. return s_val base_path = _get_base_path() while True: # Safeguard against collisions. p = base_path.joinpath( dag_id or ""NO_DAG_ID"", run_id or ""NO_RUN_ID"", task_id or ""NO_TASK_ID"", f""{uuid.uuid4()}{suffix}"", ) if not p.exists(): break p.parent.mkdir(parents=True, exist_ok=True) with p.open(mode=""wb"", compression=compression) as f: f.write(s_val) return BaseXCom.serialize_value(str(p))",CWE-Unknown,apache/airflow,3304c2a548022ba9d8c40440a70b913cfa2ee79e,"def serialize_value( value: T, *, key: str | None = None, task_id: str | None = None, dag_id: str | None = None, run_id: str | None = None, map_index: int | None = None, ) -> bytes | str: # we will always serialize ourselves and not by BaseXCom as the deserialize method # from BaseXCom accepts only XCom objects and not the value directly s_val = json.dumps(value, cls=XComEncoder).encode(""utf-8"") if compression := _get_compression(): suffix = f"".{_get_compression_suffix(compression)}"" else: suffix = """" threshold = _get_threshold() if threshold < 0 or len(s_val) < threshold: # Either no threshold or value is small enough. return s_val base_path = _get_base_path() while True: # Safeguard against collisions. p = base_path.joinpath(dag_id, run_id, task_id, f""{uuid.uuid4()}{suffix}"") if not p.exists(): break p.parent.mkdir(parents=True, exist_ok=True) with p.open(mode=""wb"", compression=compression) as f: f.write(s_val) return BaseXCom.serialize_value(str(p))" ,UNKNOWN,UNKNOWN,tests/paddle/test_paddle_autolog.py,1,"def test_autolog_log_models_configuration(log_models): mlflow.paddle.autolog(log_models=log_models) with mlflow.start_run() as run: train_model() MlflowClient().list_artifacts(run.info.run_id) assert (mlflow.last_logged_model() is not None) == log_models",CWE-703,mlflow/mlflow,5536b90a4feffcf8229076bafb374d8b84ec2dfa,"def test_autolog_log_models_configuration(log_models): mlflow.paddle.autolog(log_models=log_models) with mlflow.start_run() as run: train_model() artifacts = MlflowClient().list_artifacts(run.info.run_id) assert any(x.path == ""model"" for x in artifacts) == log_models" functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/forms/widgets.py,0,"def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context[""widget""].update( { ""checkbox_name"": checkbox_name, ""checkbox_id"": checkbox_id, ""is_initial"": self.is_initial(value), ""input_text"": self.input_text, ""initial_text"": self.initial_text, ""clear_checkbox_label"": self.clear_checkbox_label, } ) context[""widget""][""attrs""].setdefault(""disabled"", False) return context",CWE-Unknown,django/django,9942f3fb490f56bf28ee69f0a07f3eb62e7d3ab3,"def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context[""widget""].update( { ""checkbox_name"": checkbox_name, ""checkbox_id"": checkbox_id, ""is_initial"": self.is_initial(value), ""input_text"": self.input_text, ""initial_text"": self.initial_text, ""clear_checkbox_label"": self.clear_checkbox_label, } ) return context" ,UNKNOWN,UNKNOWN,airflow-core/tests/unit/serialization/test_dag_serialization.py,1,"def test_handle_v1_serdag(): v1 = { ""__version"": 1, ""dag"": { ""default_args"": { ""__type"": ""dict"", ""__var"": { ""depends_on_past"": False, ""retries"": 1, ""retry_delay"": {""__type"": ""timedelta"", ""__var"": 300.0}, ""max_retry_delay"": {""__type"": ""timedelta"", ""__var"": 600.0}, ""sla"": {""__type"": ""timedelta"", ""__var"": 100.0}, }, }, ""start_date"": 1564617600.0, ""_task_group"": { ""_group_id"": None, ""prefix_group_id"": True, ""children"": { ""bash_task"": (""operator"", ""bash_task""), ""custom_task"": (""operator"", ""custom_task""), }, ""tooltip"": """", ""ui_color"": ""CornflowerBlue"", ""ui_fgcolor"": ""#000"", ""upstream_group_ids"": [], ""downstream_group_ids"": [], ""upstream_task_ids"": [], ""downstream_task_ids"": [], }, ""is_paused_upon_creation"": False, ""_dag_id"": ""simple_dag"", ""doc_md"": ""### DAG Tutorial Documentation"", ""fileloc"": None, ""_processor_dags_folder"": ( AIRFLOW_REPO_ROOT_PATH / ""airflow-core"" / ""tests"" / ""unit"" / ""dags"" ).as_posix(), ""tasks"": [ { ""__type"": ""operator"", ""__var"": { ""task_id"": ""bash_task"", ""retries"": 1, ""retry_delay"": 300.0, ""max_retry_delay"": 600.0, ""sla"": 100.0, ""downstream_task_ids"": [], ""ui_color"": ""#f0ede4"", ""ui_fgcolor"": ""#000"", ""template_ext"": ["".sh"", "".bash""], ""template_fields"": [""bash_command"", ""env"", ""cwd""], ""template_fields_renderers"": {""bash_command"": ""bash"", ""env"": ""json""}, ""bash_command"": ""echo {{ task.task_id }}"", ""_task_type"": ""BashOperator"", # Slightly difference from v2-10-stable here, we manually changed this path ""_task_module"": ""airflow.providers.standard.operators.bash"", ""pool"": ""default_pool"", ""is_setup"": False, ""is_teardown"": False, ""on_failure_fail_dagrun"": False, ""executor_config"": { ""__type"": ""dict"", ""__var"": { ""pod_override"": { ""__type"": ""k8s.V1Pod"", ""__var"": PodGenerator.serialize_pod(executor_config_pod), } }, }, ""doc_md"": ""### Task Tutorial Documentation"", ""_log_config_logger_name"": ""airflow.task.operators"", ""_needs_expansion"": False, ""weight_rule"": ""downstream"", ""start_trigger_args"": None, ""start_from_trigger"": False, ""inlets"": [ { ""__type"": ""dataset"", ""__var"": { ""extra"": {}, ""uri"": ""asset-1"", }, }, { ""__type"": ""dataset_alias"", ""__var"": {""name"": ""alias-name""}, }, ], ""outlets"": [ { ""__type"": ""dataset"", ""__var"": { ""extra"": {}, ""uri"": ""asset-2"", }, }, ], }, }, { ""__type"": ""operator"", ""__var"": { ""task_id"": ""custom_task"", ""retries"": 1, ""retry_delay"": 300.0, ""max_retry_delay"": 600.0, ""sla"": 100.0, ""downstream_task_ids"": [], ""_operator_extra_links"": [{""tests.test_utils.mock_operators.CustomOpLink"": {}}], ""ui_color"": ""#fff"", ""ui_fgcolor"": ""#000"", ""template_ext"": [], ""template_fields"": [""bash_command""], ""template_fields_renderers"": {}, ""_task_type"": ""CustomOperator"", ""_operator_name"": ""@custom"", # Slightly difference from v2-10-stable here, we manually changed this path ""_task_module"": ""tests_common.test_utils.mock_operators"", ""pool"": ""default_pool"", ""is_setup"": False, ""is_teardown"": False, ""on_failure_fail_dagrun"": False, ""_log_config_logger_name"": ""airflow.task.operators"", ""_needs_expansion"": False, ""weight_rule"": ""downstream"", ""start_trigger_args"": None, ""start_from_trigger"": False, }, }, ], ""schedule_interval"": {""__type"": ""timedelta"", ""__var"": 86400.0}, ""timezone"": ""UTC"", ""_access_control"": { ""__type"": ""dict"", ""__var"": { ""test_role"": { ""__type"": ""dict"", ""__var"": { ""DAGs"": { ""__type"": ""set"", ""__var"": [permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT], } }, } }, }, ""edge_info"": {}, ""dag_dependencies"": [ # dataset as schedule (source) { ""source"": ""dataset"", ""target"": ""dag1"", ""dependency_type"": ""dataset"", ""dependency_id"": ""dataset_uri_1"", }, # dataset alias (resolved) as schedule (source) { ""source"": ""dataset"", ""target"": ""dataset-alias:alias_name_1"", ""dependency_type"": ""dataset"", ""dependency_id"": ""dataset_uri_2"", }, { ""source"": ""dataset:alias_name_1"", ""target"": ""dag2"", ""dependency_type"": ""dataset-alias"", ""dependency_id"": ""alias_name_1"", }, # dataset alias (not resolved) as schedule (source) { ""source"": ""dataset-alias"", ""target"": ""dag2"", ""dependency_type"": ""dataset-alias"", ""dependency_id"": ""alias_name_2"", }, # dataset as outlets (target) { ""source"": ""dag10"", ""target"": ""dataset"", ""dependency_type"": ""dataset"", ""dependency_id"": ""dataset_uri_10"", }, # dataset alias (resolved) as outlets (target) { ""source"": ""dag20"", ""target"": ""dataset-alias:alias_name_10"", ""dependency_type"": ""dataset"", ""dependency_id"": ""dataset_uri_20"", }, { ""source"": ""dataset:dataset_uri_20"", ""target"": ""dataset-alias"", ""dependency_type"": ""dataset-alias"", ""dependency_id"": ""alias_name_10"", }, # dataset alias (not resolved) as outlets (target) { ""source"": ""dag2"", ""target"": ""dataset-alias"", ""dependency_type"": ""dataset-alias"", ""dependency_id"": ""alias_name_2"", }, ], ""params"": [], }, } expected_dag_dependencies = [ # asset as schedule (source) { ""dependency_id"": ""dataset_uri_1"", ""dependency_type"": ""asset"", ""label"": ""dataset_uri_1"", ""source"": ""asset"", ""target"": ""dag1"", }, # asset alias (resolved) as schedule (source) { ""dependency_id"": ""dataset_uri_2"", ""dependency_type"": ""asset"", ""label"": ""dataset_uri_2"", ""source"": ""asset"", ""target"": ""asset-alias:alias_name_1"", }, { ""dependency_id"": ""alias_name_1"", ""dependency_type"": ""asset-alias"", ""label"": ""alias_name_1"", ""source"": ""asset:alias_name_1"", ""target"": ""dag2"", }, # asset alias (not resolved) as schedule (source) { ""dependency_id"": ""alias_name_2"", ""dependency_type"": ""asset-alias"", ""label"": ""alias_name_2"", ""source"": ""asset-alias"", ""target"": ""dag2"", }, # asset as outlets (target) { ""dependency_id"": ""dataset_uri_10"", ""dependency_type"": ""asset"", ""label"": ""dataset_uri_10"", ""source"": ""dag10"", ""target"": ""asset"", }, # asset alias (resolved) as outlets (target) { ""dependency_id"": ""dataset_uri_20"", ""dependency_type"": ""asset"", ""label"": ""dataset_uri_20"", ""source"": ""dag20"", ""target"": ""asset-alias:alias_name_10"", }, { ""dependency_id"": ""alias_name_10"", ""dependency_type"": ""asset-alias"", ""label"": ""alias_name_10"", ""source"": ""asset:dataset_uri_20"", ""target"": ""asset-alias"", }, # asset alias (not resolved) as outlets (target) { ""dependency_id"": ""alias_name_2"", ""dependency_type"": ""asset-alias"", ""label"": ""alias_name_2"", ""source"": ""dag2"", ""target"": ""asset-alias"", }, ] SerializedDAG.conversion_v1_to_v2(v1) # Update a few subtle differences v1[""dag""][""tags""] = [] v1[""dag""][""catchup""] = False v1[""dag""][""disable_bundle_versioning""] = False expected = copy.deepcopy(serialized_simple_dag_ground_truth) expected[""dag""][""dag_dependencies""] = expected_dag_dependencies del expected[""dag""][""tasks""][1][""__var""][""_operator_extra_links""] assert v1 == expected",CWE-703,apache/airflow,65c4900bd7bc4cc1d5227f68dbbc2e5a33f4eaf4,"def test_handle_v1_serdag(): v1 = { ""__version"": 1, ""dag"": { ""default_args"": { ""__type"": ""dict"", ""__var"": { ""depends_on_past"": False, ""retries"": 1, ""retry_delay"": {""__type"": ""timedelta"", ""__var"": 300.0}, ""max_retry_delay"": {""__type"": ""timedelta"", ""__var"": 600.0}, ""sla"": {""__type"": ""timedelta"", ""__var"": 100.0}, }, }, ""start_date"": 1564617600.0, ""_task_group"": { ""_group_id"": None, ""prefix_group_id"": True, ""children"": { ""bash_task"": (""operator"", ""bash_task""), ""custom_task"": (""operator"", ""custom_task""), }, ""tooltip"": """", ""ui_color"": ""CornflowerBlue"", ""ui_fgcolor"": ""#000"", ""upstream_group_ids"": [], ""downstream_group_ids"": [], ""upstream_task_ids"": [], ""downstream_task_ids"": [], }, ""is_paused_upon_creation"": False, ""_dag_id"": ""simple_dag"", ""doc_md"": ""### DAG Tutorial Documentation"", ""fileloc"": None, ""_processor_dags_folder"": ( AIRFLOW_REPO_ROOT_PATH / ""airflow-core"" / ""tests"" / ""unit"" / ""dags"" ).as_posix(), ""tasks"": [ { ""__type"": ""operator"", ""__var"": { ""task_id"": ""bash_task"", ""retries"": 1, ""retry_delay"": 300.0, ""max_retry_delay"": 600.0, ""sla"": 100.0, ""downstream_task_ids"": [], ""ui_color"": ""#f0ede4"", ""ui_fgcolor"": ""#000"", ""template_ext"": ["".sh"", "".bash""], ""template_fields"": [""bash_command"", ""env"", ""cwd""], ""template_fields_renderers"": {""bash_command"": ""bash"", ""env"": ""json""}, ""bash_command"": ""echo {{ task.task_id }}"", ""_task_type"": ""BashOperator"", # Slightly difference from v2-10-stable here, we manually changed this path ""_task_module"": ""airflow.providers.standard.operators.bash"", ""pool"": ""default_pool"", ""is_setup"": False, ""is_teardown"": False, ""on_failure_fail_dagrun"": False, ""executor_config"": { ""__type"": ""dict"", ""__var"": { ""pod_override"": { ""__type"": ""k8s.V1Pod"", ""__var"": PodGenerator.serialize_pod(executor_config_pod), } }, }, ""doc_md"": ""### Task Tutorial Documentation"", ""_log_config_logger_name"": ""airflow.task.operators"", ""_needs_expansion"": False, ""weight_rule"": ""downstream"", ""start_trigger_args"": None, ""start_from_trigger"": False, ""inlets"": [ { ""__type"": ""dataset"", ""__var"": { ""extra"": {}, ""uri"": ""asset-1"", }, }, { ""__type"": ""dataset_alias"", ""__var"": {""name"": ""alias-name""}, }, ], ""outlets"": [ { ""__type"": ""dataset"", ""__var"": { ""extra"": {}, ""uri"": ""asset-2"", }, }, ], }, }, { ""__type"": ""operator"", ""__var"": { ""task_id"": ""custom_task"", ""retries"": 1, ""retry_delay"": 300.0, ""max_retry_delay"": 600.0, ""sla"": 100.0, ""downstream_task_ids"": [], ""_operator_extra_links"": [{""tests.test_utils.mock_operators.CustomOpLink"": {}}], ""ui_color"": ""#fff"", ""ui_fgcolor"": ""#000"", ""template_ext"": [], ""template_fields"": [""bash_command""], ""template_fields_renderers"": {}, ""_task_type"": ""CustomOperator"", ""_operator_name"": ""@custom"", # Slightly difference from v2-10-stable here, we manually changed this path ""_task_module"": ""tests_common.test_utils.mock_operators"", ""pool"": ""default_pool"", ""is_setup"": False, ""is_teardown"": False, ""on_failure_fail_dagrun"": False, ""_log_config_logger_name"": ""airflow.task.operators"", ""_needs_expansion"": False, ""weight_rule"": ""downstream"", ""start_trigger_args"": None, ""start_from_trigger"": False, }, }, ], ""schedule_interval"": {""__type"": ""timedelta"", ""__var"": 86400.0}, ""timezone"": ""UTC"", ""_access_control"": { ""__type"": ""dict"", ""__var"": { ""test_role"": { ""__type"": ""dict"", ""__var"": { ""DAGs"": { ""__type"": ""set"", ""__var"": [permissions.ACTION_CAN_READ, permissions.ACTION_CAN_EDIT], } }, } }, }, ""edge_info"": {}, ""dag_dependencies"": [ { ""dependency_id"": '{""name"": ""asset-2"", ""uri"": ""asset-2""}', ""dependency_type"": ""asset"", ""label"": ""asset-2"", ""source"": ""simple_dag"", ""target"": ""asset"", }, ], ""params"": [], }, } SerializedDAG.conversion_v1_to_v2(v1) # Update a few subtle differences v1[""dag""][""tags""] = [] v1[""dag""][""catchup""] = False v1[""dag""][""disable_bundle_versioning""] = False expected = copy.deepcopy(serialized_simple_dag_ground_truth) del expected[""dag""][""tasks""][1][""__var""][""_operator_extra_links""] assert v1 == expected" ,UNKNOWN,UNKNOWN,tests/admin_views/tests.py,1,"def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username=""super"", password=""secret"", email=""super@example.com"" ) cls.deleteuser = User.objects.create_user( username=""deleteuser"", password=""secret"", is_staff=True ) cls.s1 = Section.objects.create(name=""Test section"") cls.a1 = Article.objects.create( content=""

Middle content

"", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content=""

Oldest content

"", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content=""

Newest content

"", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title=""A Long Title"", published=True, slug=""a-long-title"" ) cls.v1 = Villain.objects.create(name=""Adam"") cls.v2 = Villain.objects.create(name=""Sue"") cls.sv1 = SuperVillain.objects.create(name=""Bob"") cls.pl1 = Plot.objects.create( name=""World Domination"", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name=""World Peace"", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name=""Corn Conspiracy"", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details=""almost finished"", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location=""underground bunker"", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location=""floating castle"", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location=""super floating castle!"", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(pk=1, name=""I am recursive"", two_id=1) cls.cy2 = CyclicTwo.objects.create(pk=1, name=""I am recursive too"", one_id=1)",CWE-259,django/django,29b6a177d81b9a8d833529bebfc67ef48bda3c7f,"def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username=""super"", password=""secret"", email=""super@example.com"" ) cls.deleteuser = User.objects.create_user( username=""deleteuser"", password=""secret"", is_staff=True ) cls.s1 = Section.objects.create(name=""Test section"") cls.a1 = Article.objects.create( content=""

Middle content

"", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content=""

Oldest content

"", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content=""

Newest content

"", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title=""A Long Title"", published=True, slug=""a-long-title"" ) cls.v1 = Villain.objects.create(name=""Adam"") cls.v2 = Villain.objects.create(name=""Sue"") cls.sv1 = SuperVillain.objects.create(name=""Bob"") cls.pl1 = Plot.objects.create( name=""World Domination"", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name=""World Peace"", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name=""Corn Conspiracy"", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details=""almost finished"", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location=""underground bunker"", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location=""floating castle"", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location=""super floating castle!"", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(name=""I am recursive"", two_id=1) cls.cy2 = CyclicTwo.objects.create(name=""I am recursive too"", one_id=1)" ,UNKNOWN,UNKNOWN,tests/regressiontests/admin_views/tests.py,1,"def test_shortcut_view_only_available_to_staff(self): """""" Only admin users should be able to use the admin shortcut view. """""" user_ctype = ContentType.objects.get_for_model(User) user = User.objects.get(username='super') shortcut_url = ""/test_admin/admin/r/%s/%s/"" % (user_ctype.pk, user.pk) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=False) self.assertTemplateUsed(response, 'admin/login.html') # Logged in? Redirect. self.client.login(username='super', password='secret') response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) self.assertEqual(response.url, 'http://example.com/users/super/')",CWE-259,django/django,e94f405d9499d310ef58b7409a98759a5f5512b0,"def test_shortcut_view_only_available_to_staff(self): """""" Only admin users should be able to use the admin shortcut view. """""" user_ctype = ContentType.objects.get_for_model(User) user = User.objects.get(username='super') shortcut_url = ""/test_admin/admin/r/%s/%s/"" % (user_ctype.pk, user.pk) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=False) self.assertTemplateUsed(response, 'admin/login.html') # Logged in? Redirect. self.client.login(username='super', password='secret') response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], 'http://example.com/users/super/')" ,UNKNOWN,UNKNOWN,tests/pytests/unit/states/test_win_wusa.py,1,"def test_installed_cache_fail(kb): """""" test wusa.install when it fails to cache the file """""" mock_installed = MagicMock(return_value=False) mock_cache = MagicMock(return_value="""") with patch.dict( wusa.__salt__, {""wusa.is_installed"": mock_installed, ""cp.cache_file"": mock_cache}, ): returned = wusa.installed(name=kb, source=""salt://{}.msu"".format(kb)) expected = { ""changes"": {}, ""comment"": 'Unable to cache salt://{}.msu from saltenv ""base""'.format(kb), ""name"": kb, ""result"": False, } assert expected == returned",CWE-703,saltstack/salt,536e103cc26b63c25d0a6537135fce175c55cdf6,"def test_installed_cache_fail(kb): """""" test wusa.install when it fails to cache the file """""" mock_installed = MagicMock(return_value=False) mock_cache = MagicMock(return_value="""") with patch.dict( wusa.__salt__, {""wusa.is_installed"": mock_installed, ""cp.cache_file"": mock_cache}, ): returned = wusa.installed(name=kb, source=""salt://{}.msu"".format(kb)) expected = { ""changes"": {}, ""comment"": ""Unable to cache salt://{}.msu from "" 'saltenv ""base""'.format(kb), ""name"": kb, ""result"": False, } assert expected == returned" functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,bandit/formatters/html.py,0,"def report(manager, filename, sev_level, conf_level, lines=-1): """"""Writes issues to 'filename' in HTML format :param manager: the bandit manager object :param filename: output file name :param sev_level: Filtering severity level :param conf_level: Filtering confidence level :param lines: Number of lines to report, -1 for all """""" header_block = u"""""" Bandit Report """""" report_block = u"""""" {metrics} {skipped}
{results} """""" issue_block = u""""""
{test_name}: {test_text}
Test ID: {test_id}
Severity: {severity}
Confidence: {confidence}
File: {path}
{code} {candidates}
"""""" code_block = u""""""
{code}
"""""" candidate_block = u""""""
Candidates: {candidate_list}
"""""" candidate_issue = u""""""
{code}
"""""" skipped_block = u""""""
Skipped files:

{files_list}
"""""" metrics_block = u""""""
Metrics:
Total lines of code: {loc}
Total lines skipped (#nosec): {nosec}
"""""" issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) baseline = not isinstance(issues, list) # build the skipped string to insert in the report skipped_str = ''.join('%s - %s\n' % (fname, reason) for fname, reason in manager.skipped) if skipped_str: skipped_text = skipped_block.format(files_list=skipped_str) else: skipped_text = '' # build the results string to insert in the report results_str = '' for index, issue in enumerate(issues): if not baseline or len(issues[issue]) == 1: candidates = '' code = code_block.format(code=issue.get_code(lines, True). strip('\n').lstrip(' ')) else: candidates_str = '' code = '' for candidate in issues[issue]: candidate_code = (candidate.get_code(lines, True).strip('\n'). lstrip(' ')) candidates_str += candidate_issue.format(code=candidate_code) candidates = candidate_block.format(candidate_list=candidates_str) results_str += issue_block.format(issue_no=index, issue_class='issue-sev-{}'. format(issue.severity.lower()), test_name=issue.test, test_id=issue.test_id, test_text=issue.text, severity=issue.severity, confidence=issue.confidence, path=issue.fname, code=code, candidates=candidates) # build the metrics string to insert in the report metrics_summary = metrics_block.format( loc=manager.metrics.data['_totals']['loc'], nosec=manager.metrics.data['_totals']['nosec']) # build the report and output it report_contents = report_block.format(metrics=metrics_summary, skipped=skipped_text, results=results_str) with utils.output_file(filename, 'w') as fout: fout.write(str(header_block.encode('utf-8'))) fout.write(str(report_contents.encode('utf-8'))) if filename is not None: logger.info(""HTML output written to file: %s"" % filename)",UNKNOWN,PyCQA/bandit,a047e0fec0fbd000740ce86c51792da88118eb03,"def report(manager, filename, sev_level, conf_level, lines=-1): """"""Writes issues to 'filename' in HTML format :param manager: the bandit manager object :param filename: output file name :param sev_level: Filtering severity level :param conf_level: Filtering confidence level :param lines: Number of lines to report, -1 for all """""" header_block = u"""""" Bandit Report """""" report_block = u"""""" {metrics} {skipped}
{results} """""" issue_block = u""""""
{test_name}: {test_text}
Test ID: {test_id}
Severity: {severity}
Confidence: {confidence}
File: {path}
{code} {candidates}
"""""" code_block = u""""""
{code}
"""""" candidate_block = u""""""
Candidates: {candidate_list}
"""""" candidate_issue = u""""""
{code}
"""""" skipped_block = u""""""
Skipped files:

{files_list}
"""""" metrics_block = u""""""
Metrics:
Total lines of code: {loc}
Total lines skipped (#nosec): {nosec}
"""""" issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) baseline = not isinstance(issues, list) # build the skipped string to insert in the report skipped_str = ''.join('%s - %s\n' % (fname, reason) for fname, reason in manager.skipped) if skipped_str: skipped_text = skipped_block.format(files_list=skipped_str) else: skipped_text = '' # build the results string to insert in the report results_str = '' for index, issue in enumerate(issues): if not baseline or len(issues[issue]) == 1: candidates = '' code = code_block.format(code=issue.get_code(lines, True). strip('\n').lstrip(' ')) else: candidates_str = '' code = '' for candidate in issues[issue]: candidate_code = (candidate.get_code(lines, True).strip('\n'). lstrip(' ')) candidates_str += candidate_issue.format(code=candidate_code) candidates = candidate_block.format(candidate_list=candidates_str) results_str += issue_block.format(issue_no=index, issue_class='issue-sev-{}'. format(issue.severity.lower()), test_name=issue.test, test_id=issue.test_id, test_text=issue.text, severity=issue.severity, confidence=issue.confidence, path=issue.fname, code=code, candidates=candidates) # build the metrics string to insert in the report metrics_summary = metrics_block.format( loc=manager.metrics.data['_totals']['loc'], nosec=manager.metrics.data['_totals']['nosec']) # build the report and output it report_contents = report_block.format(metrics=metrics_summary, skipped=skipped_text, results=results_str) with utils.output_file(filename, 'w') as fout: fout.write(header_block) fout.write(report_contents) if filename is not None: logger.info(""HTML output written to file: %s"" % filename)" ,UNKNOWN,UNKNOWN,tests/test_requests.py,1,"def test_headers_preserve_order(self, httpbin): """"""Preserve order when headers provided as OrderedDict."""""" ses = requests.Session() ses.headers = OrderedDict() ses.headers['Accept-Encoding'] = 'identity' ses.headers['First'] = '1' ses.headers['Second'] = '2' headers = OrderedDict([('Third', '3'), ('Fourth', '4')]) headers['Fifth'] = '5' headers['Second'] = '222' req = requests.Request('GET', httpbin('get'), headers=headers) prep = ses.prepare_request(req) items = list(prep.headers.items()) assert items[0] == ('Accept-Encoding', 'identity') assert items[1] == ('First', '1') assert items[2] == ('Second', '222') assert items[3] == ('Third', '3') assert items[4] == ('Fourth', '4') assert items[5] == ('Fifth', '5')",CWE-703,psf/requests,b1a7dcd79915ec7a58043031da432b5841d4d8ec,"def test_headers_preserve_order(self, httpbin): """"""Preserve order when headers provided as OrderedDict."""""" ses = requests.Session() ses.headers = OrderedDict() ses.headers['Accept-Encoding'] = 'identity' ses.headers['First'] = '1' ses.headers['Second'] = '2' headers = OrderedDict([('Third', '3'), ('Fourth', '4')]) headers['Fifth'] = '5' headers['Second'] = '222' req = requests.Request('GET', httpbin('get'), headers = headers) prep = ses.prepare_request(req) items = prep.headers.items() assert items[0] == ('Accept-Encoding', 'identity') assert items[1] == ('First', '1') assert items[2] == ('Second', '222') assert items[3] == ('Third', '3') assert items[4] == ('Fourth', '4') assert items[5] == ('Fifth', '5')" ,UNKNOWN,UNKNOWN,test/units/template/test_tests_as_filters_warning.py,1,"def test_tests_as_filters_warning(mocker): fake_loader = DictDataLoader({ ""/path/to/my_file.txt"": ""foo\n"", }) templar = Templar(loader=fake_loader, variables={}) filters = templar._get_filters(templar.environment.filters) mocker.patch.object(display, 'deprecated') # Call successful test, ensure the message is correct filters['successful']({}) display.deprecated.assert_called_once_with( 'Using tests as filters is deprecated. Instead of using `result|successful` use `result is successful`', version='2.9' ) # Call success test, ensure the message is correct display.deprecated.reset_mock() filters['success']({}) display.deprecated.assert_called_once_with( 'Using tests as filters is deprecated. Instead of using `result|success` use `result is success`', version='2.9' ) # Call bool filter, ensure no deprecation message was displayed display.deprecated.reset_mock() filters['bool'](True) assert display.deprecated.call_count == 0 # Ensure custom test does not override builtin filter assert filters.get('abs') != isabs",CWE-703,ansible/ansible,a30befa609199c1733c86d57a9e95501cb2ebb08,"def test_tests_as_filters_warning(mocker): fake_loader = DictDataLoader({ ""/path/to/my_file.txt"": ""foo\n"", }) templar = Templar(loader=fake_loader, variables={}) filters = templar._get_filters(templar.environment.filters) mocker.patch.object(display, 'deprecated') # Call successful test, ensure the message is correct filters['successful']({}) display.deprecated.assert_called_once_with( 'Using tests as filters is deprecated. Instead of using `result|successful` instead use `result is successful`', version='2.9' ) # Call success test, ensure the message is correct display.deprecated.reset_mock() filters['success']({}) display.deprecated.assert_called_once_with( 'Using tests as filters is deprecated. Instead of using `result|success` instead use `result is success`', version='2.9' ) # Call bool filter, ensure no deprecation message was displayed display.deprecated.reset_mock() filters['bool'](True) assert display.deprecated.call_count == 0 # Ensure custom test does not override builtin filter assert filters.get('abs') != isabs" functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/core/data/url/handlers/mangle.py,0,"def _http_resp_2_httplib(self, original_response, mangled_response): """""" Convert an HTTPResponse.HTTPResponse object to a httplib.httpresponse subclass that I created in keepalive. :param original_response: HTTPResponse.HTTPResponse object :return: httplib.httpresponse subclass """""" ka_resp = MangledKeepAliveHTTPResponse() ka_resp.set_body(mangled_response.get_body()) ka_resp.headers = mangled_response.get_headers() ka_resp.code = mangled_response.get_code() ka_resp._url = mangled_response.get_uri().url_string ka_resp.msg = original_response.msg ka_resp.id = original_response.id ka_resp.set_wait_time(original_response.get_wait_time()) ka_resp.encoding = mangled_response.charset return ka_resp",,andresriancho/w3af,1d13fc4baf5b50e47c747d32909075b09d0de52b,"def _http_resp_2_httplib(self, original_response, mangled_response): """""" Convert an HTTPResponse.HTTPResponse object to a httplib.httpresponse subclass that I created in keepalive. :param HTTPResponse: HTTPResponse.HTTPResponse object :return: httplib.httpresponse subclass """""" ka_resp = MangledKeepAliveHTTPResponse() ka_resp.set_body(mangled_response.get_body()) ka_resp.headers = mangled_response.get_headers() ka_resp.code = mangled_response.get_code() ka_resp._url = mangled_response.get_uri().url_string ka_resp.msg = original_response.msg ka_resp.id = original_response.id ka_resp.set_wait_time(original_response.get_wait_time()) ka_resp.encoding = mangled_response.charset return ka_resp" ,UNKNOWN,UNKNOWN,pkg/tests/support/helpers.py,1,"def _install_pkgs(self, upgrade=False): pkg = self.pkgs[0] if platform.is_windows(): if upgrade: self.root = self.install_dir.parent self.bin_dir = self.install_dir self.ssm_bin = self.install_dir / ""ssm.exe"" if pkg.endswith(""exe""): # Install the package log.debug(""Installing: %s"", str(pkg)) ret = self.proc.run(str(pkg), ""/start-minion=0"", ""/S"") self._check_retcode(ret) elif pkg.endswith(""msi""): # Install the package log.debug(""Installing: %s"", str(pkg)) # Write a batch file to run the installer. It is impossible to # perform escaping of the START_MINION property that the MSI # expects unless we do it via a batch file batch_file = pathlib.Path(pkg).parent / ""install_msi.cmd"" batch_content = f'msiexec /qn /i ""{str(pkg)}"" START_MINION=""""\n' with open(batch_file, ""w"") as fp: fp.write(batch_content) # Now run the batch file ret = self.proc.run(""cmd.exe"", ""/c"", str(batch_file)) self._check_retcode(ret) else: log.error(""Invalid package: %s"", pkg) return False # Remove the service installed by the installer log.debug(""Removing installed salt-minion service"") self.proc.run(str(self.ssm_bin), ""remove"", ""salt-minion"", ""confirm"") self.update_process_path() elif platform.is_darwin(): daemons_dir = pathlib.Path(os.sep, ""Library"", ""LaunchDaemons"") service_name = ""com.saltstack.salt.minion"" plist_file = daemons_dir / f""{service_name}.plist"" log.debug(""Installing: %s"", str(pkg)) ret = self.proc.run(""installer"", ""-pkg"", str(pkg), ""-target"", ""/"") self._check_retcode(ret) # Stop the service installed by the installer self.proc.run(""launchctl"", ""disable"", f""system/{service_name}"") self.proc.run(""launchctl"", ""bootout"", ""system"", str(plist_file)) elif upgrade: log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs)) ret = self.proc.run(self.pkg_mngr, ""upgrade"", ""-y"", *self.pkgs) else: log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs)) ret = self.proc.run(self.pkg_mngr, ""install"", ""-y"", *self.pkgs) if not platform.is_darwin() and not platform.is_windows(): # Make sure we don't have any trailing references to old package file locations assert ""No such file or directory"" not in ret.stdout assert ""/saltstack/salt/run"" not in ret.stdout log.info(ret) self._check_retcode(ret)",CWE-703,saltstack/salt,1f145d37f29b02e629fcfd449d1c2b460d651030,"def _install_pkgs(self, upgrade=False): pkg = self.pkgs[0] if platform.is_windows(): if upgrade: self.root = self.install_dir.parent self.bin_dir = self.install_dir self.ssm_bin = self.install_dir / ""ssm.exe"" if pkg.endswith(""exe""): # Install the package log.debug(""Installing: %s"", str(pkg)) ret = self.proc.run(str(pkg), ""/start-minion=0"", ""/S"") self._check_retcode(ret) elif pkg.endswith(""msi""): # Install the package log.debug(""Installing: %s"", str(pkg)) # Write a batch file to run the installer. It is impossible to # perform escaping of the START_MINION property that the MSI # expects unless we do it via a batch file batch_file = pathlib.Path(pkg).parent / ""install_msi.cmd"" batch_content = f'msiexec /qn /i ""{str(pkg)}"" START_MINION=""""\n' with open(batch_file, ""w"") as fp: fp.write(batch_content) # Now run the batch file ret = self.proc.run(""cmd.exe"", ""/c"", str(batch_file)) self._check_retcode(ret) else: log.error(""Invalid package: %s"", pkg) return False # Remove the service installed by the installer log.debug(""Removing installed salt-minion service"") self.proc.run(str(self.ssm_bin), ""remove"", ""salt-minion"", ""confirm"") self.update_process_path() elif platform.is_darwin(): daemons_dir = pathlib.Path(os.sep, ""Library"", ""LaunchDaemons"") service_name = ""com.saltstack.salt.minion"" plist_file = daemons_dir / f""{service_name}.plist"" log.debug(""Installing: %s"", str(pkg)) ret = self.proc.run(""installer"", ""-pkg"", str(pkg), ""-target"", ""/"") self._check_retcode(ret) # Stop the service installed by the installer self.proc.run(""launchctl"", ""disable"", f""system/{service_name}"") self.proc.run(""launchctl"", ""bootout"", ""system"", str(plist_file)) elif upgrade: log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs)) ret = self.proc.run(self.pkg_mngr, ""upgrade"", ""-y"", *self.pkgs) else: log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs)) ret = self.proc.run(self.pkg_mngr, ""install"", ""-y"", *self.pkgs) if not (platform.is_darwin() or platform.is_windows()): # Make sure we don't have any trailing references to old package file locations assert ""No such file or directory"" not in ret.stdout assert ""/saltstack/salt/run"" not in ret.stdout log.info(ret) self._check_retcode(ret)" functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/vadinfo.py,0,"def write_vad_control(self, outfd, vad): """"""Renders a text version of a (non-short) Vad's control information"""""" # even if the ControlArea is not NULL, it is only meaningful # for shared (non private) memory sections. if vad.u.VadFlags.PrivateMemory == 1: return control_area = vad.ControlArea if not control_area: return outfd.write(""ControlArea @{0:08x} Segment {1:08x}\n"".format(control_area.dereference().obj_offset, control_area.Segment)) outfd.write(""Dereference list: Flink {0:08x}, Blink {1:08x}\n"".format(control_area.DereferenceList.Flink, control_area.DereferenceList.Blink)) outfd.write(""NumberOfSectionReferences: {0:10} NumberOfPfnReferences: {1:10}\n"".format(control_area.NumberOfSectionReferences, control_area.NumberOfPfnReferences)) outfd.write(""NumberOfMappedViews: {0:10} NumberOfUserReferences: {1:10}\n"".format(control_area.NumberOfMappedViews, control_area.NumberOfUserReferences)) outfd.write(""WaitingForDeletion Event: {0:08x}\n"".format(control_area.WaitingForDeletion)) outfd.write(""Control Flags: {0}\n"".format(str(control_area.u.Flags))) file_object = vad.FileObject if file_object: outfd.write(""FileObject @{0:08x}, Name: {1}\n"".format(file_object.obj_offset, str(file_object.FileName or '')))",,volatilityfoundation/volatility,d6050871e91dfdbad855817f0121c7c63298385a,"def write_vad_control(self, outfd, vad): """"""Renders a text version of a (non-short) Vad's control information"""""" # even if the ControlArea is not NULL, it is only meaningful # for shared (non private) memory sections. if vad.u.VadFlags.PrivateMemory == 1: return control_area = vad.ControlArea if not control_area: return outfd.write(""ControlArea @{0:08x} Segment {1:08x}\n"".format(control_area.dereference().obj_offset, control_area.Segment)) outfd.write(""Dereference list: Flink {0:08x}, Blink {1:08x}\n"".format(control_area.DereferenceList.Flink, control_area.DereferenceList.Blink)) outfd.write(""NumberOfSectionReferences: {0:10} NumberOfPfnReferences: {1:10}\n"".format(control_area.NumberOfSectionReferences, control_area.NumberOfPfnReferences)) outfd.write(""NumberOfMappedViews: {0:10} NumberOfUserReferences: {1:10}\n"".format(control_area.NumberOfMappedViews, control_area.NumberOfUserReferences)) outfd.write(""WaitingForDeletion Event: {0:08x}\n"".format(control_area.WaitingForDeletion)) outfd.write(""Control Flags: {0}\n"".format(str(control_area.u.Flags))) file_object = vad.FileObject if file_object: outfd.write(""FileObject @{0:08x}, Name: {1}\n"".format(file_object.obj_offset, file_object.FileName))" ,UNKNOWN,UNKNOWN,tests/tensorflow/test_tensorflow2_autolog.py,1,"def test_tf_keras_autolog_implicit_batch_size_for_generator_dataset_without_side_effects( generator, batch_size, ): from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense data = np.array([[1, 2, 3], [3, 2, 1], [2, 2, 2], [10, 20, 30], [30, 20, 10], [20, 20, 20]]) target = np.array([[1], [3], [2], [11], [13], [12]]) model = Sequential() model.add( Dense( 5, input_dim=3, activation=""relu"", kernel_initializer=""zeros"", bias_initializer=""zeros"" ) ) model.add(Dense(1, kernel_initializer=""zeros"", bias_initializer=""zeros"")) model.compile(loss=""mae"", optimizer=""adam"", metrics=[""mse""]) mlflow.autolog() actual_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1] mlflow.autolog(disable=True) expected_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1] np.testing.assert_allclose(actual_mse, expected_mse, atol=1) assert mlflow.last_active_run().data.params[""batch_size""] == str(batch_size)",CWE-703,mlflow/mlflow,c7cdef4d54abd31a45f10d3388113e9e2db08bbf,"def test_tf_keras_autolog_implicit_batch_size_for_generator_dataset_without_side_effects( generator, batch_size, ): from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense data = np.array([[1, 2, 3], [3, 2, 1], [2, 2, 2], [10, 20, 30], [30, 20, 10], [20, 20, 20]]) target = np.array([[1], [3], [2], [11], [13], [12]]) model = Sequential() model.add( Dense( 5, input_dim=3, activation=""relu"", kernel_initializer=""zeros"", bias_initializer=""zeros"" ) ) model.add(Dense(1, kernel_initializer=""zeros"", bias_initializer=""zeros"")) model.compile(loss=""mae"", optimizer=""adam"", metrics=[""mse""]) mlflow.autolog() actual_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1] mlflow.autolog(disable=True) expected_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1] np.testing.assert_allclose(actual_mse, expected_mse, atol=1) assert mlflow.last_active_run().data.params[""batch_size""] == str(batch_size)" functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/win32/hashdump.py,0,"def find_control_set(sysaddr): root = rawreg.get_root(sysaddr) if not root: return 1 csselect = rawreg.open_key(root, [""Select""]) if not csselect: return 1 for v in rawreg.values(csselect): if v.Name == ""Current"": return v.Data return 1",,volatilityfoundation/volatility,19d12116fe2f1f3d98873799c8fe80ddbf046f32,"def find_control_set(sysaddr): root = rawreg.get_root(sysaddr) if not root: return 1 csselect = rawreg.open_key(root, [""Select""]) if not csselect: return 1 for v in rawreg.values(csselect): if v.Name == ""Current"": return v.Data" functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/cli.py,0,"def load_dotenv(path=None): """"""Load ""dotenv"" files in order of precedence to set environment variables. If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files. Changes the current working directory to the location of the first file found, with the assumption that it is in the top level project directory and will be where the Python path should import local packages from. This is a no-op if `python-dotenv`_ is not installed. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme :param path: Load the file at this location instead of searching. :return: ``True`` if a file was loaded. .. versionadded:: 1.0 """""" if dotenv is None: if path or os.path.isfile('.env') or os.path.isfile('.flaskenv'): click.secho( ' * Tip: There are .env files present.' ' Do ""pip install python-dotenv"" to use them.', fg='yellow') return if path is not None: return dotenv.load_dotenv(path) new_dir = None for name in ('.env', '.flaskenv'): path = dotenv.find_dotenv(name, usecwd=True) if not path: continue if new_dir is None: new_dir = os.path.dirname(path) dotenv.load_dotenv(path) if new_dir and os.getcwd() != new_dir: os.chdir(new_dir) return new_dir is not None",,pallets/flask,b2ec6a33a235dbd9f57bd6265ec54cfb675243f7,"def load_dotenv(path=None): """"""Load ""dotenv"" files in order of precedence to set environment variables. If an env var is already set it is not overwritten, so earlier files in the list are preferred over later files. Changes the current working directory to the location of the first file found, with the assumption that it is in the top level project directory and will be where the Python path should import local packages from. This is a no-op if `python-dotenv`_ is not installed. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme :param path: Load the file at this location instead of searching. :return: ``True`` if a file was loaded. .. versionadded:: 1.0 """""" if dotenv is None: if path or os.path.exists('.env') or os.path.exists('.flaskenv'): click.secho( ' * Tip: There are .env files present.' ' Do ""pip install python-dotenv"" to use them.', fg='yellow') return if path is not None: return dotenv.load_dotenv(path) new_dir = None for name in ('.env', '.flaskenv'): path = dotenv.find_dotenv(name, usecwd=True) if not path: continue if new_dir is None: new_dir = os.path.dirname(path) dotenv.load_dotenv(path) if new_dir and os.getcwd() != new_dir: os.chdir(new_dir) return new_dir is not None" ,UNKNOWN,UNKNOWN,tests/unit/utils/test_thin.py,1,"def test_pack_alternatives_exclude(self): """""" test pack_alternatives when mixing manually set dependencies and auto detecting other modules. """""" patch_proc = patch( ""salt.utils.thin.subprocess.Popen"", self._popen( None, side_effect=[ (bts(self.fake_libs[""distro""]), bts("""")), (bts(self.fake_libs[""yaml""]), bts("""")), (bts(self.fake_libs[""tornado""]), bts("""")), (bts(self.fake_libs[""msgpack""]), bts("""")), (bts(self.fake_libs[""networkx""]), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), ], ), ) patch_os = patch(""os.path.exists"", return_value=True) ext_conf = copy.deepcopy(self.ext_conf) ext_conf[""test""][""auto_detect""] = True for lib in self.fake_libs.values(): os.makedirs(lib) with salt.utils.files.fopen(os.path.join(lib, ""__init__.py""), ""w+"") as fp_: fp_.write(""test"") exp_files = self.exp_files.copy() exp_files.extend( [ os.path.join(""yaml"", ""__init__.py""), os.path.join(""tornado"", ""__init__.py""), os.path.join(""msgpack"", ""__init__.py""), os.path.join(""networkx"", ""__init__.py""), ] ) patch_which = patch(""salt.utils.path.which"", return_value=True) with patch_os, patch_proc, patch_which: thin._pack_alternative(ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in exp_files: assert [x for x in calls if f""{_file}"" in x[-2]]",CWE-703,saltstack/salt,3701105a59a76d1b7dcdb46dd6e720bb85e59c42,"def test_pack_alternatives_exclude(self): """""" test pack_alternatives when mixing manually set dependencies and auto detecting other modules. """""" patch_proc = patch( ""salt.utils.thin.subprocess.Popen"", self._popen( None, side_effect=[ (bts(self.fake_libs[""distro""]), bts("""")), (bts(self.fake_libs[""yaml""]), bts("""")), (bts(self.fake_libs[""tornado""]), bts("""")), (bts(self.fake_libs[""msgpack""]), bts("""")), (bts(self.fake_libs[""networkx""]), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""""), bts("""")), (bts(""looseversion.py""), bts("""")), (bts(""packaging/__init__.py""), bts("""")), ], ), ) patch_os = patch(""os.path.exists"", return_value=True) ext_conf = copy.deepcopy(self.ext_conf) ext_conf[""test""][""auto_detect""] = True for lib in self.fake_libs.values(): os.makedirs(lib) with salt.utils.files.fopen(os.path.join(lib, ""__init__.py""), ""w+"") as fp_: fp_.write(""test"") exp_files = self.exp_files.copy() exp_files.extend( [ os.path.join(""yaml"", ""__init__.py""), os.path.join(""tornado"", ""__init__.py""), os.path.join(""msgpack"", ""__init__.py""), os.path.join(""networkx"", ""__init__.py""), ] ) patch_which = patch(""salt.utils.path.which"", return_value=True) with patch_os, patch_proc, patch_which: thin._pack_alternative(ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in exp_files: assert [x for x in calls if f""{_file}"" in x[-2]]" functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/invalid_models_tests/test_relative_fields.py,0,"def test_clash_between_accessors(self): class Target(models.Model): pass class Model(models.Model): foreign = models.ForeignKey(Target) m2m = models.ManyToManyField(Target) errors = Model.check() expected = [ Error( 'Clash between accessors for Model.foreign and Model.m2m.', hint=('Add or change a related_name argument to the definition ' 'for Model.foreign or Model.m2m.'), obj=Model._meta.get_field('foreign'), id='E016', ), Error( 'Clash between accessors for Model.m2m and Model.foreign.', hint=('Add or change a related_name argument to the definition ' 'for Model.m2m or Model.foreign.'), obj=Model._meta.get_field('m2m'), id='E016', ), ] self.assertEqual(errors, expected)",CWE-Unknown,django/django,d0133504e57589dc8983a20bf488e069bddd772c,"def test_clash_between_accessors(self): class Target(models.Model): pass class Model(models.Model): foreign = models.ForeignKey(Target) m2m = models.ManyToManyField(Target) errors = Model.check() expected = [ Error( 'Clash between accessors for Model.foreign and Model.m2m.', hint=('Add or change a related_name argument to the definition ' 'for Model.foreign or Model.m2m.'), obj=Model._meta.get_field('foreign'), id='E016', ), Error( 'Clash between accessors for Model.m2m and Model.foreign.', hint=('Add or change a related_name argument to the definition ' 'for Model.m2m or Model.foreign.'), obj=Model._meta.get_field('m2m'), id='E016', ), ] self.assertEqual(errors, expected)" ,UNKNOWN,UNKNOWN,tests/admin_views/admin.py,1,"def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results( request, queryset, search_term ) try: search_term_as_int = int(search_term) except ValueError: pass else: queryset |= self.model.objects.filter(age=search_term_as_int) return queryset, use_distinct",CWE-703,django/django,0a2d3b7387b815b4e5d5f3c026f8409fd2a7ff70,"def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results( request, queryset, search_term ) try: search_term_as_int = int(search_term) queryset |= self.model.objects.filter(age=search_term_as_int) except: pass return queryset, use_distinct" ,UNKNOWN,UNKNOWN,tests/integration/shell/cp.py,1,"def test_cp_testfile(self): ''' test salt-cp ''' minions = [] for line in self.run_salt('--out yaml ""*"" test.ping'): if not line: continue data = yaml.load(line) minions.extend(data.keys()) self.assertNotEqual(minions, []) testfile = os.path.abspath( os.path.join( os.path.dirname(os.path.dirname(__file__)), 'files', 'file', 'base', 'testfile' ) ) with salt.utils.fopen(testfile, 'r') as fh_: testfile_contents = fh_.read() for idx, minion in enumerate(minions): ret = self.run_salt( '--out yaml {0} file.directory_exists {1}'.format( pipes.quote(minion), integration.TMP ) ) data = yaml.load('\n'.join(ret)) if data[minion] is False: ret = self.run_salt( '--out yaml {0} file.makedirs {1}'.format( pipes.quote(minion), integration.TMP ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) minion_testfile = os.path.join( integration.TMP, 'cp_{0}_testfile'.format(idx) ) ret = self.run_cp('--out pprint {0} {1} {2}'.format( pipes.quote(minion), pipes.quote(testfile), pipes.quote(minion_testfile) )) data = yaml.load('\n'.join(ret)) for part in six.itervalues(data): self.assertTrue(part[minion_testfile]) ret = self.run_salt( '--out yaml {0} file.file_exists {1}'.format( pipes.quote(minion), pipes.quote(minion_testfile) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt( '--out yaml {0} file.contains {1} {2}'.format( pipes.quote(minion), pipes.quote(minion_testfile), pipes.quote(testfile_contents) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt( '--out yaml {0} file.remove {1}'.format( pipes.quote(minion), pipes.quote(minion_testfile) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion])",CWE-20,saltstack/salt,35b2076584ffeec8730f0f5af59bdec0dd29d257,"def test_cp_testfile(self): ''' test salt-cp ''' minions = [] for line in self.run_salt('--out yaml ""*"" test.ping'): if not line: continue data = yaml.load(line) minions.extend(data.keys()) # pylint: disable=incompatible-py3-code # since we're extending a list, the Py3 dict_keys view will behave # as expected. self.assertNotEqual(minions, []) testfile = os.path.abspath( os.path.join( os.path.dirname(os.path.dirname(__file__)), 'files', 'file', 'base', 'testfile' ) ) with salt.utils.fopen(testfile, 'r') as fh_: testfile_contents = fh_.read() for idx, minion in enumerate(minions): ret = self.run_salt( '--out yaml {0} file.directory_exists {1}'.format( pipes.quote(minion), integration.TMP ) ) data = yaml.load('\n'.join(ret)) if data[minion] is False: ret = self.run_salt( '--out yaml {0} file.makedirs {1}'.format( pipes.quote(minion), integration.TMP ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) minion_testfile = os.path.join( integration.TMP, 'cp_{0}_testfile'.format(idx) ) ret = self.run_cp('--out pprint {0} {1} {2}'.format( pipes.quote(minion), pipes.quote(testfile), pipes.quote(minion_testfile) )) data = yaml.load('\n'.join(ret)) for part in six.itervalues(data): self.assertTrue(part[minion_testfile]) ret = self.run_salt( '--out yaml {0} file.file_exists {1}'.format( pipes.quote(minion), pipes.quote(minion_testfile) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt( '--out yaml {0} file.contains {1} {2}'.format( pipes.quote(minion), pipes.quote(minion_testfile), pipes.quote(testfile_contents) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion]) ret = self.run_salt( '--out yaml {0} file.remove {1}'.format( pipes.quote(minion), pipes.quote(minion_testfile) ) ) data = yaml.load('\n'.join(ret)) self.assertTrue(data[minion])" ,UNKNOWN,UNKNOWN,extra/icmpsh/icmpsh_m.py,1,"def main(src, dst): if sys.platform == ""nt"": sys.stderr.write('icmpsh master can only run on Posix systems\n') sys.exit(255) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: sys.stderr.write('You need to install Python Impacket library first\n') sys.exit(255) # Make standard input a non-blocking file stdin_fd = sys.stdin.fileno() setNonBlocking(stdin_fd) # Open one socket for ICMP protocol # A special option is set on the socket so that IP headers are included # with the returned data try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error: sys.stderr.write('You need to run icmpsh master with administrator privileges\n') sys.exit(1) sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Create a new IP packet and set its source and destination addresses ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) # Create a new ICMP packet of type ECHO REPLY icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) # Instantiate an IP packets decoder decoder = ImpactDecoder.IPDecoder() while True: try: cmd = '' # Wait for incoming replies if sock in select.select([sock], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): # Socket remotely closed sock.close() sys.exit(0) # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child() # If the packet matches, report it to the user if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type(): # Get identifier and sequence number ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: sys.stdout.write(data) # Parse command from standard input try: cmd = sys.stdin.readline() except: pass if cmd == 'exit\n': return # Set sequence number and identifier icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(cmd)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) try: # Send it to the target host sock.sendto(ip.get_packet(), (dst, 0)) except socket.error as ex: sys.stderr.write(""'%s'\n"" % ex) sys.stderr.flush() except: break",CWE-703,sqlmapproject/sqlmap,1fa81fedf310c2152d151b068bc12a0821f38fa1,"def main(src, dst): if sys.platform == ""nt"": sys.stderr.write('icmpsh master can only run on Posix systems\n') sys.exit(255) try: from impacket import ImpactDecoder from impacket import ImpactPacket except ImportError: sys.stderr.write('You need to install Python Impacket library first\n') sys.exit(255) # Make standard input a non-blocking file stdin_fd = sys.stdin.fileno() setNonBlocking(stdin_fd) # Open one socket for ICMP protocol # A special option is set on the socket so that IP headers are included # with the returned data try: sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) except socket.error: sys.stderr.write('You need to run icmpsh master with administrator privileges\n') sys.exit(1) sock.setblocking(0) sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Create a new IP packet and set its source and destination addresses ip = ImpactPacket.IP() ip.set_ip_src(src) ip.set_ip_dst(dst) # Create a new ICMP packet of type ECHO REPLY icmp = ImpactPacket.ICMP() icmp.set_icmp_type(icmp.ICMP_ECHOREPLY) # Instantiate an IP packets decoder decoder = ImpactDecoder.IPDecoder() while True: cmd = '' # Wait for incoming replies if sock in select.select([sock], [], [])[0]: buff = sock.recv(4096) if 0 == len(buff): # Socket remotely closed sock.close() sys.exit(0) # Packet received; decode and display it ippacket = decoder.decode(buff) icmppacket = ippacket.child() # If the packet matches, report it to the user if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type(): # Get identifier and sequence number ident = icmppacket.get_icmp_id() seq_id = icmppacket.get_icmp_seq() data = icmppacket.get_data_as_string() if len(data) > 0: sys.stdout.write(data) # Parse command from standard input try: cmd = sys.stdin.readline() except: pass if cmd == 'exit\n': return # Set sequence number and identifier icmp.set_icmp_id(ident) icmp.set_icmp_seq(seq_id) # Include the command as data inside the ICMP packet icmp.contains(ImpactPacket.Data(cmd)) # Calculate its checksum icmp.set_icmp_cksum(0) icmp.auto_checksum = 1 # Have the IP packet contain the ICMP packet (along with its payload) ip.contains(icmp) try: # Send it to the target host sock.sendto(ip.get_packet(), (dst, 0)) except socket.error as ex: sys.stderr.write(""'%s'\n"" % ex) sys.stderr.flush()" functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/core/xmldump.py,0,"def query(self, query, queryRes): ''' Adds details of an executed query to the xml. The query details are the query itself and its results. ''' queryElem = self.__doc.createElement(QUERY_ELEM_NAME) queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query)) queryElem.appendChild(self._createTextNode(queryRes)) queriesElem = self._getRootChild(QUERIES_ELEM_NAME) if (not(queriesElem)): queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME) self._addToRoot(queriesElem) queriesElem.appendChild(queryElem)",,sqlmapproject/sqlmap,473a39b8204a67e93663b2f15954f7076a411088,"def query(self, query, queryRes): ''' Adds details of an executed query to the xml. The query details are the query itself and it's results. ''' queryElem = self.__doc.createElement(QUERY_ELEM_NAME) queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query)) queryElem.appendChild(self._createTextNode(queryRes)) queriesElem = self._getRootChild(QUERIES_ELEM_NAME) if (not(queriesElem)): queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME) self._addToRoot(queriesElem) queriesElem.appendChild(queryElem)" ,UNKNOWN,UNKNOWN,providers/tests/standard/operators/test_python.py,1,"def test_provide_context_does_not_fail(self): """"""Ensures that provide_context doesn't break dags in 2.0."""""" def func(custom, dag): assert custom == 1, ""custom should be 1"" assert dag is not None, ""dag should be set"" error_message = ""Invalid arguments were passed to PythonOperator \\(task_id: task_test-provide-context-does-not-fail\\). Invalid arguments were:\n\\*\\*kwargs: {'provide_context': True}"" with pytest.raises((TypeError, AirflowException), match=error_message): self.run_as_task(func, op_kwargs={""custom"": 1}, provide_context=True)",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_provide_context_does_not_fail(self): """"""Ensures that provide_context doesn't break dags in 2.0."""""" def func(custom, dag): assert 1 == custom, ""custom should be 1"" assert dag is not None, ""dag should be set"" error_message = ""Invalid arguments were passed to PythonOperator \\(task_id: task_test-provide-context-does-not-fail\\). Invalid arguments were:\n\\*\\*kwargs: {'provide_context': True}"" with pytest.raises((TypeError, AirflowException), match=error_message): self.run_as_task(func, op_kwargs={""custom"": 1}, provide_context=True)" ,UNKNOWN,UNKNOWN,task-sdk/tests/task_sdk/definitions/test_asset_decorators.py,1,"def test_determine_kwargs( self, mock_supervisor_comms, example_asset_func_with_valid_arg_as_inlet_asset, ): asset_definition = asset(schedule=None, uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""})( example_asset_func_with_valid_arg_as_inlet_asset ) mock_supervisor_comms.send.side_effect = [ AssetResult( name=""example_asset_func"", uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""}, ), AssetResult(name=""inlet_asset_1"", uri=""s3://bucket/object1"", group=""asset"", extra=None), AssetResult(name=""inlet_asset_2"", uri=""inlet_asset_2"", group=""asset"", extra=None), ] op = _AssetMainOperator( task_id=""example_asset_func"", inlets=[Asset.ref(name=""inlet_asset_1""), Asset.ref(name=""inlet_asset_2"")], outlets=[asset_definition], python_callable=example_asset_func_with_valid_arg_as_inlet_asset, definition_name=""example_asset_func"", ) assert op.determine_kwargs(context={""k"": ""v""}) == { ""self"": Asset( name=""example_asset_func"", uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""}, ), ""context"": {""k"": ""v""}, ""inlet_asset_1"": Asset(name=""inlet_asset_1"", uri=""s3://bucket/object1""), ""inlet_asset_2"": Asset(name=""inlet_asset_2""), } assert mock_supervisor_comms.mock_calls == [ mock.call.send(GetAssetByName(name=""example_asset_func"")), mock.call.send(GetAssetByName(name=""inlet_asset_1"")), mock.call.send(GetAssetByName(name=""inlet_asset_2"")), ]",CWE-703,apache/airflow,accfbc3dc06b73cc0ae3d2d77454ff5669788ae5,"def test_determine_kwargs( self, mock_supervisor_comms, example_asset_func_with_valid_arg_as_inlet_asset, ): asset_definition = asset(schedule=None, uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""})( example_asset_func_with_valid_arg_as_inlet_asset ) mock_supervisor_comms.get_message.side_effect = [ AssetResult( name=""example_asset_func"", uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""}, ), AssetResult(name=""inlet_asset_1"", uri=""s3://bucket/object1"", group=""asset"", extra=None), AssetResult(name=""inlet_asset_2"", uri=""inlet_asset_2"", group=""asset"", extra=None), ] op = _AssetMainOperator( task_id=""example_asset_func"", inlets=[Asset.ref(name=""inlet_asset_1""), Asset.ref(name=""inlet_asset_2"")], outlets=[asset_definition], python_callable=example_asset_func_with_valid_arg_as_inlet_asset, definition_name=""example_asset_func"", ) assert op.determine_kwargs(context={""k"": ""v""}) == { ""self"": Asset( name=""example_asset_func"", uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""}, ), ""context"": {""k"": ""v""}, ""inlet_asset_1"": Asset(name=""inlet_asset_1"", uri=""s3://bucket/object1""), ""inlet_asset_2"": Asset(name=""inlet_asset_2""), } assert mock_supervisor_comms.mock_calls == [ mock.call.send_request(mock.ANY, GetAssetByName(name=""example_asset_func"")), mock.call.get_message(), mock.call.send_request(mock.ANY, GetAssetByName(name=""inlet_asset_1"")), mock.call.get_message(), mock.call.send_request(mock.ANY, GetAssetByName(name=""inlet_asset_2"")), mock.call.get_message(), ]" ,UNKNOWN,UNKNOWN,django/db/backends/base/schema.py,1,"def remove_field(self, model, field): """""" Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """""" # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.delete_model(field.remote_field.through) # It might not actually have a column behind it if field.db_parameters(connection=self.connection)['type'] is None: return # Drop any FK constraints, MySQL requires explicit deletion if field.remote_field: fk_names = self._constraint_names(model, [field.column], foreign_key=True) for fk_name in fk_names: self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name)) # Delete the column sql = self.sql_delete_column % { ""table"": self.quote_name(model._meta.db_table), ""column"": self.quote_name(field.column), } self.execute(sql) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() # Remove all deferred statements referencing the deleted column. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column): self.deferred_sql.remove(sql)",CWE-89,django/django,c12745f6826280acb637f9c43cd2c7c2ef3d8761,"def remove_field(self, model, field): """""" Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """""" # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.delete_model(field.remote_field.through) # It might not actually have a column behind it if field.db_parameters(connection=self.connection)['type'] is None: return # Drop any FK constraints, MySQL requires explicit deletion if field.remote_field: fk_names = self._constraint_names(model, [field.column], foreign_key=True) for fk_name in fk_names: self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name)) # Delete the column sql = self.sql_delete_column % { ""table"": self.quote_name(model._meta.db_table), ""column"": self.quote_name(field.column), } self.execute(sql) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column): self.deferred_sql.remove(sql)" ,UNKNOWN,UNKNOWN,test/units/parsing/vault/test_vault.py,1,"def test_format_output(self): v = VaultLib('ansible') v.cipher_name = ""TEST"" sensitive_data = b""ansible"" data = v._format_output(sensitive_data) lines = data.split(b'\n') assert len(lines) > 1, ""failed to properly add header"" header = to_bytes(lines[0]) assert header.endswith(b';TEST'), ""header does end with cipher name"" header_parts = header.split(b';') assert len(header_parts) == 3, ""header has the wrong number of parts"" assert header_parts[0] == b'$ANSIBLE_VAULT', ""header does not start with $ANSIBLE_VAULT"" assert header_parts[1] == v.b_version, ""header version is incorrect"" assert header_parts[2] == b'TEST', ""header does end with cipher name""",CWE-703,ansible/ansible,89b0c3f6c41a50f6d2cdcefbd0f1cae0d031147c,"def test_format_output(self): v = VaultLib('ansible') v.cipher_name = ""TEST"" sensitive_data = ""ansible"" data = v._format_output(sensitive_data) lines = data.split(b'\n') assert len(lines) > 1, ""failed to properly add header"" header = to_unicode(lines[0]) assert header.endswith(';TEST'), ""header does end with cipher name"" header_parts = header.split(';') assert len(header_parts) == 3, ""header has the wrong number of parts"" assert header_parts[0] == '$ANSIBLE_VAULT', ""header does not start with $ANSIBLE_VAULT"" assert header_parts[1] == v.b_version, ""header version is incorrect"" assert header_parts[2] == 'TEST', ""header does end with cipher name""" functions_for_yaml_with_cwe.csv,UNKNOWN,UNKNOWN,lib3/yaml/composer.py,0,"def compose_node(self, parent, index): if self.check_event(AliasEvent): event = self.get_event() anchor = event.anchor if anchor not in self.anchors: raise ComposerError(None, None, ""found undefined alias %r"" % anchor, event.start_mark) return self.anchors[anchor] event = self.peek_event() anchor = event.anchor if anchor is not None: if anchor in self.anchors: raise ComposerError(""found duplicate anchor %r; first occurrence"" % anchor, self.anchors[anchor].start_mark, ""second occurrence"", event.start_mark) self.descend_resolver(parent, index) if self.check_event(ScalarEvent): node = self.compose_scalar_node(anchor) elif self.check_event(SequenceStartEvent): node = self.compose_sequence_node(anchor) elif self.check_event(MappingStartEvent): node = self.compose_mapping_node(anchor) self.ascend_resolver() return node",,yaml/pyyaml,d856c206fd4bfd71254e0d69e9d5e31bef5d2c0f,"def compose_node(self, parent, index): if self.check_event(AliasEvent): event = self.get_event() anchor = event.anchor if anchor not in self.anchors: raise ComposerError(None, None, ""found undefined alias %r"" % anchor, event.start_mark) return self.anchors[anchor] event = self.peek_event() anchor = event.anchor if anchor is not None: if anchor in self.anchors: raise ComposerError(""found duplicate anchor %r; first occurence"" % anchor, self.anchors[anchor].start_mark, ""second occurence"", event.start_mark) self.descend_resolver(parent, index) if self.check_event(ScalarEvent): node = self.compose_scalar_node(anchor) elif self.check_event(SequenceStartEvent): node = self.compose_sequence_node(anchor) elif self.check_event(MappingStartEvent): node = self.compose_mapping_node(anchor) self.ascend_resolver() return node" ,UNKNOWN,UNKNOWN,salt/utils/templates.py,1,"def render_tmpl(tmplsrc, from_str=False, to_str=False, context=None, tmplpath=None, **kws): if context is None: context = {} # Alias cmd.run to cmd.shell to make python_shell=True the default for # templated calls if 'salt' in kws: kws['salt'] = AliasedLoader(kws['salt']) # We want explicit context to overwrite the **kws kws.update(context) context = kws assert 'opts' in context assert 'saltenv' in context if 'sls' in context: slspath = context['sls'].replace('.', '/') if tmplpath is not None: context['tplpath'] = tmplpath if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'): slspath = os.path.dirname(slspath) template = tmplpath.replace('\\', '/') i = template.rfind(slspath.replace('.', '/')) if i != -1: template = template[i:] tpldir = os.path.dirname(template).replace('\\', '/') tpldata = { 'tplfile': template, 'tpldir': '.' if tpldir == '' else tpldir, 'tpldot': tpldir.replace('/', '.'), } context.update(tpldata) context['slsdotpath'] = slspath.replace('/', '.') context['slscolonpath'] = slspath.replace('/', ':') context['sls_path'] = slspath.replace('/', '_') context['slspath'] = slspath if isinstance(tmplsrc, six.string_types): if from_str: tmplstr = tmplsrc else: try: if tmplpath is not None: tmplsrc = os.path.join(tmplpath, tmplsrc) with codecs.open(tmplsrc, 'r', SLS_ENCODING) as _tmplsrc: tmplstr = _tmplsrc.read() except (UnicodeDecodeError, ValueError, OSError, IOError) as exc: if salt.utils.files.is_binary(tmplsrc): # Template is a bin file, return the raw file return dict(result=True, data=tmplsrc) log.error( 'Exception occurred while reading file %s: %s', tmplsrc, exc, exc_info_on_loglevel=logging.DEBUG ) raise exc else: # assume tmplsrc is file-like. tmplstr = tmplsrc.read() tmplsrc.close() try: output = render_str(tmplstr, context, tmplpath) if six.PY2: output = output.encode(SLS_ENCODING) if salt.utils.platform.is_windows(): newline = False if salt.utils.stringutils.to_unicode(output).endswith(('\n', os.linesep)): newline = True # Write out with Windows newlines output = os.linesep.join(output.splitlines()) if newline: output += os.linesep except SaltRenderError as exc: log.exception('Rendering exception occurred') #return dict(result=False, data=six.text_type(exc)) raise except Exception: return dict(result=False, data=traceback.format_exc()) else: if to_str: # then render as string return dict(result=True, data=output) with tempfile.NamedTemporaryFile('wb', delete=False, prefix=salt.utils.files.TEMPFILE_PREFIX) as outf: if six.PY3: output = output.encode(SLS_ENCODING) outf.write(output) # Note: If nothing is replaced or added by the rendering # function, then the contents of the output file will # be exactly the same as the input. return dict(result=True, data=outf.name)",CWE-703,saltstack/salt,07701f9868e03d57ad41c9ce8e04bef7499bd360,"def render_tmpl(tmplsrc, from_str=False, to_str=False, context=None, tmplpath=None, **kws): if context is None: context = {} # Alias cmd.run to cmd.shell to make python_shell=True the default for # templated calls if 'salt' in kws: kws['salt'] = AliasedLoader(kws['salt']) # We want explicit context to overwrite the **kws kws.update(context) context = kws assert 'opts' in context assert 'saltenv' in context if 'sls' in context: slspath = context['sls'].replace('.', '/') if tmplpath is not None: context['tplpath'] = tmplpath if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'): slspath = os.path.dirname(slspath) template = tmplpath.replace('\\', '/') i = template.rfind(slspath.replace('.', '/')) if i != -1: template = template[i:] tpldir = os.path.dirname(template).replace('\\', '/') tpldata = { 'tplfile': template, 'tpldir': '.' if tpldir == '' else tpldir, 'tpldot': tpldir.replace('/', '.'), } context.update(tpldata) context['slsdotpath'] = slspath.replace('/', '.') context['slscolonpath'] = slspath.replace('/', ':') context['sls_path'] = slspath.replace('/', '_') context['slspath'] = slspath if isinstance(tmplsrc, six.string_types): if from_str: tmplstr = tmplsrc else: try: if tmplpath is not None: tmplsrc = os.path.join(tmplpath, tmplsrc) with codecs.open(tmplsrc, 'r', SLS_ENCODING) as _tmplsrc: tmplstr = _tmplsrc.read() except (UnicodeDecodeError, ValueError, OSError, IOError) as exc: if salt.utils.files.is_binary(tmplsrc): # Template is a bin file, return the raw file return dict(result=True, data=tmplsrc) log.error( 'Exception occurred while reading file %s: %s', tmplsrc, exc, exc_info_on_loglevel=logging.DEBUG ) raise exc else: # assume tmplsrc is file-like. tmplstr = tmplsrc.read() tmplsrc.close() try: output = render_str(tmplstr, context, tmplpath) if six.PY2: output = output.encode(SLS_ENCODING) if salt.utils.platform.is_windows(): newline = False if output.endswith(('\n', os.linesep)): newline = True # Write out with Windows newlines output = os.linesep.join(output.splitlines()) if newline: output += os.linesep except SaltRenderError as exc: log.exception('Rendering exception occurred') #return dict(result=False, data=six.text_type(exc)) raise except Exception: return dict(result=False, data=traceback.format_exc()) else: if to_str: # then render as string return dict(result=True, data=output) with tempfile.NamedTemporaryFile('wb', delete=False, prefix=salt.utils.files.TEMPFILE_PREFIX) as outf: if six.PY3: output = output.encode(SLS_ENCODING) outf.write(output) # Note: If nothing is replaced or added by the rendering # function, then the contents of the output file will # be exactly the same as the input. return dict(result=True, data=outf.name)" functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/cli/batch.py,0,"def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if len(to_run) <= bnum and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: print_cli('\nExecuting run on {0}\n'.format(next_)) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(ping_ret.iterkeys()) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['id']: part}) minion_tracker[queue]['minions'].remove(part['id']) else: parts.update(part) for id in part.keys(): if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if self.opts.get('raw'): yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion)",,saltstack/salt,9ca5b02b0c37fe1a3b890173bf730f35480f75ae,"def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] if self.options: show_jid = self.options.show_jid else: show_jid = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if len(to_run) <= bnum and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: print_cli('\nExecuting run on {0}\n'.format(next_)) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(ping_ret.iterkeys()) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['id']: part}) minion_tracker[queue]['minions'].remove(part['id']) else: parts.update(part) for id in part.keys(): if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if self.opts.get('raw'): yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion)" functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,tests/test_functional.py,0,"def tearDown(self): pass",UNKNOWN,PyCQA/bandit,535ee589ad619226a3c105130773b74ac1285e7a,"def tearDown(self): pass" ,UNKNOWN,UNKNOWN,mlflow/recipes/steps/train.py,1,"def _run(self, output_directory): def my_warn(*args, **kwargs): timestamp = datetime.datetime.now().strftime(""%Y/%m/%d %H:%M:%S"") stacklevel = 1 if ""stacklevel"" not in kwargs else kwargs[""stacklevel""] frame = sys._getframe(stacklevel) filename = frame.f_code.co_filename lineno = frame.f_lineno message = f""{timestamp} {filename}:{lineno}: {args[0]}\n"" with open(os.path.join(output_directory, ""warning_logs.txt""), ""a"") as f: f.write(message) original_warn = warnings.warn warnings.warn = my_warn try: import numpy as np import pandas as pd import sklearn from sklearn.pipeline import make_pipeline from sklearn.utils.class_weight import compute_class_weight from mlflow.models import infer_signature with open(os.path.join(output_directory, ""warning_logs.txt""), ""w""): pass apply_recipe_tracking_config(self.tracking_config) transformed_training_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformed_training_data.parquet"", ) train_df = pd.read_parquet(transformed_training_data_path) validate_classification_config( self.task, self.positive_class, train_df, self.target_col ) self.using_rebalancing = False if self.extended_task == ""classification/binary"": classes = np.unique(train_df[self.target_col]) class_weights = compute_class_weight( class_weight=""balanced"", classes=classes, y=train_df[self.target_col], ) self.original_class_weights = dict(zip(classes, class_weights)) if self.rebalance_training_data and len(classes) == 2: if len(train_df) > _REBALANCING_CUTOFF: self.using_rebalancing = True train_df = self._rebalance_classes(train_df) else: _logger.info( f""Training data has less than {_REBALANCING_CUTOFF} rows, "" f""skipping rebalancing."" ) X_train, y_train = train_df.drop(columns=[self.target_col]), train_df[self.target_col] transformed_validation_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformed_validation_data.parquet"", ) validation_df = pd.read_parquet(transformed_validation_data_path) raw_training_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""split"", relative_path=""train.parquet"", ) raw_train_df = pd.read_parquet(raw_training_data_path) raw_X_train = raw_train_df.drop(columns=[self.target_col]) raw_validation_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""split"", relative_path=""validation.parquet"", ) raw_validation_df = pd.read_parquet(raw_validation_data_path) transformer_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformer.pkl"", ) tags = { MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.RECIPE), MLFLOW_RECIPE_TEMPLATE_NAME: self.step_config[""recipe""], MLFLOW_RECIPE_PROFILE_NAME: self.step_config[""profile""], MLFLOW_RECIPE_STEP_NAME: MLFLOW_RECIPES_EXECUTION_TARGET_STEP_NAME.get(), } run_name = self.tracking_config.run_name best_estimator_params = None mlflow.autolog(log_models=False, silent=True) with mlflow.start_run(run_name=run_name, tags=tags) as run: estimator = self._resolve_estimator( X_train, y_train, validation_df, run, output_directory ) best_estimator_params = estimator.get_params() fitted_estimator, additional_fitted_args = self._fitted_estimator( estimator, X_train, y_train ) logged_estimator = self._log_estimator_to_mlflow(fitted_estimator, X_train) # Create a recipe consisting of the transformer+model for test data evaluation with open(transformer_path, ""rb"") as f: transformer = cloudpickle.load(f) mlflow.sklearn.log_model( transformer, ""transform/transformer"", code_paths=self.code_paths ) trained_pipeline = make_pipeline(transformer, fitted_estimator) # Creating a wrapped recipe model which exposes a single predict function # so it can output both predict and predict_proba(for a classification problem) # at the same time. wrapped_model = WrappedRecipeModel( self.predict_scores_for_all_classes, self.predict_prefix, target_column_class_labels=additional_fitted_args.get( ""target_column_class_labels"" ), ) model_uri = get_step_output_path( recipe_root_path=self.recipe_root, step_name=self.name, relative_path=TrainStep.MODEL_ARTIFACT_RELATIVE_PATH, ) sklearn_model_uri = get_step_output_path( recipe_root_path=self.recipe_root, step_name=self.name, relative_path=TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ) if os.path.exists(model_uri): shutil.rmtree(model_uri) if os.path.exists(sklearn_model_uri): shutil.rmtree(sklearn_model_uri) # Saving the sklearn model as a separate output since `mlflow.evaluate()`, which is # used in evaluate step of the recipe, needs this model's sklearn representation # to computes metrics (the pyfunc representation of the user-facing model logged to # MLflow Tracking is not currently compatible with `mlflow.evaluate()`) mlflow.sklearn.save_model(trained_pipeline, sklearn_model_uri) artifacts = {""model_path"": sklearn_model_uri} with TempDir() as tmp: # Saving a temp model so that the output schema (signature) of the model's # pyfunc representation can be inferred and included when logging the model # to MLflow Tracking. Unfortunately, there is currently no easy way to infer # the model's signature without first saving a copy of it, and there is no easy # way to add an inferred signature to an existing model pyfunc_model_tmp_path = os.path.join(tmp.path(), ""pyfunc_model"") mlflow.pyfunc.save_model( path=pyfunc_model_tmp_path, python_model=wrapped_model, artifacts=artifacts, ) tempModel = mlflow.pyfunc.load_model(pyfunc_model_tmp_path) model_schema = infer_signature( raw_X_train, tempModel.predict(raw_X_train.copy()) ) mlflow.pyfunc.save_model( path=model_uri, python_model=wrapped_model, artifacts=artifacts, signature=model_schema, code_path=self.code_paths, ) model = mlflow.pyfunc.load_model(model_uri) # Adding a sklearn flavor to the pyfunc model so models could be loaded easily # using mlflow.sklearn.load_model tmp_model_info = Model.load(model_uri) model_data_subpath = os.path.join( ""artifacts"", TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ""model.pkl"" ) model_info = Model( artifact_path=""train/model"", run_id=run.info.run_id, utc_time_created=tmp_model_info.utc_time_created, flavors=tmp_model_info.flavors, signature=tmp_model_info.signature, # ModelSignature saved_input_example_info=tmp_model_info.saved_input_example_info, model_uuid=tmp_model_info.model_uuid, mlflow_version=tmp_model_info.mlflow_version, metadata=tmp_model_info.metadata, ) model_info.add_flavor( mlflow.sklearn.FLAVOR_NAME, pickled_model=model_data_subpath, sklearn_version=sklearn.__version__, serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE, code=""code"", ) model_info.save(f""{model_uri}/MLmodel"") mlflow.log_artifacts(model_uri, ""train/model"") with open(os.path.join(output_directory, ""run_id""), ""w"") as f: f.write(run.info.run_id) log_code_snapshot( self.recipe_root, run.info.run_id, recipe_config=self.recipe_config ) eval_metrics = {} for dataset_name, (dataset, metric_prefix) in { ""training"": (train_df, ""training_""), ""validation"": (validation_df, ""val_""), }.items(): eval_config = { ""log_model_explainability"": False, ""metric_prefix"": metric_prefix, } if self.positive_class is not None: eval_config[""pos_label""] = self.positive_class eval_result = mlflow.evaluate( model=logged_estimator.model_uri, data=dataset, targets=self.target_col, model_type=_get_model_type_from_template(self.recipe), evaluators=""default"", extra_metrics=_load_custom_metrics( self.recipe_root, self.evaluation_metrics.values(), ), evaluator_config=eval_config, ) eval_result.save(os.path.join(output_directory, f""eval_{dataset_name}"")) eval_metrics[dataset_name] = { strip_prefix(k, metric_prefix): v for k, v in eval_result.metrics.items() } target_data = raw_validation_df[self.target_col] prediction_result = model.predict(raw_validation_df.drop(self.target_col, axis=1)) use_probability_for_error_rate = False if isinstance(prediction_result, pd.DataFrame) and { f""{self.predict_prefix}label"", f""{self.predict_prefix}score"", }.issubset(prediction_result.columns): if self.positive_class: prediction_result_for_error = prediction_result[ f""{self.predict_prefix}score_{self.positive_class}"" ].values # use_probability_for_error_rate to true to compute error function # based on positive class use_probability_for_error_rate = True else: prediction_result_for_error = prediction_result[ f""{self.predict_prefix}score"" ].values prediction_result = prediction_result[f""{self.predict_prefix}label""].values else: prediction_result_for_error = prediction_result error_fn = _get_error_fn( self.recipe, use_probability=use_probability_for_error_rate, positive_class=self.positive_class, ) pred_and_error_df = pd.DataFrame( { ""target"": target_data, ""prediction"": prediction_result, ""error"": error_fn(prediction_result_for_error, target_data.to_numpy()), } ) calibrated_plot = None train_predictions = model.predict(raw_train_df.drop(self.target_col, axis=1)) if isinstance(train_predictions, pd.DataFrame) and { f""{self.predict_prefix}label"", f""{self.predict_prefix}score"", }.issubset(train_predictions.columns): predicted_training_data = raw_train_df.assign( predicted_data=train_predictions[f""{self.predict_prefix}label""], predicted_score=train_predictions[f""{self.predict_prefix}score""].values, ) if self.positive_class: worst_examples_df = BaseStep._generate_worst_examples_dataframe( raw_train_df, train_predictions[f""{self.predict_prefix}label""].values, error_fn( train_predictions[ f""{self.predict_prefix}score_{self.positive_class}"" ].values, raw_train_df[self.target_col].to_numpy(), ), self.target_col, ) if ""calibrate_proba"" in self.step_config and hasattr( additional_fitted_args.get(""original_estimator""), ""predict_proba"" ): from sklearn.calibration import CalibrationDisplay calibrated_plot = CalibrationDisplay.from_estimator( additional_fitted_args.get(""original_estimator""), raw_train_df.drop(self.target_col, axis=1), raw_train_df[self.target_col], pos_label=self.positive_class, ) else: # compute worst examples data_frame only if positive class exists worst_examples_df = pd.DataFrame() else: predicted_training_data = raw_train_df.assign(predicted_data=train_predictions) worst_examples_df = BaseStep._generate_worst_examples_dataframe( raw_train_df, train_predictions, error_fn(train_predictions, raw_train_df[self.target_col].to_numpy()), self.target_col, ) predicted_training_data.to_parquet( os.path.join(output_directory, TrainStep.PREDICTED_TRAINING_DATA_RELATIVE_PATH) ) leaderboard_df = None try: leaderboard_df = self._get_leaderboard_df(run, eval_metrics) except Exception as e: _logger.warning( ""Failed to build model leaderboard due to unexpected failure: %s"", e ) tuning_df = None if self.step_config[""tuning_enabled""]: try: tuning_df = self._get_tuning_df(run, params=best_estimator_params.keys()) except Exception as e: _logger.warning( ""Failed to build tuning results table due to unexpected failure: %s"", e ) card = self._build_step_card( eval_metrics=eval_metrics, pred_and_error_df=pred_and_error_df, model_schema=model_schema, run_id=run.info.run_id, model_uri=model_uri, worst_examples_df=worst_examples_df, train_df=raw_train_df, output_directory=output_directory, leaderboard_df=leaderboard_df, tuning_df=tuning_df, calibrated_plot=calibrated_plot, ) card.save_as_html(output_directory) for step_name in (""ingest"", ""split"", ""transform"", ""train""): self._log_step_card(run.info.run_id, step_name) return card finally: warnings.warn = original_warn",CWE-502,mlflow/mlflow,690465ad0143d76ae13e9795244ccb6005b431c4,"def _run(self, output_directory): def my_warn(*args, **kwargs): timestamp = datetime.datetime.now().strftime(""%Y/%m/%d %H:%M:%S"") stacklevel = 1 if ""stacklevel"" not in kwargs else kwargs[""stacklevel""] frame = sys._getframe(stacklevel) filename = frame.f_code.co_filename lineno = frame.f_lineno message = f""{timestamp} {filename}:{lineno}: {args[0]}\n"" with open(os.path.join(output_directory, ""warning_logs.txt""), ""a"") as f: f.write(message) original_warn = warnings.warn warnings.warn = my_warn try: import numpy as np import pandas as pd import sklearn from sklearn.pipeline import make_pipeline from sklearn.utils.class_weight import compute_class_weight from mlflow.models import infer_signature with open(os.path.join(output_directory, ""warning_logs.txt""), ""w""): pass apply_recipe_tracking_config(self.tracking_config) transformed_training_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformed_training_data.parquet"", ) train_df = pd.read_parquet(transformed_training_data_path) validate_classification_config( self.task, self.positive_class, train_df, self.target_col ) self.using_rebalancing = False if self.extended_task == ""classification/binary"": classes = np.unique(train_df[self.target_col]) class_weights = compute_class_weight( class_weight=""balanced"", classes=classes, y=train_df[self.target_col], ) self.original_class_weights = dict(zip(classes, class_weights)) if self.rebalance_training_data and len(classes) == 2: if len(train_df) > _REBALANCING_CUTOFF: self.using_rebalancing = True train_df = self._rebalance_classes(train_df) else: _logger.info( f""Training data has less than {_REBALANCING_CUTOFF} rows, "" f""skipping rebalancing."" ) X_train, y_train = train_df.drop(columns=[self.target_col]), train_df[self.target_col] transformed_validation_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformed_validation_data.parquet"", ) validation_df = pd.read_parquet(transformed_validation_data_path) raw_training_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""split"", relative_path=""train.parquet"", ) raw_train_df = pd.read_parquet(raw_training_data_path) raw_X_train = raw_train_df.drop(columns=[self.target_col]) raw_validation_data_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""split"", relative_path=""validation.parquet"", ) raw_validation_df = pd.read_parquet(raw_validation_data_path) transformer_path = get_step_output_path( recipe_root_path=self.recipe_root, step_name=""transform"", relative_path=""transformer.pkl"", ) tags = { MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.RECIPE), MLFLOW_RECIPE_TEMPLATE_NAME: self.step_config[""recipe""], MLFLOW_RECIPE_PROFILE_NAME: self.step_config[""profile""], MLFLOW_RECIPE_STEP_NAME: MLFLOW_RECIPES_EXECUTION_TARGET_STEP_NAME.get(), } run_name = self.tracking_config.run_name best_estimator_params = None mlflow.autolog(log_models=False, silent=True) with mlflow.start_run(run_name=run_name, tags=tags) as run: estimator = self._resolve_estimator( X_train, y_train, validation_df, run, output_directory ) fitted_estimator, additional_fitted_args = self._fitted_estimator( estimator, X_train, y_train ) logged_estimator = self._log_estimator_to_mlflow(fitted_estimator, X_train) # Create a recipe consisting of the transformer+model for test data evaluation with open(transformer_path, ""rb"") as f: transformer = cloudpickle.load(f) mlflow.sklearn.log_model( transformer, ""transform/transformer"", code_paths=self.code_paths ) trained_pipeline = make_pipeline(transformer, fitted_estimator) # Creating a wrapped recipe model which exposes a single predict function # so it can output both predict and predict_proba(for a classification problem) # at the same time. wrapped_model = WrappedRecipeModel( self.predict_scores_for_all_classes, self.predict_prefix, target_column_class_labels=additional_fitted_args.get( ""target_column_class_labels"" ), ) model_uri = get_step_output_path( recipe_root_path=self.recipe_root, step_name=self.name, relative_path=TrainStep.MODEL_ARTIFACT_RELATIVE_PATH, ) sklearn_model_uri = get_step_output_path( recipe_root_path=self.recipe_root, step_name=self.name, relative_path=TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ) if os.path.exists(model_uri): shutil.rmtree(model_uri) if os.path.exists(sklearn_model_uri): shutil.rmtree(sklearn_model_uri) # Saving the sklearn model as a separate output since `mlflow.evaluate()`, which is # used in evaluate step of the recipe, needs this model's sklearn representation # to computes metrics (the pyfunc representation of the user-facing model logged to # MLflow Tracking is not currently compatible with `mlflow.evaluate()`) mlflow.sklearn.save_model(trained_pipeline, sklearn_model_uri) artifacts = {""model_path"": sklearn_model_uri} with TempDir() as tmp: # Saving a temp model so that the output schema (signature) of the model's # pyfunc representation can be inferred and included when logging the model # to MLflow Tracking. Unfortunately, there is currently no easy way to infer # the model's signature without first saving a copy of it, and there is no easy # way to add an inferred signature to an existing model pyfunc_model_tmp_path = os.path.join(tmp.path(), ""pyfunc_model"") mlflow.pyfunc.save_model( path=pyfunc_model_tmp_path, python_model=wrapped_model, artifacts=artifacts, ) tempModel = mlflow.pyfunc.load_model(pyfunc_model_tmp_path) model_schema = infer_signature( raw_X_train, tempModel.predict(raw_X_train.copy()) ) mlflow.pyfunc.save_model( path=model_uri, python_model=wrapped_model, artifacts=artifacts, signature=model_schema, code_path=self.code_paths, ) model = mlflow.pyfunc.load_model(model_uri) # Adding a sklearn flavor to the pyfunc model so models could be loaded easily # using mlflow.sklearn.load_model tmp_model_info = Model.load(model_uri) model_data_subpath = os.path.join( ""artifacts"", TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ""model.pkl"" ) model_info = Model( artifact_path=""train/model"", run_id=run.info.run_id, utc_time_created=tmp_model_info.utc_time_created, flavors=tmp_model_info.flavors, signature=tmp_model_info.signature, # ModelSignature saved_input_example_info=tmp_model_info.saved_input_example_info, model_uuid=tmp_model_info.model_uuid, mlflow_version=tmp_model_info.mlflow_version, metadata=tmp_model_info.metadata, ) model_info.add_flavor( mlflow.sklearn.FLAVOR_NAME, pickled_model=model_data_subpath, sklearn_version=sklearn.__version__, serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE, code=""code"", ) model_info.save(f""{model_uri}/MLmodel"") mlflow.log_artifacts(model_uri, ""train/model"") with open(os.path.join(output_directory, ""run_id""), ""w"") as f: f.write(run.info.run_id) log_code_snapshot( self.recipe_root, run.info.run_id, recipe_config=self.recipe_config ) eval_metrics = {} for dataset_name, (dataset, metric_prefix) in { ""training"": (train_df, ""training_""), ""validation"": (validation_df, ""val_""), }.items(): eval_config = { ""log_model_explainability"": False, ""metric_prefix"": metric_prefix, } if self.positive_class is not None: eval_config[""pos_label""] = self.positive_class eval_result = mlflow.evaluate( model=logged_estimator.model_uri, data=dataset, targets=self.target_col, model_type=_get_model_type_from_template(self.recipe), evaluators=""default"", extra_metrics=_load_custom_metrics( self.recipe_root, self.evaluation_metrics.values(), ), evaluator_config=eval_config, ) eval_result.save(os.path.join(output_directory, f""eval_{dataset_name}"")) eval_metrics[dataset_name] = { strip_prefix(k, metric_prefix): v for k, v in eval_result.metrics.items() } target_data = raw_validation_df[self.target_col] prediction_result = model.predict(raw_validation_df.drop(self.target_col, axis=1)) use_probability_for_error_rate = False if isinstance(prediction_result, pd.DataFrame) and { f""{self.predict_prefix}label"", f""{self.predict_prefix}score"", }.issubset(prediction_result.columns): if self.positive_class: prediction_result_for_error = prediction_result[ f""{self.predict_prefix}score_{self.positive_class}"" ].values # use_probability_for_error_rate to true to compute error function # based on positive class use_probability_for_error_rate = True else: prediction_result_for_error = prediction_result[ f""{self.predict_prefix}score"" ].values prediction_result = prediction_result[f""{self.predict_prefix}label""].values else: prediction_result_for_error = prediction_result error_fn = _get_error_fn( self.recipe, use_probability=use_probability_for_error_rate, positive_class=self.positive_class, ) pred_and_error_df = pd.DataFrame( { ""target"": target_data, ""prediction"": prediction_result, ""error"": error_fn(prediction_result_for_error, target_data.to_numpy()), } ) calibrated_plot = None train_predictions = model.predict(raw_train_df.drop(self.target_col, axis=1)) if isinstance(train_predictions, pd.DataFrame) and { f""{self.predict_prefix}label"", f""{self.predict_prefix}score"", }.issubset(train_predictions.columns): predicted_training_data = raw_train_df.assign( predicted_data=train_predictions[f""{self.predict_prefix}label""], predicted_score=train_predictions[f""{self.predict_prefix}score""].values, ) if self.positive_class: worst_examples_df = BaseStep._generate_worst_examples_dataframe( raw_train_df, train_predictions[f""{self.predict_prefix}label""].values, error_fn( train_predictions[ f""{self.predict_prefix}score_{self.positive_class}"" ].values, raw_train_df[self.target_col].to_numpy(), ), self.target_col, ) if ""calibrate_proba"" in self.step_config and hasattr( additional_fitted_args.get(""original_estimator""), ""predict_proba"" ): from sklearn.calibration import CalibrationDisplay calibrated_plot = CalibrationDisplay.from_estimator( additional_fitted_args.get(""original_estimator""), raw_train_df.drop(self.target_col, axis=1), raw_train_df[self.target_col], pos_label=self.positive_class, ) else: # compute worst examples data_frame only if positive class exists worst_examples_df = pd.DataFrame() else: predicted_training_data = raw_train_df.assign(predicted_data=train_predictions) worst_examples_df = BaseStep._generate_worst_examples_dataframe( raw_train_df, train_predictions, error_fn(train_predictions, raw_train_df[self.target_col].to_numpy()), self.target_col, ) predicted_training_data.to_parquet( os.path.join(output_directory, TrainStep.PREDICTED_TRAINING_DATA_RELATIVE_PATH) ) leaderboard_df = None try: leaderboard_df = self._get_leaderboard_df(run, eval_metrics) except Exception as e: _logger.warning( ""Failed to build model leaderboard due to unexpected failure: %s"", e ) tuning_df = None if self.step_config[""tuning_enabled""]: try: tuning_df = self._get_tuning_df(run, params=best_estimator_params.keys()) except Exception as e: _logger.warning( ""Failed to build tuning results table due to unexpected failure: %s"", e ) card = self._build_step_card( eval_metrics=eval_metrics, pred_and_error_df=pred_and_error_df, model_schema=model_schema, run_id=run.info.run_id, model_uri=model_uri, worst_examples_df=worst_examples_df, train_df=raw_train_df, output_directory=output_directory, leaderboard_df=leaderboard_df, tuning_df=tuning_df, calibrated_plot=calibrated_plot, ) card.save_as_html(output_directory) for step_name in (""ingest"", ""split"", ""transform"", ""train""): self._log_step_card(run.info.run_id, step_name) return card finally: warnings.warn = original_warn" ,UNKNOWN,UNKNOWN,tests/pytests/unit/states/test_selinux.py,1,"def test_port_policy_present(): """""" Test to set up an SELinux port. """""" name = ""tcp/8080"" protocol = ""tcp"" port = ""8080"" ret = {""name"": name, ""changes"": {}, ""result"": False, ""comment"": """"} # Test when already present with same sel_type mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( return_value={ ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", } ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): comt = ( f'SELinux policy for ""{name}"" already present ' + 'with specified sel_type ""http_cache_port_t"", protocol ""None"" ' + 'and port ""None"".' ) ret.update({""comment"": comt, ""result"": True}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret comt = ( 'SELinux policy for ""name"" already present ' + f'with specified sel_type ""http_cache_port_t"", protocol ""{protocol}"" ' + f'and port ""{port}"".' ) ret.update({""comment"": comt, ""changes"": {}, ""result"": True, ""name"": ""name""}) assert ( selinux.port_policy_present(""name"", ""http_cache_port_t"", protocol, port) == ret ) ret.update({""name"": name}) # Test adding new port policy mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": True}): ret.update({""comment"": """", ""result"": None}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""comment"": """", ""changes"": { ""old"": None, ""new"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, }, ""result"": True, } ) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret # Test modifying policy to a new sel_type mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, {""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": True}): ret.update({""comment"": """", ""changes"": {}, ""result"": None}) assert selinux.port_policy_present(name, ""http_port_t"") == ret with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""comment"": """", ""changes"": { ""old"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, ""new"": { ""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, }, ""result"": True, } ) assert selinux.port_policy_present(name, ""http_port_t"") == ret # Test adding new port policy with custom name and using protocol and port parameters mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""name"": ""required_protocol_port"", ""comment"": """", ""changes"": { ""old"": None, ""new"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081"", }, }, ""result"": True, } ) assert ( selinux.port_policy_present( ""required_protocol_port"", ""http_cache_port_t"", protocol=""tcp"", port=""8081"", ) == ret ) # Test failure of adding new policy mock_add = MagicMock(return_value={""retcode"": 1}) mock_modify = MagicMock(return_value={""retcode"": 1}) mock_get = MagicMock(return_value=None) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): comt = ""Error adding new policy: {'retcode': 1}"" ret.update({""name"": name, ""comment"": comt, ""changes"": {}, ""result"": False}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret",CWE-703,saltstack/salt,628c0d271349b173b4af7c8bd9b88890c033a2ed,"def test_port_policy_present(): """""" Test to set up an SELinux port. """""" name = ""tcp/8080"" protocol = ""tcp"" port = ""8080"" ret = {""name"": name, ""changes"": {}, ""result"": False, ""comment"": """"} # Test when already present with same sel_type mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( return_value={ ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", } ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): comt = ( f'SELinux policy for ""{name}"" already present ' + f'with specified sel_type ""http_cache_port_t"", protocol ""None"" ' + f'and port ""None"".' ) ret.update({""comment"": comt, ""result"": True}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret comt = ( f'SELinux policy for ""name"" already present ' + f'with specified sel_type ""http_cache_port_t"", protocol ""{protocol}"" ' + f'and port ""{port}"".' ) ret.update({""comment"": comt, ""changes"": {}, ""result"": True, ""name"": ""name""}) assert ( selinux.port_policy_present(""name"", ""http_cache_port_t"", protocol, port) == ret ) ret.update({""name"": name}) # Test adding new port policy mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": True}): ret.update({""comment"": """", ""result"": None}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""comment"": """", ""changes"": { ""old"": None, ""new"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, }, ""result"": True, } ) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret # Test modifying policy to a new sel_type mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, {""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": True}): ret.update({""comment"": """", ""changes"": {}, ""result"": None}) assert selinux.port_policy_present(name, ""http_port_t"") == ret with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""comment"": """", ""changes"": { ""old"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, ""new"": { ""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080"", }, }, ""result"": True, } ) assert selinux.port_policy_present(name, ""http_port_t"") == ret # Test adding new port policy with custom name and using protocol and port parameters mock_add = MagicMock(return_value={""retcode"": 0}) mock_modify = MagicMock(return_value={""retcode"": 0}) mock_get = MagicMock( side_effect=[ None, None, {""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081""}, ] ) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): ret.update( { ""name"": ""required_protocol_port"", ""comment"": """", ""changes"": { ""old"": None, ""new"": { ""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081"", }, }, ""result"": True, } ) assert ( selinux.port_policy_present( ""required_protocol_port"", ""http_cache_port_t"", protocol=""tcp"", port=""8081"", ) == ret ) # Test failure of adding new policy mock_add = MagicMock(return_value={""retcode"": 1}) mock_modify = MagicMock(return_value={""retcode"": 1}) mock_get = MagicMock(return_value=None) with patch.dict( selinux.__salt__, { ""selinux.port_get_policy"": mock_get, ""selinux.port_add_policy"": mock_add, ""selinux.port_modify_policy"": mock_modify, }, ): with patch.dict(selinux.__opts__, {""test"": False}): comt = ""Error adding new policy: {'retcode': 1}"" ret.update({""name"": name, ""comment"": comt, ""changes"": {}, ""result"": False}) assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret" functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,task-sdk/src/airflow/sdk/log.py,0,"def load_remote_log_handler() -> RemoteLogIO | None: import airflow.logging_config return airflow.logging_config.REMOTE_TASK_LOG",CWE-Unknown,apache/airflow,e4fb6862c6b16f790fed1baa4af8882125c984c9,"def load_remote_log_handler() -> RemoteLogIO | None: import airflow.logging_config return airflow.logging_config.REMOTE_TASK_LOG" ,UNKNOWN,UNKNOWN,task-sdk/tests/task_sdk/api/test_client.py,1,"def test_get_count_with_all_params(self): """"""Test get_count with all optional parameters."""""" logical_dates_str = [""2024-01-01T00:00:00+00:00"", ""2024-01-02T00:00:00+00:00""] logical_dates = [timezone.parse(d) for d in logical_dates_str] task_ids = [""task1"", ""task2""] states = [""success"", ""failed""] def handle_request(request: httpx.Request) -> httpx.Response: assert request.url.path == ""/task-instances/count"" assert request.method == ""GET"" params = request.url.params assert params[""dag_id""] == ""test_dag"" assert params.get_list(""task_ids"") == task_ids assert params[""task_group_id""] == ""group1"" assert params.get_list(""logical_dates"") == logical_dates_str assert params.get_list(""run_ids"") == [] assert params.get_list(""states"") == states return httpx.Response(200, json=10) client = make_client(transport=httpx.MockTransport(handle_request)) result = client.task_instances.get_count( dag_id=""test_dag"", task_ids=task_ids, task_group_id=""group1"", logical_dates=logical_dates, states=states, ) assert result.count == 10",CWE-703,apache/airflow,ef80791fbae6a48059cf2870b7e175a61cf7c361,"def test_get_count_with_all_params(self): """"""Test get_count with all optional parameters."""""" logical_dates_str = [""2024-01-01T00:00:00+00:00"", ""2024-01-02T00:00:00+00:00""] logical_dates = [timezone.parse(d) for d in logical_dates_str] task_ids = [""task1"", ""task2""] states = [""success"", ""failed""] def handle_request(request: httpx.Request) -> httpx.Response: assert request.url.path == ""/task-instances/count"" assert request.method == ""GET"" params = request.url.params assert params[""dag_id""] == ""test_dag"" assert params.get_list(""task_ids"") == task_ids assert params[""task_group_id""] == ""group1"" assert params.get_list(""logical_dates"") == logical_dates_str assert params.get_list(""run_ids"") == [] assert params.get_list(""states"") == states return httpx.Response(200, json=10) client = make_client(transport=httpx.MockTransport(handle_request)) result = client.task_instances.get_count( dag_id=""test_dag"", task_ids=task_ids, task_group_id=""group1"", logical_dates=logical_dates, states=states, ) assert result.count == 10" ,UNKNOWN,UNKNOWN,tests/operators/test_trigger_dagrun.py,1,"def test_trigger_dagrun(self, dag_maker): """"""Test TriggerDagRunOperator."""""" with time_machine.travel(""2025-02-18T08:04:46Z"", tick=False): with dag_maker( TEST_DAG_ID, default_args={""owner"": ""airflow"", ""start_date"": DEFAULT_DATE}, serialized=True ): task = TriggerDagRunOperator(task_id=""test_task"", trigger_dag_id=TRIGGERED_DAG_ID) dag_maker.sync_dagbag_to_db() parse_and_sync_to_db(self.f_name) dag_maker.create_dagrun() task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) dagrun = dag_maker.session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).one() assert dagrun.run_type == DagRunType.MANUAL actual_run_id = dagrun.run_id.rsplit(""_"", 1)[0] expected_run_id = DagRun.generate_run_id( run_type=DagRunType.MANUAL, run_after=timezone.utcnow() ).rsplit(""_"", 1)[0] assert actual_run_id == expected_run_id self.assert_extra_link(dagrun, task, dag_maker.session)",CWE-703,apache/airflow,811fa2b016ca613061e5d4d32fee005e53c1bf1d,"def test_trigger_dagrun(self, dag_maker): """"""Test TriggerDagRunOperator."""""" with time_machine.travel(""2025-02-18T08:04:46Z"", tick=False): with dag_maker( TEST_DAG_ID, default_args={""owner"": ""airflow"", ""start_date"": DEFAULT_DATE}, serialized=True ): task = TriggerDagRunOperator(task_id=""test_task"", trigger_dag_id=TRIGGERED_DAG_ID) dag_maker.sync_dagbag_to_db() parse_and_sync_to_db(self.f_name) dag_maker.create_dagrun() task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) dagrun = dag_maker.session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).one() assert dagrun.external_trigger actual_run_id = dagrun.run_id.rsplit(""_"", 1)[0] expected_run_id = DagRun.generate_run_id( run_type=DagRunType.MANUAL, run_after=timezone.utcnow() ).rsplit(""_"", 1)[0] assert actual_run_id == expected_run_id self.assert_extra_link(dagrun, task, dag_maker.session)" functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,setupbase.py,0,"def find_package_data(): """""" Find IPython's package_data. """""" # This is not enough for these things to appear in an sdist. # We need to muck with the MANIFEST to get this to work # exclude components and less from the walk; # we will build the components separately excludes = [ pjoin('static', 'components'), pjoin('static', '*', 'less'), ] # walk notebook resources: cwd = os.getcwd() os.chdir(os.path.join('IPython', 'html')) static_data = [] for parent, dirs, files in os.walk('static'): if any(fnmatch(parent, pat) for pat in excludes): # prevent descending into subdirs dirs[:] = [] continue for f in files: static_data.append(pjoin(parent, f)) components = pjoin(""static"", ""components"") # select the components we actually need to install # (there are lots of resources we bundle for sdist-reasons that we don't actually use) static_data.extend([ pjoin(components, ""backbone"", ""backbone-min.js""), pjoin(components, ""bootstrap"", ""js"", ""bootstrap.min.js""), pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""), pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""), pjoin(components, ""font-awesome"", ""font"", ""*.*""), pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""), pjoin(components, ""highlight.js"", ""build"", ""highlight.pack.js""), pjoin(components, ""jquery"", ""jquery.min.js""), pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""), pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""), pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""), pjoin(components, ""marked"", ""lib"", ""marked.js""), pjoin(components, ""requirejs"", ""require.js""), pjoin(components, ""underscore"", ""underscore-min.js""), ]) # Ship all of Codemirror's CSS and JS for parent, dirs, files in os.walk(pjoin(components, 'codemirror')): for f in files: if f.endswith(('.js', '.css')): static_data.append(pjoin(parent, f)) os.chdir(os.path.join('tests',)) js_tests = glob('*.js') + glob('*/*.js') os.chdir(os.path.join(cwd, 'IPython', 'nbconvert')) nbconvert_templates = [os.path.join(dirpath, '*.*') for dirpath, _, _ in os.walk('templates')] os.chdir(cwd) package_data = { 'IPython.config.profile' : ['README*', '*/*.py'], 'IPython.core.tests' : ['*.png', '*.jpg'], 'IPython.lib.tests' : ['*.wav'], 'IPython.testing.plugin' : ['*.txt'], 'IPython.html' : ['templates/*'] + static_data, 'IPython.html.tests' : js_tests, 'IPython.qt.console' : ['resources/icon/*.svg'], 'IPython.nbconvert' : nbconvert_templates + ['tests/files/*.*', 'exporters/tests/files/*.*'], 'IPython.nbconvert.filters' : ['marked.js'], 'IPython.nbformat' : ['tests/*.ipynb','v3/v3.withref.json'] } return package_data",,jupyter/notebook,556257a66b5e4b311e9202408a8157ae71b685f3,"def find_package_data(): """""" Find IPython's package_data. """""" # This is not enough for these things to appear in an sdist. # We need to muck with the MANIFEST to get this to work # exclude components and less from the walk; # we will build the components separately excludes = [ pjoin('static', 'components'), pjoin('static', '*', 'less'), ] # walk notebook resources: cwd = os.getcwd() os.chdir(os.path.join('IPython', 'html')) static_data = [] for parent, dirs, files in os.walk('static'): if any(fnmatch(parent, pat) for pat in excludes): # prevent descending into subdirs dirs[:] = [] continue for f in files: static_data.append(pjoin(parent, f)) components = pjoin(""static"", ""components"") # select the components we actually need to install # (there are lots of resources we bundle for sdist-reasons that we don't actually use) static_data.extend([ pjoin(components, ""backbone"", ""backbone-min.js""), pjoin(components, ""bootstrap"", ""bootstrap"", ""js"", ""bootstrap.min.js""), pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""), pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""), pjoin(components, ""font-awesome"", ""font"", ""*.*""), pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""), pjoin(components, ""highlight.js"", ""build"", ""highlight.pack.js""), pjoin(components, ""jquery"", ""jquery.min.js""), pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""), pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""), pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""), pjoin(components, ""marked"", ""lib"", ""marked.js""), pjoin(components, ""requirejs"", ""require.js""), pjoin(components, ""underscore"", ""underscore-min.js""), ]) # Ship all of Codemirror's CSS and JS for parent, dirs, files in os.walk(pjoin(components, 'codemirror')): for f in files: if f.endswith(('.js', '.css')): static_data.append(pjoin(parent, f)) os.chdir(os.path.join('tests',)) js_tests = glob('*.js') + glob('*/*.js') os.chdir(os.path.join(cwd, 'IPython', 'nbconvert')) nbconvert_templates = [os.path.join(dirpath, '*.*') for dirpath, _, _ in os.walk('templates')] os.chdir(cwd) package_data = { 'IPython.config.profile' : ['README*', '*/*.py'], 'IPython.core.tests' : ['*.png', '*.jpg'], 'IPython.lib.tests' : ['*.wav'], 'IPython.testing.plugin' : ['*.txt'], 'IPython.html' : ['templates/*'] + static_data, 'IPython.html.tests' : js_tests, 'IPython.qt.console' : ['resources/icon/*.svg'], 'IPython.nbconvert' : nbconvert_templates + ['tests/files/*.*', 'exporters/tests/files/*.*'], 'IPython.nbconvert.filters' : ['marked.js'], 'IPython.nbformat' : ['tests/*.ipynb','v3/v3.withref.json'] } return package_data" ,UNKNOWN,UNKNOWN,tests/www/views/test_views_tasks.py,1,"def test_task_instances(admin_client): """"""Test task_instances view."""""" resp = admin_client.get( f""/object/task_instances?dag_id=example_bash_operator&execution_date={STR_DEFAULT_DATE}"", follow_redirects=True, ) assert resp.status_code == 200 assert resp.json == { ""also_run_this"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""also_run_this"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""run_after_loop"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""run_after_loop"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""run_this_last"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""EmptyOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 1, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""run_this_last"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_0"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_0"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_1"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_1"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_2"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_2"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""this_will_skip"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""priority_weight_strategy"": ""downstream"", ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""this_will_skip"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, }",CWE-703,apache/airflow,9be2ffc30411693d069074c6a51a243d1e61fdc0,"def test_task_instances(admin_client): """"""Test task_instances view."""""" resp = admin_client.get( f""/object/task_instances?dag_id=example_bash_operator&execution_date={STR_DEFAULT_DATE}"", follow_redirects=True, ) assert resp.status_code == 200 assert resp.json == { ""also_run_this"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""also_run_this"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""run_after_loop"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""run_after_loop"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""run_this_last"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""EmptyOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 1, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""run_this_last"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_0"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_0"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_1"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_1"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""runme_2"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 3, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""runme_2"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, ""this_will_skip"": { ""custom_operator_name"": None, ""dag_id"": ""example_bash_operator"", ""duration"": None, ""end_date"": None, ""execution_date"": DEFAULT_DATE.isoformat(), ""executor_config"": {}, ""external_executor_id"": None, ""hostname"": """", ""job_id"": None, ""map_index"": -1, ""max_tries"": 0, ""next_kwargs"": None, ""next_method"": None, ""operator"": ""BashOperator"", ""pid"": None, ""pool"": ""default_pool"", ""pool_slots"": 1, ""priority_weight"": 2, ""queue"": ""default"", ""queued_by_job_id"": None, ""queued_dttm"": None, ""run_id"": ""TEST_DAGRUN"", ""start_date"": None, ""state"": None, ""task_id"": ""this_will_skip"", ""trigger_id"": None, ""trigger_timeout"": None, ""try_number"": 1, ""unixname"": getuser(), ""updated_at"": DEFAULT_DATE.isoformat(), }, }" functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/mdadm.py,0,"def create(name, level, devices, metadata='default', test_mode=False, **kwargs): ''' Create a RAID device. .. versionchanged:: 2014.7.0 .. warning:: Use with CAUTION, as this function can be very destructive if not used properly! CLI Examples: .. code-block:: bash salt '*' raid.create /dev/md0 level=1 chunk=256 devices=""['/dev/xvdd', '/dev/xvde']"" test_mode=True .. note:: Adding ``test_mode=True`` as an argument will print out the mdadm command that would have been run. name The name of the array to create. level The RAID level to use when creating the raid. devices A list of devices used to build the array. kwargs Optional arguments to be passed to mdadm. returns test_mode=True: Prints out the full command. test_mode=False (Default): Executes command on remote the host(s) and Prints out the mdadm output. .. note:: It takes time to create a RAID array. You can check the progress in ""resync_status:"" field of the results from the following command: .. code-block:: bash salt '*' raid.detail /dev/md0 For more info, read the ``mdadm(8)`` manpage ''' opts = [] for key in kwargs: if not key.startswith('__'): opts.append('--{0}'.format(key)) if kwargs[key] is not True: opts.append(str(kwargs[key])) cmd = ['mdadm', '-C', name, '-R', '-v'] + opts + [ '-l', str(level), '-e', metadata, '-n', str(len(devices))] + devices cmd_str = ' '.join(cmd) if test_mode is True: return cmd_str elif test_mode is False: return __salt__['cmd.run'](cmd, python_shell=False)",,saltstack/salt,d744fc631182eda270b55c3f0de6d55a8023a316,"def create(name, level, devices, metadata='default', test_mode=False, **kwargs): ''' Create a RAID device. .. versionchanged:: 2014.7.0 .. warning:: Use with CAUTION, as this function can be very destructive if not used properly! CLI Examples: .. code-block:: bash salt '*' raid.create /dev/md0 level=1 chunk=256 devices=""['/dev/xvdd', '/dev/xvde']"" test_mode=True .. note:: Adding ``test_mode=True`` as an argument will print out the mdadm command that would have been run. name The name of the array to create. level The RAID level to use when creating the raid. devices A list of devices used to build the array. kwargs Optional arguments to be passed to mdadm. returns test_mode=True: Prints out the full command. test_mode=False (Default): Executes command on remote the host(s) and Prints out the mdadm output. .. note:: It takes time to create a RAID array. You can check the progress in ""resync_status:"" field of the results from the following command: .. code-block:: bash salt '*' raid.detail /dev/md0 For more info, read the ``mdadm(8)`` manpage ''' opts = [] for key in kwargs: if not key.startswith('__'): opts.append('--{0}'.format(key)) if kwargs[key] is not True: opts.append(str(kwargs[key])) cmd = ['mdadm', '-C', name, '-v'] + opts + [ '-l', str(level), '-e', metadata, '-n', str(len(devices))] + devices cmd = ' '.join(cmd) if test_mode is True: return cmd elif test_mode is False: return __salt__['cmd.run'](cmd, python_shell=False)" ,UNKNOWN,UNKNOWN,providers/sftp/tests/unit/sftp/hooks/test_sftp.py,1,"def test_close_conn(self): self.hook.conn = self.hook.get_conn() assert self.hook.conn is not None self.hook.close_conn() assert self.hook.conn is None",CWE-703,apache/airflow,998fcd6cfbc35b671a07b92d6f6fc532a00bd8dd,"def test_close_conn(self): self.hook.conn = self.hook.get_conn() assert self.hook.conn is not None self.hook.close_conn() assert self.hook.conn is None" functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/views/i18n.py,0,"def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get('domain', self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get('packages', '') packages = packages.split('+') if packages else self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context)",CWE-Unknown,django/django,6b5106b1ceec03d945c1104b21feed3e25470fe0,"def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get('domain', self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get('packages', '').split('+') or self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context)" ,UNKNOWN,UNKNOWN,tests/www/views/test_views_grid.py,1,"def test_no_runs(admin_client, dag_without_runs): resp = admin_client.get(f'/object/grid_data?dag_id={DAG_ID}', follow_redirects=True) assert resp.status_code == 200, resp.json assert resp.json == { 'dag_runs': [], 'groups': { 'children': [ { 'extra_links': [], 'id': 'task1', 'instances': [], 'is_mapped': False, 'label': 'task1', }, { 'children': [ { 'extra_links': [], 'id': 'group.mapped', 'instances': [], 'is_mapped': True, 'label': 'mapped', } ], 'id': 'group', 'instances': [], 'label': 'group', 'tooltip': '', }, ], 'id': None, 'instances': [], 'label': None, }, }",CWE-703,apache/airflow,c5774e65e3ca57bae0d594f64440f4ebc0a43b63,"def test_no_runs(admin_client, dag_without_runs): resp = admin_client.get(f'/object/grid_data?dag_id={DAG_ID}', follow_redirects=True) assert resp.status_code == 200, resp.json assert resp.json == { 'dag_runs': [], 'groups': { 'children': [ { 'extra_links': [], 'id': 'task1', 'instances': [], 'is_mapped': False, 'label': 'task1', }, { 'children': [ { 'extra_links': [], 'id': 'group.mapped', 'instances': [], 'is_mapped': True, 'label': 'mapped', } ], 'id': 'group', 'instances': [], 'label': 'group', 'tooltip': '', }, ], 'id': None, 'instances': [], 'label': None, 'tooltip': '', }, }" ,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/__init__.py,1,"def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False, ignore_unknown_opts: bool = False): ''' Transfer and run a module along with its arguments. ''' if tmp is not None: display.warning('_execute_module no longer honors the tmp parameter. Action plugins' ' should set self._connection._shell.tmpdir to share the tmpdir') del tmp # No longer used if delete_remote_tmp is not None: display.warning('_execute_module no longer honors the delete_remote_tmp parameter.' ' Action plugins should check self._connection._shell.tmpdir to' ' see if a tmpdir existed before they were called to determine' ' if they are responsible for removing it.') del delete_remote_tmp # No longer used tmpdir = self._connection._shell.tmpdir # We set the module_style to new here so the remote_tmp is created # before the module args are built if remote_tmp is needed (async). # If the module_style turns out to not be new and we didn't create the # remote tmp here, it will still be created. This must be done before # calling self._update_module_args() so the module wrapper has the # correct remote_tmp value set if not self._is_pipelining_enabled(""new"", wrap_async) and tmpdir is None: self._make_tmp_path() tmpdir = self._connection._shell.tmpdir if task_vars is None: task_vars = dict() # if a module name was not specified for this execution, use the action from the task if module_name is None: module_name = self._task.action if module_args is None: module_args = self._task.args self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts) remove_async_dir = None if wrap_async or self._task.async_val: async_dir = self.get_shell_option('async_dir', default=""~/.ansible_async"") remove_async_dir = len(self._task.environment) self._task.environment.append({""ANSIBLE_ASYNC_DIR"": async_dir}) # FUTURE: refactor this along with module build process to better encapsulate ""smart wrapper"" functionality (module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars) display.vvv(""Using module file %s"" % module_path) if not shebang and module_style != 'binary': raise AnsibleError(""module (%s) is missing interpreter line"" % module_name) self._used_interpreter = shebang remote_module_path = None if not self._is_pipelining_enabled(module_style, wrap_async): # we might need remote tmp dir if tmpdir is None: self._make_tmp_path() tmpdir = self._connection._shell.tmpdir remote_module_filename = self._connection._shell.get_remote_filename(module_path) remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename) args_file_path = None if module_style in ('old', 'non_native_want_json', 'binary'): # we'll also need a tmp file to hold our module arguments args_file_path = self._connection._shell.join_path(tmpdir, 'args') if remote_module_path or module_style != 'new': display.debug(""transferring module to remote %s"" % remote_module_path) if module_style == 'binary': self._transfer_file(module_path, remote_module_path) else: self._transfer_data(remote_module_path, module_data) if module_style == 'old': # we need to dump the module args to a k=v string in a file on # the remote system, which can be read and parsed by the module args_data = """" for k, v in module_args.items(): args_data += '%s=%s ' % (k, shlex.quote(text_type(v))) self._transfer_data(args_file_path, args_data) elif module_style in ('non_native_want_json', 'binary'): self._transfer_data(args_file_path, json.dumps(module_args)) display.debug(""done transferring module to remote"") environment_string = self._compute_environment_string() # remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for # the async_wrapper task. if remove_async_dir is not None: del self._task.environment[remove_async_dir] remote_files = [] if tmpdir and remote_module_path: remote_files = [tmpdir, remote_module_path] if args_file_path: remote_files.append(args_file_path) sudoable = True in_data = None cmd = """" if wrap_async and not self._connection.always_pipeline_modules: # configure, upload, and chmod the async_wrapper module (async_module_style, shebang, async_module_data, async_module_path) = self._configure_module( module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars) async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path) remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename) self._transfer_data(remote_async_module_path, async_module_data) remote_files.append(remote_async_module_path) async_limit = self._task.async_val async_jid = f'j{random.randint(0, 999999999999)}' # call the interpreter for async_wrapper directly # this permits use of a script for an interpreter on non-Linux platforms interpreter = shebang.replace('#!', '').strip() async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path] if environment_string: async_cmd.insert(0, environment_string) if args_file_path: async_cmd.append(args_file_path) else: # maintain a fixed number of positional parameters for async_wrapper async_cmd.append('_') if not self._should_remove_tmp_path(tmpdir): async_cmd.append(""-preserve_tmp"") cmd = "" "".join(to_text(x) for x in async_cmd) else: if self._is_pipelining_enabled(module_style): in_data = module_data display.vvv(""Pipelining is enabled."") else: cmd = remote_module_path cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip() # Fix permissions of the tmpdir path and tmpdir files. This should be called after all # files have been transferred. if remote_files: # remove none/empty remote_files = [x for x in remote_files if x] self._fixup_perms2(remote_files, self._get_remote_user()) # actually execute res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data) # parse the main result data = self._parse_returned_data(res) # NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE # get internal info before cleaning if data.pop(""_ansible_suppress_tmpdir_delete"", False): self._cleanup_remote_tmp = False # NOTE: dnf returns results .. but that made it 'compatible' with squashing, so we allow mappings, for now if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)): data['ansible_module_results'] = data['results'] del data['results'] display.warning(""Found internal 'results' key in module return, renamed to 'ansible_module_results'."") # remove internal keys remove_internal_keys(data) if wrap_async: # async_wrapper will clean up its tmpdir on its own so we want the controller side to # forget about it now self._connection._shell.tmpdir = None # FIXME: for backwards compat, figure out if still makes sense data['changed'] = True # pre-split stdout/stderr into lines if needed if 'stdout' in data and 'stdout_lines' not in data: # if the value is 'False', a default won't catch it. txt = data.get('stdout', None) or u'' data['stdout_lines'] = txt.splitlines() if 'stderr' in data and 'stderr_lines' not in data: # if the value is 'False', a default won't catch it. txt = data.get('stderr', None) or u'' data['stderr_lines'] = txt.splitlines() # propagate interpreter discovery results back to the controller if self._discovered_interpreter_key: if data.get('ansible_facts') is None: data['ansible_facts'] = {} data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter if self._discovery_warnings: if data.get('warnings') is None: data['warnings'] = [] data['warnings'].extend(self._discovery_warnings) if self._discovery_deprecation_warnings: if data.get('deprecations') is None: data['deprecations'] = [] data['deprecations'].extend(self._discovery_deprecation_warnings) # mark the entire module results untrusted as a template right here, since the current action could # possibly template one of these values. data = wrap_var(data) display.debug(""done with _execute_module (%s, %s)"" % (module_name, module_args)) return data",CWE-330,ansible/ansible,f024cf35d704369454a483495efa24ad95666cb6,"def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False, ignore_unknown_opts: bool = False): ''' Transfer and run a module along with its arguments. ''' if tmp is not None: display.warning('_execute_module no longer honors the tmp parameter. Action plugins' ' should set self._connection._shell.tmpdir to share the tmpdir') del tmp # No longer used if delete_remote_tmp is not None: display.warning('_execute_module no longer honors the delete_remote_tmp parameter.' ' Action plugins should check self._connection._shell.tmpdir to' ' see if a tmpdir existed before they were called to determine' ' if they are responsible for removing it.') del delete_remote_tmp # No longer used tmpdir = self._connection._shell.tmpdir # We set the module_style to new here so the remote_tmp is created # before the module args are built if remote_tmp is needed (async). # If the module_style turns out to not be new and we didn't create the # remote tmp here, it will still be created. This must be done before # calling self._update_module_args() so the module wrapper has the # correct remote_tmp value set if not self._is_pipelining_enabled(""new"", wrap_async) and tmpdir is None: self._make_tmp_path() tmpdir = self._connection._shell.tmpdir if task_vars is None: task_vars = dict() # if a module name was not specified for this execution, use the action from the task if module_name is None: module_name = self._task.action if module_args is None: module_args = self._task.args self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts) remove_async_dir = None if wrap_async or self._task.async_val: async_dir = self.get_shell_option('async_dir', default=""~/.ansible_async"") remove_async_dir = len(self._task.environment) self._task.environment.append({""ANSIBLE_ASYNC_DIR"": async_dir}) # FUTURE: refactor this along with module build process to better encapsulate ""smart wrapper"" functionality (module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars) display.vvv(""Using module file %s"" % module_path) if not shebang and module_style != 'binary': raise AnsibleError(""module (%s) is missing interpreter line"" % module_name) self._used_interpreter = shebang remote_module_path = None if not self._is_pipelining_enabled(module_style, wrap_async): # we might need remote tmp dir if tmpdir is None: self._make_tmp_path() tmpdir = self._connection._shell.tmpdir remote_module_filename = self._connection._shell.get_remote_filename(module_path) remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename) args_file_path = None if module_style in ('old', 'non_native_want_json', 'binary'): # we'll also need a tmp file to hold our module arguments args_file_path = self._connection._shell.join_path(tmpdir, 'args') if remote_module_path or module_style != 'new': display.debug(""transferring module to remote %s"" % remote_module_path) if module_style == 'binary': self._transfer_file(module_path, remote_module_path) else: self._transfer_data(remote_module_path, module_data) if module_style == 'old': # we need to dump the module args to a k=v string in a file on # the remote system, which can be read and parsed by the module args_data = """" for k, v in module_args.items(): args_data += '%s=%s ' % (k, shlex.quote(text_type(v))) self._transfer_data(args_file_path, args_data) elif module_style in ('non_native_want_json', 'binary'): self._transfer_data(args_file_path, json.dumps(module_args)) display.debug(""done transferring module to remote"") environment_string = self._compute_environment_string() # remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for # the async_wrapper task. if remove_async_dir is not None: del self._task.environment[remove_async_dir] remote_files = [] if tmpdir and remote_module_path: remote_files = [tmpdir, remote_module_path] if args_file_path: remote_files.append(args_file_path) sudoable = True in_data = None cmd = """" if wrap_async and not self._connection.always_pipeline_modules: # configure, upload, and chmod the async_wrapper module (async_module_style, shebang, async_module_data, async_module_path) = self._configure_module( module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars) async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path) remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename) self._transfer_data(remote_async_module_path, async_module_data) remote_files.append(remote_async_module_path) async_limit = self._task.async_val async_jid = f'j{random.randint(0, 999999999999)}' # call the interpreter for async_wrapper directly # this permits use of a script for an interpreter on non-Linux platforms interpreter = shebang.replace('#!', '').strip() async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path] if environment_string: async_cmd.insert(0, environment_string) if args_file_path: async_cmd.append(args_file_path) else: # maintain a fixed number of positional parameters for async_wrapper async_cmd.append('_') if not self._should_remove_tmp_path(tmpdir): async_cmd.append(""-preserve_tmp"") cmd = "" "".join(to_text(x) for x in async_cmd) else: if self._is_pipelining_enabled(module_style): in_data = module_data display.vvv(""Pipelining is enabled."") else: cmd = remote_module_path cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip() # Fix permissions of the tmpdir path and tmpdir files. This should be called after all # files have been transferred. if remote_files: # remove none/empty remote_files = [x for x in remote_files if x] self._fixup_perms2(remote_files, self._get_remote_user()) # actually execute res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data) # parse the main result data = self._parse_returned_data(res) # NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE # get internal info before cleaning if data.pop(""_ansible_suppress_tmpdir_delete"", False): self._cleanup_remote_tmp = False # NOTE: yum returns results .. but that made it 'compatible' with squashing, so we allow mappings, for now if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)): data['ansible_module_results'] = data['results'] del data['results'] display.warning(""Found internal 'results' key in module return, renamed to 'ansible_module_results'."") # remove internal keys remove_internal_keys(data) if wrap_async: # async_wrapper will clean up its tmpdir on its own so we want the controller side to # forget about it now self._connection._shell.tmpdir = None # FIXME: for backwards compat, figure out if still makes sense data['changed'] = True # pre-split stdout/stderr into lines if needed if 'stdout' in data and 'stdout_lines' not in data: # if the value is 'False', a default won't catch it. txt = data.get('stdout', None) or u'' data['stdout_lines'] = txt.splitlines() if 'stderr' in data and 'stderr_lines' not in data: # if the value is 'False', a default won't catch it. txt = data.get('stderr', None) or u'' data['stderr_lines'] = txt.splitlines() # propagate interpreter discovery results back to the controller if self._discovered_interpreter_key: if data.get('ansible_facts') is None: data['ansible_facts'] = {} data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter if self._discovery_warnings: if data.get('warnings') is None: data['warnings'] = [] data['warnings'].extend(self._discovery_warnings) if self._discovery_deprecation_warnings: if data.get('deprecations') is None: data['deprecations'] = [] data['deprecations'].extend(self._discovery_deprecation_warnings) # mark the entire module results untrusted as a template right here, since the current action could # possibly template one of these values. data = wrap_var(data) display.debug(""done with _execute_module (%s, %s)"" % (module_name, module_args)) return data" functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,tests/unit/utils/verify_test.py,0,"def test_valid_id_exception_handler(self): ''' Ensure we just return False if we pass in invalid or undefined paths. Refs #8259 ''' opts = {'pki_dir': '/tmp/whatever'} self.assertFalse(valid_id(opts, None))",,saltstack/salt,0dbf41e79e9d46d382244a9011fc58da1332e5d8,"def test_valid_id_exception_handler(self): ''' Ensure we just return False if we pass in invalid or undefined paths. Refs #8259 ''' opts = {'pki_dir': '/tmp/whatever'} self.assertFalse(valid_id(opts, None))" ,UNKNOWN,UNKNOWN,tests/pytests/functional/states/file/test_append.py,1,"def test_issue_1896_file_append_source(file, tmp_path, state_tree): """""" Verify that we can append a file's contents """""" testfile = tmp_path / ""test.append"" testfile.touch() firstif_file = pytest.helpers.temp_file( ""firstif"", directory=state_tree / ""testappend"", contents=FIRST_IF_CONTENTS ) secondif_file = pytest.helpers.temp_file( ""secondif"", directory=state_tree / ""testappend"", contents=SECOND_IF_CONTENTS ) with firstif_file, secondif_file: ret = file.append(name=str(testfile), source=""salt://testappend/firstif"") assert ret.result is True ret = file.append(name=str(testfile), source=""salt://testappend/secondif"") assert ret.result is True testfile_contents = testfile.read_text() assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS # Run it again ret = file.append(name=str(testfile), source=""salt://testappend/firstif"") assert ret.result is True ret = file.append(name=str(testfile), source=""salt://testappend/secondif"") assert ret.result is True testfile_contents = testfile.read_text() assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS",CWE-703,saltstack/salt,1144ca66eaa9e1ad9f54fa5da1f084da7d8b4859,"def test_issue_1896_file_append_source(file, tmp_path, state_tree): """""" Verify that we can append a file's contents """""" testfile = tmp_path / ""test.append"" testfile.touch() firstif_file = pytest.helpers.temp_file( ""firstif"", directory=state_tree / ""testappend"", contents=FIRST_IF_CONTENTS ) secondif_file = pytest.helpers.temp_file( ""secondif"", directory=state_tree / ""testappend"", contents=SECOND_IF_CONTENTS ) with firstif_file, secondif_file: ret = file.append(name=str(testfile), source=""salt://testappend/firstif"") assert ret.result is True ret = file.append(name=str(testfile), source=""salt://testappend/secondif"") assert ret.result is True testfile_contents = testfile.read_text() assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS # Run it again ret = file.append(name=str(testfile), source=""salt://testappend/firstif"") assert ret.result is True ret = file.append(name=str(testfile), source=""salt://testappend/secondif"") assert ret.result is True testfile_contents = testfile.read_text() assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS" functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/providers/google/cloud/operators/looker.py,0,"def execute(self, context: ""Context"") -> str: self.hook = LookerHook(looker_conn_id=self.looker_conn_id) resp = self.hook.start_pdt_build( model=self.model, view=self.view, query_params=self.query_params, ) self.materialization_id = resp.materialization_id if not self.materialization_id: raise AirflowException( f'No `materialization_id` was returned for model: {self.model}, view: {self.view}.' ) self.log.info(""PDT materialization job submitted successfully. Job id: %s."", self.materialization_id) if not self.asynchronous: self.hook.wait_for_job( materialization_id=self.materialization_id, wait_time=self.wait_time, timeout=self.wait_timeout, ) return self.materialization_id",CWE-Unknown,apache/airflow,37a7b27242fa06e0c805cbc01cf3cfe3557daf8e,"def execute(self, context: ""Context"") -> str: self.hook = LookerHook(looker_conn_id=self.looker_conn_id) resp = self.hook.start_pdt_build( model=self.model, view=self.view, query_params=self.query_params, ) self.materialization_id = resp.materialization_id if self.materialization_id is None: raise AirflowException( f'No `materialization_id` was returned for model: {self.model}, view: {self.view}.' ) self.log.info(""PDT materialization job submitted successfully. Job id: %s."", self.materialization_id) if not self.asynchronous: self.hook.wait_for_job( materialization_id=self.materialization_id, wait_time=self.wait_time, timeout=self.wait_timeout, ) return self.materialization_id" ,UNKNOWN,UNKNOWN,tests/api_connexion/endpoints/test_dag_endpoint.py,1,"def test_should_respond_400_with_not_exists_fields(self, fields): self._create_dag_models(1) response = self.client.get( f""/api/v1/dags/TEST_DAG_1?fields={','.join(fields)}"", environ_overrides={""REMOTE_USER"": ""test""} ) assert response.status_code == 400, f""Current code: {response.status_code}""",CWE-703,apache/airflow,7b608250468740954c6b0af7a5f7f23dfa52b473,"def test_should_respond_400_with_not_exists_fields(self, fields): self._create_dag_models(1) response = self.client.get( f""/api/v1/dags/TEST_DAG_1?fields={','.join(fields)}"", environ_overrides={""REMOTE_USER"": ""test""} ) assert response.status_code == 400, f""Current code: {response.status_code}""" ,UNKNOWN,UNKNOWN,tests/pytests/functional/modules/state/requisites/test_watch.py,1,"def test_watch_in_failure(state, state_tree): """""" test watch_in requisite when there is a failure """""" sls_contents = """""" return_changes: test.fail_with_changes: - watch_in: - test: watch_states watch_states: test.succeed_without_changes """""" fail = ""test_|-return_changes_|-return_changes_|-fail_with_changes"" watch = ""test_|-watch_states_|-watch_states_|-succeed_without_changes"" with pytest.helpers.temp_file(""requisite.sls"", sls_contents, state_tree): ret = state.sls(""requisite"") assert ret[fail].result is False assert ( ret[watch].comment == ""One or more requisite failed: requisite.return_changes"" )",CWE-703,saltstack/salt,9d335ba4ec20f89109b71753c0567e716795e755,"def test_watch_in_failure(state, state_tree): """""" test watch_in requisite when there is a failure """""" sls_contents = """""" return_changes: test.fail_with_changes: - watch_in: - test: watch_states watch_states: test.succeed_without_changes """""" fail = ""test_|-return_changes_|-return_changes_|-fail_with_changes"" watch = ""test_|-watch_states_|-watch_states_|-succeed_without_changes"" with pytest.helpers.temp_file(""requisite.sls"", sls_contents, state_tree): ret = state.sls(""requisite"") assert ret[fail].result is False assert ( ret[watch].comment == ""One or more requisite failed: requisite.return_changes"" )" ,UNKNOWN,UNKNOWN,airflow/migrations/versions/0093_2_2_0_taskinstance_keyed_to_dagrun.py,1,"def upgrade(): """"""Apply Change ``TaskInstance`` and ``TaskReschedule`` tables from execution_date to run_id."""""" conn = op.get_bind() dialect_name = conn.dialect.name dt_type = TIMESTAMP string_id_col_type = StringID() if dialect_name == ""sqlite"": naming_convention = { ""uq"": ""%(table_name)s_%(column_0_N_name)s_key"", } # The naming_convention force the previously un-named UNIQUE constraints to have the right name with op.batch_alter_table( ""dag_run"", naming_convention=naming_convention, recreate=""always"" ) as batch_op: batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) elif dialect_name == ""mysql"": with op.batch_alter_table(""dag_run"") as batch_op: batch_op.alter_column( ""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.alter_column( ""run_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) inspector = sa.inspect(conn.engine) unique_keys = inspector.get_unique_constraints(""dag_run"") for unique_key in unique_keys: batch_op.drop_constraint(unique_key[""name""], type_=""unique"") batch_op.create_unique_constraint( ""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""] ) batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""]) elif dialect_name == ""mssql"": with op.batch_alter_table(""dag_run"") as batch_op: batch_op.drop_index(""idx_not_null_dag_id_execution_date"") batch_op.drop_index(""idx_not_null_dag_id_run_id"") batch_op.drop_index(""dag_id_state"") batch_op.drop_index(""idx_dag_run_dag_id"") batch_op.drop_index(""idx_dag_run_running_dags"") batch_op.drop_index(""idx_dag_run_queued_dags"") batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) # _Somehow_ mssql was missing these constraints entirely batch_op.create_unique_constraint( ""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""] ) batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""]) batch_op.create_index(""dag_id_state"", [""dag_id"", ""state""], unique=False) batch_op.create_index(""idx_dag_run_dag_id"", [""dag_id""]) batch_op.create_index( ""idx_dag_run_running_dags"", [""state"", ""dag_id""], mssql_where=sa.text(""state='running'""), ) batch_op.create_index( ""idx_dag_run_queued_dags"", [""state"", ""dag_id""], mssql_where=sa.text(""state='queued'""), ) else: # Make sure DagRun PK columns are non-nullable with op.batch_alter_table(""dag_run"", schema=None) as batch_op: batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) # First create column nullable op.add_column(""task_instance"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True)) op.add_column(""task_reschedule"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True)) # # TaskReschedule has a FK to TaskInstance, so we have to update that before # we can drop the TI.execution_date column update_query = _multi_table_update(dialect_name, task_reschedule, task_reschedule.c.run_id) op.execute(update_query) with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op: batch_op.alter_column( ""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.drop_constraint(""task_reschedule_dag_task_date_fkey"", type_=""foreignkey"") if dialect_name == ""mysql"": # Mysql creates an index and a constraint -- we have to drop both batch_op.drop_index(""task_reschedule_dag_task_date_fkey"") batch_op.alter_column( ""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.drop_index(""idx_task_reschedule_dag_task_date"") # Then update the new column by selecting the right value from DagRun # But first we will drop and recreate indexes to make it faster if dialect_name == ""postgresql"": # Recreate task_instance, without execution_date and with dagrun.run_id op.execute( """""" CREATE TABLE new_task_instance AS SELECT ti.task_id, ti.dag_id, dag_run.run_id, ti.start_date, ti.end_date, ti.duration, ti.state, ti.try_number, ti.hostname, ti.unixname, ti.job_id, ti.pool, ti.queue, ti.priority_weight, ti.operator, ti.queued_dttm, ti.pid, ti.max_tries, ti.executor_config, ti.pool_slots, ti.queued_by_job_id, ti.external_executor_id, ti.trigger_id, ti.trigger_timeout, ti.next_method, ti.next_kwargs FROM task_instance ti INNER JOIN dag_run ON dag_run.dag_id = ti.dag_id AND dag_run.execution_date = ti.execution_date; """""" ) op.drop_table(""task_instance"") op.rename_table(""new_task_instance"", ""task_instance"") # Fix up columns after the 'create table as select' with op.batch_alter_table(""task_instance"", schema=None) as batch_op: batch_op.alter_column( ""pool"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.alter_column(""max_tries"", existing_type=sa.Integer(), server_default=""-1"") batch_op.alter_column( ""pool_slots"", existing_type=sa.Integer(), existing_nullable=True, nullable=False ) else: update_query = _multi_table_update(dialect_name, task_instance, task_instance.c.run_id) op.execute(update_query) with op.batch_alter_table(""task_instance"", schema=None) as batch_op: if dialect_name != ""postgresql"": # TODO: Is this right for non-postgres? if dialect_name == ""mssql"": constraints = get_mssql_table_constraints(conn, ""task_instance"") pk, _ = constraints[""PRIMARY KEY""].popitem() batch_op.drop_constraint(pk, type_=""primary"") elif dialect_name not in (""sqlite""): batch_op.drop_constraint(""task_instance_pkey"", type_=""primary"") batch_op.drop_index(""ti_dag_date"") batch_op.drop_index(""ti_state_lkp"") batch_op.drop_column(""execution_date"") # Then make it non-nullable batch_op.alter_column( ""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.alter_column( ""dag_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.create_primary_key(""task_instance_pkey"", [""dag_id"", ""task_id"", ""run_id""]) batch_op.create_foreign_key( ""task_instance_dag_run_fkey"", ""dag_run"", [""dag_id"", ""run_id""], [""dag_id"", ""run_id""], ondelete=""CASCADE"", ) batch_op.create_index(""ti_dag_run"", [""dag_id"", ""run_id""]) batch_op.create_index(""ti_state_lkp"", [""dag_id"", ""task_id"", ""run_id"", ""state""]) if dialect_name == ""postgresql"": batch_op.create_index(""ti_dag_state"", [""dag_id"", ""state""]) batch_op.create_index(""ti_job_id"", [""job_id""]) batch_op.create_index(""ti_pool"", [""pool"", ""state"", ""priority_weight""]) batch_op.create_index(""ti_state"", [""state""]) batch_op.create_foreign_key( ""task_instance_trigger_id_fkey"", ""trigger"", [""trigger_id""], [""id""], ondelete=""CASCADE"" ) batch_op.create_index(""ti_trigger_id"", [""trigger_id""]) with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op: batch_op.drop_column(""execution_date"") batch_op.create_index( ""idx_task_reschedule_dag_task_run"", [""dag_id"", ""task_id"", ""run_id""], unique=False, ) # _Now_ there is a unique constraint on the columns in TI we can re-create the FK from TaskReschedule batch_op.create_foreign_key( ""task_reschedule_ti_fkey"", ""task_instance"", [""dag_id"", ""task_id"", ""run_id""], [""dag_id"", ""task_id"", ""run_id""], ondelete=""CASCADE"", ) # https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1785-database-engine-error?view=sql-server-ver15 ondelete = ""CASCADE"" if dialect_name != ""mssql"" else ""NO ACTION"" batch_op.create_foreign_key( ""task_reschedule_dr_fkey"", ""dag_run"", [""dag_id"", ""run_id""], [""dag_id"", ""run_id""], ondelete=ondelete, )",CWE-89,apache/airflow,1bd538be8c5b134643a6c5eddd06f70e6f0db2e7,"def upgrade(): """"""Apply Change ``TaskInstance`` and ``TaskReschedule`` tables from execution_date to run_id."""""" conn = op.get_bind() dialect_name = conn.dialect.name dt_type = TIMESTAMP string_id_col_type = StringID() if dialect_name == ""sqlite"": naming_convention = { ""uq"": ""%(table_name)s_%(column_0_N_name)s_key"", } # The naming_convention force the previously un-named UNIQUE constraints to have the right name with op.batch_alter_table( ""dag_run"", naming_convention=naming_convention, recreate=""always"" ) as batch_op: batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) elif dialect_name == ""mysql"": with op.batch_alter_table(""dag_run"") as batch_op: batch_op.alter_column( ""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.alter_column( ""run_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) inspector = sa.inspect(conn.engine) unique_keys = inspector.get_unique_constraints(""dag_run"") for unique_key in unique_keys: batch_op.drop_constraint(unique_key[""name""], type_=""unique"") batch_op.create_unique_constraint( ""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""] ) batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""]) elif dialect_name == ""mssql"": with op.batch_alter_table(""dag_run"") as batch_op: batch_op.drop_index(""idx_not_null_dag_id_execution_date"") batch_op.drop_index(""idx_not_null_dag_id_run_id"") batch_op.drop_index(""dag_id_state"") batch_op.drop_index(""idx_dag_run_dag_id"") batch_op.drop_index(""idx_dag_run_running_dags"") batch_op.drop_index(""idx_dag_run_queued_dags"") batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) # _Somehow_ mssql was missing these constraints entirely batch_op.create_unique_constraint( ""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""] ) batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""]) batch_op.create_index(""dag_id_state"", [""dag_id"", ""state""], unique=False) batch_op.create_index(""idx_dag_run_dag_id"", [""dag_id""]) batch_op.create_index( ""idx_dag_run_running_dags"", [""state"", ""dag_id""], mssql_where=sa.text(""state='running'""), ) batch_op.create_index( ""idx_dag_run_queued_dags"", [""state"", ""dag_id""], mssql_where=sa.text(""state='queued'""), ) else: # Make sure DagRun PK columns are non-nullable with op.batch_alter_table(""dag_run"", schema=None) as batch_op: batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False) batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False) batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False) # First create column nullable op.add_column(""task_instance"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True)) op.add_column(""task_reschedule"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True)) # # TaskReschedule has a FK to TaskInstance, so we have to update that before # we can drop the TI.execution_date column update_query = _multi_table_update(dialect_name, task_reschedule, task_reschedule.c.run_id) op.execute(update_query) with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op: batch_op.alter_column( ""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.drop_constraint(""task_reschedule_dag_task_date_fkey"", ""foreignkey"") if dialect_name == ""mysql"": # Mysql creates an index and a constraint -- we have to drop both batch_op.drop_index(""task_reschedule_dag_task_date_fkey"") batch_op.alter_column( ""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False ) batch_op.drop_index(""idx_task_reschedule_dag_task_date"") # Then update the new column by selecting the right value from DagRun # But first we will drop and recreate indexes to make it faster if dialect_name == ""postgresql"": # Recreate task_instance, without execution_date and with dagrun.run_id op.execute( """""" CREATE TABLE new_task_instance AS SELECT ti.task_id, ti.dag_id, dag_run.run_id, ti.start_date, ti.end_date, ti.duration, ti.state, ti.try_number, ti.hostname, ti.unixname, ti.job_id, ti.pool, ti.queue, ti.priority_weight, ti.operator, ti.queued_dttm, ti.pid, ti.max_tries, ti.executor_config, ti.pool_slots, ti.queued_by_job_id, ti.external_executor_id, ti.trigger_id, ti.trigger_timeout, ti.next_method, ti.next_kwargs FROM task_instance ti INNER JOIN dag_run ON dag_run.dag_id = ti.dag_id AND dag_run.execution_date = ti.execution_date; """""" ) op.drop_table(""task_instance"") op.rename_table(""new_task_instance"", ""task_instance"") # Fix up columns after the 'create table as select' with op.batch_alter_table(""task_instance"", schema=None) as batch_op: batch_op.alter_column( ""pool"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.alter_column(""max_tries"", existing_type=sa.Integer(), server_default=""-1"") batch_op.alter_column( ""pool_slots"", existing_type=sa.Integer(), existing_nullable=True, nullable=False ) else: update_query = _multi_table_update(dialect_name, task_instance, task_instance.c.run_id) op.execute(update_query) with op.batch_alter_table(""task_instance"", schema=None) as batch_op: if dialect_name != ""postgresql"": # TODO: Is this right for non-postgres? if dialect_name == ""mssql"": constraints = get_mssql_table_constraints(conn, ""task_instance"") pk, _ = constraints[""PRIMARY KEY""].popitem() batch_op.drop_constraint(pk, type_=""primary"") elif dialect_name not in (""sqlite""): batch_op.drop_constraint(""task_instance_pkey"", type_=""primary"") batch_op.drop_index(""ti_dag_date"") batch_op.drop_index(""ti_state_lkp"") batch_op.drop_column(""execution_date"") # Then make it non-nullable batch_op.alter_column( ""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.alter_column( ""dag_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False ) batch_op.create_primary_key(""task_instance_pkey"", [""dag_id"", ""task_id"", ""run_id""]) batch_op.create_foreign_key( ""task_instance_dag_run_fkey"", ""dag_run"", [""dag_id"", ""run_id""], [""dag_id"", ""run_id""], ondelete=""CASCADE"", ) batch_op.create_index(""ti_dag_run"", [""dag_id"", ""run_id""]) batch_op.create_index(""ti_state_lkp"", [""dag_id"", ""task_id"", ""run_id"", ""state""]) if dialect_name == ""postgresql"": batch_op.create_index(""ti_dag_state"", [""dag_id"", ""state""]) batch_op.create_index(""ti_job_id"", [""job_id""]) batch_op.create_index(""ti_pool"", [""pool"", ""state"", ""priority_weight""]) batch_op.create_index(""ti_state"", [""state""]) batch_op.create_foreign_key( ""task_instance_trigger_id_fkey"", ""trigger"", [""trigger_id""], [""id""], ondelete=""CASCADE"" ) batch_op.create_index(""ti_trigger_id"", [""trigger_id""]) with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op: batch_op.drop_column(""execution_date"") batch_op.create_index( ""idx_task_reschedule_dag_task_run"", [""dag_id"", ""task_id"", ""run_id""], unique=False, ) # _Now_ there is a unique constraint on the columns in TI we can re-create the FK from TaskReschedule batch_op.create_foreign_key( ""task_reschedule_ti_fkey"", ""task_instance"", [""dag_id"", ""task_id"", ""run_id""], [""dag_id"", ""task_id"", ""run_id""], ondelete=""CASCADE"", ) # https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1785-database-engine-error?view=sql-server-ver15 ondelete = ""CASCADE"" if dialect_name != ""mssql"" else ""NO ACTION"" batch_op.create_foreign_key( ""task_reschedule_dr_fkey"", ""dag_run"", [""dag_id"", ""run_id""], [""dag_id"", ""run_id""], ondelete=ondelete, )" functions_for_requests_with_cwe.csv,UNKNOWN,UNKNOWN,requests/models.py,0,"def prepare_url(self, url, params): """"""Prepares the given HTTP URL."""""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = unicode(url) if is_py2 else str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = (""Invalid URL {0!r}: No scheme supplied. Perhaps you meant http://{0}?"") error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if not host: raise InvalidURL(""Invalid URL %r: No host supplied"" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith(u'*'): raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url",,psf/requests,2b06a952a9e6e23e9eda2c8759adb62739730a75,"def prepare_url(self, url, params): """"""Prepares the given HTTP URL."""""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = unicode(url) if is_py2 else str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = (""Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?"") error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if not host: raise InvalidURL(""Invalid URL %r: No host supplied"" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith(u'*'): raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url" functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/testsuite/helpers.py,0,"def test_debug_log(self): app = flask.Flask(__name__) app.debug = True @app.route('/') def index(): app.logger.warning('the standard library is dead') app.logger.debug('this is a debug statement') return '' @app.route('/exc') def exc(): 1/0 with app.test_client() as c: with catch_stderr() as err: c.get('/') out = err.getvalue() self.assert_('WARNING in helpers [' in out) self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out) self.assert_('the standard library is dead' in out) self.assert_('this is a debug statement' in out) with catch_stderr() as err: try: c.get('/exc') except ZeroDivisionError: pass else: self.assert_(False, 'debug log ate the exception')",,pallets/flask,fbd6776e68a12aa7bf7d646ca03d568cedc616f3,"def test_debug_log(self): app = flask.Flask(__name__) app.debug = True @app.route('/') def index(): app.logger.warning('the standard library is dead') app.logger.debug('this is a debug statement') return '' @app.route('/exc') def exc(): 1/0 with app.test_client() as c: with catch_stderr() as err: c.get('/') out = err.getvalue() self.assert_('WARNING in helpers [' in out) self.assert_(os.path.basename(__file__.rsplit('.')[0] + '.py') in out) self.assert_('the standard library is dead' in out) self.assert_('this is a debug statement' in out) with catch_stderr() as err: try: c.get('/exc') except ZeroDivisionError: pass else: self.assert_(False, 'debug log ate the exception')" ,UNKNOWN,UNKNOWN,django/utils/numberformat.py,1,"def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False, use_l10n=None): """""" Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ""."") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example "","") """""" use_grouping = (use_l10n or (use_l10n is None and settings.USE_L10N)) and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(number) # sign sign = '' # Treat potentially very large/small floats as Decimals. if isinstance(number, float) and 'e' in str(number).lower(): number = Decimal(str(number)) if isinstance(number, Decimal): if decimal_pos is not None: # If the provided number is too small to affect any of the visible # decimal places, consider it equal to '0'. cutoff = Decimal('0.' + '1'.rjust(decimal_pos, '0')) if abs(number) < cutoff: number = Decimal('0') # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponent = number.as_tuple() if abs(exponent) + len(digits) > 200: number = '{:e}'.format(number) coefficient, exponent = number.split('e') # Format the coefficient. coefficient = format( coefficient, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping, use_l10n, ) return '{}e{}'.format(coefficient, exponent) else: str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-': sign = '-' str_number = str_number[1:] # decimal part if '.' in str_number: int_part, dec_part = str_number.split('.') if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, '' if decimal_pos is not None: dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) dec_part = dec_part and decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = '' cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd += thousand_sep[::-1] cnt = 0 int_part_gd += digit cnt += 1 int_part = int_part_gd[::-1] return sign + int_part + dec_part",CWE-79,django/django,bc1c03407649a37a8a3c26b8d0cb355ab2fc128e,"def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False, use_l10n=None): """""" Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ""."") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example "","") """""" use_grouping = (use_l10n or (use_l10n is None and settings.USE_L10N)) and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(number) # sign sign = '' if isinstance(number, Decimal): if decimal_pos is not None: # If the provided number is too small to affect any of the visible # decimal places, consider it equal to '0'. cutoff = Decimal('0.' + '1'.rjust(decimal_pos, '0')) if abs(number) < cutoff: number = Decimal('0') # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponent = number.as_tuple() if abs(exponent) + len(digits) > 200: number = '{:e}'.format(number) coefficient, exponent = number.split('e') # Format the coefficient. coefficient = format( coefficient, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping, use_l10n, ) return '{}e{}'.format(coefficient, exponent) else: str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-': sign = '-' str_number = str_number[1:] # decimal part if '.' in str_number: int_part, dec_part = str_number.split('.') if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, '' if decimal_pos is not None: dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) dec_part = dec_part and decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = '' cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd += thousand_sep[::-1] cnt = 0 int_part_gd += digit cnt += 1 int_part = int_part_gd[::-1] return sign + int_part + dec_part" functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/dbms/oracle/fingerprint.py,0,"def checkDbms(self): if not conf.extensiveFp and Backend.isDbmsWithin(ORACLE_ALIASES): setDbms(DBMS.ORACLE) self.getBanner() return True infoMsg = ""testing %s"" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT LENGTH(SYSDATE)=LENGTH(SYSDATE) FROM DUAL does # not work connecting directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression(""LENGTH(SYSDATE)=LENGTH(SYSDATE)"") if result: infoMsg = ""confirming %s"" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1]) FROM DUAL does # not work connecting directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression(""NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1])"") if not result: warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE logger.warning(warnMsg) return False setDbms(DBMS.ORACLE) self.getBanner() if not conf.extensiveFp: return True infoMsg = ""actively fingerprinting %s"" % DBMS.ORACLE logger.info(infoMsg) # Reference: https://en.wikipedia.org/wiki/Oracle_Database for version in (""21c"", ""19c"", ""18c"", ""12c"", ""11g"", ""10g"", ""9i"", ""8i"", ""7""): number = int(re.search(r""([\d]+)"", version).group(1)) output = inject.checkBooleanExpression(""%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)"" % (number, 1 if number < 10 else 2)) if output: Backend.setVersion(version) break return True else: warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE logger.warning(warnMsg) return False",,sqlmapproject/sqlmap,df4293473d2fb6e887e31522cab5aff95e201581,"def checkDbms(self): if not conf.extensiveFp and Backend.isDbmsWithin(ORACLE_ALIASES): setDbms(DBMS.ORACLE) self.getBanner() return True infoMsg = ""testing %s"" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT LENGTH(SYSDATE)=LENGTH(SYSDATE) FROM DUAL does # not work connecting directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression(""LENGTH(SYSDATE)=LENGTH(SYSDATE)"") if result: infoMsg = ""confirming %s"" % DBMS.ORACLE logger.info(infoMsg) # NOTE: SELECT NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1]) FROM DUAL does # not work connecting directly to the Oracle database if conf.direct: result = True else: result = inject.checkBooleanExpression(""NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1])"") if not result: warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE logger.warn(warnMsg) return False setDbms(DBMS.ORACLE) self.getBanner() if not conf.extensiveFp: return True infoMsg = ""actively fingerprinting %s"" % DBMS.ORACLE logger.info(infoMsg) # Reference: https://en.wikipedia.org/wiki/Oracle_Database for version in (""21c"", ""19c"", ""18c"", ""12c"", ""11g"", ""10g"", ""9i"", ""8i"", ""7""): number = int(re.search(r""([\d]+)"", version).group(1)) output = inject.checkBooleanExpression(""%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)"" % (number, 1 if number < 10 else 2)) if output: Backend.setVersion(version) break return True else: warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE logger.warn(warnMsg) return False" ,UNKNOWN,UNKNOWN,lib/techniques/union/use.py,1,"def _oneShotUnionUse(expression, unpack=True, limited=False): retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted threadData = getCurrentThreadData() threadData.resumed = retVal is not None if retVal is None: vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector if not kb.rowXmlMode: injExpression = unescaper.escape(agent.concatQuery(expression, unpack)) kb.unionDuplicates = vector[7] kb.forcePartialUnion = vector[8] query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited) where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6] else: where = vector[6] query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False) payload = agent.payload(newValue=query, where=where) # Perform the request page, headers, _ = Request.queryPage(payload, content=True, raise404=False) incrementCounter(PAYLOAD.TECHNIQUE.UNION) if not kb.rowXmlMode: # Parse the returned page to get the exact UNION-based # SQL injection output def _(regex): return reduce(lambda x, y: x if x is not None else y, (\ extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \ extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \ if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \ None) # Automatically patching last char trimming cases if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"): warnMsg = ""automatically patching output having last char trimmed"" singleTimeWarnMessage(warnMsg) page = page.replace(kb.chars.stop[:-1], kb.chars.stop) retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop)) else: output = extractRegexResult(r""(?P()+)"", page) if output: try: root = xml.etree.ElementTree.fromstring(""%s"" % output.encode(UNICODE_ENCODING)) retVal = """" for column in kb.dumpColumns: base64 = True for child in root: value = child.attrib.get(column, """").strip() if value and not re.match(r""\A[a-zA-Z0-9+/]+={0,2}\Z"", value): base64 = False break try: value.decode(""base64"") except binascii.Error: base64 = False break if base64: for child in root: child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL for child in root: row = [] for column in kb.dumpColumns: row.append(child.attrib.get(column, NULL)) retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop) except: pass else: retVal = getUnicode(retVal) if retVal is not None: retVal = getUnicode(retVal, kb.pageEncoding) # Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError(): retVal = htmlunescape(retVal).replace(""
"", ""\n"") hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal) elif not kb.rowXmlMode: trimmed = _(""%s(?P.*?)<"" % (kb.chars.start)) if trimmed: warnMsg = ""possible server trimmed output detected "" warnMsg += ""(probably due to its length and/or content): "" warnMsg += safecharencode(trimmed) logger.warn(warnMsg) else: vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector kb.unionDuplicates = vector[7] return retVal",CWE-703,sqlmapproject/sqlmap,996ad59126555e2daa5c5522f7da38c16da05264,"def _oneShotUnionUse(expression, unpack=True, limited=False): retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted threadData = getCurrentThreadData() threadData.resumed = retVal is not None if retVal is None: vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector if not kb.rowXmlMode: injExpression = unescaper.escape(agent.concatQuery(expression, unpack)) kb.unionDuplicates = vector[7] kb.forcePartialUnion = vector[8] query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited) where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6] else: where = vector[6] query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False) payload = agent.payload(newValue=query, where=where) # Perform the request page, headers = Request.queryPage(payload, content=True, raise404=False) incrementCounter(PAYLOAD.TECHNIQUE.UNION) if not kb.rowXmlMode: # Parse the returned page to get the exact UNION-based # SQL injection output def _(regex): return reduce(lambda x, y: x if x is not None else y, (\ extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \ extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \ if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \ None) # Automatically patching last char trimming cases if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"): warnMsg = ""automatically patching output having last char trimmed"" singleTimeWarnMessage(warnMsg) page = page.replace(kb.chars.stop[:-1], kb.chars.stop) retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop)) else: output = extractRegexResult(r""(?P()+)"", page) if output: try: root = xml.etree.ElementTree.fromstring(""%s"" % output.encode(UNICODE_ENCODING)) retVal = """" for column in kb.dumpColumns: base64 = True for child in root: value = child.attrib.get(column, """").strip() if value and not re.match(r""\A[a-zA-Z0-9+/]+={0,2}\Z"", value): base64 = False break try: value.decode(""base64"") except binascii.Error: base64 = False break if base64: for child in root: child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL for child in root: row = [] for column in kb.dumpColumns: row.append(child.attrib.get(column, NULL)) retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop) except: pass else: retVal = getUnicode(retVal) if retVal is not None: retVal = getUnicode(retVal, kb.pageEncoding) # Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError(): retVal = htmlunescape(retVal).replace(""
"", ""\n"") hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal) elif not kb.rowXmlMode: trimmed = _(""%s(?P.*?)<"" % (kb.chars.start)) if trimmed: warnMsg = ""possible server trimmed output detected "" warnMsg += ""(probably due to its length and/or content): "" warnMsg += safecharencode(trimmed) logger.warn(warnMsg) else: vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector kb.unionDuplicates = vector[7] return retVal" ,UNKNOWN,UNKNOWN,tests/pytests/pkg/integration/test_version.py,1,"def test_compare_pkg_versions_redhat_rc(version, install_salt): """""" Test compare pkg versions for redhat RC packages. A tilde should be included in RC Packages and it should test to be a lower version than a non RC package of the same version. For example, v3004~rc1 should be less than v3004. """""" if install_salt.downgrade: version = install_salt.prev_version else: version = install_salt.version if install_salt.distro_id not in ( ""almalinux"", ""rocky"", ""centos"", ""redhat"", ""amzn"", ""fedora"", ""photon"", ): pytest.skip(""Only tests rpm packages"") pkg = [x for x in install_salt.pkgs if ""rpm"" in x] if not pkg: pytest.skip(""Not testing rpm packages"") pkg = pkg[0].split(""/"")[-1] if ""rc"" not in ""."".join(pkg.split(""."")[:2]): pytest.skip(""Not testing an RC package"") assert ""~"" in pkg comp_pkg = pkg.split(""~"")[0] ret = install_salt.proc.run(""rpmdev-vercmp"", pkg, comp_pkg) ret.stdout.matcher.fnmatch_lines([f""{pkg} < {comp_pkg}""])",CWE-703,saltstack/salt,22f3d2670896ca81c77be2ff4b689fbf4644aaa4,"def test_compare_pkg_versions_redhat_rc(version, install_salt): """""" Test compare pkg versions for redhat RC packages. A tilde should be included in RC Packages and it should test to be a lower version than a non RC package of the same version. For example, v3004~rc1 should be less than v3004. """""" if install_salt.distro_id not in ( ""almalinux"", ""rocky"", ""centos"", ""redhat"", ""amzn"", ""fedora"", ""photon"", ): pytest.skip(""Only tests rpm packages"") pkg = [x for x in install_salt.pkgs if ""rpm"" in x] if not pkg: pytest.skip(""Not testing rpm packages"") pkg = pkg[0].split(""/"")[-1] if ""rc"" not in ""."".join(pkg.split(""."")[:2]): pytest.skip(""Not testing an RC package"") assert ""~"" in pkg comp_pkg = pkg.split(""~"")[0] ret = install_salt.proc.run(""rpmdev-vercmp"", pkg, comp_pkg) ret.stdout.matcher.fnmatch_lines([f""{pkg} < {comp_pkg}""])" ,UNKNOWN,UNKNOWN,airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py,1,"def test_post_should_respond_already_exist(self, test_client, body): response = test_client.post(""/connections"", json=body) assert response.status_code == 201 # Another request response = test_client.post(""/connections"", json=body) assert response.status_code == 409 response_json = response.json() assert ""detail"" in response_json assert list(response_json[""detail""].keys()) == [""reason"", ""statement"", ""orig_error"", ""message""]",CWE-703,apache/airflow,7c9b2978f1d1c93ee261fad071659aac325c2148,"def test_post_should_respond_already_exist(self, test_client, body): response = test_client.post(""/connections"", json=body) assert response.status_code == 201 # Another request response = test_client.post(""/connections"", json=body) assert response.status_code == 409 response_json = response.json() assert ""detail"" in response_json assert list(response_json[""detail""].keys()) == [""reason"", ""statement"", ""orig_error""]" functions_for_paramiko_with_cwe.csv,UNKNOWN,UNKNOWN,paramiko/ber.py,0,"def decode_next(self): if self.idx >= len(self.content): return None id = ord(self.content[self.idx]) self.idx += 1 if (id & 31) == 31: # identifier > 30 id = 0 while self.idx < len(self.content): t = ord(self.content[self.idx]) self.idx += 1 id = (id << 7) | (t & 0x7f) if not (t & 0x80): break if self.idx >= len(self.content): return None # now fetch length size = ord(self.content[self.idx]) self.idx += 1 if size & 0x80: # more complimicated... # FIXME: theoretically should handle indefinite-length (0x80) t = size & 0x7f if self.idx + t > len(self.content): return None size = util.inflate_long(self.content[self.idx : self.idx + t], True) self.idx += t if self.idx + size > len(self.content): # can't fit return None data = self.content[self.idx : self.idx + size] self.idx += size # now switch on id if id == 0x30: # sequence return self.decode_sequence(data) elif id == 2: # int return util.inflate_long(data) else: # 1: boolean (00 false, otherwise true) raise BERException('Unknown ber encoding type %d (robey is lazy)' % id)",,paramiko/paramiko,c6d5ba9c5225b119bd718b4fbc1523dc9b3a3926,"def decode_next(self): if self.idx >= len(self.content): return None id = ord(self.content[self.idx]) self.idx += 1 if (id & 31) == 31: # identifier > 30 id = 0 while self.idx < len(self.content): t = ord(self.content[self.idx]) self.idx += 1 id = (id << 7) | (t & 0x7f) if not (t & 0x80): break if self.idx >= len(self.content): return None # now fetch length size = ord(self.content[self.idx]) self.idx += 1 if size & 0x80: # more complimicated... # FIXME: theoretically should handle indefinite-length (0x80) t = size & 0x7f if self.idx + t > len(self.content): return None size = self.inflate_long(self.content[self.idx : self.idx + t], True) self.idx += t if self.idx + size > len(self.content): # can't fit return None data = self.content[self.idx : self.idx + size] self.idx += size # now switch on id if id == 0x30: # sequence return self.decode_sequence(data) elif id == 2: # int return util.inflate_long(data) else: # 1: boolean (00 false, otherwise true) raise BERException('Unknown ber encoding type %d (robey is lazy)' % id)" functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/request/inject.py,0,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True): """""" Called each time sqlmap inject a SQL query on the SQL injection affected parameter. """""" if conf.hexConvert: charsetType = CHARSET_TYPE.HEXADECIMAL kb.safeCharEncode = safeCharEncode kb.resumeValues = resumeValue if suppressOutput is not None: pushValue(getCurrentThreadData().disableStdOut) getCurrentThreadData().disableStdOut = suppressOutput try: if expected == EXPECTED.BOOL: forgeCaseExpression = booleanExpression = expression if expression.upper().startswith(""SELECT ""): booleanExpression = ""(%s)=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else ""1"") else: forgeCaseExpression = agent.forgeCaseStatement(expression) if conf.direct: value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression) elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))): query = cleanQuery(expression) query = expandAsteriskForColumns(query) value = None found = False count = 0 if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I): query = query.replace(""DISTINCT "", """") if not conf.forceDns: if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION): kb.technique = PAYLOAD.TECHNIQUE.UNION value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found: kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if found and conf.dnsName: _ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items()))) warnMsg = ""option '--dns-domain' will be ignored "" warnMsg += ""as faster techniques are usable "" warnMsg += ""(%s) "" % _ singleTimeWarnMessage(warnMsg) if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found: kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN if expected == EXPECTED.BOOL: value = _goBooleanProxy(booleanExpression) else: value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found: if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME): kb.technique = PAYLOAD.TECHNIQUE.TIME else: kb.technique = PAYLOAD.TECHNIQUE.STACKED if expected == EXPECTED.BOOL: value = _goBooleanProxy(booleanExpression) else: value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) if value and isinstance(value, basestring): value = value.strip() if value.strip() else value[:1] else: errMsg = ""none of the injection types identified can be "" errMsg += ""leveraged to retrieve queries output"" raise SqlmapNotVulnerableException(errMsg) finally: kb.resumeValues = True if suppressOutput is not None: getCurrentThreadData().disableStdOut = popValue() kb.safeCharEncode = False if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler: warnMsg = ""in case of continuous data retrieval problems you are advised to try "" warnMsg += ""a switch '--no-cast' and/or switch '--hex'"" singleTimeWarnMessage(warnMsg) return extractExpectedValue(value, expected)",,sqlmapproject/sqlmap,b6e44ae64e3aa7354186a6c01a862a252aa427c0,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True): """""" Called each time sqlmap inject a SQL query on the SQL injection affected parameter. """""" if conf.hexConvert: charsetType = CHARSET_TYPE.HEXADECIMAL kb.safeCharEncode = safeCharEncode kb.resumeValues = resumeValue if suppressOutput is not None: pushValue(getCurrentThreadData().disableStdOut) getCurrentThreadData().disableStdOut = suppressOutput try: if expected == EXPECTED.BOOL: forgeCaseExpression = booleanExpression = expression if expression.upper().startswith(""SELECT ""): booleanExpression = expression[len(""SELECT ""):] if re.search(r""(?i)\(.+\)\Z"", booleanExpression): booleanExpression = ""%s=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else '1') else: forgeCaseExpression = agent.forgeCaseStatement(expression) if conf.direct: value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression) elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))): query = cleanQuery(expression) query = expandAsteriskForColumns(query) value = None found = False count = 0 if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I): query = query.replace(""DISTINCT "", """") if not conf.forceDns: if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION): kb.technique = PAYLOAD.TECHNIQUE.UNION value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found: kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if found and conf.dnsName: _ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items()))) warnMsg = ""option '--dns-domain' will be ignored "" warnMsg += ""as faster techniques are usable "" warnMsg += ""(%s) "" % _ singleTimeWarnMessage(warnMsg) if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found: kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN if expected == EXPECTED.BOOL: value = _goBooleanProxy(booleanExpression) else: value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) count += 1 found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found: if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME): kb.technique = PAYLOAD.TECHNIQUE.TIME else: kb.technique = PAYLOAD.TECHNIQUE.STACKED if expected == EXPECTED.BOOL: value = _goBooleanProxy(booleanExpression) else: value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump) if value and isinstance(value, basestring): value = value.strip() if value.strip() else value[:1] else: errMsg = ""none of the injection types identified can be "" errMsg += ""leveraged to retrieve queries output"" raise SqlmapNotVulnerableException(errMsg) finally: kb.resumeValues = True if suppressOutput is not None: getCurrentThreadData().disableStdOut = popValue() kb.safeCharEncode = False if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler: warnMsg = ""in case of continuous data retrieval problems you are advised to try "" warnMsg += ""a switch '--no-cast' and/or switch '--hex'"" singleTimeWarnMessage(warnMsg) return extractExpectedValue(value, expected)" functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/tracking/test_client.py,0,"def test_load_prompt_error(tracking_uri): client = MlflowClient(tracking_uri=tracking_uri) with pytest.raises(MlflowException, match=r""Prompt with name=test not found""): client.load_prompt(""test"", version=1) # Both file and sqlalchemy return the same error format now error_msg = r""Prompt with name=test not found"" with pytest.raises(MlflowException, match=error_msg): client.load_prompt(""test"", version=2) with pytest.raises(MlflowException, match=error_msg): client.load_prompt(""test"", version=2, allow_missing=False) # Load prompt with a model name client.create_registered_model(""model"") client.create_model_version(""model"", ""source"") with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1, allow_missing=False) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1, allow_missing=False)",,mlflow/mlflow,c526ec1b1d141918c3377e835fb78c20dce3f1e4,"def test_load_prompt_error(tracking_uri): client = MlflowClient(tracking_uri=tracking_uri) with pytest.raises(MlflowException, match=r""Prompt with name=test not found""): client.load_prompt(""test"", version=1) if tracking_uri.startswith(""file""): error_msg = r""Prompt with name=test not found"" else: error_msg = r""Prompt \(name=test, version=2\) not found"" with pytest.raises(MlflowException, match=error_msg): client.load_prompt(""test"", version=2) with pytest.raises(MlflowException, match=error_msg): client.load_prompt(""test"", version=2, allow_missing=False) # Load prompt with a model name client.create_registered_model(""model"") client.create_model_version(""model"", ""source"") with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1, allow_missing=False) with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""): client.load_prompt(""model"", version=1, allow_missing=False)" ,UNKNOWN,UNKNOWN,airflow-core/tests/unit/models/test_backfill.py,1,"def test_reprocess_behavior(reprocess_behavior, num_in_b, exc_reasons, dag_maker, session): """""" We have two modes whereby when there's an existing run(s) in the range of the backfill, we will clear an existing run. """""" # introduce runs for a dag different from the test dag # so that we can verify that queries won't pick up runs from # other dags with same date with dag_maker(schedule=""@daily"", dag_id=""noise-dag""): PythonOperator(task_id=""hi"", python_callable=print) date = ""2021-01-06"" dr = dag_maker.create_dagrun( run_id=f""scheduled_{date}"", logical_date=timezone.parse(date), session=session, state=""success"", ) # should appear more recent than next runs we'll create dr.start_date = timezone.parse(date) + timedelta(minutes=2) session.commit() # now the main part of the test # we insert some historical runs with various states and see # what the backfill behavior is depending on requested # reprocessing behavior dag_id = ""backfill-test-reprocess-behavior"" with dag_maker(schedule=""@daily"", dag_id=dag_id) as dag: PythonOperator(task_id=""hi"", python_callable=print) for date, state in [ (""2021-01-05"", ""success""), (""2021-01-06"", ""failed""), (""2021-01-07"", ""running""), ]: dr = dag_maker.create_dagrun( run_id=f""scheduled_{date}"", logical_date=timezone.parse(date), session=session, state=state, ) # should sort just older than the noise dag with same logical date dr.start_date = timezone.parse(date) for ti in dr.get_task_instances(session=session): ti.state = state session.commit() b = _create_backfill( dag_id=dag.dag_id, from_date=pendulum.parse(""2021-01-03""), to_date=pendulum.parse(""2021-01-09""), max_active_runs=2, reprocess_behavior=reprocess_behavior, reverse=False, dag_run_conf=None, ) session.expunge_all() query = ( select(DagRun) .join(BackfillDagRun.dag_run) .where(BackfillDagRun.backfill_id == b.id) .order_by(BackfillDagRun.sort_ordinal) ) # these are all the dag runs that are part of this backfill dag_runs_in_b = session.scalars(query).all() assert len(dag_runs_in_b) == num_in_b # verify they all have the right run type assert all(x.run_type == DagRunType.BACKFILL_JOB for x in dag_runs_in_b) # verify they all have the right triggered by type assert all(x.triggered_by == DagRunTriggeredByType.BACKFILL for x in dag_runs_in_b) # every run associated with the backfill should have the backfill id assert all(x.backfill_id == b.id for x in dag_runs_in_b) reasons = session.execute( select(BackfillDagRun.logical_date, BackfillDagRun.exception_reason).where( BackfillDagRun.backfill_id == b.id, BackfillDagRun.exception_reason.is_not(None) ) ).all() actual = dict({str(d.date()): r for d, r in reasons}) assert actual == exc_reasons # all the runs created by the backfill should have state queued assert all(x.state == DagRunState.QUEUED for x in dag_runs_in_b)","CWE-89, CWE-703",apache/airflow,88cef4f5986cd7798c463cd4444bfbf4257b1470,"def test_reprocess_behavior(reprocess_behavior, num_in_b, exc_reasons, dag_maker, session): """""" We have two modes whereby when there's an existing run(s) in the range of the backfill, we will clear an existing run. """""" # introduce runs for a dag different from the test dag # so that we can verify that queries won't pick up runs from # other dags with same date with dag_maker(schedule=""@daily"", dag_id=""noise dag""): PythonOperator(task_id=""hi"", python_callable=print) date = ""2021-01-06"" dr = dag_maker.create_dagrun( run_id=f""scheduled_{date}"", logical_date=timezone.parse(date), session=session, state=""success"", ) # should appear more recent than next runs we'll create dr.start_date = timezone.parse(date) + timedelta(minutes=2) session.commit() # now the main part of the test # we insert some historical runs with various states and see # what the backfill behavior is depending on requested # reprocessing behavior dag_id = ""backfill-test-reprocess-behavior"" with dag_maker(schedule=""@daily"", dag_id=dag_id) as dag: PythonOperator(task_id=""hi"", python_callable=print) for date, state in [ (""2021-01-05"", ""success""), (""2021-01-06"", ""failed""), (""2021-01-07"", ""running""), ]: dr = dag_maker.create_dagrun( run_id=f""scheduled_{date}"", logical_date=timezone.parse(date), session=session, state=state, ) # should sort just older than the noise dag with same logical date dr.start_date = timezone.parse(date) for ti in dr.get_task_instances(session=session): ti.state = state session.commit() b = _create_backfill( dag_id=dag.dag_id, from_date=pendulum.parse(""2021-01-03""), to_date=pendulum.parse(""2021-01-09""), max_active_runs=2, reprocess_behavior=reprocess_behavior, reverse=False, dag_run_conf=None, ) session.expunge_all() query = ( select(DagRun) .join(BackfillDagRun.dag_run) .where(BackfillDagRun.backfill_id == b.id) .order_by(BackfillDagRun.sort_ordinal) ) # these are all the dag runs that are part of this backfill dag_runs_in_b = session.scalars(query).all() assert len(dag_runs_in_b) == num_in_b # verify they all have the right run type assert all(x.run_type == DagRunType.BACKFILL_JOB for x in dag_runs_in_b) # verify they all have the right triggered by type assert all(x.triggered_by == DagRunTriggeredByType.BACKFILL for x in dag_runs_in_b) # every run associated with the backfill should have the backfill id assert all(x.backfill_id == b.id for x in dag_runs_in_b) reasons = session.execute( select(BackfillDagRun.logical_date, BackfillDagRun.exception_reason).where( BackfillDagRun.backfill_id == b.id, BackfillDagRun.exception_reason.is_not(None) ) ).all() actual = dict({str(d.date()): r for d, r in reasons}) assert actual == exc_reasons # all the runs created by the backfill should have state queued assert all(x.state == DagRunState.QUEUED for x in dag_runs_in_b)" functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,scripts/in_container/install_airflow_and_providers.py,0,"def install_airflow_and_providers( airflow_constraints_mode: str, airflow_constraints_location: str, airflow_constraints_reference: str, airflow_extras: str, airflow_skip_constraints: bool, default_constraints_branch: str, github_actions: bool, github_repository: str, install_selected_providers: str, package_format: str, providers_constraints_mode: str, providers_constraints_location: str, providers_constraints_reference: str, providers_skip_constraints: bool, python_version: str, use_airflow_version: str, use_packages_from_dist: bool, ): console.print(""[bright_blue]Installing Airflow and Providers"") installation_spec = find_installation_spec( airflow_constraints_mode=airflow_constraints_mode, airflow_constraints_location=airflow_constraints_location, airflow_constraints_reference=airflow_constraints_reference, airflow_extras=airflow_extras, airflow_skip_constraints=airflow_skip_constraints, default_constraints_branch=default_constraints_branch, github_repository=github_repository, install_selected_providers=install_selected_providers, package_format=package_format, providers_constraints_mode=providers_constraints_mode, providers_constraints_location=providers_constraints_location, providers_constraints_reference=providers_constraints_reference, providers_skip_constraints=providers_skip_constraints, python_version=python_version, use_airflow_version=use_airflow_version, use_packages_from_dist=use_packages_from_dist, ) if installation_spec.airflow_package: install_airflow_cmd = [ ""pip"", ""install"", ""--root-user-action"", ""ignore"", installation_spec.airflow_package, ] console.print(f""\n[bright_blue]Installing airflow package: {installation_spec.airflow_package}"") if installation_spec.airflow_constraints_location: console.print(f""[bright_blue]Use constraints: {installation_spec.airflow_constraints_location}"") install_airflow_cmd.extend([""--constraint"", installation_spec.airflow_constraints_location]) console.print() run_command(install_airflow_cmd, github_actions=github_actions, check=True) if installation_spec.provider_packages or not install_airflow_with_constraints: install_providers_cmd = [""pip"", ""install"", ""--root-user-action"", ""ignore""] console.print(""\n[bright_blue]Installing provider packages:"") for provider_package in sorted(installation_spec.provider_packages): console.print(f"" {provider_package}"") console.print() for provider_package in installation_spec.provider_packages: install_providers_cmd.append(provider_package) if installation_spec.provider_constraints_location: console.print( f""[bright_blue]with constraints: {installation_spec.provider_constraints_location}\n"" ) install_providers_cmd.extend([""--constraint"", installation_spec.provider_constraints_location]) console.print() run_command(install_providers_cmd, github_actions=github_actions, check=True) console.print(""[green]Done!"")",CWE-Unknown,apache/airflow,34846699020a472ea5e8934511518b37503fe79c,"def install_airflow_and_providers( airflow_constraints_mode: str, airflow_constraints_location: str, airflow_constraints_reference: str, airflow_extras: str, airflow_skip_constraints: bool, default_constraints_branch: str, github_actions: bool, github_repository: str, install_selected_providers: str, package_format: str, providers_constraints_mode: str, providers_constraints_location: str, providers_constraints_reference: str, providers_skip_constraints: bool, python_version: str, use_airflow_version: str, use_packages_from_dist: bool, ): console.print(""[bright_blue]Installing Airflow and Providers"") installation_spec = find_installation_spec( airflow_constraints_mode=airflow_constraints_mode, airflow_constraints_location=airflow_constraints_location, airflow_constraints_reference=airflow_constraints_reference, airflow_extras=airflow_extras, airflow_skip_constraints=airflow_skip_constraints, default_constraints_branch=default_constraints_branch, github_repository=github_repository, install_selected_providers=install_selected_providers, package_format=package_format, providers_constraints_mode=providers_constraints_mode, providers_constraints_location=providers_constraints_location, providers_constraints_reference=providers_constraints_reference, providers_skip_constraints=providers_skip_constraints, python_version=python_version, use_airflow_version=use_airflow_version, use_packages_from_dist=use_packages_from_dist, ) if installation_spec.airflow_package: install_airflow_cmd = [ ""pip"", ""install"", ""--root-user-action"", ""ignore"", installation_spec.airflow_package, ] console.print(f""\n[bright_blue]Installing airflow package: {installation_spec.airflow_package}"") if installation_spec.airflow_constraints_location: console.print(f""[bright_blue]Use constraints: {installation_spec.airflow_constraints_location}"") install_airflow_cmd.extend([""--constraint"", installation_spec.airflow_constraints_location]) console.print() run_command(install_airflow_cmd, github_actions=github_actions, check=True) if installation_spec.provider_packages: install_providers_cmd = [""pip"", ""install"", ""--root-user-action"", ""ignore""] console.print(""\n[bright_blue]Installing provider packages:"") for provider_package in sorted(installation_spec.provider_packages): console.print(f"" {provider_package}"") console.print() for provider_package in installation_spec.provider_packages: install_providers_cmd.append(provider_package) if installation_spec.provider_constraints_location: console.print( f""[bright_blue]with constraints: {installation_spec.provider_constraints_location}\n"" ) install_providers_cmd.extend([""--constraint"", installation_spec.provider_constraints_location]) console.print() run_command(install_providers_cmd, github_actions=github_actions, check=True) console.print(""[green]Done!"")" functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/cli.py,0,"def prepare_exec_for_file(filename): """"""Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """""" module = [] # Chop off file extensions or package markers if os.path.split(filename)[1] == '__init__.py': filename = os.path.dirname(filename) elif filename.endswith('.py'): filename = filename[:-3] else: raise NoAppException('The file provided (%s) does exist but is not a ' 'valid Python file. This means that it cannot ' 'be used as application. Please change the ' 'extension to .py' % filename) filename = os.path.realpath(filename) dirpath = filename while 1: dirpath, extra = os.path.split(dirpath) module.append(extra) if not os.path.isfile(os.path.join(dirpath, '__init__.py')): break sys.path.insert(0, dirpath) return '.'.join(module[::-1])",,pallets/flask,41e08f4ccd0f41896200cbf5c5f5d6f3df3df713,"def prepare_exec_for_file(filename): """"""Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """""" module = [] # Chop off file extensions or package markers if filename.endswith('.py'): filename = filename[:-3] elif os.path.split(filename)[1] == '__init__.py': filename = os.path.dirname(filename) else: raise NoAppException('The file provided (%s) does exist but is not a ' 'valid Python file. This means that it cannot ' 'be used as application. Please change the ' 'extension to .py' % filename) filename = os.path.realpath(filename) dirpath = filename while 1: dirpath, extra = os.path.split(dirpath) module.append(extra) if not os.path.isfile(os.path.join(dirpath, '__init__.py')): break sys.path.insert(0, dirpath) return '.'.join(module[::-1])" functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py,0,"def handle(self, **options): db = options['database'] interactive = options['interactive'] verbosity = options['verbosity'] for app_config in apps.get_app_configs(): content_types, app_models = get_contenttypes_and_models(app_config, db, ContentType) to_remove = [ ct for (model_name, ct) in content_types.items() if model_name not in app_models ] # Confirm that the content type is stale before deletion. using = router.db_for_write(ContentType) if to_remove: if interactive: ct_info = [] for ct in to_remove: ct_info.append(' - Content type for %s.%s' % (ct.app_label, ct.model)) collector = NoFastDeleteCollector(using=using) collector.collect([ct]) for obj_type, objs in collector.data.items(): if objs == {ct}: continue ct_info.append(' - %s %s object(s)' % ( len(objs), obj_type._meta.label, )) content_type_display = '\n'.join(ct_info) self.stdout.write(""""""Some content types in your database are stale and can be deleted. Any objects that depend on these content types will also be deleted. The content types and dependent objects that would be deleted are: %s This list doesn't include any cascade deletions to data outside of Django's models (uncommon). Are you sure you want to delete these content types? If you're unsure, answer 'no'.\n"""""" % content_type_display) ok_to_delete = input(""Type 'yes' to continue, or 'no' to cancel: "") else: ok_to_delete = False if ok_to_delete == 'yes': for ct in to_remove: if verbosity >= 2: self.stdout.write(""Deleting stale content type '%s | %s'"" % (ct.app_label, ct.model)) ct.delete() else: if verbosity >= 2: self.stdout.write(""Stale content types remain."")",CWE-Unknown,django/django,874b1f2cac7b79597ce87cc244b7cefc5c5cd821,"def handle(self, **options): db = options['database'] interactive = options['interactive'] verbosity = options['verbosity'] for app_config in apps.get_app_configs(): content_types, app_models = get_contenttypes_and_models(app_config, db, ContentType) if not app_models: continue to_remove = [ ct for (model_name, ct) in content_types.items() if model_name not in app_models ] # Confirm that the content type is stale before deletion. using = router.db_for_write(ContentType) if to_remove: if interactive: ct_info = [] for ct in to_remove: ct_info.append(' - Content type for %s.%s' % (ct.app_label, ct.model)) collector = NoFastDeleteCollector(using=using) collector.collect([ct]) for obj_type, objs in collector.data.items(): if objs == {ct}: continue ct_info.append(' - %s %s object(s)' % ( len(objs), obj_type._meta.label, )) content_type_display = '\n'.join(ct_info) self.stdout.write(""""""Some content types in your database are stale and can be deleted. Any objects that depend on these content types will also be deleted. The content types and dependent objects that would be deleted are: %s This list doesn't include any cascade deletions to data outside of Django's models (uncommon). Are you sure you want to delete these content types? If you're unsure, answer 'no'.\n"""""" % content_type_display) ok_to_delete = input(""Type 'yes' to continue, or 'no' to cancel: "") else: ok_to_delete = False if ok_to_delete == 'yes': for ct in to_remove: if verbosity >= 2: self.stdout.write(""Deleting stale content type '%s | %s'"" % (ct.app_label, ct.model)) ct.delete() else: if verbosity >= 2: self.stdout.write(""Stale content types remain."")" functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/notebookapp.py,0,"def init_settings(self, jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( ""template_path"", jupyter_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = {""autoescape"": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.i18n'], **jenv_opt) sys_info = get_sys_info() # If the user is running the notebook in a git directory, make the assumption # that this is a dev install and suggest to the developer `npm run build:watch`. base_dir = os.path.realpath(os.path.join(__file__, '..', '..')) dev_mode = os.path.exists(os.path.join(base_dir, '.git')) nbui = gettext.translation('nbui', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True) env.install_gettext_translations(nbui, newstyle=False) if dev_mode: DEV_NOTE_NPM = """"""It looks like you're running the notebook from source. If you're working on the Javascript of the notebook, try running %s in another terminal window to have the system incrementally watch and build the notebook's JavaScript for you, as you make changes."""""" % 'npm run build:watch' log.info(DEV_NOTE_NPM) if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"") if jupyter_app.ignore_minified_js: log.warning(_(""""""The `ignore_minified_js` flag is deprecated and no longer works."""""")) log.warning(_(""""""Alternatively use `%s` when working on the notebook's Javascript and LESS"""""") % 'npm run build:watch') warnings.warn(_(""The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0""), DeprecationWarning) now = utcnow() root_dir = contents_manager.root_dir home = os.path.expanduser('~') if root_dir.startswith(home + os.path.sep): # collapse $HOME to ~ root_dir = '~' + root_dir[len(home):] settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=jupyter_app.static_file_path, static_custom_path=jupyter_app.static_custom_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, ignore_minified_js=jupyter_app.ignore_minified_js, # rate limits iopub_msg_rate_limit=jupyter_app.iopub_msg_rate_limit, iopub_data_rate_limit=jupyter_app.iopub_data_rate_limit, rate_limit_window=jupyter_app.rate_limit_window, # authentication cookie_secret=jupyter_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=jupyter_app.login_handler_class, logout_handler_class=jupyter_app.logout_handler_class, password=jupyter_app.password, xsrf_cookies=True, disable_check_xsrf=jupyter_app.disable_check_xsrf, allow_remote_access=jupyter_app.allow_remote_access, local_hostnames=jupyter_app.local_hostnames, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # handlers extra_services=extra_services, # Jupyter stuff started=now, # place for extensions to register activity # so that they can prevent idle-shutdown last_activity_times={}, jinja_template_vars=jupyter_app.jinja_template_vars, nbextensions_path=jupyter_app.nbextensions_path, websocket_url=jupyter_app.websocket_url, mathjax_url=jupyter_app.mathjax_url, mathjax_config=jupyter_app.mathjax_config, shutdown_button=jupyter_app.quit_button, config=jupyter_app.config, config_dir=jupyter_app.config_dir, allow_password_change=jupyter_app.allow_password_change, server_root_dir=root_dir, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings",,jupyter/notebook,f81ec30b62fd1cec122d48c6a367b8ea6ae59809,"def init_settings(self, jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, config_manager, extra_services, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( ""template_path"", jupyter_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = {""autoescape"": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.i18n'], **jenv_opt) sys_info = get_sys_info() # If the user is running the notebook in a git directory, make the assumption # that this is a dev install and suggest to the developer `npm run build:watch`. base_dir = os.path.realpath(os.path.join(__file__, '..', '..')) dev_mode = os.path.exists(os.path.join(base_dir, '.git')) nbui = gettext.translation('nbui', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True) env.install_gettext_translations(nbui, newstyle=False) if dev_mode: DEV_NOTE_NPM = """"""It looks like you're running the notebook from source. If you're working on the Javascript of the notebook, try running %s in another terminal window to have the system incrementally watch and build the notebook's JavaScript for you, as you make changes."""""" % 'npm run build:watch' log.info(DEV_NOTE_NPM) if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"") if jupyter_app.ignore_minified_js: log.warning(_(""""""The `ignore_minified_js` flag is deprecated and no longer works."""""")) log.warning(_(""""""Alternatively use `%s` when working on the notebook's Javascript and LESS"""""") % 'npm run build:watch') warnings.warn(_(""The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0""), DeprecationWarning) now = utcnow() root_dir = contents_manager.root_dir home = os.path.expanduser('~') if root_dir.startswith(home + os.path.sep): # collapse $HOME to ~ root_dir = '~' + root_dir[len(home):] settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=jupyter_app.static_file_path, static_custom_path=jupyter_app.static_custom_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, ignore_minified_js=jupyter_app.ignore_minified_js, # rate limits iopub_msg_rate_limit=jupyter_app.iopub_msg_rate_limit, iopub_data_rate_limit=jupyter_app.iopub_data_rate_limit, rate_limit_window=jupyter_app.rate_limit_window, # maximum request sizes - support saving larger notebooks # tornado defaults are 100 MiB, we increase it to 0.5 GiB max_body_size = 512 * 1024 * 1024, max_buffer_size = 512 * 1024 * 1024, # authentication cookie_secret=jupyter_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=jupyter_app.login_handler_class, logout_handler_class=jupyter_app.logout_handler_class, password=jupyter_app.password, xsrf_cookies=True, disable_check_xsrf=jupyter_app.disable_check_xsrf, allow_remote_access=jupyter_app.allow_remote_access, local_hostnames=jupyter_app.local_hostnames, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # handlers extra_services=extra_services, # Jupyter stuff started=now, # place for extensions to register activity # so that they can prevent idle-shutdown last_activity_times={}, jinja_template_vars=jupyter_app.jinja_template_vars, nbextensions_path=jupyter_app.nbextensions_path, websocket_url=jupyter_app.websocket_url, mathjax_url=jupyter_app.mathjax_url, mathjax_config=jupyter_app.mathjax_config, shutdown_button=jupyter_app.quit_button, config=jupyter_app.config, config_dir=jupyter_app.config_dir, allow_password_change=jupyter_app.allow_password_change, server_root_dir=root_dir, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings" ,UNKNOWN,UNKNOWN,django/contrib/admin/templatetags/admin_list.py,1,"def result_headers(cl): """""" Generates the list column headers. """""" ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field( field_name, cl.model, model_admin=cl.model_admin, return_attr=True ) if attr: # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { ""text"": text, ""class_attrib"": mark_safe(' class=""action-checkbox-column""'), ""sortable"": False, } continue admin_order_field = getattr(attr, ""admin_order_field"", None) if not admin_order_field: # Not sortable yield { ""text"": text, ""class_attrib"": format_html(' class=""column-{}""', field_name), ""sortable"": False, } continue # OK, it is sortable if we got this far th_classes = ['sortable', 'column-{}'.format(field_name)] order_type = '' new_order_type = 'asc' sort_priority = 0 sorted = False # Is it currently being sorted on? if i in ordering_field_columns: sorted = True order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_primary = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field def make_qs_param(t, n): return ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_primary.insert(0, param) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_primary.append(param) o_list_toggle.append(param) o_list_remove.append(param) if i not in ordering_field_columns: o_list_primary.insert(0, make_qs_param(new_order_type, i)) yield { ""text"": text, ""sortable"": True, ""sorted"": sorted, ""ascending"": order_type == ""asc"", ""sort_priority"": sort_priority, ""url_primary"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}), ""url_remove"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}), ""url_toggle"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), ""class_attrib"": format_html(' class=""{}""', ' '.join(th_classes)) if th_classes else '', }",CWE-79,django/django,60586dd7379b295b72d8af4e03423c286913b5e8,"def result_headers(cl): """""" Generates the list column headers. """""" ordering_field_columns = cl.get_ordering_field_columns() for i, field_name in enumerate(cl.list_display): text, attr = label_for_field( field_name, cl.model, model_admin=cl.model_admin, return_attr=True ) if attr: # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { ""text"": text, ""class_attrib"": mark_safe(' class=""action-checkbox-column""'), ""sortable"": False, } continue admin_order_field = getattr(attr, ""admin_order_field"", None) if not admin_order_field: # Not sortable yield { ""text"": text, ""class_attrib"": format_html(' class=""column-{}""', field_name), ""sortable"": False, } continue # OK, it is sortable if we got this far th_classes = ['sortable', 'column-{}'.format(field_name)] order_type = '' new_order_type = 'asc' sort_priority = 0 sorted = False # Is it currently being sorted on? if i in ordering_field_columns: sorted = True order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 th_classes.append('sorted %sending' % order_type) new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param o_list_primary = [] # URL for making this field the primary sort o_list_remove = [] # URL for removing this field from sort o_list_toggle = [] # URL for toggling order type for this field make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front o_list_primary.insert(0, param) o_list_toggle.append(param) # o_list_remove - omit else: param = make_qs_param(ot, j) o_list_primary.append(param) o_list_toggle.append(param) o_list_remove.append(param) if i not in ordering_field_columns: o_list_primary.insert(0, make_qs_param(new_order_type, i)) yield { ""text"": text, ""sortable"": True, ""sorted"": sorted, ""ascending"": order_type == ""asc"", ""sort_priority"": sort_priority, ""url_primary"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}), ""url_remove"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}), ""url_toggle"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), ""class_attrib"": format_html(' class=""{}""', ' '.join(th_classes)) if th_classes else '', }" ,UNKNOWN,UNKNOWN,tests/models/test_trigger.py,1,"def test_clean_unused(session, create_task_instance): """""" Tests that unused triggers (those with no task instances referencing them) are cleaned out automatically. """""" # Make three triggers trigger1 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger1.id = 1 trigger2 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger2.id = 2 trigger3 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger3.id = 3 session.add(trigger1) session.add(trigger2) session.add(trigger3) session.commit() assert session.query(Trigger).count() == 3 # Tie one to a fake TaskInstance that is not deferred, and one to one that is task_instance = create_task_instance( session=session, task_id=""fake"", state=State.DEFERRED, execution_date=timezone.utcnow() ) task_instance.trigger_id = trigger1.id session.add(task_instance) fake_task = EmptyOperator(task_id=""fake2"", dag=task_instance.task.dag) task_instance = TaskInstance(task=fake_task, run_id=task_instance.run_id) task_instance.state = State.SUCCESS task_instance.trigger_id = trigger2.id session.add(task_instance) session.commit() # Run clear operation Trigger.clean_unused() # Verify that one trigger is gone, and the right one is left assert session.query(Trigger).one().id == trigger1.id",CWE-703,apache/airflow,ef147dd8c403cb93c5419092cab2d20012ad3a72,"def test_clean_unused(session, create_task_instance): """""" Tests that unused triggers (those with no task instances referencing them) are cleaned out automatically. """""" # Make three triggers trigger1 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger1.id = 1 trigger2 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger2.id = 2 trigger3 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={}) trigger3.id = 3 session.add(trigger1) session.add(trigger2) session.add(trigger3) session.commit() assert session.query(Trigger).count() == 3 # Tie one to a fake TaskInstance that is not deferred, and one to one that is task_instance = create_task_instance( session=session, task_id=""fake"", state=State.DEFERRED, execution_date=timezone.utcnow() ) task_instance.trigger_id = trigger1.id session.add(task_instance) fake_task = EmptyOperator(task_id=""fake2"", dag=task_instance.task.dag) task_instance = TaskInstance(task=fake_task, run_id=task_instance.run_id) task_instance.state = State.SUCCESS task_instance.trigger_id = trigger2.id session.add(task_instance) session.commit() # Run clear operation Trigger.clean_unused() # Verify that one trigger is gone, and the right one is left assert session.query(Trigger).one().id == trigger1.id" functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/audit/xst.py,0,"def _fuzzRequests(self, freq ): ''' Verify xst vulns by sending a TRACE request and analyzing the response. ''' if not self._exec: # Do nothing pass else: # This will raise the exception the next time _fuzzRequests is run and remove the plugin from the list self._exec = False # Create a mutant based on a fuzzable request # It is really important to use A COPY of the fuzzable request, and not the original. # The reason: I'm changing the method and the URL ! frCopy = freq.copy() frCopy.setURL( urlParser.getDomainPath( frCopy.getURL() ) ) frCopy.setMethod('TRACE') myMutant = mutant(frCopy) # Add a header. I search for this value to determine if XST is valid myheader = { 'FalseHeader': 'XST'} myMutant.setHeaders(myheader) # send the request to the server and recode the response response = self._sendMutant( myMutant, analyze=False ) # create a regex to test the response. regex = re.compile(""[FalseHeader: XST]"") if re.match(regex,response.getBody()): # If vulnerable record it. This will now become visible on the html Report v = vuln.vuln( freq ) v.setId( response.id ) v.setSeverity(severity.LOW) v.setName( 'Cross site tracing vulnerability' ) v.setDesc( 'The web server at ""'+ response.getURL() +'"" is vulnerable to Cross Site Tracing.' ) om.out.vulnerability( v.getDesc(), severity=v.getSeverity() ) kb.kb.append( self, 'xst', v )",,andresriancho/w3af,62c50a62de5663ebe90fd1a182de7553ea7fea5f,"def _fuzzRequests(self, freq ): ''' Verify xst vulns by sending a TRACE request and analyzing the response. ''' if not self._exec: # Do nothing pass else: # This will raise the exception the next time _fuzzRequests is run and remove the plugin from the list self._exec = False # Create a mutant based on a fuzzable request # It is really important to use A COPY of the fuzzable request, and not the original. # The reason: I'm changing the method and the URL ! frCopy = freq.copy() frCopy.setURL( urlParser.getDomainPath( frCopy.getURL() ) ) frCopy.setMethod('TRACE') myMutant = mutant(frCopy) # Add a header. I search for this value to determine if XST is valid myheader = { 'FalseHeader': 'XST'} myMutant.setHeaders(myheader) # send the request to the server and recode the response response = self._sendMutant( myMutant, analyze=False ) # create a regex to test the response. regex = re.compile(""[FalseHeader: XST]"") if re.match(regex,response.getBody()): # If vulnerable record it. This will now become visible on the html Report v = vuln.vuln( freq ) v.setId( response.id ) v.setSeverity(severity.LOW) v.setName( 'Cross site tracing vulnerability' ) v.setDesc( 'The web server at ""'+ response.getURL() +'"" is vulnerable to Cross Site Tracing.' ) om.out.vulnerability( v.getDesc() ) kb.kb.append( self, 'xst', v )" functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/core/agent.py,0,"def _(pattern, repl, string): retVal = string match = None for match in re.finditer(pattern, string): pass if match: while True: _ = re.search(r""\\g<([^>]+)>"", repl) if _: repl = repl.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1))) else: break retVal = string[:match.start()] + repl + string[match.end():] return retVal",,sqlmapproject/sqlmap,4f122ee0086a43108d0fca7191914b8649795fef,"def _(pattern, repl, string): retVal = string match = None for match in re.finditer(pattern, string): pass if match: while True: _ = re.search(r""\\g<([^>]+)>"", repl) if _: repl = repl.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1))) else: break retVal = string[:match.start()] + repl + string[match.end():] return retVal" ,UNKNOWN,UNKNOWN,django/contrib/gis/db/backends/oracle/introspection.py,1,"def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information. try: cursor.execute( 'SELECT ""DIMINFO"", ""SRID"" FROM ""USER_SDO_GEOM_METADATA"" ' 'WHERE ""TABLE_NAME""=%s AND ""COLUMN_NAME""=%s', (table_name.upper(), geo_col.upper()) ) row = cursor.fetchone() except Exception as msg: new_msg = ( 'Could not find entry in USER_SDO_GEOM_METADATA ' 'corresponding to ""%s"".""%s""\n' 'Error message: %s.') % (table_name, geo_col, msg) six.reraise(Exception, Exception(new_msg), sys.exc_info()[2]) # TODO: Research way to find a more specific geometry field type for # the column's contents. field_type = 'GeometryField' # Getting the field parameters. field_params = {} dim, srid = row if srid != 4326: field_params['srid'] = srid # Size of object array (SDO_DIM_ARRAY) is number of dimensions. dim = dim.size() if dim != 2: field_params['dim'] = dim finally: cursor.close() return field_type, field_params",CWE-89,django/django,9924c8a8b0f4281ba018ca3292ed78718fabe362,"def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information. try: cursor.execute( 'SELECT ""DIMINFO"", ""SRID"" FROM ""USER_SDO_GEOM_METADATA"" ' 'WHERE ""TABLE_NAME""=%s AND ""COLUMN_NAME""=%s', (table_name.upper(), geo_col.upper()) ) row = cursor.fetchone() except Exception as msg: new_msg = ( 'Could not find entry in USER_SDO_GEOM_METADATA ' 'corresponding to ""%s"".""%s""\n' 'Error message: %s.') % (table_name, geo_col, msg) six.reraise(Exception, Exception(new_msg), sys.exc_info()[2]) # TODO: Research way to find a more specific geometry field type for # the column's contents. field_type = 'GeometryField' # Getting the field parameters. field_params = {} dim, srid = row if srid != 4326: field_params['srid'] = srid # Length of object array ( SDO_DIM_ARRAY ) is number of dimensions. dim = len(dim) if dim != 2: field_params['dim'] = dim finally: cursor.close() return field_type, field_params" ,UNKNOWN,UNKNOWN,providers/tests/apache/pig/operators/test_pig.py,1,"def test_prepare_template(self): pig = ""sh echo $DATE;"" task_id = TEST_TASK_ID operator = PigOperator(pig=pig, task_id=task_id) operator.prepare_template() assert pig == operator.pig # converts when pigparams_jinja_translate = true operator = PigOperator(pig=pig, task_id=task_id, pigparams_jinja_translate=True) operator.prepare_template() assert operator.pig == ""sh echo {{ DATE }};""",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_prepare_template(self): pig = ""sh echo $DATE;"" task_id = TEST_TASK_ID operator = PigOperator(pig=pig, task_id=task_id) operator.prepare_template() assert pig == operator.pig # converts when pigparams_jinja_translate = true operator = PigOperator(pig=pig, task_id=task_id, pigparams_jinja_translate=True) operator.prepare_template() assert ""sh echo {{ DATE }};"" == operator.pig" functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/win_lgpo.py,0,"def _processValueItem(element, reg_key, reg_valuename, policy, parent_element, check_deleted=False, this_element_value=None): ''' helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - the registry key associated with the element (some inherit from their parent policy) reg_valuename - the registry valueName associated with the element (some inherit from their parent policy) policy - the parent policy element parent_element - the parent element (primarily passed in to differentiate children of ""elements"" objects check_deleted - if the returned expected string should be for a deleted value this_element_value - a specific value to place into the expected string returned for ""elements"" children whose values are specified by the user ''' registry = Registry() expected_string = None # https://msdn.microsoft.com/en-us/library/dn606006(v=vs.85).aspx this_vtype = 'REG_SZ' encoded_semicolon = ';'.encode('utf-16-le') encoded_null = chr(0).encode('utf-16-le') if reg_key: reg_key = reg_key.encode('utf-16-le') if reg_valuename: reg_valuename = reg_valuename.encode('utf-16-le') if etree.QName(element).localname == 'decimal' and etree.QName(parent_element).localname != 'elements': this_vtype = 'REG_DWORD' if 'value' in element.attrib: this_element_value = struct.pack(b'I', int(element.attrib['value'])) else: log.error('The %s child %s element for the policy with ' 'attributes: %s does not have the required ""value"" ' 'attribute. The element attributes are: %s', etree.QName(parent_element).localname, etree.QName(element).localname, policy.attrib, element.attrib) return None elif etree.QName(element).localname == 'longDecimal' and etree.QName(parent_element).localname != 'elements': # WARNING: no longDecimals in current ADMX files included with 2012 # server, so untested/assumed this_vtype = 'REG_QWORD' if 'value' in element.attrib: this_element_value = struct.pack(b'Q', int(element.attrib['value'])) else: log.error('The %s child %s element for the policy with ' 'attributes: %s does not have the required ""value"" ' 'attribute. The element attributes are: %s', etree.QName(parent_element).localname, etree.QName(element).localname, policy.attrib, element.attrib) return None elif etree.QName(element).localname == 'string': this_vtype = 'REG_SZ' this_element_value = b''.join([element.text.encode('utf-16-le'), encoded_null]) elif etree.QName(parent_element).localname == 'elements': standard_element_expected_string = True if etree.QName(element).localname == 'boolean': # a boolean element that has no children will add a REG_DWORD == 1 # on true or delete the value on false # https://msdn.microsoft.com/en-us/library/dn605978(v=vs.85).aspx if this_element_value is False: check_deleted = True if not check_deleted: this_vtype = 'REG_DWORD' this_element_value = struct.pack('I', 1) standard_element_expected_string = False elif etree.QName(element).localname == 'decimal': # https://msdn.microsoft.com/en-us/library/dn605987(v=vs.85).aspx this_vtype = 'REG_DWORD' requested_val = this_element_value if this_element_value is not None: this_element_value = struct.pack(b'I', int(this_element_value)) if 'storeAsText' in element.attrib: if element.attrib['storeAsText'].lower() == 'true': this_vtype = 'REG_SZ' if requested_val is not None: this_element_value = six.text_type(requested_val).encode('utf-16-le') if check_deleted: this_vtype = 'REG_SZ' elif etree.QName(element).localname == 'longDecimal': # https://msdn.microsoft.com/en-us/library/dn606015(v=vs.85).aspx this_vtype = 'REG_QWORD' requested_val = this_element_value if this_element_value is not None: this_element_value = struct.pack(b'Q', int(this_element_value)) if 'storeAsText' in element.attrib: if element.attrib['storeAsText'].lower() == 'true': this_vtype = 'REG_SZ' if requested_val is not None: this_element_value = six.text_type(requested_val).encode('utf-16-le') elif etree.QName(element).localname == 'text': # https://msdn.microsoft.com/en-us/library/dn605969(v=vs.85).aspx this_vtype = 'REG_SZ' if 'expandable' in element.attrib: if element.attrib['expandable'].lower() == 'true': this_vtype = 'REG_EXPAND_SZ' if this_element_value is not None: this_element_value = b''.join([this_element_value.encode('utf-16-le'), encoded_null]) elif etree.QName(element).localname == 'multiText': this_vtype = 'REG_MULTI_SZ' if not check_deleted else 'REG_SZ' if this_element_value is not None: this_element_value = '{0}{1}{1}'.format(chr(0).join(this_element_value), chr(0)) elif etree.QName(element).localname == 'list': standard_element_expected_string = False del_keys = b'' element_valuenames = [] element_values = this_element_value if this_element_value is not None: element_valuenames = list([str(z) for z in range(1, len(this_element_value) + 1)]) if 'additive' in element.attrib: if element.attrib['additive'].lower() == 'false': # a delete values will be added before all the other # value = data pairs del_keys = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**delvals.'.encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) if 'expandable' in element.attrib: this_vtype = 'REG_EXPAND_SZ' if element.attrib.get('explicitValue', 'false').lower() == 'true': if this_element_value is not None: element_valuenames = [str(k) for k in this_element_value.keys()] element_values = [str(v) for v in this_element_value.values()] elif 'valuePrefix' in element.attrib: # if the valuePrefix attribute exists, the valuenames are # most prefixes attributes are empty in the admx files, so the valuenames # end up being just numbers if element.attrib['valuePrefix'] != '': if this_element_value is not None: element_valuenames = ['{0}{1}'.format( element.attrib['valuePrefix'], k) for k in element_valuenames] else: # if there is no valuePrefix attribute, the valuename is the value if element_values is not None: element_valuenames = [str(z) for z in element_values] if not check_deleted: if this_element_value is not None: log.debug('_processValueItem has an explicit ' 'element_value of %s', this_element_value) expected_string = del_keys log.debug('element_valuenames == %s and element_values ' '== %s', element_valuenames, element_values) for i, item in enumerate(element_valuenames): expected_string = expected_string + b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, element_valuenames[i].encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len('{0}{1}'.format(element_values[i], chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, b''.join([element_values[i].encode('utf-16-le'), encoded_null]), ']'.encode('utf-16-le')]) else: expected_string = del_keys + b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**delvals.'.encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) elif etree.QName(element).localname == 'enum': if this_element_value is not None: pass if standard_element_expected_string and not check_deleted: if this_element_value is not None: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(this_element_value)).encode('utf-32-le'), encoded_semicolon, this_element_value, ']'.encode('utf-16-le')]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon]) if not expected_string: if etree.QName(element).localname == ""delete"" or check_deleted: # delete value expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**del.'.encode('utf-16-le'), reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(this_element_value)).encode('utf-32-le'), encoded_semicolon, this_element_value, ']'.encode('utf-16-le')]) return expected_string",,saltstack/salt,6c1fd0bf649a4f9a66eb2dbffc87556f85144222,"def _processValueItem(element, reg_key, reg_valuename, policy, parent_element, check_deleted=False, this_element_value=None): ''' helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - the registry key associated with the element (some inherit from their parent policy) reg_valuename - the registry valueName associated with the element (some inherit from their parent policy) policy - the parent policy element parent_element - the parent element (primarily passed in to differentiate children of ""elements"" objects check_deleted - if the returned expected string should be for a deleted value this_element_value - a specific value to place into the expected string returned for ""elements"" children whose values are specified by the user ''' registry = Registry() expected_string = None # https://msdn.microsoft.com/en-us/library/dn606006(v=vs.85).aspx this_vtype = 'REG_SZ' encoded_semicolon = ';'.encode('utf-16-le') encoded_null = chr(0).encode('utf-16-le') if reg_key: reg_key = reg_key.encode('utf-16-le') if reg_valuename: reg_valuename = reg_valuename.encode('utf-16-le') if etree.QName(element).localname == 'decimal' and etree.QName(parent_element).localname != 'elements': this_vtype = 'REG_DWORD' if 'value' in element.attrib: this_element_value = struct.pack(b'I', int(element.attrib['value'])) else: log.error('The %s child %s element for the policy with ' 'attributes: %s does not have the required ""value"" ' 'attribute. The element attributes are: %s', etree.QName(parent_element).localname, etree.QName(element).localname, policy.attrib, element.attrib) return None elif etree.QName(element).localname == 'longDecimal' and etree.QName(parent_element).localname != 'elements': # WARNING: no longDecimals in current ADMX files included with 2012 # server, so untested/assumed this_vtype = 'REG_QWORD' if 'value' in element.attrib: this_element_value = struct.pack(b'Q', int(element.attrib['value'])) else: log.error('The %s child %s element for the policy with ' 'attributes: %s does not have the required ""value"" ' 'attribute. The element attributes are: %s', etree.QName(parent_element).localname, etree.QName(element).localname, policy.attrib, element.attrib) return None elif etree.QName(element).localname == 'string': this_vtype = 'REG_SZ' this_element_value = b''.join([element.text.encode('utf-16-le'), encoded_null]) elif etree.QName(parent_element).localname == 'elements': standard_element_expected_string = True if etree.QName(element).localname == 'boolean': # a boolean element that has no children will add a REG_DWORD == 1 # on true or delete the value on false # https://msdn.microsoft.com/en-us/library/dn605978(v=vs.85).aspx if this_element_value is False: check_deleted = True if not check_deleted: this_vtype = 'REG_DWORD' this_element_value = chr(1).encode('utf-16-le') standard_element_expected_string = False elif etree.QName(element).localname == 'decimal': # https://msdn.microsoft.com/en-us/library/dn605987(v=vs.85).aspx this_vtype = 'REG_DWORD' requested_val = this_element_value if this_element_value is not None: this_element_value = struct.pack(b'I', int(this_element_value)) if 'storeAsText' in element.attrib: if element.attrib['storeAsText'].lower() == 'true': this_vtype = 'REG_SZ' if requested_val is not None: this_element_value = six.text_type(requested_val).encode('utf-16-le') if check_deleted: this_vtype = 'REG_SZ' elif etree.QName(element).localname == 'longDecimal': # https://msdn.microsoft.com/en-us/library/dn606015(v=vs.85).aspx this_vtype = 'REG_QWORD' requested_val = this_element_value if this_element_value is not None: this_element_value = struct.pack(b'Q', int(this_element_value)) if 'storeAsText' in element.attrib: if element.attrib['storeAsText'].lower() == 'true': this_vtype = 'REG_SZ' if requested_val is not None: this_element_value = six.text_type(requested_val).encode('utf-16-le') elif etree.QName(element).localname == 'text': # https://msdn.microsoft.com/en-us/library/dn605969(v=vs.85).aspx this_vtype = 'REG_SZ' if 'expandable' in element.attrib: if element.attrib['expandable'].lower() == 'true': this_vtype = 'REG_EXPAND_SZ' if this_element_value is not None: this_element_value = b''.join([this_element_value.encode('utf-16-le'), encoded_null]) elif etree.QName(element).localname == 'multiText': this_vtype = 'REG_MULTI_SZ' if not check_deleted else 'REG_SZ' if this_element_value is not None: this_element_value = '{0}{1}{1}'.format(chr(0).join(this_element_value), chr(0)) elif etree.QName(element).localname == 'list': standard_element_expected_string = False del_keys = b'' element_valuenames = [] element_values = this_element_value if this_element_value is not None: element_valuenames = list([str(z) for z in range(1, len(this_element_value) + 1)]) if 'additive' in element.attrib: if element.attrib['additive'].lower() == 'false': # a delete values will be added before all the other # value = data pairs del_keys = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**delvals.'.encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) if 'expandable' in element.attrib: this_vtype = 'REG_EXPAND_SZ' if element.attrib.get('explicitValue', 'false').lower() == 'true': if this_element_value is not None: element_valuenames = [str(k) for k in this_element_value.keys()] element_values = [str(v) for v in this_element_value.values()] elif 'valuePrefix' in element.attrib: # if the valuePrefix attribute exists, the valuenames are # most prefixes attributes are empty in the admx files, so the valuenames # end up being just numbers if element.attrib['valuePrefix'] != '': if this_element_value is not None: element_valuenames = ['{0}{1}'.format( element.attrib['valuePrefix'], k) for k in element_valuenames] else: # if there is no valuePrefix attribute, the valuename is the value if element_values is not None: element_valuenames = [str(z) for z in element_values] if not check_deleted: if this_element_value is not None: log.debug('_processValueItem has an explicit ' 'element_value of %s', this_element_value) expected_string = del_keys log.debug('element_valuenames == %s and element_values ' '== %s', element_valuenames, element_values) for i, item in enumerate(element_valuenames): expected_string = expected_string + b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, element_valuenames[i].encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len('{0}{1}'.format(element_values[i], chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, b''.join([element_values[i].encode('utf-16-le'), encoded_null]), ']'.encode('utf-16-le')]) else: expected_string = del_keys + b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**delvals.'.encode('utf-16-le'), encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) elif etree.QName(element).localname == 'enum': if this_element_value is not None: pass if standard_element_expected_string and not check_deleted: if this_element_value is not None: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(this_element_value)).encode('utf-32-le'), encoded_semicolon, this_element_value, ']'.encode('utf-16-le')]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon]) if not expected_string: if etree.QName(element).localname == ""delete"" or check_deleted: # delete value expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, '**del.'.encode('utf-16-le'), reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'), encoded_semicolon, ' '.encode('utf-16-le'), encoded_null, ']'.encode('utf-16-le')]) else: expected_string = b''.join(['['.encode('utf-16-le'), reg_key, encoded_null, encoded_semicolon, reg_valuename, encoded_null, encoded_semicolon, chr(registry.vtype[this_vtype]).encode('utf-32-le'), encoded_semicolon, six.unichr(len(this_element_value)).encode('utf-32-le'), encoded_semicolon, this_element_value, ']'.encode('utf-16-le')]) return expected_string" functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/projects/docker.py,0,"def validate_docker_installation(): """""" Verify if Docker is installed on host machine. """""" try: docker_path = ""docker"" process._exec_cmd([docker_path, ""--help""], throw_on_error=False) except EnvironmentError: raise ExecutionException( ""Could not find Docker executable. "" ""Ensure Docker is installed as per the instructions "" ""at https://docs.docker.com/install/overview/."" )",,mlflow/mlflow,c98313482168137e39a6e6b0ed7169de5bfe0ba5,"def validate_docker_installation(): """""" Verify if Docker is installed on host machine. """""" try: docker_path = ""docker"" process.exec_cmd([docker_path, ""--help""], throw_on_error=False) except EnvironmentError: raise ExecutionException( ""Could not find Docker executable. "" ""Ensure Docker is installed as per the instructions "" ""at https://docs.docker.com/install/overview/."" )" functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,lib/controller/handler.py,0,"def setHandler(): """""" Detect which is the target web application back-end database management system. """""" count = 0 dbmsNames = ( ""MySQL"", ""Oracle"", ""PostgreSQL"", ""Microsoft SQL Server"", ""SQLite"", ""Microsoft Access"", ""Firebird"", ""SAP MaxDB"", ""Sybase"" ) dbmsObj = [ ( MYSQL_ALIASES, MySQLMap, MySQLConn ), ( ORACLE_ALIASES, OracleMap, OracleConn ), ( PGSQL_ALIASES, PostgreSQLMap, PostgreSQLConn ), ( MSSQL_ALIASES, MSSQLServerMap, MSSQLServerConn ), ( SQLITE_ALIASES, SQLiteMap, SQLiteConn ), ( ACCESS_ALIASES, AccessMap, AccessConn ), ( FIREBIRD_ALIASES, FirebirdMap, FirebirdConn ), ( MAXDB_ALIASES, MaxDBMap, MaxDBConn ), ( SYBASE_ALIASES, SybaseMap, SybaseConn ), ] if kb.htmlFp: inferencedDbms = kb.htmlFp[-1] else: inferencedDbms = None for injection in kb.injections: if hasattr(injection, ""dbms""): inferencedDbms = injection.dbms break if inferencedDbms is not None: for i in xrange(len(dbmsObj)): dbmsAliases, _, _ = dbmsObj[i] if inferencedDbms.lower() in dbmsAliases: if i > 0: pushValue(dbmsObj[i]) dbmsObj.remove(dbmsObj[i]) dbmsObj.insert(0, popValue()) break for dbmsAliases, dbmsMap, dbmsConn in dbmsObj: if conf.dbms and conf.dbms not in dbmsAliases: debugMsg = ""skipping test for %s"" % dbmsNames[count] logger.debug(debugMsg) count += 1 continue kb.misc.handler = handler = dbmsMap() conf.dbmsConnector = dbmsConn() if conf.direct: logger.debug(""forcing timeout to 10 seconds"") conf.timeout = 10 conf.dbmsConnector.connect() if handler.checkDbms(): if not conf.dbms or conf.dbms in dbmsAliases: kb.dbmsDetected = True conf.dbmsHandler = handler return else: conf.dbmsConnector = None",,andresriancho/w3af,c8f943f5e4c2f035753a415f703aad4518e17dc4,"def setHandler(): """""" Detect which is the target web application back-end database management system. """""" count = 0 dbmsNames = ( ""MySQL"", ""Oracle"", ""PostgreSQL"", ""Microsoft SQL Server"", ""SQLite"", ""Microsoft Access"", ""Firebird"", ""SAP MaxDB"", ""Sybase"" ) dbmsMap = [ ( MYSQL_ALIASES, MySQLMap, MySQLConn ), ( ORACLE_ALIASES, OracleMap, OracleConn ), ( PGSQL_ALIASES, PostgreSQLMap, PostgreSQLConn ), ( MSSQL_ALIASES, MSSQLServerMap, MSSQLServerConn ), ( SQLITE_ALIASES, SQLiteMap, SQLiteConn ), ( ACCESS_ALIASES, AccessMap, AccessConn ), ( FIREBIRD_ALIASES, FirebirdMap, FirebirdConn ), ( MAXDB_ALIASES, MaxDBMap, MaxDBConn ), ( SYBASE_ALIASES, SybaseMap, SybaseConn ), ] if kb.htmlFp: inferencedDbms = kb.htmlFp[-1] elif hasattr(kb.injection, ""dbms""): inferencedDbms = kb.injection.dbms else: inferencedDbms = None if inferencedDbms is not None: for i in xrange(len(dbmsMap)): dbmsAliases, _, _ = dbmsMap[i] if inferencedDbms.lower() in dbmsAliases: if i > 0: pushValue(dbmsMap[i]) dbmsMap.remove(dbmsMap[i]) dbmsMap.insert(0, popValue()) break for dbmsAliases, dbmsMap, dbmsConn in dbmsMap: if conf.dbms and conf.dbms not in dbmsAliases: debugMsg = ""skipping test for %s"" % dbmsNames[count] logger.debug(debugMsg) count += 1 continue kb.misc.handler = handler = dbmsMap() conf.dbmsConnector = dbmsConn() if conf.direct: logger.debug(""forcing timeout to 10 seconds"") conf.timeout = 10 conf.dbmsConnector.connect() if handler.checkDbms(): if not conf.dbms or conf.dbms in dbmsAliases: kb.dbmsDetected = True conf.dbmsHandler = handler return else: conf.dbmsConnector = None" ,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/service.py,1,"def run(self, tmp=None, task_vars=None): ''' handler for package operations ''' if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) module = self._task.args.get('use', 'auto').lower() if module == 'auto': try: if self._task.delegate_to: # if we delegate, we should use delegated host's facts module = self._templar.template(""{{hostvars['%s']['ansible_service_mgr']}}"" % self._task.delegate_to) else: module = self._templar.template('{{ansible_service_mgr}}') except: pass # could not get it from template! if module == 'auto': facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars) self._display.debug(""Facts %s"" % facts) if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']: module = facts['ansible_facts']['ansible_service_mgr'] if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader: module = 'service' if module != 'auto': # run the 'service' module new_module_args = self._task.args.copy() if 'use' in new_module_args: del new_module_args['use'] # for backwards compatibility if 'state' in new_module_args and new_module_args['state'] == 'running': new_module_args['state'] = 'started' if module in self.UNUSED_PARAMS: for unused in self.UNUSED_PARAMS[module]: if unused in new_module_args: del new_module_args[unused] self._display.warning('Ignoring ""%s"" as it is not used in ""%s""' % (unused, module)) self._display.vvvv(""Running %s"" % module) result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars)) else: result['failed'] = True result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the ""use"" option.' return result",CWE-703,ansible/ansible,0aaee0272a07fa1cb5081290ec624975ba5b8aa2,"def run(self, tmp=None, task_vars=None): ''' handler for package operations ''' if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) module = self._task.args.get('use', 'auto').lower() if module == 'auto': try: module = self._templar.template('{{ansible_service_mgr}}') except: pass # could not get it from template! if module == 'auto': facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars) self._display.debug(""Facts %s"" % facts) if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']: module = facts['ansible_facts']['ansible_service_mgr'] if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader: module = 'service' if module != 'auto': # run the 'service' module new_module_args = self._task.args.copy() if 'use' in new_module_args: del new_module_args['use'] # for backwards compatibility if 'state' in new_module_args and new_module_args['state'] == 'running': new_module_args['state'] = 'started' if module in self.UNUSED_PARAMS: for unused in self.UNUSED_PARAMS[module]: if unused in new_module_args: del new_module_args[unused] self._display.warning('Ignoring ""%s"" as it is not used in ""%s""' % (unused, module)) self._display.vvvv(""Running %s"" % module) result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars)) else: result['failed'] = True result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the ""use"" option.' return result" ,UNKNOWN,UNKNOWN,tests/types/test_schema.py,1,"def test_tensor_spec(): a1 = TensorSpec(np.dtype(""float64""), (-1, 3, 3), ""a"") a2 = TensorSpec(np.dtype(""float""), (-1, 3, 3), ""a"") # float defaults to float64 a3 = TensorSpec(np.dtype(""float""), [-1, 3, 3], ""a"") a4 = TensorSpec(np.dtype(""int""), (-1, 3, 3), ""a"") assert a1 == a2 assert a1 == a3 assert a1 != a4 b1 = TensorSpec(np.dtype(""float64""), (-1, 3, 3), ""b"") assert b1 != a1 with pytest.raises(TypeError, match=""Expected `dtype` to be instance""): TensorSpec(""Unsupported"", (-1, 3, 3), ""a"") with pytest.raises(TypeError, match=""Expected `shape` to be instance""): TensorSpec(np.dtype(""float64""), np.array([-1, 2, 3]), ""b"") with pytest.raises( MlflowException, match=""MLflow does not support size information in flexible numpy data types"", ): TensorSpec(np.dtype(""