internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: bridgecrewio/checkov

Issue:
KeyError: 'suppress_comment' when running with -o junitxml flag
**Describe the issue**
I get the error KeyError: 'suppress_comment', when:
- Evaluating the Python rule, if I return CheckResult.SKIPPED in the scan_resource_conf method
- The error happens only when executing checkov with the flag -o junitxml

**Version (please complete the following information):**
 - Checkov Version 2.3.152

**Additional context**
Is there a way to either add the suppress_comment in the context or for the junit report not to throw an error?


Discussion:
hey @fabiodouek thanks for reaching out.
yeah, this should be possible 🙂 but just a word of advise, the `CheckResult.SKIPPED` was not meant to be used in Python custom checks, for such a use case we `CheckResult.UNKNOWN`.

Resolving patch:
diff --git a/checkov/common/checks/object_registry.py b/checkov/common/checks/object_registry.py
--- a/checkov/common/checks/object_registry.py
+++ b/checkov/common/checks/object_registry.py
@@ -195,7 +195,7 @@ def update_result(
             results[result_key] = {
                 "check": check,
                 "result": result,
-                "suppress_comment": check_result["suppress_comment"],
+                "suppress_comment": check_result.get("suppress_comment", ""),
                 "results_configuration": None,
             }
             return result
diff --git a/checkov/common/output/report.py b/checkov/common/output/report.py
--- a/checkov/common/output/report.py
+++ b/checkov/common/output/report.py
@@ -401,7 +401,7 @@ def get_test_suite(self, properties: Optional[Dict[str, Any]] = None, use_bc_ids
                 if self.check_type == CheckType.SCA_PACKAGE:
                     test_case.add_skipped_info(f"{check_id} skipped for {test_name_detail}")
                 else:
-                    test_case.add_skipped_info(record.check_result["suppress_comment"])
+                    test_case.add_skipped_info(record.check_result.get("suppress_comment", ""))
 
             test_cases.append(test_case)
 


Test patch:
Repository: bridgecrewio/checkov

Issue:
Wrong filename if using --output-file-path option
When setting the output path using `--output-file-path output_directory` checkov reports

```
Wrote output in SARIF format to the file 'results.sarif'
```

But inside the output_directory the filename is written as **results_sarif.sarif**.

Additionally it would be great to see a message like

```
Wrote output in SARIF format to the file 'output_directory/results.sarif'
```


Discussion:
hey @PascalTurbo thanks for reaching out.

When you use the `--output-file-path` flag, then we save all the specified outputs in the folder with fixed names., prefixed with `results_`. Can you share the whole `checkov` command you used, it would make it easier to find the root cause, because the output should be a bit different. And which `checkov` version are you using?
Hey @gruebel thanks for the fast response.

Here is the complete command:

```
$ checkov --version
2.3.150

$ checkov -d melee-island -o sarif --output-file-path output
[...lot of output]
Wrote output in SARIF format to the file 'results.sarif'

$ ls output
results_sarif.sarif
```

So if it's intentional to add `results_` (what makes absolutely sense after thinking about it 😄) the only "bug" is, that it writes the wrong filename to the last line of the output. (And as a feature request, add the given path).

Resolving patch:
diff --git a/checkov/common/runners/runner_registry.py b/checkov/common/runners/runner_registry.py
--- a/checkov/common/runners/runner_registry.py
+++ b/checkov/common/runners/runner_registry.py
@@ -409,8 +409,9 @@ def print_reports(
                     ))
 
             if output_format == CONSOLE_OUTPUT:
-                # don't write to file, if an explicit file path was set
-                sarif.write_sarif_output()
+                if not config.output_file_path or "," in config.output_file_path:
+                    # don't write to file, if an explicit file path was set
+                    sarif.write_sarif_output()
 
                 del output_formats["sarif"]
 


Test patch:
Repository: bridgecrewio/checkov

Issue:
Tests folder published in version 2.3.201
The wheel of version 2.3.201 contains the tests folder and pollutes the site-packages even though setup.py excludes it explicitly.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -123,8 +123,9 @@ def run(self) -> None:
     url="https://github.com/bridgecrewio/checkov",
     packages=find_packages(exclude=[
         "dogfood_tests*",
+        "flake8_plugins*",
         "integration_tests*",
-        "performance_tests*"
+        "performance_tests*",
         "tests*",
     ]),
     include_package_data=True,


Test patch:
Repository: bridgecrewio/checkov

Issue:
CheckOV can't check bicep files with modules published in Azure container registry
**Describe the issue**
In a larger Bicep environment, we publish entire solutions to the Azure Container Registry. These solutions are called by users as modules in their Bicep deployments. Therefore, it is mandatory for us that CheckOV supports scanning of such environments.

In our view, these two solutions would sufficiently address the problem, with the first solution being our favorite:

1. CheckOV downloads the modules from the Azure container registry to enable scanning of the code.
2. CheckOV checks if the Azure container registry used is whitelisted and then scans only the available code. If the registry used is not whitelisted, CheckOV returns a hardfail.

The second option would be a workaround for us, as we only want users to use our registry. The modules that are published in this registry have been scanned by checkov before publishing.

In the current version of checkov (2.3.152) the scan of the bicep file fails with a parsing error.

**Example Value**
``` bicep
module modSampleSolution 'br:sampleregistry.azurecr.io/bicep/modules/company.department/sampleSolution:1.0.0' = {
  name: 'sampleSolution-deploy'
  params: {
    parSampleParameter: 'Sample'
  }
}
```


Discussion:
hey @AlexLudwigITDienstleistungen thanks for reaching out.

The parsing error shouldn't happen, but I think I know how to fix it. I hope it is ok, if I use your example as my test case :smile:

Support for modules is currently not supported as you found out and I'm also not sure, when we will tackle it, because it is not on the short-term roadmap.
Hi @gruebel,
you are welcome to use this. It's just a simple module that does nothing more than demonstrate the problem.

Is there a time frame for this on your roadmap? Or is the roadmap publicly available somewhere?
we have a small project board where we track work on planned changes without any ETA, but for this specific feature I need to reach out internally, if we plan to tackle it or not.

https://github.com/orgs/bridgecrewio/projects/5/views/4
Hi @gruebel,
have you made any progress with this error? You mentioned that you know how to fix it.
hey @AlexLudwigITDienstleistungen 

yeah, I fixed the parsing issue, but I'm waiting to release a new version of parser, because I want to incorporate some other parsing issues related to new Bicep syntax extensions. 

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -101,7 +101,7 @@ def run(self) -> None:
         "aiomultiprocess",
         "jsonschema<5.0.0,>=4.6.0",
         "prettytable>=3.0.0",
-        "pycep-parser==0.3.9",
+        "pycep-parser==0.4.0",
         "charset-normalizer",
         "pyston-autoload==2.3.5; python_version < '3.11' and (sys_platform == 'linux' or sys_platform == 'darwin') and platform_machine == 'x86_64' and implementation_name == 'cpython'",
         "pyston==2.3.5; python_version < '3.11' and (sys_platform == 'linux' or sys_platform == 'darwin') and platform_machine == 'x86_64' and implementation_name == 'cpython'",


Test patch:
Repository: bridgecrewio/checkov

Issue:
Update CKV_AZURE_43 `each.`
**Describe the issue**
CKV_AZURE_43 StorageAccountName.py VARIABLE_REFS list does not include the `each.` used with for_each meta argument to return UNKNOWN and currently returns FAILED check which is incorrect.

**Examples**

```
module "bootstrap" {
  source = "../../modules/bootstrap"

  for_each = var.bootstrap_storage

  create_storage_account = try(each.value.create_storage, true)
  name                   = each.value.name
  resource_group_name    = try(each.value.resource_group_name, local.resource_group.name)
  location               = var.location
  storage_acl            = try(each.value.storage_acl, false)

  tags = var.tags
}
```

Within the bootstrap module - we use the `azurerm_storage_account` :

```
resource "azurerm_storage_account" "this" {
  count = var.create_storage_account ? 1 : 0

  name                     = var.name
  location                 = var.location
  resource_group_name      = var.resource_group_name
  min_tls_version          = var.min_tls_version
  account_replication_type = "LRS"
  account_tier             = "Standard"
  tags                     = var.tags
  queue_properties {
    logging {
      delete                = true
      read                  = true
      write                 = true
      version               = "1.0"
      retention_policy_days = var.retention_policy_days
    }
  }
  network_rules {
    default_action             = var.storage_acl == true ? "Deny" : "Allow"
    ip_rules                   = var.storage_acl == true ? var.storage_allow_inbound_public_ips : null
    virtual_network_subnet_ids = var.storage_acl == true ? var.storage_allow_vnet_subnets : null
  }
}
```

And Checkov returns this :

```
Check: CKV_AZURE_43: "Ensure Storage Accounts adhere to the naming rules"
        FAILED for resource: module.bootstrap.azurerm_storage_account.this
        File: /modules/bootstrap/main.tf:1-25
        Calling File: /examples/standalone_vm/main.tf:192-204
        Guide: https://docs.bridgecrew.io/docs/ensure-storage-accounts-adhere-to-the-naming-rules
```

**Version (please complete the following information):**
 - Checkov Version 2.2.125

**Additional context**



Discussion:

Resolving patch:
diff --git a/checkov/terraform/checks/resource/azure/StorageAccountName.py b/checkov/terraform/checks/resource/azure/StorageAccountName.py
--- a/checkov/terraform/checks/resource/azure/StorageAccountName.py
+++ b/checkov/terraform/checks/resource/azure/StorageAccountName.py
@@ -6,7 +6,7 @@
 
 STO_NAME_REGEX = re.compile(r"^[a-z0-9]{3,24}$")
 VARIABLE_REFS = ("local.", "module.", "var.", "random_string.", "random_id.", "random_integer.", "random_pet.",
-                 "azurecaf_name")
+                 "azurecaf_name", "each.")
 
 
 class StorageAccountName(BaseResourceCheck):


Test patch:
Repository: bridgecrewio/checkov

Issue:
update-locale triggers CKV_DOCKER_5
**Describe the issue**
CKV_DOCKER_5 (Ensure update instructions are not use alone in the Dockerfile) fails in anything that has `update` in it. From reading the source, it. seems that CKV_DOCKER_5 is geared towards `apt-get update` and `apt-get install` which, from the code, are cancelling each other out so the `update_cnt` variable remains 0. I have other `update` command like `update-locale`. I'm not sure if it's part of the issue in my Dockerfile that I need to deal or I could just ignore the failure message.

**Examples**
```
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \
  dpkg-reconfigure --frontend noninteractive locales && \
  update-locale LANG=en_US.UTF-8
```

**Version (please complete the following information):**
 - Checkov Version 2.2.229



Discussion:
Problem persists in Alpine based images as well, e.g. if you do following, checkcov will fail:
```
RUN apk update --no-cache && apk upgrade --no-cache
```

Resolving patch:
diff --git a/checkov/dockerfile/checks/UpdateNotAlone.py b/checkov/dockerfile/checks/UpdateNotAlone.py
--- a/checkov/dockerfile/checks/UpdateNotAlone.py
+++ b/checkov/dockerfile/checks/UpdateNotAlone.py
@@ -1,5 +1,6 @@
 from __future__ import annotations
 
+import re
 from typing import TYPE_CHECKING
 
 from checkov.common.models.enums import CheckCategories, CheckResult
@@ -8,6 +9,8 @@
 if TYPE_CHECKING:
     from dockerfile_parse.parser import _Instruction
 
+UPDATE_COMMANDS_PATTERN = re.compile(r"\s+(?:--)?update(?!\S)")
+
 install_commands = (
     "install",
     "source-install",
@@ -15,10 +18,7 @@
     "groupinstall",
     "localinstall",
     "add",
-)
-update_commands = (
-    "update",
-    "--update",
+    "upgrade"
 )
 
 
@@ -38,7 +38,7 @@ def scan_resource_conf(self, conf: list[_Instruction]) -> tuple[CheckResult, lis
             content = instruction["content"]
             if instruction["instruction"] in self.supported_instructions:
 
-                if any(x in content for x in update_commands):
+                if re.search(UPDATE_COMMANDS_PATTERN, content):
                     update_cnt = update_cnt + 1
                     update_instructions.append(i)
                 if any(x in content for x in install_commands):


Test patch:
diff --git a/tests/dockerfile/checks/example_UpdateNotAlone/success/Dockerfile b/tests/dockerfile/checks/example_UpdateNotAlone/success/Dockerfile
--- a/tests/dockerfile/checks/example_UpdateNotAlone/success/Dockerfile
+++ b/tests/dockerfile/checks/example_UpdateNotAlone/success/Dockerfile
@@ -8,3 +8,9 @@ RUN apk update \
  && apk add --no-cache suuu looo
 
 RUN apk --update add moo
+
+RUN apk update --no-cache && apk upgrade --no-cache
+
+RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && \
+  dpkg-reconfigure --frontend noninteractive locales && \
+  update-locale LANG=en_US.UTF-8
Repository: bridgecrewio/checkov

Issue:
Run pre-commit on changed files only
**Describe the issue**

The checkov pre-commit hook currently runs against all files on a repository. For bigger monorepos, it can take a while to run (several minutes), and slows down CI builds.

Pre-commit supports sending a list of files (pass_filenames: true), perhaps the pre-commit can be updated to supported this?

There is some discussion on this issue https://github.com/bridgecrewio/checkov/issues/661, but I thought it's worth creating a ticket just to track this.



Discussion:
If you run checkov on the monorepo where is the entry point for variables to be? The checks need to know the values and may evaluate differently for different target environments. For pass_filenames to work you'd have to an individual run on each file - checkov -f ? Plus if a file contains variables, resource dependency or locals it might change the values of other resources and almost certainly will. Cherry picking in a graph isn't straight forward.

Resolving patch:
diff --git a/checkov/common/util/ext_argument_parser.py b/checkov/common/util/ext_argument_parser.py
--- a/checkov/common/util/ext_argument_parser.py
+++ b/checkov/common/util/ext_argument_parser.py
@@ -140,6 +140,7 @@ def add_parser_args(self) -> None:
                  'to filter the runners based on the file type. For example, if you specify a ".tf" file, only the '
                  "terraform and secrets frameworks will be included. You can further limit this (e.g., skip secrets) "
                  "by using the --skip-framework argument.",
+            nargs="+",
         )
         self.add(
             "--skip-path",
diff --git a/checkov/main.py b/checkov/main.py
--- a/checkov/main.py
+++ b/checkov/main.py
@@ -2,6 +2,7 @@
 from __future__ import annotations
 
 import atexit
+import itertools
 import json
 import logging
 import os
@@ -199,6 +200,10 @@ def normalize_config(self) -> None:
         # Parse mask into json with default dict. If self.config.mask is empty list, default dict will be assigned
         self._parse_mask_to_resource_attributes_to_omit()
 
+        if self.config.file:
+            # it is passed as a list of lists
+            self.config.file = list(itertools.chain.from_iterable(self.config.file))
+
     def run(self, banner: str = checkov_banner, tool: str = checkov_tool, source_type: SourceType | None = None) -> int | None:
         self.run_metadata = {
             "checkov_version": version,


Test patch:
Repository: bridgecrewio/checkov

Issue:
Allow var-file to be passed as environment variable
**Describe the issue**
Currently you can only pass a Terraform var-file via a command line argument (--var-file). It would be useful to be able to source this from an environment variable.

**Version (please complete the following information):**
 - Checkov Version [2.3.285]



Discussion:
hey @roddick-mark thanks for reaching out.

If you are interested you can easily contribute the needed change. Just add here

https://github.com/bridgecrewio/checkov/blob/e2aa231efeed33e1a9dff389f70a5dd652f0f5fc/checkov/common/util/ext_argument_parser.py#L386-L393

following extra line
```python
env_var="CKV_VAR_FILE",
```

not need to write a test for it, because it is a functionality of the library we use and it works for other cases very well so far.

Resolving patch:
diff --git a/checkov/common/util/ext_argument_parser.py b/checkov/common/util/ext_argument_parser.py
--- a/checkov/common/util/ext_argument_parser.py
+++ b/checkov/common/util/ext_argument_parser.py
@@ -391,6 +391,7 @@ def add_parser_args(self) -> None:
                  "https://www.terraform.io/docs/language/values/variables.html#variable-definitions-tfvars-files)."
                  "Currently only supported for source Terraform (.tf file), and Helm chart scans."
                  "Requires using --directory, not --file.",
+            env_var="CKV_VAR_FILE",
         )
         self.add(
             "--external-modules-download-path",


Test patch:
Repository: bridgecrewio/checkov

Issue:
[CKV_AWS_358] - false alarm triggered even when GH Organisation is specified
**Describe the issue**

I guess there is false alarm triggered by this check.
The GitHub Organisation is already included in the values of condition for the `token.actions.githubusercontent.com:sub` variable.

**Examples**
```terraform
data "aws_iam_policy_document" "assumerole" {
  statement {
    sid    = "DefaultAssumeRole"
    effect = "Allow"

    actions = [
      "sts:AssumeRoleWithWebIdentity",
    ]

    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"

      values = [
        "sts.amazonaws.com"
      ]
    }

    condition {
      test     = "StringLike"
      variable = "token.actions.githubusercontent.com:sub"

      values = [
        "repo:GitHub-Organization/${var.github_repo}:*"
      ]
    }

    principals {
      type = "Federated"
      identifiers = [
        "arn:aws:iam::${var.aws_account_id}:oidc-provider/token.actions.githubusercontent.com"
      ]
    }
  }
}
```

Checkov output:
```sh
Check: CKV_AWS_358: "Ensure GitHub Actions OIDC trust policies only allows actions from a specific known organization"
	FAILED for resource: module.ecr_repo.aws_iam_policy_document.assumerole
	File: /../../modules/ecr-repository/data_aws_iam_policy_document_assumerole.tf:1-35
	Calling File: /module_ecr_repository.tf:2-24
```

**Version:**
 - Checkov Version [2.3.359]

**Additional context**
See https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services




Discussion:
hey @cbugneac-nex thanks for reaching out.

I found the issue. It is strange that exactly the same resource passes, when it next to other resources, but as a standalone not 😅 

Resolving patch:
diff --git a/checkov/terraform/checks/data/aws/GithubActionsOIDCTrustPolicy.py b/checkov/terraform/checks/data/aws/GithubActionsOIDCTrustPolicy.py
--- a/checkov/terraform/checks/data/aws/GithubActionsOIDCTrustPolicy.py
+++ b/checkov/terraform/checks/data/aws/GithubActionsOIDCTrustPolicy.py
@@ -56,8 +56,9 @@ def scan_data_conf(self, conf: Dict[str, List[Any]], entity_type: str) -> CheckR
                                 break
                         if found_sub_condition_value and found_sub_condition_variable:
                             return CheckResult.PASSED
-                        else:
-                            return CheckResult.FAILED
+
+                # Found a federated GitHub user, but no restirctions
+                return CheckResult.FAILED
 
         return CheckResult.PASSED
 


Test patch:
Repository: bridgecrewio/checkov

Issue:
[CKV_DOCKER_7] Erroneous failed check when --platform flag is used in multistage Dockerfile
**Describe the issue**
In the `CKV_DOCKER_7` check, when the `--platform` flag is used in a multistage Dockerfile, the check fails erroneously for images that have been created within the current Dockerfile and thus no version pegging should be required.

**Examples**
The Dockerfile below is green

```
FROM golang:1.20-bullseye AS base

FROM base AS build
```

but as soon as a `--platform` flag is added, the check fails:

```
FROM --platform=$BUILDPLATFORM golang:1.20-bullseye AS base

FROM base AS build
```

**Version (please complete the following information):**
 - Checkov Version 2.4.4


Discussion:

Resolving patch:
diff --git a/checkov/dockerfile/checks/ReferenceLatestTag.py b/checkov/dockerfile/checks/ReferenceLatestTag.py
--- a/checkov/dockerfile/checks/ReferenceLatestTag.py
+++ b/checkov/dockerfile/checks/ReferenceLatestTag.py
@@ -9,7 +9,7 @@
 if TYPE_CHECKING:
     from dockerfile_parse.parser import _Instruction
 
-MULTI_STAGE_PATTERN = re.compile(r"(\S+)\s+as\s+(\S+)", re.IGNORECASE)
+MULTI_STAGE_PATTERN = re.compile(r"(?:--platform=\S+\s+)?(\S+)\s+as\s+(\S+)", re.IGNORECASE)
 
 
 class ReferenceLatestTag(BaseDockerfileCheck):


Test patch:
diff --git a/tests/dockerfile/checks/example_ReferenceLatestTag/success_multi_stage_platform/Dockerfile b/tests/dockerfile/checks/example_ReferenceLatestTag/success_multi_stage_platform/Dockerfile
new file mode 100644
--- /dev/null
+++ b/tests/dockerfile/checks/example_ReferenceLatestTag/success_multi_stage_platform/Dockerfile
@@ -0,0 +1,5 @@
+FROM --platform=$BUILDPLATFORM python:3.11-slim AS build
+COPY test.sh /test.sh
+
+FROM build as run
+LABEL maintainer=checkov
diff --git a/tests/dockerfile/checks/test_ReferenceLatestTag.py b/tests/dockerfile/checks/test_ReferenceLatestTag.py
--- a/tests/dockerfile/checks/test_ReferenceLatestTag.py
+++ b/tests/dockerfile/checks/test_ReferenceLatestTag.py
@@ -20,7 +20,8 @@ def test(self):
             "/success_multi_stage/Dockerfile.FROM",
             "/success_multi_stage_capital/Dockerfile.FROM",
             "/success_scratch/Dockerfile.FROM",
-            "/success_multi_stage_scratch/Dockerfile.FROM"
+            "/success_multi_stage_scratch/Dockerfile.FROM",
+            "/success_multi_stage_platform/Dockerfile.FROM",
         }
         
         failing_resources = {
@@ -31,8 +32,8 @@ def test(self):
         passed_check_resources = set([c.resource for c in report.passed_checks])
         failed_check_resources = set([c.resource for c in report.failed_checks])
 
-        self.assertEqual(summary["passed"], 5)
-        self.assertEqual(summary["failed"], 2)
+        self.assertEqual(summary["passed"], len(passing_resources))
+        self.assertEqual(summary["failed"], len(failing_resources))
         self.assertEqual(summary["skipped"], 0)
         self.assertEqual(summary["parsing_errors"], 0)