Repository: bridgecrewio/checkov

Issue:
Checkov crash when processing AWS::Serverless:Function with Condition used in Globals
**Describe the issue**
Checkov crash when processing AWS::Serverless:Function with Condition used in Globals.
However, when Environment section is moved to Lambda it works as expected.

**Examples**
```yaml
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Parameters:
  EnvironmentType:
    Type: String
    AllowedValues:
      - dev
      - stage

Conditions:
  IsStageEnvironment: !Equals [ !Ref EnvironmentType, stage ]

Resources:   
  ExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole

  ActionLogBucket:
    Type: AWS::S3::Bucket

  ApplicationProcessingLambda:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.8
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
          print('hello from lambda')

Globals:
  Function:
    Environment:
      Variables:
        LogBucketName: !If [ IsStageEnvironment, !Ref ActionLogBucket, unkown ]
```

**Exception Trace**
```sh
λ LOGLEVEL=DEBUG checkov -f application.yaml
Traceback (most recent call last):
  File "C:/Users/TomaszWierzchowski/AppData/Local/Programs/Python/Python37-32/Scripts/checkov", line 9, in <module>
    sys.exit(run())
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\main.py", line 243, in run
    repo_root_for_plan_enrichment=config.repo_root_for_plan_enrichment)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\common\runners\runner_registry.py", line 67, in run
    for scan_report in reports:
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\concurrent\futures\_base.py", line 586, in result_iterator

    yield fs.pop().result()
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\concurrent\futures\_base.py", line 425, in result
    return self.__get_result()
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\common\runners\runner_registry.py", line 64, in <lambda>
    runner_filter=self.runner_filter, collect_skip_comments=collect_skip_comments),
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\runner.py", line 69, in run
    local_graph = self.graph_manager.build_graph_from_definitions(self.definitions)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_manager.py", line 49, in build_graph_from_definitions
    local_graph.build_graph(render_variables=render_variables)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_builder\local_graph.py", line 47, in build_graph
    renderer.render_variables_from_local_graph()
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\common\graph\graph_builder\variable_rendering\renderer.py", line 26, in render_variables_from_local_graph
    self._render_variables_from_edges()
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\common\graph\graph_builder\variable_rendering\renderer.py", line 64, in _render_variables_from_edges
    self._edge_evaluation_task([edge_group])
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\common\graph\graph_builder\variable_rendering\renderer.py", line 96, in _edge_evaluation_task
    self.evaluate_vertex_attribute_from_edge(inner_edges)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_builder\variable_rendering\renderer.py", line 55, in evaluate_vertex_attribute_from_edge
    self._handle_edge_list_evaluation_functions(edge_list, origin_vertex, val_to_eval)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_builder\variable_rendering\renderer.py", line 416, in _handle_edge_list_evaluation_functions
    edge, origin_vertex, cfn_evaluation_function, val_to_eval, dest_vertex_attributes)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_builder\variable_rendering\renderer.py", line 449, in _evaluate_cfn_function
    val_to_eval[ConditionFunctions.IF], dest_vertex_attributes)
  File "C:\users\tomaszwierzchowski\appdata\local\programs\python\python37-32\lib\site-packages\checkov\cloudformation\graph_builder\variable_rendering\renderer.py", line 330, in _evaluate_if_connection
    condition_name = value[0]
KeyError: 0
```

**Desktop (please complete the following information):**
 - OS: Checked on both Windows and Linux
 - Checkov Version 2.0.727


Discussion:

Patch:
diff --git a/checkov/cloudformation/graph_builder/graph_components/blocks.py b/checkov/cloudformation/graph_builder/graph_components/blocks.py
index fd9e3b355..aa8725d69 100644
--- a/checkov/cloudformation/graph_builder/graph_components/blocks.py
+++ b/checkov/cloudformation/graph_builder/graph_components/blocks.py
@@ -28,11 +28,21 @@ class CloudformationBlock(Block):
         self.condition = condition
 
     def update_attribute(
-            self, attribute_key: str, attribute_value: Any, change_origin_id: int,
-            previous_breadcrumbs: List[BreadcrumbMetadata], attribute_at_dest: str
+        self, attribute_key: str,
+        attribute_value: Any,
+        change_origin_id: int,
+        previous_breadcrumbs: List[BreadcrumbMetadata],
+        attribute_at_dest: str,
+        transform_step: bool = False,
     ) -> None:
-        super().update_attribute(attribute_key, attribute_value, change_origin_id, previous_breadcrumbs,
-                                 attribute_at_dest)
+        super().update_attribute(
+            attribute_key=attribute_key,
+            attribute_value=attribute_value,
+            change_origin_id=change_origin_id,
+            previous_breadcrumbs=previous_breadcrumbs,
+            attribute_at_dest=attribute_at_dest,
+            transform_step=transform_step,
+        )
 
         attribute_key_parts = attribute_key.split(".")
         if attribute_key_parts:
diff --git a/checkov/cloudformation/graph_builder/local_graph.py b/checkov/cloudformation/graph_builder/local_graph.py
index 998363d29..0840e8bec 100644
--- a/checkov/cloudformation/graph_builder/local_graph.py
+++ b/checkov/cloudformation/graph_builder/local_graph.py
@@ -122,6 +122,7 @@ class CloudformationLocalGraph(LocalGraph):
                             attribute_value=value,
                             change_origin_id=index,
                             attribute_at_dest=property,
+                            transform_step=True,
                         )
                     elif isinstance(value, list):
                         self.update_vertex_attribute(
@@ -130,6 +131,7 @@ class CloudformationLocalGraph(LocalGraph):
                             attribute_value=[*vertex.attributes[property], *value],
                             change_origin_id=index,
                             attribute_at_dest=property,
+                            transform_step=True,
                         )
 
     def update_vertices_breadcrumbs(self) -> None:
diff --git a/checkov/common/graph/graph_builder/graph_components/blocks.py b/checkov/common/graph/graph_builder/graph_components/blocks.py
index 777887019..26d87363b 100644
--- a/checkov/common/graph/graph_builder/graph_components/blocks.py
+++ b/checkov/common/graph/graph_builder/graph_components/blocks.py
@@ -99,8 +99,13 @@ class Block:
         return attributes_dict.get(CustomAttributes.HASH, "")
 
     def update_attribute(
-            self, attribute_key: str, attribute_value: Any, change_origin_id: Optional[int],
-            previous_breadcrumbs: List[BreadcrumbMetadata], attribute_at_dest: Optional[str]
+        self,
+        attribute_key: str,
+        attribute_value: Any,
+        change_origin_id: Optional[int],
+        previous_breadcrumbs: List[BreadcrumbMetadata],
+        attribute_at_dest: Optional[str],
+        transform_step: bool = False,
     ) -> None:
         if self._should_add_previous_breadcrumbs(change_origin_id, previous_breadcrumbs, attribute_at_dest):
             previous_breadcrumbs.append(BreadcrumbMetadata(change_origin_id, attribute_at_dest))
@@ -120,7 +125,11 @@ class Block:
             key = join_trimmed_strings(char_to_join=".", str_lst=attribute_key_parts, num_to_trim=i)
             if key.find(".") > -1:
                 self.attributes[key] = attribute_value
-                attribute_value = {attribute_key_parts[len(attribute_key_parts) - 1 - i]: attribute_value}
+                end_key_part = attribute_key_parts[len(attribute_key_parts) - 1 - i]
+                if transform_step and end_key_part in ("1", "2"):
+                    # if condition logic during the transform step breaks the values
+                    return
+                attribute_value = {end_key_part: attribute_value}
                 if self._should_set_changed_attributes(change_origin_id, attribute_at_dest):
                     self.changed_attributes[key] = previous_breadcrumbs
 
diff --git a/checkov/common/graph/graph_builder/local_graph.py b/checkov/common/graph/graph_builder/local_graph.py
index 978122df4..88b40897e 100644
--- a/checkov/common/graph/graph_builder/local_graph.py
+++ b/checkov/common/graph/graph_builder/local_graph.py
@@ -71,16 +71,17 @@ class LocalGraph:
         return self.vertices[index].get_attribute_dict(add_hash)
 
     def update_vertex_attribute(
-            self,
-            vertex_index: int,
-            attribute_key: str,
-            attribute_value: Any,
-            change_origin_id: int,
-            attribute_at_dest: Optional[Union[str, List[str]]],
+        self,
+        vertex_index: int,
+        attribute_key: str,
+        attribute_value: Any,
+        change_origin_id: int,
+        attribute_at_dest: Optional[Union[str, List[str]]],
+        transform_step: bool = False
     ) -> None:
         previous_breadcrumbs = []
         if attribute_at_dest:
             previous_breadcrumbs = self.vertices[change_origin_id].changed_attributes.get(attribute_at_dest, [])
         self.vertices[vertex_index].update_attribute(
-            attribute_key, attribute_value, change_origin_id, previous_breadcrumbs, attribute_at_dest
+            attribute_key, attribute_value, change_origin_id, previous_breadcrumbs, attribute_at_dest, transform_step
         )


Test patch:
diff --git a/tests/cloudformation/graph/graph_builder/resources/sam/template.yaml b/tests/cloudformation/graph/graph_builder/resources/sam/template.yaml
index 432037a18..0384ec701 100644
--- a/tests/cloudformation/graph/graph_builder/resources/sam/template.yaml
+++ b/tests/cloudformation/graph/graph_builder/resources/sam/template.yaml
@@ -1,6 +1,13 @@
 AWSTemplateFormatVersion: '2010-09-09'
 Transform: AWS::Serverless-2016-10-31
 
+Parameters:
+  EnvironmentType:
+    Type: String
+    AllowedValues:
+      - dev
+      - stage
+
 Globals:
   Function:
     Timeout: 5
@@ -9,6 +16,7 @@ Globals:
     Tracing: Active
     Environment:
       Variables:
+        QUEUE_URL: !If [ IsStageEnvironment, !Ref SomeQueue, unkown ]
         STAGE: Production
         TABLE_NAME: global-table
     VpcConfig:
@@ -19,6 +27,9 @@ Globals:
         - subnet-123
         - subnet-456
 
+Conditions:
+  IsStageEnvironment: !Equals [ !Ref EnvironmentType, stage ]
+
 Resources:
   SomeQueue:
     Type: AWS::SQS::Queue
diff --git a/tests/cloudformation/graph/graph_builder/test_local_graph.py b/tests/cloudformation/graph/graph_builder/test_local_graph.py
index 0207b6c54..aa5d0f7bc 100644
--- a/tests/cloudformation/graph/graph_builder/test_local_graph.py
+++ b/tests/cloudformation/graph/graph_builder/test_local_graph.py
@@ -164,7 +164,7 @@ class TestLocalGraph(TestCase):
         local_graph = CloudformationLocalGraph(definitions)
         local_graph.build_graph(render_variables=False)
 
-        self.assertEqual(len(local_graph.vertices), 5)
+        self.assertEqual(len(local_graph.vertices), 7)
         self.assertEqual(len([v for v in local_graph.vertices if v.block_type == BlockType.GLOBALS]), 1)
         self.assertEqual(len([v for v in local_graph.vertices if v.block_type == BlockType.RESOURCE]), 3)
         self.assertEqual(len([v for v in local_graph.vertices if v.block_type == BlockType.OUTPUTS]), 1)
@@ -180,6 +180,9 @@ class TestLocalGraph(TestCase):
             "Tracing",
             "Environment.Variables",
             "Environment.Variables.STAGE",
+            "Environment.Variables.QUEUE_URL",
+            "Environment.Variables.QUEUE_URL.Fn::If",
+            "Environment.Variables.QUEUE_URL.Fn::If.1.Ref",
             "VpcConfig.SecurityGroupIds",
             "VpcConfig.SubnetIds",
         ]
@@ -193,6 +196,9 @@ class TestLocalGraph(TestCase):
             "Environment.Variables",
             "Environment.Variables.STAGE",
             "Environment.Variables.TABLE_NAME",
+            "Environment.Variables.QUEUE_URL",
+            "Environment.Variables.QUEUE_URL.Fn::If",
+            "Environment.Variables.QUEUE_URL.Fn::If.1.Ref",
             "VpcConfig",
             "VpcConfig.SecurityGroupIds",
             "VpcConfig.SubnetIds",